use of org.eclipse.jdt.core.compiler.IProblem in project tomcat by apache.
the class JDTCompiler method generateClass.
/**
* Compile the servlet from .java file to .class file
*/
@Override
protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception {
long t1 = 0;
if (log.isDebugEnabled()) {
t1 = System.currentTimeMillis();
}
final String sourceFile = ctxt.getServletJavaFileName();
final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
String packageName = ctxt.getServletPackageName();
final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "") + ctxt.getServletClassName();
final ClassLoader classLoader = ctxt.getJspLoader();
String[] fileNames = new String[] { sourceFile };
String[] classNames = new String[] { targetClassName };
final ArrayList<JavacErrorDetail> problemList = new ArrayList<>();
class CompilationUnit implements ICompilationUnit {
private final String className;
private final String sourceFile;
CompilationUnit(String sourceFile, String className) {
this.className = className;
this.sourceFile = sourceFile;
}
@Override
public char[] getFileName() {
return sourceFile.toCharArray();
}
@Override
public char[] getContents() {
char[] result = null;
try (FileInputStream is = new FileInputStream(sourceFile);
InputStreamReader isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding());
Reader reader = new BufferedReader(isr)) {
char[] chars = new char[8192];
StringBuilder buf = new StringBuilder();
int count;
while ((count = reader.read(chars, 0, chars.length)) > 0) {
buf.append(chars, 0, count);
}
result = new char[buf.length()];
buf.getChars(0, result.length, result, 0);
} catch (IOException e) {
log.error("Compilation error", e);
}
return result;
}
@Override
public char[] getMainTypeName() {
int dot = className.lastIndexOf('.');
if (dot > 0) {
return className.substring(dot + 1).toCharArray();
}
return className.toCharArray();
}
@Override
public char[][] getPackageName() {
StringTokenizer izer = new StringTokenizer(className, ".");
char[][] result = new char[izer.countTokens() - 1][];
for (int i = 0; i < result.length; i++) {
String tok = izer.nextToken();
result[i] = tok.toCharArray();
}
return result;
}
@Override
public boolean ignoreOptionalProblems() {
return false;
}
}
final INameEnvironment env = new INameEnvironment() {
@Override
public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < compoundTypeName.length; i++) {
if (i > 0)
result.append('.');
result.append(compoundTypeName[i]);
}
return findType(result.toString());
}
@Override
public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
StringBuilder result = new StringBuilder();
int i = 0;
for (; i < packageName.length; i++) {
if (i > 0)
result.append('.');
result.append(packageName[i]);
}
if (i > 0)
result.append('.');
result.append(typeName);
return findType(result.toString());
}
private NameEnvironmentAnswer findType(String className) {
if (className.equals(targetClassName)) {
ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
return new NameEnvironmentAnswer(compilationUnit, null);
}
String resourceName = className.replace('.', '/') + ".class";
try (InputStream is = classLoader.getResourceAsStream(resourceName)) {
if (is != null) {
byte[] classBytes;
byte[] buf = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
int count;
while ((count = is.read(buf, 0, buf.length)) > 0) {
baos.write(buf, 0, count);
}
baos.flush();
classBytes = baos.toByteArray();
char[] fileName = className.toCharArray();
ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true);
return new NameEnvironmentAnswer(classFileReader, null);
}
} catch (IOException exc) {
log.error("Compilation error", exc);
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
log.error("Compilation error", exc);
}
return null;
}
private boolean isPackage(String result) {
if (result.equals(targetClassName)) {
return false;
}
String resourceName = result.replace('.', '/') + ".class";
try (InputStream is = classLoader.getResourceAsStream(resourceName)) {
return is == null;
} catch (IOException e) {
// we are here, since close on is failed. That means it was not null
return false;
}
}
@Override
public boolean isPackage(char[][] parentPackageName, char[] packageName) {
StringBuilder result = new StringBuilder();
int i = 0;
if (parentPackageName != null) {
for (; i < parentPackageName.length; i++) {
if (i > 0)
result.append('.');
result.append(parentPackageName[i]);
}
}
if (Character.isUpperCase(packageName[0])) {
if (!isPackage(result.toString())) {
return false;
}
}
if (i > 0)
result.append('.');
result.append(packageName);
return isPackage(result.toString());
}
@Override
public void cleanup() {
}
};
final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
final Map<String, String> settings = new HashMap<>();
settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
if (ctxt.getOptions().getJavaEncoding() != null) {
settings.put(CompilerOptions.OPTION_Encoding, ctxt.getOptions().getJavaEncoding());
}
if (ctxt.getOptions().getClassDebugInfo()) {
settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
}
// Source JVM
if (ctxt.getOptions().getCompilerSourceVM() != null) {
String opt = ctxt.getOptions().getCompilerSourceVM();
if (opt.equals("1.1")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
} else if (opt.equals("1.2")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
} else if (opt.equals("1.3")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
} else if (opt.equals("1.4")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
} else if (opt.equals("1.5")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
} else if (opt.equals("1.6")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
} else if (opt.equals("1.7")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7);
} else if (opt.equals("1.8")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
} else if (opt.equals("1.9")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_9);
} else {
log.warn("Unknown source VM " + opt + " ignored.");
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
}
} else {
// Default to 1.8
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
}
// Target JVM
if (ctxt.getOptions().getCompilerTargetVM() != null) {
String opt = ctxt.getOptions().getCompilerTargetVM();
if (opt.equals("1.1")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
} else if (opt.equals("1.2")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
} else if (opt.equals("1.3")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
} else if (opt.equals("1.4")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
} else if (opt.equals("1.5")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
} else if (opt.equals("1.6")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
} else if (opt.equals("1.7")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7);
} else if (opt.equals("1.8")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_8);
} else if (opt.equals("1.9")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_9);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_9);
} else {
log.warn("Unknown target VM " + opt + " ignored.");
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
}
} else {
// Default to 1.8
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_8);
}
final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
final ICompilerRequestor requestor = new ICompilerRequestor() {
@Override
public void acceptResult(CompilationResult result) {
try {
if (result.hasProblems()) {
IProblem[] problems = result.getProblems();
for (int i = 0; i < problems.length; i++) {
IProblem problem = problems[i];
if (problem.isError()) {
String name = new String(problems[i].getOriginatingFileName());
try {
problemList.add(ErrorDispatcher.createJavacError(name, pageNodes, new StringBuilder(problem.getMessage()), problem.getSourceLineNumber(), ctxt));
} catch (JasperException e) {
log.error("Error visiting node", e);
}
}
}
}
if (problemList.isEmpty()) {
ClassFile[] classFiles = result.getClassFiles();
for (int i = 0; i < classFiles.length; i++) {
ClassFile classFile = classFiles[i];
char[][] compoundName = classFile.getCompoundName();
StringBuilder classFileName = new StringBuilder(outputDir).append('/');
for (int j = 0; j < compoundName.length; j++) {
if (j > 0)
classFileName.append('/');
classFileName.append(compoundName[j]);
}
byte[] bytes = classFile.getBytes();
classFileName.append(".class");
try (FileOutputStream fout = new FileOutputStream(classFileName.toString());
BufferedOutputStream bos = new BufferedOutputStream(fout)) {
bos.write(bytes);
}
}
}
} catch (IOException exc) {
log.error("Compilation error", exc);
}
}
};
ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length];
for (int i = 0; i < compilationUnits.length; i++) {
String className = classNames[i];
compilationUnits[i] = new CompilationUnit(fileNames[i], className);
}
CompilerOptions cOptions = new CompilerOptions(settings);
cOptions.parseLiteralExpressionsAsConstants = true;
Compiler compiler = new Compiler(env, policy, cOptions, requestor, problemFactory);
compiler.compile(compilationUnits);
if (!ctxt.keepGenerated()) {
File javaFile = new File(ctxt.getServletJavaFileName());
javaFile.delete();
}
if (!problemList.isEmpty()) {
JavacErrorDetail[] jeds = problemList.toArray(new JavacErrorDetail[0]);
errDispatcher.javacError(jeds);
}
if (log.isDebugEnabled()) {
long t2 = System.currentTimeMillis();
log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2 - t1) + "ms");
}
if (ctxt.isPrototypeMode()) {
return;
}
// JSR45 Support
if (!options.isSmapSuppressed()) {
SmapUtil.installSmap(smap);
}
}
use of org.eclipse.jdt.core.compiler.IProblem in project che by eclipse.
the class TypeParametersFix method createCleanUp.
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, boolean insertInferredTypeArguments, boolean removeRedundantTypeArguments) {
IProblem[] problems = compilationUnit.getProblems();
IProblemLocation[] locations = new IProblemLocation[problems.length];
for (int i = 0; i < problems.length; i++) {
locations[i] = new ProblemLocation(problems[i]);
}
return createCleanUp(compilationUnit, locations, insertInferredTypeArguments, removeRedundantTypeArguments);
}
use of org.eclipse.jdt.core.compiler.IProblem in project che by eclipse.
the class UnusedCodeFix method createCleanUp.
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, boolean removeUnusedPrivateMethods, boolean removeUnusedPrivateConstructors, boolean removeUnusedPrivateFields, boolean removeUnusedPrivateTypes, boolean removeUnusedLocalVariables, boolean removeUnusedImports, boolean removeUnusedCast) {
IProblem[] problems = compilationUnit.getProblems();
IProblemLocation[] locations = new IProblemLocation[problems.length];
for (int i = 0; i < problems.length; i++) {
locations[i] = new ProblemLocation(problems[i]);
}
return createCleanUp(compilationUnit, locations, removeUnusedPrivateMethods, removeUnusedPrivateConstructors, removeUnusedPrivateFields, removeUnusedPrivateTypes, removeUnusedLocalVariables, removeUnusedImports, removeUnusedCast);
}
use of org.eclipse.jdt.core.compiler.IProblem in project che by eclipse.
the class TypeContextChecker method parseType.
private static Type parseType(String typeString, IJavaProject javaProject, List<String> problemsCollector) {
if (//speed up for a common case //$NON-NLS-1$
"".equals(typeString.trim()))
return null;
if (!typeString.trim().equals(typeString))
return null;
StringBuffer cuBuff = new StringBuffer();
//$NON-NLS-1$
cuBuff.append("interface A{");
int offset = cuBuff.length();
//$NON-NLS-1$
cuBuff.append(typeString).append(" m();}");
ASTParser p = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
p.setSource(cuBuff.toString().toCharArray());
p.setProject(javaProject);
CompilationUnit cu = (CompilationUnit) p.createAST(null);
Selection selection = Selection.createFromStartLength(offset, typeString.length());
SelectionAnalyzer analyzer = new SelectionAnalyzer(selection, false);
cu.accept(analyzer);
ASTNode selected = analyzer.getFirstSelectedNode();
if (!(selected instanceof Type))
return null;
Type type = (Type) selected;
if (MethodTypesSyntaxChecker.isVoidArrayType(type))
return null;
IProblem[] problems = ASTNodes.getProblems(type, ASTNodes.NODE_ONLY, ASTNodes.PROBLEMS);
if (problems.length > 0) {
for (int i = 0; i < problems.length; i++) problemsCollector.add(problems[i].getMessage());
}
String typeNodeRange = cuBuff.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type));
if (typeString.equals(typeNodeRange))
return type;
else
return null;
}
use of org.eclipse.jdt.core.compiler.IProblem in project che by eclipse.
the class ExtractTempRefactoring method checkNewSource.
private void checkNewSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException {
String newCuSource = fChange.getPreviewContent(new NullProgressMonitor());
CompilationUnit newCUNode = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(newCuSource, fCu, true, true, monitor);
IProblem[] newProblems = RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCompilationUnitNode);
for (int i = 0; i < newProblems.length; i++) {
IProblem problem = newProblems[i];
if (problem.isError())
result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem))));
}
}
Aggregations