List of usage examples for java.nio.file FileSystems getDefault
public static FileSystem getDefault()
From source file:com.spectralogic.ds3cli.Main.java
private static void configureLogging(final Level consoleLevel, final Level fileLevel) { final LoggerContext loggerContext = LOG.getLoggerContext(); loggerContext.reset();//from w w w .j a v a2 s.c om // set root log to the most permissive filter (affects performance big time (JAVACLI-90)) final int lowestLogLevel = Math.min(consoleLevel.toInt(), fileLevel.toInt()); LOG.setLevel(Level.toLevel(lowestLogLevel)); if (!consoleLevel.equals(Level.OFF)) { // create and add console appender final PatternLayoutEncoder consoleEncoder = new PatternLayoutEncoder(); consoleEncoder.setContext(loggerContext); consoleEncoder.setPattern(LOG_FORMAT_PATTERN); consoleEncoder.start(); final ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>(); consoleAppender.setContext(loggerContext); consoleAppender.setName("STDOUT"); consoleAppender.setEncoder(consoleEncoder); final ThresholdFilter consoleFilter = new ThresholdFilter(); consoleFilter.setLevel(consoleLevel.levelStr); consoleFilter.setName(consoleLevel.levelStr); consoleFilter.start(); consoleAppender.addFilter(consoleFilter); consoleAppender.start(); LOG.addAppender(consoleAppender); } if (!fileLevel.equals(Level.OFF)) { // create file appender only if needed. // if done in the xml, it will create an empty file final RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<>(); final FixedWindowRollingPolicy sizeBasedRollingPolicy = new FixedWindowRollingPolicy(); final SizeBasedTriggeringPolicy<Object> sizeBasedTriggeringPolicy = new SizeBasedTriggeringPolicy<>(); fileAppender.setContext(loggerContext); sizeBasedTriggeringPolicy.setContext(loggerContext); sizeBasedRollingPolicy.setContext(loggerContext); fileAppender.setRollingPolicy(sizeBasedRollingPolicy); sizeBasedRollingPolicy.setParent(fileAppender); sizeBasedRollingPolicy.setMinIndex(0); sizeBasedRollingPolicy.setMaxIndex(99); final Path logFilePath = FileSystems.getDefault().getPath(LOG_DIR, LOG_FILE_NAME); fileAppender.setFile(logFilePath.toString()); sizeBasedRollingPolicy.setFileNamePattern(LOG_DIR + LOG_ARCHIVE_FILE_PATTERN); sizeBasedRollingPolicy.start(); sizeBasedTriggeringPolicy.setMaxFileSize("10MB"); sizeBasedTriggeringPolicy.start(); final PatternLayoutEncoder fileEncoder = new PatternLayoutEncoder(); fileEncoder.setContext(loggerContext); fileEncoder.setPattern(LOG_FORMAT_PATTERN); fileEncoder.start(); fileAppender.setTriggeringPolicy((TriggeringPolicy) sizeBasedTriggeringPolicy); fileAppender.setRollingPolicy(sizeBasedRollingPolicy); fileAppender.setEncoder(fileEncoder); fileAppender.setName("LOGFILE"); sizeBasedRollingPolicy.start(); final ThresholdFilter fileFilter = new ThresholdFilter(); fileFilter.setLevel(fileLevel.levelStr); fileFilter.setName(fileLevel.levelStr); fileFilter.start(); fileAppender.addFilter(fileFilter); LOG.addAppender((Appender) fileAppender); fileAppender.start(); } }
From source file:io.stallion.dataAccess.file.FilePersisterBase.java
@Override public List<T> fetchAll() { File target = new File(Settings.instance().getTargetFolder()); if (!target.isDirectory()) { if (getItemController().isWritable()) { target.mkdirs();/*w w w . java 2s . c om*/ } else { throw new ConfigException(String.format( "The JSON bucket %s (path %s) is read-only, but does not exist in the file system. Either create the folder, make it writable, or remove it from the configuration.", getItemController().getBucket(), getBucketFolderPath())); } } TreeVisitor visitor = new TreeVisitor(); Path folderPath = FileSystems.getDefault().getPath(getBucketFolderPath()); try { Files.walkFileTree(folderPath, visitor); } catch (IOException e) { throw new RuntimeException(e); } List<T> objects = new ArrayList<>(); for (Path path : visitor.getPaths()) { if (!matchesExtension(path.toString())) { continue; } if (path.toString().contains(".#")) { continue; } if (path.getFileName().startsWith(".")) { continue; } T o = fetchOne(path.toString()); if (o != null) { objects.add(o); } } objects.sort(new PropertyComparator<T>(sortField)); if (sortDirection.toLowerCase().equals("desc")) { Collections.reverse(objects); } return objects; }
From source file:com.temenos.interaction.loader.detector.DirectoryChangeActionNotifier.java
protected void initWatchers(Collection<? extends File> resources) { if (scheduledTask != null) { scheduledTask.cancel(true);// ww w . j a v a 2s .c o m } if (resources == null || resources.isEmpty() || getListeners() == null || getListeners().isEmpty()) { return; } try { WatchService ws = FileSystems.getDefault().newWatchService(); for (File file : resources) { Path filePath = Paths.get(file.toURI()); filePath.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); } watchService = ws; scheduledTask = executorService.scheduleWithFixedDelay( new ListenerNotificationTask(watchService, getListeners(), getIntervalSeconds() * 1000), 5, getIntervalSeconds(), TimeUnit.SECONDS); } catch (IOException ex) { throw new RuntimeException("Error configuring directory change listener - unexpected IOException", ex); } }
From source file:com.bc.fiduceo.post.PostProcessingTool_IOTest.java
@Test public void testInitialisation() throws Exception { final Options options = PostProcessingTool.getOptions(); final PosixParser parser = new PosixParser(); final CommandLine commandLine = parser.parse(options, new String[] { "-j", processingConfigName, "-i", "/mmd_files", "-start", "2011-123", "-end", "2011-124", "-c", configDir.getPath() }); final FileWriter fileWriter = new FileWriter(new File(configDir, "system-config.xml")); fileWriter.write("<system-config></system-config>"); fileWriter.close();/*from w w w .j a v a 2s . co m*/ final PostProcessingContext context = PostProcessingTool.initializeContext(commandLine); final String separator = FileSystems.getDefault().getSeparator(); assertEquals(separator + "mmd_files", context.getMmdInputDirectory().toString()); assertEquals("03-May-2011 00:00:00", ProductData.UTC.createDateFormat().format(context.getStartDate())); assertEquals("04-May-2011 23:59:59", ProductData.UTC.createDateFormat().format(context.getEndDate())); final SystemConfig sysConfig = context.getSystemConfig(); assertNotNull(sysConfig); assertNull(sysConfig.getArchiveConfig()); final PostProcessingConfig config = context.getProcessingConfig(); assertNotNull(config); final List<Element> postProcessingElements = config.getPostProcessingElements(); assertNotNull(postProcessingElements); assertEquals("java.util.Collections$UnmodifiableList", postProcessingElements.getClass().getTypeName()); assertEquals(1, postProcessingElements.size()); assertEquals(TAG_NAME_SPHERICAL_DISTANCE, postProcessingElements.get(0).getName()); }
From source file:org.kitodo.production.services.file.FileService.java
/** * Creates a MetaDirectory./*from w ww.j a v a 2 s . c o m*/ * * @param parentFolderUri * The URI, where the * @param directoryName * the name of the directory * @return true or false * @throws IOException * an IOException */ URI createMetaDirectory(URI parentFolderUri, String directoryName) throws IOException { if (!fileExist(parentFolderUri.resolve(directoryName))) { CommandService commandService = ServiceManager.getCommandService(); String path = FileSystems.getDefault() .getPath(ConfigCore.getKitodoDataDirectory(), parentFolderUri.getRawPath(), directoryName) .normalize().toAbsolutePath().toString(); List<String> commandParameter = Collections.singletonList(path); File script = new File(ConfigCore.getParameter(ParameterCore.SCRIPT_CREATE_DIR_META)); CommandResult commandResult = commandService.runCommand(script, commandParameter); if (!commandResult.isSuccessful()) { String message = MessageFormat.format( "Could not create directory {0} in {1}! No new directory was created", directoryName, parentFolderUri.getPath()); logger.warn(message); throw new IOException(message); } } else { logger.info("Metadata directory: {} already existed! No new directory was created", directoryName); } return URI.create(parentFolderUri.getPath() + '/' + directoryName); }
From source file:org.ng200.openolympus.services.StorageService.java
public Path getTaskJudgeFile(final Task task) { return FileSystems.getDefault().getPath(this.storagePath, "tasks", "judges", task.getTaskLocation()); }
From source file:org.discosync.CreateSyncPack.java
/** * Create a syncpack in syncPackDir, using the fileOperations and taking the files from baseDir. *///from w w w . j av a2 s . c o m protected void createSyncPack(String baseDir, List<FileListEntry> fileOperations, String syncPackDir) throws SQLException, IOException { Path syncPackDirPath = Paths.get(syncPackDir); Files.createDirectories(syncPackDirPath); // store file operations to database File fileOpDbFile = new File(syncPackDirPath.toFile(), "fileoperations"); FileOperationDatabase db = new FileOperationDatabase(fileOpDbFile.getAbsolutePath()); db.open(); db.createFileOperationTable(); db.insertFileOperations(fileOperations); db.close(); // delete 'files' directory in syncpack and create the directory again Path targetBaseDir = Paths.get(syncPackDirPath.toAbsolutePath().toString(), "files"); Utils.deleteDirectoryRecursively(targetBaseDir); if (!Files.exists(targetBaseDir)) { Files.createDirectories(targetBaseDir); } String targetBaseDirStr = targetBaseDir.toAbsolutePath().toString(); // copy all files that need a COPY or REPLACE to the syncpack for (FileListEntry e : fileOperations) { if (e.getOperation() != FileOperations.COPY && e.getOperation() != FileOperations.REPLACE) { continue; } // don't copy directories that should be created on target if (e.isDirectory()) { continue; } String path = e.getPath(); Path sourcePath = FileSystems.getDefault().getPath(baseDir, path); Path targetPath = Paths.get(targetBaseDirStr, path); if (!Files.exists(targetPath.getParent())) { Files.createDirectories(targetPath.getParent()); } Files.copy(sourcePath, targetPath); } }
From source file:com.spotify.helios.servicescommon.PersistentAtomicReference.java
public static <T> PersistentAtomicReference<T> create(final String filename, final JavaType javaType, final Supplier<? extends T> initialValue) throws IOException, InterruptedException { return create(FileSystems.getDefault().getPath(filename), javaType, initialValue); }
From source file:org.evosuite.junit.CoverageAnalysisWithRefectionSystemTest.java
@Test public void testGetAllInterfaces() throws IOException { EvoSuite evosuite = new EvoSuite(); String targetClass = ClassWithPrivateInterfaces.class.getCanonicalName(); String testClass = ClassWithPrivateInterfacesTest.class.getCanonicalName(); Properties.TARGET_CLASS = targetClass; Properties.CRITERION = new Properties.Criterion[] { Properties.Criterion.LINE }; Properties.OUTPUT_VARIABLES = RuntimeVariable.Total_Goals + "," + RuntimeVariable.LineCoverage; Properties.STATISTICS_BACKEND = StatisticsBackend.CSV; Properties.COVERAGE_MATRIX = true; String[] command = new String[] { "-class", targetClass, "-Djunit=" + testClass, "-measureCoverage" }; Object statistics = evosuite.parseCommandLine(command); Assert.assertNotNull(statistics);// www . j av a 2s . c om // Assert coverage String statistics_file = System.getProperty("user.dir") + File.separator + Properties.REPORT_DIR + File.separator + "statistics.csv"; System.out.println("statistics_file: " + statistics_file); CSVReader reader = new CSVReader(new FileReader(statistics_file)); List<String[]> rows = reader.readAll(); assertTrue(rows.size() == 2); reader.close(); assertEquals("14", CsvJUnitData.getValue(rows, RuntimeVariable.Total_Goals.name())); assertEquals(0.93, Double.valueOf(CsvJUnitData.getValue(rows, RuntimeVariable.LineCoverage.name())), 0.01); // Assert that all test cases have passed String matrix_file = System.getProperty("user.dir") + File.separator + Properties.REPORT_DIR + File.separator + "data" + File.separator + targetClass + File.separator + Properties.Criterion.LINE.name() + File.separator + Properties.COVERAGE_MATRIX_FILENAME; System.out.println("matrix_file: " + matrix_file); List<String> lines = Files.readAllLines(FileSystems.getDefault().getPath(matrix_file)); assertTrue(lines.size() == 1); assertEquals(13 + 1 + 1, lines.get(0).replace(" ", "").length()); // number of goals + test result ('+' pass, '-' fail) assertTrue(lines.get(0).replace(" ", "").endsWith("+")); }