NodeEntity attributes are NULL after transaction closed when using AspectJ - java

I've got a strange problem when using AspectJ, Neo4j NodeEntities and transactions.
I'm developing a spring application and using spring-data-neo4j with aspectj weaving. The problem is, that my fetched entities are empty outside of the transaction. Without AspectJ everything works as expected.
Here is a full test-case with maven:
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>org.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.4.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<neo4j.version>2.1.7</neo4j.version>
<spring-data-commons.version>1.10.0.RELEASE</spring-data-commons.version>
<spring-data-neo4j.version>3.3.0.RELEASE</spring-data-neo4j.version>
</properties>
<dependencies>
<!-- spring dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>${spring-data-commons.version}</version>
</dependency>
<!-- spring + neo4j dependencies -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
<version>${spring-data-neo4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-tx</artifactId>
<version>${spring-data-neo4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-aspects</artifactId>
<version>${spring-data-neo4j.version}</version>
</dependency>
<!-- for aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
<optional>true</optional>
<scope>provided</scope>
</dependency>
<!-- for testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-kernel</artifactId>
<version>${neo4j.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>aspects</id>
<build>
<plugins>
<!-- disable default compiler -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
</executions>
</plugin>
<!-- enable aspectj compiler -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.8.5</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<outxml>true</outxml>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
<aspectLibrary>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
<complianceLevel>${java.version}</complianceLevel>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<repositories>
<repository>
<id>spring-libs-milestone</id>
<name>Spring Milestone</name>
<url>https://repo.spring.io/libs-milestone</url>
</repository>
</repositories>
</project>
demo/DemoNode.java
package demo;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.Indexed;
import org.springframework.data.neo4j.annotation.NodeEntity;
#NodeEntity
public class DemoNode {
#GraphId
private Long id;
#Indexed(unique = true)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
demo/DemoRepository.java
package demo;
import org.springframework.data.neo4j.repository.GraphRepository;
public interface DemoRepository extends GraphRepository<DemoNode> {
public DemoNode findByName(String name);
}
demo/DemoApplicationTests.java
package demo;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import org.neo4j.test.TestGraphDatabaseFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.aspects.config.Neo4jAspectConfiguration;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.support.node.Neo4jHelper;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class DemoApplicationTests {
#Configuration
#ComponentScan("demo")
#EnableTransactionManagement
#EnableNeo4jRepositories(basePackages = "demo")
public static class DemoConfiguration extends Neo4jAspectConfiguration {
public DemoConfiguration() {
setBasePackage("demo");
}
#Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
return new TestGraphDatabaseFactory().newImpermanentDatabase();
}
}
#Autowired
private GraphDatabaseService graphDbService;
#Autowired
private DemoRepository demoRepo;
#Before
public void resetDb() {
Neo4jHelper.cleanDb(graphDbService);
}
// NOT successful
#Test
public void testNeo4jTransaction() {
DemoNode node;
final String name = "demo";
try (Transaction tx = graphDbService.beginTx()) {
node = new DemoNode();
node.setName(name);
node = demoRepo.save(node);
tx.success();
}
assertEquals(name, node.getName());
try (Transaction tx = graphDbService.beginTx()) {
node = demoRepo.findByName(name);
tx.success();
}
assertEquals(name, node.getName()); // expected:<demo> but was:<null>
}
// successful
#Test
public void testNeo4jWithGetTransaction() {
DemoNode node;
final String name = "demo";
try (Transaction tx = graphDbService.beginTx()) {
node = new DemoNode();
node.setName(name);
node = demoRepo.save(node);
tx.success();
}
assertEquals(name, node.getName());
try (Transaction tx = graphDbService.beginTx()) {
node = demoRepo.findByName(name);
tx.success();
}
try (Transaction tx = graphDbService.beginTx()) {
assertEquals(name, node.getName());
}
}
}
When you test this with mvn test everything is fine. But when using aspectj (mvn test -Paspects) it will fail:
DemoApplicationTests.testNeo4jNativeTransaction:64 expected:<demo> but was:<null>
What I found out when debugging this: Inside the transaction with AspectJ I could retrieve the name with the getter. BUT: All properties are always null. So my guess is: AspectJ weaving stores the values somewhere else and overrides the setter/getter for this. The new getter requires an active transaction, so outside of the transaction it will not work/will use the default getter that doesn't work with the null properties.
When I'm increasing the debug level I could see some message regarding this:
DEBUG o.s.d.n.f.DetachedEntityState - Outside of transaction, GET value from field class java.lang.String name rel: false idx: true
Am I doing something wrong? Do I need to create a clone and return this? Imho this would be an ugly way ...
Thanks in advance! I'm already searched and tried multiple hours but couldn't find any solution and any other problems here on stackoverflow or somewhere else in the internet. Maybe it's a bug ... maybe expected behaviour or maybe I'm doing some wrong ... I don't know.
UPDATE
I added a second test that works. It has a transaction around the getter. So when the getter is called in a transaction everything is fine. But I think this is a curious behaviour. Outside of the transaction the entity should be detached, but usable.

Related

Why when I access the controller route the html is not found nor does it return data to me with Postman?

I have thought that it could be a dependency problem and I have looked at the pom.xml and I consider that I have everything I need
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 https://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>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.home</groupId>
<artifactId>class</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>class</name>
<description>AquĆ­ estan las clases</description>
<properties>
<java.version>17</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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.0.1</version>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Then I thought that it could be a problem with the controller that is not returning data or redirecting correctly but I can't think of what it could be
My controller
#RestController
public class PruebaController {
#Autowired
private PersonaService personaService;
#GetMapping(value="/index",produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> index(){
return ResponseEntity.ok(this.personaService.findAll());
}
}
The problem is that when I do the command -> "spring-boot:run" and go to the link I get -> Error 404
I am also sure that the connection to the database is made perfectly so I only have to rule out that the service is done wrong but I don't know what it could be
PersonaService.java
public interface PersonaService {
Page<PersonaDTO> findAll();
PersonaDTO findByNSS(String NSS);
PersonaDTO findByNumTarjeta(String numTarjeta);
void save(PersonaDTO paciente);
void saveAll(List<PersonaDTO> pacientes);
void deleteById(Long id);
}
and this is my file
PersonaImpl.java
package Services.Implementation;
import DTO.PersonaDTO;
import Repository.PersonaRepository;
import Services.Interfaces.PersonaService;
import Utils.MHelpers;
import com.example.demo.Persona;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
#Component
public class PersonaImpl implements PersonaService {
#Autowired
private PersonaRepository PersonaRepository;
#Override
public Page<PersonaDTO> findAll() {
Page<Persona> personas = this.PersonaRepository.findAll();
return personas.map(this::convertToPersonaDTO);
}
#Override
public PersonaDTO findByNSS(String NSS) {
Optional<Persona> personas = this.PersonaRepository.findByNSS(NSS);
if (!personas.isPresent()){
return null;
}
return MHelpers.modelMapper().map(personas.get(),PersonaDTO.class);
}
#Override
public PersonaDTO findByNumTarjeta(String numTarjeta) {
Optional<Persona> personas = this.PersonaRepository.findByNumTarjeta(numTarjeta);
if (!personas.isPresent()){
return null;
}
return MHelpers.modelMapper().map(personas.get(),PersonaDTO.class);
}
#Override
public void save(PersonaDTO personaDTO) {
Persona persona = MHelpers.modelMapper().map(personaDTO, Persona.class);
this.PersonaRepository.save(persona);
}
#Override
public void saveAll(List<PersonaDTO> personas) {
List<Persona> p = new ArrayList<>();
for (PersonaDTO persona: personas) {
Persona pers = MHelpers.modelMapper().map(persona,Persona.class);
p.add(pers);
}
this.PersonaRepository.saveAll(p);
}
#Override
public void deleteById(Long id) {
this.PersonaRepository.deleteById(id);
}
private PersonaDTO convertToPersonaDTO(final Persona persona){
return MHelpers.modelMapper().map(persona,PersonaDTO.class);
}
}
If you need more information tell me

Whitelabel Error Page This application has no explicit mapping for /error

I have problem with my application. I added uploading image page but i get problem.
enter image description here
Before my project work corretly. I can login in test1 be user and test3. Admin can log test2 and test3, but when i add uploadImage and i wanna log be Admin i get whitelabel, if i change this for user i get this same problem. I think this should be problem with mapping or scaning, my structure maybe is not correctly but idk because i dont have enough experience. Lower i add my code, if someone need more code, ask.
My uploadImage:
package com.example.imageUploader.gui;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.Route;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.imageUploader.ImageUploader;
import org.springframework.web.bind.annotation.GetMapping;
import java.awt.*;
// problem moze byc z mapowaniem albo zaleznosciami miedzy folderami ze ten jest za wysoko
#Route("uploadImage")
public class UploadGui extends VerticalLayout
{
private ImageUploader imageUploader;
#Autowired
public UploadGui(ImageUploader imageUploader)
{
this.imageUploader = imageUploader;
TextField textField = new TextField();
Button button = new Button("upload");
button.addClickListener(clickEvent -> imageUploader.uploadFile(textField.getValue()));
add(textField);
add(button);
}
}
My run:
package com.example.imageUploader;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
#SpringBootApplication
//#ComponentScan(basePackages = "com.example.imageUploader.gui.UploadGui")
public class ImageUploaderApplication {
public static void main(String[] args) {
SpringApplication.run(ImageUploaderApplication.class, args);
}
}
My logging:
package com.example.imageUploader;
import com.example.imageUploader.model.AppUser;
import com.example.imageUploader.repo.AppUserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Collections;
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
private UserDetailsServiceImpl userDetailsService;
private AppUserRepo appUserRepo;
#Autowired
public WebSecurityConfig(UserDetailsServiceImpl userDetailsService, AppUserRepo appUserRepo) {
this.userDetailsService = userDetailsService;
this.appUserRepo = appUserRepo;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.antMatchers("/test1").hasRole("USER")
.antMatchers("/test2").hasRole("ADMIN")
.antMatchers("/uploadImage").hasRole("ADMIN")
.and()
.formLogin().permitAll();
}
#Bean
public PasswordEncoder passwordEncoder()
{
return new BCryptPasswordEncoder();
}
#EventListener(ApplicationReadyEvent.class)
public void get()
{
AppUser appUserUser = new AppUser("User", passwordEncoder().encode("haslo123"), "ROLE_USER");
AppUser appUserAdmin = new AppUser("Admin", passwordEncoder().encode("haslo123"), "ROLE_ADMIN");
appUserRepo.save(appUserUser);
appUserRepo.save(appUserAdmin);
}
}
My 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 https://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.7.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>imageUploader</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>imageUploader</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<vaadin.version>23.1.4</vaadin.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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
</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.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.cloudinary</groupId>
<artifactId>cloudinary-http44</artifactId>
<version>1.22.1</version>
</dependency>
<dependency>
<groupId>com.cloudinary</groupId>
<artifactId>cloudinary-taglib</artifactId>
<version>1.0.14</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-bom</artifactId>
<version>${vaadin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>production</id>
<build>
<plugins>
<plugin>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-maven-plugin</artifactId>
<version>${vaadin.version}</version>
<executions>
<execution>
<id>frontend</id>
<phase>compile</phase>
<goals>
<goal>prepare-frontend</goal>
<goal>build-frontend</goal>
</goals>
<configuration>
<productionMode>true</productionMode>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
Screen of my structure:
enter image description here
Ok, problem solved. I put this part of my pom.xml in the comment and resolve problem.
<profiles>
<profile>
<id>production</id>
<build>
<plugins>
<plugin>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-maven-plugin</artifactId>
<version>${vaadin.version}</version>
<executions>
<execution>
<id>frontend</id>
<phase>compile</phase>
<goals>
<goal>prepare-frontend</goal>
<goal>build-frontend</goal>
</goals>
<configuration>
<productionMode>true</productionMode>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>

MessageMessageBodyWriter not found for media type=application/xml, type=class java.util.ArrayList

I am trying to execute a very simple REST API using JAXrs. I have been following JetBrains tutorial and I'm stuck at the point where the API needs to return Reponse/XML. The java version used here is 1.8 and the Tomcat is 10.0.
I Guess there is some dependencies missing. Can someone help?
Here are my code snippets:
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>org.surender</groupId>
<artifactId>messenger</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>messenger</name>
<build>
<finalName>messenger</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<inherited>true</inherited>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.activation/activation -->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-runtime -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.0-b170127.1453</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>4.0.0</version>
<scope>runtime</scope>
</dependency>
<!-- uncomment this to get JSON support <dependency> <groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId> </dependency> -->
</dependencies>
<properties>
<jersey.version>3.1.0-M2</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Model Class
package org.surender.model;
import javax.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlElement;
#XmlRootElement(name = "Surender")
public class MessagesModel {
#XmlElement(name = "Message ID")
public int messageId;
public String messageTxt;
public String messageLike;
public String messageComment;
public MessagesModel(int messageId, String messageTxt, String messageLike, String messageComment) {
super();
System.out.println("Objects getting created");
this.messageId = messageId;
this.messageTxt = messageTxt;
this.messageLike = messageLike;
this.messageComment = messageComment;
}
public MessagesModel() {
}
public int getMessageId() {
return messageId;
}
public void setMessageId(int messageId) {
this.messageId = messageId;
}
public String getMessageTxt() {
return messageTxt;
}
public void setMessageTxt(String messageTxt) {
this.messageTxt = messageTxt;
}
public String getMessageLike() {
return messageLike;
}
public void setMessageLike(String messageLike) {
this.messageLike = messageLike;
}
public String getMessageComment() {
return messageComment;
}
public void setMessageComment(String messageComment) {
this.messageComment = messageComment;
}
}
Message Service
package org.surender.service;
import java.util.ArrayList;
import java.util.List;
import org.surender.model.MessagesModel;
public class MessagesService {
public List<MessagesModel> getMessages() {
List<MessagesModel> messagesList = new ArrayList<MessagesModel>();
messagesList.add(new MessagesModel(1,"Hey There !","2","Hello"));
messagesList.add(new MessagesModel(1,"Hola Amigo!","2","Hello"));
return messagesList;
}
public MessagesService() {
}
}
MessageResource
package org.surender.messenger;
import java.util.ArrayList;
import java.util.List;
import org.surender.model.MessagesModel;
import org.surender.service.MessagesService;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.GenericEntity;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
#Path("messages")
public class Messages {
MessagesService msgService = new MessagesService();
#GET
#Produces(MediaType.APPLICATION_XML)
public Response getMessages() {
System.out.println("Hi... I'm here one");
GenericEntity<List<MessagesModel>> entity = new GenericEntity<List<MessagesModel>>(msgService.getMessages()) {};
return Response.ok(entity).build();
}
}

Spring Cloud Stream Source - Not Pulling

I'm trying to develop a customized Source for a proof of concept in Spring Cloud Dataflow.
I managed to deploy it correctly, but it seems that the bean is not pulled.
Here's a part of the parent pom.xml
...
<properties>
<spring-cloud.version>Hoxton.SR8</spring-cloud.version>
...
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
...
Here's the project pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cloud-connectors</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.4.RELEASE</version>
<configuration>
<excludes>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-app-starter-metadata-maven-plugin</artifactId>
<version>2.0.2.RELEASE</version>
<executions>
<execution>
<id>aggregate-metadata</id>
<phase>compile</phase>
<goals>
<goal>aggregate-metadata</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
SourceApplication.java
#SpringBootApplication
#EnableBinding(Source.class)
#EnableConfigurationProperties(ReportingProperties.class)
public class SourceApplication {
public static void main(String[] args) {
SpringApplication.run(SourceApplication.class, args);
}
}
ReportingProperties.java
#Validated
#ConfigurationProperties("reporting-properties")
public class ReportingProperties {
/**
* The starting date of the reporting.
*/
private LocalDateTime fromDate = LocalDateTime.now().minusDays(1000);
/**
* The end date of the reporting.
*/
private LocalDateTime toDate = LocalDateTime.now();
public LocalDateTime getFromDate() {
return fromDate;
}
public ReportingProperties setFromDate(LocalDateTime fromDate) {
this.fromDate = fromDate;
return this;
}
public LocalDateTime getToDate() {
return toDate;
}
public ReportingProperties setToDate(LocalDateTime toDate) {
this.toDate = toDate;
return this;
}
}
And finally the service :
#Configuration
#EnableBinding(Source.class)
public class PullUsersService {
#Bean
#Publisher(channel = Source.OUTPUT)
#SendTo(Source.OUTPUT)
public Supplier<String> pullUsers() {
return () -> "Test";
}
}
I'm wondering how to trigger the pulling mechanism so when deployed I can see "Test" in the logs
(I believe everything is setup correctly on SCDF, if I do "time | log" i can see some results in the log, but if I do "myservice | log" nothing appears.
What am I doing wrong ? (maybe there's some redundancy in my code)
The answer above is correct, you can also do it the following way:
Note: Remove all #EnableBinding(Source.class) anotations
#Component
public class PullUsersService {
#PollableBean
public Supplier<String> pullUsers() {
return () -> "Test";
}
}
Add the following configurations if you want queue to rabbitMq or kafka based on your binder configuration
spring.cloud.function.definition=pullUsers
spring.cloud.stream.bindings.pullUsers-out-0.destination=users
spring.cloud.stream.bindings.pullUsers-out-0.group=users-service
spring.cloud.stream.bindings.pullUsers-out-0.producer.requiredGroups=users-service
spring.cloud.stream.bindings.pullUsers-out-0.producer.requiredGroups configuration forces producer to create the queues
That's interesting what made you to use this:
#Publisher(channel = Source.OUTPUT)
#SendTo(Source.OUTPUT)
If you take a look into that time source code you mention, you'll see something like this:
#PollableSource
public String publishTime() {
return new SimpleDateFormat(this.triggerProperties.getDateFormat()).format(new Date());
}
Consider to use that #PollableSource instead and don't use a Supplier.
The point is that all your current annotations do nothing with polling.
The #Publisher works only when we call the method.
The #SendTo is fully ignored here since #Publisher does exactly the same and it "sends to".

"Exception in thread "mainHow to resolve this exception: " java.lang.NoClassDefFoundError: net/bytebuddy/NamingStrategy..."

I'm trying to connect a local database to my application using hibernate. I'm getting the following error:
Jul 02, 2019 9:20:08 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {[WORKING]}
Exception in thread "main" java.lang.NoClassDefFoundError: net/bytebuddy/NamingStrategy$SuffixingRandom$BaseNameResolver
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.cfg.Environment.buildBytecodeProvider(Environment.java:345)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.cfg.Environment.buildBytecodeProvider(Environment.java:337)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.cfg.Environment.<clinit>(Environment.java:230)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:78)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:67)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:58)
at ProjectDBTest/ProjectDBTest2.HibernateUtil.getSessionFactory(HibernateUtil.java:28)
at ProjectDBTest/ProjectDBTest2.App.main(App.java:28)
Caused by: java.lang.ClassNotFoundException: net.bytebuddy.NamingStrategy$SuffixingRandom$BaseNameResolver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 8 more
Any help on how to resolve this would be greatly appreciated.
Initially, I was getting 'java.lang.NoClassDefFoundError: java/sql/SQLException' exception and so I added 'requires java.sql' after seeing this as a suggested solution elsewhere on Stack Overflow, but now a the exception described above arises. I'm not sure where I'm gone wrong in my code or what is missing.
Here is my module-info.java file:
module ProjectDBTest {
requires java.persistence;
//requires lombok;
requires javafx.graphics;
requires org.hibernate.orm.core;
requires java.naming;
requires java.sql;
exports ProjectDBTest2.DB;
}
main class:
package ProjectDBTest2;
import ProjectDBTest2.DB.Vocabulary;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.List;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
Vocabulary word1 = new Vocabulary();
word1.setUnitID(1);
word1.setWord("test");
word1.setVocabClass("noun");
word1.setVocabDefinition("this is a test");
word1.setVocabID(7);
System.out.println(word1.getUnitID());
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
session.save(word1);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
List< Vocabulary > students = session.createQuery("from Vocabulary ", Vocabulary.class).list();
students.forEach(s -> System.out.println(s.getWord()));
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
}
}
Hibernate util file:
package ProjectDBTest2;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private static StandardServiceRegistry registry;
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
// Create registry
registry = new StandardServiceRegistryBuilder().configure().build();
// Create MetadataSources
MetadataSources sources = new MetadataSources(registry);
// Create Metadata
Metadata metadata = sources.getMetadataBuilder().build();
// Create SessionFactory
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
e.printStackTrace();
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
return sessionFactory;
}
public static void shutdown() {
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
Persistence data class:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//#Data
#Entity
#Table(name = "vocabulary")
public class Vocabulary {
#Id
#Column(name = "V_ID")
private int vocabID;
#Column(name = "V_WORD")
private String word;
#Column(name = "V_CLASS")
private String vocabClass;
#Column(name = "V_DEFINITION")
private String vocabDefinition;
#Column(name = "U_ID")
private int unitID;
public int getVocabID() {
return vocabID;
}
public void setVocabID(int vocabID) {
this.vocabID = vocabID;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getVocabClass() {
return vocabClass;
}
public void setVocabClass(String vocabClass) {
this.vocabClass = vocabClass;
}
public String getVocabDefinition() {
return vocabDefinition;
}
public void setVocabDefinition(String vocabDefinition) {
this.vocabDefinition = vocabDefinition;
}
public int getUnitID() {
return unitID;
}
public void setUnitID(int unitID) {
this.unitID = unitID;
}
}
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>ProjectDBTest2</groupId>
<artifactId>ProjectDBTest2.0</artifactId>
<version>1.0-SNAPSHOT</version>
<name>ProjectDBTest2.0</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy -->
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.3.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok-->
<!--
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency> -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics</artifactId>
<version>13-ea+9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx</artifactId>
<version>13-ea+9</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-base -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-base</artifactId>
<version>13-ea+9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-controls -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>13-ea+9</version>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
I'm using intelliJ ultimate 2019.1 and language level is set to 11.
I finally managed to solve the issue by updating my module-info.java file to include:
module AlienDB {
requires static lombok;
requires java.persistence;
requires org.hibernate.orm.core;
requires java.naming;
requires java.sql;
requires com.sun.xml.bind;
requires net.bytebuddy;
opens Aliens to org.hibernate.orm.core;
exports Aliens;
}
Previously I was adding java.xml.bind which was causing further issues.

Categories

Resources