@BeforeClass(groups = "AllEnv") public void makeTestDirectories() throws IOException { if (Files.exists(Cテスト用ルートディレクトリ)) DirectoryDeleter.delete(Cテスト用ルートディレクトリ); Files.createDirectories(C読み込みテスト用ディレクトリ); Files.createDirectories(C書き込みテスト用ディレクトリ); Files.createDirectories(C読み込める設定ファイルかと思ったらディレクトリだった); Files.createDirectories(C書き込める設定ファイルかと思ったらディレクトリだった); Files.createFile(C存在するけど形式がおかしい設定ファイル); Files.write( C存在して読み込み可能な設定ファイル, Arrays.asList( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>", "<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">", "<properties>", "<comment>Properties File for Boardgame Server</comment>", "<entry key=\"WINDOW_H\">252</entry>", "<entry key=\"WINDOW_Y\">2</entry>", "<entry key=\"WINDOW_X\">1</entry>", "<entry key=\"WINDOW_W\">251</entry>", "</properties>"), Charset.forName("UTF-8")); Files.createFile(C設定ファイルが書き込み不能だった); C設定ファイルが書き込み不能だった.toFile().setWritable(false); }
/** * Test method for {@link SubtitleProvider#loadSubtitles(Path)}. Check that multiple subtitles are * loaded. * * @throws IOException if there was an I/O error. */ @Test public void testLoadSubtitles() throws IOException { final SubtitleFormat subtitleFormat = mock(SubtitleFormat.class); final SubtitleReader subtitleReader = mock(SubtitleReader.class); final SubtitleFile subtitleFile = mock(SubtitleFile.class); final SubtitleFile secondSubtitle = mock(SubtitleFile.class); final Path folder = subtitleFolder.newFolder().toPath(); final Path file = folder.resolve("single.srt"); final Path second = folder.resolve("other.srt"); Files.createFile(file); Files.createFile(second); Files.createFile(folder.resolve("test.sub")); when(subtitleFormatManager.getFormatByPath(file)) .thenReturn(new HashSet<>(Arrays.asList(subtitleFormat))); when(subtitleFormatManager.getFormatByPath(second)) .thenReturn(new HashSet<>(Arrays.asList(subtitleFormat))); when(subtitleFormat.getReader()).thenReturn(subtitleReader); when(subtitleReader.readFile(file)).thenReturn(subtitleFile); when(subtitleReader.readFile(second)).thenReturn(secondSubtitle); final Map<SubtitleFile, SubtitleFormat> subtitles = subtitleProvider.loadSubtitles(folder); assertEquals(2, subtitles.size()); // final Entry<SubtitleFile, SubtitleFormat> loaded = subtitles.entrySet().iterator().next(); // assertEquals(subtitleFile, loaded.getKey()); // assertEquals(subtitleFormat, loaded.getValue()); }
@BeforeClass void setupTestFolder() throws IOException { testFolder = TestUtil.createTemporaryDirectory(); supportsLinks = TestUtil.supportsLinks(testFolder); TreeSet<Path> set = new TreeSet<>(); // Level 1 Path empty = testFolder.resolve("empty"); Path file = testFolder.resolve("file"); Path dir = testFolder.resolve("dir"); Path dir2 = testFolder.resolve("dir2"); Files.createDirectory(empty); Files.createFile(file); Files.createDirectory(dir); Files.createDirectory(dir2); set.add(empty); set.add(file); set.add(dir); set.add(dir2); if (supportsLinks) { Path tmp = testFolder.resolve("linkDir"); Files.createSymbolicLink(tmp, dir); set.add(tmp); tmp = testFolder.resolve("linkFile"); Files.createSymbolicLink(tmp, file); set.add(tmp); } level1 = set.toArray(new Path[0]); // Level 2 Path tmp = dir.resolve("d1"); Files.createDirectory(tmp); set.add(tmp); tmp = dir.resolve("f1"); Files.createFile(tmp); set.add(tmp); if (supportsLinks) { tmp = dir.resolve("lnDir2"); Files.createSymbolicLink(tmp, dir2); set.add(tmp); } // walk include starting folder set.add(testFolder); all = set.toArray(new Path[0]); // Follow links if (supportsLinks) { tmp = testFolder.resolve("linkDir"); set.add(tmp.resolve("d1")); set.add(tmp.resolve("f1")); tmp = tmp.resolve("lnDir2"); set.add(tmp); } all_folowLinks = set.toArray(new Path[0]); }
public void testUncheckedIOException() throws IOException { Path triggerFile = testFolder.resolve(Paths.get("dir2", "IOException")); Files.createFile(triggerFile); Path triggerDir = testFolder.resolve(Paths.get("empty", "IOException")); Files.createDirectories(triggerDir); Files.createFile(triggerDir.resolve("file")); FaultyFileSystem.FaultyFSProvider fsp = FaultyFileSystem.FaultyFSProvider.getInstance(); FaultyFileSystem fs = (FaultyFileSystem) fsp.newFileSystem(testFolder, null); try { fsp.setFaultyMode(false); Path fakeRoot = fs.getRoot(); try (Stream<Path> s = Files.list(fakeRoot.resolve("dir2"))) { // only one file s.forEach(path -> assertEquals(path.getFileName().toString(), "IOException")); } try (Stream<Path> s = Files.walk(fakeRoot.resolve("empty"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); // ordered as depth-first assertEquals(result, new String[] {"empty", "IOException", "file"}); } fsp.setFaultyMode(true); try (Stream<Path> s = Files.list(fakeRoot.resolve("dir2"))) { s.forEach(path -> fail("should have caused exception")); } catch (UncheckedIOException uioe) { assertTrue(uioe.getCause() instanceof FaultyFileSystem.FaultyException); } try (Stream<Path> s = Files.walk(fakeRoot.resolve("empty"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); fail("should not reach here due to IOException"); } catch (UncheckedIOException uioe) { assertTrue(uioe.getCause() instanceof FaultyFileSystem.FaultyException); } try (Stream<Path> s = Files.walk(fakeRoot.resolve("empty").resolve("IOException"))) { String[] result = s.map(path -> path.getFileName().toString()).toArray(String[]::new); fail("should not reach here due to IOException"); } catch (IOException ioe) { assertTrue(ioe instanceof FaultyFileSystem.FaultyException); } catch (UncheckedIOException ex) { fail("Top level should be repored as is"); } } finally { // Cleanup if (fs != null) { fs.close(); } Files.delete(triggerFile); TestUtil.removeAll(triggerDir); } }
@Override protected void setUp() throws Exception { deleteDirectory(ROOT); super.setUp(); Files.createFile(Paths.get(ROOT, "basic", FILE)); Files.createFile(Paths.get(ROOT, "basic-as-default", FILE)); Files.createFile(Paths.get(ROOT, "basic-as-default-with-filter", FILE)); Files.createFile(Paths.get(ROOT, "posix", FILE)); }
/** Creates a test environment with bin, config and plugins directories. */ static Tuple<Path, Environment> createEnv(FileSystem fs, Function<String, Path> temp) throws IOException { Path home = temp.apply("install-plugin-command-tests"); Files.createDirectories(home.resolve("bin")); Files.createFile(home.resolve("bin").resolve("elasticsearch")); Files.createDirectories(home.resolve("config")); Files.createFile(home.resolve("config").resolve("elasticsearch.yml")); Path plugins = Files.createDirectories(home.resolve("plugins")); assertTrue(Files.exists(plugins)); Settings settings = Settings.builder().put("path.home", home).build(); return Tuple.tuple(home, new Environment(settings)); }
public void testPlatformBinPermissions() throws Exception { assumeTrue("posix filesystem", isPosix); Tuple<Path, Environment> env = createEnv(fs, temp); Path pluginDir = createPluginDir(temp); Path platformDir = pluginDir.resolve("platform"); Path platformNameDir = platformDir.resolve("linux-x86_64"); Path platformBinDir = platformNameDir.resolve("bin"); Files.createDirectories(platformBinDir); Path programFile = Files.createFile(platformBinDir.resolve("someprogram")); // a file created with Files.createFile() should not have execute permissions Set<PosixFilePermission> sourcePerms = Files.getPosixFilePermissions(programFile); assertFalse(sourcePerms.contains(PosixFilePermission.OWNER_EXECUTE)); assertFalse(sourcePerms.contains(PosixFilePermission.GROUP_EXECUTE)); assertFalse(sourcePerms.contains(PosixFilePermission.OTHERS_EXECUTE)); String pluginZip = createPlugin("fake", pluginDir); installPlugin(pluginZip, env.v1()); assertPlugin("fake", pluginDir, env.v2()); // check that the installed program has execute permissions, even though the one added to the // plugin didn't Path installedPlatformBinDir = env.v2() .pluginsFile() .resolve("fake") .resolve("platform") .resolve("linux-x86_64") .resolve("bin"); assertTrue(Files.isDirectory(installedPlatformBinDir)); Path installedProgramFile = installedPlatformBinDir.resolve("someprogram"); assertTrue(Files.isRegularFile(installedProgramFile)); Set<PosixFilePermission> installedPerms = Files.getPosixFilePermissions(installedProgramFile); assertTrue(installedPerms.contains(PosixFilePermission.OWNER_EXECUTE)); assertTrue(installedPerms.contains(PosixFilePermission.GROUP_EXECUTE)); assertTrue(installedPerms.contains(PosixFilePermission.OTHERS_EXECUTE)); }
/** Check that a cancelled key will never be queued */ static void testCancel(Path dir) throws IOException { System.out.println("-- Cancel --"); try (WatchService watcher = FileSystems.getDefault().newWatchService()) { System.out.format("register %s for events\n", dir); WatchKey myKey = dir.register(watcher, new WatchEvent.Kind<?>[] {ENTRY_CREATE}); checkKey(myKey, dir); System.out.println("cancel key"); myKey.cancel(); // create a file in the directory Path file = dir.resolve("mars"); System.out.format("create: %s\n", file); Files.createFile(file); // poll for keys - there will be none System.out.println("poll..."); try { WatchKey key = watcher.poll(3000, TimeUnit.MILLISECONDS); if (key != null) throw new RuntimeException("key should not be queued"); } catch (InterruptedException x) { throw new RuntimeException(x); } // done Files.delete(file); System.out.println("OKAY"); } }
/** * 修改渠道号 * * <p>demo: <code>changeChannel("xxx../../my.apk", "hiapk");</code> * * @param zipFilename apk文件 * @param channel 新渠道号 * @return true or false */ public static boolean buildChannel(String zipFilename, String channelPrefix, String channel) { try (FileSystem zipfs = createZipFileSystem(zipFilename, false)) { String channelBegin = "/META-INF/" + channelPrefix; String channelFlagName = channelBegin + channel; final Path root = zipfs.getPath("/META-INF/"); ChannelFileVisitor visitor = new ChannelFileVisitor(channelBegin); Files.walkFileTree(root, visitor); Path existChannel = visitor.getChannelFile(); Path newChannel = zipfs.getPath(channelFlagName); if (existChannel != null) { Files.move(existChannel, newChannel, StandardCopyOption.ATOMIC_MOVE); } else { Files.createFile(newChannel); } return true; } catch (IOException e) { e.printStackTrace(); } return false; }
void storeXml(ParseIndexContext ctx, Path xml) throws IOException { Files.createFile(xml); PrintWriter p = new PrintWriter(Files.newBufferedWriter(xml, utf8)); p.print("<?xml version='1.1' encoding='" + NotesRetriever.utf8.name() + "'?><snotes>"); ctx.list.sort(Comparator.comparing(o1 -> o1.number)); for (NoteListItem i : ctx.list) { p.print("\n<n"); p.print(" n='" + i.number + "'"); if (i.mark != null) p.print(" m='" + i.mark + "'"); p.print(" a='" + i.apparea + "'"); p.print(" l='" + i.asklangu + "'"); p.print(" d='" + DateTimeFormatter.ISO_LOCAL_DATE.format(i.date) + "'"); p.print(" c='" + i.category + "'"); p.print(" p='" + i.priority + "'"); if (i.objid != null) p.print(" o='" + i.objid + "'"); p.print(">" + StringEscapeUtils.escapeXml11(i.title) + "</n>"); } p.flush(); for (Pair<String, String> a : ctx.lareas) { p.print("\n<area rcode='" + a.getKey() + "' value='" + a.getValue() + "'/>"); } p.flush(); // p.print("\n<!-- [Statistics]"); // if (dsd==0 && dod==0) { // p.print("\tNotes collected: " + q + ", no duplicates found"); // } else { // p.print("\nUnique notes collected: " + q); // p.print("\nDuplicate notes with the same date: " + dsd); // p.print("\nDuplocate notes with the other date: " + dod); // } // p.println("\t-->"); p.print("\n</snotes>"); p.close(); }
/** Start the logging system. We must define a new log to store everything. */ public synchronized void createLog() { if (logPath == null) { String id = String.format("log_%d", System.currentTimeMillis()); try { // Try to close the old channel. if (logChannel != null) { logChannel.close(); } logPath = Paths.get(db.getLogPath() + System.getProperty("file.separator") + id).toAbsolutePath(); if (!Files.exists(logPath)) { // Create the necessary parent directories. Files.createDirectories(Paths.get(db.getLogPath()).toAbsolutePath()); // Make sure that our WAL is created before we return. logPath = Files.createFile(logPath); // Open up the line of communication. String flag = "rw"; if (flushPolicy == Flush.SAFE) { flag += "d"; } logChannel = new RandomAccessFile(logPath.toString(), flag).getChannel(); // Map the file. logBuffer = mapWAL(); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
/** * Create new encrypt/decrypt instance with required parameters. * * @param sourceFileName File you want to encrypt/decrypt. * @param destinationFileName File which will be the result of encryption/decryption. * @param encryptionKey Encryption key which will be used in process of encryption/decryption. * @param initializationVector Initialization vector which will be used in process of * encryption/decryption. * @param mode {@link FileEncryption} ENCRYPT_MODE/DECRYPT_MODE. */ public FileEncryption( String sourceFileName, String destinationFileName, String encryptionKey, String initializationVector, int mode) { SecretKeySpec keySpec = new SecretKeySpec(hexToByte(encryptionKey), "AES"); AlgorithmParameterSpec paramSpec = new IvParameterSpec(hexToByte(initializationVector)); try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(mode, keySpec, paramSpec); inputPath = Paths.get(sourceFileName); File outputFile = new File(destinationFileName); outputPath = outputFile.toPath(); if (!outputFile.exists()) { Files.createFile(outputPath); } } catch (NoSuchAlgorithmException e) { System.out.println("No AES/CBC/PKCS5Padding algorithm available."); } catch (NoSuchPaddingException e) { System.out.println("No such padding."); } catch (InvalidKeyException e) { System.out.println("Invalid key."); } catch (InvalidAlgorithmParameterException e) { System.out.println("Invalid algorithm parameters."); } catch (IOException e) { System.out.println("Could not read a file."); } }
private static void pathesAndFileCreation() throws IOException { System.out.println("yes\\no"); System.out.println("c:\\program files\\myProgram"); System.out.println("c:/program files/myProgram"); String win = "c:\\HaxLogs.txt"; String unix = "c:/HaxLogs.txt"; File winFile = new File(win); System.out.println("win file exists: " + winFile.exists()); File unixFile = new File(unix); System.out.println("unix file exists: " + unixFile.exists()); Path path = Paths.get("myFile.txt"); System.out.println(path); System.out.println(path.toAbsolutePath()); Path absolutePath = Paths.get("d:/myFile.txt"); System.out.println(absolutePath); System.out.println(absolutePath.toAbsolutePath()); if (!Files.exists(absolutePath)) { Files.createFile(absolutePath); System.out.println("file created"); } else { System.out.println("file already exists"); } }
/* * Windowsでは読み込み可否設定はできないっぽい */ @Test(groups = "LinuxOnly", expectedExceptions = IllegalArgumentException.class) public void loadが呼び出されたけど設定ファイルが読み込み不能な時はIllegalArgumentExceptionをスローするよ() throws IOException { Files.createFile(C設定ファイルが読み込み不能だった); C設定ファイルが読み込み不能だった.toFile().setReadable(false); ServerProperties.INSTANCE.load(C設定ファイルが読み込み不能だった.toString()); }
/** 读写文件的优化 */ @Test public void testReadAndWriter() { // StandardCharsets.UTF_8 Path path2 = Paths.get(PATH); String string = ParentPath + "\\writer.txt"; Path path3 = Paths.get(string); try { Files.createFile(path3); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try (BufferedReader reader = Files.newBufferedReader(path2, Charset.forName("GBK")); BufferedWriter bw = Files.newBufferedWriter(path3, Charset.forName("UTF-8"), StandardOpenOption.WRITE)) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); bw.write(line); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void LoadFile() { try { if (!Files.exists(_path)) { Files.createFile(_path); return; } Files.readAllLines(_path, StandardCharsets.UTF_8); try { String playerName = ""; String timeStamp = ""; for (String line : Files.readAllLines(_path, StandardCharsets.UTF_8)) { if (line.equals("")) continue; if (playerName.equals("")) { playerName = line; continue; } if (timeStamp.equals("")) { timeStamp = line; _whiteListed.Add(new PlayerWhitelistRecord(playerName, timeStamp)); continue; } } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } }
public static void saveData(String file, EnumMap<PlayerStats, Float> map, boolean overwrite) { FileSystem fileSystem = FileSystems.getDefault(); Path path = fileSystem.getPath(file); if (Files.isDirectory(path)) throw new IllegalArgumentException("This method is not supposed to read a directory"); if (Files.exists(path) && Files.isReadable(path)) { if (overwrite == false) return; } else try { Files.createFile(path); } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(Files.newOutputStream(path))) { objectOutputStream.writeObject(map); } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
@Test public void test() { AntivirusPlugin antivirusPlugin = new AntivirusPlugin(); Path testFile = null; FileOutputStream f = null; try { List<byte[]> bytesList = AntivirusProperties.getByteSequences(); if (bytesList.size() == 0) { fail( "You should have at least one sequence in file antivirus.properties. Please write one"); } // empty file can't be infected testFile = Files.createFile(Paths.get("testfile")); assertTrue(antivirusPlugin.canCopyFile(testFile)); // adding infected sequence of bytes to file f = new FileOutputStream(testFile.toFile()); f.write(bytesList.get(0)); assertFalse(antivirusPlugin.canCopyFile(testFile)); } catch (IOException e) { fail(e.getMessage()); } finally { closeStream(f); deleteFile(testFile); } }
@Test public void rewritesRequireStatementForDirectoryIndex2() throws IOException { createDirectories(path("foo")); createFile(path("foo/bar.js")); CompilerUtil compiler = createCompiler(path("foo/bar/index.js"), path("foo/bar.js"), path("foo/main.js")); compiler.compile( createSourceFile(path("foo/bar/index.js"), "exports.a = 123;"), createSourceFile(path("foo/bar.js"), "exports.b = 456;"), createSourceFile( path("foo/main.js"), "var bar1 = require('./bar');", "var bar2 = require('./bar/');", "exports.c = bar1.a * bar2.b;")); assertThat(compiler.toSource()) .startsWith( lines( "var $jscomp = {};", "$jscomp.scope = {};", "var module$foo$bar$index = {};", "module$foo$bar$index.a = 123;", "var module$foo$bar = {};", "module$foo$bar.b = 456;", "var module$foo$main = {};", "module$foo$main.c = module$foo$bar.a * module$foo$bar$index.b;")); }
public void open(Path path) { try { if (!Files.exists(path)) path = Files.createFile(path); writer = Files.newBufferedWriter(path, charset); } catch (IOException e) { e.printStackTrace(); } }
public FileResource create() { try { Files.createFile(file); } catch (IOException e) { throw New.unchecked(e); } return this; }
private FileBasedConfig getGerritConfigFile(SitePaths sitePath) throws IOException { FileBasedConfig cfg = new FileBasedConfig(sitePath.gerrit_config.toFile(), FS.DETECTED); if (!cfg.getFile().exists()) { Path etc_path = Files.createDirectories(sitePath.etc_dir); Files.createFile(etc_path.resolve("gerrit.config")); } return cfg; }
@Test public void handlesReferencesToOtherModulesTypesEvenIfNotExplicitlyRequired() throws IOException { Path root = path("root.js"); Path bar = path("foo/bar.js"); Path baz = path("foo/baz.js"); createFile(root); createDirectories(bar.getParent()); createFile(bar); createFile(baz); CompilerUtil compiler = createCompiler(root, bar, baz); compiler.compile( createSourceFile(root, "/** @param {!./foo/bar.Person} p . */", "function inRoot(p) {}"), createSourceFile(bar, "/** @constructor */", "exports.Person = function(){};"), createSourceFile(baz, "/** @param {!./bar.Person} p . */", "function inBaz(p) {}")); }
public void testConfig() throws Exception { Tuple<Path, Environment> env = createEnv(fs, temp); Path pluginDir = createPluginDir(temp); Path configDir = pluginDir.resolve("config"); Files.createDirectory(configDir); Files.createFile(configDir.resolve("custom.yaml")); String pluginZip = createPlugin("fake", pluginDir); installPlugin(pluginZip, env.v1()); assertPlugin("fake", pluginDir, env.v2()); }
public void testConfigNotDir() throws Exception { Tuple<Path, Environment> env = createEnv(fs, temp); Path pluginDir = createPluginDir(temp); Path configDir = pluginDir.resolve("config"); Files.createFile(configDir); String pluginZip = createPlugin("fake", pluginDir); UserException e = expectThrows(UserException.class, () -> installPlugin(pluginZip, env.v1())); assertTrue(e.getMessage(), e.getMessage().contains("not a directory")); assertInstallCleaned(env.v2()); }
public void testBin() throws Exception { Tuple<Path, Environment> env = createEnv(fs, temp); Path pluginDir = createPluginDir(temp); Path binDir = pluginDir.resolve("bin"); Files.createDirectory(binDir); Files.createFile(binDir.resolve("somescript")); String pluginZip = createPlugin("fake", pluginDir); installPlugin(pluginZip, env.v1()); assertPlugin("fake", pluginDir, env.v2()); }
@Before private void setUp() throws IOException { final String[] fileNames = { "backup_CombinedData_2016-Jun-20_at_00-14-00", "backup_CombinedData_2016-Jul-19_at_00-20-00", // TODO other types }; for (final String fileName : fileNames) { Files.createFile(testPath.resolve(fileName)); } }
public void testMissingDescriptor() throws Exception { Tuple<Path, Environment> env = createEnv(fs, temp); Path pluginDir = createPluginDir(temp); Files.createFile(pluginDir.resolve("fake.yml")); String pluginZip = writeZip(pluginDir, "elasticsearch"); NoSuchFileException e = expectThrows(NoSuchFileException.class, () -> installPlugin(pluginZip, env.v1())); assertTrue(e.getMessage(), e.getMessage().contains("plugin-descriptor.properties")); assertInstallCleaned(env.v2()); }
private void ensureServiceOutExists() { try { if (!Files.exists(taskDefinition.getServiceLogOutPath())) { Files.createFile(taskDefinition.getServiceLogOutPath()); } } catch (FileAlreadyExistsException faee) { log.debug("Executor out {} already existed", taskDefinition.getServiceLogOut()); } catch (Throwable t) { log.error("Failed creating executor out {}", taskDefinition.getServiceLogOut(), t); } }
@Test public void testCreate_NotDirectory() throws IOException { final Path root = random(); try { Files.createFile(root); exception.expect(NotDirectoryException.class); new SitePaths(root); } finally { Files.delete(root); } }