List of usage examples for java.nio.file Path resolve
default Path resolve(String other)
From source file:ddf.test.itests.platform.TestConfiguration.java
private Path getExportSubDirectory(Path exportDirectory, String... paths) { Path directory = exportDirectory.resolve("etc"); for (String path : paths) { directory = directory.resolve(path); }// ww w . j av a 2 s . c o m return directory; }
From source file:org.fao.geonet.api.records.formatters.FormatterApi.java
public synchronized Element getPluginLocResources(final ServiceContext context, Path formatDir) throws Exception { final String formatDirPath = formatDir.toString(); Element allLangResources = this.pluginLocs.get(formatDirPath); if (isDevMode(context) || allLangResources == null) { allLangResources = new Element("loc"); Path baseLoc = formatDir.resolve("loc"); if (Files.exists(baseLoc)) { final Element finalAllLangResources = allLangResources; Files.walkFileTree(baseLoc, new SimpleFileVisitor<Path>() { private void addTranslations(String locDirName, Element fileElements) { if (locDirName != null && !locDirName.isEmpty()) { Element resources = finalAllLangResources.getChild(locDirName); if (resources == null) { resources = new Element(locDirName); finalAllLangResources.addContent(resources); }// www. j a v a 2 s .co m resources.addContent(fileElements); } } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().toLowerCase().endsWith(".xml")) { try { final Element fileElements = Xml.loadFile(file); final String fileName = getNameWithoutExtension(file.getFileName().toString()); fileElements.setName(fileName); final String locDirName = getNameWithoutExtension( file.getParent().getFileName().toString()); addTranslations(locDirName, fileElements); } catch (JDOMException e) { throw new RuntimeException(e); } } else if (file.getFileName().toString().toLowerCase().endsWith(".json")) { try { final String fileName = getNameWithoutExtension(file.getFileName().toString()); final String[] nameParts = fileName.split("-", 2); IsoLanguagesMapper isoLanguagesMapper = context.getBean(IsoLanguagesMapper.class); String lang = isoLanguagesMapper.iso639_1_to_iso639_2(nameParts[0].toLowerCase(), nameParts[0]); final JSONObject json = new JSONObject( new String(Files.readAllBytes(file), Constants.CHARSET)); Element fileElements = new Element(nameParts[1]); final Iterator keys = json.keys(); while (keys.hasNext()) { String key = (String) keys.next(); fileElements.addContent(new Element(key).setText(json.getString(key))); } addTranslations(lang, fileElements); } catch (JSONException e) { throw new RuntimeException(e); } } return super.visitFile(file, attrs); } }); } this.pluginLocs.put(formatDirPath, allLangResources); } return allLangResources; }
From source file:eu.itesla_project.eurostag.EurostagImpactAnalysis.java
private void readSecurityIndexes(List<Contingency> contingencies, Path workingDir, ImpactAnalysisResult result) throws IOException { long start = System.currentTimeMillis(); int files = 0; for (int i = 0; i < contingencies.size(); i++) { Contingency contingency = contingencies.get(i); for (String securityIndexFileName : Arrays.asList(TSO_LIMITS_SECURITY_INDEX_FILE_NAME, WP43_SMALLSIGNAL_SECURITY_INDEX_FILE_NAME, WP43_TRANSIENT_SECURITY_INDEX_FILE_NAME, WP43_OVERLOAD_SECURITY_INDEX_FILE_NAME, WP43_UNDEROVERVOLTAGE_SECURITY_INDEX_FILE_NAME)) { Path file = workingDir.resolve( securityIndexFileName.replace(Command.EXECUTION_NUMBER_PATTERN, Integer.toString(i))); if (Files.exists(file)) { try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { for (SecurityIndex index : SecurityIndexParser.fromXml(contingency.getId(), reader)) { result.addSecurityIndex(index); }//from ww w . j a v a2 s .c o m } files++; } } // also scan errors in output EurostagUtil.searchErrorMessage( workingDir.resolve( FAULT_OUT_GZ_FILE_NAME.replace(Command.EXECUTION_NUMBER_PATTERN, Integer.toString(i))), result.getMetrics(), i); } LOGGER.trace("{} security indexes files read in {} ms", files, (System.currentTimeMillis() - start)); }
From source file:com.c4om.autoconf.ulysses.configanalyzer.configurationextractor.LocalCopyConfigurationsExtractor.java
/** * This method performs the extraction. * The context must contain: /*from www .j a v a 2 s . c om*/ * <ul> * <li>One or more {@link ConfigureAppsTarget} returned by {@link ConfigurationAnalysisContext#getInputTargets()}. * All the referenced {@link Application} must return "file://" URIs at {@link Application#getConfigurationURIs()}.</li> * <li>An {@link Environment} object returned by {@link ConfigurationAnalysisContext#getInputEnvironment()}, from which * the configuration of the runtime where all the referenced applications are run.</li> * </ul> * @see com.c4om.autoconf.ulysses.interfaces.configanalyzer.configurationextractor.ConfigurationsExtractor#extractConfigurations(com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.datastructures.ConfigurationAnalysisContext) */ @Override public void extractConfigurations(ConfigurationAnalysisContext context) throws ConfigurationExtractionException { try { Path tempFolderPath = Files.createTempDirectory("ConfigurationAnalyzer"); for (Target currentTarget : context.getInputTargets().values()) { if (!(currentTarget instanceof ConfigureAppsTarget)) { continue; } Properties configurationAnalyzerSettings = context.getConfigurationAnalyzerSettings(); String runtimeConfigurationDirName = configurationAnalyzerSettings .getProperty(PROPERTY_KEY_RUNTIME_CONFIGURATION_FILENAME); if (runtimeConfigurationDirName == null) { throw new ConfigurationExtractionException( "Property '" + PROPERTY_KEY_RUNTIME_CONFIGURATION_FILENAME + "' not found"); } ConfigureAppsTarget currentConfigureAppsTarget = (ConfigureAppsTarget) currentTarget; for (String appId : currentConfigureAppsTarget.getParameters().keySet()) { Path subfolderForApp = tempFolderPath.resolve(Paths.get(appId)); List<File> copiedFiles = new ArrayList<>(); Files.createDirectory(subfolderForApp); //We copy the application configuration files to the root of the directory. //We also copy the runtime configuration. Application currentApplication = (Application) currentConfigureAppsTarget.getParameters() .get(appId); for (URI configurationURI : currentApplication.getConfigurationURIs()) { //TODO: Let other configuration URIs live, specially, SVN-based ones, which should be extracted by other extractors. This would require some refactoring. if (!configurationURI.getScheme().equalsIgnoreCase("file")) { throw new ConfigurationExtractionException( "URI '" + configurationURI.toString() + "' does not have a 'file' scheme"); } Path configurationPath = Paths.get(configurationURI); Path configurationPathName = configurationPath.getFileName(); if (configurationPathName.toString().equals(runtimeConfigurationDirName)) { throw new ConfigurationExtractionException( "One of the application configuration files has the same name than the runtime configuration folder ('" + runtimeConfigurationDirName + "')"); } Path destinationConfigurationPath = Files.copy(configurationPath, subfolderForApp.resolve(configurationPathName), REPLACE_EXISTING); File destinationConfigurationFile = destinationConfigurationPath.toFile(); copiedFiles.add(destinationConfigurationFile); } File runtimeConfigurationDirectory = new File( context.getInputEnvironment().getApplicationConfigurations().get(appId)); File destinationRuntimeConfigurationDirectory = subfolderForApp .resolve(runtimeConfigurationDirName).toFile(); FileUtils.copyDirectory(runtimeConfigurationDirectory, destinationRuntimeConfigurationDirectory); copiedFiles.add(destinationRuntimeConfigurationDirectory); ExtractedConfiguration<File> extractedConfiguration = new FileExtractedConfiguration(appId, currentTarget, copiedFiles); context.getExtractedConfigurations().add(extractedConfiguration); } } } catch (IOException e) { throw new ConfigurationExtractionException(e); } }
From source file:io.github.swagger2markup.extensions.DynamicDocumentExtensionTest.java
@Test public void testSwagger2MarkdownExtensions() throws IOException, URISyntaxException { //Given//from w ww.j a va 2 s.c o m Path file = Paths .get(DynamicDocumentExtensionTest.class.getResource("/yaml/swagger_petstore.yaml").toURI()); Path outputDirectory = Paths.get("build/test/markdown/generated"); FileUtils.deleteQuietly(outputDirectory.toFile()); //When Properties properties = new Properties(); properties .load(DynamicDocumentExtensionTest.class.getResourceAsStream("/config/markdown/config.properties")); Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder(properties) .withMarkupLanguage(MarkupLanguage.MARKDOWN).build(); Swagger2MarkupExtensionRegistry registry = new Swagger2MarkupExtensionRegistryBuilder() //.withDefinitionsDocumentExtension(new DynamicDefinitionsDocumentExtension(Paths.get("src/test/resources/docs/markdown/extensions"))) //.withPathsDocumentExtension(new DynamicPathsDocumentExtension(Paths.get("src/test/resources/docs/markdown/extensions"))) .build(); Swagger2MarkupConverter.from(file).withConfig(config).withExtensionRegistry(registry).build() .toFolder(outputDirectory); //Then assertThat(new String(Files.readAllBytes(outputDirectory.resolve("paths.md")))) .contains("Pet update request extension"); assertThat(new String(Files.readAllBytes(outputDirectory.resolve("definitions.md")))) .contains("Pet extension"); }
From source file:com.nartex.RichFileManager.java
@Override public JSONObject add() { JSONObject fileInfo = new JSONObject(); Iterator<FileItem> it = this.files.iterator(); String mode = ""; String currentPath = ""; boolean error = false; long size = 0; if (!it.hasNext()) { fileInfo = this.uploadError(lang("INVALID_FILE_UPLOAD")); } else {/*from ww w.j a va2 s . c o m*/ String allowed[] = { ".", "-" }; String fileName = ""; FileItem targetItem = null; try { while (it.hasNext()) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("mode")) { mode = item.getString(); // v1.0.6 renamed mode add to upload if (!mode.equals("upload") && !mode.equals("add") && !mode.equals("replace")) { //this.error(lang("INVALID_FILE_UPLOAD")); } } else if (item.getFieldName().equals("currentpath")) { currentPath = item.getString(); } else if (item.getFieldName().equals("newfilepath")) { currentPath = item.getString(); } } else if (item.getFieldName().equals("files")) { // replace //replace= true; size = item.getSize(); targetItem = item; // v1.0.6 renamed mode add to upload if (mode.equals("add") || mode.equals("upload")) { fileName = item.getName(); // set fileName } } else if (item.getFieldName().equals("newfile")) { fileName = item.getName(); // strip possible directory (IE) int pos = fileName.lastIndexOf(File.separator); if (pos > 0) { fileName = fileName.substring(pos + 1); } size = item.getSize(); targetItem = item; } } if (!error) { if (mode.equals("replace")) { String tmp[] = currentPath.split("/"); fileName = tmp[tmp.length - 1]; int pos = fileName.lastIndexOf(File.separator); if (pos > 0) fileName = fileName.substring(pos + 1); if (fileName != null) { currentPath = currentPath.replace(fileName, ""); currentPath = currentPath.replace("//", "/"); } } else { if (!isImage(fileName) && (config.getProperty("upload-imagesonly") != null && config.getProperty("upload-imagesonly").equals("true") || this.params.get("type") != null && this.params.get("type").equals("Image"))) { fileInfo = this.uploadError(lang("UPLOAD_IMAGES_ONLY")); error = true; } LinkedHashMap<String, String> strList = new LinkedHashMap<String, String>(); strList.put("fileName", fileName); fileName = cleanString(strList, allowed).get("fileName"); } long maxSize = 0; if (config.getProperty("upload-size") != null) { maxSize = Integer.parseInt(config.getProperty("upload-size")); if (maxSize != 0 && size > (maxSize * 1024 * 1024)) { fileInfo = this.uploadError(sprintf(lang("UPLOAD_FILES_SMALLER_THAN"), maxSize + "Mb")); error = true; } } if (!error) { currentPath = cleanPreview(currentPath.replaceFirst("^/", ""));// relative Path path = currentPath.equals("") ? this.documentRoot : this.documentRoot.resolve(currentPath); if (config.getProperty("upload-overwrite").toLowerCase().equals("false")) { fileName = this.checkFilename(path.toString(), fileName, 0); } if (mode.equals("replace")) { File saveTo = path.resolve(fileName).toFile(); targetItem.write(saveTo); log.info("saved " + saveTo); } else { fileName = fileName.replace("//", "/").replaceFirst("^/", "");// relative File saveTo = path.resolve(fileName).toFile(); targetItem.write(saveTo); log.info("saved " + saveTo); } fileInfo.put("Path", getPreviewFolder() + currentPath); fileInfo.put("Name", fileName); fileInfo.put("Error", ""); fileInfo.put("Code", 0); } } } catch (Exception e) { fileInfo = this.uploadError(lang("INVALID_FILE_UPLOAD")); } } return fileInfo; }
From source file:fr.duminy.jbackup.core.archive.Decompressor.java
public void decompress(Path archive, Path targetDirectory, TaskListener listener, Cancellable cancellable) throws ArchiveException { if (listener != null) { try {//from w w w .jav a 2s . c om listener.totalSizeComputed(Files.size(archive)); } catch (IOException ioe) { throw new ArchiveException(ioe); } } targetDirectory = (targetDirectory == null) ? Paths.get(".") : targetDirectory; if (!Files.exists(targetDirectory)) { throw new IllegalArgumentException( String.format("The target directory '%s' doesn't exist.", targetDirectory)); } MutableLong processedSize = new MutableLong(); try (InputStream archiveStream = Files.newInputStream(archive); ArchiveInputStream input = factory.create(archiveStream)) { ArchiveInputStream.Entry entry = getNextEntryIfNotCancelled(input, cancellable); while (entry != null) { InputStream entryStream = createCountingInputStream(listener, processedSize, entry.getInput()); try { Path file = targetDirectory.resolve(entry.getName()); Files.createDirectories(file.getParent()); Files.copy(entryStream, file); } finally { entry.close(); } entry = getNextEntryIfNotCancelled(input, cancellable); } } catch (IOException e) { throw new ArchiveException(e); } catch (Exception e) { throw new ArchiveException(e); } }
From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java
@Test public void moveChildrenMergesOneDirectoryIntoAnother() throws IOException { Path srcDir = tmp.newFolder("dir1"); Files.write(tmp.newFile("dir1/file1"), "new file 1".getBytes(Charsets.UTF_8)); tmp.newFolder("dir1/subdir1"); Files.write(tmp.newFile("dir1/subdir1/file2"), "new file 2".getBytes(Charsets.UTF_8)); tmp.newFolder("dir1/subdir1/subdir2"); Files.write(tmp.newFile("dir1/subdir1/subdir2/file3"), "new file 3".getBytes(Charsets.UTF_8)); tmp.newFolder("dir1/subdir1/subdir2/subdir3"); tmp.newFolder("dir2"); Path destRoot = tmp.newFolder("dir2/dir3"); Files.write(tmp.newFile("dir2/dir3/file1"), "old file 1".getBytes(Charsets.UTF_8)); Files.write(tmp.newFile("dir2/dir3/file1_1"), "old file 1_1".getBytes(Charsets.UTF_8)); tmp.newFolder("dir2/dir3/dir4"); tmp.newFolder("dir2/dir3/subdir1"); filesystem.mergeChildren(Paths.get("dir1"), Paths.get("dir2/dir3"), StandardCopyOption.REPLACE_EXISTING); assertTrue(Files.isDirectory(srcDir)); assertEquals("new file 1", Files.readAllLines(destRoot.resolve("file1")).get(0)); assertEquals("old file 1_1", Files.readAllLines(destRoot.resolve("file1_1")).get(0)); assertTrue(Files.isDirectory(destRoot.resolve("dir4"))); assertTrue(Files.isDirectory(destRoot.resolve("subdir1"))); assertEquals("new file 2", Files.readAllLines(destRoot.resolve("subdir1").resolve("file2")).get(0)); assertTrue(Files.isDirectory(destRoot.resolve("subdir1").resolve("subdir2"))); assertEquals("new file 3", Files.readAllLines(destRoot.resolve("subdir1").resolve("subdir2").resolve("file3")).get(0)); assertTrue(Files.isDirectory(destRoot.resolve("subdir1").resolve("subdir2").resolve("subdir3"))); assertFalse(Files.exists(srcDir.resolve("subdir1"))); assertFalse(Files.exists(srcDir.resolve("file1"))); }
From source file:eu.itesla_project.eurostag.EurostagExportTool.java
@Override public void run(CommandLine line) throws Exception { ComponentDefaultConfig defaultConfig = ComponentDefaultConfig.load(); EurostagConfig eurostagConfig = EurostagConfig.load(); Path caseFile = Paths.get(line.getOptionValue("case-file")); Path outputDir = Paths.get(line.getOptionValue("output-dir")); if (!Files.isDirectory(outputDir)) { throw new RuntimeException(outputDir + " is not a directory"); }/*from www . j a v a 2s .c om*/ DynamicDatabaseClient ddbClient = new IIDMDynamicDatabaseFactory().create(eurostagConfig.isDdbCaching()); System.out.println("loading case..."); // load network Network network = Importers.loadNetwork(caseFile); if (network == null) { throw new RuntimeException("Case '" + caseFile + "' not found"); } network.getStateManager().allowStateMultiThreadAccess(true); System.out.println("exporting ech..."); // export .ech and dictionary EurostagEchExportConfig exportConfig = new EurostagEchExportConfig(); BranchParallelIndexes parallelIndexes = BranchParallelIndexes.build(network, exportConfig); EurostagDictionary dictionary = EurostagDictionary.create(network, parallelIndexes, exportConfig); new EurostagEchExport(network, exportConfig, parallelIndexes, dictionary) .write(outputDir.resolve("sim.ech")); try (Writer writer = Files.newBufferedWriter(outputDir.resolve("sim.ech"), StandardCharsets.UTF_8)) { EsgGeneralParameters parameters = new EsgGeneralParameters(); parameters.setTransformerVoltageControl(false); parameters.setSvcVoltageControl(false); EsgNetwork networkEch = new EurostagEchExport(network, exportConfig, parallelIndexes, dictionary) .createNetwork(parameters); new EurostagNetworkModifier().hvLoadModelling(networkEch); new EsgWriter(networkEch, parameters).write(writer, network.getId() + "/" + network.getStateManager().getWorkingStateId()); } dictionary.dump(outputDir.resolve("dict.csv")); System.out.println("exporting dta..."); // export .dta ddbClient.dumpDtaFile(outputDir, "sim.dta", network, parallelIndexes.toMap(), EurostagUtil.VERSION, dictionary.toMap()); System.out.println("exporting seq..."); // export .seq EurostagScenario scenario = new EurostagScenario(SimulationParameters.load(), eurostagConfig); try (BufferedWriter writer = Files.newBufferedWriter(outputDir.resolve(PRE_FAULT_SEQ_FILE_NAME), StandardCharsets.UTF_8)) { scenario.writePreFaultSeq(writer, PRE_FAULT_SAC_FILE_NAME); } ContingenciesProvider contingenciesProvider = defaultConfig .newFactoryImpl(ContingenciesProviderFactory.class).create(); scenario.writeFaultSeqArchive(contingenciesProvider.getContingencies(network), network, dictionary, faultNum -> FAULT_SEQ_FILE_NAME.replace( eu.itesla_project.computation.Command.EXECUTION_NUMBER_PATTERN, Integer.toString(faultNum))) .as(ZipExporter.class).exportTo(outputDir.resolve(ALL_SCENARIOS_ZIP_FILE_NAME).toFile()); // export limits try (OutputStream os = Files.newOutputStream(outputDir.resolve(LIMITS_ZIP_FILE_NAME))) { EurostagImpactAnalysis.writeLimits(network, dictionary, os); } }
From source file:org.elasticsearch.xpack.security.authc.esnative.tool.SetupPasswordToolIT.java
@SuppressWarnings("unchecked") public void testSetupPasswordToolAutoSetup() throws Exception { final String testConfigDir = System.getProperty("tests.config.dir"); logger.info("--> CONF: {}", testConfigDir); final Path configPath = PathUtils.get(testConfigDir); setSystemPropsForTool(configPath);// www . java2 s . co m Response nodesResponse = client().performRequest("GET", "/_nodes/http"); Map<String, Object> nodesMap = entityAsMap(nodesResponse); Map<String, Object> nodes = (Map<String, Object>) nodesMap.get("nodes"); Map<String, Object> firstNode = (Map<String, Object>) nodes.entrySet().iterator().next().getValue(); Map<String, Object> firstNodeHttp = (Map<String, Object>) firstNode.get("http"); String nodePublishAddress = (String) firstNodeHttp.get("publish_address"); final int lastColonIndex = nodePublishAddress.lastIndexOf(':'); InetAddress actualPublishAddress = InetAddresses.forString(nodePublishAddress.substring(0, lastColonIndex)); InetAddress expectedPublishAddress = new NetworkService(Collections.emptyList()) .resolvePublishHostAddresses(Strings.EMPTY_ARRAY); final int port = Integer.valueOf(nodePublishAddress.substring(lastColonIndex + 1)); List<String> lines = Files.readAllLines(configPath.resolve("elasticsearch.yml")); lines = lines.stream() .filter(s -> s.startsWith("http.port") == false && s.startsWith("http.publish_port") == false) .collect(Collectors.toList()); lines.add(randomFrom("http.port", "http.publish_port") + ": " + port); if (expectedPublishAddress.equals(actualPublishAddress) == false) { lines.add("http.publish_address: " + InetAddresses.toAddrString(actualPublishAddress)); } Files.write(configPath.resolve("elasticsearch.yml"), lines, StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING); MockTerminal mockTerminal = new MockTerminal(); SetupPasswordTool tool = new SetupPasswordTool(); final int status; if (randomBoolean()) { mockTerminal.addTextInput("y"); // answer yes to continue prompt status = tool.main(new String[] { "auto" }, mockTerminal); } else { status = tool.main(new String[] { "auto", "--batch" }, mockTerminal); } assertEquals(0, status); String output = mockTerminal.getOutput(); logger.info("CLI TOOL OUTPUT:\n{}", output); String[] outputLines = output.split("\\n"); Map<String, String> userPasswordMap = new HashMap<>(); Arrays.asList(outputLines).forEach(line -> { if (line.startsWith("PASSWORD ")) { String[] pieces = line.split(" "); String user = pieces[1]; String password = pieces[pieces.length - 1]; logger.info("user [{}] password [{}]", user, password); userPasswordMap.put(user, password); } }); assertEquals(4, userPasswordMap.size()); userPasswordMap.entrySet().forEach(entry -> { final String basicHeader = "Basic " + Base64.getEncoder() .encodeToString((entry.getKey() + ":" + entry.getValue()).getBytes(StandardCharsets.UTF_8)); try { Response authenticateResponse = client().performRequest("GET", "/_xpack/security/_authenticate", new BasicHeader("Authorization", basicHeader)); assertEquals(200, authenticateResponse.getStatusLine().getStatusCode()); Map<String, Object> userInfoMap = entityAsMap(authenticateResponse); assertEquals(entry.getKey(), userInfoMap.get("username")); } catch (IOException e) { throw new UncheckedIOException(e); } }); }