Migrating maven project to modules - ignore module-info.java - java

We're currently migrating to JPMS setting up module-info.java for all modules in a maven multi-module project.
For us it would be ideal to have module-info.java already reside in "dev" branch but not affecting any builds. So idea is to exclude module-info.java by default and include it only in specific maven profiles.
Does that make sense?
Anyway, doesn't work for me, module-info.java is picked up even though in excludes section as follows:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${version.maven-compiler-plugin}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<release>${maven.compiler.release}</release>
<compilerArgs>
<arg>-Xlint:${maven.compiler.warningsToIgnore}</arg>
</compilerArgs>
<excludes>
<exclude>**/module-info.java</exclude>
</excludes>
</configuration>
</plugin>
Any ideas?
PS: Idea was taken from How to exclude module-info.java in Netbeans (11)?

Still it's intersting that filter doesn't work for module-info.java, but looking the source of compiler plugin I guess that's just the way it is:
https://github.com/apache/maven-compiler-plugin/blob/master/src/main/java/org/apache/maven/plugin/compiler/CompilerMojo.java
protected void preparePaths( Set<File> sourceFiles )
{
//assert compilePath != null;
File moduleDescriptorPath = null;
boolean hasModuleDescriptor = false;
for ( File sourceFile : sourceFiles )
{
if ( "module-info.java".equals( sourceFile.getName() ) )
{
moduleDescriptorPath = sourceFile;
hasModuleDescriptor = true;
break;
}
}

Related

Is it possible to configure maven to compile generated sources wouthout the use of a plugin?

I know this question is not new. But it seems that there is no definite answer. This answer from 2012 states that if generated sources are placed under target/generated-sources/<tool> they will be compiled. ANTLR 4 maven plugin follows this paradigm. Per documentation, the default value of outputDirectory is: ${project.build.directory}/generated-sources/antlr4.
Now in my case I have a custom tool that generates sources. I've set its output directory to be at ${project.build.directory}/generated-sources/whatever and it didn't work. Regarding the whateverpart, I've tried to use the id of the goal that generates the sources and even tried to hijack antlr4 name. No result though.
When I try this solution that suggests using mojo build-helper-maven-plugin it compiles as expected. But according to maven guide to generating sources it should be working without any helper plugin, shouldn't it? Am I missing something?
Here is the POM (fragment) configuration that I use to generate the sources.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4.0</version>
<executions>
<execution>
<id>generate-code</id>
<phase>generate-sources</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<includeProjectDependencies>false</includeProjectDependencies>
<includePluginDependencies>true</includePluginDependencies>
<executableDependency>
<groupId>com.company.product</groupId>
<artifactId>CodeGenerator</artifactId>
</executableDependency>
<arguments>
<argument>${basedir}/</argument>
<argument>${project.build.directory}/generated-sources/generate-code/</argument>
</arguments>
<mainClass>com.company.codegeneration.CodeGenerator</mainClass>
</configuration>
<dependencies>
<dependency>
<groupId>com.company.product</groupId>
<artifactId>CodeGenerator</artifactId>
<version>1.0-SNAPSHOT</version>
<type>jar</type>
</dependency>
</dependencies>
</plugin>
Your understanding is just a bit incorrect.
Nothing automatic, plugins generating source code typically handle that by adding their output directory (something like target/generated-sources/ by convention) as source directory to the POM so that it will be included later during the compile phase.
Some less well implemented plugins don't do that for you and you have
to add the directory yourself, for example using the Build Helper
Maven Plugin.
As the other answer noted, most plugins typically add the generated code as new source path.
Ex: See antlr4's Antlr4Mojo.java class. Here, the plugin is adding the generated classes to project source by calling addSourceRoot method in execute method.
// Omitted some code
void addSourceRoot(File outputDir) {
if (generateTestSources) {
project.addTestCompileSourceRoot(outputDir.getPath());
}
else {
project.addCompileSourceRoot(outputDir.getPath());
}
}
// Omitted some code
#Override
public void execute() throws MojoExecutionException, MojoFailureException {
// Omitted code
if(project!=null)
{
// Tell Maven that there are some new source files underneath the output
// directory.
addSourceRoot(this.getOutputDirectory());
}
}
// Omitted some code
So, you can either do this in your custom plugin or use the build-helper-maven-plugin.

Xtend generation with Maven creates wrong String concatenation

When my maven script generates Java from Xtend files, , it generates files with wrong string concatenation.
xtend:
def writeImports(f){
'''
import "test.file"
«getImports()»
'''
}
Generated Java
public CharSequence writeImports () {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import "test.file"");
_builder.newLine();
_builder.append("�getImports()�");
_builder.newLine();
return _builder;
}
Eclipse with the same xtend version generates the correct and expected format, :
public CharSequence writeImports () {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import "test.file"");
_builder.newLine();
String _getImports = this.getImports();
_builder.append(_getImports , "");
_builder.newLine();
return _builder;
}
(eclipse also creates an extra xtendbin file)
The maven script is basically the same as explained in the xtext tutorial, https://eclipse.org/Xtext/documentation/350_continuous_integration.html
<plugin>
<groupId>org.eclipse.xtend</groupId>
<artifactId>xtend-maven-plugin</artifactId>
<version>2.12.0</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>xtend-install-debug-info</goal>
<goal>testCompile</goal>
<goal>xtend-test-install-debug-info</goal>
</goals>
</execution>
</executions>
<configuration>
<outputDirectory>xtend-gen</outputDirectory>
</configuration>
</plugin>
I tried some different xtend versions but it didnt help. Do i need to set some configuration for xtend? Where can i find the possible configuration settings? How do i get the correctly generated file with Maven?
Help would be much appreciated.

Error:java: javacTask: source release 8 requires target release 1.8

Using IntelliJ IDE can't compile any projects. Screenshots of settings below:
Used JDK:
Project SDK and Language level:
Language Level:
Anybody have any ideas?
Go to File > Settings > Build, Execution, Deployment > Compiler > Java Compiler If on a Mac, it's under Intellij IDEA > Preferences... > Build, Execution, Deployment > Java Compiler
Change Target bytecode version to 1.8 of the module that you are working for.
If you are using Maven
Add the compiler plugin to pom.xml under the top-level project node:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
(Hoisted from the comments.)
Note: If you don't mind reimporting your project, then the only thing you really need to do is change the pom and reimport the project, then IntelliJ will pick up the correct settings and you don't have to manually change them.
You need to go to Settings and set under the Java compiler the following:
also check the Project Settings
This looks like the kind of error that Maven generates when you don't have the compiler plugin configured correctly. Here's an example of a Java 8 compiler config.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- ... -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<!-- ... -->
</project>
The quickest way I found:
press:CTRL + SHIFT + A (For Mac ⌘ + SHIFT + A)
type: java compiler
press: ENTER
In the Settings window, set the Target bytecode to 1.8
(or 9 for java9)
There are two ways to solve this problem:
Set settings (File -> Settings -> Build, Execution, Deployment -> Java Compiler):
Add a build section to your pom.xml:
Many answers regarding Maven are right but you don't have to configure the plugin directly.
Like described on the wiki page of the Apache Maven Compiler Plugin you can just set the 2 properties used by the plugin.
<project>
[...]
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
[...]
</project>
I fixed this by going to Project Structure -> Modules, find the module in question, click on Dependencies tab, change Module SDK to Project SDK.
I fixed it just by changing target compile version to 1.8. Its in:
File >> Settings >> Build, Execution, Deployment >> Compiler >> Java Compiler
You need to go to the /.idea/compiler.xml and change target to required jdk level.
In my case I fixed this issue by opening .iml file of project (it is located in project root folder and have name same as the name of project) and changing line <orderEntry type="jdk" jdkName="1.7" jdkType="JavaSDK" /> to <orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
I had everything configured as in others answers here but by some reason Idea updated .iml file incorrectly.
I fixed it by modify my POM file. Notice the last comment under the highest voted answer.
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
The source must matches the target.
I just re-import maven button, then the error disappeared.
In your Gradle app level file >> compileOptions add this two lines
android {
compileOptions {
...
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
...
}
}
If you are working with Android-studio 1.3, Follow the below steps -
Go to File - Project Structure
Under modules- app-Properties tab, choose
Source Compatibility -1.8 and
Target Compatibility - 1.8.
And you are good to go.
Under compiler.xml file you will find :
<bytecodeTargetLevel>
<module name="your_project_name_main" target="1.8" />
<module name="your_project_name_test" target="1.8" />
</bytecodeTargetLevel>
and you can change the target value from your old to the new for me i needed to change it from 1.5 to 1.8
With Intellij, using Maven, you must check that Intellij has auto-imported your project.
You can check by clicking on the Maven tab on the right of your Editor.
If your Project is not here, then add the pom.xml file by clicking on +.
Obviously, the project must also have the relevant <build/> :
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
I've just spent a while struggling with the same problem.
The only thing that worked for me was not using the built mvn (3.3.9) but pointing it to an external downloaded version (3.5.0). Finally the project opened and everything was good.
Don't forget to set dependencies for your module:
This issue occurs if your module is configured with Annotation processor and other module is not.Set the same configuration for all the modules as it wold be cyclic dependency.
the below code working fine by my side. I just add it in the pom.xml file.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
For me, the problem was about Maven not able to find proper configurations, since these items were specified in parent pom.
Changing File -> Settings -> Build, Excecution, Deployment -> Maven -> User Settings file to point to my custom settings with proper repositories fixed the problem that was otherwise hiding.
Found out about the problem through Help -> Show log in explorer -> clicking the log file, when previously only got the error in the title and "java.lang.NullPointerException" in the console.
If none of the other answers work, check your Module SDK.
I had this error pop up for me after I had updated the project SDK to 1.8, the Javac compiler to 1.8, etc. The setting that was the problem for me was the "Module SDK".
(on Linux) Go to File > Project Structure... then in the window that opens, select Modules under Project Settings. Select the module in question from the list and then the Dependencies tab and make sure that Module SDK is set appropriately.
I have checked all of the above but the error still occurs.
But reimport all maven Projects (reload button inside Maven Projects panel) works in my case.
The only thing that helped me was to delete .idea/compiler.xml file.
Solution of the problem is very simple.You have to open .idea/compiler.xml file on your İdea Project and
You should write appropriate target version

Add classpath to netbeans maven project

I have a java project which uses .properties files for configuration. On the server, when launching, I set the classpath to include a folder which contains all the properties files. On my local machine, I'd like to point to a different folder.
I'm looking to add to the classpath, ideally for all projects, but adding it to each project is also fine. I've tried changing the Run > VM Options to include classpath, but with that change it can't find the main class, and I get java.lang.NoClassDefFoundError. I've also tried changing nbactions.xml directly to set the classpath to -classpath ~\MyFolder\;%classpath, but this has the same problem.
To add to the difficulty, the server is running linux while my local machine is running Windows.
I stuck with topic-starter issue also for a long time. My goal - put config files for debug purpose in project root and extend classpath to ${basedir}, so this code:
String appConfigLocation = System.getProperty("config.location");
if (appConfigLocation == null) {
logger.error("System property 'config.location' is not set...");
System.exit(1);
}
InputStream appConfigStream = Main.class.getClassLoader().getResourceAsStream(appConfigLocation);
if (appConfigStream == null) {
logger.error("Can't find resource {} in classpath, fix 'config.location'...", appConfigLocation);
System.exit(1);
}
Properties appProps = new Properties();
try {
appProps.load(appConfigStream);
} catch (IOException ex) {
System.out.println("IO error during loading of {}...", appConfigLocation);
System.exit(1);
}
read configs from ${basedir}. I like that instead of putting them to src/main/resources.
Check sources of ExecMojo.java for v1.2.1 http://grepcode.com/file/repo1.maven.org/maven2/org.codehaus.mojo/exec-maven-plugin/1.2.1/org/codehaus/mojo/exec/ExecMojo.java?av=f :
if ( CLASSPATH_TOKEN.equals( args[i] ) ) {
commandArguments.add( computeClasspathString( null ) );
}
and and v1.3.2 http://grepcode.com/file/repo1.maven.org/maven2/org.codehaus.mojo/exec-maven-plugin/1.3.2/org/codehaus/mojo/exec/ExecMojo.java?av=f:
if ( args[i].contains( CLASSPATH_TOKEN ) ) {
commandArguments.add( args[i].replace( CLASSPATH_TOKEN,
computeClasspathString( null ) ) );
}
So update NB config Execute goals to new version:
process-classes org.codehaus.mojo:exec-maven-plugin:1.3.2:exec
and use complex -classpath args in exec.argsparams:
exec.args=-classpath %classpath:.:"${basedir}" \
-Dconfig.location=app.properties \
-Dlogback.configurationFile=logback.xml \
${packageClassName}
Fix any action you need to have such behavior:
See also:
http://wiki.netbeans.org/FaqEnvVarsDuringRun
http://wiki.netbeans.org/FaqSysPropsDuringRun
Hi I had a similar need to give NetBeans7.4 a classpath to a jar with a driver outwith Maven dependencies e.g. c:\Program Files\Java\jdk1.7.0_25\db\lib\derby.jar in a Java Maven project called MyProject.
As you were thinking with the Run > VM Options, I would suggest the following:
1) right-click on MyProject to open project Properties
2) in 'Project Properties' pop-up, select 'Actions'
3) locate 'Run pproject' among the 'Actions' and select it
4) edit in 'Set Properties' text box entering
exec.args=-cp %classpath;.;"c:\Program Files\Java\jdk1.7.0_25\db\lib\derby.jar" biz.letsweb.derbyconnect.App
exec.executable=java
exec.workingdir=c:\Users\Tomasz\Documents\NetBeansProjects\DerbyConnect\target\classes
Alternatively edit nbactions.xml analogically. Once I did this, I could simply run the project inside NetBeans by pressing green arrow.
what about having the properties included as ? and those you use locally only have in a 's and activate that profile on local machine?
This is how I've been adding classpath to many of my projects
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.nitinsurana.policereports.GUI</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
An outside the box solution I ended up using for my similar case in NetBeans 7.3.1:
Adding files to java classpath at runtime
private static void addSoftwareLibrary(File file) throws Exception {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
method.setAccessible(true);
method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()});
}
This gives me a hacky way to add files to my classpath at run time via program arguments. Related notes I compiled while researching:
To include a dependency for compilation only, not runtime set:
Dependency Scope
<dependency><scope>provided</scope>...</dependency>
To exclude a dependency from the shaded jar, set: Exclude
<exclude>groupId:artifactId[[:type]:classifier]</exclude>
To copy resources to the target directory from outside the typical source directory: Copy Resources
<project>
...
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<executions>
<execution>
<id>copy-resources</id>
<!-- here the phase you need -->
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>target/extra-resources</outputDirectory>
<resources>
<resource>
<directory>extra-resources</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
...
</build>
...
</project>
Note that the base path for directory is the project home. The linked post has <filtering>true</filtering> which can cause "invalid mark" in Netbeans 7.3.1.

Simple compilation fails under Maven, succeeds with javac

I have a simple Maven project that includes one file, App.java, containing
package com.foo;
public class App
{
private Long wrapper;
public long getlong() {
if (null != wrapper) {
return wrapper;
} else {
return 0;
}
}
}
(You can duplicate this by using the Maven in 5 minutes project creation and replacing App.java with the above).
mvn compile produces
.../foo/App.java:[9,12] incompatible types
found : java.lang.Long
required: long
while navigating to the directory and running javac App.java produces no errors. Anybody know what's up? (I assume that Maven uses whatever version of Java is installed on my box; in any case, that's 1.6.0_21. Thanks.
It is probably compiling with a source or target version of 1.4. You will need to configure the compiler plugin to compile for a higher version. See "How do I set up Maven so it will compile with a target and source JVM of my choice?" and "Setting the -source and -target of the Java Compiler":
...
<build>
...
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
...
</build>
...

Categories

Resources