summaryrefslogtreecommitdiffstats
path: root/src/main/java/com/kitfox/util/ServicesListerAntTask.java
blob: 7d8bc4c75ff3fd20cfd7974c43f94b7d097d6df8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/*
 * ServicesListerAntTask.java
 *
 * Created on September 17, 2006, 4:08 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.kitfox.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import org.apache.tools.ant.taskdefs.DefBase;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.resources.FileResource;

/**
 * This ant task examines a directory hierarchy containing .class files and
 * constructs lists of all classes that extend a given base class.  This
 * is meant to facilitate the generation of META-INF/services lists
 * for jar files.
 *
 * <code>
 * &lt;servicesLister&gt;
 *     &lt;examinepath&gt;
 *         &lt;pathelement location="${path-to-find-classfiles-to-be-analyzed}"&gt;
 *     &lt;/examinepath&gt;
 *     &lt;classpath&gt;
 *         &lt;pathelement location="${classpath-needed-to-construct-Class-objects-of-classes-in-examine-path}"&gt;
 *     &lt;/classpath&gt;
 *     &lt;service className="name.of.class.to.build.list.For1" toDir="location/to/save/generated.list1"&gt;
 *     &lt;service className="name.of.class.to.build.list.For2" toDir="location/to/save/generated.list2"&gt;
 * &lt;/servicesLister&gt;
 * </code>
 * 
 * @author kitfox
 */
public class ServicesListerAntTask extends DefBase
{
    /**
     * Contains info for a single service to generate a list for.  There may be 
     * zero or more services tags embedded in the servicesLister task.
     *
     * If the toFile parameter is set to the name of a directory, the output
     * file name is computed at new File(toFile, className)
     */
    public class Service
    {
        private String className;
        private File toFile;
        private File toDir;
        private Class targetClass;

        ArrayList<String> targets = new ArrayList<String>();
        
        public String getClassName()
        {
            return className;
        }

        public void setClassName(String className)
        {
            this.className = className;
        }

        public File getToFile()
        {
            return toFile;
        }

        public void setToFile(File toFile)
        {
            this.toFile = toFile;
        }

        public File getToDir()
        {
            return toDir;
        }

        public void setToDir(File toDir)
        {
            if (toDir.exists() && !toDir.isDirectory())
            {
                throw new BuildException("toDir argument must be a directory: " + toDir);
            }
            this.toDir = toDir;
        }

        public Class getTargetClass()
        {
            return targetClass;
        }

        public void setTargetClass(Class targetClass)
        {
            this.targetClass = targetClass;
        }

        private void writeTarget(String className)
        {
            targets.add(className);
        }

        private void writeToFile()
        {
            try
            {
                if (toFile != null)
                {
                    if (toFile.exists() && toFile.isDirectory())
                    {
                        toFile = new File(toFile, className);
                    }
                }
                else
                {
                    if (toDir == null)
                    {
                        throw new BuildException("Must specify either a toFile or a toDir parameter");
                    }
                    toFile = new File(toDir, className);
                }
                
                
                //Make sure parent directory exists
                File parent = toFile.getParentFile();
                if (!parent.exists())
                {
                    parent.mkdirs();
                }
                
                FileWriter fout = new FileWriter(toFile);
                PrintWriter pw = new PrintWriter(new BufferedWriter(fout));

                pw.println("#Automatically generated services list");
                pw.println("#Mark McKay - " + new Date());

                for (String target: targets)
                {
                    pw.println(target);
                }
                
                pw.close();
            }
            catch (IOException e)
            {
                throw new BuildException(e);
            }
        }
    }
    
    Path examinePath;
//    ResourceCollection targetRes;
    ArrayList<Service> services = new ArrayList<Service>();
    
    /**
     * The examine path should be a subset of the classpath and include all the
     * classes that should be examined for possible inclusion in the services list.
     */
    public Path createExaminePath() throws BuildException
    {
        if (examinePath == null)
        {
            examinePath = new Path(getProject());
            return examinePath;
        }
        throw new BuildException("Only one examine path can be set");
    }

    /*
    public void addFileSet(FileSet fileSet)
    {
        if (this.targetRes != null)
        {
            throw new BuildException("Resources to be examined set multiple times");
        }
        this.targetRes = fileSet;
    }
     */
    
    public Service createService()
    {
        Service service = new Service();
        services.add(service);
        return service;
    }
    
    /**
     * Creates a new instance of ServicesListerAntTask
     */
    public ServicesListerAntTask()
    {
    }
    
    static final FilenameFilter FFILTER_CLASS = new FilenameFilter()
    {
        public boolean accept(File dir, String name)
        {
            return name.endsWith(".class");
        }
    };
    
    public void scanPath(ClassLoader loader, File dir, File pathRoot)
    {
        String pathAbs = pathRoot.getAbsolutePath();
//System.err.println("***Abs path: " + pathAbs);
//        File[] fileList = dir.listFiles(FFILTER_CLASS);
        for (File file: dir.listFiles())
        {
            if (file.getName().endsWith(".class"))
            {
                String fileAbs = file.getAbsolutePath();
//System.err.println("***Abs file: " + fileAbs);
                String relName = fileAbs.substring(pathAbs.length() + 1, fileAbs.length() - ".class".length());
                relName = relName.replaceAll("[/\\\\]", ".");
//System.err.println("***Rel name: " + relName);
                Class cls;
                try
                {
                    cls = loader.loadClass(relName);
                } 
                catch (ClassNotFoundException ex)
                {
                    throw new BuildException(ex);
                }

                if (cls == null)
                {
                    log("Could not examine class " + file);
                    continue;
                }
                else 
                {
                    //Ignore classes that cannot be instantiated
                    int mod = cls.getModifiers();
                    if (!Modifier.isPublic(mod) || Modifier.isAbstract(mod) || Modifier.isInterface(mod))
                    {
                        continue;
                    }
                }

                for (Service service: services)
                {
                    if (service.getTargetClass().isAssignableFrom(cls))
                    {
                        service.writeTarget(relName);
                    }
                }
            }
            else if (file.isDirectory())
            {
                scanPath(loader, file, pathRoot);
            }
        }
    }
    
    public void execute() throws BuildException
    {
        if (examinePath == null)
        {
            throw new BuildException("Examine path not set - please specify path to files to check for services");
        }

        ClassLoader loader = createLoader();
        
        for (Service service: services)
        {
            String name = service.getClassName();
            Class cls;
            try
            {
                cls = loader.loadClass(name);
            } 
            catch (ClassNotFoundException ex)
            {
                throw new BuildException(String.format("Could not find %s in classpath", name), ex);
            }
            service.setTargetClass(cls);
        }
        
        
        for (Iterator it = examinePath.iterator(); it.hasNext();)
        {
            Resource res = (Resource)it.next();
            if (!(res instanceof FileResource)) continue;
            
//System.err.println("*****Resource " + res.getName() + ", " + res.getClass().getName() + ", " + res.toString());
            File root = ((FileResource)res).getFile();
//System.err.println("*****File " + Name() + " " + res);

            //Find all .class files under the path
            scanPath(loader, root, root);
        }
        

        //Write all to disk
        for (Service service: services)
        {
            service.writeToFile();
        }        
        
    }
    
}