Dateiverwaltung für die WebBox
ulrich
2017-03-20 a450f233393a9e3297fea633373635d060a3c709
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
/*
    Dateiverwaltung - File management in your browser
    Copyright (C) 2017 Ulrich Hilger, http://uhilger.de
 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.
 
    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package de.uhilger.filecms.api;
 
import de.uhilger.filecms.data.CompilerIssue;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import org.apache.commons.io.FileUtils;
 
/**
 *
 */
public class CompileService extends Api {
  
  private static final Logger logger = Logger.getLogger(CompileService.class.getName());
    
  public List<CompilerIssue> compileAll(String relPath) {
    logger.fine(relPath);
    List<CompilerIssue> compilerIssues = new ArrayList();
    try {
      File targetDir = getTargetDir(relPath);
      ArrayList<File> files = new ArrayList();
      collectFiles(files, targetDir, new JavaFileFilter());
      JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
      DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector();
      StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
      Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);
      
      File buildDir = new File(targetDir.getParentFile(), "build");
      final Iterable<String> options = Arrays.asList(new String[]{"-Xlint",
                    /*"-cp", project.getClassPath(),*/
                    /*
                      ausgehend von src eins hoeher, dann nach build
                    */
                    "-d", buildDir.getAbsolutePath()
                    });      
      FileUtils.deleteDirectory(buildDir);
      buildDir.mkdir();
      compiler.getTask(null, null, diagnostics, options, null, compilationUnits).call();
      fileManager.close();
      collectResults(diagnostics, compilerIssues, relPath);
    } catch(Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    }
    return compilerIssues;
  }
  
  private void collectResults(DiagnosticCollector<JavaFileObject> diagnostics, List<CompilerIssue> compilerIssues, String relPath) {
    List compileResults = diagnostics.getDiagnostics();
    Iterator i = compileResults.iterator();
    while (i.hasNext()) {
      Object o = i.next();
      Diagnostic<? extends JavaFileObject> err;
      if (o instanceof Diagnostic) {
        err = (Diagnostic) o;
        CompilerIssue issue = new CompilerIssue();
        issue.setKind(err.getKind().name());
        issue.setLineNumber(err.getLineNumber());
        issue.setMessage(err.getMessage(Locale.GERMANY));
        
        String srcName = err.getSource().getName().replace("\\", "/");
        String cleanRelPath = relPath.replace(HOME_DIR_NAME + "/", "").replace(PUB_DIR_NAME + "/", "");
        int pos = srcName.indexOf(cleanRelPath);
        String className = srcName.substring(pos + cleanRelPath.length());
        issue.setSourceName(className.replace("/", ".").substring(1));
        //issue.setSourceName(srcName + "\r\n" + relPath);
        compilerIssues.add(issue);
      }
    }
  }
  
  private void collectFiles(ArrayList<File> files, File dir, FileFilter filter) {
    File[] dirFiles = dir.listFiles(filter);
    for(int i = 0; i < dirFiles.length; i++) {
      if(dirFiles[i].isDirectory()) {
        logger.fine("drill down to " + dirFiles[i].getAbsolutePath());
        collectFiles(files, dirFiles[i], filter);
      } else {
        logger.fine("add " + dirFiles[i].getAbsolutePath());
        files.add(dirFiles[i]);
      }
    }
  }
  
  public class JavaFileFilter implements FileFilter {
 
    @Override
    public boolean accept(File pathname) {
      boolean doAccept = false;
      if(pathname.getName().endsWith(".java") || pathname.isDirectory()) {
        doAccept = true;
      }
      return doAccept;
    }
  
  }
  
  /**
   * 
   * @param relPath
   * @param fileNames
   * @param mode 0 = test, 1 = build
   * @return
   * @throws IOException 
   */
  public List<CompilerIssue> compile(String relPath, List fileNames, String mode) throws IOException {
    File targetDir = getTargetDir(relPath);
    ArrayList<File> files = new ArrayList();
    for(int i=0; i < fileNames.size(); i++) {
      Object o = fileNames.get(i);
      if(o instanceof ArrayList) {
        ArrayList al = (ArrayList) o;
        logger.fine(al.get(0).toString());
        File targetFile = new File(targetDir, al.get(0).toString());
        logger.fine(targetFile.getAbsolutePath());
        files.add(targetFile);
      }
    }
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(files);    
    if( mode.equals("1")) {
      final Iterable<String> options = Arrays.asList(new String[]{"-Xlint",
              /*"-cp", project.getClassPath(),*/
              "-d", targetDir.getAbsolutePath()
              });
      compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits1).call();
    } else {
      compiler.getTask(null, null, diagnostics, null, null, compilationUnits1).call();
    }     
    fileManager.close();
    List<CompilerIssue> compilerIssues = new ArrayList();
    collectResults(diagnostics, compilerIssues, relPath);
    return compilerIssues;
  }
  
}
 
 
/*
 
 Beispeil fuer einen dynamischen Compiler-Aufruf
 'in memory'
 
 String className = "mypackage.MyClass";
 String javaCode = "package mypackage;\n" +
                  "public class MyClass implements Runnable {\n" +
                  "    public void run() {\n" +
                  "        System.out.println("\"Hello World\");\n" +
                  "    }\n" +
                  "}\n";
 Class aClass = CompilerUtils.CACHED_COMPILER.loadFromJava(className, javaCode);
 Runnable runner = (Runnable) aClass.newInstance();
 runner.run();
 
*/
 
/*
  CodeMirror Breakpoint bzw. Gutter Marker
 
  https://codemirror.net/demo/marker.html
*/