List of usage examples for java.nio.file Path relativize
Path relativize(Path other);
From source file:fr.ortolang.diffusion.client.cmd.CheckBagCommand.java
private void checkSnapshotMetadata(Path root) { Path metadata = Paths.get(root.toString(), "metadata"); try {/*from ww w .j a va2 s . c om*/ Files.walkFileTree(metadata, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path target = Paths.get(root.toString(), "objects", metadata.relativize(file.getParent()).toString()); if (!Files.exists(target)) { errors.append("-> unexisting target for metadata: ").append(file).append("\r\n"); if (fix) { try { Files.delete(file); fixed.append("-> deleted metadata: ").append(file).append("\r\n"); } catch (IOException e) { errors.append("-> unable to fix: ").append(e.getMessage()).append("\r\n"); } } } else if (file.endsWith("ortolang-item-json")) { checkOrtolangItemJson(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); } catch (IOException e) { System.out.println("Unable to walk file tree: " + e.getMessage()); } }
From source file:ffx.potential.utils.PotentialsFileOpener.java
public PotentialsFileOpener(File[] files) { if (files == null) { throw new IllegalArgumentException(" Array of files to be opened was null."); }//from ww w . j a v a 2 s. c o m int numFiles = files.length; if (numFiles == 0) { throw new IllegalArgumentException(" Array of files to be opened was empty."); } List<File> fileList = new ArrayList<>(); List<Path> pathList = new ArrayList<>(); Path pwdPath; try { pwdPath = Paths.get(new File("").getCanonicalPath()); } catch (IOException ex) { pwdPath = Paths.get(new File("").getAbsolutePath()); } for (File tryFile : files) { if (!(tryFile.exists() && tryFile.isFile())) { continue; } Path absPath; try { absPath = Paths.get(tryFile.getCanonicalPath()); } catch (IOException ex) { absPath = Paths.get(tryFile.getAbsolutePath()); } Path thisPath = pwdPath.relativize(absPath); fileList.add(tryFile); pathList.add(thisPath); } int numAccepted = fileList.size(); if (numAccepted < 1) { throw new IllegalArgumentException(" No valid files could be found to open."); } allFiles = fileList.toArray(new File[numAccepted]); allPaths = pathList.toArray(new Path[numAccepted]); this.file = allFiles[0]; this.filepath = allPaths[0]; assemblies = new ArrayList<>(); propertyList = new ArrayList<>(); }
From source file:org.dataconservancy.packaging.tool.impl.generator.OrePackageModelBuilderTest.java
@Test public void mixedRelationshipExtractionTest() throws Exception { OrePackageModelBuilder builder = new OrePackageModelBuilder(); File baseDir = tmpfolder.newFolder("flowers"); PackageAssembler assembler = new FunctionalAssemblerMock(baseDir); PackageGenerationParameters params = new PackageGenerationParameters(); params.addParam(GeneralParameterNames.CONTENT_ROOT_LOCATION, baseDir.getPath()); builder.init(params);/*w w w . ja v a 2s . c om*/ PackageArtifact collection = newArtifact(ArtifactType.Collection); PackageArtifact dataItem = newArtifact(ArtifactType.DataItem); PackageArtifact dataFile = newArtifact(ArtifactType.DataFile); addRel(DcsBoPackageOntology.IS_MEMBER_OF, collection, dataItem); addRel(DcsBoPackageOntology.IS_MEMBER_OF, dataItem, dataFile); File content = new File(baseDir, "barn.tst"); IOUtils.write("test", new FileOutputStream(content)); Path rootPath = Paths.get(baseDir.getPath()); Path filePath = Paths.get(content.getPath()); dataFile.setArtifactRef(rootPath.relativize(filePath).toString()); final String REL = "http://arbitrary/rel"; final String EXTERNAL_REL_VALUE = "http://external/target"; addExternalRel(collection, REL, EXTERNAL_REL_VALUE); addRel(REL, dataFile, collection); PackageDescription desc = new PackageDescription(); desc.setPackageArtifacts(asSet(collection, dataItem, dataFile)); desc.setRootArtifactRef(collection.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()) { if (att.getName().contains(REL)) { extractedValues.add(att.getValue()); } } } assertEquals(2, extractedValues.size()); assertTrue(extractedValues.contains(EXTERNAL_REL_VALUE)); // The URI of the dataItem isn't apparent, so we assume that it's the other entry // in the extracted values set }
From source file:org.dataconservancy.packaging.tool.impl.generator.OrePackageModelBuilderTest.java
@Test public void externalRelationshipExtractionTest() throws Exception { OrePackageModelBuilder builder = new OrePackageModelBuilder(); File baseDir = tmpfolder.newFolder("grass"); PackageAssembler assembler = new FunctionalAssemblerMock(baseDir); PackageGenerationParameters params = new PackageGenerationParameters(); params.addParam(GeneralParameterNames.CONTENT_ROOT_LOCATION, baseDir.getPath()); builder.init(params);//from w w w . jav a2 s .c o m PackageArtifact collection = newArtifact(ArtifactType.Collection); PackageArtifact dataItem = newArtifact(ArtifactType.DataItem); PackageArtifact dataFile = newArtifact(ArtifactType.DataFile); addRel(DcsBoPackageOntology.IS_MEMBER_OF, collection, dataItem); addRel(DcsBoPackageOntology.IS_MEMBER_OF, dataItem, dataFile); File content = new File(baseDir, "pastures"); IOUtils.write("test", new FileOutputStream(content)); Path rootPath = Paths.get(baseDir.getPath()); Path filePath = Paths.get(content.getPath()); dataFile.setArtifactRef(String.valueOf(rootPath.relativize(filePath))); final String EXTERNAL_REL = "http://arbitrary/rel"; final String EXTERNAL_REL_VALUE = "http://external/target"; addExternalRel(collection, EXTERNAL_REL, EXTERNAL_REL_VALUE); PackageDescription desc = new PackageDescription(); desc.setPackageArtifacts(asSet(collection, dataItem, dataFile)); desc.setRootArtifactRef(collection.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()); } } assertTrue(extractedValues.contains(EXTERNAL_REL_VALUE)); }
From source file:org.dataconservancy.packaging.tool.impl.generator.OrePackageModelBuilderTest.java
@Test public void multipleCreatorsTest() throws Exception { OrePackageModelBuilder builder = new OrePackageModelBuilder(); File baseDir = tmpfolder.newFolder("moocow"); PackageGenerationParameters params = new PackageGenerationParameters(); params.addParam(GeneralParameterNames.CONTENT_ROOT_LOCATION, baseDir.getPath()); builder.init(params);// w w w.j av a 2 s .c o m PackageAssembler assembler = new FunctionalAssemblerMock(baseDir); PackageArtifact collection = newArtifact(ArtifactType.Collection); PropertyValueGroup creator1 = new PropertyValueGroup(); creator1.addSubPropertyValue(DcsBoPackageOntology.PERSON_NAME, "creator 1"); creator1.addSubPropertyValue(DcsBoPackageOntology.EMAIL, "mailTo:creator1@email.com"); creator1.addSubPropertyValue(DcsBoPackageOntology.PHONE, "tel:5405854152"); PropertyValueGroup creator2 = new PropertyValueGroup(); creator1.addSubPropertyValue(DcsBoPackageOntology.PERSON_NAME, "creator 2"); creator1.addSubPropertyValue(DcsBoPackageOntology.EMAIL, "mailTo:creator2@email.com"); creator1.addSubPropertyValue(DcsBoPackageOntology.PHONE, "tel:5408888888"); PropertyValueGroup creator3 = new PropertyValueGroup(); creator1.addSubPropertyValue(DcsBoPackageOntology.PERSON_NAME, "creator 3"); creator1.addSubPropertyValue(DcsBoPackageOntology.EMAIL, "mailTo:creator3@email.com"); creator1.addSubPropertyValue(DcsBoPackageOntology.PHONE, "tel:5405555555"); collection.addPropertyValueGroup(DcsBoPackageOntology.CREATOR, creator1); collection.addPropertyValueGroup(DcsBoPackageOntology.CREATOR, creator2); collection.addPropertyValueGroup(DcsBoPackageOntology.CREATOR, creator3); PackageArtifact dataItem = newArtifact(ArtifactType.DataItem); addRel(DcsBoPackageOntology.IS_MEMBER_OF, collection, dataItem); PackageArtifact dataFile = newArtifact(ArtifactType.DataFile); addRel(DcsBoPackageOntology.IS_MEMBER_OF, dataItem, dataFile); File content = new File(baseDir, "catman"); IOUtils.write("test", new FileOutputStream(content)); Path rootPath = Paths.get(baseDir.getPath()); Path filePath = Paths.get(content.getPath()); dataFile.setArtifactRef(rootPath.relativize(filePath).toString()); PackageDescription desc = new PackageDescription(); desc.setPackageArtifacts(asSet(collection, dataItem, dataFile)); desc.setRootArtifactRef(collection.getArtifactRef()); builder.buildModel(desc, assembler); ResourceMapExtractor extractor = new ResourceMapExtractor(); Map<String, AttributeSet> attrs = extractor.execute(baseDir, builder.getPackageRemURI()); //The implementation of resource map extractor used in this tests put a creator's name, phone and email address //in separate attributes making it impossible to group them in the correct grouping under a specific creator. //However, to test that more than one creator's information was expressed in the ReM, this test will verify // the count of each attributes: 3 of creator's names, emails, phone numbers int countCreatorName = 0; int countCreatorEmail = 0; int countCreatorPhone = 0; for (AttributeSet attSet : attrs.values()) { for (Attribute att : attSet.getAttributes()) { if (att.getName().contains(Metadata.CREATOR_NAME)) { countCreatorName++; } else if (att.getName().contains(Metadata.CREATOR_EMAIL)) { countCreatorEmail++; } else if (att.getName().contains(Metadata.CREATOR_PHONE)) { countCreatorPhone++; } } } assertEquals(3, countCreatorEmail); assertEquals(3, countCreatorPhone); assertEquals(3, countCreatorName); }
From source file:org.roda.core.storage.fs.FSUtils.java
/** * Copies a directory/file from one path to another * //from w w w.ja v a2 s .c o m * @param sourcePath * source path * @param targetPath * target path * @param replaceExisting * true if the target directory/file should be replaced if it already * exists; false otherwise * @throws AlreadyExistsException * @throws GenericException */ public static void copy(final Path sourcePath, final Path targetPath, boolean replaceExisting) throws AlreadyExistsException, GenericException { // check if we can replace existing if (!replaceExisting && FSUtils.exists(targetPath)) { throw new AlreadyExistsException("Cannot copy because target path already exists: " + targetPath); } // ensure parent directory exists or can be created try { if (targetPath != null) { Files.createDirectories(targetPath.getParent()); } } catch (IOException e) { throw new GenericException("Error while creating target directory parent folder", e); } if (FSUtils.isDirectory(sourcePath)) { try { Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { Files.createDirectories(targetPath.resolve(sourcePath.relativize(dir))); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { Files.copy(file, targetPath.resolve(sourcePath.relativize(file))); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { throw new GenericException("Error while copying one directory into another", e); } } else { try { CopyOption[] copyOptions = replaceExisting ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING } : new CopyOption[] {}; Files.copy(sourcePath, targetPath, copyOptions); } catch (IOException e) { throw new GenericException("Error while copying one file into another", e); } } }
From source file:org.dataconservancy.packaging.tool.impl.generator.OrePackageModelBuilderTest.java
@Test public void dataFileTest() throws Exception { OrePackageModelBuilder builder = new OrePackageModelBuilder(); PackageAssembler assembler = mock(PackageAssembler.class); PackageGenerationParameters params = new PackageGenerationParameters(); params.addParam(GeneralParameterNames.CONTENT_ROOT_LOCATION, tmpfolder.getRoot().getPath()); builder.init(params);// ww w.jav a 2 s . c om when(assembler.reserveResource(anyString(), eq(PackageResourceType.METADATA))).thenAnswer(invocation -> { String path = (String) invocation.getArguments()[0]; assertTrue(path.startsWith("/ORE-REM")); assertTrue(path.endsWith(".xml")); return uriFor(path); }); when(assembler.createResource(anyString(), eq(PackageResourceType.DATA), any(InputStream.class))) .thenAnswer(invocation -> { String path = (String) invocation.getArguments()[0]; assertTrue(path.endsWith("tst")); return uriFor(path); }); PackageArtifact project = newArtifact(ArtifactType.Project); PackageArtifact collection = newArtifact(ArtifactType.Collection); PackageArtifact dataItem = newArtifact(ArtifactType.DataItem); PackageArtifact dataFile = newArtifact(ArtifactType.DataFile); PackageArtifact dataFileExplicitPath = newArtifact(ArtifactType.DataFile); /* Add a file with no explicit path specified */ File content = tmpfolder.newFile("dataFileTest.tst"); IOUtils.write("test", new FileOutputStream(content)); Path rootPath = Paths.get(tmpfolder.getRoot().getPath()); Path contentPath = Paths.get(content.getPath()); dataFile.setArtifactRef(rootPath.relativize(contentPath).toString()); /* Add another file, this time with an explicit path */ content = tmpfolder.newFile("dataFileTest2.tst"); contentPath = Paths.get(content.getPath()); IOUtils.write("test", new FileOutputStream(content)); dataFileExplicitPath.setArtifactRef(rootPath.relativize(contentPath).toString()); //dataFileExplicitPath.addSimplePropertyValue(Property.FILE_PATH.toString(), // EXPLICIT_FILE_PATH); addRel(DcsBoPackageOntology.IS_MEMBER_OF, project, collection); addRel(DcsBoPackageOntology.IS_MEMBER_OF, collection, dataItem); addRel(DcsBoPackageOntology.IS_MEMBER_OF, dataItem, dataFile); addRel(DcsBoPackageOntology.IS_MEMBER_OF, dataItem, dataFileExplicitPath); PackageDescription desc = new PackageDescription(); desc.setPackageArtifacts(asSet(project, collection, dataItem, dataFile, dataFileExplicitPath)); desc.setRootArtifactRef(project.getArtifactRef()); builder.buildModel(desc, assembler); verify(assembler, times(2)).createResource(anyString(), eq(PackageResourceType.DATA), any(InputStream.class)); //verify(assembler).createResource(eq(EXPLICIT_FILE_PATH), // eq(PackageResourceType.DATA), // any(InputStream.class)); verify(assembler, times(4)).reserveResource(anyString(), eq(PackageResourceType.METADATA)); verify(assembler, times(4)).putResource(any(URI.class), any(InputStream.class)); }
From source file:ffx.potential.utils.PotentialsFileOpener.java
public PotentialsFileOpener(String[] filenames) { if (filenames == null) { throw new IllegalArgumentException(" Array of files to be opened was null."); }// w w w . java 2 s.c o m int numFiles = filenames.length; if (numFiles == 0) { throw new IllegalArgumentException(" Array of files to be opened was empty."); } List<File> fileList = new ArrayList<>(); List<Path> pathList = new ArrayList<>(); Path pwdPath; try { pwdPath = Paths.get(new File("").getCanonicalPath()); } catch (IOException ex) { pwdPath = Paths.get(new File("").getAbsolutePath()); } for (String filename : filenames) { try { File tryFile = new File(filename); if (!(tryFile.exists() && tryFile.isFile())) { continue; } Path absPath; try { absPath = Paths.get(tryFile.getCanonicalPath()); } catch (IOException ex) { absPath = Paths.get(tryFile.getAbsolutePath()); } Path thisPath = pwdPath.relativize(absPath); fileList.add(tryFile); pathList.add(thisPath); } catch (Exception ex) { // Simply continue. } } int numAccepted = fileList.size(); if (numAccepted < 1) { throw new IllegalArgumentException(" No valid files could be found to open."); } allFiles = fileList.toArray(new File[numAccepted]); allPaths = pathList.toArray(new Path[numAccepted]); this.file = allFiles[0]; this.filepath = allPaths[0]; assemblies = new ArrayList<>(); propertyList = new ArrayList<>(); }
From source file:org.dataconservancy.packaging.tool.impl.generator.OrePackageModelBuilderTest.java
@Test public void testIgnoredArtifactAreLeftOutOfREM() throws Exception { OrePackageModelBuilder builder = new OrePackageModelBuilder(); File baseDir = tmpfolder.newFolder("moocow"); PackageAssembler assembler = new FunctionalAssemblerMock(baseDir); PackageGenerationParameters params = new PackageGenerationParameters(); params.addParam(GeneralParameterNames.CONTENT_ROOT_LOCATION, baseDir.getPath()); builder.init(params);//from www. ja v a2 s .c o m PackageArtifact collection = newArtifact(ArtifactType.Collection); PackageArtifact ignoredDataItem = newArtifact(ArtifactType.DataItem); ignoredDataItem.setIgnored(true); PackageArtifact ignoredDataFile = newArtifact(ArtifactType.DataFile); ignoredDataFile.setIgnored(true); PackageArtifact unignoredDataItem = newArtifact(ArtifactType.DataItem); PackageArtifact unignoredDataFile = newArtifact(ArtifactType.DataFile); addRel(DcsBoPackageOntology.IS_MEMBER_OF, collection, ignoredDataItem); addRel(DcsBoPackageOntology.IS_MEMBER_OF, ignoredDataItem, ignoredDataFile); addRel(DcsBoPackageOntology.IS_MEMBER_OF, collection, unignoredDataItem); addRel(DcsBoPackageOntology.IS_MEMBER_OF, unignoredDataItem, unignoredDataFile); File content = new File(baseDir, "batman"); Path rootPath = Paths.get(baseDir.getPath()); Path filePath = Paths.get(content.getPath()); IOUtils.write("test", new FileOutputStream(content)); unignoredDataFile.setArtifactRef(rootPath.relativize(filePath).toString()); PackageDescription desc = new PackageDescription(); desc.setPackageArtifacts( asSet(collection, ignoredDataItem, ignoredDataFile, unignoredDataFile, unignoredDataItem)); desc.setRootArtifactRef(collection.getArtifactRef()); builder.buildModel(desc, assembler); ResourceMapExtractor extractor = new ResourceMapExtractor(); Map<String, AttributeSet> attrs = extractor.execute(baseDir, builder.getPackageRemURI()); int collectionCount = 0; int dataItemCount = 0; int dataFileCount = 0; for (AttributeSet attSet : attrs.values()) { if (attSet.getName().contains(AttributeSetName.ORE_REM_COLLECTION)) { collectionCount++; } if (attSet.getName().contains(AttributeSetName.ORE_REM_DATAITEM)) { dataItemCount++; } if (attSet.getName().contains(AttributeSetName.ORE_REM_FILE)) { dataFileCount++; } } assertEquals(1, collectionCount); assertEquals(1, dataItemCount); assertEquals(1, dataFileCount); }
From source file:org.dataconservancy.packaging.tool.impl.generator.OrePackageModelBuilderTest.java
@Test public void metadataFileTest() throws Exception { OrePackageModelBuilder builder = new OrePackageModelBuilder(); PackageAssembler assembler = mock(PackageAssembler.class); when(assembler.reserveResource(anyString(), eq(PackageResourceType.METADATA))).thenAnswer(invocation -> { String path = (String) invocation.getArguments()[0]; assertTrue(path.startsWith("/ORE-REM")); assertTrue(path.endsWith(".xml")); return uriFor(path); });/* ww w. ja v a 2 s.c o m*/ when(assembler.createResource(anyString(), eq(PackageResourceType.DATA), any(InputStream.class))) .thenAnswer(invocation -> { String path = (String) invocation.getArguments()[0]; assertTrue(path.endsWith("tst")); return uriFor(path); }); PackageArtifact project = newArtifact(ArtifactType.Project); PackageArtifact collection = newArtifact(ArtifactType.Collection); PackageArtifact dataItem = newArtifact(ArtifactType.DataItem); PackageArtifact metadataFile = newArtifact(ArtifactType.MetadataFile); /* Add a file with no explicit path specified */ File content = tmpfolder.newFile("dataFileTest32.tst"); PackageGenerationParameters params = new PackageGenerationParameters(); params.addParam(GeneralParameterNames.CONTENT_ROOT_LOCATION, tmpfolder.getRoot().getPath()); builder.init(params); Path rootPath = Paths.get(tmpfolder.getRoot().getPath()); Path contentPath = Paths.get(content.getPath()); IOUtils.write("test", new FileOutputStream(content)); metadataFile.setArtifactRef(rootPath.relativize(contentPath).toString()); addRel(DcsBoPackageOntology.IS_MEMBER_OF, project, collection); addRel(DcsBoPackageOntology.IS_MEMBER_OF, collection, dataItem); addRel(DcsBoPackageOntology.IS_METADATA_FOR, collection, metadataFile); PackageDescription desc = new PackageDescription(); desc.setPackageArtifacts(asSet(project, collection, dataItem, metadataFile)); desc.setRootArtifactRef(project.getArtifactRef()); builder.buildModel(desc, assembler); verify(assembler, times(1)).createResource(anyString(), eq(PackageResourceType.DATA), any(InputStream.class)); verify(assembler, times(4)).reserveResource(anyString(), eq(PackageResourceType.METADATA)); verify(assembler, times(4)).putResource(any(URI.class), any(InputStream.class)); // TODO Must actually test that an isMetadataFor relationship is produced. }