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

The following examples show how to use com.google.common.io.Files#copy() . 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: EventQueueBackingStoreFactory.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
private static EventQueueBackingStore upgrade(File checkpointFile,
  int capacity, String name, File backupCheckpointDir,
  boolean shouldBackup)
        throws Exception {
  LOG.info("Attempting upgrade of " + checkpointFile + " for " + name);
  EventQueueBackingStoreFileV2 backingStoreV2 =
      new EventQueueBackingStoreFileV2(checkpointFile, capacity, name);
  String backupName = checkpointFile.getName() + "-backup-"
      + System.currentTimeMillis();
  Files.copy(checkpointFile,
      new File(checkpointFile.getParentFile(), backupName));
  File metaDataFile = Serialization.getMetaDataFile(checkpointFile);
  EventQueueBackingStoreFileV3.upgrade(backingStoreV2, checkpointFile,
      metaDataFile);
  return new EventQueueBackingStoreFileV3(checkpointFile, capacity, name,
    backupCheckpointDir, shouldBackup);
}
 
Example 2
Source File: DistributedFilesPersistenceHandlerTest.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@BeforeInjecting
public void setUpClasses() throws IOException {
    given(settings.getProperty(LimboSettings.DISTRIBUTION_SIZE)).willReturn(SegmentSize.SIXTEEN);
    dataFolder = temporaryFolder.newFolder();
    playerDataFolder = new File(dataFolder, "playerdata");
    playerDataFolder.mkdir();

    File limboFilesFolder = new File(TEST_RESOURCES_FOLDER + PROJECT_ROOT + "data/limbo");
    for (File file : limboFilesFolder.listFiles()) {
        File from = new File(playerDataFolder, file.getName());
        Files.copy(file, from);
    }

    given(bukkitService.getWorld(anyString()))
        .willAnswer(invocation -> {
            World world = mock(World.class);
            given(world.getName()).willReturn(invocation.getArgument(0));
            return world;
        });
}
 
Example 3
Source File: TestLog4jAppenderWithAvro.java    From kite with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  URL schemaUrl = getClass().getClassLoader().getResource("myrecord.avsc");
  Files.copy(Resources.newInputStreamSupplier(schemaUrl),
      new File("/tmp/myrecord.avsc"));

  int port = 25430;
  source = new AvroSource();
  ch = new MemoryChannel();
  Configurables.configure(ch, new Context());

  Context context = new Context();
  context.put("port", String.valueOf(port));
  context.put("bind", "localhost");
  Configurables.configure(source, context);

  List<Channel> channels = new ArrayList<Channel>();
  channels.add(ch);

  ChannelSelector rcs = new ReplicatingChannelSelector();
  rcs.setChannels(channels);

  source.setChannelProcessor(new ChannelProcessor(rcs));

  source.start();
}
 
Example 4
Source File: MigraterYamlFileResourceTest.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldWriteWithCorrectCharset() throws IOException {
    // given
    File file = temporaryFolder.newFile();
    Files.copy(TestHelper.getJarFile(CHINESE_MESSAGES_FILE), file);
    MigraterYamlFileResource resource = new MigraterYamlFileResource(file);
    ConfigurationData configurationData = buildConfigurationData();
    configurationData.initializeValues(resource.createReader());
    String newMessage = "您当前并没有任何邮箱与该账号绑定";
    configurationData.setValue(new StringProperty("third", ""), newMessage);

    // when
    resource.exportProperties(configurationData);

    // then
    PropertyReader reader = resource.createReader();
    assertThat(reader.getString("first"), equalTo("错误的密码"));
    assertThat(reader.getString("second"), equalTo("为了验证您的身份,您需要将一个电子邮件地址与您的帐户绑定!"));
    assertThat(reader.getString("third"), equalTo(newMessage));
}
 
Example 5
Source File: ChronicleMap3_12IntegerKeyCompatibilityTest.java    From Chronicle-Map with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoChecksums() throws Exception {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    URL fileUrl = cl.getResource("chronicle-map-3-12-no-checksums.dat");
    File file = new File(fileUrl.toURI());
    File persistenceFile = Builder.getPersistenceFile();
    Files.copy(file, persistenceFile);
    try (ChronicleMap<Integer, String> map = ChronicleMap.of(Integer.class, String.class)
            .averageValue("1")
            .entries(1)
            .checksumEntries(false)
            .recoverPersistedTo(persistenceFile, false)) {
        assertEquals(2, map.size());
        assertEquals("1", map.get(1));
        assertEquals("-1", map.get(-1));
    }
}
 
Example 6
Source File: OrganizationRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Resource getTmpEMFResource(String fileName, final File originalFile) throws IOException {
        fileName = fileName.replaceAll(".xml", ".organization");
    final File tmpFile = File.createTempFile("tmp", fileName, ProjectUtil.getBonitaStudioWorkFolder());
    Files.copy(originalFile, tmpFile);
    return new OrganizationResourceFactoryImpl().createResource(URI.createFileURI(tmpFile.getAbsolutePath()));
}
 
Example 7
Source File: MergeJavaResourcesTask.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private static void copy(@NonNull File inputFile,
                         @NonNull File outputDir,
                         @NonNull String archivePath) throws IOException {

    File outputFile = new File(outputDir, archivePath);
    createParentFolderIfNecessary(outputFile);
    Files.copy(inputFile, outputFile);
}
 
Example 8
Source File: FileUtil.java    From redis-manager with Apache License 2.0 5 votes vote down vote up
public static void copyFile(String source, String dest) throws Exception {
	if (StringUtils.isBlank(source) || StringUtils.isBlank(dest)) {
		throw new Exception("source or dest must not blank.");
	}
	File sourceFile = new File(source);
	File destFile = new File(dest);
	if (!destFile.exists()) {
		destFile.getParentFile().mkdirs();
	}
	Files.copy(sourceFile, destFile);
}
 
Example 9
Source File: FindAndRemoveTests.java    From jsondb-core with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  dbFilesFolder.mkdir();
  Files.copy(new File("src/test/resources/dbfiles/instances.json"), instancesJson);
  ICipher cipher = new DefaultAESCBCCipher("1r8+24pibarAWgS85/Heeg==");
  jsonDBTemplate = new JsonDBTemplate(dbFilesLocation, "io.jsondb.tests.model", cipher);
}
 
Example 10
Source File: HelpTranslationGeneratorIntegrationTest.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
@BeforeInjecting
public void setUpClasses() throws IOException {
    dataFolder = temporaryFolder.newFolder();
    File messagesFolder = new File(dataFolder, "messages");
    messagesFolder.mkdir();
    helpMessagesFile = new File(messagesFolder, "help_test.yml");
    Files.copy(TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "message/help_test.yml"), helpMessagesFile);
    given(settings.getProperty(PluginSettings.MESSAGES_LANGUAGE)).willReturn("test");
}
 
Example 11
Source File: InsertTests.java    From jsondb-core with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  dbFilesFolder.mkdir();
  Files.copy(new File("src/test/resources/dbfiles/instances.json"), instancesJson);
  ICipher cipher = new DefaultAESCBCCipher("1r8+24pibarAWgS85/Heeg==");
  jsonDBTemplate = new JsonDBTemplate(dbFilesLocation, "io.jsondb.tests.model", cipher);
}
 
Example 12
Source File: YamlFile.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Copy this configuration file to another file, without deleting configuration file.
 * @param file destination file (mustn't be a directory)
 * @return the new copied file
 * @throws FileNotFoundException if configuration file is not found as source to copy
 * @throws IllegalArgumentException if path is a directory or it is null
 * @throws IOException if there I/O error occurs copying file
 */
public void copyTo(File file) throws FileNotFoundException, IllegalArgumentException, IOException {
    Validate.notNull(configFile, "This configuration file is null!");
    if (!configFile.exists())
        throw new FileNotFoundException(configFile.getName() + " is not found in " + configFile.getAbsolutePath());
    else {
        if (!file.isDirectory())
            Files.copy(configFile, file);
        else
            throw new IllegalArgumentException(file.getAbsolutePath() + " is a directory!");
    }
}
 
Example 13
Source File: ReconstructionEvaluator.java    From myrrix-recommender with Apache License 2.0 5 votes vote down vote up
private static Multimap<Long,RecommendedItem> readAndCopyDataFiles(File dataDir, File tempDir) throws IOException {
  Multimap<Long,RecommendedItem> data = ArrayListMultimap.create();
  for (File dataFile : dataDir.listFiles(new PatternFilenameFilter(".+\\.csv(\\.(zip|gz))?"))) {
    log.info("Reading {}", dataFile);
    int count = 0;
    for (CharSequence line : new FileLineIterable(dataFile)) {
      Iterator<String> parts = COMMA_TAB_SPLIT.split(line).iterator();
      long userID = Long.parseLong(parts.next());
      long itemID = Long.parseLong(parts.next());
      if (parts.hasNext()) {
        String token = parts.next().trim();
        if (!token.isEmpty()) {
          data.put(userID, new GenericRecommendedItem(itemID, LangUtils.parseFloat(token)));
        }
        // Ignore remove lines
      } else {
        data.put(userID, new GenericRecommendedItem(itemID, 1.0f));
      }
      if (++count % 1000000 == 0) {
        log.info("Finished {} lines", count);
      }
    }

    Files.copy(dataFile, new File(tempDir, dataFile.getName()));
  }
  return data;
}
 
Example 14
Source File: StoreLoadTest.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testSave() throws IOException
{
	try (Store store = new Store(StoreLocation.LOCATION))
	{
		store.load();

		File testStoreFile = folder.newFolder();
		for (File f : StoreLocation.LOCATION.listFiles())
		{
			Files.copy(f, new File(testStoreFile, f.getName()));
		}

		try (Store testStore = new Store(testStoreFile))
		{
			testStore.load();

			Assert.assertTrue(store.equals(testStore));

			testStore.save();
		}

		try (Store testStore = new Store(testStoreFile))
		{
			testStore.load();

			Assert.assertTrue(store.equals(testStore));
		}
	}
}
 
Example 15
Source File: SaveTests.java    From jsondb-core with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  dbFilesFolder.mkdir();
  Files.copy(new File("src/test/resources/dbfiles/instances.json"), instancesJson);
  ICipher cipher = new DefaultAESCBCCipher("1r8+24pibarAWgS85/Heeg==");
  jsonDBTemplate = new JsonDBTemplate(dbFilesLocation, "io.jsondb.tests.model", cipher);
}
 
Example 16
Source File: Compiler.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
private void ensureLib(String tempdir, String name, String resource) {
  try {
    File outFile = new File(tempdir, name);
    if (outFile.exists()) {
      return;
    }
    File tmpLibDir = new File(tempdir);
    tmpLibDir.mkdirs();
    Files.copy(Resources.newInputStreamSupplier(Compiler.class.getResource(resource)), outFile);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 17
Source File: AbstractEvaluator.java    From myrrix-recommender with Apache License 2.0 4 votes vote down vote up
@Override
public final EvaluationResult evaluate(File originalDataDir,
                                       double trainingPercentage,
                                       double evaluationPercentage,
                                       RescorerProvider provider) 
    throws TasteException, IOException, InterruptedException {

  Preconditions.checkArgument(trainingPercentage > 0.0 && trainingPercentage < 1.0,
                              "Training % must be in (0,1): %s", trainingPercentage);
  Preconditions.checkArgument(evaluationPercentage > 0.0 && evaluationPercentage <= 1.0,
                              "Eval % must be in (0,1): %s", evaluationPercentage);
  Preconditions.checkArgument(originalDataDir.exists() && originalDataDir.isDirectory(),
                              "%s is not a directory", originalDataDir);

  File trainingDataDir = Files.createTempDir();
  trainingDataDir.deleteOnExit();
  File trainingFile = new File(trainingDataDir, "training.csv.gz");
  trainingFile.deleteOnExit();
  
  // If the test has a model, copy it to use as a starting point as part of the test
  File trainingModelFile = new File(originalDataDir, "model.bin.gz");
  if (trainingModelFile.exists() && trainingModelFile.isFile()) {
    Files.copy(trainingModelFile, new File(trainingDataDir, trainingModelFile.getName()));
  }

  ServerRecommender recommender = null;
  try {
    Multimap<Long,RecommendedItem> testData =
        split(originalDataDir, trainingFile, trainingPercentage, evaluationPercentage, provider);

    recommender = new ServerRecommender(trainingDataDir);
    recommender.await();

    return evaluate(recommender, testData);
  } finally {
    if (recommender != null) {
      recommender.close();
    }
    IOUtils.deleteRecursively(trainingDataDir);
  }
}
 
Example 18
Source File: PdfStandaardConvertor.java    From iaf with Apache License 2.0 4 votes vote down vote up
@Override
public void convert(MediaType mediaType, File file, CisConversionResult result, ConversionOption conversionOption)
		throws Exception {
	Files.copy(file, result.getPdfResultFile());
	result.setNumberOfPages(getNumberOfPages(result.getPdfResultFile()));
}
 
Example 19
Source File: FileUtils.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
private static void copyFile(File source, File destination) throws IOException {
    Files.copy(source, destination);
}
 
Example 20
Source File: CollectionMetaDataTests.java    From jsondb-core with MIT License 4 votes vote down vote up
@Before
public void setUp() throws Exception {
  dbFilesFolder.mkdir();
  Files.copy(new File("src/test/resources/dbfiles/instances.json"), instancesJson);
  cipher = new DefaultAESCBCCipher("1r8+24pibarAWgS85/Heeg==");
}