List of usage examples for java.nio.file Path relativize
Path relativize(Path other);
From source file:com.liferay.sync.engine.SyncSystemTest.java
protected void addFolder(Path testFilePath, JsonNode stepJsonNode) throws Exception { SyncSite syncSite = getSyncSite(stepJsonNode); String dependency = getString(stepJsonNode, "dependency"); final Path dependencyFilePath = getDependencyFilePath(testFilePath, dependency); FileSystem fileSystem = FileSystems.getDefault(); final Path targetFilePath = Paths.get(FileUtil.getFilePathName(syncSite.getFilePathName(), dependency.replace("common" + fileSystem.getSeparator(), ""))); Files.walkFileTree(dependencyFilePath, new SimpleFileVisitor<Path>() { @Override// w w w . j a v a 2 s. c o m public FileVisitResult preVisitDirectory(Path filePath, BasicFileAttributes basicFileAttributes) throws IOException { Path relativeFilePath = dependencyFilePath.relativize(filePath); Files.createDirectories(targetFilePath.resolve(relativeFilePath)); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path filePath, BasicFileAttributes basicFileAttributes) throws IOException { Path relativeFilePath = dependencyFilePath.relativize(filePath); Files.copy(filePath, targetFilePath.resolve(relativeFilePath)); return FileVisitResult.CONTINUE; } }); }
From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java
/** * Perform an initial commit after large changes to a site. Will not work against the global config repo. * @param site/*from w w w. ja v a 2s . c o m*/ * @param message * @return true if successful, false otherwise */ public boolean performInitialCommit(String site, String message, String sandboxBranch) { boolean toReturn = true; Repository repo = getRepository(site, GitRepositories.SANDBOX, sandboxBranch); try (Git git = new Git(repo)) { Status status = git.status().call(); if (status.hasUncommittedChanges() || !status.isClean()) { DirCache dirCache = git.add().addFilepattern(GIT_COMMIT_ALL_ITEMS).call(); RevCommit commit = git.commit().setMessage(message).call(); // TODO: SJ: Do we need the commit id? // commitId = commit.getName(); } checkoutSandboxBranch(site, repo, sandboxBranch); // Create Published by cloning Sandbox // Build a path for the site/sandbox Path siteSandboxPath = buildRepoPath(GitRepositories.SANDBOX, site); // Built a path for the site/published Path sitePublishedPath = buildRepoPath(GitRepositories.PUBLISHED, site); try (Git publishedGit = Git.cloneRepository() .setURI(sitePublishedPath.relativize(siteSandboxPath).toString()) .setDirectory(sitePublishedPath.normalize().toAbsolutePath().toFile()).call()) { Repository publishedRepo = publishedGit.getRepository(); publishedRepo = optimizeRepository(publishedRepo); checkoutSandboxBranch(site, publishedRepo, sandboxBranch); publishedRepo.close(); publishedGit.close(); } catch (GitAPIException | IOException e) { logger.error("Error adding origin (sandbox) to published repository", e); } git.close(); } catch (GitAPIException err) { logger.error("error creating initial commit for site: " + site, err); toReturn = false; } return toReturn; }
From source file:org.dataconservancy.packaging.tool.impl.generator.OrePackageModelBuilderTest.java
@Test public void propertyExtractionTest() throws Exception { OrePackageModelBuilder builder = new OrePackageModelBuilder(); File baseDir = tmpfolder.newFolder("destiny"); PackageAssembler assembler = new FunctionalAssemblerMock(baseDir); PackageGenerationParameters params = new PackageGenerationParameters(); params.addParam(GeneralParameterNames.CONTENT_ROOT_LOCATION, baseDir.getPath()); builder.init(params);/*from ww w . j a va2 s . co m*/ PackageArtifact project = newArtifact(ArtifactType.Project); PackageArtifact collection = newArtifact(ArtifactType.Collection); PackageArtifact dataItem = newArtifact(ArtifactType.DataItem); PackageArtifact dataFile = newArtifact(ArtifactType.DataFile); PackageArtifact metadataFile = newArtifact(ArtifactType.MetadataFile); addRandomPropertiesTo(project); addRel(DcsBoPackageOntology.IS_MEMBER_OF, project, collection); addRandomPropertiesTo(collection); addRel(DcsBoPackageOntology.IS_MEMBER_OF, collection, dataItem); addRandomPropertiesTo(dataItem); addRel(DcsBoPackageOntology.IS_METADATA_FOR, collection, metadataFile); addRandomPropertiesTo(metadataFile); Path rootPath = Paths.get(baseDir.getPath()); File metaContent = new File(baseDir, "dataFileTest12.tst"); Path metaConentPath = Paths.get(metaContent.getPath()); IOUtils.write("test", new FileOutputStream(metaContent)); metadataFile.setArtifactRef(rootPath.relativize(metaConentPath).toString()); addRel(DcsBoPackageOntology.IS_MEMBER_OF, dataItem, dataFile); addRandomPropertiesTo(dataFile); File content = new File(baseDir, "cow"); IOUtils.write("test", new FileOutputStream(content)); Path contentPath = Paths.get(content.getPath()); dataFile.setArtifactRef(rootPath.relativize(contentPath).toString()); PackageDescription desc = new PackageDescription(); desc.setPackageArtifacts(asSet(project, collection, dataItem, dataFile, metadataFile)); desc.setRootArtifactRef(project.getArtifactRef()); builder.buildModel(desc, assembler); ResourceMapExtractor extractor = new ResourceMapExtractor(); Map<String, AttributeSet> attrs = extractor.execute(baseDir, builder.getPackageRemURI()); Set<String> extractedValues = new HashSet<>(); for (AttributeSet attSet : attrs.values()) { for (Attribute att : attSet.getAttributes()) { extractedValues.add(att.getValue()); } } for (PackageArtifact artifact : asSet(project, collection, dataItem, dataFile, metadataFile)) { for (String key : artifact.getPropertyNames()) { if (artifact.hasSimpleProperty(key)) { for (String value : artifact.getSimplePropertyValues(key)) { assertTrue("Missing value for property " + key, extractedValues.contains(value)); } } else if (artifact.hasPropertyValueGroup(key)) { artifact.getPropertyValueGroups(key); for (PropertyValueGroup group : artifact.getPropertyValueGroups(key)) { for (String subKey : group.getSubPropertyNames()) { for (String value : group.getSubPropertyValues(subKey)) { assertTrue(String.format("Missing value for property %s->%s", key, subKey), extractedValues.contains(value)); } assertTrue(extractedValues.containsAll(group.getSubPropertyValues(subKey))); } } } else { Assert.fail("No value for property " + key); } } } }
From source file:org.everit.i18n.propsxlsconverter.internal.I18nConverterImpl.java
/** * Calculate file access between the working directory and language file. * * @param languageFile/*from ww w . ja v a2s .c om*/ * the language file. * @return the calculated file access path. */ private String calculateFileAccess(final File languageFile, final String[] languages, final String workingDirectory) { Path workingDirectoryPath = Paths.get(workingDirectory); String languageFileAbsolutePath = languageFile.getAbsolutePath(); Path languageFilePath = Paths.get(languageFileAbsolutePath); String fileName = languageFile.getName(); for (String lang : languages) { String searchLang = UNDERLINE + lang; int lastIndexOf = fileName.lastIndexOf(searchLang); if (lastIndexOf > -1) { String defaultLangFileName = calculateDefaultLangFileName(fileName, searchLang, lastIndexOf); String defaultLangFileAbsolutePath = languageFileAbsolutePath.replace(fileName, defaultLangFileName); languageFilePath = Paths.get(defaultLangFileAbsolutePath); } } Path relativize = workingDirectoryPath.relativize(languageFilePath); return relativize.toString(); }
From source file:it.greenvulcano.configuration.BaseConfigurationManager.java
@Override public void deploy(String name) throws XMLConfigException, FileNotFoundException { Path configurationArchivePath = getConfigurationPath(name); Path current = Paths.get(XMLConfig.getBaseConfigPath()); Path staging = current.getParent().resolve("deploy"); Path destination = current.getParent().resolve(name); if (LOCK.tryLock()) { if (Files.exists(configurationArchivePath) && !Files.isDirectory(configurationArchivePath)) { try { ZipInputStream configurationArchive = new ZipInputStream( Files.newInputStream(configurationArchivePath, StandardOpenOption.READ)); LOG.debug("Starting deploy of configuration " + name); ZipEntry zipEntry = null; for (Path cfgFile : Files.walk(current).collect(Collectors.toSet())) { if (!Files.isDirectory(cfgFile)) { Path target = staging.resolve(current.relativize(cfgFile)); Files.createDirectories(target); Files.copy(cfgFile, target, StandardCopyOption.REPLACE_EXISTING); }//w w w. j a va2 s.co m } LOG.debug("Staging new config " + name); while ((zipEntry = configurationArchive.getNextEntry()) != null) { Path entryPath = staging.resolve(zipEntry.getName()); LOG.debug("Adding resource: " + entryPath); if (zipEntry.isDirectory()) { entryPath.toFile().mkdirs(); } else { Path parent = entryPath.getParent(); if (!Files.exists(parent)) { Files.createDirectories(parent); } Files.copy(configurationArchive, entryPath, StandardCopyOption.REPLACE_EXISTING); } } //**** Deleting old config dir LOG.debug("Removing old config: " + current); Files.walk(current, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(java.nio.file.Path::toFile).forEach(File::delete); LOG.debug("Deploy new config " + name + " in path " + destination); Files.move(staging, destination, StandardCopyOption.ATOMIC_MOVE); setXMLConfigBasePath(destination.toString()); LOG.debug("Deploy complete"); deployListeners.forEach(l -> l.onDeploy(destination)); } catch (Exception e) { if (Objects.nonNull(staging) && Files.exists(staging)) { LOG.error("Deploy failed, rollback to previous configuration", e); try { Files.walk(staging, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(java.nio.file.Path::toFile).forEach(File::delete); setXMLConfigBasePath(current.toString()); } catch (IOException | InvalidSyntaxException rollbackException) { LOG.error("Failed to delete old configuration", e); } } else { LOG.error("Deploy failed", e); } throw new XMLConfigException("Deploy failed", e); } finally { LOCK.unlock(); } } else { throw new FileNotFoundException(configurationArchivePath.toString()); } } else { throw new IllegalStateException("A deploy is already in progress"); } }
From source file:org.deventropy.shared.utils.DirectoryArchiverUtilTest.java
private ArchiveEntries createArchiveEntries(final File sourceDirectory, final String pathPrefix) throws IOException { final ArchiveEntries archiveEntries = new ArchiveEntries(); final Path sourcePath = Paths.get(sourceDirectory.toURI()); final StringBuilder normalizedPathPrefix = new StringBuilder(); if (null != pathPrefix && !pathPrefix.isEmpty()) { normalizedPathPrefix.append(pathPrefix.replace("\\", "/")); if (normalizedPathPrefix.charAt(normalizedPathPrefix.length() - 1) != '/') { normalizedPathPrefix.append('/'); }/* ww w .j a v a 2 s . c o m*/ } Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { final Path relativeSourcePath = sourcePath.relativize(dir); String normalizedPath = normalizedPathPrefix.toString() + relativeSourcePath; if (!normalizedPath.isEmpty()) { if (!normalizedPath.endsWith("/")) { normalizedPath += "/"; } archiveEntries.dirs.add(normalizedPath.replace("\\", "/")); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { final Path relativeSourcePath = sourcePath.relativize(file); final String normalizedPath = normalizedPathPrefix.toString() + relativeSourcePath; final byte[] md5Digest = getMd5Digest(Files.newInputStream(file), true); archiveEntries.files.put(normalizedPath.replace("\\", "/"), md5Digest); return FileVisitResult.CONTINUE; } }); return archiveEntries; }
From source file:org.elasticsearch.plugins.PluginManagerIT.java
/** creates a plugin .zip and returns the url for testing */ private String createPlugin(final Path structure, String... properties) throws IOException { writeProperties(structure, properties); Path zip = createTempDir().resolve(structure.getFileName() + ".zip"); try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(zip))) { Files.walkFileTree(structure, new SimpleFileVisitor<Path>() { @Override//w w w. j a v a 2 s . c o m public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { stream.putNextEntry(new ZipEntry(structure.relativize(file).toString())); Files.copy(file, stream); return FileVisitResult.CONTINUE; } }); } if (randomBoolean()) { writeSha1(zip, false); } else if (randomBoolean()) { writeMd5(zip, false); } return zip.toUri().toURL().toString(); }
From source file:org.elasticsearch.plugins.PluginManagerIT.java
/** creates a plugin .zip and bad checksum file and returns the url for testing */ private String createPluginWithBadChecksum(final Path structure, String... properties) throws IOException { writeProperties(structure, properties); Path zip = createTempDir().resolve(structure.getFileName() + ".zip"); try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(zip))) { Files.walkFileTree(structure, new SimpleFileVisitor<Path>() { @Override// w ww . j a v a2 s. co m public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { stream.putNextEntry(new ZipEntry(structure.relativize(file).toString())); Files.copy(file, stream); return FileVisitResult.CONTINUE; } }); } if (randomBoolean()) { writeSha1(zip, true); } else { writeMd5(zip, true); } return zip.toUri().toURL().toString(); }
From source file:org.bonitasoft.platform.setup.PlatformSetup.java
public void pull(Path configurationFolder, Path licensesFolder) throws PlatformException { try {/*www . java 2s .c o m*/ recreateDirectory(configurationFolder); if (Files.isDirectory(licensesFolder)) { FileUtils.cleanDirectory(licensesFolder.toFile()); } List<File> licenses = new ArrayList<>(); List<File> files = configurationService.writeAllConfigurationToFolder(configurationFolder.toFile(), licensesFolder.toFile()); LOGGER.info("Retrieved following files in " + configurationFolder); for (File file : files) { if (file.toPath().getParent().equals(licensesFolder)) { licenses.add(file); } else { LOGGER.info(configurationFolder.relativize(file.toPath()).toString()); } } if (!licenses.isEmpty()) { LOGGER.info("Retrieved following licenses in " + licensesFolder); for (File license : licenses) { LOGGER.info(licensesFolder.relativize(license.toPath()).toString()); } } } catch (IOException e) { throw new PlatformException(e); } }
From source file:playRepository.GitRepository.java
/** * Clones a local repository./*from w ww . ja va 2s .co m*/ * * This doesn't copy Git objects but hardlink them to save disk space. * * @param originalProject * @param forkProject * @throws IOException */ protected static void cloneHardLinkedRepository(Project originalProject, Project forkProject) throws IOException { Repository origin = GitRepository.buildGitRepository(originalProject); Repository forked = GitRepository.buildGitRepository(forkProject); forked.create(); final Path originObjectsPath = Paths.get(new File(origin.getDirectory(), "objects").getAbsolutePath()); final Path forkedObjectsPath = Paths.get(new File(forked.getDirectory(), "objects").getAbsolutePath()); // Hardlink files .git/objects/ directory to save disk space, // but copy .git/info/alternates because the file can be modified. SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attr) throws IOException { Path newPath = forkedObjectsPath.resolve(originObjectsPath.relativize(file.toAbsolutePath())); if (file.equals(forkedObjectsPath.resolve("/info/alternates"))) { Files.copy(file, newPath); } else { FileUtils.mkdirs(newPath.getParent().toFile(), true); Files.createLink(newPath, file); } return java.nio.file.FileVisitResult.CONTINUE; } }; Files.walkFileTree(originObjectsPath, visitor); // Import refs. for (Map.Entry<String, Ref> entry : origin.getAllRefs().entrySet()) { RefUpdate updateRef = forked.updateRef(entry.getKey()); Ref ref = entry.getValue(); if (ref.isSymbolic()) { updateRef.link(ref.getTarget().getName()); } else { updateRef.setNewObjectId(ref.getObjectId()); updateRef.update(); } } }