I'm trying to run my custom PMD rules on SonarQube but, so far, without success.
I have created a plugin which extends from the sonar-pmd-plugin. In this plugin I have my PMD ruleset file (custom_rules.xml), a Sonar rules file (pmd-extensions.xml) and the Java classes of my custom rules.
SonarQube identifies my rules, and I have enabled them in my default quality profile. Finally, when I run the sonar analysis on a given project, I see that my custom rules are properly executed and that they find violations in the project under analysis.
However, these violations are never shown on the project dashboard on SonarQube.
The version of SonarQube I'm using is 5.1.1. The version of the PMD plugin is 2.4.1.
I created a minimal example for this issue, with only one custom rule.
custom_rules.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="My custom rules" xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
<rule
language="java"
name="RuleJavaAssert"
message="Avoid assert in production"
class="br.gov.tcu.rules.RuleJavaAssert">
<description>Production code should not use the assert command</description>
<priority>3</priority>
</rule>
</ruleset>
pmd-extensions.xml:
<rules>
<rule>
<key>br.gov.tcu.rules.RuleJavaAssert</key>
<name>Avoid assert in production</name>
<category name="Maintainability" />
<priority>BLOCKER</priority>
<description>Production code should not use the assert command</description>
<configKey>br/gov/tcu/rules/custom_rules.xml/RuleJavaAssert</configKey>
</rule>
</rules>
RuleJavaAssert.java:
public class RuleJavaAssert extends AbstractJavaRule {
#Override
public Object visit(ASTAssertStatement node, Object data) {
System.err.println("Found violation");
addViolation(data, node);
return super.visit(node, data);
}
}
AssertViolation.java:
public class AssertViolation {
public static void testMethod() {
String test = "test";
assert(test != null);
}
}
The output of SonarQube analysis on the console, when run against a project which contains the class "AssertViolation.java":
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building teste-pmd 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- sonar-maven-plugin:2.7.1:sonar (default-cli) # teste-pmd ---
[INFO] User cache: D:\Users\x02315941199\.sonar\cache
[INFO] SonarQube version: 5.1.1
(...)
[INFO] [15:48:17.564] Sensor PmdSensor
[INFO] [15:48:17.564] Execute PMD 5.3.1...
[INFO] [15:48:17.580] Java version: 1.7
[INFO] [15:48:17.595] PMD configuration: D:\Users\x02315941199\Documents\PMD\workspace\teste-pmd\target\sonar\pmd.xml
Found violation
[INFO] [15:48:17.815] PMD configuration: D:\Users\x02315941199\Documents\PMD\workspace\teste-pmd\target\sonar\pmd-unit-tests.xml
[INFO] [15:48:17.815] Execute PMD 5.3.1 done: 251 ms
[INFO] [15:48:17.971] Sensor PmdSensor (done) | time=407ms
(...)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.185 s
[INFO] Finished at: 2015-11-11T15:48:19-02:00
[INFO] Final Memory: 72M/741M
[INFO] ------------------------------------------------------------------------
From the console message "Found violation" I can see that the rule was executed properly, but still SonarQube indicates 0 issues.
Any thoughts?
Thanks
The reason SonarQube doesn't show the violations is because the violation recorder in the sonar-pmd-plugin searches for the rule by its key.
Therefore, the key attribute in the pmd-extensions.xml file must equal the name attribute of the rule in custom_rules.xml
The provided example would be fixed by changing the pmd-extensions.xml content to:
<rules>
<rule>
<key>RuleJavaAssert</key>
<name>Avoid assert in production</name>
<category name="Maintainability" />
<priority>BLOCKER</priority>
<description>Production code should not use the assert command</description>
<configKey>br/gov/tcu/rules/custom_rules.xml/RuleJavaAssert</configKey>
</rule>
</rules>
Related
I have a toy program that has a compilation error only in Eclipse when I try to use a Chronicle import and compile to language level 11. The program compiles and runs in maven, and also in IntelliJ (with the same maven and JDK).
The versions I have are:
maven 3.6.1
jdk openjdk version "11" 2018-09-25
eclipse 2020-03-R
chronicle-bom 2.19.199 (supported java11 since 2.17)
This is my pom.xml
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>testjava11</groupId>
<artifactId>chronicle-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>net.openhft</groupId>
<artifactId>chronicle-bom</artifactId>
<version>2.19.199</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>net.openhft</groupId>
<artifactId>chronicle-map</artifactId>
</dependency>
</dependencies>
</project>
And here is my simple test class:
import net.openhft.chronicle.bytes.BytesMarshallable;
public class App {
public static void main(String[] args) {
System.out.println("BytesMarshallable: " + new BytesMarshallable() {});
}
}
The output when running exec:java directly with maven is
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< testjava11:chronicle-test >----------------------
[INFO] Building chronicle-test 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) # chronicle-test ---
[INFO] Deleting C:\Users\eclipse-workspace\chronicle-test\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) # chronicle-test ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) # chronicle-test ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\Users\eclipse-workspace\chronicle-test\target\classes
[INFO]
[INFO] --- exec-maven-plugin:3.0.0:java (default-cli) # chronicle-test ---
BytesMarshallable: App$1#309d6b5b
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.400 s
[INFO] Finished at: 2020-06-11T15:04:53+02:00
[INFO] ------------------------------------------------------------------------
It compiles in IntelliJ and this is the output when I run as a Java Application:
BytesMarshallable: App$1#39fb3ab6
Process finished with exit code 0
However, in Eclipse the class App will not compile. The error is on the import line and says:
The type java.lang.String cannot be resolved. It is indirectly referenced from required .class files
There is an additional message in the Problems panel:
The project was not built since its build path is incomplete.
Cannot find the class file for java.lang.String.
Fix the build path then try building this project
But I don't see what the issue is in my build path:
Furthermore, I can see java.lang is present in the package explorer:
(Note that if I change the language level to 8, but still using JDK 11, it will work in Eclipse.)
I have checked for obvious issues (build path, maven/jdk path) and everything appears correct to me. Why do I get this error in Eclipse and how can I fix it?
The full error message is :
Type java.lang.String is indirectly referenced from required .class files but cannot be resolved since the declaring package java.lang exported
from module java.base conflicts with a package accessible from module
It's caused by one of the transitive dependencies, net.openhft:affinity:3.2.3, embedding 2 classes from the java.lang package, which is illegal. The ECJ compiler in Eclipse complaining about it is expected. However, the fact it works in javac is a bug in itself: https://bugs.openjdk.java.net/browse/JDK-8215739
There's an affinity issue about it: https://github.com/OpenHFT/Java-Thread-Affinity/issues/58
If you're not using the thread affinity features, just exclude affinity from your dependencies and the Eclipse compiler will stop complaining.
The error was solved after I opened
Window > Preferences: Java > Installed JREs > Execution Env
And re-selected the JavaSE-11, Apply and Close
In my case I had following error, and it had no relationship with "Configure build path" --
The type java.io.FilterOutputStream cannot be resolved. It is indirectly referenced from required .class files
The error was solved after I create a package and located the problematic class into the class.
It has a mismatch with pom file so update in pom file as well.
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
I have used these two then its working fine for me.
We’re building Java servlet apps using eclipse and maven which run in the Google Cloud Platform.
We are starting to look at integrating OpenClover into our builds to provide test coverage and code complexity statistics.
Some of our apps have dependencies on Google libraries, such as com.google.cloud.spanner.Statement.Builder.
When we try and run clover from the command line against these servlets we see the following errors:
[INFO] Building auditio 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) # auditio ---
[INFO]
[INFO] --- clover-maven-plugin:4.3.0:setup (default-cli) # auditio ---
[INFO] OpenClover Version 4.3.0, built on August 03 2018 (build-1010)
[INFO] Creating new database at 'C:\.......\service\auditio\target\clover\clover.db'.
[INFO] Processing files at 1.8 source level.
[INFO] C:\...........\service\auditio\AuditIoSpanner.java:54:5:unexp
ected token: builder
[INFO] Instrumentation error
com.atlassian.clover.api.CloverException: C:\...............\service\auditio\src\main\java\com\mandm\service\aud
itio\AuditIoSpanner.java:54:5:unexpected token: builder
at com.atlassian.clover.instr.java.Instrumenter.instrument(Instrumenter.java:159)
at com.atlassian.clover.CloverInstr.execute(CloverInstr.java:76)
at com.atlassian.clover.CloverInstr.mainImpl(CloverInstr.java:54)
[ERROR] Failed to execute goal org.openclover:clover-maven-plugin:4.3.0:setup (default-cli) on project auditio: Clover has fa
iled to instrument the source files in the [C:\........service\auditio\target\clover\src-instrumented] d
irectory -> [Help 1]
This is when running the following command:
mvn clean clover:setup test clover:aggregate clover:clover check
With the following in our pom.xml
<plugin>
<groupId>org.openclover</groupId>
<artifactId>clover-maven-plugin</artifactId>
<version>4.3.0</version>
<configuration>
<targetPercentage>75%</targetPercentage>
</configuration>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>instrument</goal>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
We’re running JDK 1.8.
While we can exclude the offending class files that contain these references to get the clover coverage to work, that isn’t ideal.
Servlets that do not have these specific references will run clover just fine.
Can anyone advise why this might be occurring and if there is a known resolution?
Thanks in advance.
After reaching out to OpenClover support they have confirmed that this is caused by a bug in their latest (4.3.0) release as can be seen here - https://bitbucket.org/openclover/clover/issues/72
- and will be resolved in a patch.
I have a custom linker to generate a manifest file that used to work fine up to GWT 2.7. When I changed to GWT 2.8 I noticed it stopped generating the file myapp.manifest.
On module.gwt.xml I have
<?xml version="1.0" encoding="UTF-8"?>
<module>
<inherits name="com.google.gwt.user.User" />
<inherits name="com.google.gwt.core.Core" />
<source path="client" />
<source path="shared" />
<source path="constants" />
<entry-point class="br.com.universo.client.AppStart" />
<extend-property name="locale" values="pt" />
<extend-property name="locale" values="en" />
<set-property-fallback name="locale" value="en" />
<define-linker class="br.com.universo.AppManifest"
name="manifest" />
<add-linker name="manifest" />
</module>
This is the compilation log on 2.7
[INFO] --- gwt-maven-plugin:2.7.0:compile (default) # universo-bootstrap ---
[INFO] auto discovered modules [br.com.universo.core.appCore, br.com.universo.app]
[INFO] br.com.universo.core.appCore has no EntryPoint - compilation skipped
[INFO] Compiling module br.com.universo.app
[INFO] Ignored 7 units with compilation errors in first pass.
[INFO] Compile with -strict or with -logLevel set to TRACE or DEBUG to see all errors.
[INFO] Compiling 6 permutations
[INFO] Compiling permutation 0...
[INFO] Process output
[INFO] Compiling
[INFO] Compiling permutation 1...
[INFO] Compiling permutation 2...
[INFO] Compiling
[INFO] Compiling permutation 3...
[INFO] Compiling permutation 4...
[INFO] Compiling permutation 5...
[INFO] Compile of permutations succeeded
[INFO] Compilation succeeded -- 165.867s
[INFO] MyApp OffLine Linker started
[INFO] MyApp OffLine Linker ended
[INFO] Linking into /universo/universo-bootstrap/target/universo-bootstrap-1.0-SNAPSHOT/app
[INFO] Link succeeded
[INFO] Linking succeeded -- 1.239s
On GWT 2.8 I am using tbroyer gwt maven archetype modular-webapp. The linker class was defined under the client module, but on a package outside
<source path="client" />
and on compilation log I don't see the lines:
[INFO] MyApp OffLine Linker started
[INFO] MyApp OffLine Linker ended
which I suppose indicates it is not being called?
[INFO] --- gwt-maven-plugin:1.0-rc-7:compile (default-compile) # universo-client ---
[INFO] Compiling module br.com.universo.app
[INFO] Compiling 9 permutations
[INFO] Compiling permutation 0...
[INFO] [WARN] Namespace option is not compatible with CodeSplitter, turning it off.
[INFO] Compiling permutation 1...
[INFO] Compiling permutation 2...
[INFO] Compiling permutation 3...
[INFO] Compiling permutation 4...
[INFO] Compiling permutation 5...
[INFO] Compiling permutation 6...
[INFO] Compiling permutation 7...
[INFO] Compiling permutation 8...
[INFO] Compile of permutations succeeded
[INFO] Compilation succeeded -- 104.171s
[INFO] Linking into /universo/universo-client/target/universo-client-1.0-SNAPSHOT/app
[INFO] Link succeeded
[INFO] Linking succeeded -- 1.818s
The Linker class AppManifest.java
package br.com.universo;
import java.util.Date;
import com.google.gwt.core.ext.LinkerContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.linker.AbstractLinker;
import com.google.gwt.core.ext.linker.ArtifactSet;
import com.google.gwt.core.ext.linker.EmittedArtifact;
import com.google.gwt.core.ext.linker.LinkerOrder;
import com.google.gwt.core.ext.linker.LinkerOrder.Order;
import com.google.gwt.core.ext.linker.Shardable;
#Shardable
#LinkerOrder(Order.POST)
public class AppManifest extends AbstractLinker {
static final String[] cache = new String[] {
"# Css"
, "/css/base.css"
, "/css/feedback.css"
, "/css/layout.css"
, "/css/prettyPhoto.css"
, "/css/shortcodes.css"
, "/css/slideshow.css"
, "/css/style.css"
};
static final String[] network = new String[] {
"*"
};
#Override
public String getDescription() {
return "MyApp OffLine Linker";
}
#Override
public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts) throws UnableToCompleteException {
System.out.println("MyApp OffLine Linker started");
ArtifactSet artifactset = new ArtifactSet(artifacts);
StringBuilder builder= new StringBuilder("CACHE MANIFEST\n");
builder.append("# Cache Version " + new Date() + "\n\n");
builder.append("CACHE:\n");
for (String line : cache) {
builder.append(line + "\n");
}
builder.append("\n\n");
for(EmittedArtifact emitted: artifacts.find(EmittedArtifact.class))
{
if(emitted.getPartialPath().endsWith(".symbolMap"))continue;
if(emitted.getPartialPath().endsWith(".txt"))continue;
builder.append(emitted.getPartialPath()).append("\n");
}
builder.append("\n\n");
builder.append("NETWORK:\n");
for (String line : network) {
builder.append(line + "\n");
}
builder.append("\n\n");
builder.append("FALLBACK:\n");
EmittedArtifact manifest = emitString(logger, builder.toString(), "myapp.manifest");
artifactset.add(manifest);
System.out.println("MyApp OffLine Linker ended");
return artifactset;
}
}
Any help is well appreciated!
I finally had it working changing my AppManifast.java. I noticed on current documentation that when using #Shardable annotation you have to override the other link method signature, so I added the following lines to the class:
#Override
public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts, boolean onePermutation) throws UnableToCompleteException {
return link(logger, context, artifacts);
}
It took me forever to find out...
I am using hyperjaxb to generate Java classes from an xsd file. How can I configure it to generate hibernate annotations, and to trigger hbm2ddl to create a MySQL database with tables for the generated classes?
I downloaded the purchase order sample for hibernate from this link, then navigated to the target directory in cmd.exe and ran mvn clean install, but the resulting folders did not contain any java classes, and this also did not contain any hibernate/MySQL. I would like to get a working example that creates everything from a downloaded xsd file so that I can just plug my own xsd file into the code and have all the java/hibernate/mysql be autogenerated. That way I can spend my time tweaking my xsd file so that the resulting java/hibernate/MySQL is what I need it to be.
A code example or step by step instructions would be really helpful. I am using eclipse.
**EDIT: **
The answer to this question came after posting a few other questions. To find the complete answer to this question, you will need to review the answers to those other questions, in particular, the one at this link.
UPDATE
Finally it appeared that the OP was looking for generated classes in the root directory of the project insteadof target\generated-source\xjc, despite the tutorial clearly states where to look:
If you browse the target/generated-sources/xjc directory, you'll find
few generated java files, for instance PurchaseOrderType.java.
I don't understand it when you say that nothing is generated. I've just rechecked it, everything works fine.
My steps are:
Download hyperjaxb3-ejb-samples-po-initial-0.5.6-maven-src.zip
Unzip
Go to hyperjaxb3-ejb-samples-po-initial-0.5.6
mvn clean install
Here's what I get:
[INFO] ------------------------------------------------------------------------
[INFO] Building Hyperjaxb3 Samples [po-initial:maven] 0.5.6
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) # hyperjaxb3-ejb-samples-po-initial-maven ---
[INFO] Deleting C:\Projects\workspaces\hj3\dist\hyperjaxb3-ejb-samples-po-initial-0.5.6\target
[INFO]
[INFO] --- maven-hyperjaxb3-plugin:0.6.0:generate (default) # hyperjaxb3-ejb-samples-po-initial-maven ---
[INFO] Sources are not up-to-date; XJC execution will be executed.
[WARNING] According to the Java Persistence API specification, section 2.1, entities must be top-level classes:
"The entity class must be a top-level class."
Your JAXB model is not customized as with top-level local scoping, please use the <jaxb:globalBinding localScoping="toplevel"/> global bindings customization.
org.jvnet.hyperjaxb3.ejb.plugin.EjbPlugin
[WARNING] According to the Java Persistence API specification, section 2.1, entities must implement the serializable interface:
"If an entity instance is to be passed by value as a detached object
(e.g., through a remote interface), the entity class must implement
the Serializable interface."
Your JAXB model is not customized as serializable, please use the <jaxb:serializable/> global bindings customization element to make your model serializable.
org.jvnet.hyperjaxb3.ejb.plugin.EjbPlugin
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) # hyperjaxb3-ejb-samples-po-initial-maven ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) # hyperjaxb3-ejb-samples-po-initial-maven ---
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 5 source files to C:\Projects\workspaces\hj3\dist\hyperjaxb3-ejb-samples-po-initial-0.5.6\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) # hyperjaxb3-ejb-samples-po-initial-maven ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:testCompile (default-testCompile) # hyperjaxb3-ejb-samples-po-initial-maven ---
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 5 source files to C:\Projects\workspaces\hj3\dist\hyperjaxb3-ejb-samples-po-initial-0.5.6\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) # hyperjaxb3-ejb-samples-po-initial-maven ---
[INFO] Surefire report directory: C:\Projects\workspaces\hj3\dist\hyperjaxb3-ejb-samples-po-initial-0.5.6\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running RoundtripTest
Detected [file:/C:/Projects/workspaces/hj3/dist/hyperjaxb3-ejb-samples-po-initial-0.5.6/target/classes/META-INF/persistence.xml].
RoundtripTest
Loading entity manager factory properties.
RoundtripTest
Loading entity manager factory properties from [file:/C:/Projects/workspaces/hj3/dist/hyperjaxb3-ejb-samples-po-initial-0.5.6/target/test-classes/persistence.properties].
RoundtripTest
Testing samples.
RoundtripTest
Sample directory [C:\Projects\workspaces\hj3\dist\hyperjaxb3-ejb-samples-po-initial-0.5.6\src\test\samples].
RoundtripTest
Testing sample [po.xml].
RoundtripTest
Unmarshalling.
RoundtripTest
Opening session.
RoundtripTest
Saving the object.
RoundtripTest
Opening session.
RoundtripTest
Loading the object.
RoundtripTest
Closing the session.
RoundtripTest
Initial object:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<purchaseOrder orderDate="1999-10-20">
<shipTo country="US">
<name>Alice Smith</name>
<street>123 Maple Street</street>
<city>Mill Valley</city>
<state>CA</state>
<zip>90952</zip>
</shipTo>
<billTo country="US">
<name>Robert Smith</name>
<street>8 Oak Avenue</street>
<city>Old Town</city>
<state>PA</state>
<zip>95819</zip>
</billTo>
<comment>Hurry, my lawn is going wild!</comment>
<items>
<item partNum="872-AA">
<productName>Lawnmower</productName>
<quantity>1</quantity>
<USPrice>148.95</USPrice>
<comment>Confirm this is electric</comment>
</item>
<item partNum="926-AA">
<productName>Baby Monitor</productName>
<quantity>1</quantity>
<USPrice>39.98</USPrice>
<shipDate>1999-05-21</shipDate>
</item>
</items>
</purchaseOrder>
RoundtripTest
Source object:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<purchaseOrder orderDate="1999-10-20" Hjid="1">
<shipTo country="US" Hjid="2">
<name>Alice Smith</name>
<street>123 Maple Street</street>
<city>Mill Valley</city>
<state>CA</state>
<zip>90952</zip>
</shipTo>
<billTo country="US" Hjid="1">
<name>Robert Smith</name>
<street>8 Oak Avenue</street>
<city>Old Town</city>
<state>PA</state>
<zip>95819</zip>
</billTo>
<comment>Hurry, my lawn is going wild!</comment>
<items Hjid="1">
<item partNum="872-AA" Hjid="1">
<productName>Lawnmower</productName>
<quantity>1</quantity>
<USPrice>148.95</USPrice>
<comment>Confirm this is electric</comment>
</item>
<item partNum="926-AA" Hjid="2">
<productName>Baby Monitor</productName>
<quantity>1</quantity>
<USPrice>39.98</USPrice>
<shipDate>1999-05-21</shipDate>
</item>
</items>
</purchaseOrder>
RoundtripTest
Result object:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<purchaseOrder orderDate="1999-10-20" Hjid="1">
<shipTo country="US" Hjid="2">
<name>Alice Smith</name>
<street>123 Maple Street</street>
<city>Mill Valley</city>
<state>CA</state>
<zip>90952</zip>
</shipTo>
<billTo country="US" Hjid="1">
<name>Robert Smith</name>
<street>8 Oak Avenue</street>
<city>Old Town</city>
<state>PA</state>
<zip>95819</zip>
</billTo>
<comment>Hurry, my lawn is going wild!</comment>
<items Hjid="1">
<item partNum="872-AA" Hjid="1">
<productName>Lawnmower</productName>
<quantity>1</quantity>
<USPrice>148.95</USPrice>
<comment>Confirm this is electric</comment>
</item>
<item partNum="926-AA" Hjid="2">
<productName>Baby Monitor</productName>
<quantity>1</quantity>
<USPrice>39.98</USPrice>
<shipDate>1999-05-21</shipDate>
</item>
</items>
</purchaseOrder>
RoundtripTest
Checking the document identity.
RoundtripTest
Finished testing sample [po.xml].
RoundtripTest
Finished testing samples.
RoundtripTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.552 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) # hyperjaxb3-ejb-samples-po-initial-maven ---
[INFO] Building jar: C:\Projects\workspaces\hj3\dist\hyperjaxb3-ejb-samples-po-initial-0.5.6\target\hyperjaxb3-ejb-samples-po-initial-maven-0.5.6.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) # hyperjaxb3-ejb-samples-po-initial-maven ---
[INFO] Installing C:\Projects\workspaces\hj3\dist\hyperjaxb3-ejb-samples-po-initial-0.5.6\target\hyperjaxb3-ejb-samples-po-initial-maven-0.5.6.jar to C:\Repository\org\jvnet\hyperjaxb3\hyperjaxb3-ejb-samples-po-initial-maven\0.5.6\hyperjaxb3-ejb-samples-po-initial-maven-0.5.6.jar
[INFO] Installing C:\Projects\workspaces\hj3\dist\hyperjaxb3-ejb-samples-po-initial-0.5.6\pom.xml to C:\Repository\org\jvnet\hyperjaxb3\hyperjaxb3-ejb-samples-po-initial-maven\0.5.6\hyperjaxb3-ejb-samples-po-initial-maven-0.5.6.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 12.100 s
[INFO] Finished at: 2014-10-09T00:42:10+01:00
[INFO] Final Memory: 22M/96M
[INFO] ------------------------------------------------------------------------
Full mvn clean install -X log is here.
So I hope you see, it works perfectly. Please post you mvn clean install -X, maybe you do something wrong.
Now, concerning your question, here's the MySQL example:
https://github.com/highsource/hyperjaxb3/tree/master/ejb/tests/po-mysql
This project includes a snippet of hbm2ddl generation:
https://github.com/highsource/hyperjaxb3/tree/master/ejb/tests/issues
The hbm2ddl is commented out for some reason, not sure if it works, but it should give the direction.
This is a part of another answer which answers the MySQL part. I add this here for future reference in an attempt to close this question.
So from now on I assume that the PO tutorial worked fine: the code was generated, roundtrip test ran with the HSQLDB database etc.
Now we'll address two questions:
How to switch to MySQL?
How to generate database schema with hbm2ddl?
Let's get started.
Switching to MySQL
First of all, you have to replace HSQLDB with MySQL in the pom.xml. Remove this:
<dependency>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>1.8.0.7</version>
<scope>test</scope>
</dependency>
And add this:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.5</version>
<scope>test</scope>
</dependency>
Next, edit src/test/resources/persistence.properties. Replace this:
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.connection.driver_class=org.hsqldb.jdbcDriver
hibernate.connection.username=sa
hibernate.connection.password=
hibernate.connection.url=jdbc:hsqldb:target/test-database/database
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.provider_class=org.hibernate.cache.HashtableCacheProvider
hibernate.jdbc.batch_size=0
With this:
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.username=...
hibernate.connection.password=...
hibernate.connection.url=jdbc:mysql://localhost/hj3
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.provider_class=org.hibernate.cache.HashtableCacheProvider
hibernate.jdbc.batch_size=0
I personally don't have a MySQL database at hand at the moment, so I can't really test the roundtrip. Therefore I'll comment out
<!--roundtripTestClassName>RoundtripTest</roundtripTestClassName-->
in pom.xml.
If you have a database at hand, just configure the right URL/username/password in the mentioned persistence.properties file.
At this point your Maven project is reconfigured to use MySQL. If the roundtrip test is not commented out and the database is available, the roundrip test should run with the DB, i.e. create the schema, import the sample XML, read it back and compare alpha and omega.
So now we have the tutorial on MySQL and can move on.
Generating the database schema
This was a tricky part to figure out.
In order to generate the database schema in a file, you have to use the hbm2ddl tool. There are Maven plugins for that, in case of Hibernate 3 it seemed that the Codehaus plugin is the leading one. Finally, I have figured out the following configuration. You have to add the following plugin to your pom.xml (project/build/plugins):
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>hibernate3-maven-plugin</artifactId>
<version>3.0</version>
<executions>
<execution>
<id>generate-schema</id>
<phase>compile</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
<configuration>
<hibernatetool>
<classpath>
<path location="${project.build.directory}/classes" />
</classpath>
<jpaconfiguration persistenceunit="org.jvnet.hyperjaxb3.ejb.tests.pocustomized" propertyfile="src/test/resources/persistence.properties"/>
<hbm2ddl export="false" create="true" update="false" format="true" outputfilename="schema.ddl" />
</hibernatetool>
</configuration>
<dependencies>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.5.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.5</version>
</dependency>
</dependencies>
</plugin>
Few things are important:
Hyperjaxb3 generates JPA annotations, so you have to use jpaconfiguration.
Therefore the hibernate3-maven-plugin must be executed in the compile phase (you need classes to read annotations from so they have to be compiled at that moment).
You have to include the compiled classes (${project.build.directory}/classes) to the hibernatetool's classpath so that it can discover classes and read annotations.
You have to let the hibernatetool know where you find your Hibernate properties (propertyfile="src/test/resources/persistence.properties").
Finally you have to let it know, which persistence unit you want to process (persistenceunit="org.jvnet.hyperjaxb3.ejb.tests.pocustomized"). Take a look at target/generated-sources/xjc/META-INF/persistence.xml.
Finally, add all the required dependencies.
Finally you arrive at the configuration I posted above. At this point the build should also generate the database schema in target/sql/hibernate3/schema.ddl.
I have a maven-based GWT project that includes Guava. I am running into trouble with Maven trying (and failing) to compile the sources that it finds in guava-gwt*.jar:
could not parse error message: symbol: static setCountImpl
location: class
/home/mark/.m2/repository/com/google/guava/guava-gwt/11.0.1/guava-gwt-11.0.1.jar(com/google/common/collect/AbstractMultiset.java):100: error: cannot find symbol
return setCountImpl(this, element, count);
^
I can't figure out why Maven thinks it needs to compile the sources in guava-gwt. Here's what my project looks like:
├── pom.xml
└── src
├── main
│ └── java
└── test
└── java
└── SomeTestFile.java
SomeTestFile.java
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.junit.Test;
public class SomeTestFile {
#Test
public void testMethod() {
Multimap<Integer, String> someMap = ArrayListMultimap.create();
someMap.put(5, "five");
System.out.println(someMap);
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>guava-problem</groupId>
<artifactId>guava-problem</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>11.0.1</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-gwt</artifactId>
<version>11.0.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
I have already tried the following:
Removing the guava dependency (leaving only guava-gwt)
Scoping guava-gwt to provided
I'm not sure what else to try. guava-gwt includes sources because GWT will compile it into equivalent Javascript. But I don't want Maven to try to compile these sources.
Edit
Just a note...the test files themselves have no real need for guava-gwt over guava since they are compiled and run as Java code (they don't go through the GWT compile step). I don't need guava-gwt specifically for these tests but it needs to be available for my actual GWT client code.
Full Maven Output
mark#mark-peters:~/devel/guava-problem$ mvn -V clean test-compile
Apache Maven 2.2.1 (rdebian-1)
Java version: 1.7.0
Java home: /usr/lib/jvm/jdk1.7.0/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux" version: "2.6.32-38-generic" arch: "amd64" Family: "unix"
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Unnamed - guava-problem:guava-problem:jar:1.0
[INFO] task-segment: [clean, test-compile]
[INFO] ------------------------------------------------------------------------
[INFO] [clean:clean {execution: default-clean}]
[INFO] Deleting file set: /home/mark/devel/guava-problem/target (included: [**], excluded: [])
[INFO] [resources:resources {execution: default-resources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/mark/devel/guava-problem/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [resources:testResources {execution: default-testResources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/mark/devel/guava-problem/src/test/resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] Compiling 1 source file to /home/mark/devel/guava-problem/target/test-classes
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Compilation failure
/home/mark/.m2/repository/com/google/guava/guava-gwt/11.0.1/guava-gwt-11.0.1.jar(com/google/common/collect/AbstractMultiset.java):[19,0] error: cannot find symbol
could not parse error message: symbol: static setCountImpl
location: class
/home/mark/.m2/repository/com/google/guava/guava-gwt/11.0.1/guava-gwt-11.0.1.jar(com/google/common/collect/AbstractMultiset.java):100: error: cannot find symbol
return setCountImpl(this, element, count);
^
could not parse error message: symbol: method setCountImpl(AbstractMultiset<E>,E,int)
location: class AbstractMultiset<E>
where E is a type-variable:
E extends Object declared in class AbstractMultiset
/home/mark/.m2/repository/com/google/guava/guava-gwt/11.0.1/guava-gwt-11.0.1.jar(com/google/common/collect/AbstractMultiset.java):105: error: cannot find symbol
return setCountImpl(this, element, oldCount, newCount);
^
[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Tue Feb 21 12:49:42 EST 2012
[INFO] Final Memory: 18M/212M
[INFO] ------------------------------------------------------------------------
Edit (again)
Having found that the source of the problem has nothing to do with Guava but rather the Maven version (see my answer), I've updated the title and question to try to be a lot more helpful to future users.
tl;dr
Maven 2 and JDK 7 are incompatible, as Maven tries to parse javac output which has changed in JDK 7.
Full explanation
Raghuram's note that this worked for him in Maven 3+ took me down the road of exploring this not as a config problem but as an actual Maven problem. I started doing more testing and found that this problem:
Occurs with Java 7 and Maven 2.2.1
Does not occur with Java 7 and Maven 3+
Does not occur with Java 6 and Maven 2.2.1
So at that point it became clear to me that the "could not parse error message" errors were relevant, and the problem probably had less to do with the guava-gwt compilation occurring and more to do with Maven not knowing how to handle the errors properly.
To test this I created a separate Maven project that has nothing to do with Guava:
├── pom.xml
└── src
└── main
└── java
└── ClassWithWarnings.java
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>maven-problem</groupId>
<artifactId>maven-problem</artifactId>
<version>1.0</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
</project>
ClassWithWarnings.java
public class ClassWithWarnings implements java.io.Serializable {}
Lo and behold, Maven tanks on this project as well when using Java 7:
mark#mark-peters:~/devel/maven-problem$ mvn -V compile
Apache Maven 2.2.1 (rdebian-1)
Java version: 1.7.0
Java home: /usr/lib/jvm/jdk1.7.0/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux" version: "2.6.32-38-generic" arch: "amd64" Family: "unix"
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Unnamed - maven-problem:maven-problem:jar:1.0
[INFO] task-segment: [compile]
[INFO] ------------------------------------------------------------------------
[INFO] [resources:resources {execution: default-resources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/mark/devel/maven-problem/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Compiling 1 source file to /home/mark/devel/maven-problem/target/classes
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Compilation failure
could not parse error message: warning: [options] bootstrap class path not set in conjunction with -source 1.3
/home/mark/devel/maven-problem/src/main/java/ClassWithWarnings.java:1: warning: [serial] serializable class ClassWithWarnings has no definition of serialVersionUID
public class ClassWithWarnings implements java.io.Serializable {}
^
[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Tue Feb 21 13:10:47 EST 2012
[INFO] Final Memory: 14M/150M
[INFO] ------------------------------------------------------------------------
With Java 6, it still reports the warnings, but can parse the Javac output and so doesn't tank:
Apache Maven 2.2.1 (rdebian-1)
Java version: 1.6.0_20
Java home: /usr/lib/jvm/java-6-openjdk/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux" version: "2.6.32-38-generic" arch: "amd64" Family: "unix"
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Unnamed - maven-problem:maven-problem:jar:1.0
[INFO] task-segment: [compile]
[INFO] ------------------------------------------------------------------------
[INFO] [resources:resources {execution: default-resources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/mark/devel/maven-problem/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Compiling 1 source file to /home/mark/devel/maven-problem/target/classes
[WARNING] /home/mark/devel/maven-problem/src/main/java/ClassWithWarnings.java:[1,7] [serial] serializable class ClassWithWarnings has no definition of serialVersionUID
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Tue Feb 21 13:18:39 EST 2012
[INFO] Final Memory: 9M/150M
[INFO] ------------------------------------------------------------------------
So it seems as if the problem was that the latest Maven 2 release doesn't know how to parse error messages from Java 7+ javac. Maven 3 does. I still haven't found documentation of this and am a little surprised that Maven doesn't give a warning when it tries to compile against a JDK version that it doesn't know how to support properly.
Converting my comment to an answer...
The exact pom file along with the test class above compiles fine on my Windows box with maven 3.0.4.
The problem could be with the maven version that you are using. Or there could be other maven goals in the actual pom, which may be causing an issue.
For a similar problem I upgraded maven-compiler-plugin to a later version.
Happened to us, that we received the exact same failure, but with gradle instead of maven. After switching from ArrayListMultimap to LinkedListMultimap to error is gone. So it seems, that in version 11.0.2 at least the ArrayListMultimap is broken.
It appears that it's not trying to compile the Guava libraries, but without the full maven build log we can't tell.
Judging by the information you've posted so far, it would appear instead that you have two incompatible versions of a class or library on your classpath during compilation.
I'm going to try your test project and see if I can give you more information.
EDIT:
So I've found a couple of interesting things. First, I was able to get your project to work without a whole lot of fanfare :(
I changed your pom to:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>11.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-gwt</artifactId>
<version>11.0.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
By default though, your test file will not run. I refactored it so it was is now named SomeTestFileTest which will actually run the test.
I'm running Maven v2.2.1 on OSX. I also cleaned out my ~/.m2/repository before starting. I suggest you try the same: nuke your local repository folder and retry your build. If that doesn't work, let me know what version of maven you're running.