Java Code Examples for com.google.common.io.Files#move()

The following examples show how to use com.google.common.io.Files#move() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DelegateGenerationManager.java    From myrrix-recommender with Apache License 2.0 6 votes vote down vote up
/**
 * Saves a model (as a {@link Generation} to a given file.
 *
 * @see #readModel()
 */
private static void saveModel(Generation generation, File modelFile) throws IOException {

  File newModelFile = File.createTempFile(DelegateGenerationManager.class.getSimpleName(), ".bin.gz");
  log.info("Writing model to {}", newModelFile);

  try {
    GenerationSerializer.writeGeneration(generation, newModelFile);
  } catch (IOException ioe) {
    if (newModelFile.exists() && !newModelFile.delete()) {
      log.warn("Could not delete {}", newModelFile);
    }
    throw ioe;
  }

  log.info("Done, moving into place at {}", modelFile);
  if (modelFile.exists() && !modelFile.delete()) {
    log.warn("Could not delete old {}", modelFile);
  }
  Files.move(newModelFile, modelFile);
}
 
Example 2
Source File: EnhancedMove.java    From PeerWasp with MIT License 6 votes vote down vote up
private void manyNonEmptyFolderMoveTestFunc() throws IOException{
		logger.debug("--------------------START------------");
		int nrFolders = 10;
		int nrFilesPerFolder = 10;
		Path destination = addFolder();
		List<Path> paths = addManyFilesInManyFolders(10, 10);
		List<Path> destinationPaths = new ArrayList<Path>();
		int totalFiles = nrFolders + nrFolders * nrFilesPerFolder + 1;

		assertCleanedUpState(totalFiles);
		Path lastDestination = null;
		for(Path path: paths){
			if(path.toFile().isDirectory()){
				lastDestination = destination.resolve(path.getFileName());
//				destinationPaths.add(lastDestination);
				if(path.toFile().exists()){
					Files.move(path.toFile(), lastDestination.toFile());
					destinationPaths.add(lastDestination);
				}
			}

		}
		waitForExists(destinationPaths, WAIT_TIME_SHORT);
		assertCleanedUpState(totalFiles);
		logger.debug("--------------------END------------");
	}
 
Example 3
Source File: WebDriverSetup.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static void downloadAndExtractGeckoDriver(File directory, String downloadFilenameSuffix,
        String downloadFilenameExt, String optionalExt, Archiver archiver) throws IOException {
    // using System.out to make sure user sees why there is a delay here
    System.out.print("Downloading Mozilla geckodriver " + GECKO_DRIVER_VERSION + "...");
    URL url = new URL("https://github.com/mozilla/geckodriver/releases/download/v"
            + GECKO_DRIVER_VERSION + "/geckodriver-v" + GECKO_DRIVER_VERSION + '-'
            + downloadFilenameSuffix + '.' + downloadFilenameExt);
    InputStream in = url.openStream();
    File archiveFile = File.createTempFile("geckodriver-" + GECKO_DRIVER_VERSION + '-',
            '.' + downloadFilenameExt);
    Files.asByteSink(archiveFile).writeFrom(in);
    in.close();
    archiver.extract(archiveFile, directory);
    Files.move(new File(directory, "geckodriver" + optionalExt),
            new File(directory, "geckodriver-" + GECKO_DRIVER_VERSION + optionalExt));
    archiveFile.delete();
    System.out.println(" OK");
}
 
Example 4
Source File: Move.java    From PeerWasp with MIT License 6 votes vote down vote up
private void moveManyFilesIntoFolder(List<Path> files, Path dstFolder, int nrMoves) {
	ArrayList<Path> movedFiles = new ArrayList<Path>();

	for(int i = 0; i < nrMoves; i++){
		if(files.get(i).toFile().isDirectory()){
			nrMoves--;
			continue;
		}

		Path dstPath = dstFolder.resolve(files.get(i).getFileName());
		try {
			Files.move(files.get(i).toFile(), dstPath.toFile());
			movedFiles.add(dstPath);
		} catch (IOException e) {
			e.printStackTrace();
			movedFiles.remove(dstPath);
		}
	}

	assertTrue(nrMoves == movedFiles.size());
	waitForExists(movedFiles, WAIT_TIME_LONG);
}
 
Example 5
Source File: CommandLineSteps.java    From datamill with ISC License 6 votes vote down vote up
@When("^" + Phrases.SUBJECT + " moves \"(.+)\" to \"(.+)\" in the temporary directory$")
public void move(String from, String to) throws IOException {
    File temporaryDirectory = (File) propertyStore.get(TEMPORARY_DIRECTORY);
    if (temporaryDirectory == null || !temporaryDirectory.isDirectory()) {
        fail("A temporary directory was not created to move files!");
    }

    String resolvedFrom = placeholderResolver.resolve(from);
    String resolvedTo = placeholderResolver.resolve(to);

    File fromFile = new File(temporaryDirectory, resolvedFrom);
    File toFile = new File(temporaryDirectory, resolvedTo);

    if (fromFile.exists()) {
        Files.move(fromFile, toFile);
    } else {
        fail("Failed to move non-existent file " + fromFile.getAbsolutePath());
    }
}
 
Example 6
Source File: SimpleMetaDataManager.java    From science-journal with Apache License 2.0 6 votes vote down vote up
@Override
public void moveExperimentToAnotherAccount(Experiment experiment, AppAccount targetAccount)
    throws IOException {
  // Move experiment directory.
  File sourceExperimentDirectory =
      FileMetadataUtil.getInstance()
          .getExperimentDirectory(appAccount, experiment.getExperimentId());
  File targetExperimentDirectory =
      FileMetadataUtil.getInstance()
          .getExperimentDirectory(targetAccount, experiment.getExperimentId());
  File parent = targetExperimentDirectory.getParentFile();
  if (!parent.exists() && !parent.mkdir()) {
    if (Log.isLoggable(TAG, Log.ERROR)) {
      Log.e(TAG, "Failed to create parent directory.");
    }
    // TODO(lizlooney): Handle this situation!
    throw new IOException("Failed to create parent directory " + parent);
  }
  Files.move(sourceExperimentDirectory, targetExperimentDirectory);
}
 
Example 7
Source File: DelegateGenerationManager.java    From myrrix-recommender with Apache License 2.0 6 votes vote down vote up
private synchronized void closeAppender() throws IOException {
  if (appender != null) {
    try {
      appender.close(); // Want to know of output stream close failed -- maybe failed to write
    } catch (IOException ioe) {
      // But proceed anyway with what was written
      log.warn("Failed to close appender cleanly", ioe);
    }
    if (appendFile.exists()) {
      if (IOUtils.isGZIPFileEmpty(appendFile)) {
        log.info("File appears to have no data, deleting: {}", appendFile);
        if (!appendFile.delete()) {
          log.warn("Could not delete {}", appendFile);
        }
      } else {
        Files.move(appendFile, new File(inputDir, System.currentTimeMillis() + ".csv.gz"));
      }
    }
  }
}
 
Example 8
Source File: FileGetter.java    From STGUploader with MIT License 6 votes vote down vote up
public static void migrateFiles(){
    File oldDir = new File(Environment.getExternalStorageDirectory(), "STG");
    if(oldDir.exists()) {
        File[] files = oldDir.listFiles();
        for(File file : files) {
            File newFile = getFile(file.getName());
            try {
                Files.move(file, newFile);
            } catch (IOException e) {
                e.printStackTrace();
                Logger.error(e.toString());
            }
        }
        oldDir.delete();
    }
}
 
Example 9
Source File: InputFile.java    From kafka-connect-spooldir with Apache License 2.0 5 votes vote down vote up
public void moveToDirectory(File outputDirectory) {
  File outputFile = new File(outputDirectory, this.inputFile.getName());
  try {
    if (this.inputFile.exists()) {
      log.info("Moving {} to {}", this.inputFile, outputFile);
      Files.move(this.inputFile, outputFile);
    }
  } catch (IOException e) {
    log.error("Exception thrown while trying to move {} to {}", this.inputFile, outputFile, e);
  }
}
 
Example 10
Source File: SimpleMetaDataManager.java    From science-journal with Apache License 2.0 5 votes vote down vote up
@Override
public void moveAllExperimentsToAnotherAccount(AppAccount targetAccount) throws IOException {
  // This method should not be called if canMoveAllExperimentsToAnotherAccount returns false.
  if (!canMoveAllExperimentsToAnotherAccount(targetAccount)) {
    throw new IllegalStateException("moveAllExperimentsToAnotherAccount now allowed now");
  }

  getFileMetadataManager().beforeMovingAllExperimentsToAnotherAccount();

  // Move experiment root directory.
  File sourceExperimentsRoot =
      FileMetadataUtil.getInstance().getExperimentsRootDirectory(appAccount);
  File targetExperimentsRoot =
      FileMetadataUtil.getInstance().getExperimentsRootDirectory(targetAccount);
  Files.move(sourceExperimentsRoot, targetExperimentsRoot);

  // Move user_metadata.proto.
  File sourceUserMetadataFile = FileMetadataUtil.getInstance().getUserMetadataFile(appAccount);
  File targetUserMetadataFile = FileMetadataUtil.getInstance().getUserMetadataFile(targetAccount);
  Files.move(sourceUserMetadataFile, targetUserMetadataFile);

  // Move experiment and sensor databases.
  ImmutableList<String> filesToMove =
      ImmutableList.of("main.db", "main.db-journal", "sensors.db", "sensors.db-journal");
  String[] sourceNames = context.databaseList();
  for (String sourceName : sourceNames) {
    if (filesToMove.contains(sourceName)) {
      File sourceFile = context.getDatabasePath(sourceName);
      String targetName = targetAccount.getDatabaseFileName(sourceName);
      File targetFile = new File(sourceFile.getParentFile(), targetName);
      Files.move(sourceFile, targetFile);
    }
  }
}
 
Example 11
Source File: DropXliffImportCommandTest.java    From mojito with Apache License 2.0 5 votes vote down vote up
void removeDateFromXliffNames() throws IOException {
    Collection<File> files = FileUtils.listFiles(getTargetTestDir(), null, true);
    for (File file : files) {
        String newName = file.getName().replaceAll("_.*.xliff", "_.xliff");
        Files.move(file, file.toPath().resolveSibling(newName).toFile());
    }
}
 
Example 12
Source File: WorkspaceEventHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDiscardStaleWorkingCopies() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	IFolder src = javaProject.getProject().getFolder("src");
	IPackageFragmentRoot srcRoot = javaProject.getPackageFragmentRoot(src);
	IPackageFragment mypack = srcRoot.createPackageFragment("mypack", true, null);
	// @formatter:off
	String contents = "package mypack;\n" +
					"public class Foo {" +
					"}\n";
	// @formatter:on
	ICompilationUnit unit = mypack.createCompilationUnit("Foo.java", contents, true, null);
	openDocument(unit, contents, 1);
	assertTrue(unit.isWorkingCopy());

	String oldUri = JDTUtils.getFileURI(srcRoot.getResource());
	String parentUri = JDTUtils.getFileURI(src);
	String newUri = oldUri.replace("mypack", "mynewpack");
	File oldPack = mypack.getResource().getLocation().toFile();
	File newPack = new File(oldPack.getParent(), "mynewpack");
	Files.move(oldPack, newPack);
	assertTrue(unit.isWorkingCopy());
	DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams(Arrays.asList(
		new FileEvent(newUri, FileChangeType.Created),
		new FileEvent(parentUri, FileChangeType.Changed),
		new FileEvent(oldUri, FileChangeType.Deleted)
	));
	new WorkspaceEventsHandler(projectsManager, javaClient, lifeCycleHandler).didChangeWatchedFiles(params);
	assertFalse(unit.isWorkingCopy());
}
 
Example 13
Source File: DatasetFileConverter.java    From mmtf-spark with Apache License 2.0 5 votes vote down vote up
private static void moveToSingleFile(String dirname, String filename) throws IOException {
    File part = getPartsFile(dirname);
    if (part != null) {
        File singleFile = new File(filename);
        Files.move(part, singleFile);
        FileUtils.deleteDirectory(new File(dirname));
    }
}
 
Example 14
Source File: LegacyDynamicSpawnStrategy.java    From bazel with Apache License 2.0 5 votes vote down vote up
private void moveFileOutErr(ActionExecutionContext actionExecutionContext, FileOutErr outErr)
    throws IOException {
  if (outErr.getOutputPath().exists()) {
    Files.move(
        outErr.getOutputPath().getPathFile(),
        actionExecutionContext.getFileOutErr().getOutputPath().getPathFile());
  }
  if (outErr.getErrorPath().exists()) {
    Files.move(
        outErr.getErrorPath().getPathFile(),
        actionExecutionContext.getFileOutErr().getErrorPath().getPathFile());
  }
}
 
Example 15
Source File: FSDagStateStore.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public synchronized void writeCheckpoint(Dag<JobExecutionPlan> dag) throws IOException {
  // write to a temporary name then rename to make the operation atomic when the file system allows a file to be
  // replaced
  String fileName = DagManagerUtils.generateDagId(dag) + DAG_FILE_EXTENSION;
  String serializedDag = serializeDag(dag);

  File tmpCheckpointFile = new File(this.dagCheckpointDir, fileName + ".tmp");
  File checkpointFile = new File(this.dagCheckpointDir, fileName);

  Files.write(serializedDag, tmpCheckpointFile, Charsets.UTF_8);
  Files.move(tmpCheckpointFile, checkpointFile);
}
 
Example 16
Source File: GitMonitoringService.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Write the last processed commit githash to the checkpoint file
 * @param gitHash
 * @throws IOException
 */
private void writeCheckpoint(String gitHash) throws IOException {
  // write to a temporary name then rename to make the operation atomic when the file system allows a file to be
  // replaced
  File tmpCheckpointFile = new File(this.repoDir, CHECKPOINT_FILE_TMP);
  File checkpointFile = new File(this.repoDir, CHECKPOINT_FILE);

  Files.write(gitHash, tmpCheckpointFile, Charsets.UTF_8);

  Files.move(tmpCheckpointFile, checkpointFile);
}
 
Example 17
Source File: Move.java    From PeerWasp with MIT License 5 votes vote down vote up
private void moveFileOrFolder(Path srcFile, Path dstFile, boolean wait) throws IOException {
	System.out.println("Move " + srcFile + " to " + dstFile);
	Files.move(srcFile.toFile(), dstFile.toFile());
	if(wait){
		waitForExists(dstFile, WAIT_TIME_LONG);
	}
}
 
Example 18
Source File: FileProcessorImpl.java    From accelerator-initializer with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void moveFile(File from, File to) {
    try {
        Files.move(from, to);
    } catch (IOException e) {
        throw new InitializerException("It was not possible to move file from {} to {}",e, from, to);
    }
}
 
Example 19
Source File: Move.java    From PeerWasp with MIT License 5 votes vote down vote up
@Test
public void localUpdateOnLocalMoveTest() throws IOException{
	Path folder = addFolder();
	Path srcFile = addFile();
	Path dstFile = folder.resolve(srcFile.getFileName());
	Files.move(srcFile.toFile(), dstFile.toFile());
	sleepMillis(config.getAggregationIntervalInMillis() / 2);
	updateSingleFile(dstFile, true);
	assertCleanedUpState(2);
}
 
Example 20
Source File: FetchingCacheServiceImpl.java    From genie with Apache License 2.0 4 votes vote down vote up
private void lookupOrDownload(
    final URI sourceFileUri,
    final File destinationFile
) throws DownloadException, IOException {

    final String uriString = sourceFileUri.toASCIIString();

    log.debug("Lookup: {}", uriString);

    // Unique id to store the resource on local disk
    final String resourceCacheId = getResourceCacheId(sourceFileUri);

    // Get a handle to the resource
    final Resource resource;
    try {
        resource = resourceLoader.getResource(uriString);
    } catch (Throwable t) {
        log.error(
            "Failed to retrieve resource: {}, {} - {}",
            uriString,
            t.getClass().getSimpleName(),
            t.getMessage()
        );
        throw t;
    }

    if (!resource.exists()) {
        throw new DownloadException("Resource not found: " + uriString);
    }

    final long resourceLastModified = resource.lastModified();

    //Handle to resourceCacheId/version
    final File cacheResourceVersionDir = getCacheResourceVersionDir(
        resourceCacheId,
        resourceLastModified
    );

    //Create the resource version dir in cache if it does not exist
    createDirectoryStructureIfNotExists(cacheResourceVersionDir);

    try (
        CloseableLock lock = fileLockFactory.getLock(
            touchCacheResourceVersionLockFile(
                resourceCacheId,
                resourceLastModified
            )
        )
    ) {
        //Critical section begin
        lock.lock();

        //Handle to the resource cached locally
        final File cachedResourceVersionDataFile = getCacheResourceVersionDataFile(
            resourceCacheId,
            resourceLastModified
        );

        if (!cachedResourceVersionDataFile.exists()) {
            log.debug(
                "Cache miss: {} (id: {})",
                uriString,
                resourceCacheId
            );

            // Download the resource into the download file in cache
            // resourceCacheId/version/data.tmp
            final File cachedResourceVersionDownloadFile = getCacheResourceVersionDownloadFile(
                resourceCacheId,
                resourceLastModified
            );
            try (
                InputStream in = resource.getInputStream();
                OutputStream out = new FileOutputStream(cachedResourceVersionDownloadFile)
            ) {
                FileCopyUtils.copy(in, out);
                Files.move(cachedResourceVersionDownloadFile, cachedResourceVersionDataFile);
            }
        } else {
            log.debug(
                "Cache hit: {} (id: {})",
                uriString,
                resourceCacheId
            );
        }

        //Copy from cache data file resourceCacheId/version/DATA_FILE_NAME to targetFile
        Files.copy(cachedResourceVersionDataFile, destinationFile);
        //Critical section end
    } catch (LockException e) {
        throw new DownloadException("Error downloading dependency", e);
    }

    //Clean up any older versions
    cleanUpTaskExecutor.execute(
        new CleanupOlderVersionsTask(resourceCacheId, resourceLastModified)
    );
}