How to configure JaVers with OpenJPA in a Spring boot project - openjpa

I'm trying to set up auditing for my project which is currently a Spring boot with Open JPA. Require help/pointers on configuring Javers for Open JPA.
I have tried configuring the project with SpringBoot annotations provided by Javers. It gives me following error -
org.apache.openjpa.persistence.EntityManagerImpl cannot be cast to org.hibernate.Session
#Bean
#Transactional
public DialectName javersSqlDialectName() {
Session session = (Session)entityManager.getDelegate();//.getSession();
Dialect hibernateDialect=null;
try {
Object dialect =
org.apache.commons.beanutils.PropertyUtils.getProperty(session.getSessionFactory(), "dialect");
hibernateDialect = (Dialect) dialect;
}
catch(Exception ex) {
System.out.println("Serious error");
}
return dialectMapper.map(hibernateDialect);
}

Related

SpringBoot 2.2.6 JUnit dataSource lookup error

I'm working on a big project written with java8 and SringBoot 2.2.6. The project uses Envers and, the girl builds the architecture say to me that she doesn't manage to put in the application.properties the Envers configuration. Than she do as follows:
#Configuration
public class JPAConfig {
#Autowired
private DataSource dataSource;
#Bean(name="entityManagerFactory")
public LocalSessionFactoryBean sessionFactory() throws IOException {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setHibernateProperties(getHibernateProperties());
factoryBean.setDataSource(dataSource);
factoryBean.setPackagesToScan("it.xxxx.xxxxx.xxxxx.common.model");
return factoryBean;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", PostgreSQL82Dialect.class.getName());
properties.put("hibernate.default_schema", "test");
properties.put("hibernate.listeners.envers.autoRegister", true);
properties.put("org.hibernate.envers.revision_field_name", "rev");
properties.put("org.hibernate.envers.revision_type_field_name", "rev_type");
properties.put("org.hibernate.envers.audit_table_prefix", "aud_");
properties.put("org.hibernate.envers.store_data_at_delete", true);
properties.put("org.hibernate.envers.audit_table_suffix", "");
return properties;
}
}
Problem is that without dataSource class name I can't start my #SpringBootTest classes and I don't know how to add it in a scenario like this (without change the configuration I mean).
I also tries to add this row inside the application.properties:
spring.profiles.active=#spring.profile#
spring.datasource.driver-class-name=org.postgresql.Driver
#JPA
spring.datasource.jndi-name=jdbc/test
But doesn't work at all..
If I run the App with JUnit I obtain this error:
org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException: Failed to look up JNDI DataSource with name 'jdbc/test'; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
Can you help me??
Thanks a lot
You need to register your Datasource as JNDI resource in the spring-boot embedded tomcat.
You can add it as test scope configuration.
This answer shows how to register a JNDI resource: https://stackoverflow.com/a/26005740/5230585

How i config spring boot + elasticsearch and postgresql

i'm a newbie i want to config project spring boot with elasticsearch and postgresql.
i want to write the api if FE transmisson in the param isES = true, we call the function connect Elasticsearch else we call the function connect with postgresql.
please help me
thanks
`#Autowired
private SinhvienesRepo sinhvienesrepo;
#Autowired
private Search essearch;
#Autowired
private SinhvienRepo sinhvienrepo;
#GetMapping("/sinhvienes")
Iterable<Sinhvienes> Sinhvienes() {
return sinhvienesrepo.findAll();
}
#GetMapping("/sinhviens")
List<Sinhvien> Sinhvien() {
return sinhvienrepo.findAll();`

How to integrate a JAX-RS REST-Service with a JNDI lookup into SpringBoot?

I have a simple jax-rs REST-service that is deployed as a WAR on a wildfly server and uses a JNDI lookup for a datasource configured in the standalone.xml. For this the path is read from a datasource.properties file. The service then performas database actions through this datasource.
Now I want to use this REST-service in a SpringBoot application which is deployed to an embedded tomcat. My implementation uses RESTEasy and the service can easily be integrated with the resteasy-spring-boot-starter. But the JNDI lookup doesn't work, because of course the datasource is now not configured in a standalone.xml, but in the application.properties file. It is a completely different datasource.
I'm looking for a solution to set the datasource without having to "hard code" it. This is how the connection is retrieved currently in the WAR for the wildfly:
private Connection getConnection() {
Connection connection = null;
try (InputStream config = OutboxRestServiceJbossImpl.class.getClassLoader().getResourceAsStream("application.properties")) {
Properties properties = new Properties();
properties.load(config);
DataSource ds = (DataSource) new InitialContext().lookup(properties.getProperty("datasource"));
connection = ds.getConnection();
} catch (Exception e) {
}
return connection;
}
Currently I solved this by having a core module which actually performs the logic and 2 implementations with jax-rs for wildfly and SpringMVC in SpringBoot. They invoke the methods of an instance of the core module and the the connection is handed over to these methods. This looks like this for wildfly:
public String getHelloWorld() {
RestServiceCoreImpl rsc = new RestServiceCoreImpl();
try (Connection connection = getConnection()) {
String helloWorld = rsc.getHelloWorld(connection);
} catch (Exception e) {
}
return helloWorld;
}
public String getHelloWorld(Connection connection){
//database stuff, eg. connection.execute(SQL);
}
And like this in SpringBoot:
#Autowired
RestServiceCoreImpl rsc;
#Autowired
DataSource restServiceDataSource;
#Override
public String getHelloWorld() {
try (Connection connection = restServiceDataSource.getConnection()){
return rsc.getHelloWorld(connection);
} catch (SQLException e) {
}
return null;
}
Is there any way to solve this datasource issue? I need the SpringMVC solution to be replaced with the jax-rs solution within SpringBoot.
Okay, I was able to solve this myself. Here is my solution:
I enabled the naming in the embedded tomcat server as follows:
#Bean
public TomcatServletWebServerFactory tomcatFactory() {
return new TomcatServletWebServerFactory() {
#Override
protected TomcatWebServer getTomcatWebServer(org.apache.catalina.startup.Tomcat tomcat) {
tomcat.enableNaming();
return super.getTomcatWebServer(tomcat);
}
Then I was able to add the JNDI ressource in the server context. Now a JNDI lookup is possible.

how to give mongodb socketkeepalive in spring boot application?

In spring boot if we want to connect to mongodb, we can create a configuration file for mongodb or writing datasource in application.properties
I am following the second way
For me, I am gettint this error
"Timeout while receiving message; nested exception is com.mongodb.MongoSocketReadTimeoutException: Timeout while receiving message
.
spring.data.mongodb.uri = mongodb://mongodb0.example.com:27017/admin
I am gettint this error If I am not using my app for 6/7 hours and after that If I try to hit any controller to retrieve data from Mongodb. After 1/2 try I am able to get
Question - Is it the normal behavior of mongodb?
So, in my case it is closing the socket after some particular hours
I read some blogs where it was written you can give socket-keep-alive, so the connection pool will not close
In spring boot mongodb connection, we can pass options in uri like
spring.data.mongodb.uri = mongodb://mongodb0.example.com:27017/admin/?replicaSet=test&connectTimeoutMS=300000
So, I want to give socket-keep-alive options for spring.data.mongodb.uri like replicaset here.
I searched the official site, but can't able to find any
You can achieve this by providing a MongoClientOptions bean. Spring Data's MongoAutoConfiguration will pick this MongoClientOptions bean up and use it further on:
#Bean
public MongoClientOptions mongoClientOptions() {
return MongoClientOptions.builder()
.socketKeepAlive(true)
.build();
}
Also note that the socket-keep-alive option is deprecated (and defaulted to true) since mongo-driver version 3.5 (used by spring-data since version 2.0.0 of spring-data-mongodb)
You can achieve to pass this option using MongoClientOptionsFactoryBean.
public MongoClientOptions mongoClientOptions() {
try {
final MongoClientOptionsFactoryBean bean = new MongoClientOptionsFactoryBean();
bean.setSocketKeepAlive(true);
bean.afterPropertiesSet();
return bean.getObject();
} catch (final Exception e) {
throw new BeanCreationException(e.getMessage(), e);
}
}
Here an example of this configuration by extending AbstractMongoConfiguration:
#Configuration
public class DataportalApplicationConfig extends AbstractMongoConfiguration {
//#Value: inject property values into components
#Value("${spring.data.mongodb.uri}")
private String uri;
#Value("${spring.data.mongodb.database}")
private String database;
/**
* Configure the MongoClient with the uri
*
* #return MongoClient.class
*/
#Override
public MongoClient mongoClient() {
return new MongoClient(new MongoClientURI(uri,mongoClientOptions().builder()));
}

gwt-rpc + appengine + persistence using restlet throws exception

I was trying to rebuild the Restlet sample Application for GWT + GAE ( http://wiki.restlet.org/docs_2.1/13-restlet/21-restlet/318-restlet/303-restlet.html ) .
I changed it a bit, since I am planning something diffrent but I thought it would be a good start.
It was going okish until now. The "Put" was coming through to app engine but when i tried to persist the Objects using JPA i get the following Exception:
Caused by: org.datanucleus.exceptions.ClassNotResolvedException: Class "de.fr1zle.shoplist.web.gae.client.ShoppingListRessourceProxy" was not found in the CLASSPATH. Please check your specification and your CLASSPATH.
at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:250)
at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:415)
at org.datanucleus.metadata.MetaDataManager.loadPersistenceUnit(MetaDataManager.java:767)
... 79 more
As you can see, datanucleus somehow tries to access the GWT Proxy class when loading the info from the persistence.xml.
I use the following in my ServerRessource:
#Put
public void putShoppingList(ShoppingList shoppingList) {
ShoppingListDOA shoppingListDOA = new ShoppingListDOA(shoppingList);
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("transactions-optional");
try {
EntityManager entityManager = emf.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(shoppingListDOA);
entityManager.flush();
transaction.commit();
entityManager.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (emf != null)
emf.close();
}
}
I somehow have the feeling that DataNucleus enhances the Proxy Class, too although I changed the properites for it to not do so.
Using: GAE 1.4.2 (tried 1.4.3, too) , GWT 2.2 and Restlet 2.1m3
Am I missing a point here? Your help is appricated :-)
Thanks in advance!
fr1zle