KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > importscrubber > SourceFile


1 package net.sourceforge.importscrubber;
2
3 import java.io.*;
4
5 /**
6  * Encapsulates operations on the Java source code file
7  *
8  * TODO: refactor this into a parser class - this constructor is getting heinous
9  */

10 public class SourceFile
11 {
12     private File _file;
13     private String JavaDoc _encoding;
14     private PackageStmt _package;
15     private String JavaDoc _classBody;
16     private ImportStatements _imports = new ImportStatements();
17     private String JavaDoc _firstCommentHeader;
18     private String JavaDoc _secondCommentHeader;
19
20     public SourceFile(File file, String JavaDoc encoding) throws IOException
21     {
22         _file = file;
23         _encoding = encoding;
24
25         // read in the source
26
FileInputStream inputstream = new FileInputStream(_file);
27         InputStreamReader reader = null;
28         if (_encoding != null) {
29             reader = new InputStreamReader(inputstream, _encoding);
30         } else {
31             reader = new InputStreamReader(inputstream);
32         }
33         BufferedReader buff = new BufferedReader(reader);
34
35         StringBuffer JavaDoc classBodyBuffer = new StringBuffer JavaDoc((int)file.length());
36         StringBuffer JavaDoc firstCommentHeaderBuffer = new StringBuffer JavaDoc();
37         StringBuffer JavaDoc secondCommentHeaderBuffer = new StringBuffer JavaDoc();
38
39         String JavaDoc currentLine = null;
40         boolean passedFirstCommentHeader = false;
41         boolean passedSecondCommentHeader = false;
42
43         while ((currentLine = buff.readLine()) != null) {
44             // discard imports
45
if (currentLine.startsWith(ImportStatements.MARKER)) {
46                 passedFirstCommentHeader = true;
47                 passedSecondCommentHeader = true;
48                 continue;
49             }
50
51             // check for package stmt
52
if (currentLine.startsWith(PackageStmt.MARKER)) {
53                 passedFirstCommentHeader = true;
54                 _package = new PackageStmt(currentLine);
55                 continue;
56             }
57
58             // TODO - what happens if there are no import statements and no package header?
59
// preserve comment headers, if any exist
60
if(!passedFirstCommentHeader) {
61                 firstCommentHeaderBuffer.append(currentLine);
62                 firstCommentHeaderBuffer.append(ImportScrubber.LINE_SEPARATOR);
63                 continue;
64             }
65
66             if(passedFirstCommentHeader && !passedSecondCommentHeader) {
67                 secondCommentHeaderBuffer.append(currentLine);
68                 secondCommentHeaderBuffer.append(ImportScrubber.LINE_SEPARATOR);
69                 continue;
70             }
71
72             // everything else is part of the class body
73
passedSecondCommentHeader = true;
74             classBodyBuffer.append(currentLine);
75             classBodyBuffer.append(ImportScrubber.LINE_SEPARATOR);
76         }
77
78         if (_package == null) {
79             _package = new PackageStmt();
80         }
81
82         buff.close();
83         inputstream.close();
84         reader.close();
85         if (ImportScrubber.DEBUG)
86             System.out.println("Done parsing source code file " + file.getAbsolutePath());
87
88         _classBody = classBodyBuffer.toString();
89         _firstCommentHeader = firstCommentHeaderBuffer.toString();
90         _secondCommentHeader = secondCommentHeaderBuffer.toString();
91     }
92
93     public void addImport(String JavaDoc className)
94     {
95         try
96         {
97             _imports.add(className);
98         } catch (Exception JavaDoc e) {
99             // funky classnames will result in ImportStatement throwing StringIndexOutOfBoundsException
100
System.out.println("Non-fatal, but unexpected error while processing " + className + " in " + _file + " --");
101             e.printStackTrace();
102         }
103     }
104
105     public void save(StatementFormat format) throws IOException
106     {
107         if (ImportScrubber.DEBUG)
108             System.out.println("Imports before pruning:" + _imports.getCount());
109         String JavaDoc maybeError = _imports.removeUnreferenced(_classBody);
110         if (maybeError != null) {
111             System.err.println("Skipping " + _file.getPath() + ": " + maybeError);
112             return;
113         }
114         _imports.removeLocalToPackage(_package);
115         int extIndex = _file.getName().length() - ".java".length();
116         String JavaDoc thisClass = _file.getName().substring(0, extIndex);
117         // doublecheck
118
if (_file.getName().substring(extIndex).compareToIgnoreCase(".java") != 0) {
119             System.err.println("Warning: not a .java file; can't prune inner classes");
120         } else {
121             _imports.removeInnerClasses(_package.getPkg() + "." + thisClass);
122         }
123
124         // we don't overwrite when DEBUG is on
125
if (ImportScrubber.DEBUG) {
126             System.out.println("Imports remaining:\n" + _imports.getOutput(format));
127         } else {
128             // push everything together
129
StringBuffer JavaDoc finishedSource = new StringBuffer JavaDoc((int)(_classBody.length() * 1.1));
130             finishedSource.append(_firstCommentHeader);
131             finishedSource.append(_package.getOutput());
132
133             finishedSource.append(removeMultipleBlankLines(_secondCommentHeader));
134             finishedSource.append(_imports.getOutput(format));
135
136             _classBody = ImportScrubber.LINE_SEPARATOR + removeMultipleBlankLines(_classBody);
137             finishedSource.append(_classBody);
138
139             // write it to disk
140
OutputStreamWriter osw = null;
141             if (_encoding != null) {
142                 osw = new OutputStreamWriter(new FileOutputStream(_file), _encoding);
143             } else {
144                 osw = new OutputStreamWriter(new FileOutputStream(_file));
145             }
146
147             BufferedWriter writer = new BufferedWriter(osw);
148             writer.write(finishedSource.toString());
149             writer.close();
150         }
151     }
152
153     private String JavaDoc removeMultipleBlankLines(String JavaDoc in)
154     {
155         while (in.startsWith(ImportScrubber.LINE_SEPARATOR)) {
156             in = in.substring(ImportScrubber.LINE_SEPARATOR.length());
157         }
158         return in;
159     }
160 }
161
Popular Tags