下面列出了java.nio.file.Path#equals ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static boolean isTestClass(String className, ClassLoader classLoader, Path testLocation) {
String classFileName = className.replace('.', File.separatorChar) + ".class";
URL resource = classLoader.getResource(classFileName);
if (resource == null) {
return false;
}
if (Files.isDirectory(testLocation)) {
return resource.getProtocol().startsWith("file") && isInTestDir(resource);
}
if (!resource.getProtocol().equals("jar")) {
return false;
}
String path = resource.getPath();
if (!path.startsWith("file:")) {
return false;
}
path = path.substring(5, path.lastIndexOf('!'));
return testLocation.equals(Paths.get(path));
}
/**
* @param project a project
* @param directory a process directory
* @param command a command to execute (if empty string, the parameter is ignored)
* @param doStartNotify true if the handler should call OSHandler#startNotify
* @deprecated Use {@link BuckCommandHandler(Project, BuckCommand, boolean)}
*/
@Deprecated
public BuckCommandHandler(
Project project, File directory, BuckCommand command, boolean doStartNotify) {
this(project, command, doStartNotify);
Path actualPath = commandLine.getWorkDirectory().toPath();
if (!actualPath.equals(directory.toPath())) {
LOG.warn(
"Running buck command \""
+ commandLine.getCommandLineString()
+ "\" from the work directory \""
+ actualPath.toString()
+ "\" and not in the requested directory \""
+ directory.toPath()
+ "\"");
}
}
@Override
public void start(Consumer<List<Digest>> onDigests) throws IOException, InterruptedException {
List<Dirent> dirents = null;
try {
dirents = readdir(root, /* followSymlinks= */ false);
} catch (IOException e) {
logger.log(Level.SEVERE, "error reading directory " + root.toString(), e);
}
ImmutableList.Builder<ListenableFuture<Void>> removeDirectoryFutures = ImmutableList.builder();
// only valid path under root is cache
for (Dirent dirent : dirents) {
String name = dirent.getName();
Path child = root.resolve(name);
if (!child.equals(fileCache.getRoot())) {
removeDirectoryFutures.add(Directories.remove(root.resolve(name), removeDirectoryService));
}
}
ImmutableList.Builder<Digest> blobDigests = ImmutableList.builder();
fileCache.start(blobDigests::add, removeDirectoryService);
onDigests.accept(blobDigests.build());
getInterruptiblyOrIOException(allAsList(removeDirectoryFutures.build()));
}
/**
* Register the given directory with the WatchService
*/
public void register(Path dir) throws IOException {
if (!enable)
return;
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
if (trace) {
Path prev = keys.get(key);
if (prev == null) {
System.out.format("CatalogWatcher register: %s%n", dir);
} else {
if (!dir.equals(prev)) {
System.out.format("update: %s -> %s%n", prev, dir);
}
}
}
keys.put(key, dir);
}
/**
* @param cellRoot Absolute path to the root of the cell the rule is defined in.
* @param map the map of values that define the rule.
* @param buildFilePath Absolute path to the build file the rule is defined in
* @return the build target defined by the rule.
*/
public static UnflavoredBuildTarget createFromRawNode(
Path cellRoot, CanonicalCellName cellName, Map<String, Object> map, Path buildFilePath) {
@Nullable String basePath = (String) map.get(InternalTargetAttributeNames.BASE_PATH);
@Nullable String name = (String) map.get("name");
if (basePath == null || name == null) {
throw new IllegalStateException(
String.format(
"Attempting to parse build target from malformed raw data in %s: %s.",
buildFilePath, Joiner.on(",").withKeyValueSeparator("->").join(map)));
}
Path otherBasePath = cellRoot.relativize(MorePaths.getParentOrEmpty(buildFilePath));
if (!otherBasePath.equals(otherBasePath.getFileSystem().getPath(basePath))) {
throw new IllegalStateException(
String.format(
"Raw data claims to come from [%s], but we tried rooting it at [%s].",
basePath, otherBasePath));
}
return UnflavoredBuildTarget.of(
CellRelativePath.of(cellName, ForwardRelativePath.of(basePath)), name);
}
/**
* @return a list of headers that represents a chain of includes ending in a particular header.
*/
private List<Path> getPathToUntrackedHeader(
SourcePathResolverAdapter pathResolver, List<String> includeLines, Path header) {
// We parse the tree structure linearly by maintaining a stack of the current active parents.
Stack<Path> active_parents = new Stack<Path>();
for (String line : includeLines) {
int currentDeepLevel = countCharAtTheBeginning(line, ' ') - 1;
Preconditions.checkState(
currentDeepLevel <= active_parents.size(),
"Error parsing dependency file for %s",
prettyPrintFileName(inputPath, true));
while (currentDeepLevel < active_parents.size()) {
active_parents.pop();
}
Path currentHeader = filesystem.resolve(line.trim()).normalize();
currentHeader =
headerPathNormalizer
.getAbsolutePathForUnnormalizedPath(pathResolver, currentHeader)
.orElse(currentHeader);
active_parents.push(currentHeader);
if (currentHeader.equals(header)) {
return Lists.reverse(active_parents);
}
}
return Collections.singletonList(header);
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (dir.equals(sourcePath))
return FileVisitResult.CONTINUE;
else
return recursive ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE;
}
/**
* Open the asset folder.
*
* @param newAsset the asset folder.
*/
@FxThread
public void openAssetFolder(@NotNull final Path newAsset) {
final EditorConfig config = EditorConfig.getInstance();
final Path currentAsset = config.getCurrentAsset();
if (newAsset.equals(currentAsset)) return;
config.addOpenedAsset(newAsset);
config.setCurrentAsset(newAsset);
config.save();
FX_EVENT_MANAGER.notify(new ChangedCurrentAssetFolderEvent(newAsset));
}
/**
* Determines if <code>--force</code> should be used inorder to not accidentally overwrite a
* real certificate.
* <p>
* <p>
* All of the following must be met for <code>--force</code> to <b>NOT</b> be required:
* <ul>
* <li>The path to the keystore file is the default path: <code>[Gateway Keystore Directory]/gateway.jks</code></li>
* <li>The alias name for the key is the default name: <code>gateway-identity</code></li>
* <li>The relevant certificate does not exist or is self-signed</li>
* <li>The relevant certificate has a subject name ending in "OU=Test,O=Hadoop,L=Test,ST=Test,C=US"</li>
* </ul>
*
* @param config the Gateway configuration
* @param ks a {@link KeystoreService} implementation
* @return <code>true</code> if <code>--force</code> is required; otherwise <code>false</code>
*/
private boolean isForceRequired(GatewayConfig config, KeystoreService ks) {
// Test the path of the keystore file
Path defaultKeystorePath = Paths.get(config.getGatewayKeystoreDir(), GatewayConfig.DEFAULT_GATEWAY_KEYSTORE_NAME).toAbsolutePath();
Path actualKeystorePath = Paths.get(config.getIdentityKeystorePath()).toAbsolutePath();
if (!defaultKeystorePath.equals(actualKeystorePath)) {
// The path is not the default path: --force is required
return true;
}
// Test the alias name for the key
if (!GatewayConfig.DEFAULT_IDENTITY_KEY_ALIAS.equals(config.getIdentityKeyAlias())) {
// The alias name for the key is not the default name (gateway-identity): --force is required
return true;
}
// Test the certificate
try {
Certificate certificate = ks.getCertificateForGateway();
if (certificate instanceof X509Certificate) {
if (!X509CertificateUtil.isSelfSignedCertificate(certificate)) {
// The relevant certificate exists and is not self-signed: --force is required
return true;
} else if (!((X509Certificate) certificate).getSubjectDN().getName().matches(".*?,\\s*OU=Test,\\s*O=Hadoop,\\s*L=Test,\\s*ST=Test,\\s*C=US")) {
// The subject name of certificate does not end with "OU=Test,O=Hadoop,L=Test,ST=Test,C=US": --force is required
return true;
}
}
} catch (KeyStoreException | KeystoreServiceException e) {
// A certificate was (probably) not previously created...
}
// All indicators point to a previously created test certificate: --force is not required
return false;
}
private boolean areFilesTheSame(Path a, Path b) throws IOException {
if (a.equals(b)) {
return true;
}
final long totalSize = Files.size(a);
if (totalSize != Files.size(b)) {
return false;
}
try (InputStream ia = Files.newInputStream(a);
InputStream ib = Files.newInputStream(b)) {
final int bufSize = 8192;
final byte[] aBuf = new byte[bufSize];
final byte[] bBuf = new byte[bufSize];
for (int toRead = (int) totalSize; toRead > 0; ) {
final int chunkSize = Integer.min(toRead, bufSize);
ByteStreams.readFully(ia, aBuf, 0, chunkSize);
ByteStreams.readFully(ib, bBuf, 0, chunkSize);
for (int idx = 0; idx < chunkSize; idx++) {
if (aBuf[idx] != bBuf[idx]) {
return false;
}
}
toRead -= chunkSize;
}
}
return true;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (!dir.equals(basePath)) {
tarArchiveOutputStream.putArchiveEntry(new TarArchiveEntry(basePath.relativize(dir).toFile()));
tarArchiveOutputStream.closeArchiveEntry();
}
return FileVisitResult.CONTINUE;
}
Path resolve(Path relative) throws IOException {
final Path root = getRoot();
final Path full = root.resolve(relative).normalize().toAbsolutePath();
if (full.equals(root)) {
throw new IOException("The file path " + relative + " resolved to " + full
+ " is the root directory " + root);
} else if (!full.startsWith(root)) {
throw new IOException("The file path " + relative + " resolved to " + full
+ " is not a sub-path under root directory " + root);
}
return full;
}
@Nonnull
@MustNotContainNull
public static List<Topic> findTopicsRelatedToFile(@Nullable final File baseFolder, @Nonnull final File file, @Nonnull final MindMap map) {
final List<Topic> result = new ArrayList<>();
final Path theFile = file.isAbsolute() ? file.toPath() : new File(baseFolder, file.getAbsolutePath()).toPath();
final boolean folder = file.isDirectory();
for (final Topic t : map) {
final ExtraFile linkToFile = (ExtraFile) t.getExtras().get(Extra.ExtraType.FILE);
if (linkToFile != null) {
final MMapURI uri = linkToFile.getAsURI();
final Path linkFile = uri.asFile(baseFolder).toPath();
if (folder) {
if (linkFile.startsWith(theFile)) {
result.add(t);
}
} else if (linkFile.equals(theFile)) {
result.add(t);
}
}
}
return result;
}
/**
* Merge part file shards produced by {@link KeyIgnoringVCFOutputFormat} into a
* single file with the given header.
* @param partDirectory the directory containing part files
* @param outputFile the file to write the merged file to
* @param header the header for the merged file
* @throws IOException
*/
public static void mergeParts(final String partDirectory, final String outputFile,
final VCFHeader header) throws IOException {
// First, check for the _SUCCESS file.
final Path partPath = asPath(partDirectory);
final Path successPath = partPath.resolve("_SUCCESS");
if (!Files.exists(successPath)) {
throw new NoSuchFileException(successPath.toString(), null, "Unable to find _SUCCESS file");
}
final Path outputPath = asPath(outputFile);
if (partPath.equals(outputPath)) {
throw new IllegalArgumentException("Cannot merge parts into output with same " +
"path: " + partPath);
}
List<Path> parts = getFilesMatching(partPath, NIOFileUtil.PARTS_GLOB,
TabixUtils.STANDARD_INDEX_EXTENSION);
if (parts.isEmpty()) {
throw new IllegalArgumentException("Could not write bam file because no part " +
"files were found in " + partPath);
} else if (isBCF(parts)) {
throw new IllegalArgumentException("BCF files are not supported.");
}
Files.deleteIfExists(outputPath);
try (final OutputStream out = Files.newOutputStream(outputPath)) {
boolean blockCompressed = writeHeader(out, outputPath, parts, header);
mergeInto(parts, out);
if (blockCompressed) {
writeTerminatorBlock(out);
}
}
deleteRecursive(partPath);
}
@Test
public void testFilter() throws IOException {
File baseDir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
File nestedDir1 = new File(baseDir, "x");
Assert.assertTrue(nestedDir1.mkdirs());
File nestedDir2 = new File(baseDir, "y");
Assert.assertTrue(nestedDir2.mkdirs());
File file1 = new File(nestedDir1, "x.txt");
final File file2 = new File(nestedDir2, "y.txt");
File file3 = new File(nestedDir2, "x.txt");
File file4 = new File(nestedDir2, "x.x");
File dir5 = new File(nestedDir2, "d.txt"); // while i matches, because it is a dir, we ignore it
Assert.assertTrue(dir5.mkdirs());
Files.createFile(file1.toPath());
Files.createFile(file2.toPath());
Files.createFile(file3.toPath());
Files.createFile(file4.toPath());
GlobDirectoryStream dsRef;
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
return entry.equals(file2.toPath());
}
};
try (GlobDirectoryStream ds = new GlobDirectoryStream(baseDir.toPath(), Paths.get("*/*.txt"), filter)) {
dsRef = ds;
Iterator<Path> it = ds.iterator();
Assert.assertTrue(it.hasNext());
Set<Path> found = new HashSet<>();
found.add(it.next());
Assert.assertFalse(it.hasNext());
Assert.assertEquals(ImmutableSet.of(file2.toPath()), found);
}
Assert.assertEquals(0, dsRef.getOpenCounter());
}
/** @param input the given input stream must be reset later on
* @param path
* @return either the path of the root node of the given docview xml or {@code null} if no docview xml given
* @throws IOException */
private static Path getDocumentViewXmlRootPath(BufferedInputStream input, Path path) throws IOException {
Path name = path.getFileName();
Path rootPath = null;
int nameCount = path.getNameCount();
if (name.equals(Paths.get(Constants.DOT_CONTENT_XML))) {
if (nameCount > 1) {
rootPath = path.subpath(0, nameCount - 1);
} else {
rootPath = Paths.get("");
}
// correct suffix matching
} else if (name.toString().endsWith(".xml")) {
// we need to rely on a buffered input stream to be able to reset it later
input.mark(1024);
// analyze content
// this closes the input source internally, therefore protect against closing
// make sure to initialize the SLF4J logger appropriately (for the XmlAnalyzer)
try {
SerializationType type = XmlAnalyzer.analyze(new InputSource(new CloseShieldInputStream(input)));
if (type == SerializationType.XML_DOCVIEW) {
// remove .xml extension
String fileName = path.getFileName().toString();
fileName = fileName.substring(0, fileName.length() - ".xml".length());
if (nameCount > 1) {
rootPath = path.subpath(0, nameCount - 1).resolve(fileName);
} else {
rootPath = Paths.get(fileName);
}
}
} finally {
input.reset();
}
}
return rootPath;
}
protected ProjectConfig projectConfig(Path dir) {
if (projectConfig != null && dir.equals(projectDir)) {
return projectConfig;
}
Path dotHelidon = dir.resolve(DOT_HELIDON);
projectConfig = new ProjectConfig(dotHelidon);
projectDir = dir;
return projectConfig;
}
private boolean srcIsCreatedUnderRootFolder(Path input) {
return input.equals(folder.getRoot().toPath().resolve("src/main/java"))
|| input.equals(folder.getRoot().toPath().resolve("src/main/resources"));
}
@Override
public Optional<Map<String, String>> convert(HttpRequest httpRequest) throws MalformedURLException, UnsupportedEncodingException {
String requestUri = httpRequest.getUri();
Path requestUriPath = Paths.get(requestUri);
if (!((requestUri.startsWith(baseUrl)) || requestUri.startsWith("/"))) {
throw new IllegalArgumentException("I am not responsible for this request URL: " + requestUri);
}
if (requestUri.endsWith(LINK_INTERCEPTOR_MARKER)) {
httpRequest.setUri(requestUri.split(LINK_INTERCEPTOR_MARKER)[0]);
return Optional.empty();
}
for (ApplicationActionConfiguration applicationActionConfiguration: applicationActionConfigurations) {
ParameterConfiguration urlParameterConfiguration = applicationActionConfiguration
.getWebDriverAction()
.getParametersConfiguration()
.get(Constants.PAGE);
// first the easy case; if the value is hardcoded in the configuration
// and the current url matches, then we have found the action
if (!urlParameterConfiguration.isExposed()) {
Path expectedPath = Paths.get(baseUrl, urlParameterConfiguration.getValue());
Path relativeExpectedPath = Paths.get(urlParameterConfiguration.getValue());
if (expectedPath.equals(requestUriPath) || relativeExpectedPath.equals(requestUriPath)) {
return Optional.of(ImmutableMap.of(EVENT, applicationActionConfiguration.getName()));
}
} else {
String[] urlParts = requestUri.split(baseUrl);
if (urlParts.length < 2) {
return Optional.empty();
}
String urlContinuation = urlParts[1];
return Optional.of(ImmutableMap.of(
EVENT, applicationActionConfiguration.getName(),
urlParameterConfiguration.getAlias(), urlContinuation
));
}
}
return Optional.empty();
}
/** {@inheritDoc} */
@Override
public UnixSshPath relativize( Path other ) {
if ( other == null ) {
throw new NullPointerException();
}
if ( !(other instanceof UnixSshPath) ) {
throw new ProviderMismatchException();
}
UnixSshPath unixOther = (UnixSshPath) other;
if ( isAbsolute() && !unixOther.isAbsolute() ) {
throw new IllegalArgumentException( "this and other must have same isAbsolute" );
}
if ( getNameCount() == 0 ) {
return unixOther;
}
Path relative = null;
Path remainingOther = null;
Iterator<Path> otherIterator = unixOther.iterator();
for ( Path part : this ) {
if ( relative != null ) {
relative = relative.resolve( ".." );
continue;
}
if ( otherIterator.hasNext() ) {
Path otherPart = otherIterator.next();
if ( !part.equals( otherPart ) ) {
remainingOther = otherPart;
while ( otherIterator.hasNext() ) {
remainingOther = remainingOther.resolve(
otherIterator.next() );
}
relative = new UnixSshPath( getFileSystem(), ".." );
}
}
else {
relative = new UnixSshPath( getFileSystem(), ".." );
}
}
if ( relative == null ) {
while ( otherIterator.hasNext() ) {
if ( remainingOther == null ) {
remainingOther = new UnixSshPath( getFileSystem(), "" );
}
else {
remainingOther = remainingOther.resolve(
otherIterator.next() );
}
}
return remainingOther == null
? new UnixSshPath( getFileSystem(), "" )
: (UnixSshPath) remainingOther;
}
return remainingOther == null
? (UnixSshPath) relative
: (UnixSshPath) relative.resolve( remainingOther );
}