List of usage examples for org.apache.commons.io FileUtils moveFile
public static void moveFile(File srcFile, File destFile) throws IOException
From source file:org.cleverbus.core.common.file.DefaultFileRepository.java
@Override public void commitFile(String fileId, String fileName, FileContentTypeExtEnum contentType, List<String> subFolders) { Assert.hasText(fileId, "fileId must not be empty"); Assert.hasText(fileName, "fileName must not be empty"); Assert.notNull(subFolders, "subFolders must not be null"); File tmpFile = new File(tempDir, fileId); // check file existence if (!tmpFile.exists() || !tmpFile.canRead()) { String msg = "temp file " + tmpFile + " doesn't exist or can't be read"; Log.error(msg);/* w w w .j a v a 2 s .c o m*/ throw new IntegrationException(InternalErrorEnum.E115, msg); } // move file to target directory String targetDirName = FilenameUtils.concat(fileRepoDir.getAbsolutePath(), StringUtils.join(subFolders, File.separator)); targetDirName = FilenameUtils.normalize(targetDirName); File targetDir = new File(targetDirName); try { FileUtils.moveFileToDirectory(tmpFile, targetDir, true); Log.debug("File (" + tmpFile + ") was successfully moved to directory - " + targetDir); } catch (IOException e) { String msg = "error occurred during moving temp file " + tmpFile + " to target directory - " + targetDirName; Log.error(msg); throw new IntegrationException(InternalErrorEnum.E115, msg); } // rename file File targetTmpFile = new File(targetDir, fileId); String targetFileName = FilenameUtils.concat(targetDir.getAbsolutePath(), getFileName(fileName, contentType)); targetFileName = FilenameUtils.normalize(targetFileName); try { FileUtils.moveFile(targetTmpFile, new File(targetFileName)); Log.debug("File (" + tmpFile + ") was successfully committed. New path: " + targetFileName); } catch (IOException e) { String msg = "error occurred during renaming temp file " + tmpFile + " to target directory - " + targetDirName; Log.error(msg); throw new IntegrationException(InternalErrorEnum.E115, msg); } }
From source file:org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.ec2.bigdata.RepetativeInstallAndUninstallStockDemoWithProblemAtInstallEc2Test.java
private void corruptCassandraService(String cassandraPostStartScriptPath, String newPostStartScriptPath) throws IOException { File cassandraPostStartScript = new File(cassandraPostStartScriptPath); FileUtils.moveFile(cassandraPostStartScript, new File(newPostStartScriptPath)); }
From source file:org.cruxframework.crux.tools.codeserver.CodeServer.java
protected void execute() throws Exception { AbstractCruxCompiler compiler = CruxCompilerFactory.createCompiler(); compiler.setOutputCharset("UTF-8"); CruxBridge.getInstance().setSingleVM(true); CruxRegisterUtil.registerFilesCruxBridge(null); ServiceFactoryInitializer.initialize(null); RestServiceFactoryInitializer.initialize(null); compiler.initializeCompiler();//from www . j av a 2s .com Set<String> screenIDs = null; try { screenIDs = ScreenResourceResolverInitializer.getScreenResourceResolver().getAllScreenIDs(moduleName); } catch (Exception e) { logger.info("Error retrieving crux pages list for module [" + moduleName + "]. " + "Please, verify if the module name parameter matches the module short name on your .gwt file", e); } if (screenIDs != null && !screenIDs.isEmpty()) { logger.info("Starting code server for module [" + moduleName + "]"); CruxBridge.getInstance().registerLastPageRequested(screenIDs.iterator().next()); processUserAgent(); String[] args = getServerParameters(); HotDeploymentScanner hotDeploymentScanner = initializeRecompileListener(); runGWTCodeServer(args); if (Boolean.valueOf(ConfigurationFactory.getConfigurations().generateIndexInDevMode())) { for (String screenID : screenIDs) { URL preProcessCruxPage = compiler.preProcessCruxPage(new URL(screenID), Modules.getInstance().getModule(moduleName)); File index = new File(webDir + File.separator + moduleName + File.separator + screenID.substring(screenID.lastIndexOf("/") + 1, screenID.lastIndexOf(".crux.xml")) + ".html"); index.delete(); FileUtils.moveFile(new File(preProcessCruxPage.getFile()), index); } } if (startHotDeploymentScanner) { hotDeploymentScanner.recompileCodeServer(); } } else { logger.error("Unable to find any screens in module [" + moduleName + "]"); } }
From source file:org.cytoscape.app.internal.manager.App.java
/** * Default app installation method that can be used by classes extending this class. * /*from w w w . ja v a 2 s . co m*/ * Attempts to install an app by copying it to the installed apps directory, * creating an instance of the app's class that extends the {@link AbstractCyApp} class, * and registering it with the given {@link AppManager} object. The app is instanced by * calling its createAppInstance() method. * * @param appManager The AppManager used to register this app with. * @throws AppInstallException If there was an error while attempting to install the app such * as improper app packaging, failure to copy the file to the installed apps directory, * or failure to create an instance of the app. */ protected void defaultInstall(AppManager appManager) throws AppInstallException { // Check if the app has been verified to contain proper packaging. if (!this.isAppValidated()) { // If the app is not packaged properly or is missing fields in its manifest file, do not install the app // as the install operation will fail. throw new AppInstallException( "Cannot install app; app file has not been checked to have proper metadata"); } // Check if the app has already been installed. if (this.getStatus() == AppStatus.INSTALLED) { // Do nothing if it is already installed throw new AppInstallException("This app has already been installed."); } for (App app : appManager.getApps()) { if (this.heuristicEquals(app) && this != app) { // If we already have an App object registered to the app manager // that represents this app, re-use that app object app.setAppFile(this.appFile); app.install(appManager); //appManager.installApp(app); return; } } // Obtain the paths to the local storage directories for holding installed and uninstalled apps. String installedAppsPath = appManager.getInstalledAppsPath(); String uninstalledAppsPath = appManager.getUninstalledAppsPath(); // Attempt to copy the app to the directory for installed apps. try { File appFile = this.getAppFile(); if (!appFile.exists()) { DebugHelper.print("Install aborted: file " + appFile.getCanonicalPath() + " does not exist"); return; } // Make sure no app with the same filename and app name is already installed File installedDirectoryTargetFile = new File(installedAppsPath + File.separator + appFile.getName()); File uninstalledDirectoryTargetFile = new File( uninstalledAppsPath + File.separator + appFile.getName()); String copyDestinationFileName = appFile.getName(); // Check for filename collisions in both the installed apps directory as well as the // uninstalled apps directory if (installedDirectoryTargetFile.exists() || uninstalledDirectoryTargetFile.exists()) { Set<App> registeredApps = appManager.getApps(); // The app registered to the app manager that happens to have the same filename App conflictingApp = null; File registeredAppFile; for (App registeredApp : registeredApps) { registeredAppFile = registeredApp.getAppFile(); if (registeredAppFile != null && registeredAppFile.getName().equalsIgnoreCase(appFile.getName())) { conflictingApp = registeredApp; } } // Only prevent the overwrite if the filename conflict is with an app registered // to the app manager if (conflictingApp != null) { // Check if the apps have the same name if (this.getAppName().equalsIgnoreCase(conflictingApp.getAppName())) { // Same filename, same app name found // Forgive the collision if we are copying from the uninstalled apps directory if (appFile.getParentFile().getCanonicalPath().equals(uninstalledAppsPath)) { // Forgive collision if other app is not installed } else if (conflictingApp.getStatus() != AppStatus.INSTALLED) { // Ignore collisions with self // } else if (conflictingApp.getAppFile().equals(appFile)) { } else { /* for (App app : appManager.getApps()) { if (this.heuristicEquals(app) && this != app) { DebugHelper.print("Install aborted: heuristic finds app already installed"); DebugHelper.print("conflict app status: " + app.getStatus()); DebugHelper.print("conflict app name: " + app.getAppName()); appManager.installApp(app); return; } } */ // Skip installation, suspected that a copy of the app is already installed // return; } } else { // Same filename, different app name found // Rename file Collection<String> directoryPaths = new LinkedList<String>(); directoryPaths.add(installedAppsPath); directoryPaths.add(uninstalledAppsPath); copyDestinationFileName = suggestFileName(directoryPaths, appFile.getName()); } } } // Only perform the copy if the app was not already in the target directory if (!appFile.getParentFile().getCanonicalPath().equals(installedAppsPath)) { // Uses Apache Commons library; overwrites files with the same name. // FileUtils.copyFileToDirectory(appFile, new File(installedAppsPath)); // If we copied it from the uninstalled apps directory, remove it from that directory File targetFile = new File(installedAppsPath + File.separator + copyDestinationFileName); if (appFile.getParentFile().getCanonicalPath().equals(uninstalledAppsPath)) { FileUtils.moveFile(appFile, targetFile); } else { FileUtils.copyFile(appFile, targetFile); } // Update the app's path this.setAppFile(new File(installedAppsPath + File.separator + copyDestinationFileName)); } } catch (IOException e) { throw new AppInstallException("Unable to copy app file to installed apps directory: " + e.getMessage()); } // Make a second copy to be used to load the actual classes // This is used to prevent errors associated with moving jar files that have classes loaded from them. if (this.getAppTemporaryInstallFile() == null) { String temporaryInstallPath = appManager.getTemporaryInstallPath(); List<String> temporaryInstallPathCollection = new LinkedList<String>(); temporaryInstallPathCollection.add(temporaryInstallPath); // Rename the file if necessary to avoid overwrites File temporaryInstallTargetFile = new File(temporaryInstallPath + File.separator + suggestFileName(temporaryInstallPathCollection, appFile.getName())); try { FileUtils.copyFile(appFile, temporaryInstallTargetFile); this.setAppTemporaryInstallFile(temporaryInstallTargetFile); } catch (IOException e) { logger.warn("Failed to make copy of app file to be used for loading classes. The problem was: " + e.getMessage()); } } // Create an app instance only if one was not already created if (this.getAppInstance() == null) { Object appInstance; try { appInstance = createAppInstance(appManager.getSwingAppAdapter()); } catch (AppInstanceException e) { throw new AppInstallException("Unable to create app instance: " + e.getMessage()); } // Keep a reference to the newly created instance this.setAppInstance((AbstractCyApp) appInstance); } this.setStatus(AppStatus.INSTALLED); appManager.addApp(this); }
From source file:org.cytoscape.app.internal.manager.App.java
/** * Moves an app file to the given directory, copying the app if it is outside one of the local app storage directories * and moving if it is not. Also assigns filename that does not colliide with any from the local app storage directories. * //from w w w. j a v a 2 s. c om * Will also add postfix to filename if desired filename already exists in target directory when * moving app to a directory other than the 3 local app storage directories. * * @param appManager A reference to the app manager * @param targetDirectory The local storage directory to move to, such as the local sotrage directory * containing installed apps obtained via the app manager * @throws IOException If there was an error while moving/copying the file */ public void moveAppFile(AppManager appManager, File targetDirectory) throws IOException { File parentPath = this.getAppFile().getParentFile(); File installDirectoryPath = new File(appManager.getInstalledAppsPath()); File disabledDirectoryPath = new File(appManager.getDisabledAppsPath()); File uninstallDirectoryPath = new File(appManager.getUninstalledAppsPath()); // Want to make sure the app file's name does not collide with another name in these directories LinkedList<String> uniqueNameDirectories = new LinkedList<String>(); if (!parentPath.equals(installDirectoryPath)) uniqueNameDirectories.add(installDirectoryPath.getCanonicalPath()); if (!parentPath.equals(disabledDirectoryPath)) uniqueNameDirectories.add(disabledDirectoryPath.getCanonicalPath()); if (!parentPath.equals(uninstallDirectoryPath)) uniqueNameDirectories.add(uninstallDirectoryPath.getCanonicalPath()); if (!parentPath.equals(targetDirectory) && !installDirectoryPath.equals(targetDirectory) && !disabledDirectoryPath.equals(targetDirectory) && !uninstallDirectoryPath.equals(targetDirectory)) uniqueNameDirectories.add(targetDirectory.getCanonicalPath()); // If the app file is in one of these directories, do a move instead of a copy LinkedList<File> moveDirectories = new LinkedList<File>(); moveDirectories.add(installDirectoryPath); moveDirectories.add(disabledDirectoryPath); moveDirectories.add(uninstallDirectoryPath); File targetFile = new File(targetDirectory.getCanonicalPath() + File.separator + suggestFileName(uniqueNameDirectories, this.getAppFile().getName())); if (!targetDirectory.equals(parentPath)) { if (moveDirectories.contains(parentPath)) { FileUtils.moveFile(this.getAppFile(), targetFile); //System.out.println("Moving: " + this.getAppFile() + " -> " + targetFile); // ** Disabled to let directory observers assign file reference // this.setAppFile(targetFile); } else { FileUtils.copyFile(this.getAppFile(), targetFile); //System.out.println("Copying: " + this.getAppFile() + " -> " + targetFile); // ** Disabled to let directory observers assign file reference // this.setAppFile(targetFile); } } }
From source file:org.cytoscape.app.internal.manager.KarafArchiveApp.java
@Override public void uninstall(AppManager appManager) throws AppUninstallException { // Use the default uninstallation procedure consisting of moving the app file // to the uninstalled apps directory // defaultUninstall(appManager); try {// w w w. ja v a 2 s .c om File uninstallDirectoryTargetFile = new File( appManager.getUninstalledAppsPath() + File.separator + getAppFile().getName()); if (uninstallDirectoryTargetFile.exists()) { uninstallDirectoryTargetFile.delete(); } try { FileUtils.moveFile(getAppFile(), uninstallDirectoryTargetFile); } catch (FileExistsException e) { } this.setAppFile(uninstallDirectoryTargetFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new AppUninstallException( "Unable to move app file to uninstalled apps directory: " + e.getMessage()); } this.getAppTemporaryInstallFile().delete(); this.setStatus(AppStatus.UNINSTALLED); }
From source file:org.dataconservancy.dcs.ingest.file.impl.FileSystemContentStager.java
public StagedFile add(InputStream stream, Map<String, String> metadata) { if (baseDir == null) { throw new NullPointerException("Base directory not set!"); }// w w w. j a v a2s. c om FilePathSource path = pathAlgorithm.getPath(stream, metadata); String initialPath = null; if (path.getPathName() != null) { initialPath = path.getPathName(); File initialFile = new File(baseDir, initialPath); if (initialFile.exists() && pathAlgorithm.isContentAddressable()) { return new FsStagedFile(path, createSip(path.getPathKey())); } } else { initialPath = getTempPath(); } try { File initialFile = new File(baseDir, initialPath); FileOutputStream out = FileUtils.openOutputStream(initialFile); InputStream source = path.getInputStream(); IOUtils.copy(source, out); out.close(); source.close(); if (!path.getPathName().equals(initialPath)) { File dest = new File(baseDir, path.getPathName()); if (dest.exists() && pathAlgorithm.isContentAddressable()) { initialFile.delete(); return new FsStagedFile(path, createSip(path.getPathKey())); } else { FileUtils.moveFile(initialFile, dest); } } } catch (IOException e) { log.error("Error storing file: " + e.getMessage()); throw new RuntimeException("Could not store content", e); } return new FsStagedFile(path, createSip(path.getPathKey())); }
From source file:org.dcm4chee.proxy.dimse.CStore.java
private Attributes processInputStream(ProxyAEExtension proxyAEE, Association as, PresentationContext pc, Attributes rq, PDVInputStream data, File file) throws FileNotFoundException, IOException { LOG.debug("{}: write {}", as, file); // stream to write spool file FileOutputStream fout = new FileOutputStream(file); BufferedOutputStream bout = new BufferedOutputStream(fout); DicomOutputStream out = new DicomOutputStream(bout, UID.ExplicitVRLittleEndian); String cuid = rq.getString(Tag.AffectedSOPClassUID); String iuid = rq.getString(Tag.AffectedSOPInstanceUID); String tsuid = pc.getTransferSyntax(); Attributes fmi = as.createFileMetaInformation(iuid, cuid, tsuid); // fix//from w w w .j a va 2 s .com // spool first try { if (data instanceof PDVInputStream) { ((PDVInputStream) data).copyTo(out); } else if (data != null) { StreamUtils.copy(data, out); } } finally { fout.flush(); fout.getFD().sync(); SafeClose.close(out); SafeClose.close(bout); SafeClose.close(fout); } // coerce second DicomInputStream din = new DicomInputStream(file); Attributes attrs = null; try { // include only an uri in the read dataset din.setIncludeBulkData(IncludeBulkData.URI); attrs = din.readDataset(-1, -1); } finally { SafeClose.close(din); } File tempFile = new File(file.getPath() + ".tmpBulkData"); fout = new FileOutputStream(tempFile); bout = new BufferedOutputStream(fout); out = new DicomOutputStream(bout, UID.ExplicitVRLittleEndian); attrs = AttributeCoercionUtils.coerceDataset(proxyAEE, as, Role.SCU, Dimse.C_STORE_RQ, attrs, rq); try { out.writeDataset(fmi, attrs); fout.flush(); fout.getFD().sync(); } finally { SafeClose.close(out); SafeClose.close(bout); SafeClose.close(fout); } try { FileUtils.deleteQuietly(file); FileUtils.moveFile(tempFile, file); } catch (IOException e) { LOG.error("Exception moving temp file with coerced set to spool", e); } Properties prop = new Properties(); prop.setProperty("hostname", as.getConnection().getHostname()); String patID = attrs.getString(Tag.PatientID); prop.setProperty("patient-id", (patID == null || patID.length() == 0) ? "<UNKNOWN>" : patID); prop.setProperty("study-iuid", attrs.getString(Tag.StudyInstanceUID)); prop.setProperty("sop-instance-uid", attrs.getString(Tag.SOPInstanceUID)); prop.setProperty("sop-class-uid", attrs.getString(Tag.SOPClassUID)); prop.setProperty("transfer-syntax-uid", fmi.getString(Tag.TransferSyntaxUID)); prop.setProperty("source-aet", as.getCallingAET()); String path = file.getPath(); File info = new File(path.substring(0, path.length() - 5) + ".info"); FileOutputStream infoOut = new FileOutputStream(info); try { prop.store(infoOut, null); infoOut.flush(); infoOut.getFD().sync(); } finally { infoOut.close(); } attrs = null; return fmi; }
From source file:org.dita.dost.module.CleanPreprocessModule.java
@Override public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException { final URI base = job.getInputDir(); final Collection<FileInfo> fis = job.getFileInfo().stream().collect(Collectors.toList()); final LinkFilter filter = new LinkFilter(); filter.setJob(job);/*from ww w. jav a 2 s.c o m*/ filter.setLogger(logger); final Collection<FileInfo> res = new ArrayList<>(fis.size()); for (final FileInfo fi : fis) { try { final FileInfo.Builder builder = new FileInfo.Builder(fi); final File srcFile = new File(job.tempDirURI.resolve(fi.uri)); if (srcFile.exists()) { final URI rel = base.relativize(fi.result); final File destFile = new File(job.tempDirURI.resolve(rel)); if (fi.format == null || fi.format.equals(ATTR_FORMAT_VALUE_DITA) || fi.format.equals(ATTR_FORMAT_VALUE_DITAMAP)) { logger.info("Processing " + srcFile.toURI() + " to " + destFile.toURI()); filter.setCurrentFile(srcFile.toURI()); filter.setDestFile(destFile.toURI()); transform(srcFile.toURI(), destFile.toURI(), Collections.singletonList(filter)); if (!srcFile.equals(destFile)) { logger.debug("Deleting " + srcFile.toURI()); FileUtils.deleteQuietly(srcFile); } } else if (fi.format.equals("coderef")) { // SKIP } else if (!srcFile.equals(destFile)) { logger.info("Copying " + srcFile.toURI() + " to " + destFile.toURI()); FileUtils.moveFile(srcFile, destFile); } builder.uri(rel); // start map if (fi.src.equals(job.getInputFile())) { job.setProperty(INPUT_DITAMAP_URI, rel.toString()); job.setProperty(INPUT_DITAMAP, toFile(rel).getPath()); } } res.add(builder.build()); } catch (final IOException e) { logger.error("Failed to clean " + job.tempDirURI.resolve(fi.uri) + ": " + e.getMessage(), e); } } fis.stream().forEach(fi -> job.remove(fi)); res.stream().forEach(fi -> job.add(fi)); try { job.write(); } catch (IOException e) { throw new DITAOTException(); } return null; }
From source file:org.dspace.installer_edm.InstallerCrosswalk.java
/** * Abre el jar para escribir el nuevo archivo class compilado, elresto de archivos los copia tal cual * * @throws IOException// w w w .ja v a2 s. co m */ protected void writeNewJar() throws IOException { // buffer para leer datos de los archivos final int BUFFER_SIZE = 1024; // directorio de trabajo File jarDir = new File(this.oaiApiJarJarFile.getName()).getParentFile(); // nombre del jar String name = oaiApiJarWorkFile.getName(); String extension = name.substring(name.lastIndexOf('.')); name = name.substring(0, name.lastIndexOf('.')); // archivo temporal del nuevo jar File newJarFile = File.createTempFile(name, extension, jarDir); newJarFile.deleteOnExit(); // flujo de escritura del nuevo jar JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile)); // recorrer todos los archivos del jar menos el crosswalk para replicarlos try { Enumeration<JarEntry> entries = oaiApiJarJarFile.entries(); while (entries.hasMoreElements()) { installerEDMDisplay.showProgress('.'); JarEntry entry = entries.nextElement(); if (!entry.getName().equals(edmCrossWalkClass)) { JarEntry entryOld = new JarEntry(entry); entryOld.setCompressedSize(-1); jarOutputStream.putNextEntry(entryOld); InputStream intputStream = oaiApiJarJarFile.getInputStream(entry); int count; byte data[] = new byte[BUFFER_SIZE]; while ((count = intputStream.read(data, 0, BUFFER_SIZE)) != -1) { jarOutputStream.write(data, 0, count); } intputStream.close(); } } installerEDMDisplay.showLn(); // aadir class compilado addClass2Jar(jarOutputStream); // cerrar jar original oaiApiJarJarFile.close(); // borrar jar original oaiApiJarWorkFile.delete(); // cambiar jar original por nuevo try { /*if (newJarFile.renameTo(oaiApiJarWorkFile) && oaiApiJarWorkFile.setExecutable(true, true)) { oaiApiJarWorkFile = new File(oaiApiJarName); } else { throw new IOException(); }*/ if (jarOutputStream != null) jarOutputStream.close(); FileUtils.moveFile(newJarFile, oaiApiJarWorkFile); oaiApiJarWorkFile.setExecutable(true, true); oaiApiJarWorkFile = new File(oaiApiJarName); } catch (Exception io) { io.printStackTrace(); throw new IOException(); } } finally { if (jarOutputStream != null) { jarOutputStream.close(); } } }