Java compiler ignores source files generated by annotations processor - java

I'm messing up with an annotations processor. It should be able to generate source files with Java classes, but for some reason when I start a compilation, compiler ends with an error that it can not find my generated class.
Even weirder is that after this error message I check my filesystem, the file is there and also has correct content. When I start the compilation second time, compiler is happy and ends without any errors.
To generate a file I'm using this piece of code:
private void writeBarFile() {
Filer filer = processingEnv.getFiler();
Messager messager = processingEnv.getMessager();
try {
// this should prepare a new Java source file
final JavaFileObject fooFileObject = filer.createSourceFile("sample.module.GeneratedClass");
// Here we open a writer
try (Writer writer = fooFileObject.openWriter()) {
// And write some content
writer.append("package sample.module;\n").append("public class GeneratedClass {}");
}
} catch (IOException ex) {
messager.printMessage(Diagnostic.Kind.ERROR, ex.getMessage());
}
}
By calling filer.createSourceFile I should get an instance of new Java file which will be generated.
Than I have another module, where I have my annotation used and where is also used a generated class.
package sample.module;
import sample.annotation.Foo;
#Foo(bar = "test1")
public class Sample1 {
// This class is generated by annotations processor
GeneratedClass t;
}
The output from the compiler after first compilation:
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /F:/annotations_processor_example/sample-module/src/main/java/sample/module/Sample1.java:[10,3] cannot find symbol
symbol: class GeneratedClass
location: class sample.module.Sample1
[INFO] 1 error
[INFO] -------------------------------------------------------------
But it does not make sense because the file is already generated and I can see i on the file system.
Is there anything that must be somehow enabled or am I just missing something?
I have tried multiple Java versions (11, 17 and 19), but it's same error everywhere.
There is a sample project on GitHub.
I will appreciate any help or just an explanation what am I doing wrong.

Related

Maven + MWE2Launcher + XText model refences an uncompiled Java Class

i have a Question about XText/Maven.
I have a XText/Maven/Java Project.
In this Project lie the Xtext Models and Java source Files.
Some of the Modelfiles reference some Java files. E.G.:
Model:
package a.b.c
import java.util.List
import x.y.z.MyClass // <-- This is one of the Javafile in the same Project
dto MyModel
{
MyClass myClass
}
Java:
package x.y.z;
public class MyClass
{
String foo;
String bar;
}
Structure:
project
|
|----src/main
|
|---/java/x/y/z/MyClass.java
|
|---/model/a/b/c/MyModel.dto
|
|---/gen/a/b/c/MyModel.java <-- here goes the generated Javafile from the Model
I have already managed to write an Xtext/Eclipse plugin, so the Eclipse build generate my Modelfiles and compiles the Javafiles just fine.
But now i try to build the Project with Maven. I Manage already accomplished the Generate process via an mwe2 Workflow with use of the Class
org.eclipse.emf.mwe2.launch.runtime.MWE2Launcher
and other Modelfiles genrate just fine, but the MyModel references a Java Class that is not yet Compiled and so it is not Found:
[ERROR] Execution Failed: Problems running workflow my.company.model.xtext.domainmodel.generator: Validation problems:
[ERROR] 49 errors:
[ERROR] MyModel.dto - <path>/model/a/b/c/MyModel.dto
[ERROR] 4: x.y.z.MyClass cannot be resolved to a type.
...
So the Error itself is clear. I tryed with sucess to Precompile the Java File first and add these to the Classpath. But i have dozen of this Problems and i hope the is a better way to tell Xtext/Mwe2Launcher that it should reference the requierd Java Files. Because in some magic way it already work in Eclipse but i have no Idea how.
I have the same problem. But I use Gradle instead of Maven. However it may be still useful for someone:
task precompile(type: JavaCompile) {
source = 'src/main/java'
classpath = sourceSets.main.compileClasspath
destinationDir = sourceSets.main.java.outputDir
}
task generateXtextLanguage(type: JavaExec) {
dependsOn precompile
main = 'org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher'
args += "src/main/mwe2/...your_path_here.../generate.mwe2"
classpath = layout.files(configurations.mwe2, sourceSets.main.java.outputDir)
inputs.file 'src/main/mwe2/...your_path_here.../generate.mwe2'
inputs.dir 'src/main/xcore'
outputs.dir 'target/generated-sources/xtext-gen'
}
I added precompile task. generateXtextLanguage dependsOn it. Also I added precompiled classes to a classpath.

Intellij: No usages found in Project Files

I'm using IntelliJ 15 and I'm trying to find usages of methods and objects in a .java file packed in a .jar file downloaded through Maven. I now that they're used: I can find them through the simple search (ctrl+f) command, but when I try with the Find Usages command the post-title message is returned.
I've read this post, but it doesn't work.
This an example of a method in a file InstanceManager.class (belonging to .jar file imported with Maven):
private void notifyNewInstance(Instance instance) {
List var2 = this.instanceListeners;
synchronized(this.instanceListeners) {
Iterator var3 = this.instanceListeners.iterator();
while(var3.hasNext()) {
InstanceListener listener = (InstanceListener)var3.next();
try {
listener.newInstanceAvailable(instance);
} catch (Throwable var7) {
LOG.error("Notification of new instance availability failed.", var7);
}
}
}
}
And in the same file is called with this.notifyNewInstance(host); but if I use Find usages on notifyNewInstance I'll receive the error.
UPDATE:
I've tried to Download the source code, but I get the message:
Cannot download sources Sources not found for:
org.apache.flink:flink-runtime_2.10:1.1-20160316.114232-35
Can you help me with that?
You need to get the source code.
Assuming you're attempting to do this on Apache Flink:
Source Code found here
If you only want a particular folder from the source code, you can use the method found here.

gradle generated files fail to compile

I am trying to get a JavaCC plugin working properly with Gradle. The plugin generates .java files correctly, but then during the compileJavaC task it crashes and burns with cannot find symbol errors. My JavaCC .jj file contains code that references other java files that are not generated, and I am guessing that the compileJava task tries to compile the generated code without providing a reference to the non-generated code.
Here is a minimum breaking example. build.gradle:
apply plugin: 'java'
//compile .jj file in src/main/javacc
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath group: 'ca.coglinc', name: 'javacc-gradle-plugin', version: '1.0.0'
}
}
apply plugin: 'javacc'
src/main/MyClass.java:
public class MyClass {
public MyClass(){
}
}
and src/main/javacc/MyParser.jj:
options
{}
PARSER_BEGIN(MyParser)
import java.util.*;
public class MyParser {
public static void main(String[] args) throws ParseException {
MyClass mc = new MyClass();
}
}
PARSER_END(MyParser)
SKIP:
{
" "
}
TOKEN:
{
<ANYTHING: ~[]>
}
void production():
{}
{
(<ANYTHING>)+
}
Running gradle build gives the following:
gradle build
:compileJavacc
Java Compiler Compiler Version 5.0 (Parser Generator)
(type "javacc" with no arguments for help)
Reading from file C:\Users\Nate Glenn\Desktop\java_workspace\test-gradle-javacc\
src\main\javacc\MyParser.jj . . .
File "TokenMgrError.java" does not exist. Will create one.
File "ParseException.java" does not exist. Will create one.
File "Token.java" does not exist. Will create one.
File "SimpleCharStream.java" does not exist. Will create one.
Parser generated successfully.
:compileJavaC:\Users\Nate Glenn\Desktop\java_workspace\test-gradle-javacc\build\
generated\javacc\MyParser.java:5: error: cannot find symbol
MyClass mc = new MyClass();
^
symbol: class MyClass
location: class MyParser
C:\Users\Nate Glenn\Desktop\java_workspace\test-gradle-javacc\build\generated\ja
vacc\MyParser.java:5: error: cannot find symbol
MyClass mc = new MyClass();
^
symbol: class MyClass
location: class MyParser
2 errors
FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':compileJava'.
> Compilation failed; see the compiler error output for details.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug
option to get more log output.
BUILD FAILED
Total time: 9.002 secs
How can I fix my Gradle build file so that javaCompileC correctly includes non-generated files when compiling the generated files?
Your source tree for MyClass is incorrect. It should be src/main/java/MyClass.java. In gradle, just like maven, convention is that java files by default are in src/main/java, and since you're not overriding this in your build.gradle file, I assume this is just an error on your part. The plugin correctly adds the JavaCC output path to the compileJava task's classpath, so if you create your java classes in the correct path for the compileJava task, everything should be fine :)
Just tried your example this way and it works.
By the way, thanks for your contribution to the plugin.
Just some additional FYI, if you would like to overwrite the compile path, here is how you would do it:
//customized source sets to over-write the default src/main/java path
sourceSets {
main{
java {
srcDir 'Java Source'
}
resources {
srcDir 'resources'
}
}
test {
java {
srcDir 'tests'
}
}
}

Executing groovy file in Java

I am trying to execute a .groovy file in Java however being new to both Java and Groovy I am having some problems. I'm doing this to learn more and would appreciate if someone could tell me what i am doing wrong.
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.GroovyShell;
import javax.naming.Binding;
import java.io.File;
public class testClass extends GroovyShell{
public static void main(String[] args){
try{
ClassLoader parent = testClass.class.getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
Class groovyClass = loader.parseClass(new File("src/testg.groovy"));
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
Object[] args1 = {};
groovyObject.invokeMethod("run",args1);
}catch(Exception e) {
System.out.println("error loading file");
}
}
}
I am getting the following errors :
Groovyc: Cannot compile Groovy files: no Groovy library is defined for module 'Prep'
Using javac 1.7.0_09 to compile java sources
Compilation completed with 1 error and 0 warnings in 9 sec
1 error
0 warnings
Groovyc: Internal groovyc error: code 1
Or perhaps someone could give me an example of how to execute e.g. hello world script written in groovy, in java.
That's not an error thrown by your code. It's an error thrown by IntelliJ, which tries to compile your .groovy file to a .class file.
Since what you want is to parse and run this groovy file at runtime, you shouldn't care about this error. Or rather, to avoid it, you should not put the .groovy file in a directory marked as a source directory in the IntelliJ project, so that IntelliJ doesn't try to compile it.

GWT Compile Issues in Java (Google App Engine)

Im having a weird compile issue using the Google App engine in java using eclipse. When I try to GWT Compile my code I get an error that is as follows:
Compiling module beer.SQLBeer
Validating newly compiled units
Ignored 1 unit with compilation errors in first pass.
Compile with -strict or with -logLevel set to TRACE or DEBUG to see all errors.
Finding entry point classes
[ERROR] Errors in 'file:/C:/Users/Mark/workspace/SQLBeer/src/beer/client/SQLBeer.java'
[ERROR] Line 12: The import com.google.appengine.api.rdbms cannot be resolved
[ERROR] Line 13: The import com.google.apphosting cannot be resolved
[ERROR] Line 14: The import com.google.cloud cannot be resolved
[ERROR] Line 18: ServersServlet cannot be resolved to a type
[ERROR] Line 22: The method doPost(HttpServletRequest, HttpServletResponse) of type SQLBeer must override or implement a supertype method
[ERROR] Line 26: Connection cannot be resolved to a type
[ERROR] Line 28: AppEngineDriver cannot be resolved to a type
[ERROR] Line 29: Connection cannot be resolved to a type
[ERROR] Unable to find type 'beer.client.SQLBeer'
[ERROR] Hint: Previous compiler errors may have made this type unavailable
[ERROR] Hint: Check the inheritance chain from your module; it may not be inheriting a required module or a module may not be adding its source path entries properly
Exception in thread "UnitWriteThread"
I am not sure why it cannot resolve the imports, and this is preventing me from deploying my code onto the Google app engine. I feel because it is not playing nicely with my imports its the same reason im getting the error
[ERROR] Line 22: The method doPost(HttpServletRequest, HttpServletResponse) of type SQLBeer must override or implement a supertype method
I am really new to using GWT and the Google App Engine for Eclipse, but im trying to access a database my team created using Google Cloud SQL. And I feel Like im getting close, if i can over come these errors.
The Project Code
package beer.client;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.rdbms.AppEngineDriver;
import com.google.apphosting.utils.servlet.ServersServlet;
import com.google.cloud.sql.jdbc.Connection;
#SuppressWarnings("serial")
public class SQLBeer extends ServersServlet {
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
PrintWriter out = resp.getWriter();
Connection c = null;
try {
DriverManager.registerDriver(new AppEngineDriver());
c = (Connection) DriverManager
.getConnection("jdbc:google:rdbms://asu.edu:cst433team1:team1db/mysql");
String fname = req.getParameter("fname");
String content = req.getParameter("content");
/**
* This code appears to do the web form fun
*/
// if (fname == "" || content == "") {
// out.println("<html><head></head><body>You are missing either a message or a name! Try again! Redirecting in 3 seconds...</body></html>");
// } else {
// String statement = "INSERT INTO entries (guestName, content) VALUES( ? , ? )";
// PreparedStatement stmt = c.prepareStatement(statement);
// stmt.setString(1, fname);
// stmt.setString(2, content);
// int success = 2;
// success = stmt.executeUpdate();
// if (success == 1) {
// out.println("<html><head></head><body>Success! Redirecting in 3 seconds...</body></html>");
// } else if (success == 0) {
// out.println("<html><head></head><body>Failure! Please try again! Redirecting in 3 seconds...</body></html>");
// }
// }
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (c != null)
try {
c.close();
} catch (SQLException ignore) {
}
}
//resp.setHeader("Refresh", "3; url=/beer.jsp");
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Any Suggestion on what I could do to fix these errors? Ive tried different Imports but they all seem to lead to the same issues in the GWT Compiler.
EDIT: I changed the extend to HttpServlet and now the error is a little different
Compiling module beer.SQLBeer
Validating newly compiled units
Ignored 1 unit with compilation errors in first pass.
Compile with -strict or with -logLevel set to TRACE or DEBUG to see all errors.
Finding entry point classes
[ERROR] Errors in 'file:/C:/Users/Mark/workspace/SQLBeer/src/beer/client/SQLBeer.java'
[ERROR] Line 13: The import com.google.appengine.api.rdbms cannot be resolved
[ERROR] Line 14: The import com.google.cloud cannot be resolved
[ERROR] Line 26: Connection cannot be resolved to a type
[ERROR] Line 28: AppEngineDriver cannot be resolved to a type
[ERROR] Line 29: Connection cannot be resolved to a type
[ERROR] Unable to find type 'beer.client.SQLBeer'
[ERROR] Hint: Previous compiler errors may have made this type unavailable
[ERROR] Hint: Check the inheritance chain from your module; it may not be inheriting a required module or a module may not be adding its source path entries properly
Exception in thread "UnitWriteThread" java.lang.RuntimeException: Unable to read from byte cache
First, check that this isn't a classpath issue - meaning you don't have all the required jars in the lib directory and on the classpath.
If that fails, make sure that this code isn't Client side(guessing from your package name), which will gets compiled to javascript. You dont want this to happen for database connection code so you should use this code on the server side.
See the Documentation on Client side & Server side code.

Categories

Resources