Java Code Examples for org.apache.commons.io.FileUtils.touch()

The following are Jave code examples for showing how to use touch() of the org.apache.commons.io.FileUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: trivor-nlp   File: SentimentTraining.java   View Source Code Vote up 7 votes
public void train() {
    try {
        InputStreamFactory modelStream = new MarkableFileInputStreamFactory(
                new File(getClass().getClassLoader().getResource(TRAIN_INPUT).getFile())
        );
        final ObjectStream<String> lineStream = new PlainTextByLineStream(modelStream, "UTF-8");
        final ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);

        final TrainingParameters mlParams = new TrainingParameters();
        mlParams.put(TrainingParameters.ITERATIONS_PARAM, 5000);
        mlParams.put(TrainingParameters.CUTOFF_PARAM, 5);

        final DoccatModel model = DocumentCategorizerME.train("en", sampleStream, mlParams, new DoccatFactory());
        final Path path = Paths.get(MODEL_OUTPUT);
        FileUtils.touch(path.toFile());
        try (OutputStream modelOut = new BufferedOutputStream(new FileOutputStream(path.toString()))) {
            model.serialize(modelOut);
        }
    } catch (Exception e) {
        LOGGER.error("an error occurred while training the sentiment analysis model", e);
        throw new IllegalStateException(e);
    }
}
 
Example 2
Project: Reer   File: TestFile.java   View Source Code Vote up 6 votes
public TestFile touch() {
    try {
        FileUtils.touch(this);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    assertIsFile();
    return this;
}
 
Example 3
Project: Reer   File: GFileUtils.java   View Source Code Vote up 6 votes
public static void touch(File file) {
    try {
        FileUtils.touch(file);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 4
Project: odoxSync   File: FileProcessorBatchTest.java   View Source Code Vote up 6 votes
@Test
public void batch_should_skip_on_second_scan() throws IOException {
    long fileSize = ((Contants.REGION_SIZE * SlowFileProcessor.BATCH_SIZE) * 2) + 1;
    String workingDirectory = "/home/gaganis/IdeaProjects/DirectorySynchronizer/testdata/source";
    String fileName = "ubuntu-16.04.1-desktop-amd64.iso";
    File file = new File(fileName);
    updateAbsolutePath(file, workingDirectory, fileName);

    FileProcessor fileProcessor = getFileProcessor(fileSize, workingDirectory, file);
    BatchArea batchArea = fileProcessor.nextBatchArea();
    assertThat(batchArea.isSkip).isFalse();

    fileProcessor.doBeforeBatchByteRead();
    fileProcessor.process(
            new byte[(int) (Contants.REGION_SIZE * SlowFileProcessor.BATCH_SIZE)],
            batchArea);
    fileProcessor = getFileProcessor(fileSize, workingDirectory, file);
    batchArea = fileProcessor.nextBatchArea();
    assertThat(batchArea.isSkip).isTrue();
    FileUtils.touch(file.getAbsolutePath().toFile());

}
 
Example 5
Project: devops-cm-client   File: UploadFileToTransportTest.java   View Source Code Vote up 6 votes
@Test
public void testUploadFileStraightForward() throws Exception {

    setMock(setupMock());

    String fileName = UUID.randomUUID().toString() + ".txt";
    File upload = tmp.newFile(fileName);
    FileUtils.touch(upload);

    UploadFileToTransport.main(new String[] {
    "-u", SERVICE_USER,
    "-p", SERVICE_PASSWORD,
    "-e", SERVICE_ENDPOINT,
    "dummy-cmd",
    "8000042445", "L21K90002J", "HCP", upload.getAbsolutePath()
    });

    assertThat(changeId.getValue(), is(equalTo("8000042445")));
    assertThat(transportId.getValue(), is(equalTo("L21K90002J")));
    assertThat(filePath.getValue(), endsWith(fileName));
    assertThat(applicationId.getValue(), is(equalTo("HCP")));
}
 
Example 6
Project: invesdwin-context-r   File: ModifiedTempFileService.java   View Source Code Vote up 5 votes
@Override
public File createTempFile(final String prefix, final String suffix) throws IOException {
    final File file = new File(folder, fileUniqueNameGenerator.get(prefix) + suffix);
    FileUtils.touch(file);
    tempFiles.add(file);
    return file;
}
 
Example 7
Project: odoxSync   File: FileProcessorBatchTest.java   View Source Code Vote up 5 votes
public static void testTouchSkip(File file, Supplier<FileProcessor> fileProcessorSupplier, long byteArraySize) throws IOException, InterruptedException {
    FileProcessor fileProcessor = fileProcessorSupplier.get();

    fileProcessor.doBeforeFileRead(null);
    BatchArea batchArea = fileProcessor.nextBatchArea();
    assertThat(batchArea.isSkip).isFalse();

    fileProcessor.doBeforeBatchByteRead();
    fileProcessor.process(
            new byte[(int) byteArraySize],
            batchArea);

    //2nd pass
    fileProcessor = fileProcessorSupplier.get();
    fileProcessor.doBeforeFileRead(null);
    batchArea = fileProcessor.nextBatchArea();
    assertThat(batchArea.isSkip).isTrue();

    Thread.sleep(1000);//The 1 second precision of touch makes the test flaky, hence the sleep to make the touch roll to the next second
    FileUtils.touch(file.getAbsolutePath().toFile());

    //3rd pass
    fileProcessor = fileProcessorSupplier.get();
    fileProcessor.doBeforeFileRead(null);
    batchArea = fileProcessor.nextBatchArea();
    assertThat(batchArea.isSkip).isFalse();
}
 
Example 8
Project: airsonic   File: PlaylistServiceTestImport.java   View Source Code Vote up 5 votes
@Test
public void testImportFromM3U() throws Exception {
    String username = "testUser";
    String playlistName = "test-playlist";
    StringBuilder builder = new StringBuilder();
    builder.append("#EXTM3U\n");
    File mf1 = folder.newFile();
    FileUtils.touch(mf1);
    File mf2 = folder.newFile();
    FileUtils.touch(mf2);
    File mf3 = folder.newFile();
    FileUtils.touch(mf3);
    builder.append(mf1.getAbsolutePath() + "\n");
    builder.append(mf2.getAbsolutePath() + "\n");
    builder.append(mf3.getAbsolutePath() + "\n");
    doAnswer(new PersistPlayList(23)).when(playlistDao).createPlaylist(any());
    doAnswer(new MediaFileHasEverything()).when(mediaFileService).getMediaFile(any(File.class));
    InputStream inputStream = new ByteArrayInputStream(builder.toString().getBytes("UTF-8"));
    String path = "/path/to/"+playlistName+".m3u";
    playlistService.importPlaylist(username, playlistName, path, inputStream, null);
    verify(playlistDao).createPlaylist(actual.capture());
    verify(playlistDao).setFilesInPlaylist(eq(23), medias.capture());
    Playlist expected = new Playlist();
    expected.setUsername(username);
    expected.setName(playlistName);
    expected.setComment("Auto-imported from " + path);
    expected.setImportedFrom(path);
    expected.setShared(true);
    expected.setId(23);
    assertTrue("\n" + ToStringBuilder.reflectionToString(actual.getValue()) + "\n\n did not equal \n\n" + ToStringBuilder.reflectionToString(expected), EqualsBuilder.reflectionEquals(actual.getValue(), expected, "created", "changed"));
    List<MediaFile> mediaFiles = medias.getValue();
    assertEquals(3, mediaFiles.size());
}
 
Example 9
Project: airsonic   File: PlaylistServiceTestImport.java   View Source Code Vote up 5 votes
@Test
public void testImportFromPLS() throws Exception {
    String username = "testUser";
    String playlistName = "test-playlist";
    StringBuilder builder = new StringBuilder();
    builder.append("[playlist]\n");
    File mf1 = folder.newFile();
    FileUtils.touch(mf1);
    File mf2 = folder.newFile();
    FileUtils.touch(mf2);
    File mf3 = folder.newFile();
    FileUtils.touch(mf3);
    builder.append("File1=" + mf1.getAbsolutePath() + "\n");
    builder.append("File2=" + mf2.getAbsolutePath() + "\n");
    builder.append("File3=" + mf3.getAbsolutePath() + "\n");
    doAnswer(new PersistPlayList(23)).when(playlistDao).createPlaylist(any());
    doAnswer(new MediaFileHasEverything()).when(mediaFileService).getMediaFile(any(File.class));
    InputStream inputStream = new ByteArrayInputStream(builder.toString().getBytes("UTF-8"));
    String path = "/path/to/"+playlistName+".pls";
    playlistService.importPlaylist(username, playlistName, path, inputStream, null);
    verify(playlistDao).createPlaylist(actual.capture());
    verify(playlistDao).setFilesInPlaylist(eq(23), medias.capture());
    Playlist expected = new Playlist();
    expected.setUsername(username);
    expected.setName(playlistName);
    expected.setComment("Auto-imported from " + path);
    expected.setImportedFrom(path);
    expected.setShared(true);
    expected.setId(23);
    assertTrue("\n" + ToStringBuilder.reflectionToString(actual.getValue()) + "\n\n did not equal \n\n" + ToStringBuilder.reflectionToString(expected), EqualsBuilder.reflectionEquals(actual.getValue(), expected, "created", "changed"));
    List<MediaFile> mediaFiles = medias.getValue();
    assertEquals(3, mediaFiles.size());
}
 
Example 10
Project: airsonic   File: PlaylistServiceTestImport.java   View Source Code Vote up 5 votes
@Test
public void testImportFromXSPF() throws Exception {
    String username = "testUser";
    String playlistName = "test-playlist";
    StringBuilder builder = new StringBuilder();
    builder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                   + "<playlist version=\"1\" xmlns=\"http://xspf.org/ns/0/\">\n"
                   + "    <trackList>\n");
    File mf1 = folder.newFile();
    FileUtils.touch(mf1);
    File mf2 = folder.newFile();
    FileUtils.touch(mf2);
    File mf3 = folder.newFile();
    FileUtils.touch(mf3);
    builder.append("<track><location>file://" + mf1.getAbsolutePath() + "</location></track>\n");
    builder.append("<track><location>file://" + mf2.getAbsolutePath() + "</location></track>\n");
    builder.append("<track><location>file://" + mf3.getAbsolutePath() + "</location></track>\n");
    builder.append("    </trackList>\n" + "</playlist>\n");
    doAnswer(new PersistPlayList(23)).when(playlistDao).createPlaylist(any());
    doAnswer(new MediaFileHasEverything()).when(mediaFileService).getMediaFile(any(File.class));
    InputStream inputStream = new ByteArrayInputStream(builder.toString().getBytes("UTF-8"));
    String path = "/path/to/"+playlistName+".xspf";
    playlistService.importPlaylist(username, playlistName, path, inputStream, null);
    verify(playlistDao).createPlaylist(actual.capture());
    verify(playlistDao).setFilesInPlaylist(eq(23), medias.capture());
    Playlist expected = new Playlist();
    expected.setUsername(username);
    expected.setName(playlistName);
    expected.setComment("Auto-imported from " + path);
    expected.setImportedFrom(path);
    expected.setShared(true);
    expected.setId(23);
    assertTrue("\n" + ToStringBuilder.reflectionToString(actual.getValue()) + "\n\n did not equal \n\n" + ToStringBuilder.reflectionToString(expected), EqualsBuilder.reflectionEquals(actual.getValue(), expected, "created", "changed"));
    List<MediaFile> mediaFiles = medias.getValue();
    assertEquals(3, mediaFiles.size());
}
 
Example 11
Project: osc-core   File: ReleaseUpgradeMgr.java   View Source Code Vote up 5 votes
private static void createUpgradeMarkerFile() {
    try {
        FileUtils.touch(new File(DB_UPGRADE_IN_PROGRESS_MARKER_FILE));
    } catch (IOException e) {
        log.error("Fail to create upgrade in progress marker file");
    }
}
 
Example 12
Project: instalint   File: FileMetadataTest.java   View Source Code Vote up 5 votes
@Test
public void empty_file() throws Exception {
  File tempFile = temp.newFile();
  FileUtils.touch(tempFile);

  FileMetadata.Metadata metadata = new FileMetadata().readMetadata(tempFile, StandardCharsets.UTF_8);
  assertThat(metadata.lines).isEqualTo(1);
  assertThat(metadata.originalLineOffsets).containsOnly(0);
  assertThat(metadata.lastValidOffset).isEqualTo(0);
}
 
Example 13
Project: otter-G   File: FileLoadActionTest.java   View Source Code Vote up 5 votes
protected List<FileData> buildFileDatas(String namespace, EventType eventType, int start, int count, boolean create)
                                                                                                                    throws IOException {
    List<FileData> files = new ArrayList<FileData>();

    for (int i = start; i < count; i++) {
        FileData fileData = new FileData();
        fileData.setNameSpace(namespace); // namespace is null means file is
                                          // local file
        fileData.setEventType(eventType);
        fileData.setPairId(i % NUMBER_OF_FILE_DATA_COPIES);
        fileData.setPath(ROOT_DIR.getAbsolutePath() + "/target/" + eventType.getValue() + i);

        String parentPath = ROOT_DIR.getPath();
        if (namespace != null) {
            parentPath = parentPath + "/" + namespace;
        }
        File file = new File(parentPath, fileData.getPath());
        if (!file.exists() && create) {
            FileUtils.touch(file);
        }

        fileData.setSize(file.exists() ? file.length() : 0);
        fileData.setLastModifiedTime(file.exists() ? file.lastModified() : Calendar.getInstance().getTimeInMillis());
        fileData.setTableId(TABLE_ID);

        files.add(fileData);
    }

    return files;
}
 
Example 14
Project: tkcg   File: Generator.java   View Source Code Vote up 5 votes
/**
 * 处理模板生成.
 *
 * @param model model
 * @param files files
 * @param templateDirectory templateDirectoryFile
 * @throws IOException io exception
 */
private void processTemplate(FreemarkerHelper templateHelper, Map<String, Object> model, List<File> files,
                             File templateDirectory) throws IOException {
    for (File file : files) {
        String fileName = file.getName();
        String targetName = templateHelper.processToString(model, fileName.replace(FREEMARKER_TEMPLATE_SUFFIX, ""));
        File targetFile = getTargetFile(templateHelper, model, templateDirectory, file, outDirectoryFile,
                                        targetName);
        FileUtils.touch(targetFile);
        String templateName = getRelativizeTemplateFile(templateDirectory, file).toPath().toString();
        templateHelper.processToFile(model, templateName, targetFile, "UTF-8");
    }
}
 
Example 15
Project: gdx-splash   File: LockFile.java   View Source Code Vote up 5 votes
public static void create() {
    try {
        FileUtils.touch(new File(Main.LOCK_FILE));
    } catch (Exception e) {
        e.printStackTrace();
        // TODO do smth
    }
}
 
Example 16
Project: dhus-core   File: FileSystemDataStoreTest.java   View Source Code Vote up 4 votes
@BeforeClass
public void init () throws IOException, 
   DataStoreLocalArchiveNotExistingException, InterruptedException
{
   tmp = Files.createTempDir();
   tmp.mkdirs ();
   HierarchicalDirectoryBuilder db = 
         new HierarchicalDirectoryBuilder (tmp, 100);
   int i=1000;
   while (i-->0) 
   {
      File root = db.getDirectory ();
      FileUtils.touch (new File(root, "toto.txt"));
      FileUtils.touch (new File(root,
         HierarchicalDirectoryBuilder.DHUS_ENTRY_NAME));
      new File(root, "directory").mkdirs ();
   }

   // Set info coming from system configuration
   max_no = cfgManager.getArchiveConfiguration().getIncomingConfiguration().getMaxFileNo();

   incoming_root = new File(cfgManager.getArchiveConfiguration().getIncomingConfiguration().getPath()).getAbsoluteFile();

   String[] folders_to_test_true =
   {
      incoming_root.getAbsolutePath() + "/X1",
      incoming_root.getAbsolutePath() + "/X2",
      incoming_root.getAbsolutePath() + "/X3",
      incoming_root.getAbsolutePath() + "/X4",
      incoming_root.getAbsolutePath() + "/X1/X1/X1/X1/X1/X1/X1/X1/X1",
      incoming_root.getAbsolutePath() + "/X1/X2/X3/X4/X5/X6/X7/X8/X9",
      incoming_root.getAbsolutePath() + "/X1/X1/X1/XAF/X1/X1/X1/X1/X1/",
      incoming_root.getAbsolutePath() + File.separator + Long.toHexString(max_no - 1).substring(1),
      incoming_root.getAbsolutePath() + "/X1/X1/X1/X1/X1/X1/" + HierarchicalDirectoryBuilder.DHUS_ENTRY_NAME,
      incoming_root.getAbsolutePath() + "/X1/X1/X1/X1/X1/X1/" + HierarchicalDirectoryBuilder.DHUS_ENTRY_NAME + File.separator + IncomingManager.INCOMING_PRODUCT_DIR,
   };
   
   String[] folders_to_test_false =
   {
      "/tmp/toto",
      incoming_root.getAbsolutePath () + "/my_data",
      incoming_root.getAbsolutePath () + "/X2/X23453/X2/" + HierarchicalDirectoryBuilder.DHUS_ENTRY_NAME,
      incoming_root.getAbsolutePath () + "/X3/" + HierarchicalDirectoryBuilder.DHUS_ENTRY_NAME + "/data",
      incoming_root.getAbsolutePath () + "/X1/X1/X1/X1/X1/X1/" + HierarchicalDirectoryBuilder.DHUS_ENTRY_NAME + File.separator + IncomingManager.INCOMING_PRODUCT_DIR + File.separator + "mydata",
      incoming_root.getAbsolutePath () + File.separator + max_no + "X1/X2/X3",
      incoming_root.getAbsolutePath () + "/X3/data",
      incoming_root.getAbsolutePath () + "/A4",
   };

   folders_to_test[0]=folders_to_test_true;
   folders_to_test[1]=folders_to_test_false;
   incomingPathChecker = new IncomingPathChecker ();

}
 
Example 17
Project: dcmrs-broker   File: CacheManager.java   View Source Code Vote up 4 votes
static void writeObject(Attributes obj, String txUid, String classUid)
		throws IOException
{
	String studyUid = obj.getString(Tag.StudyInstanceUID);
	String seriesUid = obj.getString(Tag.SeriesInstanceUID);
	String instanceUid = obj.getString(Tag.SOPInstanceUID);

	File dcmFile = buildFile(studyUid, seriesUid, instanceUid, "dcm");
	File tmpFile = buildFile(studyUid, seriesUid, instanceUid, "tmp");
	File errFile = buildFile(studyUid, seriesUid, instanceUid, "err");
	try {
		if (errFile.isFile()) {
			logger.info("Overwriting error file: {}", errFile);

			FileUtils.deleteQuietly(errFile);
		}

		FileUtils.touch(tmpFile); // Create parent directories if needed

		try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
			if (UID.ImplicitVRLittleEndian.equals(txUid)) {
				// DicomOutputStream throws exception when writing dataset with LEI
				txUid = UID.ExplicitVRLittleEndian;
			}
			else if (UID.ExplicitVRBigEndianRetired.equals(txUid)) {
				// Should never happen, but just in case
				txUid = UID.ExplicitVRLittleEndian;

				logger.info("Trancoding dataset from big to "
							+ "little endian for: {}", dcmFile);
			}


			Attributes fmi = Attributes.createFileMetaInformation(instanceUid,
																  classUid,
																  txUid);

			DicomOutputStream dos = new DicomOutputStream(fos, txUid);
			dos.writeDataset(fmi, obj);
			dos.close();
		}

		Files.move(tmpFile.toPath(),
				   dcmFile.toPath(),
				   StandardCopyOption.ATOMIC_MOVE,
				   StandardCopyOption.REPLACE_EXISTING);
	}
	catch (Exception ex) {
		logger.warn("Unable save DICOM object to: " + dcmFile, ex);

		FileUtils.touch(errFile);
		FileUtils.deleteQuietly(tmpFile);
		FileUtils.deleteQuietly(dcmFile);

		if (ex instanceof IOException) {
			throw (IOException) ex;
		}
		else {
			throw new IOException(ex);
		}
	}
}
 
Example 18
Project: Hydrograph   File: MultiParameterFileDialog.java   View Source Code Vote up 4 votes
private void createNewParamterFile(String file) throws IOException{
	FileUtils.touch(new File(file));
}