JSF Client error consuming Rest Service made with JAX-RS - jersey

I try to test the methods established in the restservice (JAX-RS) with a separate client made in jsf, the test is simply to press a button and execute the method.
JAX-RS service code
#Stateless
#Path("/personas")
public class PersonaServiceRS {
#Inject
private IPersonaService personaService;
#GET
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Persona> listarPersona(){
System.out.println("Listar personas");
return personaService.listarPersonas();
}
#GET
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Path("{id}")
public Persona buscarPersonaPorID(#PathParam("id") int id){
System.out.println("buscarporId: " + id);
return personaService.buscarPersonaPorId(new Persona(id));
}
#POST
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response agregarPersona(Persona persona) {
try {
personaService.registrarPersona(persona);
System.out.println("Persona agregada: " + persona);
return Response.ok().entity(persona).build();
} catch(Exception e){
e.printStackTrace(System.out);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
}
#PUT
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Path("{id}")
public Response modificarPersona(#PathParam("id") int id, Persona personaForm){
try {
Persona persona = personaService.buscarPersonaPorId(new Persona(id));
if(persona != null){
personaService.modificarPersona(personaForm);
System.out.println("Persona modificada: " + personaForm);
return Response.ok().entity(personaForm).build();
}else{
return Response.status(Status.NOT_FOUND).build();
}
} catch(Exception e){
e.printStackTrace(System.out);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
}
#DELETE
#Path("{id}")
public Response eliminarPersona(#PathParam("id") int id){
System.out.println("Entre Eliminar");
try{
personaService.eliminarPersona(new Persona(id));
System.out.println("Persona Eliminada con id: " + id);
return Response.ok().build();
}catch(Exception e){
e.printStackTrace(System.out);
return Response.status(404).build();
}
}
}
client index.xhml in jsf
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Prueba JSF Form!</title>
</h:head>
<h:body>
<h:outputLabel value="Prueba de JSF!" />
<h1>Opciones de Aplicativo</h1>
<br/><br/><br/>
<h:form>
<h:commandButton value="Encontrar persona por ID" action="#{personaController.encontrarPersonaId()}"></h:commandButton>
</h:form>
</h:body>
</html>
controller class PersonaController jsf
package co.com.prueba.controllers;
import co.com.prueba.services.PersonaRestService;
import java.io.Serializable;
import javax.enterprise.context.*;
import javax.inject.Named;
#Named
#SessionScoped
public class PersonaController implements Serializable{
public void encontrarPersonaId(){
System.out.println("encontrarPersonaID");
PersonaRestService personaService = new PersonaRestService();
String nombrePersona = personaService.encontrarPersonaId(1);
System.out.println("nombrePersona 1: " + nombrePersona);
}
}
service class PersonaRestService
import co.com.prueba.model.Persona;
import java.util.List;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
public class PersonaRestService {
private static final String URL_BASE = "http://localhost:8585/ProyectoPrueba/webservice";
private static Client cliente;
private static WebTarget webTarget;
private static Persona persona;
private static List<Persona> personas;
private static Invocation.Builder invocationBuilder;
private static Response response;
public String encontrarPersonaId(int id){
System.out.println("Entre encontrar persona con id: " + id);
cliente = ClientBuilder.newClient();
webTarget = cliente.target(URL_BASE).path("/personas");
System.out.println("Creo el webTarget:" + webTarget);
persona = webTarget.path("/1").request().get(Persona.class); //path y despues request
System.out.println("Persona recuperada por id: " + persona);
return persona.getNombre();
}
}
client pom.xml in jsf
<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>co.com.prueba</groupId>
<artifactId>ClienteRsProyectoPrueba</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>ClienteRsProyectoPrueba</name>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<failOnMissingWebXml>false</failOnMissingWebXml>
<jakartaee>8.0</jakartaee>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${jakartaee}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.30.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.30.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.30.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.30.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.13.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0-b170201.1204</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>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.1.2</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${jakartaee}</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
==== Testing the findPersonaId method from this main class, It works fine:
public class TestConsolaClases {
public static void main(String[] args) {
PersonaRestService rs = new PersonaRestService();
String nombre = rs.encontrarPersonaId(1);
System.out.println("nombre: " + nombre);
}
}
However, from the jsf index, when executing, it generates the following error:
exception
javax.servlet.ServletException: java.lang.NoSuchMethodError: org.glassfish.jersey.internal.LocalizationMessages.WARNING_PROPERTIES()Ljava/lang/String;
root cause
javax.faces.el.EvaluationException: java.lang.NoSuchMethodError: org.glassfish.jersey.internal.LocalizationMessages.WARNING_PROPERTIES()Ljava/lang/String;
root cause
java.lang.NoSuchMethodError: org.glassfish.jersey.internal.LocalizationMessages.WARNING_PROPERTIES()Ljava/lang/String;
Initializing Soteria 1.0 for context '/ClienteRsProyectoPrueba'|#]
Inicializando Mojarra 2.3.2 ( 20170627-2139 e63598abf2ed2bb1a24674f308a734e0dce18a72) para el contexto '/ClienteRsProyectoPrueba'|#]
Loading application [ClienteRsProyectoPrueba] at [/ClienteRsProyectoPrueba]|#]
ClienteRsProyectoPrueba was successfully deployed in 3.120 milliseconds.|#]
encontrarPersonaID|#]
Entre encontrar persona con id: 1|#]
Creo el webTarget:JerseyWebTarget { http://localhost:8585/ProyectoPrueba/webservice/personas }|#]
#{personaController.encontrarPersonaId()}: java.lang.NoSuchMethodError: org.glassfish.jersey.internal.LocalizationMessages.WARNING_PROPERTIES()Ljava/lang/String;
javax.faces.FacesException: #{personaController.encontrarPersonaId()}: java.lang.NoSuchMethodError: org.glassfish.jersey.internal.LocalizationMessages.WARNING_PROPERTIES()Ljava/lang/String;
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:119)
at javax.faces.component.UICommand.broadcast(UICommand.java:330)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:870)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1418)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:201)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:670)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1580)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:652)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:591)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:463)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:168)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:242)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
at java.lang.Thread.run(Thread.java:748)
Caused by: javax.faces.el.EvaluationException: java.lang.NoSuchMethodError: org.glassfish.jersey.internal.LocalizationMessages.WARNING_PROPERTIES()Ljava/lang/String;
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 35 more
Caused by: java.lang.NoSuchMethodError: org.glassfish.jersey.internal.LocalizationMessages.WARNING_PROPERTIES()Ljava/lang/String;
at org.glassfish.jersey.internal.config.SystemPropertiesConfigurationModel.getProperties(SystemPropertiesConfigurationModel.java:120)
at org.glassfish.jersey.internal.config.SystemPropertiesConfigurationProvider.getProperties(SystemPropertiesConfigurationProvider.java:29)
at org.glassfish.jersey.internal.config.ExternalPropertiesConfigurationFactory.readExternalPropertiesMap(ExternalPropertiesConfigurationFactory.java:55)
at org.glassfish.jersey.internal.config.ExternalPropertiesConfigurationFactory.configure(ExternalPropertiesConfigurationFactory.java:72)
at org.glassfish.jersey.internal.config.ExternalPropertiesConfigurationFeature.configure(ExternalPropertiesConfigurationFeature.java:26)
at org.glassfish.jersey.model.internal.CommonConfig.configureFeatures(CommonConfig.java:701)
at org.glassfish.jersey.model.internal.CommonConfig.configureMetaProviders(CommonConfig.java:635)
at org.glassfish.jersey.client.ClientConfig$State.configureMetaProviders(ClientConfig.java:411)
at org.glassfish.jersey.client.ClientConfig$State.initRuntime(ClientConfig.java:456)
at org.glassfish.jersey.internal.util.collection.Values$LazyValueImpl.get(Values.java:341)
at org.glassfish.jersey.client.ClientConfig.getRuntime(ClientConfig.java:826)
at org.glassfish.jersey.client.ClientRequest.getConfiguration(ClientRequest.java:285)
at org.glassfish.jersey.client.JerseyInvocation.validateHttpMethodAndEntity(JerseyInvocation.java:143)
at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:112)
at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:108)
at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:99)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:428)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:324)
at co.com.prueba.services.PersonaRestService.encontrarPersonaId(PersonaRestService.java:31)
at co.com.prueba.controllers.PersonaController.encontrarPersonaId(PersonaController.java:15)
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 javax.el.ELUtil.invokeMethod(ELUtil.java:304)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:535)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
at com.sun.el.parser.AstValue.invoke(AstValue.java:285)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:107)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 36 more
|#]
StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
java.lang.NoSuchMethodError: org.glassfish.jersey.internal.LocalizationMessages.WARNING_PROPERTIES()Ljava/lang/String;
at org.glassfish.jersey.internal.config.SystemPropertiesConfigurationModel.getProperties(SystemPropertiesConfigurationModel.java:120)
at org.glassfish.jersey.internal.config.SystemPropertiesConfigurationProvider.getProperties(SystemPropertiesConfigurationProvider.java:29)
at org.glassfish.jersey.internal.config.ExternalPropertiesConfigurationFactory.readExternalPropertiesMap(ExternalPropertiesConfigurationFactory.java:55)
at org.glassfish.jersey.internal.config.ExternalPropertiesConfigurationFactory.configure(ExternalPropertiesConfigurationFactory.java:72)
at org.glassfish.jersey.internal.config.ExternalPropertiesConfigurationFeature.configure(ExternalPropertiesConfigurationFeature.java:26)
at org.glassfish.jersey.model.internal.CommonConfig.configureFeatures(CommonConfig.java:701)
at org.glassfish.jersey.model.internal.CommonConfig.configureMetaProviders(CommonConfig.java:635)
at org.glassfish.jersey.client.ClientConfig$State.configureMetaProviders(ClientConfig.java:411)
at org.glassfish.jersey.client.ClientConfig$State.initRuntime(ClientConfig.java:456)
at org.glassfish.jersey.internal.util.collection.Values$LazyValueImpl.get(Values.java:341)
at org.glassfish.jersey.client.ClientConfig.getRuntime(ClientConfig.java:826)
at org.glassfish.jersey.client.ClientRequest.getConfiguration(ClientRequest.java:285)
at org.glassfish.jersey.client.JerseyInvocation.validateHttpMethodAndEntity(JerseyInvocation.java:143)
at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:112)
at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:108)
at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:99)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:428)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:324)
at co.com.prueba.services.PersonaRestService.encontrarPersonaId(PersonaRestService.java:31)
at co.com.prueba.controllers.PersonaController.encontrarPersonaId(PersonaController.java:15)
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 javax.el.ELUtil.invokeMethod(ELUtil.java:304)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:535)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
at com.sun.el.parser.AstValue.invoke(AstValue.java:285)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:107)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:330)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:870)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1418)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:201)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:670)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1580)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:652)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:591)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:463)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:168)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:242)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
at java.lang.Thread.run(Thread.java:748)
|#]

Related

My Camel route app detects other app's published ampq message(?), but, fails to handle, with "no type converter available" error. How can I resolve?

My Camel route app detects other app's published ampq message(publishes numbers), but, fails to handle, with "no type converter available" error. How can I resolve?.
"org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: java.lang.Integer to the required type: java.io.InputStream with value 79"
routebuilder class
package aaa.bbb.ccc.qscx;
import java.io.IOException;
import javax.ejb.Startup;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.reactive.streams.api.CamelReactiveStreamsService;
import org.eclipse.microprofile.reactive.messaging.Incoming;
import org.reactivestreams.Subscriber;
#Startup
#ApplicationScoped
public class TheRoutes extends RouteBuilder {
#Inject
TheProcessor theProcessor;
#Inject
CamelContext ctx;
#Inject
CamelReactiveStreamsService crss;
#Override
public void configure() throws IOException, InterruptedException {
from("reactive-streams:in")
.process(theProcessor)
.log(".........from reactive-streams:in - body: ${body}");
}
#Incoming("prices")
public Subscriber<String> sink() {
return crss.subscriber("file:./target?fileName=values.txt&fileExist=append", String.class);
}
}
pom.xml
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>aaa.bbb.ccc </groupId>
<artifactId>qscx</artifactId>
<version>1.0</version>
<properties>
<compiler-plugin.version>3.8.1</compiler-plugin.version>
<maven.compiler.parameters>true</maven.compiler.parameters>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<quarkus-plugin.version>1.0.0.CR2</quarkus-plugin.version>
<quarkus.platform.artifact-id>quarkus-universe-bom</quarkus.platform.artifact-id>
<quarkus.platform.group-id>io.quarkus</quarkus.platform.group-id>
<quarkus.platform.version>1.0.0.CR2</quarkus.platform.version>
<surefire-plugin.version>2.22.1</surefire-plugin.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>${quarkus.platform.group-id}</groupId>
<artifactId>${quarkus.platform.artifact-id}</artifactId>
<version>${quarkus.platform.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-reactive-messaging-amqp</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-reactive-messaging</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.quarkus</groupId>
<artifactId>camel-quarkus-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.quarkus</groupId>
<artifactId>camel-quarkus-timer</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-artemis-jms</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.quarkus</groupId>
<artifactId>camel-quarkus-bean</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-reactive-streams-operators</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.quarkus</groupId>
<artifactId>camel-quarkus-support-common</artifactId>
</dependency>
<dependency>
<groupId>io.smallrye.reactive</groupId>
<artifactId>smallrye-reactive-messaging-camel</artifactId>
<version>1.0.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.26</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>build</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<configuration>
<systemProperties>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
</systemProperties>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>native</id>
<activation>
<property>
<name>native</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<systemProperties>
<native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path>
</systemProperties>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<quarkus.package.type>native</quarkus.package.type>
</properties>
</profile>
</profiles>
<name>qscx</name>
</project>
application.properties
amqp-username=quarkus
amqp-password=quarkus
mp.messaging.incoming.prices.address=prices
mp.messaging.incoming.prices.connector=smallrye-amqp
mp.messaging.incoming.prices.host=localhost
mp.messaging.incoming.prices.port=5672
mp.messaging.incoming.prices.username=quarkus
mp.messaging.incoming.prices.password=quarkus
mp.messaging.incoming.prices.broadcast=true
mp.messaging.incoming.prices.containerId=my-container-id
console stacktrace (excerpt)
2019-11-22 22:31:22,930 WARN [org.apa.cam.com.rea.str.ReactiveStreamsConsumer] (Camel (camel-1) thread #1 - reactive-streams://DCE85ACAC992C3A-0000000000000000) Error processing exchange. Exchange[DCE85ACAC992C3A-000000000000005F]. Caused by: [org.apache.camel.component.file.GenericFileOperationFailedException - Cannot store file: .\target\values.txt]: org.apache.camel.component.file.GenericFileOperationFailedException: Cannot store file: .\target\values.txt
at org.apache.camel.component.file.FileOperations.storeFile(FileOperations.java:376)
at org.apache.camel.component.file.GenericFileProducer.writeFile(GenericFileProducer.java:300)
at org.apache.camel.component.file.GenericFileProducer.processExchange(GenericFileProducer.java:164)
at org.apache.camel.component.file.GenericFileProducer.process(GenericFileProducer.java:75)
at org.apache.camel.support.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:67)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:134)
at org.apache.camel.processor.errorhandler.RedeliveryErrorHandler$RedeliveryState.run(RedeliveryErrorHandler.java:476)
at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:185)
at org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:59)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:87)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:228)
at org.apache.camel.component.reactive.streams.ReactiveStreamsConsumer.lambda$doSend$3(ReactiveStreamsConsumer.java:96)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.camel.InvalidPayloadException: No body available of type: java.io.InputStream but has value: 79 of type: java.lang.Integer on: Message[]. Caused by: No type converter available to convert from type: java.lang.Integer to the required type: java.io.InputStream with value 79. Exchange[DCE85ACAC992C3A-000000000000005F]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: java.lang.Integer to the required type: java.io.InputStream with value 79]
at org.apache.camel.support.MessageSupport.getMandatoryBody(MessageSupport.java:115)
at org.apache.camel.component.file.FileOperations.storeFile(FileOperations.java:355)
... 14 more
Caused by: org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: java.lang.Integer to the required type: java.io.InputStream with value 79
at org.apache.camel.impl.converter.BaseTypeConverterRegistry.mandatoryConvertTo(BaseTypeConverterRegistry.java:139)
at org.apache.camel.support.MessageSupport.getMandatoryBody(MessageSupport.java:113)
... 15 more
other notes
publishing app is based upon the Quark Ampq example:
https://github.com/quarkusio/quarkus-quickstarts/tree/master/amqp-quickstart/src/main/java/org/acme/quarkus/sample
technologies
java 8
quarkus
smallrye
camel
maven
It seems the subscriber does not currently execute the type conversion. It may be solved in a future release.
In the meantime, you need to enforce it in the route:
#Override
public void configure() throws IOException, InterruptedException {
from("direct:proc")
.convertBodyTo(String.class)
.to("file:./target?fileName=values.txt&fileExist=append");
}
#Incoming("prices")
public Subscriber<String> sink() {
return crss.subscriber("direct:proc", String.class);
}

Springboot app deployed in CloudFoundry - Get and Post operation on db fail

I am building a sample Spring application that will expose a REST
API to get and post data to a table in a database. Building the basic stuff.
I am using PostgreSQL for the data source in Cloud Foundry.
The GET API which returns a string works fine. The API which does POST returns 404 Not Found. The API which returns the entries in the table throws an exception.
Type Exception Report
Message Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DatabaseException
Description:
The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: syntax error at or near "GROUP"
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#Configuration
#EnableJpaRepositories(basePackageClasses =
CustomerFeedbackRepository.class)
#Profile("cloud")
public class CloudDatabaseConfig extends AbstractCloudConfig {
#Bean
public DataSource dataSource() {
List<String> dataSourceNames =
Arrays.asList("BasicDbcpPooledDataSourceCreator","TomcatJdbcPooledDataSourceCreator","HikariCpPooledDataSourceCreator","TomcatDbcpPooledDataSourceCreator");
DataSourceConfig dbConfig = new DataSourceConfig(dataSourceNames);
return connectionFactory().dataSource(dbConfig);
}
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
return EntityManagerFactoryProvider.get(dataSource, CustomerFeedback.class.getPackage().getName());
}
#Bean(name = "transactionManager")
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
#PostMapping("/capturecf")
#RequestMapping(value ="CustomerFeedback", method = RequestMethod.POST)
public CustomerFeedback addFeedback(#RequestBody CustomerFeedback custfeedback)
{
return customerfeedbackrepo.save(custfeedback);
}
#PostMapping("/captureua")
#RequestMapping(value = "UsageActivity", method = RequestMethod.POST)
public UsageActivity addUsageTracking(#Valid #RequestBody UsageActivity usageActivity)
{
return usageactivityrepository.save(usageActivity);
}
#GetMapping("/usageactivity")
public List<UsageActivity> getAllNotes() {
return usageactivityrepository.findAll();`enter code here`
}
<dependencies>
<!-- APIs for servlets and injection -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Spring Framework and Spring WebMVC -->
<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>
<!-- Logging library -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>com.sap.hcp.cf.logging</groupId>
<artifactId>cf-java-logging-support-logback</artifactId>
<version>${sap.logging.version}</version>
</dependency>
<dependency>
<groupId>com.sap.hcp.cf.logging</groupId>
<artifactId>cf-java-logging-support-servlet</artifactId>
<version>${sap.logging.version}</version>
</dependency>
<!-- JSON conversion -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<!-- Actuator for adding management endpoints -->
<dependency>
<groupId> org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
<!-- Bean validation (#NotNull etc.) -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
</dependency>
<!-- MethodValidationPostProcessor relies on Expression Language -->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.1-b04</version>
</dependency>
<!-- Spring Cloud Connector -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-spring-service-connector</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-cloudfoundry-connector</artifactId>
<version>1.2.1.RELEASE</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.2.RELEASE</version>
<exclusions>
<exclusion>
<!-- We need spring-core 4.2 or later, but spring-data includes 4.1.9 -->
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- EclipseLink as JPA implementation -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.6.2</version>
</dependency>
<!-- PostgreSQL database implementations -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1206-jdbc41</version>
<scope>runtime</scope>
</dependency>
<!-- connection pooling -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
<scope>runtime</scope>
</dependency>
<!-- Testing -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- Use MockMvcResultMatchers.jsonPath to assert the JSON body -->
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
<scope>test</scope>
</dependency>
<!-- H2 (in-memory) database implementation -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.184</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>customerconnect</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<!-- Provides the application at http://localhost:8080/ using an embedded
Tomcat server with a pre-configured environment referencing the SAP proxy -->
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>${maven.tomcat.port}</port>
<path>/</path>
<systemProperties>
<http.proxyHost>${http.proxyHost}</http.proxyHost>
<http.proxyPort>${http.proxyPort}</http.proxyPort>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>3.0.2</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>findbugs</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.5</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>pmd</goal>
<goal>cpd</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.5.201505241946</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>default-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
<version>2.5</version>
</plugin>
</plugins>
</reporting>
</project>
package com.sap.customerconnect.ads.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.sap.customerconnect.ads.models.UsageActivity;
import com.sap.customerconnect.ads.models.UsageActivityPK;
#Component
#Repository
public interface UsageActivityRepository extends JpaRepository<UsageActivity, UsageActivityPK> {
}
package com.sap.customerconnect.ads.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.sap.customerconnect.ads.models.CustomerFeedback;
import com.sap.customerconnect.ads.models.CustomerFeedbackPK;
#Component
#Repository
public interface CustomerFeedbackRepository extends JpaRepository<CustomerFeedback, CustomerFeedbackPK>{
}
package com.sap.customerconnect.ads.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;
#IdClass(UsageActivityPK.class)
#Entity
#Table(name = "UsageActivity")
public class UsageActivity {
#Id
#Column(name = "PRODUCT_ID")
private String ProductId;
#Id
#Column(name = "CUSTOMER_ID")
private String CustomerId;
#Id
#Column(name = "SCREEN_ID")
private String ScreenId;
#Column(name = "GROUP")
private String Group;
#Column(name = "ACTION")
private String Action;
#Column(name = "DESCRIPTION")
private String Description;
#Column(name = "COUNT")
private Integer Count;
public UsageActivity() {
}
public String getProductId() {
return ProductId;
}
public void setProductId(String productId) {
ProductId = productId;
}
public String getCustomerId() {
return CustomerId;
}
public void setCustomerId(String customerId) {
CustomerId = customerId;
}
public String getScreenId() {
return ScreenId;
}
public void setScreenId(String screenId) {
ScreenId = screenId;
}
public String getGroup() {
return Group;
}
public void setGroup(String group) {
Group = group;
}
public String getAction() {
return Action;
}
public void setAction(String action) {
Action = action;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public Integer getCount() {
return Count;
}
public void setCount(Integer count) {
Count = count;
}
public UsageActivity(String productId, String customerId, String screenId, String group, String action,
String description, Integer count) {
super();
ProductId = productId;
CustomerId = customerId;
ScreenId = screenId;
Group = group;
Action = action;
Description = description;
Count = count;
}
}
package com.sap.customerconnect.ads.models;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class UsageActivityPK implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "PRODUCT_ID")
private String ProductId;
#Column(name = "CUSTOMER_ID")
private String CustomerId;
#Column(name = "SCREEN_ID")
private String ScreenId;
}
The POST and GET operations on the repository does not work.

import spring-boot-starter by myself, start print error log 'Unable to read meta-data for class'

hello everybody, I have a problem with spring-boot-starter.
I write some code to implement a starter
But not working properly,when start my project
idea console print error log:
java.lang.IllegalStateException: Unable to read meta-data for class com.beiming.zipkin.starter.config.ExampleAutoConfigure
at org.springframework.boot.autoconfigure.AutoConfigurationSorter$AutoConfigurationClass.getAnnotationMetadata(AutoConfigurationSorter.java:245) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.AutoConfigurationSorter$AutoConfigurationClass.getOrder(AutoConfigurationSorter.java:214) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.AutoConfigurationSorter$AutoConfigurationClass.access$000(AutoConfigurationSorter.java:155) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.AutoConfigurationSorter.lambda$getInPriorityOrder$0(AutoConfigurationSorter.java:63) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355) ~[na:1.8.0_111]
at java.util.TimSort.sort(TimSort.java:220) ~[na:1.8.0_111]
at java.util.Arrays.sort(Arrays.java:1512) ~[na:1.8.0_111]
at java.util.ArrayList.sort(ArrayList.java:1454) ~[na:1.8.0_111]
at org.springframework.boot.autoconfigure.AutoConfigurationSorter.getInPriorityOrder(AutoConfigurationSorter.java:61) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.AutoConfigurationImportSelector$AutoConfigurationGroup.sortAutoConfigurations(AutoConfigurationImportSelector.java:461) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.autoconfigure.AutoConfigurationImportSelector$AutoConfigurationGroup.selectImports(AutoConfigurationImportSelector.java:442) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGrouping.getImports(ConfigurationClassParser.java:881) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGroupingHandler.processGroupImports(ConfigurationClassParser.java:804) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorHandler.process(ConfigurationClassParser.java:774) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:185) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:315) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:232) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:275) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:95) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:691) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:528) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at com.example.teststarter.TestStarterApplication.main(TestStarterApplication.java:12) [classes/:na]
Caused by: java.io.FileNotFoundException: class path resource [com/beiming/zipkin/starter/config/ExampleAutoConfigure.class] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:180) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:51) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:103) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.boot.type.classreading.ConcurrentReferenceCachingMetadataReaderFactory.createMetadataReader(ConcurrentReferenceCachingMetadataReaderFactory.java:88) ~[spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.boot.type.classreading.ConcurrentReferenceCachingMetadataReaderFactory.getMetadataReader(ConcurrentReferenceCachingMetadataReaderFactory.java:75) ~[spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:81) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.boot.autoconfigure.AutoConfigurationSorter$AutoConfigurationClass.getAnnotationMetadata(AutoConfigurationSorter.java:241) ~[spring-boot-autoconfigure-2.1.1.RELEASE.jar:2.1.1.RELEASE]
... 26 common frames omitted
I can't understand what this error means.
Next is my code 、config file and dependency:
#Configuration
#ConditionalOnClass(ExampleService.class)
#EnableConfigurationProperties(ExampleServiceProperties.class)
public class ExampleAutoConfigure {
private final ExampleServiceProperties properties;
#Autowired
public ExampleAutoConfigure(ExampleServiceProperties properties) {
this.properties = properties;
}
#Bean
#ConditionalOnMissingBean
#ConditionalOnProperty(prefix = "example.service", value = "enabled", havingValue = "true")
ExampleService exampleService() {
return new ExampleService(properties.getPrefix(), properties.getSuffix());
}
}
#ConfigurationProperties("example.service")
public class ExampleServiceProperties {
private String prefix;
private String suffix;
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
public class ExampleService {
private String prefix;
private String suffix;
public ExampleService(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
public String wrap(String word) {
return prefix + word + suffix;
}
}
#SpringBootApplication
public class ZipkinSpringBootStarterApplication {
public static void main(String[] args) {
SpringApplication.run(ZipkinSpringBootStarterApplication.class, args);
}
}
here my config :
<?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.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.beiming.zipkin.starter</groupId>
<artifactId>zipkin-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>zipkin-spring-boot-starter</name>
<description>Demo project for Spring Boot</description>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<!--<proc>none</proc>-->
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
That all , Appreciate it!
Would you try to add #AutoConfiguration in your main class, or try to disable remove
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
</dependencies>
In case you are using this starter in another spring-boot application then you need to remove
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
</executions>
</plugin>
from your pom. It causes your configuration class to be placed under BOOT-INF/classes/ root inside the jar therefore, your application cannot find it. Here is a more detailed explanation: Unable to read meta-data for class. Spring autoconfig
I was having same problem then I changed spring-boot maven plugin to this
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
</plugins>
in general spring-boot maven plugin it creates jar having BOOT-INF folder , if you add exec classifier then it creates jar having starter classes package so that other projects can recognize starter classes. It works in my case .

SpringTest DBUnit: Failed to Load Application Context cause by Unable to locate keycloak.json

Hi I am new to spring mvc and would like to create an integration test using spring test dbunit but I am encountering an error. Keycloak.json file was not found but it exists under the test folder. The path of keycloak.json is also indicated in the application.properties file. Please see error below.Thanks
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'keycloakPreAuthActionsFilter' defined in class path resource [com/projects/commons/security/SecurityConfig.class]: Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adapterDeploymentContext' defined in class path resource [com/projects/commons/security/SecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.keycloak.adapters.AdapterDeploymentContext]: Factory method 'adapterDeploymentContext' threw exception; nested exception is java.io.FileNotFoundException: Unable to locate Keycloak configuration file: keycloak.json
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:134)
at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:61)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 29 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'keycloakPreAuthActionsFilter' defined in class path resource [com/projects/commons/security/SecurityConfig.class]: Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adapterDeploymentContext' defined in class path resource [com/projects/commons/security/SecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.keycloak.adapters.AdapterDeploymentContext]: Factory method 'adapterDeploymentContext' threw exception; nested exception is java.io.FileNotFoundException: Unable to locate Keycloak configuration file: keycloak.json
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 48 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'keycloakPreAuthActionsFilter' defined in class path resource [com/projects/commons/security/SecurityConfig.class]: Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adapterDeploymentContext' defined in class path resource [com/projects/commons/security/SecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.keycloak.adapters.AdapterDeploymentContext]: Factory method 'adapterDeploymentContext' threw exception; nested exception is java.io.FileNotFoundException: Unable to locate Keycloak configuration file: keycloak.json
.
.
.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adapterDeploymentContext' defined in class path resource [com/projects/commons/security/SecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.keycloak.adapters.AdapterDeploymentContext]: Factory method 'adapterDeploymentContext' threw exception; nested exception is java.io.FileNotFoundException: Unable to locate Keycloak configuration file: keycloak.json
Here is the BaseTestClass
//import classes
#Configuration
#ComponentScan( {"com.projects.person", "com.projects.commons"} )
#EnableWebMvc
#EnableTransactionManagement
#PropertySource( "classpath:application.properties" )
public class BaseTestConfig extends WebMvcConfigurerAdapter
{
#Autowired
private Environment env;
#Autowired
private OperatingSystem operatingSystem;
#Autowired
private PropertiesFactory propertiesFactory;
#Bean
public UrlBasedViewResolver setupViewResolver()
{
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix( "/WEB-INF/pages/" );
resolver.setSuffix( ".jsp" );
resolver.setViewClass( JstlView.class );
return resolver;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan( "com.projects.person.model.db" );
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
String databaseUrl = "jdbc:h2:tcp://localhost/persondb";
if( operatingSystem.isWindows() )
{
databaseUrl = "jdbc:h2:tcp://localhost/~/persondb";
}
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl( databaseUrl );
dataSource.setUsername("sa");
dataSource.setPassword("");
return dataSource;
}
#Bean
public H2Connection dbUnitConnection() throws SQLException, DatabaseUnitException {
return new H2Connection(dataSource().getConnection(), "Person");
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
properties.put("hibernate.show_sql", "false");
return properties;
}
#Bean
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager transactionManager = propertiesFactory.createTransactionManagerProperty();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
Here is Spring Test I created
//import classes
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(classes = {BaseTestConfig.class})
#TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
/*DirtiesContextTestExecutionListener.class,*/
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class
})
#DbUnitConfiguration(databaseConnection = "dbUnitConnection")
#DatabaseSetup("classpath:dataset/empty-person.xml")
public class AddPersonTest {
private static final String FIRSTNAME = "JANE";
public static final String MIDDLENAME = "CRUZ";
public static final String LASTNAME = "BILO";
#Autowired
private PersonController personController;
#Autowired
private Principals principals;
private PersonDB person;
#Before
public void setUp() {
person = new PersonDB();
person.setFirstName(FIRSTNAME);
person.setMiddleName(MIDDLENAME);
person.setLastName(LASTNAME);
#BeforeClass
public static void initContext() {
System.setProperty("spring.profiles.active", "dev");
System.setProperty("keycloak.configurationFile", "keycloak.json");
}
#Test
#ExpectedDatabase("classpath:dataset/add-person.xml")
public void testCreatePersonInstance() throws CrossSiteScriptingException {
BindingResult mockBindingResult = mock(BindingResult.class);
when(mockBindingResult.hasErrors()).thenReturn(false);
personController.addPerson(person, mockBindingResult, principals.create(USERNAME, USERNAME, TRIGGERUI));
}
#Bean
public Principals myPrincipals() {
return new Principals();
}
}
H2 Data Set to be tested:
empty set:
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<persons />
</dataset>
add person set:
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<persons PERSON_ID="1" FIRSTNAME="JANE" MIDDLENAME="CRUZ" LASTNAME="BILO"/>
</dataset>
These are the dependecies declared in 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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Person</groupId>
<artifactId>Person</artifactId>
<packaging>war</packaging>
<version>${version.release}.${version.additionalFeatures}-${version.batch}</version>
<properties>
<hibernate.version>4.2.0.Final</hibernate.version>
<mysql.connector.version>5.1.21</mysql.connector.version>
<spring.version>4.3.0.RELEASE</spring.version>
<spring.security.version>3.2.2.RELEASE</spring.security.version>
<jersey.version>1.9</jersey.version>
<powermock.version>1.6.4</powermock.version>
<version.release>4</version.release>
<version.additionalFeatures>0</version.additionalFeatures>
<version.batch>1</version.batch>
<version.milestone>I3</version.milestone>
<version.bugFix>0</version.bugFix>
<common-gui.version>0.0.0-SNAPSHOT-0</common-gui.version>
</properties>
<scm>
<connection>scm:svn:.../trunk/Person/</connection>
<url>.../trunk/Person/</url>
</scm>
<dependencies>
<!-- SLF4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<!-- Logger -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- DB related dependencies -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.176</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- SPRING -->
<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>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- Caching Supports -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- JERSEY -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey.version}</version>
</dependency>
<!-- APACHE -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-util</artifactId>
<version>8.0.0-RC1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- CGLIB is required to process #Configuration classes -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Servlet API and 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>
<!-- TEST -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test-mvc</artifactId>
<version>1.0.0.M1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</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>com.nokia.care.common-gui</groupId>
<artifactId>Commons</artifactId>
<version>${common-gui.version}</version>
</dependency>
<!-- KEYCLOAK -->
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-security-adapter</artifactId>
<version>3.0.0.Final</version>
</dependency>
<dependency>
<groupId>com.github.springtestdbunit</groupId>
<artifactId>spring-test-dbunit</artifactId>
<version>1.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.5.2</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>junit</artifactId>
<groupId>junit</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-maven-milestone</id>
<name>Spring Maven Milestone Repository</name>
<url>http://maven.springframework.org/milestone</url>
</repository>
</repositories>
<build>
<finalName>${project.artifactId}-${project.version}-${buildNumber}.${version.milestone}</finalName>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>buildnumber-maven-plugin</artifactId>
<version>1.2</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>create</goal>
</goals>
</execution>
</executions>
<configuration>
<docheck>false</docheck>
<doupdate>false</doupdate>
<useLastCommittedRevision>true</useLastCommittedRevision>
<revisionOnScmFailure>unavailable</revisionOnScmFailure>
<providerImplementations>
<svn>javasvn</svn>
</providerImplementations>
</configuration>
<dependencies>
<dependency>
<groupId>org.tmatesoft.svnkit</groupId>
<artifactId>svnkit</artifactId>
<version>1.8.9</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.5.0</version>
<executions>
<execution>
<configuration>
<executable>python</executable>
<arguments>
<argument>src/test/webapp/resources/grunt.py</argument>
</arguments>
</configuration>
<id>grunt-build</id>
<phase>test</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<packagingExcludes>WEB-INF/classes/dev.application.properties,WEB-INF/keycloak.json</packagingExcludes>
<webResources>
<resource>
<targetPath>WEB-INF/pages</targetPath>
<directory>src/main/webapp/WEB-INF/pages</directory>
<includes>
<include>Login.jsp</include>
<include>Banner.jsp</include>
</includes>
<filtering>true</filtering>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.7</version>
<configuration>
<dependencyLocationsEnabled>false</dependencyLocationsEnabled>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.6</version>
<configuration>
<formats>
<format>html</format>
<format>xml</format>
</formats>
</configuration>
</plugin>
</plugins>
</reporting>
<profiles>
<profile>
<id>jenkins</id>
<activation>
<property>
<name>env.BUILD_NUMBER</name>
</property>
</activation>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.7</version>
<configuration>
<formats>
<format>xml</format>
</formats>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>cobertura</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</profile>
</profiles>
</project>
Based on your Maven configuration, I can only assume that the file that cannot be found is WEB-INF/keycloak.json which does not reside in the root of the project.
Furthermore, I'll assume that your WEB-INF folder resides under src/main/webapp/WEB-INF within the root of your project, and that would explain why the file cannot be found with your current test configuration.
Based on my previous assumptions, the following should hopefully work for you.
#BeforeClass
public static void initContext() {
System.setProperty("spring.profiles.active", "dev");
System.setProperty("keycloak.configurationFile", "src/main/webapp/WEB-INF/keycloak.json");
}

Arquillian JPA tutorial: Could not create new instance of class org.jboss.arquillian.test.impl.EventTestRunnerAdaptor

I finished following the JPA tutorial at http://arquillian.org/guides/testing_java_persistence/ , but when I try to run the test ("Run the Test on GlassFish" section of the guide) as JUnit I obtain the following messages in Eclipse's console:
java.lang.RuntimeException: Could not create new instance of class org.jboss.arquillian.test.impl.EventTestRunnerAdaptor
at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:160)
at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:111)
at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:97)
at org.jboss.arquillian.test.spi.TestRunnerAdaptorBuilder.build(TestRunnerAdaptorBuilder.java:52)
at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:93)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:156)
... 10 more
Caused by: org.jboss.arquillian.container.impl.ContainerCreationException: Could not create Container glassfish-embedded
at org.jboss.arquillian.container.impl.LocalContainerRegistry.create(LocalContainerRegistry.java:85)
at org.jboss.arquillian.container.impl.client.container.ContainerRegistryCreator.createRegistry(ContainerRegistryCreator.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:135)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:115)
at org.jboss.arquillian.core.impl.ManagerImpl.bindAndFire(ManagerImpl.java:236)
at org.jboss.arquillian.core.impl.InstanceImpl.set(InstanceImpl.java:74)
at org.jboss.arquillian.config.impl.extension.ConfigurationRegistrar.loadConfiguration(ConfigurationRegistrar.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:135)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:115)
at org.jboss.arquillian.core.impl.ManagerImpl.start(ManagerImpl.java:261)
at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.<init>(EventTestRunnerAdaptor.java:56)
... 15 more
Caused by: java.lang.IllegalArgumentException: DeployableContainer must be specified
at org.jboss.arquillian.core.spi.Validate.notNull(Validate.java:44)
at org.jboss.arquillian.container.impl.ContainerImpl.<init>(ContainerImpl.java:71)
at org.jboss.arquillian.container.impl.LocalContainerRegistry.create(LocalContainerRegistry.java:76)
... 39 more
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.arquillian.example</groupId>
<artifactId>arquillian-tutorial</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>arquillian-tutorial</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>1.1.1.Final</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.8.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-integration</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>net.avh4.util</groupId>
<artifactId>imagecomparison</artifactId>
<version>0.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-6.0</artifactId>
<version>1.0.0.Final</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<!--<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-weld-ee-embedded-1.1</artifactId>
<version>1.0.0.CR3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-core</artifactId>
<version>1.1.5.Final</version>
<scope>test</scope>
</dependency>-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>1.2.0.Final</version>
<scope>provided</scope>
</dependency>
</dependencies>
<profile>
<id>arquillian-glassfish-embedded</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-glassfish-embedded-3.1</artifactId>
<version>1.0.0.CR3</version>
</dependency>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-web</artifactId>
<version>3.1.2</version>
</dependency>
</dependencies>
<build>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
<testResource>
<directory>src/test/resources-glassfish-embedded</directory>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<systemPropertyVariables>
<java.util.logging.config.file>
${project.build.testOutputDirectory}/logging.properties
</java.util.logging.config.file>
<derby.stream.error.file>
${project.build.directory}/derby.log
</derby.stream.error.file>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</project>
arquillian.xml
<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns="http://jboss.org/schema/arquillian"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<container qualifier="glassfish-embedded" default="true">
<configuration>
<property name="resourcesXml">
src/test/resources-glassfish-embedded/glassfish-resources.xml
</property>
</configuration>
</container>
</arquillian>
Game.java
package org.arquillian.example;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
public class Game implements Serializable {
private Long id;
private String title;
public Game() {}
public Game(String title) {
this.title = title;
}
#Id #GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#NotNull
#Size(min = 3, max = 50)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return "Game#" + hashCode() + "[id = " + id + "; title = " + title + "]";
}
}
GamePersistenceTest.java
package org.arquillian.example;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
import org.junit.Before;
import org.junit.After;
import java.util.List;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.junit.Assert;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
#RunWith(Arquillian.class)
public class GamePersistenceTest {
#Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addPackage(Game.class.getPackage())
.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
private static final String[] GAME_TITLES = {
"Super Mario Brothers",
"Mario Kart",
"F-Zero"
};
#PersistenceContext
EntityManager em;
#Inject
UserTransaction utx;
// tests go here
#Before
public void preparePersistenceTest() throws Exception {
clearData();
insertData();
startTransaction();
}
private void clearData() throws Exception {
utx.begin();
em.joinTransaction();
System.out.println("Dumping old records...");
em.createQuery("delete from Game").executeUpdate();
utx.commit();
}
private void insertData() throws Exception {
utx.begin();
em.joinTransaction();
System.out.println("Inserting records...");
for (String title : GAME_TITLES) {
Game game = new Game(title);
em.persist(game);
}
utx.commit();
// clear the persistence context (first-level cache)
em.clear();
}
private void startTransaction() throws Exception {
utx.begin();
em.joinTransaction();
}
#After
public void commitTransaction() throws Exception {
utx.commit();
}
private static void assertContainsAllGames(Collection<Game> retrievedGames) {
Assert.assertEquals(GAME_TITLES.length, retrievedGames.size());
final Set<String> retrievedGameTitles = new HashSet<String>();
for (Game game : retrievedGames) {
System.out.println("* " + game);
retrievedGameTitles.add(game.getTitle());
}
Assert.assertTrue(retrievedGameTitles.containsAll(Arrays.asList(GAME_TITLES)));
}
#Test
public void shouldFindAllGamesUsingCriteriaApi() throws Exception {
// given
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Game> criteria = builder.createQuery(Game.class);
Root<Game> game = criteria.from(Game.class);
criteria.select(game);
// TIP: If you don't want to use the JPA 2 Metamodel,
// you can change the get() method call to get("id")
criteria.orderBy(builder.asc(game.get(Game_.id)));
// No WHERE clause, which implies select all
// when
System.out.println("Selecting (using Criteria)...");
List<Game> games = em.createQuery(criteria).getResultList();
// then
System.out.println("Found " + games.size() + " games (using Criteria):");
assertContainsAllGames(games);
}
}
The pom.xml of the project has some of the profiles like arquillian-weld-ee-embedded, arquillian-glassfish-embedded, and arquillian-jbossas-managed.and none of them is active by default,so to make the Arquillian container workable,you need to make any of these profile default.
check the following pom.xml
` <dependenies>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>arquillian-jbossas-embedded</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<dependencies>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-6.0</artifactId>
<version>1.0.0.Final</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-weld-ee-embedded-1.1</artifactId>
<version>1.0.0.CR7</version>
</dependency>
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-core</artifactId>
<version>2.1.0.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.4</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<id>arquillian-jbossas-managed</id>
<dependencies>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-6.0</artifactId>
<version>1.0.0.Final</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.as</groupId>
<artifactId>jboss-as-arquillian-container-managed</artifactId>
<version>7.1.1.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.protocol</groupId>
<artifactId>arquillian-protocol-servlet</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
</profiles>

Resources