use of org.eclipse.jdt.core.compiler.IProblem in project eclipse.jdt.ls by eclipse.
the class DocumentLifeCycleHandlerTest method testNotExpectedPackage2.
@Test
public void testNotExpectedPackage2() throws Exception {
newDefaultProject();
// @formatter:off
String content = "package org;\n" + "public class Foo {" + "}";
// @formatter:on
temp = createTempFolder();
Path path = Paths.get(temp.getAbsolutePath(), "org", "eclipse");
File file = createTempFile(path.toFile(), "Foo.java", content);
URI uri = file.toURI();
ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
openDocument(cu, cu.getSource(), 1);
CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, new NullProgressMonitor());
IProblem[] problems = astRoot.getProblems();
assertEquals("Unexpected number of errors", 0, problems.length);
String source = cu.getSource();
int length = source.length();
source = source.replace("org", "org.eclipse");
changeDocument(cu, source, 2, JDTUtils.toRange(cu, 0, source.length()), length);
FileUtils.writeStringToFile(file, source);
saveDocument(cu);
cu = JDTUtils.resolveCompilationUnit(uri);
astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, new NullProgressMonitor());
problems = astRoot.getProblems();
assertEquals("Unexpected number of errors", 0, problems.length);
source = cu.getSource();
length = source.length();
source = source.replace("org.eclipse", "org.eclipse.toto");
changeDocument(cu, source, 3, JDTUtils.toRange(cu, 0, source.length()), length);
FileUtils.writeStringToFile(file, source);
saveDocument(cu);
cu = JDTUtils.resolveCompilationUnit(uri);
astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, new NullProgressMonitor());
problems = astRoot.getProblems();
assertEquals("Unexpected number of errors", 1, problems.length);
}
use of org.eclipse.jdt.core.compiler.IProblem in project eclipse.jdt.ls by eclipse.
the class DocumentLifeCycleHandlerTest method testCreateCompilationUnit.
@Test
public void testCreateCompilationUnit() throws Exception {
IJavaProject javaProject = newEmptyProject();
// @formatter:off
String fooContent = "package org;\n" + "public class Foo {" + "}\n";
String barContent = "package org;\n" + "public class Bar {\n" + " Foo test() { return null; }\n" + "}\n";
// @formatter:on
IFolder src = javaProject.getProject().getFolder("src");
javaProject.getPackageFragmentRoot(src);
File sourceDirectory = src.getRawLocation().makeAbsolute().toFile();
File org = new File(sourceDirectory, "org");
org.mkdir();
File file = new File(org, "Bar.java");
file.createNewFile();
FileUtils.writeStringToFile(file, barContent);
ICompilationUnit bar = JDTUtils.resolveCompilationUnit(file.toURI());
bar.getResource().refreshLocal(IResource.DEPTH_ONE, null);
assertNotNull("Bar doesn't exist", javaProject.findType("org.Bar"));
file = new File(org, "Foo.java");
file.createNewFile();
URI uri = file.toURI();
ICompilationUnit unit = JDTUtils.resolveCompilationUnit(uri);
openDocument(unit, "", 1);
FileUtils.writeStringToFile(file, fooContent);
changeDocumentFull(unit, fooContent, 1);
saveDocument(unit);
closeDocument(unit);
CompilationUnit astRoot = sharedASTProvider.getAST(bar, CoreASTProvider.WAIT_YES, null);
IProblem[] problems = astRoot.getProblems();
assertEquals("Unexpected number of errors", 0, problems.length);
}
use of org.eclipse.jdt.core.compiler.IProblem in project tomcat70 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<JavacErrorDetail>();
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;
FileInputStream is = null;
InputStreamReader isr = null;
Reader reader = null;
try {
is = new FileInputStream(sourceFile);
isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding());
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);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ioe) {
/*Ignore*/
}
}
if (isr != null) {
try {
isr.close();
} catch (IOException ioe) {
/*Ignore*/
}
}
if (is != null) {
try {
is.close();
} catch (IOException exc) {
/*Ignore*/
}
}
}
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();
String sep = "";
for (int i = 0; i < compoundTypeName.length; i++) {
result.append(sep);
result.append(compoundTypeName[i]);
sep = ".";
}
return findType(result.toString());
}
@Override
public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
StringBuilder result = new StringBuilder();
String sep = "";
for (int i = 0; i < packageName.length; i++) {
result.append(sep);
result.append(packageName[i]);
sep = ".";
}
result.append(sep);
result.append(typeName);
return findType(result.toString());
}
private NameEnvironmentAnswer findType(String className) {
InputStream is = null;
try {
if (className.equals(targetClassName)) {
ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
return new NameEnvironmentAnswer(compilationUnit, null);
}
String resourceName = className.replace('.', '/') + ".class";
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);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException exc) {
// Ignore
}
}
}
return null;
}
private boolean isPackage(String result) {
if (result.equals(targetClassName)) {
return false;
}
String resourceName = result.replace('.', '/') + ".class";
InputStream is = null;
try {
is = classLoader.getResourceAsStream(resourceName);
return is == null;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}
@Override
public boolean isPackage(char[][] parentPackageName, char[] packageName) {
StringBuilder result = new StringBuilder();
String sep = "";
if (parentPackageName != null) {
for (int i = 0; i < parentPackageName.length; i++) {
result.append(sep);
result.append(parentPackageName[i]);
sep = ".";
}
}
if (Character.isUpperCase(packageName[0])) {
if (!isPackage(result.toString())) {
return false;
}
}
result.append(sep);
result.append(packageName);
return isPackage(result.toString());
}
@Override
public void cleanup() {
}
};
final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
final Map<String, String> settings = new HashMap<String, String>();
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
"1.9");
} else {
log.warn("Unknown source VM " + opt + " ignored.");
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
}
} else {
// Default to 1.6
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
}
// 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
"1.9");
settings.put(CompilerOptions.OPTION_Compliance, // CompilerOptions.VERSION_1_9
"1.9");
} else {
log.warn("Unknown target VM " + opt + " ignored.");
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
}
} else {
// Default to 1.6
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
}
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");
FileOutputStream fout = null;
BufferedOutputStream bos = null;
try {
fout = new FileOutputStream(classFileName.toString());
bos = new BufferedOutputStream(fout);
bos.write(bytes);
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
}
}
}
}
}
} 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 webtools.sourceediting by eclipse.
the class JSPJavaValidator method performValidation.
void performValidation(IFile f, IReporter reporter, IStructuredModel model) {
for (int i = 0; i < DEPEND_ONs.length; i++) {
addDependsOn(f.getProject().getFile(DEPEND_ONs[i]));
}
if (model instanceof IDOMModel) {
IDOMModel domModel = (IDOMModel) model;
ModelHandlerForJSP.ensureTranslationAdapterFactory(domModel);
IDOMDocument xmlDoc = domModel.getDocument();
JSPTranslationAdapter translationAdapter = (JSPTranslationAdapter) xmlDoc.getAdapterFor(IJSPTranslation.class);
IJSPTranslation translation = translationAdapter.getJSPTranslation();
if (!reporter.isCancelled()) {
loadPreferences(f);
// only update task markers if the model is the same as what's on disk
boolean updateJavaTasks = UPDATE_JAVA_TASKS && !domModel.isDirty() && f != null && f.isAccessible();
if (updateJavaTasks) {
// remove old Java task markers
try {
IMarker[] foundMarkers = f.findMarkers(JAVA_TASK_MARKER_TYPE, true, IResource.DEPTH_ONE);
for (int i = 0; i < foundMarkers.length; i++) {
foundMarkers[i].delete();
}
} catch (CoreException e) {
Logger.logException(e);
}
}
translation.setProblemCollectingActive(true);
translation.reconcileCompilationUnit();
List problems = translation.getProblems();
// add new messages
for (int i = 0; i < problems.size() && !reporter.isCancelled(); i++) {
IProblem problem = (IProblem) problems.get(i);
/*
* Possible error in problem collection; EL translation is
* extensible, so we must be paranoid about this.
*/
if (problem == null)
continue;
IMessage m = createMessageFromProblem(problem, f, translation, domModel.getStructuredDocument());
if (m != null) {
if (problem.getID() == IProblem.Task) {
if (updateJavaTasks) {
// add new Java task marker
try {
IMarker task = f.createMarker(JAVA_TASK_MARKER_TYPE);
task.setAttribute(IMarker.LINE_NUMBER, new Integer(m.getLineNumber()));
task.setAttribute(IMarker.CHAR_START, new Integer(m.getOffset()));
task.setAttribute(IMarker.CHAR_END, new Integer(m.getOffset() + m.getLength()));
task.setAttribute(IMarker.MESSAGE, m.getText());
task.setAttribute(IMarker.USER_EDITABLE, Boolean.FALSE);
switch(m.getSeverity()) {
case IMessage.HIGH_SEVERITY:
{
task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_HIGH));
task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_ERROR));
}
break;
case IMessage.LOW_SEVERITY:
{
task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_LOW));
task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_INFO));
}
break;
default:
{
task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL));
task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_WARNING));
}
}
} catch (CoreException e) {
Logger.logException(e);
}
}
} else {
reporter.addMessage(fMessageOriginator, m);
}
}
}
}
}
unloadPreferences();
}
use of org.eclipse.jdt.core.compiler.IProblem in project webtools.sourceediting by eclipse.
the class JSPJavaTranslatorCoreTest method testIterationTags.
public void testIterationTags() throws Exception {
String testName = "testIterationTags";
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(testName);
if (!project.isAccessible()) {
// Create new project
project = BundleResourceUtil.createSimpleProject(testName, null, null);
assertTrue(project.exists());
BundleResourceUtil.copyBundleEntriesIntoWorkspace("/testfiles/" + testName, "/" + testName);
}
/* This test is failing as of 20180213 so until someone can debug and fix it, comment it out */
/* waitForBuildAndValidation(project); */
IFile testFile = project.getFile("/WebContent/test.jsp");
assertTrue("test.jsp is not accessible", testFile.isAccessible());
IDOMModel model = null;
try {
model = (IDOMModel) StructuredModelManager.getModelManager().getModelForEdit(testFile);
ModelHandlerForJSP.ensureTranslationAdapterFactory(model);
JSPTranslationAdapter translationAdapter = (JSPTranslationAdapter) model.getDocument().getAdapterFor(IJSPTranslation.class);
JSPTranslationExtension translation = translationAdapter.getJSPTranslation();
translation.setProblemCollectingActive(true);
assertNotNull("No Java translation found", translation);
translation.reconcileCompilationUnit();
translation.setProblemCollectingActive(false);
List<IProblem> problems = translation.getProblems();
assertNotNull("Translation had a null problems list.", problems);
Iterator<IProblem> it = problems.iterator();
String javaText = translation.getJavaText();
int startOffset = javaText.indexOf("<plain:simple>");
assertTrue("<plan:simple> scope not found.", startOffset > 0);
int endOffset = javaText.indexOf("</plain:simple>", startOffset);
assertTrue("</plan:simple> scope not found.", endOffset > 0);
// Finds all errors caused by "continue cannot be used outside of a loop" - should only occur between <plain:simple></plain:simple>
while (it.hasNext()) {
IProblem problem = it.next();
if (problem.isError()) {
if ("continue cannot be used outside of a loop".equals(problem.getMessage())) {
assertTrue("'continue cannot be used outside of a loop' outside of iteration tag: ", problem.getSourceStart() > startOffset && problem.getSourceEnd() < endOffset);
}
}
}
} finally {
if (model != null)
model.releaseFromEdit();
}
}
Aggregations