@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); }
@Override public Item item(final QueryContext qc, final InputInfo ii) throws QueryException { checkCreate(qc); final Path path = toPath(0, qc); final B64 archive = toB64(exprs[1], qc, false); final TokenSet hs = entries(2, qc); try (ArchiveIn in = ArchiveIn.get(archive.input(info), info)) { while (in.more()) { final ZipEntry ze = in.entry(); final String name = ze.getName(); if (hs == null || hs.delete(token(name)) != 0) { final Path file = path.resolve(name); if (ze.isDirectory()) { Files.createDirectories(file); } else { Files.createDirectories(file.getParent()); Files.write(file, in.read()); } } } } catch (final IOException ex) { throw ARCH_FAIL_X.get(info, ex); } return null; }
private void initHomeDir() throws IOException { String[] filesToCheck = new String[] {"logs", "tmp", "log4j.xml", "templates"}; if (!Files.exists(config.getHomeDir())) { Files.createDirectories(config.getHomeDir()); } if (Files.exists(config.getHomeDir()) && Files.isDirectory(config.getHomeDir())) { for (String fileToCheck : filesToCheck) { Path sourceFile = config.getResourceFetcher().getFile(fileToCheck); if (sourceFile != null && Files.exists(sourceFile)) { Path destFile = config.getHomeDir().resolve(fileToCheck); if (!Files.exists(destFile)) { if (Files.isDirectory(sourceFile)) { Files.createDirectories(destFile); for (Path f : PathUtils.list(sourceFile)) { if (Files.isDirectory(f)) { Path destDir2 = destFile.resolve(f.getFileName().toString()); for (Path x : PathUtils.list(f)) { FileUtils.copyFile( x.toFile(), destDir2.resolve(x.getFileName().toString()).toFile()); } } else if (Files.isDirectory(f)) { FileUtils.copyFile( f.toFile(), destFile.resolve(f.getFileName().toString()).toFile()); } } } else { FileUtils.copyFile(sourceFile.toFile(), destFile.toFile()); } } } } } }
public void run() throws Throwable { if (Files.notExists(jdkMods)) { return; } if (!CompilerUtils.compile(src, classes)) { throw new AssertionError("Compilation failure. See log."); } String modName = "test"; Files.createDirectories(jmods); Files.createDirectories(jars); Path jarfile = jars.resolve("test.jar"); JarUtils.createJarFile(jarfile, classes); Path image = Paths.get("mysmallimage"); runJmod(jarfile.toString(), modName); runJlink(image, modName, "--compress", "2"); execute(image, modName); Files.delete(jmods.resolve(modName + ".jmod")); image = Paths.get("myimage"); runJmod(classes.toString(), modName); runJlink(image, modName); execute(image, modName); }
@Test public void testRemoveUnfinishedLeftovers_abort_multipleFolders() throws Throwable { ColumnFamilyStore cfs = MockSchema.newCFS(KEYSPACE); File origiFolder = new Directories(cfs.metadata).getDirectoryForNewSSTables(); File dataFolder1 = new File(origiFolder, "1"); File dataFolder2 = new File(origiFolder, "2"); Files.createDirectories(dataFolder1.toPath()); Files.createDirectories(dataFolder2.toPath()); SSTableReader[] sstables = { sstable(dataFolder1, cfs, 0, 128), sstable(dataFolder1, cfs, 1, 128), sstable(dataFolder2, cfs, 2, 128), sstable(dataFolder2, cfs, 3, 128) }; LogTransaction log = new LogTransaction(OperationType.COMPACTION); assertNotNull(log); LogTransaction.SSTableTidier[] tidiers = { log.obsoleted(sstables[0]), log.obsoleted(sstables[2]) }; log.trackNew(sstables[1]); log.trackNew(sstables[3]); Collection<File> logFiles = log.logFiles(); Assert.assertEquals(2, logFiles.size()); // fake an abort log.txnFile().abort(); Arrays.stream(sstables).forEach(s -> s.selfRef().release()); // test listing Assert.assertEquals( sstables[1].getAllFilePaths().stream().map(File::new).collect(Collectors.toSet()), getTemporaryFiles(dataFolder1)); Assert.assertEquals( sstables[3].getAllFilePaths().stream().map(File::new).collect(Collectors.toSet()), getTemporaryFiles(dataFolder2)); // normally called at startup LogTransaction.removeUnfinishedLeftovers(Arrays.asList(dataFolder1, dataFolder2)); // old tables should be only table left assertFiles(dataFolder1.getPath(), new HashSet<>(sstables[0].getAllFilePaths())); assertFiles(dataFolder2.getPath(), new HashSet<>(sstables[2].getAllFilePaths())); // complete the transaction to avoid LEAK errors Arrays.stream(tidiers).forEach(LogTransaction.SSTableTidier::run); assertNull(log.complete(null)); }
/** 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)); }
private Path executeWindupAgainstAppUntilRule( final String inputDir, final GraphContext grCtx, final Class<MavenizeRuleProvider> ruleToRunUpTo) throws IOException, IllegalAccessException, InstantiationException { Assume.assumeTrue("Exists: " + inputDir, new File(inputDir).exists()); final Path outputPath = Paths.get(FileUtils.getTempDirectory().toString(), "Windup-Mavenization-output"); FileUtils.deleteDirectory(outputPath.toFile()); Files.createDirectories(outputPath); grCtx.getGraph().getBaseGraph().commit(); // Configure Windup core final WindupConfiguration processorConfig = new WindupConfiguration(); processorConfig.setRuleProviderFilter(new RuleProviderWithDependenciesPredicate(ruleToRunUpTo)); processorConfig.setGraphContext(grCtx); processorConfig.addInputPath(Paths.get(inputDir)); processorConfig.setOutputDirectory(outputPath); processorConfig.setOptionValue(ScanPackagesOption.NAME, Collections.singletonList("")); processorConfig.setOptionValue(SourceModeOption.NAME, false); processorConfig.setOptionValue(MavenizeOption.NAME, true); processor.execute(processorConfig); return outputPath; }
/** Test that an empty dir will be removed during cleaning. */ @Test public void testCleanNotEmptyGrandParentDir() throws Exception { String expResult = "0c40ffacd15b0f66d5081a93407d3ff5e3c65a71"; Path grandparent = rootDir.toPath().resolve("0c"); Path parent = grandparent.resolve("40ffacd15b0f66d5081a93407d3ff5e3c65a71"); Path other = grandparent.resolve("40ffacd15b0f66d5081a93407d3ff5e3c65a81"); Files.createDirectories(other); Path expectedContent = parent.resolve("content"); assertFalse(expectedContent + " shouldn't exist", Files.exists(expectedContent)); assertFalse(parent + " shouldn't exist", Files.exists(parent)); byte[] result; try (InputStream stream = getResourceAsStream("overlay.xhtml")) { assertThat(repository.hasContent(HashUtil.hexStringToByteArray(expResult)), is(false)); result = repository.addContent(stream); } assertThat(result, is(notNullValue())); assertThat(HashUtil.bytesToHexString(result), is(expResult)); assertThat(repository.hasContent(HashUtil.hexStringToByteArray(expResult)), is(true)); assertTrue(expectedContent + " should have been created", Files.exists(expectedContent)); assertTrue(parent + " should have been created", Files.exists(parent)); repository.removeContent(new ContentReference("overlay.xhtml", expResult)); assertFalse(repository.hasContent(HashUtil.hexStringToByteArray(expResult))); assertFalse(expectedContent + " should have been deleted", Files.exists(expectedContent)); assertFalse(parent.toAbsolutePath() + " should have been deleted", Files.exists(parent)); assertTrue(other + " should not have been deleted", Files.exists(other)); assertTrue(grandparent + " should not have been deleted", Files.exists(grandparent)); Path content = repository.getContent(result).getPhysicalFile().toPath(); assertFalse(Files.exists(content)); }
private ImmutableMap<Path, Path> getExpandedSourcePaths( ExecutionContext context, ImmutableMap<Path, Path> paths) throws IOException { ProjectFilesystem projectFilesystem = context.getProjectFilesystem(); ImmutableMap.Builder<Path, Path> sources = ImmutableMap.builder(); for (ImmutableMap.Entry<Path, Path> ent : paths.entrySet()) { if (ent.getValue().toString().endsWith(SRC_ZIP)) { Path destinationDirectory = projectFilesystem.resolve(tempDir.resolve(ent.getKey())); Files.createDirectories(destinationDirectory); ImmutableList<Path> zipPaths = Unzip.extractZipFile( projectFilesystem.resolve(ent.getValue()), destinationDirectory, Unzip.ExistingFileMode.OVERWRITE); for (Path path : zipPaths) { Path modulePath = destinationDirectory.relativize(path); sources.put(modulePath, path); } } else { sources.put(ent.getKey(), ent.getValue()); } } return sources.build(); }
public static void main(String[] args) throws IOException, TransformerException, XPathExpressionException { if (args.length != 1) { System.err.println("Use: CreateFolderStructureHere PATH_TO_FILES"); System.exit(1); } Set<Image> imagesList = new HashSet<Image>(); System.out.println("Parsing files..."); File base = new File(args[0]); for (File file : base.listFiles()) { Image i = Image.createFromFile(file); if (i != null) { imagesList.add(i); } } System.out.println("Moving files..."); for (Image i : imagesList) { System.out.println(i); File targetPath = i.getTargetPath(); if (targetPath != null) { if (!targetPath.exists()) { System.out.println("Creating folder structure..."); Files.createDirectories(targetPath.toPath()); } System.out.println("Moving file..."); Files.move(i.getFile().toPath(), i.getTargetFile().toPath(), ATOMIC_MOVE); } } System.out.println("Done!"); }
public static Path storeInTemp(String pluginName, InputStream in, SitePaths sitePaths) throws IOException { if (!Files.exists(sitePaths.tmp_dir)) { Files.createDirectories(sitePaths.tmp_dir); } return asTemp(in, tempNameFor(pluginName), ".jar", sitePaths.tmp_dir); }
@Activate public void activate() { timer = new Timer(); Path dbPath = Paths.get(DATABASE_PATH); Path dbFolderPath = Paths.get(ENCLOSING_FOLDER); // Make sure the directory exists, if it does not, make it. if (!dbFolderPath.toFile().isDirectory()) { log.info("The specified folder location for the database did not exist and will be created."); try { Files.createDirectories(dbFolderPath); } catch (IOException e) { log.error("Could not create the required folder for the database."); throw new PersistenceException("Database folder could not be created."); } } // Notify if the database file does not exist. boolean dbFound = Files.exists(dbPath); if (!dbFound) { log.info("The database file could not be located, a new database will be constructed."); } else { log.info("A previous database file has been found."); } localDB = DBMaker.newFileDB(dbPath.toFile()).asyncWriteEnable().closeOnJvmShutdown().make(); timer.schedule(commitTask, FLUSH_FREQUENCY_MILLIS, FLUSH_FREQUENCY_MILLIS); log.info("Started"); }
static void copyFile(File src, File dst) throws IOException { Path parent = dst.toPath().getParent(); if (parent != null) { Files.createDirectories(parent); } Files.copy(src.toPath(), dst.toPath(), COPY_ATTRIBUTES, REPLACE_EXISTING); }
/** * ファイルデータをストレージに保存します. * * @param metadata ファイルデータを含むurlTreeメタデータオブジェクト * @param ctx urlTreeコンテキストオブジェクト */ @Override public void save(UrlTreeMetaData<InputStream> metadata, UrlTreeContext ctx) throws BadContentException { String localFileName = metadata.getAbsolutePath(); logger.debug("saving " + localFileName); Path f = this.generateFileObj(localFileName); InputStream b = metadata.getData(); // nullの場合は書き換えない。 if (b == null) { return; } try { Path parent = f.getParent(); // 書き込む場所がなければ親ディレクトリを作成 if (Files.notExists(parent)) { Files.createDirectories(parent); } Files.copy(b, f, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new GenericResourceException(e); } }
@Test public void testSearchCandidates() throws Exception { Path outputBaseDir = mktempdir(); Path emptyInputDir = outputBaseDir.resolve("dummy-input"); Files.createDirectories(emptyInputDir); CommandLineExecuter.main( new String[] { "--pdf-dir", getResourcePath("/examples/minimal-pdf"), "--text-dir", outputBaseDir.resolve("text").toString(), "--db-dir", outputBaseDir.resolve("db").toString(), "--index-dir", outputBaseDir.resolve("index").toString(), "--search-candidates", "--convert-to-text", "--tag", "foo-bar", "--queries-file", getResourcePath("/commandLine/queryTerms.csv") }); log.debug("OutputBase exists at " + outputBaseDir.toFile()); FileUtils.deleteDirectory(outputBaseDir.toFile()); }
/** * reads config or generates new random if any errors ocurred * * @throws java.io.IOException on errors reading file */ void loadConfiguration() throws IOException { // myCorrPath = EnsembleController.getPath(myFolder + "/" + CORR_FILE); Files.createDirectories(GibbsConfigurationManager.getPath(myFolder)); boolean recover = myEnsemble.opt.isOld(); // reading old state if (recover) { if (Files.exists(myConfigPath)) { try { readCoordinates(Files.readAllLines(myConfigPath, Charset.forName("UTF-8"))); System.out.print(": config loaded - ok"); } catch (Exception e) { System.out.println("WARNING: failed to read config for " + myFolder); System.out.println(e.getLocalizedMessage()); recover = false; } } else { recover = false; } } if (!recover) { System.out.print("! from scratch"); initParticlesPosition(); // initial distribution, reset counters saveConfiguration(); // System.exit(0); } }
/** * Creates/opens a zip file at the specified location. Does <b>not</b> create parent folders. * * @param zipFile the path to the zip file * @param create true if the file should be created, if non-existent * @param rootFirst the root folder * @param rootMore the rest of the path * @throws IOException */ public ZipFileDataStore(Path zipFile, boolean create, String rootFirst, String... rootMore) throws IOException { URI zipUri = zipFile.toUri(); URI uri = URI.create("jar:file:" + zipUri.getPath()); FileSystem fileSys; try { fileSys = FileSystems.getFileSystem(uri); log.info("Opened existing file " + uri); } catch (FileSystemNotFoundException e) { // create must always be set: // if not a FileSystem without "create" could be created // and would be used ever after - there is no way a FileSystem could be removed Map<String, String> env = new HashMap<>(); env.put("create", "true"); fileSys = FileSystems.newFileSystem(uri, env); log.info("Created file " + uri); } this.zipFile = uri; this.fileSystem = fileSys; this.root = fileSys.getPath(rootFirst, rootMore).toAbsolutePath(); // checking if the root already exists is done in createDirs() if (create) { Files.createDirectories(root); } }
@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;")); }
@Test public void processesExternModules() throws IOException { Path extern = path("root/externs/xml.js"); Path module = path("root/source/foo.js"); createDirectories(extern.getParent()); write( extern, lines( "/** @const */", "var xml = {};", "/** @param {string} str", " * @return {!Object}", " */", "xml.parse = function(str) {};", "module.exports = xml;") .getBytes(StandardCharsets.UTF_8)); CompilerUtil compiler = createCompiler(ImmutableSet.of(extern), ImmutableSet.of(module)); compiler.compile(module, "var xml = require('xml');", "xml.parse('abc');"); assertThat(compiler.toSource()) .contains( lines( "var xml = $jscomp.scope.xml_module;", "var module$root$source$foo = {};", "$jscomp.scope.xml_module.parse(\"abc\");")); }
static boolean unpackZipTo(Path zipfile, Path destDirectory) throws IOException { boolean ret = true; byte[] bytebuffer = new byte[BUFFERSIZE]; ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipfile.toFile())); ZipEntry zipentry; while ((zipentry = zipinputstream.getNextEntry()) != null) { Path newFile = destDirectory.resolve(zipentry.getName()); if (!Files.exists(newFile.getParent(), LinkOption.NOFOLLOW_LINKS)) { Files.createDirectories(newFile.getParent()); } if (!Files.isDirectory(newFile, LinkOption.NOFOLLOW_LINKS)) { FileOutputStream fileoutputstream = new FileOutputStream(newFile.toFile()); int bytes; while ((bytes = zipinputstream.read(bytebuffer)) > -1) { fileoutputstream.write(bytebuffer, 0, bytes); } fileoutputstream.close(); } zipinputstream.closeEntry(); } zipinputstream.close(); return ret; }
public void initIndex() throws Exception { try { Files.createDirectories(updateLocation); } catch (Exception a) { // ignore } long startUpdate = System.currentTimeMillis(); System.out.println("fetching updates "); updateIndex(); long span = System.currentTimeMillis() - startUpdate; System.out.println("done updates index - time taken = " + span); i = new Index(updateLocation.resolve("index.json")); LinkedList<Runnable> updateOperations = new LinkedList<>(); for (SmallModuleEntry sme : i.getSmallModuleEntrys()) { LocallyPresent locallyPresent = UploaderPlugin.locallyPresent(updateLocation, sme); if (locallyPresent != LocallyPresent.ABSENT) { if (sme.isDead()) { deleteLocal(sme); // dead plugins get cleaned. :D } else { updateOperations.add(loadInNewThread(sme)); } } } ReactiveThread rt = ReactiveThread.create( CompletionCallback.DUMMY, "Updating all plugins", updateOperations.toArray(new Runnable[updateOperations.size()])); rt.setDaemon(true); rt.start(); }
public ReadWriteStorageManager( Path savePath, ModuleEnvironment environment, EngineEntityManager entityManager, BlockManager blockManager, BiomeManager biomeManager, boolean storeChunksInZips) throws IOException { super(savePath, environment, entityManager, blockManager, biomeManager, storeChunksInZips); entityManager.subscribeForDestruction(this); entityManager.subscribeForChanges(this); // TODO Ensure that the component library and the type serializer library are thread save (e.g. // immutable) this.privateEntityManager = createPrivateEntityManager(entityManager.getComponentLibrary()); Files.createDirectories(getStoragePathProvider().getStoragePathDirectory()); this.saveTransactionHelper = new SaveTransactionHelper(getStoragePathProvider()); this.saveThreadManager = TaskMaster.createFIFOTaskMaster("Saving", 1); this.config = CoreRegistry.get(Config.class); this.entityRefReplacingComponentLibrary = privateEntityManager .getComponentLibrary() .createCopyUsingCopyStrategy(EntityRef.class, new DelayedEntityRefCopyStrategy(this)); this.entitySetDeltaRecorder = new EntitySetDeltaRecorder(this.entityRefReplacingComponentLibrary); }
private void checkFileStructure() { try { if (!Files.exists(pathFile)) { Files.createDirectories(pathFile); } Path path = Paths.get(pathFile.toString(), FILE_SYSTEM); if (!Files.exists(path)) { Files.createDirectory(path); } path = Paths.get(pathFile.toString(), FILE_SYSTEM, PROBLEMS); if (!Files.exists(path)) { Files.createDirectory(path); } path = Paths.get(pathFile.toString(), FILE_SYSTEM, SUBMISSIONS); if (!Files.exists(path)) { Files.createDirectory(path); } path = Paths.get(pathFile.toString(), FILE_SYSTEM, COMPETITIONS); if (!Files.exists(path)) { Files.createDirectory(path); } path = Paths.get(pathFile.toString(), FILE_SYSTEM, TEMP); if (!Files.exists(path)) { Files.createDirectory(path); } path = Paths.get(pathFile.toString(), FILE_SYSTEM, CONFIG); if (!Files.exists(path)) { Files.createDirectory(path); } } catch (IOException e) { FileSystemLogging.logger.log( Level.FINE, "IOException while creating file system structure", e); } }
private void moveCorruptedReplayFile(Path replayFile) throws IOException { Path corruptedReplaysDirectory = preferencesService.getCorruptedReplaysDirectory(); Files.createDirectories(corruptedReplaysDirectory); Path target = corruptedReplaysDirectory.resolve(replayFile.getFileName()); logger.debug("Moving corrupted replay file from {} to {}", replayFile, target); Files.move(replayFile, target); notificationService.addNotification( new PersistentNotification( i18n.get("corruptedReplayFiles.notification"), Severity.WARN, Collections.singletonList( new Action( i18n.get("corruptedReplayFiles.show"), event -> { try { // Argh, using AWT since JavaFX doesn't provide a proper method :-( Desktop.getDesktop().open(corruptedReplaysDirectory.toFile()); } catch (IOException e) { logger.warn("Could not reveal corrupted replay directory", e); } })))); }
/** 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(); } } }
/** * Marshals the object to the given path that must represent a path to the file. * * <p>This method is capable of setting the schema version to the object being marshalled. * * @param path Path to file * @param object Object to marshal * @param noNamespaceSchemaLocation NoNamespaceSchemaLocation to set. If it's <code>null</code> no * location will be set. * @param schemaVersion If schema version is set and object to marshall is instance of {@link * ISchemaVersionAware} then the given schema version will be set to the object. Use <code>0 * </code> to ignore setting of schema version. * @throws JAXBException If {@link JAXBException} occurs. * @throws IOException If {@link IOException} occurs. */ public void marshall( Path path, Object object, String noNamespaceSchemaLocation, int schemaVersion) throws JAXBException, IOException { if (Files.isDirectory(path)) { throw new IOException("Can not marshal object to the path that represents the directory"); } Files.deleteIfExists(path); Files.createDirectories(path.getParent()); JAXBContext context = JAXBContext.newInstance(object.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); if (null != noNamespaceSchemaLocation) { marshaller.setProperty( Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, noNamespaceSchemaLocation); } // set schema version if needed if ((object instanceof ISchemaVersionAware) && (0 != schemaVersion)) { ((ISchemaVersionAware) object).setSchemaVersion(schemaVersion); } try (OutputStream outputStream = Files.newOutputStream(path, StandardOpenOption.CREATE_NEW)) { marshaller.marshal(object, outputStream); } }
private static void writeReport(Report report) { if (report == null) { return; } if (!SHOULD_WRITE_REPORT) { return; } report.timestamp = new Date().toString(); report.javaVersion = System.getProperty("java.runtime.version"); report.hardwareConfig = getHwConfigFromEnv(); report.jvmArgs = getNonXenonJvmArgs(); report.xenonArgs = getXenonTestArgs(); report.id = getIdFromEnv(); report.os = System.getProperty("os.name") + " " + System.getProperty("os.version"); Path dest = getReportRootFolder(); dest = dest.resolve(report.id); report.prepare(); Logger logger = Logger.getAnonymousLogger(); try { Files.createDirectories(dest); dest = dest.resolve(report.name + ".json").toAbsolutePath(); String json = Utils.toJsonHtml(report); Files.write(dest, json.getBytes(Utils.CHARSET)); logger.info(String.format("Report for test run %s written to %s", report.id, dest)); } catch (IOException e) { logger.log(Level.WARNING, "Could not save test results to " + dest, e); } }
@Test public void executeTests() throws IOException { String testBase = server.whereIs("/selenium-server/tests"); Path outputFile = Paths.get(StandardSystemProperty.JAVA_IO_TMPDIR.value()) .resolve("core-test-suite" + browser.replace('*', '-') + ".html"); if (Files.exists(outputFile)) { Files.delete(outputFile); } Files.createDirectories(outputFile.getParent()); String result = new HTMLLauncher() .runHTMLSuite( browser, // We need to do this because the path relativizing code in java.net.URL is // clearly having a bad day. "/selenium-server/tests" appended to "../tests/" // ends up as "/tests" rather than "/selenium-server/tests" as you'd expect. testBase + "/TestSuite.html", testBase + "/TestSuite.html", outputFile.toFile(), TimeUnit.MINUTES.toSeconds(5), null); assertEquals("PASSED", result); }
public void split() throws IOException { List<ObjectPath> pathTable = asset.getPaths(); TypeTree typeTree = asset.getTypeTree(); // assets with just one object can't be split any further if (pathTable.size() == 1) { L.warning("Asset doesn't contain sub-assets!"); return; } for (ObjectPath path : pathTable) { // skip filtered classes if (cf != null && !cf.accept(path)) { continue; } String className = ClassID.getNameForID(path.getClassID(), true); AssetFile subAsset = new AssetFile(); subAsset.getHeader().setFormat(asset.getHeader().getFormat()); ObjectPath subFieldPath = new ObjectPath(); subFieldPath.setClassID1(path.getClassID1()); subFieldPath.setClassID2(path.getClassID2()); subFieldPath.setLength(path.getLength()); subFieldPath.setOffset(0); subFieldPath.setPathID(1); subAsset.getPaths().add(subFieldPath); TypeTree subTypeTree = subAsset.getTypeTree(); subTypeTree.setEngineVersion(typeTree.getEngineVersion()); subTypeTree.setVersion(-2); subTypeTree.setFormat(typeTree.getFormat()); subTypeTree.getFields().put(path.getClassID(), typeTree.getFields().get(path.getClassID())); subAsset.setDataBuffer(asset.getPathBuffer(path)); Path subAssetDir = outputDir.resolve(className); if (Files.notExists(subAssetDir)) { Files.createDirectories(subAssetDir); } // probe asset name String subAssetName = getObjectName(asset, path); if (subAssetName != null) { // remove any chars that could cause troubles on various file systems subAssetName = FilenameSanitizer.sanitizeName(subAssetName); } else { // use numeric names subAssetName = String.format("%06d", path.getPathID()); } subAssetName += ".asset"; Path subAssetFile = subAssetDir.resolve(subAssetName); if (Files.notExists(subAssetFile)) { L.log(Level.INFO, "Writing {0}", subAssetFile); subAsset.save(subAssetFile); } } }
public static void createLogDir() { try { Files.createDirectories(Paths.get(Chatty.getDebugLogDirectory())); } catch (IOException ex) { Logger.getLogger(Logging.class.getName()).log(Level.SEVERE, null, ex); } }