FSInfo.java revision 3155:30e288cb2d22
1 2package com.sun.tools.javac.file; 3 4import java.io.IOException; 5import java.nio.file.Files; 6import java.nio.file.Path; 7import java.nio.file.Paths; 8import java.util.ArrayList; 9import java.util.Collections; 10import java.util.List; 11import java.util.StringTokenizer; 12import java.util.jar.Attributes; 13import java.util.jar.JarFile; 14import java.util.jar.Manifest; 15 16import com.sun.tools.javac.util.Context; 17 18/** 19 * Get meta-info about files. Default direct (non-caching) implementation. 20 * @see CacheFSInfo 21 * 22 * <p><b>This is NOT part of any supported API. 23 * If you write code that depends on this, you do so at your own risk. 24 * This code and its internal interfaces are subject to change or 25 * deletion without notice.</b> 26 */ 27public class FSInfo { 28 29 /** Get the FSInfo instance for this context. 30 * @param context the context 31 * @return the Paths instance for this context 32 */ 33 public static FSInfo instance(Context context) { 34 FSInfo instance = context.get(FSInfo.class); 35 if (instance == null) 36 instance = new FSInfo(); 37 return instance; 38 } 39 40 protected FSInfo() { 41 } 42 43 protected FSInfo(Context context) { 44 context.put(FSInfo.class, this); 45 } 46 47 public Path getCanonicalFile(Path file) { 48 try { 49 return file.toRealPath(); 50 } catch (IOException e) { 51 return file.toAbsolutePath().normalize(); 52 } 53 } 54 55 public boolean exists(Path file) { 56 return Files.exists(file); 57 } 58 59 public boolean isDirectory(Path file) { 60 return Files.isDirectory(file); 61 } 62 63 public boolean isFile(Path file) { 64 return Files.isRegularFile(file); 65 } 66 67 public List<Path> getJarClassPath(Path file) throws IOException { 68 Path parent = file.getParent(); 69 try (JarFile jarFile = new JarFile(file.toFile())) { 70 Manifest man = jarFile.getManifest(); 71 if (man == null) 72 return Collections.emptyList(); 73 74 Attributes attr = man.getMainAttributes(); 75 if (attr == null) 76 return Collections.emptyList(); 77 78 String path = attr.getValue(Attributes.Name.CLASS_PATH); 79 if (path == null) 80 return Collections.emptyList(); 81 82 List<Path> list = new ArrayList<>(); 83 84 for (StringTokenizer st = new StringTokenizer(path); 85 st.hasMoreTokens(); ) { 86 String elt = st.nextToken(); 87 Path f = Paths.get(elt); 88 if (!f.isAbsolute() && parent != null) 89 f = parent.resolve(f).toAbsolutePath(); 90 list.add(f); 91 } 92 93 return list; 94 } 95 } 96} 97