List of usage examples for java.io File setLastModified
public boolean setLastModified(long time)
From source file:org.alfresco.solr.AlfrescoCoreAdminHandler.java
/** * Note files can alter due to background processes so file not found is Ok * /*from www . j a v a2 s. c o m*/ * @param srcDir * @param destDir * @param preserveFileDate * @throws IOException */ static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate) throws IOException { if (destDir.exists()) { throw new IOException("Destination should be created from clean"); } else { if (!destDir.mkdirs()) { throw new IOException("Destination '" + destDir + "' directory cannot be created"); } if (preserveFileDate) { // OL if file not found so does not need to check destDir.setLastModified(srcDir.lastModified()); } } if (!destDir.canWrite()) { throw new IOException("No access to destination directory" + destDir); } File[] files = srcDir.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File currentCopyTarget = new File(destDir, files[i].getName()); if (files[i].isDirectory()) { copyDirectory(files[i], currentCopyTarget, preserveFileDate); } else { copyFile(files[i], currentCopyTarget, preserveFileDate); } } } }
From source file:com.linkedin.databus.core.TestDbusEventBufferPersistence.java
@Test public void testMetaFileTimeStamp() throws InvalidConfigException, IOException { int maxEventBufferSize = 1144; int maxIndividualBufferSize = 500; DbusEventBuffer dbusBuf = new DbusEventBuffer(getConfig(maxEventBufferSize, maxIndividualBufferSize, 100, 500, AllocationPolicy.MMAPPED_MEMORY, _mmapDirStr, true)); File metaFile = new File(_mmapDir, dbusBuf.metaFileName()); // after buffer is created - meta file should be removed Assert.assertFalse(metaFile.exists()); dbusBuf.saveBufferMetaInfo(false);/*from www .j ava 2 s . c o m*/ // new file should be created Assert.assertTrue(metaFile.exists()); DbusEventBufferMetaInfo mi = new DbusEventBufferMetaInfo(metaFile); mi.loadMetaInfo(); Assert.assertTrue(mi.isValid()); // now let's touch one of the mmap files File writeBufferFile = new File(new File(metaFile.getParent(), mi.getSessionId()), "writeBuffer_0"); long modTime = System.currentTimeMillis() + 1000; //Precision of the mod time is 1 sec writeBufferFile.setLastModified(modTime); LOG.debug("setting mod time for " + writeBufferFile + " to " + modTime + " now val = " + writeBufferFile.lastModified()); mi = new DbusEventBufferMetaInfo(metaFile); mi.loadMetaInfo(); Assert.assertTrue(mi.isValid()); //we don't invalidate the meta file based on mod time }
From source file:org.springframework.integration.ftp.outbound.FtpServerOutboundTests.java
private long setModifiedOnSource1() { File firstRemote = new File(getSourceRemoteDirectory(), " ftpSource1.txt"); firstRemote.setLastModified(System.currentTimeMillis() - 1_000_000); long modified = firstRemote.lastModified(); assertTrue(modified > 0);//from www .j a v a2s . c o m return modified; }
From source file:net.mybox.mybox.ServerClientConnection.java
private void handleInput(Common.Signal input) { Server.printMessage("(" + Common.now() + ") Client " + handle + ": " + input.toString()); if (input == Common.Signal.c2s) { try {/*from w w w. j ava2s. c o m*/ String fileName = ByteStream.toString(inStream); String fileTimeString = ByteStream.toString(inStream); // TODO: create underlying directory if the file needs it long fileTime = Long.valueOf(fileTimeString); System.out.println("getting file: " + fileName + " modtime " + fileTime); File file = new File(localDir + "/" + fileName); ByteStream.toFile(inStream, file); if (!file.setLastModified(fileTime)) { System.err.println("Unable to set file modification time"); System.exit(1); } server.spanCatchupOperation(handle, account.id, input, fileName); } catch (Exception e) { System.out.println(input.toString() + " operation failed: " + e.getMessage()); } } else if (input == Common.Signal.clientWantsToSend) { try { String fileName = ByteStream.toString(inStream); String fileTimeString = ByteStream.toString(inStream); long fileTime = Long.valueOf(fileTimeString); System.out.println("clientWantsToSend: " + fileName + " modtime " + fileTime); File file = new File(localDir + "/" + fileName); sendCommandToClient(Common.Signal.clientWantsToSend_response); ByteStream.toStream(outStream, fileName); // reply 'yes' if it refers to a file that does not exist or if the times do not match if (file.isFile() && file.lastModified() == fileTime) { ByteStream.toStream(outStream, "no"); } else { ByteStream.toStream(outStream, "yes"); } } catch (Exception e) { System.out.println(input.toString() + " operation failed: " + e.getMessage()); } } else if (input == Common.Signal.clientWants) { try { String fileName = ByteStream.toString(inStream); System.out.println("client requesting from server: " + fileName); File file = new File(localDir + "/" + fileName); if (file.exists()) { outQueue.push(new MyFile(fileName, 10, "file")); checkQueue(); } } catch (Exception e) { System.out.println(input.toString() + " operation failed: " + e.getMessage()); } } else if (input == Common.Signal.deleteOnServer) { // handles files and directories try { String fileName = ByteStream.toString(inStream); System.out.println("client requested deletion on server: " + fileName); File item = new File(localDir + "/" + fileName); if (item.isDirectory()) Common.deleteLocalDirectory(item); else if (item.exists()) // assume it is a file item.delete(); else System.out.println("unable to find item on server to delete"); server.spanCatchupOperation(handle, account.id, input, fileName); } catch (Exception e) { System.out.println(input.toString() + " operation failed: " + e.getMessage()); } } else if (input == Common.Signal.renameOnServer) { // handles files and directories try { String oldName = ByteStream.toString(inStream); String newName = ByteStream.toString(inStream); System.out.println("client requested rename on server: (" + oldName + ") to (" + newName + ")"); File oldFile = new File(localDir + "/" + oldName); File newFile = new File(localDir + "/" + newName); if (oldFile.exists()) { oldFile.renameTo(newFile); } server.spanCatchupOperation(handle, account.id, input, oldName + "->" + newName); } catch (Exception e) { System.out.println(input.toString() + " operation failed: " + e.getMessage()); } } else if (input == Common.Signal.createDirectoryOnServer) { try { String name = ByteStream.toString(inStream); System.out.println("client requesting create directory on server: " + name); Common.createLocalDirectory(localDir + "/" + name); // update database // preparedInsert = connection.prepareStatement("insert or ignore into archive values(?,?,?);"); // preparedInsert.setString(1, name); // preparedInsert.setString(2, "d"); // preparedInsert.setLong(3, (new Date()).getTime()); // preparedInsert.executeUpdate(); // TODO: check return number before continuing // connection.commit(); server.spanCatchupOperation(handle, account.id, input, name); } catch (Exception e) { System.out.println(input.toString() + " operation failed: " + e.getMessage()); System.exit(1); } } else if (input == Common.Signal.requestServerFileList) { sendServerFileList(); } else if (input == Common.Signal.attachaccount) { String args = null; try { args = ByteStream.toString(inStream); } catch (Exception e) { // } HashMap attachInput = Common.jsonDecode(args); String email = (String) attachInput.get("email"); // String password = (String)attachInput.get("password"); JSONObject jsonOut = new JSONObject(); jsonOut.put("serverMyboxVersion", Common.appVersion); if (attachAccount(email)) { jsonOut.put("status", "success"); jsonOut.put("quota", account.quota); jsonOut.put("salt", account.salt); server.updateMultiMap(account.id, handle); } else { jsonOut.put("status", "failed"); jsonOut.put("error", "invalid account"); } try { sendCommandToClient(Common.Signal.attachaccount_response); ByteStream.toStream(outStream, jsonOut.toJSONString()); } catch (Exception e) { // } Server.printMessage("attachaccount_response: " + jsonOut); } else { Server.printMessage("unknown command: " + input); failedRequestCount++; } }
From source file:de.uzk.hki.da.pkg.NativeJavaTarArchiveBuilder.java
public void unarchiveFolder(File srcTar, File destFolder) throws Exception { FileInputStream fin = new FileInputStream(srcTar); BufferedInputStream in = new BufferedInputStream(fin); TarArchiveInputStream tIn = new TarArchiveInputStream(in); HashMap<String, Long> modDateMap = new HashMap<String, Long>(); TarArchiveEntry entry;/* ww w . j a v a2 s . c o m*/ do { entry = tIn.getNextTarEntry(); if (entry == null) break; logger.debug(entry.getName()); String dstName = destFolder.getAbsolutePath() + "/" + entry.getName(); File entryFile = new File(dstName); if (entry.isDirectory()) { entryFile.mkdirs(); modDateMap.put(dstName, new Long(entry.getModTime().getTime())); } else { new File(entryFile.getAbsolutePath().substring(0, entryFile.getAbsolutePath().lastIndexOf('/'))) .mkdirs(); FileOutputStream out = new FileOutputStream(entryFile); IOUtils.copy(tIn, out); out.close(); entryFile.setLastModified(entry.getModTime().getTime()); } } while (true); tIn.close(); in.close(); fin.close(); for (Map.Entry<String, Long> moddi : modDateMap.entrySet()) { String key = moddi.getKey(); Long value = moddi.getValue(); (new File(key)).setLastModified(value); } }
From source file:com.funambol.server.cleanup.ClientLogCleanUpAgentTest.java
public void testInternalRun_ArchivationRequiredArchive_ExceededMaxArchivedFile() throws Throwable { File f = new File(EXCEEDED_ARCHIVE_DIR); assertTrue("Archive dir does not exist", f.exists()); File[] childs = f.listFiles(); assertTrue("Wrong number of children contained", childs.length == 6); List<String> oldestFiles = new ArrayList<String>(); oldestFiles.add("20101110_165640.zip"); oldestFiles.add("20101110_165840.zip"); oldestFiles.add("20101110_170540.zip"); File child = null; String fileName = null;//from ww w .j a va2 s .co m for (int i = 0; i < childs.length; i++) { child = childs[i]; fileName = child.getName(); if (oldestFiles.contains(fileName)) { assertTrue("Unable to set last modified for '" + fileName + "'", child.setLastModified(System.currentTimeMillis() - 1000)); } else { assertTrue("Unable to set last modified for '" + fileName + "'", child.setLastModified(System.currentTimeMillis())); } } // // archive dir contain more children than the maxNumberOfArchivedFiles // ClientLogCleanUpAgent instance = new ClientLogCleanUpAgent(LOGS_DIR, EXCEEDED_ARCHIVE_DIR, activationThreshold, maxNumberOfArchivedFiles, numberOfArchivedFilesToDelete, timeToRest, lockName); PrivateAccessor.invoke(instance, "internalRun", null, null); f = new File(EXCEEDED_ARCHIVE_DIR); assertTrue("Archive dir does not exist anymore", f.exists()); String[] childNames = f.list(); // the old 3 plus the new one assertTrue("Archive dir contains more children", childNames.length == 4); }
From source file:com.streamsets.pipeline.stage.origin.remote.TestRemoteDownloadSource.java
@Test public void testNoErrorOrdering() throws Exception { path = "remote-download-source/parseSameTimestamp"; File dir = new File(currentThread().getContextClassLoader() .getResource("remote-download-source/parseSameTimestamp").getPath()); File[] files = dir.listFiles(); Assert.assertEquals(3, files.length); for (File f : files) { if (f.getName().equals("panda.txt")) { Assert.assertTrue(f.setLastModified(18000000L)); } else if (f.getName().equals("polarbear.txt")) { f.setLastModified(18000000L); } else if (f.getName().equals("sloth.txt")) { f.setLastModified(17000000L); }//from w w w .j av a2 s. com } setupSSHD(path, false); RemoteDownloadSource origin = new RemoteDownloadSource( getBean("sftp://localhost:" + String.valueOf(port) + "/", true, "testuser", "pass", null, null, null, true, DataFormat.JSON, null)); SourceRunner runner = new SourceRunner.Builder(RemoteDownloadSource.class, origin).addOutputLane("lane") .build(); runner.runInit(); List<Record> expected = getExpectedRecords(); Record record = RecordCreator.create(); record.set(Field.create(new HashMap<String, Field>())); record.set("/name", Field.create("polarbear")); record.set("/age", Field.create("6")); record.set("/characterisitics", Field.create(Arrays.asList(Field.create("cool"), Field.create("cute"), Field.create("huge"), Field.create("round"), Field.create("playful")))); expected.add(record); String offset = "-1"; for (int i = 0; i < 3; i++) { StageRunner.Output op = runner.runProduce(offset, 1000); offset = op.getNewOffset(); List<Record> actual = op.getRecords().get("lane"); Assert.assertEquals(1, actual.size()); System.out.println(actual.get(0).get()); Assert.assertEquals(expected.get(i).get(), actual.get(0).get()); } }
From source file:net.sf.jvifm.model.FileModelManager.java
public boolean touch(String filepath, long lastModified) { File file = new File(filepath); if (!file.exists()) { try {/* w w w.j a v a 2s. c om*/ file.createNewFile(); } catch (IOException e) { e.printStackTrace(); return false; } } else { file.setLastModified(lastModified); } notifyAddFile(file); return true; }
From source file:org.springframework.integration.file.FileWritingMessageHandlerTests.java
@Test public void replaceIfDifferentFile() throws IOException { File file = new File(this.temp.newFolder(), "foo.txt"); FileCopyUtils.copy("foo".getBytes(), new FileOutputStream(file)); file.setLastModified(42_000_000); QueueChannel output = new QueueChannel(); this.handler.setOutputChannel(output); this.handler.setPreserveTimestamp(true); this.handler.setFileExistsMode(FileExistsMode.REPLACE_IF_MODIFIED); this.handler.handleMessage(MessageBuilder.withPayload(file).build()); Message<?> result = output.receive(0); assertFileContentIs(result, "foo"); assertLastModifiedIs(result, 42_000_000); FileCopyUtils.copy("bar".getBytes(), new FileOutputStream(file)); file.setLastModified(42_000_000);//from ww w. ja v a2 s. c o m this.handler.handleMessage(MessageBuilder.withPayload(file).build()); result = output.receive(0); assertFileContentIs(result, "foo"); // no overwrite - timestamp same assertLastModifiedIs(result, 42_000_000); file.setLastModified(43_000_000); this.handler.handleMessage(MessageBuilder.withPayload(file).build()); result = output.receive(0); assertFileContentIs(result, "bar"); assertLastModifiedIs(result, 43_000_000); }
From source file:com.streamsets.pipeline.stage.origin.remote.TestRemoteDownloadSource.java
@Test public void testRestartCompletedFile() throws Exception { path = "remote-download-source/parseSameTimestamp"; File dir = new File(currentThread().getContextClassLoader() .getResource("remote-download-source/parseSameTimestamp").getPath()); File[] files = dir.listFiles(); Assert.assertEquals(3, files.length); for (File f : files) { if (f.getName().equals("panda.txt")) { Assert.assertTrue(f.setLastModified(18000000L)); } else if (f.getName().equals("polarbear.txt")) { Assert.assertTrue(f.setLastModified(18000000L)); } else if (f.getName().equals("sloth.txt")) { Assert.assertTrue(f.setLastModified(17000000L)); }//from ww w .j a va 2s .c o m } setupSSHD(path, false); RemoteDownloadSource origin = new RemoteDownloadSource( getBean("sftp://localhost:" + String.valueOf(port) + "/", true, "testuser", "pass", null, null, null, true, DataFormat.JSON, null)); SourceRunner runner = new SourceRunner.Builder(RemoteDownloadSource.class, origin).addOutputLane("lane") .build(); runner.runInit(); List<Record> expected = getExpectedRecords(); Record record = RecordCreator.create(); record.set(Field.create(new HashMap<String, Field>())); record.set("/name", Field.create("polarbear")); record.set("/age", Field.create("6")); record.set("/characterisitics", Field.create(Arrays.asList(Field.create("cool"), Field.create("cute"), Field.create("huge"), Field.create("round"), Field.create("playful")))); expected.add(record); String offset = "-1"; StageRunner.Output op = runner.runProduce(offset, 1); offset = op.getNewOffset(); List<Record> actual = op.getRecords().get("lane"); Assert.assertEquals(1, actual.size()); System.out.println(actual.get(0)); Assert.assertEquals(expected.get(0).get(), actual.get(0).get()); runner.runDestroy(); // Create a new source. origin = new RemoteDownloadSource(getBean("sftp://localhost:" + String.valueOf(port) + "/", true, "testuser", "pass", null, null, null, true, DataFormat.JSON, null)); runner = new SourceRunner.Builder(RemoteDownloadSource.class, origin).addOutputLane("lane").build(); runner.runInit(); // Since we don't proactively close steams, we must hit at least one null event in a batch to close the current // stream and open the next one, else the next batch will be empty and the data comes in the batch following that. op = runner.runProduce(offset, 1); runner.runProduce(offset, 1); // Forces a new stream to be opened. offset = op.getNewOffset(); actual = op.getRecords().get("lane"); Assert.assertEquals(1, actual.size()); System.out.println(actual.get(0)); Assert.assertEquals(expected.get(1).get(), actual.get(0).get()); op = runner.runProduce(offset, 2); actual = op.getRecords().get("lane"); Assert.assertEquals(1, actual.size()); Assert.assertEquals(expected.get(2).get(), actual.get(0).get()); runner.runDestroy(); }