List of usage examples for java.nio.file Path toString
String toString();
From source file:misc.FileHandler.java
/** * Returns the relative directory to the client's root directory containing * the access bundle for the given file name or <code>null</code>, if an * access bundle is not found.//from w ww .java2 s .c om * * @param clientRoot * the complete path to the client's root directory. Must exist. * @param fileName * a valid file name which may be inexistent. Must be relative to * <code>clientRoot</code>. * @return the relative directory to the client's root directory containing * the access bundle for the given file name or <code>null</code>, * if an access bundle is not found. */ public static Path getAccessBundleDirectory(Path clientRoot, Path fileName) { if ((clientRoot == null) || !Files.isDirectory(clientRoot)) { throw new IllegalArgumentException("clientRoot must be an existing directory!"); } if (!isFileName(fileName)) { throw new IllegalArgumentException("fileName must be a valid file name!"); } Path upperMostDirectory = FileHandler.getUpperMostDirectory(fileName); Path completeUpperMostDirectory = Paths.get(clientRoot.toString(), upperMostDirectory.toString()); if (!ROOT_PATH.equals(upperMostDirectory) && Files .exists(Paths.get(completeUpperMostDirectory.toString(), AccessBundle.ACCESS_BUNDLE_FILENAME))) { return upperMostDirectory; } else if (Files.exists(Paths.get(clientRoot.toString(), AccessBundle.ACCESS_BUNDLE_FILENAME))) { return ROOT_PATH; } else { return null; } }
From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java
/** * ???????????????true???./*from w w w. j a v a 2 s.c o m*/ * * @param key ? * @return ?????true */ @Override public boolean canLoad(String key, UrlTreeContext ctx) throws BadContentException { if (key == null) { return false; } if (!isValidFileName(key)) { return false; } String key2; if (key.equals("root")) { key2 = ""; } else { key2 = key; } Path f = this.generateFileObj(key2); logger.debug(f.toString() + ": canload called"); return Files.exists(f, LinkOption.NOFOLLOW_LINKS); }
From source file:logfile.LogfileStreamer.java
private void startElasticsearchIfNecessary() throws IOException { if (!"no".equals(System.getProperty("create.es.instance"))) { final Path tempDirectory = Files.createTempDirectory("usa-gov-logfile-parser"); System.out.println("Starting elasticsearch instance (data: " + tempDirectory + ")"); final Settings settings = Settings.settingsBuilder().put("cluster.name", clusterName) .put("path.home", tempDirectory.toString()).put("path.data", tempDirectory.toString()) .put(Node.HTTP_ENABLED, true).build(); NodeBuilder.nodeBuilder().settings(settings).node().start(); } else {/*from ww w . j a v a 2s .c o m*/ System.out.println("Not starting elasticsearch instance, please check if available at localhost:9200"); } }
From source file:com.romeikat.datamessie.core.base.util.FileUtil.java
public synchronized String createTargetDir() { try {/*w ww . j av a 2 s. c o m*/ final String dirName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss")); Path dir = Paths.get(exportDir, dirName); dir = getNonExisting(dir); Files.createDirectories(dir); return dir.toString(); } catch (final Exception e) { LOG.error("Could not create target directory", e); return null; } }
From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.internal.actions.Explode.java
private String stripLeadingFolders(String aName, int aLevels) { if (aLevels > 0) { Path p = Paths.get(aName); if (p.getNameCount() <= aLevels) { return null; } else {//from w w w . j a va2 s . co m p = p.subpath(aLevels, p.getNameCount()); aName = p.toString(); return aName; } } else { return aName; } }
From source file:io.github.mbarre.schemacrawler.tool.linter.BaseLintTest.java
protected List<LintWrapper> executeToJsonAndConvertToLintList(SchemaCrawlerOptions options, Connection connection) throws Exception { final Executable executable = new SchemaCrawlerExecutable("lint"); final Path linterConfigsFile = FileSystems.getDefault().getPath("", this.getClass().getClassLoader().getResource("schemacrawler-linter-configs-test.xml").getPath()); final LintOptionsBuilder optionsBuilder = new LintOptionsBuilder(); optionsBuilder.withLinterConfigs(linterConfigsFile.toString()); executable.setAdditionalConfiguration(optionsBuilder.toConfig()); Path out = Paths.get("target/test_" + this.getClass().getSimpleName() + ".json"); OutputOptions outputOptions = new OutputOptions(TextOutputFormat.json, out); outputOptions.setOutputFile(Paths.get("target/test_" + this.getClass().getSimpleName() + ".json")); executable.setOutputOptions(outputOptions); executable.setSchemaCrawlerOptions(options); executable.execute(connection);//from ww w. ja v a 2s .co m File output = new File(out.toString()); String data = IOUtils.toString(new FileInputStream(output)); Assert.assertNotNull(data); JSONObject json = new JSONObject(data.toString().substring(1, data.toString().length() - 2)); List<LintWrapper> lints = new ArrayList<>(); if (json.get("table_lints") instanceof JSONObject) { Assert.assertNotNull(json.getJSONObject("table_lints")); JSONArray jsonLints = json.getJSONObject("table_lints").getJSONArray("lints"); Assert.assertNotNull(jsonLints); if (options.getTableNamePattern() != null && !options.getTableNamePattern().isEmpty()) Assert.assertEquals(options.getTableNamePattern(), json.getJSONObject("table_lints").getString("name")); for (int i = 0; i < jsonLints.length(); i++) { if (!"databasechangelog".equals(json.getJSONObject("table_lints").getString("name")) && !"databasechangeloglock".equals(json.getJSONObject("table_lints").getString("name"))) lints.add(createLintWrapper(json.getJSONObject("table_lints").getString("name"), jsonLints.getJSONObject(i))); } } else { Assert.assertNotNull(json.getJSONArray("table_lints")); JSONArray jsonTableLints = json.getJSONArray("table_lints"); for (int i = 0; i < jsonTableLints.length(); i++) { JSONArray jsonLints = jsonTableLints.getJSONObject(i).getJSONArray("lints"); Assert.assertNotNull(jsonLints); if (options.getTableNamePattern() != null && !options.getTableNamePattern().isEmpty()) Assert.assertEquals(options.getTableNamePattern(), json.getJSONObject("table_lints").getString("name")); for (int j = 0; j < jsonLints.length(); j++) { if (!"databasechangelog".equals(jsonTableLints.getJSONObject(i).getString("name")) && !"databasechangeloglock".equals(jsonTableLints.getJSONObject(i).getString("name"))) lints.add(createLintWrapper(jsonTableLints.getJSONObject(i).getString("name"), jsonLints.getJSONObject(j))); } } } return lints; }
From source file:com.nextgenactionscript.vscode.project.ASConfigProjectConfigStrategy.java
public ProjectOptions getOptions() { changed = false;/* www . ja v a 2 s . com*/ if (asconfigPath == null) { return null; } File asconfigFile = asconfigPath.toFile(); if (!asconfigFile.exists()) { return null; } Path projectRoot = asconfigPath.getParent(); ProjectType type = ProjectType.APP; String config = null; String[] files = null; String additionalOptions = null; CompilerOptions compilerOptions = new CompilerOptions(); try (InputStream schemaInputStream = getClass().getResourceAsStream("/schemas/asconfig.schema.json")) { JsonSchemaFactory factory = new JsonSchemaFactory(); JsonSchema schema = factory.getSchema(schemaInputStream); String contents = FileUtils.readFileToString(asconfigFile); ObjectMapper mapper = new ObjectMapper(); JsonNode json = mapper.readTree(contents); Set<ValidationMessage> errors = schema.validate(json); if (!errors.isEmpty()) { System.err.println("Failed to validate asconfig.json."); for (ValidationMessage error : errors) { System.err.println(error.toString()); } return null; } else { if (json.has(ProjectOptions.TYPE)) //optional, defaults to "app" { String typeString = json.get(ProjectOptions.TYPE).asText(); type = ProjectType.fromToken(typeString); } config = json.get(ProjectOptions.CONFIG).asText(); if (json.has(ProjectOptions.FILES)) //optional { JsonNode jsonFiles = json.get(ProjectOptions.FILES); int fileCount = jsonFiles.size(); files = new String[fileCount]; for (int i = 0; i < fileCount; i++) { String pathString = jsonFiles.get(i).asText(); Path filePath = projectRoot.resolve(pathString); files[i] = filePath.toString(); } } if (json.has(ProjectOptions.COMPILER_OPTIONS)) //optional { JsonNode jsonCompilerOptions = json.get(ProjectOptions.COMPILER_OPTIONS); if (jsonCompilerOptions.has(CompilerOptions.DEBUG)) { compilerOptions.debug = jsonCompilerOptions.get(CompilerOptions.DEBUG).asBoolean(); } if (jsonCompilerOptions.has(CompilerOptions.DEFINE)) { HashMap<String, String> defines = new HashMap<>(); JsonNode jsonDefine = jsonCompilerOptions.get(CompilerOptions.DEFINE); for (int i = 0, count = jsonDefine.size(); i < count; i++) { JsonNode jsonNamespace = jsonDefine.get(i); String name = jsonNamespace.get(CompilerOptions.DEFINE_NAME).asText(); Object value = jsonNamespace.get(CompilerOptions.DEFINE_VALUE).asText(); if (value instanceof String) { value = "\"" + value + "\""; } defines.put(name, value.toString()); } compilerOptions.defines = defines; } if (jsonCompilerOptions.has(CompilerOptions.EXTERNAL_LIBRARY_PATH)) { JsonNode jsonExternalLibraryPath = jsonCompilerOptions .get(CompilerOptions.EXTERNAL_LIBRARY_PATH); ArrayList<File> externalLibraryPath = new ArrayList<>(); for (int i = 0, count = jsonExternalLibraryPath.size(); i < count; i++) { String pathString = jsonExternalLibraryPath.get(i).asText(); Path filePath = projectRoot.resolve(pathString); externalLibraryPath.add(filePath.toFile()); } compilerOptions.externalLibraryPath = externalLibraryPath; } if (jsonCompilerOptions.has(CompilerOptions.INCLUDE_CLASSES)) { JsonNode jsonIncludeClasses = jsonCompilerOptions.get(CompilerOptions.INCLUDE_CLASSES); ArrayList<String> includeClasses = new ArrayList<>(); for (int i = 0, count = jsonIncludeClasses.size(); i < count; i++) { String qualifiedName = jsonIncludeClasses.get(i).asText(); includeClasses.add(qualifiedName); } compilerOptions.includeClasses = includeClasses; } if (jsonCompilerOptions.has(CompilerOptions.INCLUDE_NAMESPACES)) { JsonNode jsonIncludeNamespaces = jsonCompilerOptions .get(CompilerOptions.INCLUDE_NAMESPACES); ArrayList<String> includeNamespaces = new ArrayList<>(); for (int i = 0, count = jsonIncludeNamespaces.size(); i < count; i++) { String namespaceURI = jsonIncludeNamespaces.get(i).asText(); includeNamespaces.add(namespaceURI); } compilerOptions.includeNamespaces = includeNamespaces; } if (jsonCompilerOptions.has(CompilerOptions.INCLUDE_SOURCES)) { JsonNode jsonIncludeSources = jsonCompilerOptions.get(CompilerOptions.INCLUDE_SOURCES); ArrayList<File> includeSources = new ArrayList<>(); for (int i = 0, count = jsonIncludeSources.size(); i < count; i++) { String pathString = jsonIncludeSources.get(i).asText(); Path filePath = projectRoot.resolve(pathString); includeSources.add(filePath.toFile()); } compilerOptions.includeSources = includeSources; } if (jsonCompilerOptions.has(CompilerOptions.JS_OUTPUT_TYPE)) { String jsonJSOutputType = jsonCompilerOptions.get(CompilerOptions.JS_OUTPUT_TYPE).asText(); compilerOptions.jsOutputType = jsonJSOutputType; } if (jsonCompilerOptions.has(CompilerOptions.NAMESPACE)) { JsonNode jsonLibraryPath = jsonCompilerOptions.get(CompilerOptions.NAMESPACE); ArrayList<MXMLNamespaceMapping> namespaceMappings = new ArrayList<>(); for (int i = 0, count = jsonLibraryPath.size(); i < count; i++) { JsonNode jsonNamespace = jsonLibraryPath.get(i); String uri = jsonNamespace.get(CompilerOptions.NAMESPACE_URI).asText(); String manifest = jsonNamespace.get(CompilerOptions.NAMESPACE_MANIFEST).asText(); MXMLNamespaceMapping mapping = new MXMLNamespaceMapping(uri, manifest); namespaceMappings.add(mapping); } compilerOptions.namespaceMappings = namespaceMappings; } if (jsonCompilerOptions.has(CompilerOptions.LIBRARY_PATH)) { JsonNode jsonLibraryPath = jsonCompilerOptions.get(CompilerOptions.LIBRARY_PATH); ArrayList<File> libraryPath = new ArrayList<>(); for (int i = 0, count = jsonLibraryPath.size(); i < count; i++) { String pathString = jsonLibraryPath.get(i).asText(); Path filePath = projectRoot.resolve(pathString); libraryPath.add(filePath.toFile()); } compilerOptions.libraryPath = libraryPath; } if (jsonCompilerOptions.has(CompilerOptions.SOURCE_PATH)) { JsonNode jsonSourcePath = jsonCompilerOptions.get(CompilerOptions.SOURCE_PATH); ArrayList<File> sourcePath = new ArrayList<>(); for (int i = 0, count = jsonSourcePath.size(); i < count; i++) { String pathString = jsonSourcePath.get(i).asText(); Path filePath = projectRoot.resolve(pathString); sourcePath.add(filePath.toFile()); } compilerOptions.sourcePath = sourcePath; } if (jsonCompilerOptions.has(CompilerOptions.WARNINGS)) { compilerOptions.warnings = jsonCompilerOptions.get(CompilerOptions.WARNINGS).asBoolean(); } } //these options are formatted as if sent in through the command line if (json.has(ProjectOptions.ADDITIONAL_OPTIONS)) //optional { additionalOptions = json.get(ProjectOptions.ADDITIONAL_OPTIONS).asText(); } } } catch (Exception e) { System.err.println("Failed to parse asconfig.json: " + e); e.printStackTrace(); return null; } //in a library project, the files field will be treated the same as the //include-sources compiler option if (type == ProjectType.LIB && files != null) { if (compilerOptions.includeSources == null) { compilerOptions.includeSources = new ArrayList<>(); } for (int i = 0, count = files.length; i < count; i++) { String filePath = files[i]; compilerOptions.includeSources.add(new File(filePath)); } files = null; } ProjectOptions options = new ProjectOptions(); options.type = type; options.config = config; options.files = files; options.compilerOptions = compilerOptions; options.additionalOptions = additionalOptions; return options; }
From source file:com.codealot.textstore.FileStore.java
/** * Create a FileStore based on the given directory. * /* w w w . j a v a 2s .com*/ * @param storeRoot * must be a directory */ public FileStore(final Path storeRoot) { Objects.requireNonNull(storeRoot, "Storage path not given."); if (!Files.isDirectory(storeRoot)) { throw new IllegalArgumentException("Path " + storeRoot + " is not a directory."); } this.storeRoot = storeRoot.toString(); }
From source file:misc.FileHandler.java
/** * Encrypts the given file using the newest key found in the respective * access bundle and protects the metadata with a message authentication * code using the respective integrity key, if desired. Otherwise, the file * stays as is and no message authentication code is computed. * /* w w w . ja va 2 s . c om*/ * @param prefix * the path to the client's root directory. May not be * <code>null</code>. * @param file * the relative path to the client's root directory of the * original file to protect. May not be <code>null</code>. * @param isDiff * <code>true</code>, if the <code>file</code> is a binary diff. * </code>false</code>, otherwise. * @param diff * the complete path to the diff file. If <code>isDiff</code> is * <code>true</code>, this parameter may not be <code>null</code> * . * @return the complete path of the file, the metadata of the file as well * as the MAC of the protected data (if applicable). * <code>null</code>, if an error occurs (for example, if the access * bundle is not found). */ public static Triple<Path, ProtectedData, byte[]> getData(Path prefix, Path file, boolean isDiff, Path diff) { if (prefix == null) { throw new NullPointerException("prefix may not be null!"); } if (file == null) { throw new NullPointerException("file may not be null!"); } if (isDiff && (diff == null)) { throw new IllegalArgumentException("if isDiff is true, diff must not be null!"); } Path completePath = isDiff ? diff : Paths.get(prefix.toString(), file.toString()); if (!Files.isReadable(completePath)) { Logger.logError(String.format("file %s must exist and be readable!", completePath.toString())); return null; } Triple<Path, ProtectedData, byte[]> result = null; Path accessBundleDirectory = FileHandler.getAccessBundleDirectory(prefix, file); AccessBundle bundle = FileHandler.getAccessBundle(prefix, accessBundleDirectory); if (bundle != null) { if ((bundle.getHighestContentKey() != null)) { PreparationProvider provider = PreparationProviderFactory.getInstance( bundle.getHighestContentKey().getAlgorithm(), bundle.getHighestIntegrityKey().getAlgorithm()); result = provider.prepareSend(completePath, bundle.getHighestContentKey(), bundle.getHighestIntegrityKey(), isDiff); } else if ((bundle.getHighestContentKey() == null) && (bundle.getHighestIntegrityKey() == null)) { PreparationProvider provider = PreparationProviderFactory.getInstance(null, null); result = provider.prepareSend(completePath, null, null, isDiff); } else { Logger.logError(String.format("Invalid access bundle in %s", accessBundleDirectory.toString())); } } else { Logger.logError( String.format("No or invalid access bundle present in %s", accessBundleDirectory.toString())); } return result; }
From source file:au.org.ands.vocabs.toolkit.provider.transform.PropertyRewriterTransformProvider.java
@Override public final boolean transform(final TaskInfo taskInfo, final JsonNode subtask, final HashMap<String, String> results) { // Prepare for rewriting. if (!loadRewriteMap()) { results.put(TaskStatus.ERROR, "PropertyRewriter unable to load rewrite map"); return false; }// w ww . j a va2 s . co m Path originalHarvestdir = Paths.get(ToolkitFileUtils.getTaskHarvestOutputPath(taskInfo)); // Use this transform name and the task ID to construct // the path names. String transformName = "PropertyRewriter_" + taskInfo.getTask().getId(); String transformOutputDir = ToolkitFileUtils.getTaskTransformTemporaryOutputPath(taskInfo, transformName); Path transformOutputDirPath = Paths.get(transformOutputDir); try { ToolkitFileUtils.requireEmptyDirectory(transformOutputDir); } catch (IOException ex) { results.put(TaskStatus.EXCEPTION, "Exception in PropertyRewriter while cleaning old " + "transform output directory"); logger.error("Exception in PropertyRewriter while cleaning old " + "transform output directory: ", ex); return false; } // Open the harvest directory ... try (DirectoryStream<Path> stream = Files.newDirectoryStream(originalHarvestdir)) { // ... and iterate over every file in the harvest directory. for (Path entry : stream) { // First, parse the file into a model and do rewriting. Model model = new LinkedHashModel(); RDFFormat format = Rio.getParserFormatForFileName(entry.toString()); RDFParser rdfParser = Rio.createParser(format); ConceptHandler conceptHandler = new ConceptHandler(metadataRewriteConf, model); rdfParser.setRDFHandler(conceptHandler); FileInputStream is = new FileInputStream(entry.toString()); logger.debug("Reading RDF:" + entry.toString()); rdfParser.parse(is, entry.toString()); // And now serialize the result. String resultFileName = transformOutputDirPath.resolve(entry.getFileName()).toString(); FileOutputStream out = new FileOutputStream(resultFileName); // Write in the same format we read. Rio.write(model, out, format); out.close(); } } catch (DirectoryIteratorException | IOException | RDFParseException | RDFHandlerException | UnsupportedRDFormatException ex) { results.put(TaskStatus.EXCEPTION, "Exception in PropertyRewriter while Parsing RDF"); logger.error("Exception in PropertyRewriter while Parsing RDF:", ex); return false; } // Done rewriting, and was successful. Replace the old // harvest with the transformed files. if (!ToolkitFileUtils.renameTransformTemporaryOutputPath(taskInfo, transformName)) { results.put(TaskStatus.ERROR, "Error in PropertyRewriter when renaming output " + "directory"); logger.error("Error in PropertyRewriter when renaming output " + "directory"); return false; } return true; }