Get unresolved imports - java

I'm writing eclipse plugin that looks for unresolved imports in all source files.
I found that it can be helpful to use IProblem or IMarker objects. Here's code example
public IMarker[] findJavaProblemMarkers(ICompilationUnit cu)
throws CoreException {
IResource javaSourceFile = cu.getUnderlyingResource();
IMarker[] markers =
javaSourceFile.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER,
true, IResource.DEPTH_INFINITE);
}
frome here
I don't know how I can get info from IProblem or IMarker about which import cause the compilation problem (unresolved import).
Any help?

http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.jdt.doc.isv/guide/jdt_api_classpath.htm
There are a list of different int values in the IProblem interface representing different errors; if you could get the errorcodes of a file somehow, you could use them. (Example, ImportNotVisible, ImportNotFound, etc.). Just check if the error ID matches one of the error ID's for import failures there.

An IMarker knows the line number and start and stop chars for the java source marked by the IMarker. You can take the substring of the java source string and, if the marker type indicates that it's a problem with the class or import, you can search the project's classpath for a class or package matching (or similar to) that substring.

Related

Standard Method TEXT is undefined when compiling jasper report

When I package my stand-alone-java-application, that compiles, renders and prints Jasper-Reports, in a fat jar with all dependencies, I get the error that the function TEXT – a function used in the report and defined in the net.sf.jasperreports-functions-library is not found.
The method TEXT(Integer, String) is undefined for the type [...]
value = IF(LEN(TEXT(((java.lang.Integer)parameter_X.getValue()),"#"))==2,"***",REPT("*",6-LEN(TEXT(((java.lang.Integer)parameter_X.getValue()),"#")))) //$JR_EXPR_ID=58$
Other functions from the same library work. When I run the application with gradle run, the function is found and the report can be printed. The library is on my classpath.
There are several similar questions on this site and Stackoverflow, but neither provided answers, that worked for me. In the following, I will explain what I tried:
In my build.gradle-File I defined dependencies to the following libraries:
implementation('net.sf.jasperreports:jasperreports:6.18.1')
implementation('net.sf.jasperreports:jasperreports-functions:6.18.1')
In my java-Files, I created a DesignFile and statically imported the functions into it. I tried two methods:
Method 1 as given in an answer in this thread: Unresolved symbols when compiling jasper report
/*…*/
designFile = JRXmlLoader.load(sourceFile.getAbsolutePath());
designFile.addImport("static net.sf.jasperreports.functions.standard.TextFunctions.*");
designFile.addImport("static net.sf.jasperreports.functions.standard.MathFunctions.*");
designFile.addImport("static net.sf.jasperreports.functions.standard.DateTimeFunctions.*");
designFile.addImport("static net.sf.jasperreports.functions.standard.LogicalFunctions.*");
JasperReport compiledReport = JasperCompileManager.getInstance(ctx).compile(designFile);
/*…*/
Method 2: importing each function on its own
public static String[] textFunctions(){
return new String[]{"BASE", "CHAR", "CLEAN", "CODE", "CONCATENATE", "DOUBLE_VALUE",
"EXACT", "FIND", /*"FIXED", */"FLOAT_VALUE", "INTEGER_VALUE", "LEFT", "LEN", "LONG_VALUE",
"LOWER", "LTRIM", "MID", "PROPER", "REPLACE", "REPT", "RIGHT", "RTRIM", "SEARCH", "SUBSTITUTE",
"T", /*"TEXT",*/ "TRIM", "UPPER"};
}}
/*…*/
designFile = JRXmlLoader.load(sourceFile.getAbsolutePath());
for (String textFunction : textFunctions()){
designFile.addImport("static net.sf.jasperreports.functions.standard.TextFunctions." + textFunction);
}/* similarly for logical functions, numeric functions and datetime functions*/
}
JasperReport compiledReport = JasperCompileManager.getInstance(ctx).compile(designFile);
/*…*/
As you can see, the function TEXT is commented out. That’s because the program fails at runtime when run with “gradle run”, when I comment it in:
net.sf.jasperreports.engine.JRException: Errors were encountered when compiling report expressions class file:
1. The import net.sf.jasperreports.functions.standard.TextFunctions.TEXT cannot be resolved
import static net.sf.jasperreports.functions.standard.TextFunctions.TEXT;
The same thing is true with most datetime-functions, in fact, only TIME can be imported to the DesignObject without error at runtime
In addition to that, when I type net.sf.jasperreports.functions.standard.TextFunctions. in my IDE, the content-assist shows a list of available functions, yet TEXT is missing.
I suspected, that the function is simply missing in the library, but it is there. In the .gradle/cache/modules-2/files-2.1/… directory, there is the jar with the TextFunctions.java, that contains the function TEXT:
When building the FatJar with dependencies, I have a TextFunctions.class-File in it, that contains the TEXT-Function as well.
In my jar, there are two jasperreports_extension.properties on the root level:
with the smaller one (from the jasperreport-functions-dependency) containing the following lines:
net.sf.jasperreports.extension.registry.factory.functions=net.sf.jasperreports.functions.FunctionsRegistryFactory
net.sf.jasperreports.extension.functions.datetime=net.sf.jasperreports.functions.standard.DateTimeFunctions
net.sf.jasperreports.extension.functions.math=net.sf.jasperreports.functions.standard.MathFunctions, net.sf.jasperreports.functions.standard.LogicalFunctions
net.sf.jasperreports.extension.functions.text=net.sf.jasperreports.functions.standard.TextFunctions
net.sf.jasperreports.extension.functions.report=net.sf.jasperreports.functions.standard.ReportFunctions
Funnily enough, commenting out TEXT, running it locally with gradle run, it works without problems. But packaging it and running it with java -jar it fails to find this function. And statically importing this function leads to gradle run failing as well.
What is happening and how can I fix this? I want to distribute my FatJar on a server and run it, but this problems makes it impossible for me.

Disable name prefix in javadoc

When generating the Javadoc, it adds on prefix to the imported class name, as shown below on the first line 'java.lang'.
How to properly disable that?
Have tried adding -noqualifier in Other command line arguments in my IntelliJ popup window but the following error occurred:
javadoc: error - Illegal package name: "/Users"
Below is a snippet from the Javadoc I generated:
public TrainRoute(java.lang.String name,
int routeNumber)
Creates a new TrainRoute with the given name and number.
Should meet the specification of Route.Route(String, int)
Parameters:
name - The name of the route.
routeNumber - The route number of the route.
I know this is an old question, but still relevant. I am aware of two solution which can be used alone or in combination:
To suppress prefixes on java packages use:
-noqualifier java.*
To suppress prefixes and link to the actual Java docs use:
-link https://docs.oracle.com/javase/8/docs/api
Both suppress the java name qualifiers. The second also links to the Oracle docs.
See javadoc options docs for more info.

Error with Java String in declaration in intellij

I've updated my intellij to 2017.2.5 and imported all the projects. For some reason, declaration and constructors show some error with Strings. e.g. private String type = "abc"; and name = " xyz"; Error asks me to change it to java.lang.string as a solution.
Jdk is up to date. libraries are up to date, so what is the problem? Project structure looks ok. How do I fix this?
Just delete the line:
import org.apache.xpath.operations.String
This is causing a type conflict between java.lang.String (what you want) and an Apache class (which you probably don't want).

Change to compiler 1.7 when creating a List produced errors throughout the entire project

I am using Eclipse Juno and Java.
I was trying to create a new list:
List myList = new ArrayList();
This had an error and the resolution on it was along the lines of change compiler to 1.7 which I accepted. The errror on this list creation line was corrected however I now have many errors thoughout the whole project on lines that were previously working. Some examples are:
class GetAccountAndCubsHandler<T> implements AsyncCallback<List<AccountAndCubs>>
Multiple markers at this line
- The hierarchy of the type GetAccountAndCubsHandler is inconsistent
- List cannot he resolved to a type
public class AccountCreationView extends Composite {
Multiple markers at this line
- The hierarchy of the type AccountCreationView is inconsistent
- Breakpoint:AccountCreationView
#SuppressWarnings("unused")
private String accountId;
First line - Multiple markers at this line
- SuppressWarnings cannot be resolved to a type
- The attribute valie is undefined for the annotation type SuppressWarnings
Second line - String cannot be resolved to a type
As you can imagine having my whole project adversely affected in this way is very disconcerting so any advice on how to recover would be greatly appreciated.
Regards,
Glyn
"String cannot be resolved to a type"
Ensure that a valid JRE or JDK is specified in your build-path.
Since you're using Eclipse, right-click on your project, then Properties → Java Build Path.
Perhaps you don't have a Java 7 JRE configured in the Installed JREs preference panel.

Warning: File for type '[Insert class here]' created in the last round will not be subject to annotation processing

I switched an existing code base to Java 7 and I keep getting this warning:
warning: File for type '[Insert class here]' created in the last round
will not be subject to annotation processing.
A quick search reveals that no one has hit this warning.
It's not documented in the javac compiler source either:
From OpenJDK\langtools\src\share\classes\com\sun\tools\javac\processing\JavacFiler.java
private JavaFileObject createSourceOrClassFile(boolean isSourceFile, String name) throws IOException {
checkNameAndExistence(name, isSourceFile);
Location loc = (isSourceFile ? SOURCE_OUTPUT : CLASS_OUTPUT);
JavaFileObject.Kind kind = (isSourceFile ?
JavaFileObject.Kind.SOURCE :
JavaFileObject.Kind.CLASS);
JavaFileObject fileObject =
fileManager.getJavaFileForOutput(loc, name, kind, null);
checkFileReopening(fileObject, true);
if (lastRound) // <-------------------------------TRIGGERS WARNING
log.warning("proc.file.create.last.round", name);
if (isSourceFile)
aggregateGeneratedSourceNames.add(name);
else
aggregateGeneratedClassNames.add(name);
openTypeNames.add(name);
return new FilerOutputJavaFileObject(name, fileObject);
}
What does this mean and what steps can I take to clear this warning?
Thanks.
The warning
warning: File for type '[Insert class here]' created in the last round
will not be subject to annotation processing
means that your were running an annotation processor creating a new class or source file using a javax.annotation.processing.Filer implementation (provided through the javax.annotation.processing.ProcessingEnvironment) although the processing tool already decided its "in the last round".
This may be problem (and thus the warning) because the generated file itself may contain annotations being ignored by the annotation processor (because it is not going to do a further round).
The above ought to answer the first part of your question
What does this mean and what steps can I take to clear this warning?
(you figured this out already by yourself, didn't you :-))
What possible steps to take? Check your annotation processors:
1) Do you really have to use filer.createClassFile / filer.createSourceFile on the very last round of the annotaion processor? Usually one uses the filer object inside of a code block like
for (TypeElement annotation : annotations) {
...
}
(in method process). This ensures that the annotation processor will not be in its last round (the last round always being the one having an empty set of annotations).
2) If you really can't avoid writing your generated files in the last round and these files are source files, trick the annotation processor and use the method "createResource" of the filer object (take "SOURCE_OUTPUT" as location).
In OpenJDK test case this warning produced because processor uses "processingOver()" to write new file exactly at last round.
public boolean process(Set<? extends TypeElement> elems, RoundEnvironment renv) {
if (renv.processingOver()) { // Write only at last round
Filer filer = processingEnv.getFiler();
Messager messager = processingEnv.getMessager();
try {
JavaFileObject fo = filer.createSourceFile("Gen");
Writer out = fo.openWriter();
out.write("class Gen { }");
out.close();
messager.printMessage(Diagnostic.Kind.NOTE, "File 'Gen' created");
} catch (IOException e) {
messager.printMessage(Diagnostic.Kind.ERROR, e.toString());
}
}
return false;
}
I modified original example code a bit. Added diagnostic note "File 'Gen' created", replaced "*" mask with "org.junit.runner.RunWith" and set return value to "true". Produced compiler log was:
Round 1:
input files: {ProcFileCreateLastRound}
annotations: [org.junit.runner.RunWith]
last round: false
Processor AnnoProc matches [org.junit.runner.RunWith] and returns true.
Round 2:
input files: {}
annotations: []
last round: true
Note: File 'Gen' created
Compilation completed successfully with 1 warning
0 errors
1 warning
Warning: File for type 'Gen' created in the last round will not be subject to annotation processing.
If we remove my custom note from log, it's hard to tell that file 'Gen' was actually created on 'Round 2' - last round. So, basic advice applies: if in doubt - add more logs.
Where is also a little bit of useful info on this page:
http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/javac.html
Read section about "ANNOTATION PROCESSING" and try to get more info with compiler options:
-XprintProcessorInfo
Print information about which annotations a processor is asked to process.
-XprintRounds Print information about initial and subsequent annotation processing rounds.
I poked around the java 7 compiler options and I found this:
-implicit:{class,none}
Controls the generation of class files for implicitly loaded source files. To automatically generate class files, use -implicit:class. To suppress class file generation, use -implicit:none. If this option is not specified, the default is to automatically generate class files. In this case, the compiler will issue a warning if any such class files are generated when also doing annotation processing. The warning will not be issued if this option is set explicitly. See Searching For Types.
Source
Can you try and implicitly declare the class file.

Categories

Resources