Dateiverwaltung für die WebBox
ulrich
2017-03-20 d9d37bcb9b8550280c5a5737527bb81dad58256b
commit | author | age
0ac262 1 /*
U 2     Dateiverwaltung - File management in your browser
3     Copyright (C) 2017 Ulrich Hilger, http://uhilger.de
4
5     This program is free software: you can redistribute it and/or modify
6     it under the terms of the GNU Affero General Public License as
7     published by the Free Software Foundation, either version 3 of the
8     License, or (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU Affero General Public License for more details.
14
15     You should have received a copy of the GNU Affero General Public License
16     along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18 package de.uhilger.filecms.api;
19
e3043f 20 import de.uhilger.filecms.data.CompilerIssue;
0ac262 21 import java.io.File;
72e43d 22 import java.io.FileFilter;
0ac262 23 import java.io.IOException;
U 24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Locale;
72e43d 29 import java.util.logging.Level;
0ac262 30 import java.util.logging.Logger;
U 31 import javax.tools.Diagnostic;
32 import javax.tools.DiagnosticCollector;
33 import javax.tools.JavaCompiler;
34 import javax.tools.JavaFileObject;
35 import javax.tools.StandardJavaFileManager;
36 import javax.tools.ToolProvider;
a450f2 37 import org.apache.commons.io.FileUtils;
0ac262 38
U 39 /**
40  *
41  */
72e43d 42 public class CompileService extends Api {
0ac262 43   
U 44   private static final Logger logger = Logger.getLogger(CompileService.class.getName());
72e43d 45     
U 46   public List<CompilerIssue> compileAll(String relPath) {
47     logger.fine(relPath);
48     List<CompilerIssue> compilerIssues = new ArrayList();
49     try {
50       File targetDir = getTargetDir(relPath);
51       ArrayList<File> files = new ArrayList();
52       collectFiles(files, targetDir, new JavaFileFilter());
53       JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
54       DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector();
55       StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
56       Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);
a450f2 57       
d9d37b 58       
U 59       final Iterable<String> options = buildOptions(targetDir);
60       
a450f2 61       compiler.getTask(null, null, diagnostics, options, null, compilationUnits).call();
72e43d 62       fileManager.close();
a450f2 63       collectResults(diagnostics, compilerIssues, relPath);
72e43d 64     } catch(Exception ex) {
U 65       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
66     }
67     return compilerIssues;
f23f2b 68   }
U 69   
a450f2 70   private void collectResults(DiagnosticCollector<JavaFileObject> diagnostics, List<CompilerIssue> compilerIssues, String relPath) {
f23f2b 71     List compileResults = diagnostics.getDiagnostics();
U 72     Iterator i = compileResults.iterator();
73     while (i.hasNext()) {
74       Object o = i.next();
75       Diagnostic<? extends JavaFileObject> err;
76       if (o instanceof Diagnostic) {
77         err = (Diagnostic) o;
78         CompilerIssue issue = new CompilerIssue();
79         issue.setKind(err.getKind().name());
80         issue.setLineNumber(err.getLineNumber());
81         issue.setMessage(err.getMessage(Locale.GERMANY));
a450f2 82         
U 83         String srcName = err.getSource().getName().replace("\\", "/");
84         String cleanRelPath = relPath.replace(HOME_DIR_NAME + "/", "").replace(PUB_DIR_NAME + "/", "");
85         int pos = srcName.indexOf(cleanRelPath);
86         String className = srcName.substring(pos + cleanRelPath.length());
87         issue.setSourceName(className.replace("/", ".").substring(1));
88         //issue.setSourceName(srcName + "\r\n" + relPath);
f23f2b 89         compilerIssues.add(issue);
U 90       }
91     }
72e43d 92   }
0ac262 93   
72e43d 94   private void collectFiles(ArrayList<File> files, File dir, FileFilter filter) {
U 95     File[] dirFiles = dir.listFiles(filter);
96     for(int i = 0; i < dirFiles.length; i++) {
97       if(dirFiles[i].isDirectory()) {
98         logger.fine("drill down to " + dirFiles[i].getAbsolutePath());
99         collectFiles(files, dirFiles[i], filter);
100       } else {
101         logger.fine("add " + dirFiles[i].getAbsolutePath());
102         files.add(dirFiles[i]);
103       }
104     }
105   }
106   
107   public class JavaFileFilter implements FileFilter {
108
109     @Override
110     public boolean accept(File pathname) {
111       boolean doAccept = false;
112       if(pathname.getName().endsWith(".java") || pathname.isDirectory()) {
113         doAccept = true;
114       }
115       return doAccept;
116     }
117   
118   }
0ac262 119   
d9d37b 120   public class JarFileFilter implements FileFilter {
U 121
122     @Override
123     public boolean accept(File pathname) {
124       boolean doAccept = false;
125       if(pathname.getName().endsWith(".jar")) {
126         doAccept = true;
127       }
128       return doAccept;
129     }
130   
131   }
132   
fd0b4c 133   /**
U 134    * 
135    * @param relPath
136    * @param fileNames
137    * @param mode 0 = test, 1 = build
138    * @return
139    * @throws IOException 
140    */
141   public List<CompilerIssue> compile(String relPath, List fileNames, String mode) throws IOException {
0ac262 142     File targetDir = getTargetDir(relPath);
U 143     ArrayList<File> files = new ArrayList();
144     for(int i=0; i < fileNames.size(); i++) {
145       Object o = fileNames.get(i);
146       if(o instanceof ArrayList) {
147         ArrayList al = (ArrayList) o;
148         logger.fine(al.get(0).toString());
149         File targetFile = new File(targetDir, al.get(0).toString());
150         logger.fine(targetFile.getAbsolutePath());
151         files.add(targetFile);
152       }
153     }
154     JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
155     DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector();
156     StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
f23f2b 157     Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(files);    
d9d37b 158     final Iterable<String> options = buildOptions(targetDir);
U 159     compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits1).call();
0ac262 160     fileManager.close();
e3043f 161     List<CompilerIssue> compilerIssues = new ArrayList();
a450f2 162     collectResults(diagnostics, compilerIssues, relPath);
e3043f 163     return compilerIssues;
0ac262 164   }
d9d37b 165
U 166   private final Iterable<String> buildOptions(File targetDir) {
167       String cbase = getCatalinaBase();
168       File lib = new File(cbase, "lib");
169       String cp = "";
170       cp = buildCPFromDir(cp, lib);
171       logger.fine(lib.getAbsolutePath());
172       logger.fine(cp);
173       /*
174         wegen dieser Funktion MUSS alles in 'src' liegen
175       */
176       File srcDir = targetDir;
177       while(!srcDir.getName().endsWith("src")) {        
178         srcDir = srcDir.getParentFile();
179       }
180       File appDir = srcDir.getParentFile();
181       File appLibDir = new File(appDir, "web/WEB-INF/lib");
182       cp = buildCPFromDir(cp, appLibDir);
183       logger.fine(cp);
184       /*
185         ausgehend von src eins hoeher, dann nach build
186       */
187       File buildDir = new File(appDir, "build");
188       final Iterable<String> options = Arrays.asList(new String[]{"-Xlint",
189                     "-cp", cp,
190                     "-d", buildDir.getAbsolutePath()
191                     });      
192       try {
193         FileUtils.deleteDirectory(buildDir);
194         buildDir.mkdir();
195       } catch (IOException ex) {
196         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
197       }
198       return options;
199   }
200   /*
201   -classpath $JLIB/jettison-1.3.3.jar:$JLIB/xstream-1.4.7.jar
202   */
203   private String buildCPFromDir(String cp, File dir) {
204     StringBuffer buf = new StringBuffer(cp);
205     File[] files = dir.listFiles(new JarFileFilter());
206     for(int i = 0; i < files.length; i++) {
207       if(buf.length() > 0) {
208         buf.append(File.pathSeparatorChar);
209       }
210       //buf.append("\"");
211       buf.append(files[i].getAbsolutePath());
212       //buf.append("\"");
213     }
214     
215     return buf.toString();
216   }
0ac262 217 }
U 218
219
d9d37b 220
0ac262 221 /*
U 222
223  Beispeil fuer einen dynamischen Compiler-Aufruf
224  'in memory'
225
226  String className = "mypackage.MyClass";
227  String javaCode = "package mypackage;\n" +
228                   "public class MyClass implements Runnable {\n" +
229                   "    public void run() {\n" +
230                   "        System.out.println("\"Hello World\");\n" +
231                   "    }\n" +
232                   "}\n";
233  Class aClass = CompilerUtils.CACHED_COMPILER.loadFromJava(className, javaCode);
234  Runnable runner = (Runnable) aClass.newInstance();
235  runner.run();
236
d920b7 237 */
U 238
239 /*
240   CodeMirror Breakpoint bzw. Gutter Marker
241
242   https://codemirror.net/demo/marker.html
0ac262 243 */