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.omegat.core.team2.RebaseAndCommit.java
public static void rebaseAndCommit(Prepared prep, RemoteRepositoryProvider provider, File projectDir, String path, IRebase rebaser) throws Exception { if (!provider.isUnderMapping(path)) { throw new RuntimeException("Path is not under mapping: " + path); }//from w w w . j ava 2s.com Log.logDebug(LOGGER, "Rebase and commit '" + path + "'"); final String currentBaseVersion; String savedVersion = provider.getTeamSettings().get(VERSION_PREFIX + path); if (savedVersion != null) { currentBaseVersion = savedVersion; } else { // version wasn't stored - assume latest. TODO Probably need to ask ? provider.switchToVersion(path, null); currentBaseVersion = provider.getVersion(path); } final File localFile = new File(projectDir, path); final boolean fileChangedLocally; { File baseRepoFile = null; if (prep != null && prep.versionBase.equals(currentBaseVersion)) { baseRepoFile = prep.fileBase; } if (baseRepoFile == null) { baseRepoFile = provider.switchToVersion(path, currentBaseVersion); } if (!localFile.exists()) { // there is no local file - just use remote Log.logDebug(LOGGER, "local file '" + path + "' doesn't exist"); fileChangedLocally = false; } else if (FileUtils.contentEquals(baseRepoFile, localFile)) { // versioned file was not changed - no need to commit Log.logDebug(LOGGER, "local file '" + path + "' wasn't changed"); fileChangedLocally = false; } else { Log.logDebug(LOGGER, "local file '" + path + "' was changed"); fileChangedLocally = true; rebaser.parseBaseFile(baseRepoFile); } // baseRepoFile is not valid anymore because we will switch to other version } File headRepoFile = null; String headVersion = null; if (prep != null) { headVersion = prep.versionHead; headRepoFile = prep.fileHead; } if (headVersion == null) { headRepoFile = provider.switchToVersion(path, null); headVersion = provider.getVersion(path); } final boolean fileChangedRemotely; { if (!localFile.exists()) { // there is no local file - just use remote if (headRepoFile.exists()) { fileChangedRemotely = true; rebaser.parseHeadFile(headRepoFile); } else { // there is no remote file also fileChangedRemotely = false; } } else if (StringUtils.equals(currentBaseVersion, headVersion)) { Log.logDebug(LOGGER, "remote file '" + path + "' wasn't changed"); fileChangedRemotely = false; } else { // base and head versions are differ - somebody else committed changes Log.logDebug(LOGGER, "remote file '" + path + "' was changed"); fileChangedRemotely = true; rebaser.parseHeadFile(headRepoFile); } } final File tempOut = new File(projectDir, path + "#based_on_" + headVersion); if (tempOut.exists() && !tempOut.delete()) { throw new Exception("Unable to delete previous temp file"); } boolean needBackup = false; if (fileChangedLocally && fileChangedRemotely) { // rebase need only in case file was changed locally AND remotely Log.logDebug(LOGGER, "rebase and save '" + path + "'"); needBackup = true; rebaser.rebaseAndSave(tempOut); } else if (fileChangedLocally && !fileChangedRemotely) { // only local changes - just use local file Log.logDebug(LOGGER, "only local changes - just use local file '" + path + "'"); } else if (!fileChangedLocally && fileChangedRemotely) { // only remote changes - get remote Log.logDebug(LOGGER, "only remote changes - get remote '" + path + "'"); needBackup = true; if (headRepoFile.exists()) {// otherwise file was removed remotelly FileUtils.copyFile(headRepoFile, tempOut); } } else { Log.logDebug(LOGGER, "there are no changes '" + path + "'"); // there are no changes } if (needBackup) { // new file was saved, need to update version // code below tries to update file "in transaction" with update version if (localFile.exists()) { final File bakTemp = new File(projectDir, path + "#oldbased_on_" + currentBaseVersion); bakTemp.delete(); FileUtils.moveFile(localFile, bakTemp); } provider.getTeamSettings().set(VERSION_PREFIX + path, headVersion); if (tempOut.exists()) { localFile.delete(); FileUtils.moveFile(tempOut, localFile); } } if (prep != null) { prep.needToCommit = fileChangedLocally; prep.commitComment = rebaser.getCommentForCommit(); if (fileChangedLocally) { prep.charset = rebaser.getFileCharset(localFile); } // no need to commit yet - it will make other thread after return; } else if (fileChangedLocally) { // new file already saved - need to commit String comment = rebaser.getCommentForCommit(); provider.copyFilesFromProjectToRepo(path, rebaser.getFileCharset(localFile)); String newVersion = provider.commitFileAfterVersion(path, comment, headVersion, null); if (newVersion != null) { // file was committed good provider.getTeamSettings().set(VERSION_PREFIX + path, newVersion); } } }
From source file:org.omegat.core.team2.TeamSettings.java
/** * Update setting./* ww w . ja v a2s. c om*/ */ public static synchronized void set(String key, String newValue) { try { Properties p = new Properties(); File f = getConfigFile(); File fNew = new File(getConfigFile().getAbsolutePath() + ".new"); if (f.exists()) { FileInputStream in = new FileInputStream(f); try { p.load(in); } finally { in.close(); } } else { f.getParentFile().mkdirs(); } if (newValue != null) { p.setProperty(key, newValue); } else { p.remove(key); } FileOutputStream out = new FileOutputStream(fNew); try { p.store(out, null); } finally { out.close(); } f.delete(); FileUtils.moveFile(fNew, f); } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:org.onebusaway.util.FileUtility.java
public void moveFile(String srcFileName, String destFileName) throws Exception { FileUtils.moveFile(new File(srcFileName), new File(destFileName)); }
From source file:org.opencastproject.workingfilerepository.impl.WorkingFileRepositoryImpl.java
/** * {@inheritDoc}/* w w w.j a va 2 s . com*/ * * @see org.opencastproject.workingfilerepository.api.WorkingFileRepository#moveTo(java.lang.String, java.lang.String, * java.lang.String, java.lang.String, java.lang.String) */ @Override public URI moveTo(String fromCollection, String fromFileName, String toMediaPackage, String toMediaPackageElement, String toFileName) throws NotFoundException, IOException { File source = getFileFromCollection(fromCollection, fromFileName); File sourceMd5 = getMd5File(source); File destDir = getElementDirectory(toMediaPackage, toMediaPackageElement); logger.debug("Moving {} from {} to {}/{}", new String[] { fromFileName, fromCollection, toMediaPackage, toMediaPackageElement }); if (!destDir.exists()) { // we needed to create the directory, but couldn't try { FileUtils.forceMkdir(destDir); } catch (IOException e) { throw new IllegalStateException("could not create mediapackage/element directory '" + destDir.getAbsolutePath() + "' : " + e); } } File dest = null; try { dest = getFile(toMediaPackage, toMediaPackageElement); logger.debug("Removing existing file from target location at {}", dest); delete(toMediaPackage, toMediaPackageElement); } catch (NotFoundException e) { dest = new File(getElementDirectory(toMediaPackage, toMediaPackageElement), PathSupport.toSafeName(toFileName)); } try { FileUtils.moveFile(source, dest); FileUtils.moveFile(sourceMd5, getMd5File(dest)); } catch (IOException e) { FileUtils.deleteDirectory(destDir); throw new IllegalStateException("unable to copy file" + e); } return getURI(toMediaPackage, toMediaPackageElement, dest.getName()); }
From source file:org.opencastproject.workspace.impl.WorkspaceImpl.java
/** * {@inheritDoc}//from w ww . j av a2 s.com * * @see org.opencastproject.workspace.api.Workspace#moveTo(java.net.URI, java.lang.String, java.lang.String, * java.lang.String) */ @Override public URI moveTo(URI collectionURI, String toMediaPackage, String toMediaPackageElement, String toFileName) throws NotFoundException, IOException { String path = collectionURI.toString(); String filename = FilenameUtils.getName(path); String collection = getCollection(collectionURI); logger.debug("Moving {} from {} to {}/{}", new String[] { filename, collection, toMediaPackage, toMediaPackageElement }); // Move the local file File original = getWorkspaceFile(collectionURI, false); if (original.isFile()) { URI copyURI = wfr.getURI(toMediaPackage, toMediaPackageElement, toFileName); File copy = getWorkspaceFile(copyURI, true); FileUtils.forceMkdir(copy.getParentFile()); FileUtils.deleteQuietly(copy); FileUtils.moveFile(original, copy); } // Tell working file repository return wfr.moveTo(collection, filename, toMediaPackage, toMediaPackageElement, toFileName); }
From source file:org.opendatakit.briefcase.util.TransferFromODK.java
@Override public boolean doAction() { boolean allSuccessful = true; for (FormStatus fs : formsToTransfer) { boolean isSuccessful = true; try {/* w ww .j av a 2 s . c o m*/ if (terminationFuture.isCancelled()) { fs.setStatusString("aborted. Skipping fetch of form and submissions...", true); EventBus.publish(new FormStatusEvent(fs)); return false; } BriefcaseFormDefinition briefcaseLfd = doResolveOdkCollectFormDefinition(fs); if (briefcaseLfd == null) { allSuccessful = isSuccessful = false; continue; } OdkCollectFormDefinition odkFormDef = (OdkCollectFormDefinition) fs.getFormDefinition(); File odkFormDefFile = odkFormDef.getFormDefinitionFile(); final String odkFormName = odkFormDefFile.getName().substring(0, odkFormDefFile.getName().lastIndexOf(".")); DatabaseUtils formDatabase = null; try { formDatabase = new DatabaseUtils( FileSystemUtils.getFormDatabase(briefcaseLfd.getFormDirectory())); File destinationFormInstancesDir; try { destinationFormInstancesDir = FileSystemUtils .getFormInstancesDirectory(briefcaseLfd.getFormDirectory()); } catch (FileSystemException e) { e.printStackTrace(); allSuccessful = isSuccessful = false; fs.setStatusString("unable to create instances folder: " + e.getMessage(), false); EventBus.publish(new FormStatusEvent(fs)); continue; } // we have the needed directory structure created... fs.setStatusString("preparing to retrieve instance data", true); EventBus.publish(new FormStatusEvent(fs)); // construct up the list of folders that might have ODK form data. File odkFormInstancesDir = new File(odkFormDefFile.getParentFile().getParentFile(), "instances"); // rely on ODK naming conventions to identify form data files... File[] odkFormInstanceDirs = odkFormInstancesDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { boolean beginsWithFormName = pathname.getName().startsWith(odkFormName); if (!beginsWithFormName) return false; // skip the separator character, as it varies between 1.1.5, 1.1.6 and 1.1.7 String afterName = pathname.getName().substring(odkFormName.length() + 1); // aftername should be a reasonable date though we allow extra stuff at the end... // protects against someone having "formname" and "formname_2" // and us mistaking "formname_2_2009-01-02_15_10_03" as containing // instance data for "formname" instead of "formname_2" boolean outcome = afterName .matches("^[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}-[0-9]{2}-[0-9]{2}.*"); return outcome; } }); if (odkFormInstanceDirs != null) { int instanceCount = 1; for (File dir : odkFormInstanceDirs) { if (terminationFuture.isCancelled()) { allSuccessful = isSuccessful = false; fs.setStatusString("aborting retrieving submissions...", true); EventBus.publish(new FormStatusEvent(fs)); return false; } // 1.1.8 -- submission is saved as submission.xml. // full instance data is stored as directoryName.xml (as is the convention in 1.1.5, 1.1.7) // File fullXml = new File(dir, dir.getName() + ".xml"); File xml = new File(dir, "submission.xml"); if (!xml.exists() && fullXml.exists()) { xml = fullXml; // e.g., 1.1.5, 1.1.7 } // this is a hack added to support easier generation of large test cases where we // copy a single instance directory repeatedly. Normally the xml submission file // has the name of the enclosing directory, but if you copy directories, this won't // be the case. In this instance, if there is one xml file in the directory, // rename it to match the directory name. if (!xml.exists()) { File[] xmlFiles = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".xml"); } }); if (xmlFiles.length == 1) { try { FileUtils.moveFile(xmlFiles[0], xml); } catch (IOException e) { e.printStackTrace(); allSuccessful = isSuccessful = false; fs.setStatusString("unable to rename form instance xml: " + e.getMessage(), false); EventBus.publish(new FormStatusEvent(fs)); continue; } } } if (xml.exists()) { // OK, we can copy the directory off... // Briefcase instances directory name is arbitrary. // Rename the xml within that to always be "submission.xml" // to remove the correspondence to the directory name. File scratchInstance = FileSystemUtils .getFormSubmissionDirectory(destinationFormInstancesDir, dir.getName()); String safeName = scratchInstance.getName(); int i = 2; while (scratchInstance.exists()) { String[] contents = scratchInstance.list(); if (contents == null || contents.length == 0) break; scratchInstance = new File(destinationFormInstancesDir, safeName + "-" + Integer.toString(i)); i++; } try { FileUtils.copyDirectory(dir, scratchInstance); } catch (IOException e) { e.printStackTrace(); allSuccessful = isSuccessful = false; fs.setStatusString("unable to copy saved instance: " + e.getMessage(), false); EventBus.publish(new FormStatusEvent(fs)); continue; } if (xml.equals(fullXml)) { // need to rename File odkSubmissionFile = new File(scratchInstance, fullXml.getName()); File scratchSubmissionFile = new File(scratchInstance, "submission.xml"); try { FileUtils.moveFile(odkSubmissionFile, scratchSubmissionFile); } catch (IOException e) { e.printStackTrace(); allSuccessful = isSuccessful = false; fs.setStatusString("unable to rename submission file to submission.xml: " + e.getMessage(), false); EventBus.publish(new FormStatusEvent(fs)); continue; } } else { // delete the full xml file (keep only the submission.xml) File odkSubmissionFile = new File(scratchInstance, fullXml.getName()); odkSubmissionFile.delete(); } fs.setStatusString(String.format("retrieving (%1$d)", instanceCount), true); EventBus.publish(new FormStatusEvent(fs)); ++instanceCount; } } } } catch (FileSystemException e) { e.printStackTrace(); allSuccessful = isSuccessful = false; fs.setStatusString("unable to open form database: " + e.getMessage(), false); EventBus.publish(new FormStatusEvent(fs)); continue; } finally { if (formDatabase != null) { try { formDatabase.close(); } catch (SQLException e) { e.printStackTrace(); allSuccessful = isSuccessful = false; fs.setStatusString("unable to close form database: " + e.getMessage(), false); EventBus.publish(new FormStatusEvent(fs)); continue; } } } } finally { if (isSuccessful) { fs.setStatusString("SUCCESS!", true); EventBus.publish(new FormStatusEvent(fs)); } else { fs.setStatusString("FAILED.", true); EventBus.publish(new FormStatusEvent(fs)); } } } return allSuccessful; }
From source file:org.openengsb.core.services.internal.deployer.connector.ConnectorDeployerService.java
private void doUpdate(File artifact) throws Exception { ConnectorFile connectorFile = oldConfigs.get(artifact); final String connectorId = connectorFile.getName(); ConnectorDescription persistenceContent = serviceManager.getAttributeValues(connectorId); ChangeSet changes = connectorFile.getChanges(artifact); final ConnectorDescription newDescription; try {/*from w ww .j a v a2 s . co m*/ newDescription = applyChanges(persistenceContent, changes); connectorFile.update(artifact); } catch (MergeException e) { File backupFile = getBackupFile(artifact); FileUtils.moveFile(artifact, backupFile); Properties properties = connectorFile.toProperties(); properties.store(new FileWriter(artifact), "Connector update failed. The invalid connector-file has been saved to " + backupFile.getName()); throw e; } SecurityContext.executeWithSystemPermissions(new Callable<Object>() { @Override public Object call() throws Exception { serviceManager.update(connectorId, newDescription); return null; } }); }
From source file:org.openiot.gsn.http.ac.ParameterSet.java
public DataSource fileUploader(String vsname, String saveDirectory) { DataSource ds = null;/*from ww w .j a va 2 s. c om*/ String name = null; String filename = null; String filetype = null; File file = null; try { Enumeration filesEnum = this.multipartreq.getFileNames(); while (filesEnum.hasMoreElements()) { name = (String) filesEnum.nextElement(); filename = this.multipartreq.getFilesystemName(name); filetype = this.multipartreq.getContentType(name); file = this.multipartreq.getFile(name); if (filename != null && filetype != null) { //rename the name of the Virtual Sensor to the unique name //logger.info("filename " + filename); //logger.info("name " + name); //logger.info("abs path " + file.getAbsolutePath()); changeSensorName(file.getAbsolutePath(), vsname); String newFilePath = file.getAbsolutePath().replace(file.getName(), "") + vsname + ".xml"; File newFile = new File(newFilePath); try { FileUtils.moveFile(file, newFile); } catch (IOException e) { e.printStackTrace(); } ds = new DataSource(vsname, "4", vsname + ".xml", filetype, saveDirectory); } if (file != null) { logger.info("length: " + file.length()); } } } catch (Exception e) { logger.error("ERROR IN fileUploader Method"); logger.error(e.getMessage(), e); } return ds; }
From source file:org.openmrs.module.emrmonitor.UptimeLog.java
/** * Rotates the current uptime.log file to a new file with the current datetime *//*from w w w .j a va2 s . c om*/ public static synchronized File rotate() { Date now = new Date(); String filename = DateFormatUtils.format(now, DATE_FORMAT) + ".log"; File destinationFile = new File(getLogDirectory(), filename); try { writeToLog(now, LOG_COMPLETED_TOKEN); FileUtils.moveFile(getLogFile(), destinationFile); initializeLogFile(now); } catch (IOException e) { throw new IllegalStateException("Unable to rotate log file to destination", e); } return destinationFile; }
From source file:org.opennms.upgrade.implementations.JmxRrdMigratorOffline.java
/** * Fixes a JMX configuration file.//from w w w .j ava 2 s . com * * @param jmxConfigFile the JMX configuration file * @throws OnmsUpgradeException the OpenNMS upgrade exception */ private void fixJmxConfigurationFile(File jmxConfigFile) throws OnmsUpgradeException { try { log("Updating JMX metric definitions on %s\n", jmxConfigFile); zipFile(jmxConfigFile); backupFiles.add(new File(jmxConfigFile.getAbsolutePath() + ZIP_EXT)); File outputFile = new File(jmxConfigFile.getCanonicalFile() + ".temp"); FileWriter w = new FileWriter(outputFile); Pattern extRegex = Pattern.compile("import-mbeans[>](.+)[<]"); Pattern aliasRegex = Pattern.compile("alias=\"([^\"]+\\.[^\"]+)\""); List<File> externalFiles = new ArrayList<File>(); LineIterator it = FileUtils.lineIterator(jmxConfigFile); while (it.hasNext()) { String line = it.next(); Matcher m = extRegex.matcher(line); if (m.find()) { externalFiles.add(new File(jmxConfigFile.getParentFile(), m.group(1))); } m = aliasRegex.matcher(line); if (m.find()) { String badDs = m.group(1); String fixedDs = getFixedDsName(badDs); log(" Replacing bad alias %s with %s on %s\n", badDs, fixedDs, line.trim()); line = line.replaceAll(badDs, fixedDs); if (badMetrics.contains(badDs) == false) { badMetrics.add(badDs); } } w.write(line + "\n"); } LineIterator.closeQuietly(it); w.close(); FileUtils.deleteQuietly(jmxConfigFile); FileUtils.moveFile(outputFile, jmxConfigFile); if (!externalFiles.isEmpty()) { for (File configFile : externalFiles) { fixJmxConfigurationFile(configFile); } } } catch (Exception e) { throw new OnmsUpgradeException("Can't fix " + jmxConfigFile + " because " + e.getMessage(), e); } }