I am trying to integrate eclipselink JPA into my Spring Web application.
Is there any good guide oh how to configure eclipseLink for MySql database in Spring MVC using Java based configuration only?. No dispatcher-servlet.xml.
I am familiar with Java based Spring configuration. (Using #Configuration, #EnableWebMvc, #ComponentScan, #EnableTransactionManagement etc). But not familiar with eclipseLink java based configuration in Spring MVC.
Following is the 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 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>roster3</groupId>
<artifactId>roster3</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>roster3 Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.0.2.RELEASE</spring.version>
<hibernate.version>4.3.4.Final</hibernate.version>
<hibernate.validator.version>5.1.0.Final</hibernate.validator.version>
<mysql.connector.version>5.1.29</mysql.connector.version>
<eclipselink.version>2.5.0</eclipselink.version>
<aspectj.version>1.5.4</aspectj.version>
</properties>
<repositories>
<repository>
<id>oss.sonatype.org</id>
<name>OSS Sonatype Staging</name>
<url>https://oss.sonatype.org/content/groups/staging</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency> -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Servlet & jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Hibernate Validation & DB Validation -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.validator.version}</version>
</dependency>
<!-- eclipselink -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>${eclipselink.version}</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
<artifactId>commonj.sdo</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
</dependencies>
<build>
<!-- To define the plugin version in your parent POM -->
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.3-SNAPSHOT</version>
<configuration>
<url>http://127.0.0.1:8080/roster3</url>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
<argLine>-javaagent:eclipselink.jar</argLine>
</configuration>
</plugin>
<!-- This plugin ensures the EclipseLink static weaving -->
<plugin>
<artifactId>eclipselink-staticweave-maven-plugin</artifactId>
<groupId>au.com.alderaan</groupId>
<version>1.0.4</version>
<executions>
<execution>
<goals>
<goal>weave</goal>
</goals>
<phase>process-classes</phase>
<configuration>
<logLevel>ALL</logLevel>
<!-- <includeProjectClasspath>true</includeProjectClasspath> -->
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>${eclipselink.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings
only. It has no influence on the Maven build itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
au.com.alderaan
</groupId>
<artifactId>
eclipselink-staticweave-maven-plugin
</artifactId>
<versionRange>
[1.0.4,)
</versionRange>
<goals>
<goal>weave</goal>
</goals>
</pluginExecutionFilter>
<action>
<execute>
<runOnIncremental>true</runOnIncremental>
</execute>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>roster3</finalName>
</build>
</project>
Following is what I tried as of now.
Configuration class Config.java
package com.ecw.roster.config;
import java.util.Properties;
import org.eclipse.persistence.platform.database.DatabasePlatform;
import org.eclipse.persistence.platform.database.MySQLPlatform;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
#Configuration //Marks this class as configuration
#EnableWebMvc
//Specifies which package to scan
#ComponentScan("com.ecw.roster")
#PropertySource(value = "classpath:application.properties")
//Enable Spring's annotations
#EnableTransactionManagement
public class Config extends WebMvcConfigurerAdapter{
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
private static final String PROPERTY_NAME_DATABASEPLATFORM = "databasePlatform";
private static final String PROPERTY_NAME_GENERATE_DDL = "generateDdl";
private static final String PROPERTY_NAME_SHOW_SQL = "showSql";
#Value("${jdbc.driverClassName}")
private String driverClassName;
#Value("${jdbc.url}")
private String url;
#Value("${jdbc.username}")
private String username;
#Value("${jdbc.password}")
private String password;
#Value("${hibernate.dialect}")
private String hibernate_dialect;
#Value("${hibernate.show_sql}")
private String hibernate_show_sql;
#Value("${entitymanager.packages.to.scan}")
private String entity_package_to_scan;
#Bean
public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
System.out.println("Roster 3 : Initializing UrlBasedViewResolver........");
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Bean
public PlatformTransactionManager transactionManager(){
System.out.println("Roster 3 : LocalContainerEntityManagerFactoryBean *************");
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPackagesToScan(new String[] { "com.ecw.roster.beans" });
em.setPersistenceUnitName("roster3");
DatabasePlatform dp = new MySQLPlatform();
em.setJpaVendorAdapter(getEclipseLinkJpaVendorAdapter());
return em;
}
private EclipseLinkJpaVendorAdapter getEclipseLinkJpaVendorAdapter(){
System.out.println("Roster 3 : EclipseLinkJpaVendorAdapter initialization ***************");
EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter();
vendorAdapter.setDatabasePlatform("org.eclipse.persistence.platform.database.MySQLPlatform");
vendorAdapter.setGenerateDdl(false);
vendorAdapter.setShowSql(true);
return vendorAdapter;
}
private Properties eclipseLinkProperty(){
Properties properties = new Properties();
properties.put("eclipselink.deploy-on-startup", "true");
properties.put("eclipselink.ddl-generation", "create-or-extend-tables");
properties.put("eclipselink.ddl-generation.output-mode", "database");
properties.put("eclipselink.weaving", "static");
properties.put("eclipselink.weaving.lazy", "true");
properties.put("eclipselink.weaving.internal", "true");
properties.put("eclipselink.logging.level", "SEVERE");
properties.put("eclipselink.query-results-cache.type", "WEAK");
properties.put("eclipselink.jdbc.batch-writing", "JDBC");
properties.put("eclipselink.jdbc.batch-writing.size", "1000");
return properties;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println("In Resouce Handler");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/defaultTheme/");
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("/WEB-INF/messages/messages/");
return messageSource;
}
}
persistence.xml file for eclipselink:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="roster3" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.ecw.roster.beans.Roster</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/roster" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="mysqladmin" />
</properties>
</persistence-unit>
</persistence>
I am able to build & deploy the project but I am getting connection leaks & then my context is stopped by tomcat container.
Please advice me what I am doing wrong with it.
Thanks
The following configuration will enable Spring to use two application contexts (the root context and the web application context) and will configure most of the things you need.
#Configuration
#EnableTransactionManagement
#EnableMBeanExport
#EnableJpaRepositories("your.jpa.repositories.package")
#ComponentScan(basePackages = "gr.xe.payments", excludeFilters = {#ComponentScan.Filter(value = Controller.class), #ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE ,value = MvcConfig.class)})
public class ApplicationConfig {
}
#EnableWebMvc
#ComponentScan(basePackages = "your.controller.package", includeFilters = #ComponentScan.Filter(value = Controller.class))
public class MvcConfig extends WebMvcConfigurerAdapter {
#Bean
public TilesConfigurer tilesViewResolver() {
TilesConfigurer tilesViewResolver = new TilesConfigurer();
tilesViewResolver.setDefinitions(new String[]{"/WEB-INF/tiles.xml"});
return tilesViewResolver;
}
#Bean
public UrlBasedViewResolver urlBasedViewResolver() {
UrlBasedViewResolver urlBasedViewResolver = new UrlBasedViewResolver();
urlBasedViewResolver.setViewClass(TilesView.class);
return urlBasedViewResolver;
}
#Bean(name = "messageSource")
public ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource() {
ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource();
reloadableResourceBundleMessageSource.setBasename("WEB-INF/i18n/messages");
reloadableResourceBundleMessageSource.setFallbackToSystemLocale(false);
reloadableResourceBundleMessageSource.setDefaultEncoding("UTF-8");
return reloadableResourceBundleMessageSource;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
#Configuration
public class DatabaseConfig {
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(false);
LocalContainerEntityManagerFactoryBean factory =
new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("your.domain.package");
factory.setDataSource(dataSource());
factory.setJpaProperties(jpaProperties());
return factory;
}
#Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory().getObject());
return txManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public DataSource dataSource() {
//This uses JNDI, you could create the data source in any way you want
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
return (DataSource) envCtx.lookup("jdbc/yourDS");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Unable to lookup datasource", e);
}
}
private Properties jpaProperties() {
Properties properties = new Properties();
//use whatever EclipseLink properties you like
return properties;
}
}
EDIT:
The relevant dependencies are
<properties>
<spring.version>3.2.8.RELEASE</spring.version>
<spring-security.version>3.1.3.RELEASE</spring-security.version>
</properties>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.2.0.RELEASE</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
<exclusion>
<artifactId>jcl-over-slf4j</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.1</version>
</dependency>
Related
I'm trying to use junit to test a Spigot plugin, but I get the following error:
java.lang.NoSuchMethodError: org.yaml.snakeyaml.LoaderOptions.setMaxAliasesForCollections(I)V
at org.bukkit.configuration.file.YamlConfiguration.loadFromString(YamlConfiguration.java:56)
at org.bukkit.configuration.file.FileConfiguration.load(FileConfiguration.java:160)
at org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(YamlConfiguration.java:217)
at tests.MessengerTests.conf(MessengerTests.java:24)
at tests.MessengerTests.msr(MessengerTests.java:19)
at tests.MessengerTests.testBasic(MessengerTests.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
I've tried searching for this error on DuckDuckGo, but haven't found a solution. I've tried updating spigot-api to 1.16.5, but get the same error. Is this a bug with Spigot, or could it be solved another way? I don't know what else to try here.
MessengerTests.java
package tests;
import me.rubyjay.bukkit.core.api.messenger.Messenger;
import me.rubyjay.bukkit.core.api.zconfig.ZConfigFile;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.StringReader;
public class MessengerTests {
private static Messenger msr(ZConfigFile conf) {
return new Messenger(new TestModule(), conf);
}
private static Messenger msr(String contents) {
return msr(conf(contents));
}
private static ZConfigFile conf(String contents) {
StringReader reader = new StringReader(contents);
YamlConfiguration conf = YamlConfiguration.loadConfiguration(reader);
return ZConfigFile.wrap(new File("test.yml"), conf);
}
#Test
public void testBasic() {
Messenger msr = msr("hello: '&9Hello&7, &2World&d!!'").cfg("hello");
Assert.assertEquals("§9Hello§7, §2World§d!!", msr.outString());
}
#Test
public void testLink() {
Messenger msr = msr("test: 'If you like cheese, [click here](https://duckduckgo.com/?q=cheese), but not here.'").cfg("test");
Assert.assertEquals("§9Hello§7, §2World§d!!", msr.outComponent());
}
// #Test
// public void testData() {
// Messenger msr = msr("hello: '&9Hello&7, &2World&d!! '");
// Assert.assertEquals("§9Hello§7, §2World§d!!", msr.getString());
// }
//
// #Test
// public void testList() {
// Messenger msr = msr("{\"cmd\":{\"list\":{\"head\":\"&9--- Header ---\",\"item\":\"&b - <item>\",\"foot\":\"&9--------------\"}}}");
// Assert.assertEquals("§9Hello§7, §2World§d!!", msr.getString());
// }
#Test
public void testMissingConfigPathAbsolute() {
Messenger msr = msr("").cfg("this.message.does.not.exist");
Assert.assertEquals("§cMissing config message: this.message.does.not.exist", msr.outString());
}
#Test
public void testMissingConfigPathRelative() {
Messenger msr = msr("{\"this\":{\"message\":{\"exists\":\"but we're not using it.\"}}}")
.path("this.message").cfg(".does.not.exist");
Assert.assertEquals("§cMissing config message: this.message.does.not.exist", msr.outString());
}
}
ZConfigFile.java
package me.rubyjay.bukkit.core.api.zconfig;
import org.bukkit.configuration.file.FileConfiguration;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Ruby jay
*/
public class ZConfigFile extends ZConfigWrapper {
private final File file;
private ZConfigFile(File file, FileConfiguration config) {
super(config);
this.file = file;
}
#Override
public FileConfiguration unwrap() {
return (FileConfiguration)super.unwrap();
}
public static ZConfigFile wrap(File file, FileConfiguration config) {
if (file == null || config == null) {
return null;
} else {
return new ZConfigFile(file, config);
}
}
/**
* #return the file
*/
public File getFile() {
return file;
}
public boolean save() {
try {
unwrap().save(file);
return true;
} catch (IOException ex) {
Logger.getLogger(ZConfigFile.class.getName()).log(Level.SEVERE, "Failed to save zconfig " + file.getName(), ex);
return false;
}
}
public boolean backup() {
String name = file.getName();
try {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd.HH-mm-ss");
name += "." + dateFormat.format(date) + ".old";
unwrap().save(new File(file.getParentFile(), name));
return true;
} catch (IOException ex) {
Logger.getLogger(ZConfigFile.class.getName()).log(Level.SEVERE, "Failed to backup zconfig " + name, ex);
return false;
}
}
}
ZConfigWrapper.java
package me.rubyjay.bukkit.core.api.zconfig;
import org.bukkit.Color;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationOptions;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* #inheritDoc
*
* #author Ruby jay
*/
public class ZConfigWrapper implements ZConfig {
private final ConfigurationSection config;
private String rootPath;
protected ZConfigWrapper(ConfigurationSection config) {
this.config = config;
}
public ConfigurationSection unwrap() {
return config;
}
public static ZConfig newEmpty() {
return new ZConfigWrapper(new MemoryConfiguration());
}
#Contract("null -> null")
public static ZConfig wrap(ConfigurationSection conf) {
if (conf == null) {
return null;
} else if (conf instanceof ZConfig) {
return (ZConfig) conf;
} else {
return new ZConfigWrapper(conf);
}
}
// (Redacted) Implemented methods
// Example:
#NotNull
#Override
public Set<String> getKeys(boolean deep) {
return config.getKeys(deep);
}
// End Example
#NotNull
#Override
public ZConfig getRoot() {
return ZConfigWrapper.wrap(Objects.requireNonNull(config.getRoot()));
}
#Override
public String toString() {
return getValues().toString();
}
}
Zonfig is an interface that extends org.bukkit.configuration.Configuration and adds a lot of custom methods.
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>me.rubyjay.bukkit</groupId>
<artifactId>ruby-core</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>RubyCore</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<minecraft.version>1.16.5</minecraft.version>
<minecraft_version>1_16_R1</minecraft_version>
<spigot.version>1.16.5-R0.1-SNAPSHOT</spigot.version>
</properties>
<repositories>
<repository>
<id>spigotmc-repo</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>vault-repo</id>
<url>http://nexus.hc.to/content/repositories/pub_releases</url>
</repository>
<repository>
<id>sk89q-repo</id>
<url>http://maven.sk89q.com/repo/</url>
</repository>
<repository>
<id>dmulloy2-repo</id>
<url>http://repo.dmulloy2.net/nexus/repository/public/</url>
</repository>
<repository>
<id>placeholderapi</id>
<url>http://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
<repository>
<id>codemc-repo</id>
<url>https://repo.codemc.org/repository/maven-public/</url>
<layout>default</layout>
</repository>
<repository>
<id>skullcreator-repo</id>
<url>https://dl.bintray.com/deanveloper/SkullCreator</url>
</repository>
</repositories>
<dependencies>
<!--<editor-fold desc="org.jetbrains:annotations">-->
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>LATEST</version>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="junit">-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="ninja.leaping.configurate">-->
<dependency>
<groupId>ninja.leaping.configurate</groupId>
<artifactId>configurate-gson</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>ninja.leaping.configurate</groupId>
<artifactId>configurate-hocon</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>ninja.leaping.configurate</groupId>
<artifactId>configurate-yaml</artifactId>
<version>3.3</version>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="net.sourceforge.htmlunit">-->
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.30</version>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="org.spigotmc">-->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>${spigot.version}</version>
<scope>provided</scope>
</dependency>
<!--<dependency>-->
<!--<groupId>org.spigotmc</groupId>-->
<!--<artifactId>minecraft-server</artifactId>-->
<!--<version>${minecraft.version}-SNAPSHOT</version>-->
<!--<type>jar</type>-->
<!--<scope>provided</scope>-->
<!--</dependency>-->
<!--</editor-fold>-->
<!--<editor-fold desc="net.milkbowl.vault">-->
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>LATEST</version>
<scope>provided</scope>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="me.clip:placeholderapi">-->
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.8.2</version>
<scope>provided</scope>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="de.tr7zw:item-nbt-api">-->
<dependency>
<groupId>de.tr7zw</groupId>
<artifactId>item-nbt-api</artifactId>
<version>LATEST</version>
<scope>compile</scope>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="com.deanveloper:skullcreator">-->
<dependency>
<groupId>dev.dbassett</groupId>
<artifactId>skullcreator</artifactId>
<version>3.0.0</version>
<scope>compile</scope>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="com.sk89q:worldedit">-->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!--</editor-fold>-->
<!--<editor-fold desc="com.sk89q.worldguard">-->
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-core</artifactId>
<version>7.0.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-legacy</artifactId>
<version>7.0.0-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>com.sk89q</groupId>
<artifactId>commandbook</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--</editor-fold>-->
</dependencies>
<!--<editor-fold defaultstate="collapsed" desc="build">-->
<build>
<defaultGoal>clean package</defaultGoal>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test</testSourceDirectory>
<finalName>${project.name}</finalName>
<plugins>
<plugin>
<version>3.6.1</version>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<minimizeJar>true</minimizeJar>
</configuration>
</execution>
</executions>
<configuration>
<relocations>
<relocation>
<pattern>de.tr7zw.changeme.nbtapi</pattern>
<shadedPattern>de.tr7zw.nbtapi.rubycore</shadedPattern>
</relocation>
</relocations>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<executions>
<execution>
<id>copy-resources</id>
<!-- here the phase you need -->
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>libraries/</outputDirectory>
<resources>
<resource>
<!-- Get main artifact -->
<directory>target</directory>
<!-- Don't filter binary files -->
<filtering>false</filtering>
<includes>
<include>${project.build.finalName}.jar</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<groupId>org.codehaus.mojo</groupId>
<executions>
<execution>
<id>Distribution script</id>
<phase>install</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>bash</executable>
<commandlineArgs>/home/ruby/AppData/minecraft/server/bin/mcdist</commandlineArgs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<!--</editor-fold>-->
</project>
So I've had this happen before on my IDE, mostly when I was editing the main projects API. And then going into the second project, not syncing the maven repo between it, and then compiling it, since I added/changed a class file in the API, the class "technically" doesn't exist, because it's now using different methods. This might not be helpful, cause I had to both sync and restart my IDE multiple times to fix the issue. But I got it working after a while.
This is my first question on Stack, so I apologize if it's not formatted correctly.
I have an application that sends out an email using an HTML template when a shipment has changed status. The sending mechanism is working as it should, and it is finding my template just fine. The problem is that the email that is sent is just my HTML in plain text and not rendered at all. So instead of a nicely rendered HTML page, the body of the email is just code.
I think the problem lies somewhere in the config file. I have another app that is using an older version of Thymeleaf and works exactly as it should, but unfortunately the setup for that is outdated and no longer works. Also, I have attempted a few different config options, as shown in the commented out portion of my code.
I have checked every line of the HTML template to make sure there are no unclosed tags or symbols that would escape the HTML. All data is being pulled over from the controller into the template, and I have checked to make sure the template is displayed properly in a browser. It's just when it puts everything together and sends the email that it fails to work and doesn't render.
I have included my pom file, a relevant portion from the app.config, and the app.config itself. Again, this is my first question on here, so if I'm missing something I'd be happy to add it, and if the question is formatted wrong I apologize and am open to critique on how to do it correctly.
Thank you.
The app is using Spring Boot 2.1.1, Spring 5, and Thymeleaf 3.0.11. I have also tried using Spring 4, as well as downgraded versions of Thymeleaf.
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.api</groupId>
<artifactId>tms-scheduled-tasks</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>tms-scheduled-tasks</name>
<description>TMS Scheduled Tasks</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
</plugins>
</build>
</project>
From application.properties
# Thymeleaf
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false
AppConfig
package com.api.tmsscheduledtasks.config;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import
org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import
org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("com.api")
public class AppConfig implements WebMvcConfigurer {
private ApplicationContext applicationContext;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/WEB-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
/**
* According to some resource I can no longer remember
*/
#Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("classpath:/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
return templateResolver;
}
#Bean
SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
#Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
return viewResolver;
}
/**
* According to Baeldung
*/
// #Bean
// public ViewResolver htmlViewResolver() {
// ThymeleafViewResolver resolver = new ThymeleafViewResolver();
// resolver.setTemplateEngine(templateEngine((templateResolver())));
// resolver.setContentType("text/html");
// resolver.setCharacterEncoding("UTF-8");
// resolver.setViewNames(ArrayUtil.array("*.html"));
//
// return resolver;
// }
//
// private ISpringTemplateEngine templateEngine(ITemplateResolver
templateResolver) {
// SpringTemplateEngine engine = new SpringTemplateEngine();
// engine.setTemplateResolver(templateResolver);
// return engine;
// }
//
// private ITemplateResolver templateResolver() {
// SpringResourceTemplateResolver templateResolver = new
SpringResourceTemplateResolver();
// templateResolver.setApplicationContext(applicationContext);
// templateResolver.setPrefix("classpath:/templates/");
// templateResolver.setSuffix(".html");
// templateResolver.setCacheable(false);
// templateResolver.setTemplateMode(TemplateMode.HTML);
//
// return templateResolver;
// }
/**
* According to thymeleaf.org
*/
// public void setApplicationContext(ApplicationContext
applicationContext) {
// this.applicationContext = applicationContext;
// }
//
// #Bean
// public ViewResolver viewResolver() {
// ThymeleafViewResolver resolver = new ThymeleafViewResolver();
// resolver.setTemplateEngine(templateEngine());
// resolver.setCharacterEncoding("UTF-8");
// return resolver;
// }
//
// #Bean
// public TemplateEngine templateEngine() {
// SpringTemplateEngine engine = new SpringTemplateEngine();
// engine.setEnableSpringELCompiler(true);
// engine.setTemplateResolver(templateResolver());
// return engine;
// }
//
// private ITemplateResolver templateResolver() {
// SpringResourceTemplateResolver resolver = new
SpringResourceTemplateResolver();
// resolver.setApplicationContext(applicationContext);
// resolver.setPrefix("/WEB-INF/templates/");
// resolver.setTemplateMode(TemplateMode.HTML);
// return resolver;
// }
/**
* Old setup from other app
*/
// #Bean
// public TemplateResolver templateResolver() {
// TemplateResolver templateResolver = new
ClassLoaderTemplateResolver();
// templateResolver.setSuffix(".html");
// templateResolver.setTemplateMode("HTML");
//
// return templateResolver;
// }
EDIT
After talking to a colleague at work he discovered the issue. It turns out I overlooked the Email class where everything was being built. It was a fairly silly mistake on my part, but I'll post the original code below and then the answer.
import org.springframework.mail.SimpleMailMessage;
public class Email {
private SimpleMailMessage message;
public Email setFrom(String from) {
getMessage().setFrom(from);
return this;
}
public Email setTo(String to) {
getMessage().setTo(to);
return this;
}
public Email setSubject(String subject) {
getMessage().setSubject(subject);
return this;
}
public Email setText(String text) {
getMessage().setText(text);
return this;
}
public SimpleMailMessage build() {
return getMessage();
}
protected SimpleMailMessage getMessage() {
if (message == null) {
message = new SimpleMailMessage();
}
return this.message;
}
}
Again. The solution was very simple, but I it was something I had overlooked in the Email class, I should have removed the SimpleMailMessage and replaced it with a MimeMessagePreparator. Nothing was wrong at all in the config or any of that. Just me overlooking an old method from when it was set up and forgetting to change it. Here is the change that was made.
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
public class Email {
private String from;
private String to;
private String subject;
private String text;
public Email setFrom(String from) {
this.from = from;
return this;
}
public Email setTo(String to) {
this.to = to;
return this;
}
public Email setSubject(String subject) {
this.subject = subject;
return this;
}
public Email setText(String text) {
this.text = text;
return this;
}
public MimeMessagePreparator build() {
return mimeMessage -> {
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
messageHelper.setFrom(from);
messageHelper.setTo(to);
messageHelper.setSubject(subject);
messageHelper.setText(text, true);
};
}
}
My question is related with a "Cycle detected while trying to load class" error when starting a jpa-only bundle.
I have created a JPA bundle with maven archetype, and modify its pom.xml to be used with Karaf (4.0.1), Aries Blueprint, MySQL, OpenJPA, OpenJDK 1.8. Entity classes where generated by using eclipse-tooling added to persistence.xml as well.
I'm able to compile it and install it on Karaf without errors. I got errors when starting the bundle. This classes run well at Karaf 2.x (Geronimo App Server).
I suspect it could be related with #OneToMany/#ManyToOne annotated fields in classes, because if I generate just one class with no joins, bundle started perfectly. I tried pax-jdbc-mysql way as well (not using blueprint) but with same results besides dataSource where created successfully. My classes just have jpa annotations.
The bundle structure is the following:
bse.jpa\
- src/main/java/mycustom-path/entities
- src/main/resources/META-INF
MANIFEST.MF
persistence.xml
- src/main/resources/OSGI-INF/blueprint
datasource.xml
Class definition example:
#Entity
#Table(name="business_entities")
#NamedQuery(name="BusinessEntity.findAll", query="SELECT b FROM BusinessEntity b")
public class BusinessEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(unique=true, nullable=false)
private Integer identity;
#Column(length=1000)
private String address;
#Column(length=150)
private String city;
#Column(length=1000)
private String comments;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="date_created")
private Date dateCreated;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="date_updated")
private Date dateUpdated;
#Column(length=200)
private String description;
#Column(length=75)
private String email;
#Column(length=45)
private String fax;
private Integer idcompany;
private Integer idcountry;
private Integer iduser;
#Column(name="iduser_updated")
private Integer iduserUpdated;
#Column(length=200)
private String name;
#Column(length=45)
private String phone;
#Column(length=45)
private String postalcode;
#Column(name="tax_id", length=20)
private String taxId;
#Column(length=500)
private String website;
//bi-directional many-to-one association to BusinessEntityContact
#OneToMany(mappedBy="businessEntity")
private List<BusinessEntityContact> businessEntityContacts;
//bi-directional many-to-one association to CustomerExtInfo
#OneToMany(mappedBy="businessEntity")
private List<CustomerExtInfo> customerExtInfos;
//bi-directional many-to-many association to EntityCategory
#ManyToMany(mappedBy="businessEntities")
private List<EntityCategory> entityCategories;
//bi-directional many-to-one association to EntityAccount
#OneToMany(mappedBy="businessEntity")
private List<EntityAccount> entityAccounts;
//bi-directional many-to-one association to ProviderExtInfo
#OneToMany(mappedBy="businessEntity")
private List<ProviderExtInfo> providerExtInfos;
public BusinessEntity() {
}
public Integer getIdentity() {
return this.identity;
}
public void setIdentity(Integer identity) {
this.identity = identity;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getComments() {
return this.comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getDateUpdated() {
return this.dateUpdated;
}
public void setDateUpdated(Date dateUpdated) {
this.dateUpdated = dateUpdated;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFax() {
return this.fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public Integer getIdcompany() {
return this.idcompany;
}
public void setIdcompany(Integer idcompany) {
this.idcompany = idcompany;
}
public Integer getIdcountry() {
return this.idcountry;
}
public void setIdcountry(Integer idcountry) {
this.idcountry = idcountry;
}
public Integer getIduser() {
return this.iduser;
}
public void setIduser(Integer iduser) {
this.iduser = iduser;
}
public Integer getIduserUpdated() {
return this.iduserUpdated;
}
public void setIduserUpdated(Integer iduserUpdated) {
this.iduserUpdated = iduserUpdated;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPostalcode() {
return this.postalcode;
}
public void setPostalcode(String postalcode) {
this.postalcode = postalcode;
}
public String getTaxId() {
return this.taxId;
}
public void setTaxId(String taxId) {
this.taxId = taxId;
}
public String getWebsite() {
return this.website;
}
public void setWebsite(String website) {
this.website = website;
}
public List<BusinessEntityContact> getBusinessEntityContacts() {
return this.businessEntityContacts;
}
public void setBusinessEntityContacts(List<BusinessEntityContact> businessEntityContacts) {
this.businessEntityContacts = businessEntityContacts;
}
public BusinessEntityContact addBusinessEntityContact(BusinessEntityContact businessEntityContact) {
getBusinessEntityContacts().add(businessEntityContact);
businessEntityContact.setBusinessEntity(this);
return businessEntityContact;
}
public BusinessEntityContact removeBusinessEntityContact(BusinessEntityContact businessEntityContact) {
getBusinessEntityContacts().remove(businessEntityContact);
businessEntityContact.setBusinessEntity(null);
return businessEntityContact;
}
public List<CustomerExtInfo> getCustomerExtInfos() {
return this.customerExtInfos;
}
public void setCustomerExtInfos(List<CustomerExtInfo> customerExtInfos) {
this.customerExtInfos = customerExtInfos;
}
public CustomerExtInfo addCustomerExtInfo(CustomerExtInfo customerExtInfo) {
getCustomerExtInfos().add(customerExtInfo);
customerExtInfo.setBusinessEntity(this);
return customerExtInfo;
}
public CustomerExtInfo removeCustomerExtInfo(CustomerExtInfo customerExtInfo) {
getCustomerExtInfos().remove(customerExtInfo);
customerExtInfo.setBusinessEntity(null);
return customerExtInfo;
}
public List<EntityCategory> getEntityCategories() {
return this.entityCategories;
}
public void setEntityCategories(List<EntityCategory> entityCategories) {
this.entityCategories = entityCategories;
}
public List<EntityAccount> getEntityAccounts() {
return this.entityAccounts;
}
public void setEntityAccounts(List<EntityAccount> entityAccounts) {
this.entityAccounts = entityAccounts;
}
public EntityAccount addEntityAccount(EntityAccount entityAccount) {
getEntityAccounts().add(entityAccount);
entityAccount.setBusinessEntity(this);
return entityAccount;
}
public EntityAccount removeEntityAccount(EntityAccount entityAccount) {
getEntityAccounts().remove(entityAccount);
entityAccount.setBusinessEntity(null);
return entityAccount;
}
public List<ProviderExtInfo> getProviderExtInfos() {
return this.providerExtInfos;
}
public void setProviderExtInfos(List<ProviderExtInfo> providerExtInfos) {
this.providerExtInfos = providerExtInfos;
}
public ProviderExtInfo addProviderExtInfo(ProviderExtInfo providerExtInfo) {
getProviderExtInfos().add(providerExtInfo);
providerExtInfo.setBusinessEntity(this);
return providerExtInfo;
}
public ProviderExtInfo removeProviderExtInfo(ProviderExtInfo providerExtInfo) {
getProviderExtInfos().remove(providerExtInfo);
providerExtInfo.setBusinessEntity(null);
return providerExtInfo;
}
}
The error I got is:
2017-12-08 07:30:22,514 | ERROR | lixDispatchQueue | container | 108 - org.apache.aries.jpa.container - 2.6.1 | FrameworkEvent ERROR - org.apache.aries.jpa.container
org.osgi.framework.hooks.weaving.WeavingException: Weaving failure on class cbn.bse.jpa.persistence.entities.EntityAccount in bundle bse.jpa/1.0.0.SNAPSHOT using transformer org.apache.openjpa.persistence.PersistenceProviderImpl$ClassTransformerImpl#4d3cfedd
at org.apache.aries.jpa.container.weaving.impl.JPAWeavingHook.transformClass(JPAWeavingHook.java:101)[108:org.apache.aries.jpa.container:2.6.1]
at org.apache.aries.jpa.container.weaving.impl.JPAWeavingHook.weave(JPAWeavingHook.java:65)[108:org.apache.aries.jpa.container:2.6.1]
at org.apache.felix.framework.util.SecureAction.invokeWeavingHook(SecureAction.java:1203)[org.apache.felix.framework-5.6.4.jar:]
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.transformClass(BundleWiringImpl.java:2370)[org.apache.felix.framework-5.6.4.jar:]
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.findClass(BundleWiringImpl.java:2057)[org.apache.felix.framework-5.6.4.jar:]
at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1518)[org.apache.felix.framework-5.6.4.jar:]
at org.apache.felix.framework.BundleWiringImpl.access$200(BundleWiringImpl.java:79)[org.apache.felix.framework-5.6.4.jar:]
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1958)[org.apache.felix.framework-5.6.4.jar:]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)[:1.8.0_151]
at java.lang.Class.forName0(Native Method)[:1.8.0_151]
at java.lang.Class.forName(Class.java:348)[:1.8.0_151]
at org.apache.openjpa.meta.MetaDataRepository.classForName(MetaDataRepository.java:1559)[165:org.apache.openjpa:2.4.1]
at org.apache.openjpa.meta.MetaDataRepository.loadPersistentTypesInternal(MetaDataRepository.java:1535)[165:org.apache.openjpa:2.4.1]
at org.apache.openjpa.meta.MetaDataRepository.loadPersistentTypes(MetaDataRepository.java:1513)[165:org.apache.openjpa:2.4.1]
at org.apache.openjpa.kernel.AbstractBrokerFactory.loadPersistentTypes(AbstractBrokerFactory.java:279)[165:org.apache.openjpa:2.4.1]
at org.apache.openjpa.kernel.AbstractBrokerFactory.initializeBroker(AbstractBrokerFactory.java:235)[165:org.apache.openjpa:2.4.1]
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:211)[165:org.apache.openjpa:2.4.1]
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:154)[165:org.apache.openjpa:2.4.1]
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)[165:org.apache.openjpa:2.4.1]
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:153)[165:org.apache.openjpa:2.4.1]
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.getProperties(EntityManagerFactoryImpl.java:108)[165:org.apache.openjpa:2.4.1]
at org.apache.aries.jpa.support.osgi.impl.EMFTracker.getTransactionType(EMFTracker.java:96)[109:org.apache.aries.jpa.support:2.6.1]
at org.apache.aries.jpa.support.osgi.impl.EMFTracker.addingService(EMFTracker.java:78)[109:org.apache.aries.jpa.support:2.6.1]
at org.osgi.util.tracker.ServiceTracker$Tracked.customizerAdding(ServiceTracker.java:941)[org.osgi.core-6.0.0.jar:]
at org.osgi.util.tracker.ServiceTracker$Tracked.customizerAdding(ServiceTracker.java:870)[org.osgi.core-6.0.0.jar:]
at org.osgi.util.tracker.AbstractTracked.trackAdding(AbstractTracked.java:256)[org.osgi.core-6.0.0.jar:]
at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:229)[org.osgi.core-6.0.0.jar:]
at org.osgi.util.tracker.ServiceTracker$Tracked.serviceChanged(ServiceTracker.java:901)[org.osgi.core-6.0.0.jar:]
at org.apache.felix.framework.EventDispatcher.invokeServiceListenerCallback(EventDispatcher.java:990)[org.apache.felix.framework-5.6.4.jar:]
at org.apache.felix.framework.EventDispatcher.fireEventImmediately(EventDispatcher.java:838)[org.apache.felix.framework-5.6.4.jar:]
at org.apache.felix.framework.EventDispatcher.fireServiceEvent(EventDispatcher.java:545)[org.apache.felix.framework-5.6.4.jar:]
at org.apache.felix.framework.Felix.fireServiceEvent(Felix.java:4579)[org.apache.felix.framework-5.6.4.jar:]
at org.apache.felix.framework.Felix.registerService(Felix.java:3571)[org.apache.felix.framework-5.6.4.jar:]
at org.apache.felix.framework.BundleContextImpl.registerService(BundleContextImpl.java:348)[org.apache.felix.framework-5.6.4.jar:]
at org.apache.felix.framework.BundleContextImpl.registerService(BundleContextImpl.java:355)[org.apache.felix.framework-5.6.4.jar:]
at org.apache.aries.jpa.container.impl.ManagedEMF.createAndPublishEMF(ManagedEMF.java:132)[108:org.apache.aries.jpa.container:2.6.1]
at org.apache.aries.jpa.container.impl.ManagedEMF.updated(ManagedEMF.java:125)[108:org.apache.aries.jpa.container:2.6.1]
at org.apache.felix.cm.impl.helper.ManagedServiceTracker.updated(ManagedServiceTracker.java:189)[3:org.apache.felix.configadmin:1.8.14]
at org.apache.felix.cm.impl.helper.ManagedServiceTracker.updateService(ManagedServiceTracker.java:152)[3:org.apache.felix.configadmin:1.8.14]
at org.apache.felix.cm.impl.helper.ManagedServiceTracker.provideConfiguration(ManagedServiceTracker.java:85)[3:org.apache.felix.configadmin:1.8.14]
at org.apache.felix.cm.impl.ConfigurationManager$ManagedServiceUpdate.provide(ConfigurationManager.java:1463)[3:org.apache.felix.configadmin:1.8.14]
at org.apache.felix.cm.impl.ConfigurationManager$ManagedServiceUpdate.run(ConfigurationManager.java:1419)[3:org.apache.felix.configadmin:1.8.14]
at org.apache.felix.cm.impl.UpdateThread.run0(UpdateThread.java:141)[3:org.apache.felix.configadmin:1.8.14]
at org.apache.felix.cm.impl.UpdateThread.run(UpdateThread.java:109)[3:org.apache.felix.configadmin:1.8.14]
at java.lang.Thread.run(Thread.java:748)[:1.8.0_151]
Caused by: <openjpa-2.4.1-r422266:1730418 nonfatal general error> org.apache.openjpa.util.GeneralException: cbn/bse/jpa/persistence/entities/EntityAccount
at org.apache.openjpa.enhance.PCClassFileTransformer.transform0(PCClassFileTransformer.java:172)
at org.apache.openjpa.enhance.PCClassFileTransformer.transform(PCClassFileTransformer.java:128)
at org.apache.openjpa.persistence.PersistenceProviderImpl$ClassTransformerImpl.transform(PersistenceProviderImpl.java:292)
at org.apache.aries.jpa.container.weaving.impl.JPAWeavingHook.transformClass(JPAWeavingHook.java:86)[108:org.apache.aries.jpa.container:2.6.1]
... 44 more
Caused by: java.lang.NoClassDefFoundError: cbn/bse/jpa/persistence/entities/EntityAccount
at java.lang.Class.getDeclaredMethods0(Native Method)[:1.8.0_151]
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)[:1.8.0_151]
at java.lang.Class.getDeclaredMethods(Class.java:1975)[:1.8.0_151]
at org.apache.openjpa.lib.util.J2DoPrivHelper$9.run(J2DoPrivHelper.java:334)
at org.apache.openjpa.lib.util.J2DoPrivHelper$9.run(J2DoPrivHelper.java:332)
at java.security.AccessController.doPrivileged(Native Method)[:1.8.0_151]
at org.apache.openjpa.persistence.PersistenceMetaDataDefaults.determineImplicitAccessType(PersistenceMetaDataDefaults.java:366)
at org.apache.openjpa.persistence.PersistenceMetaDataDefaults.determineAccessType(PersistenceMetaDataDefaults.java:332)
at org.apache.openjpa.persistence.PersistenceMetaDataDefaults.populate(PersistenceMetaDataDefaults.java:274)
at org.apache.openjpa.meta.MetaDataRepository.addMetaData(MetaDataRepository.java:921)
at org.apache.openjpa.meta.MetaDataRepository.addMetaData(MetaDataRepository.java:906)
at org.apache.openjpa.persistence.AnnotationPersistenceMetaDataParser.getMetaData(AnnotationPersistenceMetaDataParser.java:756)
at org.apache.openjpa.persistence.AnnotationPersistenceMetaDataParser.parseClassAnnotations(AnnotationPersistenceMetaDataParser.java:544)
at org.apache.openjpa.persistence.AnnotationPersistenceMetaDataParser.parse(AnnotationPersistenceMetaDataParser.java:414)
at org.apache.openjpa.persistence.PersistenceMetaDataFactory.load(PersistenceMetaDataFactory.java:259)
at org.apache.openjpa.meta.MetaDataRepository.getMetaDataInternal(MetaDataRepository.java:587)
at org.apache.openjpa.meta.MetaDataRepository.getMetaDataInternal(MetaDataRepository.java:397)
at org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:389)
at org.apache.openjpa.meta.ValueMetaDataImpl.resolveDeclaredType(ValueMetaDataImpl.java:487)
at org.apache.openjpa.meta.ValueMetaDataImpl.resolve(ValueMetaDataImpl.java:466)
at org.apache.openjpa.meta.FieldMetaData.resolve(FieldMetaData.java:1883)
at org.apache.openjpa.meta.ClassMetaData.resolveMeta(ClassMetaData.java:1874)
at org.apache.openjpa.meta.ClassMetaData.resolve(ClassMetaData.java:1808)
at org.apache.openjpa.meta.MetaDataRepository.processBuffer(MetaDataRepository.java:829)
at org.apache.openjpa.meta.MetaDataRepository.resolveMeta(MetaDataRepository.java:726)
at org.apache.openjpa.meta.MetaDataRepository.resolve(MetaDataRepository.java:650)
at org.apache.openjpa.meta.MetaDataRepository.getMetaDataInternal(MetaDataRepository.java:418)
at org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:389)
at org.apache.openjpa.enhance.PCEnhancer.<init>(PCEnhancer.java:286)
at org.apache.openjpa.enhance.PCEnhancer.<init>(PCEnhancer.java:257)
at org.apache.openjpa.enhance.PCClassFileTransformer.transform0(PCClassFileTransformer.java:151)
... 47 more
Caused by: java.lang.ClassNotFoundException: Cycle detected while trying to load class: cbn.bse.jpa.persistence.entities.EntityAccount
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1980)[org.apache.felix.framework-5.6.4.jar:]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)[:1.8.0_151]
... 78 more
the pom.xml, I'm using is:
<?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>
<parent>
<artifactId>bse.persistence</artifactId>
<groupId>bse.persistence</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<groupId>bse.jpa</groupId>
<artifactId>bse.jpa</artifactId>
<packaging>bundle</packaging>
<name>bse.jpa Bundle</name>
<description>bse.jpa OSGi bundle project.</description>
<properties>
<maven-bundle-plugin.version>3.3.0</maven-bundle-plugin.version>
<osgi.version>5.0.0</osgi.version>
</properties>
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>${osgi.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>osgi.cmpn</artifactId>
<version>${osgi.version}</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>osgi.enterprise</artifactId>
<version>${osgi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>2.4.1</version>
<type>bundle</type>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jpa_2.0_spec</artifactId>
<version>1.1</version>
<type>bundle</type>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>${maven-bundle-plugin.version}</version>
<extensions>true</extensions>
<configuration>
<archive>
<manifestEntries>
<Meta-Persistence>META-INF/persistence.xml</Meta-Persistence>
<Bundle-Blueprint>OSGI-INF/blueprint/*.xml</Bundle-Blueprint>
</manifestEntries>
</archive>
<manifestLocation>src/main/resources/META-INF</manifestLocation>
<rebuildBundle>true</rebuildBundle>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Version>${project.version}</Bundle-Version>
<Bundle-Activator>bse.jpa.Activator</Bundle-Activator>
<Import-Package>com.mysql.jdbc.jdbc2.optional,
javax.sql,
javax.persistence;version=2.0,
javax.persistence.metamodel,
javax.transaction,
javax.transaction.xa,
org.osgi.framework</Import-Package>
<Export-Package>cbn.bse.jpa.persistence.entities,
bse.jpa
</Export-Package>
<Meta-Persistence>META-INF/persistence.xml</Meta-Persistence>
<Bundle-ManifestVersion>2</Bundle-ManifestVersion>
<Include-Resource>src/main/resources</Include-Resource>
<Bundle-Blueprint>OSGI-INF/blueprint/*.xml</Bundle-Blueprint>
</instructions>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<maxmem>256M</maxmem>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<includes>cbn/bse/jpa/persistence/entities/**/*.class</includes>
</configuration>
<executions>
<execution>
<id>enhancer</id>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>2.4.1</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>assembly</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Blueprint file:
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<bean class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" id="sssDataSource" >
<property name="serverName" value="localhost"></property>
<property name="databaseName" value="rrrr"></property>
<property name="port" value="3306"></property>
<property name="user" value="yyyy"></property>
<property name="password" value="xxxxx"></property>
</bean>
<!-- javax.sql.DataSource -->
<service id="bseDSService" interface="javax.sql.DataSource" ref="sssDataSource">
<service-properties>
<entry key="osgi.jndi.service.name" value="jdbc/rrrr" />
</service-properties>
</service>
</blueprint>
Thanks in advance!!
I fond a solution for this, which is not a fix, but an alternative. I decided to go with EclipseLink 2.6.4 (using persistence 2.1), and with some little changes at pom.xml and persistence.xml I was able to start my bundle.
Considering I'm still using Karaf 4.1 (Apache Felix), and Aries (JPA and Blueprint), I believe the problem could be related with the libraries I'm not using anymore for this bundle: OpenJPA (most likely) or Geronimo JPA (JSR-317).
I'm sorry not having more time right now to find a fix with OpenJPA to this issue, but I'm hurry with this thing. I hope this solution helps someone else with the same problem.
Here is my current pom.xml (I added Jackson's library dependencies due I perform some JSON transformations in my services, which you may not need):
<?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>
<parent>
<artifactId>xxx.persistence</artifactId>
<groupId>bse.persistence</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<groupId>bse.jpa</groupId>
<artifactId>zzz.yyy</artifactId>
<packaging>bundle</packaging>
<name>bse.jpa Bundle</name>
<description>zzz.yyy OSGi bundle project.</description>
<properties>
<maven-bundle-plugin.version>3.3.0</maven-bundle-plugin.version>
<osgi.version>6.0.0</osgi.version>
</properties>
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>${osgi.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>osgi.cmpn</artifactId>
<version>${osgi.version}</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>osgi.enterprise</artifactId>
<version>${osgi.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.7</version>
<type>bundle</type>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.7</version>
<type>bundle</type>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.4</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.antlr</artifactId>
<version>2.6.4</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.asm</artifactId>
<version>2.6.4</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.jpql</artifactId>
<version>2.6.4</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.core</artifactId>
<version>2.6.4</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.6.4</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>
org.eclipse.persistence.jpa.modelgen.processor
</artifactId>
<version>2.6.4</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>${maven-bundle-plugin.version}</version>
<extensions>true</extensions>
<configuration>
<archive>
<manifestEntries>
<Meta-Persistence>META-INF/persistence.xml</Meta-Persistence>
<Bundle-Blueprint>OSGI-INF/blueprint/*.xml</Bundle-Blueprint>
</manifestEntries>
</archive>
<manifestLocation>src/main/resources/META-INF</manifestLocation>
<rebuildBundle>true</rebuildBundle>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Version>${project.version}</Bundle-Version>
<Bundle-Activator>bse.jpa.Activator</Bundle-Activator>
<Import-Package>com.mysql.jdbc.jdbc2.optional,
org.apache.felix.service.command,
org.apache.karaf.shell.commands,
org.apache.karaf.shell.console,
org.eclipse.persistence.internal.weaving,
org.eclipse.persistence.internal.descriptors,
org.eclipse.persistence.queries,
org.eclipse.persistence.descriptors.changetracking,
org.eclipse.persistence.internal.identitymaps,
org.eclipse.persistence.sessions,
org.eclipse.persistence.internal.jpa.rs.metadata.model,
org.eclipse.persistence.indirection,
javax.sql,
javax.persistence;version=2.0,
javax.persistence.metamodel,
javax.transaction,
javax.transaction.xa,
org.osgi.framework,
org.osgi.util.tracker,
*</Import-Package>
<Export-Package>cbn.bse.jpa.persistence.entities,
bse.jpa
</Export-Package>
<Meta-Persistence>META-INF/persistence.xml</Meta-Persistence>
<Bundle-ManifestVersion>2</Bundle-ManifestVersion>
<Include-Resource>src/main/resources</Include-Resource>
<Bundle-Blueprint>OSGI-INF/blueprint/*.xml</Bundle-Blueprint>
</instructions>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<maxmem>256M</maxmem>
</configuration>
</plugin>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<version>2.2.4</version>
<executions>
<execution>
<id>eclipselink-jpa-metamodel</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<processors>
<processor>org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor</processor>
</processors>
<compilerArguments>-Aeclipselink.persistencexml=${basedir}/src/test/resources/META-INF/persistence.xml</compilerArguments>
<outputDirectory>${project.build.directory}/generated-sources</outputDirectory>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor
</artifactId>
<version>2.6.4</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>assembly</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Persistence (you can change it to use JTA with pax-jdbc-mysql easily):
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="rrrr" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<non-jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/rrrr)</non-jta-data-source>
<class>Account</class>
<class>Warehouse</class>
<class>Widget</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.logging.level" value="WARNING"/>
<property name="eclipselink.logging.level.sql" value="WARNING"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="eclipselink.logging.timestamp" value="true"/>
<property name="eclipselink.logging.session" value="true"/>
<property name="eclipselink.logging.thread" value="true"/>
<property name="eclipselink.logging.exceptions" value="true"/>
<property name="eclipselink.session.include.descriptor.queries" value="true"/>
<property name="eclipselink.weaving" value="true"/>
</properties>
</persistence-unit>
</persistence>
Helpful references:
Luca Burgazzoli's Karaf examples (jpa)
Travis Steel's EclipseLink JPA Metamodel Generation in Eclipse with Maven
I have an issue with Spring JPA, Hibernate, MySQL.
I have an Entity (Nom.java) and repository (public interface NomRepository extends JpaRepository). They are created and injected just fine.
The issue is that when I'm trying to save a record via repository's save method spring complaines that "Table '' doesn't exist".
Indeed I do not see this table in MySQL. U've tried different values of hibernate.hbm2ddl.auto but it did not help.
I use XML-less configuration BTW.
Here's the config file:
package ru.interosite.awp.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
#Configuration
#ComponentScan("ru.interosite.awp")
#EnableAutoConfiguration
public class AppConfiguration {
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/awp");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setPersistenceUnitName("my_pu");
lef.setPackagesToScan("ru.interosite.awp.data");
lef.setDataSource(dataSource);
lef.setJpaVendorAdapter(jpaVendorAdapter);
lef.setJpaProperties(getJpaProperties());
return lef;
}
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabase(Database.MYSQL);
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect");
return jpaVendorAdapter;
}
private Properties getJpaProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto", "update");
setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
setProperty("hibernate.show_sql", "true");
setProperty("hibernate.format_sql", "true");
}
};
}
}
Here's how I start the app:
package ru.interosite.awp;
import java.awt.Font;
import javax.swing.UIManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import ru.interosite.awp.config.AppConfiguration;
import ru.interosite.awp.gui.UIUtils;
public class Boot {
private static final Logger LOGGER = LoggerFactory.getLogger(Boot.class);
public static void main( String[] args )
{
UIUtils.setUIFont(new javax.swing.plaf.FontUIResource(Font.SANS_SERIF, Font.PLAIN, 16));
try {
String lafClassName = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(lafClassName);
} catch (Exception e) {
LOGGER.debug(e.getMessage());
}
ApplicationContext ctx = SpringApplication.run(AppConfiguration.class, args);
((Runner)ctx.getBean("runner")).start();
}
}
This is my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.interosite</groupId>
<artifactId>AWP</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>AWP</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<start-class>ru.interosite.awp.Runner</start-class>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>0.5.0.M4</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>org.jboss.repository.releases</id>
<name>JBoss Maven Release Repository</name>
<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
you need to change two method and delete getProperties() method:
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(dataSource);
lef.setJpaVendorAdapter(jpaVendorAdapter);
lef.setPackagesToScan("com.spring.domain");
return lef;
}
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(true);
hibernateJpaVendorAdapter.setGenerateDdl(true); //Auto creating scheme when true
hibernateJpaVendorAdapter.setDatabase(Database.H2);//Database type
return hibernateJpaVendorAdapter;
}
the point is:
hibernateJpaVendorAdapter.setGenerateDdl(true);
In the latest version [spring boot].Include the below in application.properties
spring.jpa.generate-ddl=true
Ok, finally I have found how to fix it.
1) First, I moved AppConfiguration class to top-level package, ru.interosite.awp in my case
2) Second, I changed annotations to be:
#Configuration
#ComponentScan
#EnableJpaRepositories
public class AppConfiguration {...
Seems that #EnableAutoConfiguration annotation messed things up.
I dunno if it is a bug or feature. Looks like a bug of spring-boot actually.
I swapped to the M5 spring-boot-starter-xxx jars and now I'm seeing my tables get created
Here's my Application class (this is my first attempt at spring boot so...)
import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.H2;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(H2).build();
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(dataSource);
lef.setJpaVendorAdapter(jpaVendorAdapter);
lef.setPackagesToScan("org.home.wtw.domain");
return lef;
}
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(true);
hibernateJpaVendorAdapter.setGenerateDdl(true);
hibernateJpaVendorAdapter.setDatabase(Database.H2);
return hibernateJpaVendorAdapter;
}
#Bean
public PlatformTransactionManager transactionManager(
EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
If you want the tables to be created, you must set hibernate.hbm2ddl.auto property to create. Here are the possible values for hibernate.hbm2ddl.auto :
validate: validate the schema, makes no changes to the database.
update: update the schema.
create: creates the schema, destroying previous data.
create-drop: drop the schema at the end of the session.
Also, check that you are your database url is correct.
[Update]And don't forget to define a transaction manager for spring.
#Bean
public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor()
{
PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor = new PersistenceAnnotationBeanPostProcessor();
return persistenceAnnotationBeanPostProcessor;
}
Trying giving spring.jpa.hibernate.ddl-auto=create in application.properties file.
I am using:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
I am attempting to test a piece of code with the following call:
final KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, DEFAULT_PROVIDER);
The two constants are of type String, so I'm calling:
java.security.KeyPairGenerator.getInstance(String algorithm, String provider)
I've tried:
import static org.mockito.Mockito.when;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(KeyPairGenerator.class)
public class TestClass {
private static final String DEFAULT_PROVIDER = "BC";
private static final String KEY_PAIR_ALGORITHM = "RSA";
#Test
public void test() throws NoSuchAlgorithmException, NoSuchProviderException {
final KeyPairGenerator kpg = Mockito.mock(KeyPairGenerator.class);
PowerMockito.mockStatic(KeyPairGenerator.class);
when(KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, DEFAULT_PROVIDER)).thenReturn(kpg);
}
}
I've tried replacing when(KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, DEFAULT_PROVIDER)).thenReturn(kpg); with PowerMockito.doReturn(kpg).when(KeyPairGenerator.class); but neither seem to get me where I want as I'm still getting the NoSuchProviderException. Any insight would be appreciated.
You might want try changing your line #PrepareForTest statement.
From:
#PrepareForTest(KeyPairGenerator.class)
to:
#PrepareForTest(ClassThatCallsTheStaticMethod.class)