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