下面列出了java.nio.file.Path#endsWith ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static List<Archive> init() {
List<Archive> result = new ArrayList<>();
Path home = Paths.get(System.getProperty("java.home"));
try {
if (home.endsWith("jre")) {
// jar files in <javahome>/jre/lib
result.addAll(addJarFiles(home.resolve("lib")));
} else if (Files.exists(home.resolve("lib"))) {
// either a JRE or a jdk build image
Path classes = home.resolve("classes");
if (Files.isDirectory(classes)) {
// jdk build outputdir
result.add(new JDKArchive(classes, ClassFileReader.newInstance(classes)));
}
// add other JAR files
result.addAll(addJarFiles(home.resolve("lib")));
} else {
throw new RuntimeException("\"" + home + "\" not a JDK home");
}
return result;
} catch (IOException e) {
throw new Error(e);
}
}
static List<Path> getJREClasses() throws IOException {
List<Path> result = new ArrayList<Path>();
Path home = Paths.get(System.getProperty("java.home"));
if (home.endsWith("jre")) {
// jar files in <javahome>/jre/lib
// skip <javahome>/lib
result.addAll(addJarFiles(home.resolve("lib")));
} else if (home.resolve("lib").toFile().exists()) {
// either a JRE or a jdk build image
File classes = home.resolve("classes").toFile();
if (classes.exists() && classes.isDirectory()) {
// jdk build outputdir
result.add(classes.toPath());
}
// add other JAR files
result.addAll(addJarFiles(home.resolve("lib")));
} else {
throw new RuntimeException("\"" + home + "\" not a JDK home");
}
return result;
}
/**
* Escapes forward slashes in a Path as a String that is safe to consume with other tools (such as
* gcc). On Unix systems, this is equivalent to {@link java.nio.file.Path Path.toString()}.
*
* @param path the Path to escape
* @return the escaped Path
*/
public static String escapePathForCIncludeString(Path path) {
if (File.separatorChar != '\\') {
return path.toString();
}
StringBuilder result = new StringBuilder();
if (path.startsWith(File.separator)) {
result.append("\\\\");
}
for (Iterator<Path> iterator = path.iterator(); iterator.hasNext(); ) {
result.append(iterator.next());
if (iterator.hasNext()) {
result.append("\\\\");
}
}
if (path.getNameCount() > 0 && path.endsWith(File.separator)) {
result.append("\\\\");
}
return result.toString();
}
static List<Path> getJREClasses() throws IOException {
List<Path> result = new ArrayList<Path>();
Path home = Paths.get(System.getProperty("java.home"));
if (home.endsWith("jre")) {
// jar files in <javahome>/jre/lib
// skip <javahome>/lib
result.addAll(addJarFiles(home.resolve("lib")));
} else if (home.resolve("lib").toFile().exists()) {
// either a JRE or a jdk build image
File classes = home.resolve("classes").toFile();
if (classes.exists() && classes.isDirectory()) {
// jdk build outputdir
result.add(classes.toPath());
}
// add other JAR files
result.addAll(addJarFiles(home.resolve("lib")));
} else {
throw new RuntimeException("\"" + home + "\" not a JDK home");
}
return result;
}
public void watch() throws InterruptedException, IOException {
try {
final Path directoryPath = file.toPath().getParent();
final WatchService watchService = FileSystems.getDefault().newWatchService();
directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
final WatchKey wk = watchService.take();
for (WatchEvent<?> event : wk.pollEvents()) {
final Path fileChangedPath = (Path) event.context();
if (fileChangedPath.endsWith(file.getName())) {
onModified();
}
}
wk.reset();
}
} catch (Exception e) {
logger.error("exception when handling change of mock file: {}", e.getMessage());
}
}
private void pollShutdown(Drillbit drillbit) throws IOException, InterruptedException {
final String drillHome = System.getenv("DRILL_HOME");
final String gracefulFile = System.getenv("GRACEFUL_SIGFILE");
final Path drillHomePath;
if (drillHome == null || gracefulFile == null) {
logger.warn("Cannot access graceful file. Graceful shutdown from command line will not be supported.");
return;
}
try {
drillHomePath = Paths.get(drillHome);
} catch (InvalidPathException e) {
logger.warn("Cannot access graceful file. Graceful shutdown from command line will not be supported.");
return;
}
boolean triggered_shutdown = false;
WatchKey wk = null;
try (final WatchService watchService = drillHomePath.getFileSystem().newWatchService()) {
drillHomePath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
while (!triggered_shutdown) {
wk = watchService.take();
for (WatchEvent<?> event : wk.pollEvents()) {
final Path changed = (Path) event.context();
if (changed != null && changed.endsWith(gracefulFile)) {
drillbit.interruptPollShutdown = false;
triggered_shutdown = true;
drillbit.close();
break;
}
}
}
} finally {
if (wk != null) {
wk.cancel();
}
}
}
private void verifySymLinks(String bindir) throws IOException {
File binDir = new File(bindir);
System.err.println("verifying links in: " + bindir);
File isaDir = new File(binDir, getArch()).getAbsoluteFile();
if (!isaDir.exists()) {
throw new RuntimeException("dir: " + isaDir + " does not exist");
}
try (DirectoryStream<Path> ds = Files.newDirectoryStream(binDir.toPath())) {
for (Path p : ds) {
if (symlinkExcludes.matcher(p.toString()).matches() ||
Files.isDirectory(p, NOFOLLOW_LINKS)) {
continue;
}
Path link = new File(isaDir, p.getFileName().toString()).toPath();
if (Files.isSymbolicLink(link)) {
Path target = Files.readSymbolicLink(link);
if (target.startsWith("..") && p.endsWith(target.getFileName())) {
// System.out.println(target + " OK");
continue;
}
System.err.println("target:" + target);
System.err.println("file:" + p);
}
throw new RuntimeException("could not find link to " + p);
}
}
}
protected void runImpl(CommandLine cli) throws Exception {
raiseLogLevelUnlessVerbose(cli);
String zkHost = getZkHost(cli);
if (zkHost == null) {
throw new IllegalStateException("Solr at " + cli.getOptionValue("solrUrl") +
" is running in standalone server mode, downconfig can only be used when running in SolrCloud mode.\n");
}
try (SolrZkClient zkClient = new SolrZkClient(zkHost, 30000)) {
echoIfVerbose("\nConnecting to ZooKeeper at " + zkHost + " ...", cli);
String confName = cli.getOptionValue("confname");
String confDir = cli.getOptionValue("confdir");
Path configSetPath = Paths.get(confDir);
// we try to be nice about having the "conf" in the directory, and we create it if it's not there.
if (configSetPath.endsWith("/conf") == false) {
configSetPath = Paths.get(configSetPath.toString(), "conf");
}
if (Files.exists(configSetPath) == false) {
Files.createDirectories(configSetPath);
}
echo("Downloading configset " + confName + " from ZooKeeper at " + zkHost +
" to directory " + configSetPath.toAbsolutePath());
zkClient.downConfig(confName, configSetPath);
} catch (Exception e) {
log.error("Could not complete downconfig operation for reason: {}", e.getMessage());
throw (e);
}
}
private static List<Archive> init() {
List<Archive> result = new ArrayList<>();
Path home = Paths.get(System.getProperty("java.home"));
try {
if (home.endsWith("jre")) {
// jar files in <javahome>/jre/lib
result.addAll(addJarFiles(home.resolve("lib")));
if (home.getParent() != null) {
// add tools.jar and other JDK jar files
Path lib = home.getParent().resolve("lib");
if (Files.exists(lib)) {
result.addAll(addJarFiles(lib));
}
}
} else if (Files.exists(home.resolve("lib"))) {
// either a JRE or a jdk build image
Path classes = home.resolve("classes");
if (Files.isDirectory(classes)) {
// jdk build outputdir
result.add(new JDKArchive(classes));
}
// add other JAR files
result.addAll(addJarFiles(home.resolve("lib")));
} else {
throw new RuntimeException("\"" + home + "\" not a JDK home");
}
return result;
} catch (IOException e) {
throw new Error(e);
}
}
public static String archiveNameForClassesDir(Path path) {
if (path.endsWith(TARGET_CLASSES)) {
// Maven
return path.subpath(path.getNameCount() - 3, path.getNameCount() - 2).toString() + JAR;
} else if (path.endsWith(BUILD_CLASSES_MAIN) || path.endsWith(BUILD_RESOURCES_MAIN)) {
// Gradle + Gradle 4+
return path.subpath(path.getNameCount() - 4, path.getNameCount() - 3).toString() + JAR;
} else {
return UUID.randomUUID().toString() + JAR;
}
}
private static List<Archive> init() {
List<Archive> result = new ArrayList<>();
Path home = Paths.get(System.getProperty("java.home"));
try {
if (home.endsWith("jre")) {
// jar files in <javahome>/jre/lib
result.addAll(addJarFiles(home.resolve("lib")));
if (home.getParent() != null) {
// add tools.jar and other JDK jar files
Path lib = home.getParent().resolve("lib");
if (Files.exists(lib)) {
result.addAll(addJarFiles(lib));
}
}
} else if (Files.exists(home.resolve("lib"))) {
// either a JRE or a jdk build image
Path classes = home.resolve("classes");
if (Files.isDirectory(classes)) {
// jdk build outputdir
result.add(new JDKArchive(classes));
}
// add other JAR files
result.addAll(addJarFiles(home.resolve("lib")));
} else {
throw new RuntimeException("\"" + home + "\" not a JDK home");
}
return result;
} catch (IOException e) {
throw new Error(e);
}
}
private void verifySymLinks(String bindir) throws IOException {
File binDir = new File(bindir);
System.err.println("verifying links in: " + bindir);
File isaDir = new File(binDir, getArch()).getAbsoluteFile();
if (!isaDir.exists()) {
throw new RuntimeException("dir: " + isaDir + " does not exist");
}
try (DirectoryStream<Path> ds = Files.newDirectoryStream(binDir.toPath())) {
for (Path p : ds) {
if (symlinkExcludes.matcher(p.toString()).matches() ||
Files.isDirectory(p, NOFOLLOW_LINKS)) {
continue;
}
Path link = new File(isaDir, p.getFileName().toString()).toPath();
if (Files.isSymbolicLink(link)) {
Path target = Files.readSymbolicLink(link);
if (target.startsWith("..") && p.endsWith(target.getFileName())) {
// System.out.println(target + " OK");
continue;
}
System.err.println("target:" + target);
System.err.println("file:" + p);
}
throw new RuntimeException("could not find link to " + p);
}
}
}
@Override
protected boolean isIgnored(Path path, String pathStr) {
if (path.endsWith("pom.xml"))
return false; // never ignore pom.xml!
if (isFile(pathStr, IGNORED_FILES))
return true; // ignore ignored files
if (isBelowFolder(pathStr, IGNORED_FOLDERS))
return true; // ignore files in ignored folders
if (hasExtension(path, ".prefs"))
return true; // ignore Eclipse preferences
if (hasExtension(path, ".bib"))
return true; // ignore BibTeX files
return false;
}
private Path regularOutputDirectory(MavenProject project, Path outputDirectory) {
Path cloverTargetPath = Paths.get(project.getBuild().getDirectory());
Path targetPath = cloverTargetPath.getParent();
if (!targetPath.endsWith("target")) {
log.warn("Guessing that target directory is " + targetPath + ", this might not be correct.");
}
Path outputDirectoryRelativeToCloverDirectory = cloverTargetPath.relativize(outputDirectory);
return targetPath.resolve(outputDirectoryRelativeToCloverDirectory);
}
/**
* Recursively finds the specified filename in the specified directory
*
* @param downloadDirectory to search
* @param fileName to discover
* @return discovered file path or null
*/
public static Path getFile(Path downloadDirectory, String fileName)
{
try
{
DirectoryStream<Path> stream = Files.newDirectoryStream(downloadDirectory);
Iterator<Path> it = stream.iterator();
while(it.hasNext())
{
Path path = it.next();
if(Files.isDirectory(path) && !path.equals(getOutputDirectory(downloadDirectory)))
{
Path subPath = getFile(path, fileName);
if(subPath != null && subPath.endsWith(fileName))
{
return subPath;
}
}
else if(path.endsWith(fileName))
{
return path;
}
}
}
catch(IOException ioe)
{
System.out.println("Error while searching for [" + fileName + "]");
System.exit(EXIT_CODE_IO_ERROR);
}
return null;
}
private void verifySymLinks(String bindir) throws IOException {
File binDir = new File(bindir);
System.err.println("verifying links in: " + bindir);
File isaDir = new File(binDir, getArch()).getAbsoluteFile();
if (!isaDir.exists()) {
throw new RuntimeException("dir: " + isaDir + " does not exist");
}
try (DirectoryStream<Path> ds = Files.newDirectoryStream(binDir.toPath())) {
for (Path p : ds) {
if (symlinkExcludes.matcher(p.toString()).matches() ||
Files.isDirectory(p, NOFOLLOW_LINKS)) {
continue;
}
Path link = new File(isaDir, p.getFileName().toString()).toPath();
if (Files.isSymbolicLink(link)) {
Path target = Files.readSymbolicLink(link);
if (target.startsWith("..") && p.endsWith(target.getFileName())) {
// System.out.println(target + " OK");
continue;
}
System.err.println("target:" + target);
System.err.println("file:" + p);
}
throw new RuntimeException("could not find link to " + p);
}
}
}
private void verifySymLinks(String bindir) throws IOException {
File binDir = new File(bindir);
System.err.println("verifying links in: " + bindir);
File isaDir = new File(binDir, getArch()).getAbsoluteFile();
if (!isaDir.exists()) {
throw new RuntimeException("dir: " + isaDir + " does not exist");
}
try (DirectoryStream<Path> ds = Files.newDirectoryStream(binDir.toPath())) {
for (Path p : ds) {
if (symlinkExcludes.matcher(p.toString()).matches() ||
Files.isDirectory(p, NOFOLLOW_LINKS)) {
continue;
}
Path link = new File(isaDir, p.getFileName().toString()).toPath();
if (Files.isSymbolicLink(link)) {
Path target = Files.readSymbolicLink(link);
if (target.startsWith("..") && p.endsWith(target.getFileName())) {
// System.out.println(target + " OK");
continue;
}
System.err.println("target:" + target);
System.err.println("file:" + p);
}
throw new RuntimeException("could not find link to " + p);
}
}
}
public static void zip(Path targetFile, Path... inputFiles) throws IOException {
if (inputFiles.length == 0) {
return;
}
// recurse into a single base-directory
if (inputFiles.length == 1 && Files.isDirectory(inputFiles[0])) {
final Path[] inputs;
try (Stream<Path> search = Files.find(inputFiles[0], Integer.MAX_VALUE, (p, a) -> true)) {
inputs = search.toArray(Path[]::new);
} catch (IOException inner) {
throw inner;
}
zip(targetFile, inputs);
return;
}
// the root to relativize paths against for the name-resolution of the Zip entries
final Path root = Files.isDirectory(inputFiles[0]) ? inputFiles[0] : inputFiles[0].getParent();
// ensure parent directory exists
Files.createDirectories(targetFile.getParent());
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(targetFile,
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING))) {
for (Path externalFile : inputFiles) {
// skip root
if (externalFile.equals(root)
// skip the target file if it's within the resolved input files
|| externalFile.endsWith(targetFile) || targetFile.endsWith(externalFile)) {
continue;
}
// only copy the content of regular files
if (!Files.isRegularFile(externalFile)) {
continue;
}
final Path relative = root.relativize(externalFile);
ZipEntry entry = new ZipEntry(relative.toString());
zos.putNextEntry(entry);
Files.copy(externalFile, zos);
zos.closeEntry();
}
zos.finish();
}
}
void registerKey(Path dir, WatchKey key) throws FileNotFoundException {
dir = dir.toAbsolutePath();
File dirFile = dir.toFile();
// we should only be getting directories here.
if (!dirFile.isDirectory()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Not adding file {}", dir.toAbsolutePath());
}
return;
}
final int dirLength = dir.getNameCount() - 1;
if (!dir.startsWith(homeDirectoryBasePath) && dirLength != homeDirNameCount) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Not adding non home directory {}", dir.toAbsolutePath());
}
return;
} else if (dirLength <= homeDirNameCount) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("adding home directory {}", dir.toAbsolutePath());
}
addWatchKey(key, dir);
return;
} else if (dir.endsWith(".ssh")) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("adding home/<user>/.ssh directory {}", dir.toAbsolutePath());
}
String userName = dir.getName(dir.getNameCount() - 2).toString();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("got user {} for {} ", userName, dirFile.getAbsolutePath());
}
File target = new File(dirFile, AuthorizedKeysFileScanner.AUTHORIZED_KEYS_NAME);
authorizedKeysMap.updateUser(userName, target.getAbsolutePath(),
AuthorizedKeysFileScanner.getStream(userName, target));
addWatchKey(key, dir);
// we need to remove the home dir now.
removeWatchKey(dir.getParent());
return;
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Not adding non .ssh dir {}", dir.toAbsolutePath());
}
}
}
static boolean isClassFile(Path p) {
return p.endsWith(".class") && !p.endsWith("module-info.class") && Files.isRegularFile(p);
}