List of usage examples for org.apache.commons.io FileUtils moveFile
public static void moveFile(File srcFile, File destFile) throws IOException
From source file:hd3gtv.mydmam.useraction.fileoperation.UAFileOperationTrash.java
public void process(JobProgression progression, UserProfile userprofile, UAConfigurator user_configuration, HashMap<String, SourcePathIndexerElement> source_elements) throws Exception { String user_base_directory_name = userprofile.getBaseFileName_BasedOnEMail(); if (trash_directory_name == null) { trash_directory_name = "Trash"; }/* w ww .jav a 2 s .c o m*/ Log2Dump dump = new Log2Dump(); dump.add("user", userprofile.key); dump.add("trash_directory_name", trash_directory_name); dump.add("user_base_directory_name", user_base_directory_name); dump.add("source_elements", source_elements.values()); Log2.log.debug("Prepare trash", dump); progression.update("Prepare trashs directories"); File current_user_trash_dir; HashMap<String, File> trashs_dirs = new HashMap<String, File>(); for (Map.Entry<String, SourcePathIndexerElement> entry : source_elements.entrySet()) { String storagename = entry.getValue().storagename; if (trashs_dirs.containsKey(storagename)) { continue; } File storage_dir = Explorer .getLocalBridgedElement(SourcePathIndexerElement.prepareStorageElement(storagename)); current_user_trash_dir = new File(storage_dir.getPath() + File.separator + trash_directory_name + File.separator + user_base_directory_name); if (current_user_trash_dir.exists() == false) { FileUtils.forceMkdir(current_user_trash_dir); } else { CopyMove.checkExistsCanRead(current_user_trash_dir); CopyMove.checkIsWritable(current_user_trash_dir); CopyMove.checkIsDirectory(current_user_trash_dir); } trashs_dirs.put(storagename, current_user_trash_dir); if (stop) { return; } } progression.update("Move item(s) to trash(s) directorie(s)"); progression.updateStep(1, source_elements.size()); Date now = new Date(); for (Map.Entry<String, SourcePathIndexerElement> entry : source_elements.entrySet()) { progression.incrStep(); File current_element = Explorer.getLocalBridgedElement(entry.getValue()); CopyMove.checkExistsCanRead(current_element); CopyMove.checkIsWritable(current_element); current_user_trash_dir = trashs_dirs.get(entry.getValue().storagename); File f_destination = new File(current_user_trash_dir.getPath() + File.separator + simpledateformat.format(now) + "_" + current_element.getName()); if (current_element.isDirectory()) { FileUtils.moveDirectory(current_element, f_destination); } else { FileUtils.moveFile(current_element, f_destination); } if (stop) { return; } ContainerOperations.copyMoveMetadatas(entry.getValue(), entry.getValue().storagename, "/" + trash_directory_name + "/" + user_base_directory_name, false, this); ElasticsearchBulkOperation bulk = Elasticsearch.prepareBulk(); explorer.deleteStoragePath(bulk, Arrays.asList(entry.getValue())); bulk.terminateBulk(); if (stop) { return; } } ElasticsearchBulkOperation bulk = Elasticsearch.prepareBulk(); ArrayList<SourcePathIndexerElement> spie_trashs_dirs = new ArrayList<SourcePathIndexerElement>(); for (String storage_name : trashs_dirs.keySet()) { SourcePathIndexerElement root_trash_directory = SourcePathIndexerElement .prepareStorageElement(storage_name); root_trash_directory.parentpath = root_trash_directory.prepare_key(); root_trash_directory.directory = true; root_trash_directory.currentpath = "/" + trash_directory_name; spie_trashs_dirs.add(root_trash_directory); } explorer.refreshStoragePath(bulk, spie_trashs_dirs, false); bulk.terminateBulk(); }
From source file:com.googlecode.psiprobe.controllers.deploy.UploadWarController.java
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { File tmpWar = null;/*from w w w . j ava 2 s .co m*/ String contextName = null; boolean update = false; boolean compile = false; boolean discard = false; // // parse multipart request and extract the file // FileItemFactory factory = new DiskFileItemFactory(1048000, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); upload.setHeaderEncoding("UTF8"); try { for (Iterator it = upload.parseRequest(request).iterator(); it.hasNext();) { FileItem fi = (FileItem) it.next(); if (!fi.isFormField()) { if (fi.getName() != null && fi.getName().length() > 0) { tmpWar = new File(System.getProperty("java.io.tmpdir"), FilenameUtils.getName(fi.getName())); fi.write(tmpWar); } } else if ("context".equals(fi.getFieldName())) { contextName = fi.getString(); } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { update = true; } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { compile = true; } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { discard = true; } } } catch (Exception e) { logger.fatal("Could not process file upload", e); request.setAttribute("errorMessage", getMessageSourceAccessor() .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() })); if (tmpWar != null && tmpWar.exists()) { tmpWar.delete(); } tmpWar = null; } String errMsg = null; if (tmpWar != null) { try { if (tmpWar.getName().endsWith(".war")) { if (contextName == null || contextName.length() == 0) { String warFileName = tmpWar.getName().replaceAll("\\.war$", ""); contextName = "/" + warFileName; } contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName); // // pass the name of the newly deployed context to the presentation layer // using this name the presentation layer can render a url to view compilation details // String visibleContextName = "".equals(contextName) ? "/" : contextName; request.setAttribute("contextName", visibleContextName); if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) { logger.debug("updating " + contextName + ": removing the old copy"); getContainerWrapper().getTomcatContainer().remove(contextName); } if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) { // // move the .war to tomcat application base dir // String destWarFilename = getContainerWrapper().getTomcatContainer() .formatContextFilename(contextName); File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(), destWarFilename + ".war"); FileUtils.moveFile(tmpWar, destWar); // // let Tomcat know that the file is there // getContainerWrapper().getTomcatContainer().installWar(contextName, new URL("jar:" + destWar.toURI().toURL().toString() + "!/")); Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName); if (ctx == null) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled", new Object[] { visibleContextName }); } else { request.setAttribute("success", Boolean.TRUE); if (discard) { getContainerWrapper().getTomcatContainer().discardWorkDir(ctx); } if (compile) { Summary summary = new Summary(); summary.setName(ctx.getName()); getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true); request.getSession(true).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary); request.setAttribute("compileSuccess", Boolean.TRUE); } } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists", new Object[] { visibleContextName }); } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure"); } } catch (Exception e) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure", new Object[] { e.getMessage() }); logger.error("Tomcat throw an exception when trying to deploy", e); } finally { if (errMsg != null) { request.setAttribute("errorMessage", errMsg); } tmpWar.delete(); } } } return new ModelAndView(new InternalResourceView(getViewName())); }
From source file:gov.nih.nci.caintegrator.file.FileManagerImpl.java
/** * {@inheritDoc}/*from w w w . j a v a 2 s . c o m*/ */ public File createMarkersFile(StudySubscription studySubscription, Marker[] markers) throws IOException { File tmpFile = GisticUtils.writeMarkersFile(markers); File resultFile = createNewStudySubscriptionFile(studySubscription, tmpFile.getName()); FileUtils.moveFile(tmpFile, resultFile); return resultFile; }
From source file:de.fhg.iais.asc.xslt.binaries.DownloadAndScaleBinary.java
private boolean moveToPermanentOriginal() { File binaryRoot = this.context.getBinaryRoot(); File f = new File(binaryRoot, this.typeSubPath); if (f.isFile()) { try {/*from w ww . ja v a 2 s .c o m*/ FileUtils.moveFile(f, this.permanentOriginal); return true; } catch (IOException e) { String srcPath = f.getAbsolutePath(); String destPath = this.permanentOriginal.getAbsolutePath(); String msg = String.format("Can't move file \"%s\" to \"%s\"", srcPath, destPath); throw new AscTechnicalErrorException(msg); } } return false; }
From source file:com.docd.purefm.utils.PFMFileUtils.java
public static void moveFile(@NonNull final GenericFile source, @NonNull final GenericFile target, final boolean useCommandLine) throws IOException { if (useCommandLine) { if (target.exists()) { throw new FileExistsException("Target exists"); }//from w w w . j a v a 2 s . co m final boolean result = CommandLine.execute(new CommandMove(source, target)); if (!result) { throw new IOException("Move failed"); } } else { FileUtils.moveFile(source.toFile(), target.toFile()); } }
From source file:com.ubb.imaging.ExifMetadataWriter.java
/** * This method illustrates how to add/update EXIF metadata in a JPEG file. * /*from w ww .j ava 2 s.co m*/ * @param srcFile * A source image file. * @param imageId * @param dstFile * The output file. * @throws IOException * @throws ImageReadException * @throws ImageWriteException */ public void changeExifMetadata(File srcFile, File dstFile, String imageId) throws IOException, ImageReadException, ImageWriteException { OutputStream os = null; boolean canThrow = false; try { TiffOutputSet outputSet = null; // note that metadata might be null if no metadata is found. final ImageMetadata metadata = (ImageMetadata) Imaging.getMetadata(srcFile); final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata; if (null != jpegMetadata) { // note that exif might be null if no Exif metadata is found. final TiffImageMetadata exif = jpegMetadata.getExif(); if (null != exif) { // TiffImageMetadata class is immutable (read-only). // TiffOutputSet class represents the Exif data to write. // // Usually, we want to update existing Exif metadata by // changing // the values of a few fields, or adding a field. // In these cases, it is easiest to use getOutputSet() to // start with a "copy" of the fields read from the image. outputSet = exif.getOutputSet(); } } // if file does not contain any exif metadata, we create an empty // set of exif metadata. Otherwise, we keep all of the other // existing tags. if (null == outputSet) { outputSet = new TiffOutputSet(); } { // Example of how to add a field/tag to the output set. // // Note that you should first remove the field/tag if it already // exists in this directory, or you may end up with duplicate // tags. See above. // // Certain fields/tags are expected in certain Exif directories; // Others can occur in more than one directory (and often have a // different meaning in different directories). // // TagInfo constants often contain a description of what // directories are associated with a given tag. // // see // org.apache.commons.imaging.formats.tiff.constants.AllTagConstants // final TiffOutputDirectory exifDirectory = outputSet.getOrCreateExifDirectory(); updateImageUniqueId(exifDirectory, imageId); updateDocumentName(exifDirectory, imageId); updateUserComments(exifDirectory); updateImageDescription(exifDirectory, LINK_TO_RESOURCE.concat(imageId)); // AllTagConstants.TIFF_TAG_IMAGE_DESCRIPTION // AllTagConstants.TIFF_TAG_DOCUMENT_NAME // AllTagConstants.TIFF_TAG_COPYRIGHT } os = new BufferedOutputStream(new FileOutputStream(dstFile)); new ExifRewriter().updateExifMetadataLossless(srcFile, os, outputSet); canThrow = true; } finally { IoUtils.closeQuietly(canThrow, os); //delete the source file srcFile.delete(); //move the new file with new metadata to the source file path (it's like copy and delete). FileUtils.moveFile(dstFile, srcFile); } }
From source file:com.comcast.magicwand.spells.web.chrome.ChromePhoenixDriver.java
/** * {@inheritDoc}//from w w w .j a v a2 s.co m */ public boolean verify(PhoenixDriverIngredients i) { Map<String, Object> driverConfigs = i.getDriverConfigs(); ChromePlatformSpecifics cps = createChromePlatformSpecifics( (String) driverConfigs.get(CHROME_DRIVER_VERSION)); LOG.debug("Using cps[{}, {}, {}]", cps.getSuffix(), cps.getExtension(), cps.getVersion()); String version = cps.getVersion(); String osName = cps.getSuffix(); String pwd = System.getProperty("user.dir"); //determine the driver name String driverName = String.format("chromedriver%s-%s", osName, version); String driverTargetDir = Paths.get(pwd, "target", "drivers").toString(); File driver = Paths.get(driverTargetDir, driverName + cps.getExtension()).toFile(); if (!driver.exists()) { LOG.debug("No cached chromedriver driver found"); /* Download chromedriver zip */ File zipDriver = Paths.get(driverTargetDir, driverName + ".zip").toFile(); if (!zipDriver.exists()) { String driverURL = String.format(DRIVER_URL_FORMAT, version, osName); try { URL driverZipURL = new URL(driverURL); LOG.debug("Will download driver package [{}]", driverURL); FileUtils.copyURLToFile(driverZipURL, zipDriver); } catch (IOException e) { LOG.error("Error downloading [{}]: {}", driverURL, e); return false; } } /* Exctract chromedriver zip */ try { extractZip(zipDriver, driverTargetDir); } catch (IOException e) { LOG.error("Error extracting [{}]: {}", zipDriver, driverTargetDir, e); return false; } /* For caching purposes, rename chromedriver to keep os and version info */ File genericDriver = Paths.get(driverTargetDir, "chromedriver" + cps.getExtension()).toFile(); try { FileUtils.moveFile(genericDriver, driver); } catch (IOException e) { LOG.error("Error moving [{}] to [{}]: {}", genericDriver, driver, e); return false; } driver.setExecutable(true); } LOG.debug("Will use driver at [{}]", driver); systemSetProperty("webdriver.chrome.driver", driver.toString()); this.webDriver = this.createDriver(i.getDriverCapabilities()); return true; }
From source file:de.ingrid.interfaces.csw.index.StatusProvider.java
/** * Write the status to the disc. To keep the time for modifying the actual * status file as short as possible, the method writes the file into a * temporary file first and then renames this file to the original status * file name. Note: Since renaming a file is not atomic in Windows, if the * target file exists already (we need to delete and then rename), this * method is synchronized.//from ww w. j av a 2s . co m * * @throws IOException */ public synchronized void write() throws IOException { // serialize the Configuration instance to xml XStream xstream = new XStream(); String xml = xstream.toXML(this.states); // write the configuration to a temporary file first File tmpFile = File.createTempFile("config", null); BufferedWriter output = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(tmpFile.getAbsolutePath()), "UTF8")); try { output.write(xml); output.close(); output = null; } finally { if (output != null) { output.close(); } } // move the temporary file to the configuration file this.lastStatusFile.delete(); FileUtils.moveFile(tmpFile, this.lastStatusFile); }
From source file:com.alibaba.jstorm.utils.LoadConf.java
public static void mv(String src, String dest) { try {/*from www.j av a 2 s . c om*/ FileUtils.moveFile(new File(src), new File(dest)); } catch (Exception ignored) { } }
From source file:com.amazonaws.eclipse.android.sdk.newproject.NewAndroidProjectWizard.java
@Override @SuppressWarnings("restriction") public boolean performFinish() { if (getContainer() instanceof WizardDialog) { setRunnableContext((WizardDialog) getContainer()); }/*from ww w . j a v a 2 s . c om*/ try { NewProjectWizardState newProjectWizardState = new NewProjectWizardState(Mode.ANY); newProjectWizardState.projectName = dataModel.getProjectName(); newProjectWizardState.applicationName = "AWS Android Application"; newProjectWizardState.packageName = dataModel.getPackageName(); newProjectWizardState.target = dataModel.getAndroidTarget(); newProjectWizardState.createActivity = false; new NewProjectCreator(newProjectWizardState, runnableContext).createAndroidProjects(); IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(dataModel.getProjectName()); IJavaProject javaProject = JavaCore.create(project); AndroidSdkInstall awsAndroidSdk = AndroidSdkManager.getInstance().getDefaultSdkInstall(); awsAndroidSdk.writeMetadataToProject(javaProject); AwsAndroidSdkClasspathUtils.addAwsAndroidSdkToProjectClasspath(javaProject, awsAndroidSdk); AndroidManifestFile androidManifestFile = new AndroidManifestFile(project); androidManifestFile.initialize(); copyProguardPropertiesFile(project); if (dataModel.isSampleCodeIncluded()) { // copy sample code files over Bundle bundle = Platform.getBundle(AndroidSDKPlugin.PLUGIN_ID); URL url = FileLocator.find(bundle, new Path("resources/S3_Uploader/"), null); try { File sourceFile = new File(FileLocator.resolve(url).toURI()); File projectFolder = project.getLocation().toFile(); File projectSourceFolder = new File(projectFolder, "src"); for (File file : sourceFile.listFiles()) { File destinationFile = new File(project.getLocation().toFile(), file.getName()); if (file.isDirectory()) FileUtils.copyDirectory(file, destinationFile); else FileUtils.copyFile(file, destinationFile); } // move *.java files to new src dir String s = dataModel.getPackageName().replace(".", File.separator) + File.separator; for (File file : projectSourceFolder.listFiles()) { if (file.isDirectory()) continue; File destinationFile = new File(projectSourceFolder, s + file.getName()); FileUtils.moveFile(file, destinationFile); // update package lines with regex // replace "com.amazonaws.demo.s3uploader" with dataModel.getPackageName() List<String> lines = FileUtils.readLines(destinationFile); ArrayList<String> outLines = new ArrayList<String>(); for (String line : lines) { outLines.add(line.replace("com.amazonaws.demo.s3uploader", dataModel.getPackageName())); } FileUtils.writeLines(destinationFile, outLines); } // update android manifest file androidManifestFile.addSampleActivity(); } catch (Exception e) { IStatus status = new Status(IStatus.ERROR, AndroidSDKPlugin.PLUGIN_ID, "Unable to update AWS SDK with sample app for Android project setup", e); StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG); } } // refresh the workspace to pick up the changes we just made project.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (Exception e) { IStatus status = new Status(IStatus.ERROR, AndroidSDKPlugin.PLUGIN_ID, "Unable to create new AWS Android project", e); StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG); return false; } return true; }