I created a simple Kotlin Quarkus application that connects to my local MongoDB instance following the official guide.
The connection works, however it seems that it fails to inject the MongoClient/ReactiveMongoClient like so:
...
import com.mongodb.client.MongoClient
...
#ApplicationScoped
open class KotlinService #Inject constructor(private val mongoClient: MongoClient) {
fun getCollection(): MongoCollection<Document> = mongoClient.getDatabase("test").getCollection("hello")
}
Calling getCollection() results in:
org.jboss.resteasy.spi.UnhandledException: java.lang.NullPointerException
at org.jboss.resteasy.core.ExceptionHandler.handleApplicationException(ExceptionHandler.java:106)
at org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:372)
at org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:209)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:496)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:252)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:153)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:363)
at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:156)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:238)
at io.quarkus.resteasy.runtime.standalone.RequestDispatcher.service(RequestDispatcher.java:73)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatch(VertxRequestHandler.java:118)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.lambda$handle$0(VertxRequestHandler.java:74)
at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$2(ContextImpl.java:316)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.NullPointerException
at ...service.KotlinService.getCollection(KotlinService.kt:12)
at ...resource.ReceiptResource.getAll(ReceiptResource.kt:19)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
.....
If I rewrite the class in Java instead it works fine:
...
import com.mongodb.client.MongoClient;
...
#ApplicationScoped
public class JavaService {
private MongoClient mongoClient;
#Inject
public JavaService(MongoClient mongoClient) {
this.mongoClient = mongoClient;
}
public MongoCollection<Document> getCollection() {
return mongoClient.getDatabase("test").getCollection("hello");
}
}
A bug or am I missing something here?
Update
Reported as a bug on github.
Related
I am migrating the spring boot app from spring boot 1.5.4 to spring boot 2.7.5, In old code I have hibernate at DAO layer. (does the migration caused the issue, I did not find very particular about the issue )
properties file has connection details and used below key
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
Application class have following annotations,
#EnableTransactionManagement #EnableJpaRepositories(basePackages = {"repository package"}) #ComponentScan(basePackages = {"base package"}) #EntityScan(basePackages = {"entity package"})
DAO code :
private EntityManager entityManager;
private Session getSession() {
return entityManager.unwrap(Session.class);
}
// problematic code
public void doSomething(){
String hqlBuilder = "Update Query statement"
Query query = getSession().createQuery(hqlBuilder);
int result = query.executeUpdate();
}```
Service code:
Service class has #Transctional defined at class level however it throws exception on invoking the doSomething() method on DAO instance
`**Caused by: javax.persistence.TransactionRequiredException: Executing an update/delete query**
at org.hibernate.internal.AbstractSharedSessionContract.checkTransactionNeededForUpdateOperation(AbstractSharedSessionContract.java:445)
at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1692)
at <removed the package path>.dao.impl.LastViewedHistoryElementDaoHibernate.insertOrUpdate(LastViewedHistoryElementDaoHibernate.java:122)
at impl.LastViewedHistoryElementDaoHibernate$$FastClassBySpringCGLIB$$f8fba493.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
... 271 common frames omitted`
**In DAO method returns it throws the TransactionRequiredException : No Transaction in progress**
Thank you, I did applied the #EnableTransactionManagement #Transactional, added spring jpa. I did configure Transaction manager in config also however not luck,
```#Autowired
HikariDataSource dataSource;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setPackagesToScan(
new String[]{"<My packages>"});
//sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public PlatformTransactionManager transactionManager() {
HibernateTransactionManager hibernateTransactionManager
= new HibernateTransactionManager();
hibernateTransactionManager.setSessionFactory(sessionFactory().getObject());
return hibernateTransactionManager;
}```
but still same error as Caused by: javax.persistence.TransactionRequiredException: no transaction is in progress
at org.hibernate.internal.AbstractSharedSessionContract.checkTransactionNeededForUpdateOperation(AbstractSharedSessionContract.java:445)
at org.hibernate.internal.SessionImpl.checkTransactionNeededForUpdateOperation(SessionImpl.java:3496)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1399)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1394)
at org.springframework.orm.hibernate5.SessionFactoryUtils.flush(SessionFactoryUtils.java:113)
at org.springframework.orm.hibernate5.SpringSessionSynchronization.beforeCommit(SpringSessionSynchronization.java:95)
at org.springframework.transaction.support.TransactionSynchronizationUtils.triggerBeforeCommit(TransactionSynchronizationUtils.java:97)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerBeforeCommit(AbstractPlatformTransactionManager.java:916)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:727)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:407)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708)
Can't get Feign Client to work. First tried with POST. Kept running into errors related to Encoder/Decoder saying type is not right.
Then found an example on github to call simple GET API finally and decided to give it a shot.
Still fails
On Github and online, I am seeing multiple versions of Feign Client
Spring-Cloud, OpenFeign, Netflix.feign having different versions.
Could anyone describe what's the best and stable Feign client one should use for production?
package com.paa.controllers;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#FeignClient (name="test-service",url="https://www.reddit.com/r")
public interface GetFeignClient {
#RequestMapping(method = RequestMethod.GET, value = "/java.json")
public String posts();
}
Controller:
#RestController
#RequestMapping("/some/api")
public class TestWLCController {
#Autowired
private GetFeignClient getFeignClient;
.. some stuff
#RequestMapping(value="/postSomething",method = RequestMethod.POST)
#ApiOperation(value = "Configures something",
notes = "basic rest controller for testing feign")
public ResponseEntity<SomeResponse> feignPost(
UriComponentsBuilder builder,
#ApiParam(name = "myRequest",
value = "request for configuring something",
required = true)
#Valid #RequestBody SomeRequest someRequest) {
String resp = null;
try {
resp = getFeignClient.posts();
} catch (Exception er) {
er.printStackTrace();
}
}
}
Application:
Tried all possible permutations of annotations thinking it would resolve AutoWire stuff but still fails
#Configuration
#ComponentScan
#EnableAutoConfiguration
//#EnableEurekaClient
#EnableFeignClients
//#SpringBootApplication
//#EnableFeignClients
//#EnableFeignClients(basePackages = {"com.paa.xenia.controllers", "com.paa.xenia.services"})
public class ServiceApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(XeniaServiceApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}
2016-07-20 18:15:42.406[0;39m [31mERROR[0;39m [35m32749[0;39m
[2m---[0;39m [2m[ main][0;39m
[36mo.s.boot.SpringApplication [0;39m [2m:[0;39m
Application startup failed
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'testWLCController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private com.paa.controllers.GetFeignClient
com.paa.controllers.TestWLCController.gfClient; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'com.aa..controllers.GetFeignClient':
FactoryBean threw exception on object creation; nested exception is
java.lang.NullPointerException at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
~[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE] at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766)
[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE] at
org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361)
[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:307)
[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1191)
[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1180)
[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE] at
com.paa.ServiceApplication.main(ServiceApplication.java:44) [bin/:na]
Caused by: org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private com.paa.controllers.GetFeignClient
com.paa.controllers.TestWLCController.gfClient; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'com.paa.controllers.GetFeignClient':
FactoryBean threw exception on object creation; nested exception is
java.lang.NullPointerException at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] ... 17 com.n frames
omitted
I'm not sure if you eventually figured it out yourself, but for the sake of others who might stumble across this thread, below is a working example of what you were trying to do. I'll first point out a few things that are incorrect, or at least, not desired in your code, then show my code that works.
You should try not to use the url attribute. Instead, set up a list of servers using <feign client name>.ribbon.listOfServers in bootstrap.yml (or bootstrap.properties). This allows for client side load balancing because listOfServers can be a comma-separated list.
Using Ribbon for HTTPS connections, you need to specify two things that you don't need for HTTP connections. The port, which is part of the listOfServers and <feign client name>.ribbon.IsSecure: true. Without the port, the connection is made to port 80 and without the IsSecure, HTTP is used.
Testing using curl, I found that Reddit takes a very long time to respond. See this SO post for details of how to break down the total time taken by the request-response cycle.
$ curl -v -H "User-Agent: Mozilla/5.0" -w "#curl-format.txt" -o /dev/null -s "https://www.reddit.com/r/java/top.json?count=1"
{ [2759 bytes data]
* Connection #0 to host www.reddit.com left intact
time_namelookup: 0.527
time_connect: 0.577
time_appconnect: 0.758
time_pretransfer: 0.758
time_redirect: 0.000
time_starttransfer: 11.189
----------
time_total: 11.218
According the Netflix Wiki, the default read and connect timeouts are 3000 milliseconds, so you will always timeout unless you change those.
You may have noticed that I specified a User-Agent header in the curl request. That's because Reddis seems to be very picky about that and if not specified, returns a HTTP 429 "Too many requests" most of the times. They don't return a Retry-After header in the response so there's no telling how long you need to wait before making another request.
Spring Cloud Netflix as well as Netflix Feign is open source, so some (a lot of) patience and debugging skills come really handy.
"Talk is cheap. Show me the code." (Torvalds, Linus (2000-08-25)).
I generated a Gradle app using the excellent Spring Initializr site. Here's a snippet from the build.gradle file.
dependencies {
compile('org.springframework.cloud:spring-cloud-starter-feign')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Camden.SR3"
}
}
Feign client:
#FeignClient(name = "reddit")
public interface RedditClient {
#RequestMapping(method = GET, value = "/r/java/top.json?count=1",
headers = {USER_AGENT + "=Mozilla/5.0", ACCEPT + "=" + APPLICATION_JSON_VALUE})
public String posts();
}
Boot Application:
#SpringBootApplication
#EnableFeignClients
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#RestController
static class DemoController {
#Autowired
private RedditClient redditClient;
#GetMapping("/posts")
public String posts() {
return redditClient.posts();
}
}
}
bootstrap.yml:
reddit:
ribbon:
listOfServers: www.reddit.com:443
ConnectTimeout: 20000
ReadTimeout: 20000
IsSecure: true
hystrix.command.default.execution:
timeout.enabled: true
isolation.thread.timeoutInMilliseconds: 50000
Integration test:
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DemoApplicationTest {
#Autowired
private TestRestTemplate restTemplate;
#Test
public void testGetPosts() {
ResponseEntity<String> responseEntity = restTemplate.getForEntity("/posts", String.class);
HttpStatus statusCode = responseEntity.getStatusCode();
assertThat(String.format("Actual status code: %d, reason: %s.",
statusCode.value(), statusCode.getReasonPhrase()),
statusCode.is2xxSuccessful(), equalTo(true));
}
}
Dependencies:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Greenwich.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
App:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.test.cloud.bookservice.models.Book;
#SpringBootApplication
#RestController
#RequestMapping("/books")
#EnableFeignClients
public class BookServiceApplication {
Logger logger = LogManager.getLogger(BookServiceApplication.class);
#Autowired
private StoreClient storeClient;
public static void main(String[] args) {
SpringApplication.run(BookServiceApplication.class, args);
}
#GetMapping("/book")
public Book findBook() {
return this.restTemplate.getForObject("http://stores/book", Book.class);
}
#FeignClient(name = "StoreClient", url = "127.0.0.1:8089")
interface StoreClient {
#RequestMapping(method = RequestMethod.GET, value = "/stores/book", consumes = "application/json")
Book getBook();
}
}
Someone was interested to find out how did we do it so posting answer for their benefit.
Parent Module
package com.hitech.module.base;
#EnableFeignClients
public abstract class BaseApplication extends SpringBootServletInitializer {
...
..
}
build.gradle:
buildscript {
ext {
springBootVersion = '1.3.5.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("io.spring.gradle:dependency-management-plugin:0.5.6.RELEASE")
}
}
...
...
dependencies {
compile('io.springfox:springfox-swagger-ui:2.5.0')
compile('io.springfox:springfox-swagger2:2.5.0')
compile('org.springframework.cloud:spring-cloud-starter-feign')
Child Module
package com.hitech.module.app;
import com.hitech.module.base.BaseApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
#SpringBootApplication(exclude = {MongoDataAutoConfiguration.class, MongoAutoConfiguration.class},
scanBasePackages = {"com.hitech.module.base", "com.hitech.module.app", })
#EnableFeignClients("com.hitech.module.app.clients")
public class MyServiceApplication extends BaseApplication {
private static final Logger LOG = LoggerFactory.getLogger(MyServiceApplication.class);
public static void main(String[] args) {
String s1 = "google";
LOG.info ("=== Started Orchestration Service ===");
SpringApplication.run(MyServiceApplication.class, args);
}
}
bootstrap.yml
feign:
hystrix:
enabled: false
datasource:
audit:
mongodb:
host: localhost
port: 27019
database: audit
I've got a problem with EJB/Glassfish. I'm working on a client-server application in which the client creates an entity object and must send it to the server application, which must persist the entity in its database. I've choose to use session beans to communicate with the server.
I've implemented some simple cases in which a method in the session bean takes as input a string or an int and it works fine. The problem arises when I try to give an entity object as input.
I report my entity class:
#Entity
public class Example implements Serializable {
private static final long serialVersionUID = 1L;
#Id
String nome;
public void setNome(String nome) {
this.nome = nome;
}
public String getNome() {
return nome;
}
Here my session bean:
#Stateless
public class GestoreLibreriaRemoto implements GestoreLibreriaRemotoRemote {
#Override
public String getProva(Example prova) {
return prova.getNome();
}
Here my client application:
public class GestoreLibreriaLocale {
public static void assegnaCategoriaACopia(CopiaUtente copia, Categoria categoria) throws
public void prova() {
GestoreLibreriaRemotoRemote gestore = lookupGestoreLibreriaRemotoRemote();
Example example = new Example();
prova.setNome("hodor");
System.out.println(gestore.getProva(example));
}
private GestoreLibreriaRemotoRemote lookupGestoreLibreriaRemotoRemote() {
try {
Context c = new InitialContext();
return (GestoreLibreriaRemotoRemote) c.lookup("java:global/ServerMDB/ServerMDB-ejb/GestoreLibreriaRemoto");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
In my main class I simply call GestoreLibreriaLocale.prova() and i get the following error:
java.lang.reflect.InvocationTargetException
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:483)
at org.glassfish.appclient.client.acc.AppClientContainer.launch(AppClientContainer.java:446)
at org.glassfish.appclient.client.AppClientFacade.main(AppClientFacade.java:166)
Caused by: javax.ejb.EJBException: java.rmi.MarshalException: CORBA MARSHAL 1330446346 Maybe; nested exception is:
org.omg.CORBA.MARSHAL: ----------BEGIN server-side stack trace----------
org.omg.CORBA.MARSHAL: AVVERTENZA: 00810010: Error from readValue on ValueHandler in CDRInputStream vmcid: OMG minor code: 10 completed: Maybe
at com.sun.proxy.$Proxy139.valuehandlerReadError(Unknown Source)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.readRMIIIOPValueType(CDRInputStream_1_0.java:912)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.read_value(CDRInputStream_1_0.java:1005)
at com.sun.corba.ee.impl.encoding.CDRInputObject.read_value(CDRInputObject.java:518)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl$14.read(DynamicMethodMarshallerImpl.java:383)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.readArguments(DynamicMethodMarshallerImpl.java:450)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:171)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.sun.corba.ee.impl.io.IIOPInputStream
at com.sun.corba.ee.impl.io.ValueHandlerImpl.createInputStream(ValueHandlerImpl.java:820)
at com.sun.corba.ee.impl.io.ValueHandlerImpl.readValue(ValueHandlerImpl.java:263)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.readRMIIIOPValueType(CDRInputStream_1_0.java:903)
... 16 more
The error log continues, I don't report the whole log but if you need it I can post it.
Please help me, I'm working on it from days without resolving it.
Thanks for the attention,
Francesco
This seems to be a bug in the current Java versions (e.g. 1.7.0_55 and 1.8.0_05), have a look at this issue: GLASSFISH-21047
To make it work, install either an older or a newer Java version (e.g. 1.7.0_051 or 1.8.0_020).
See also:
Exception inside CORBA when accessing a remote bean
My ejb 3 classes and remote interface are as follows :
package com.myeclipse.ejb3;
import java.io.Serializable;
public interface IMyBean extends Serializable
{
public void doSomething();
}
Remote interface:
package com.myeclipse.ejb3;
import javax.ejb.Remote;
#Remote
public interface MyBeanRemote extends IMyBean {
}
Stateless ejb:
package com.myeclipse.ejb3;
import javax.ejb.Stateless;
#Stateless(mappedName="ejb/MyBean")
public class MyBean implements MyBeanRemote
{
public void doSomething()
{
System.out.println("Hello world");
}
}
Project is successully deployed as a jar file in weblogic. I developed
a standalone client to call ejb. But this is failing. Kindly help.
I've included all the weblogic server libraries to connect to jndi and
remote business interface for complilation.
Client Code :
package Ejb3_Client;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class MyBeanClient {
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
try {
Properties p = new Properties();
p.put("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory");
p.put("java.naming.provider.url", "t3://172.21.123.70:8001");
InitialContext ctx = new InitialContext(p);
MyBeanRemote bean = (MyBeanRemote) ctx.lookup("ejb/MyBean#com.myeclipse.ejb3.MyBeanRemote");
System.out.println("bean instance "+ bean);
bean.doSomething();
System.out.println("bean worked");
} catch (NamingException e) {
e.printStackTrace();
}
}
}
But I am getting this exception:
javax.naming.CommunicationException [Root exception is
java.rmi.UnmarshalException: failed to unmarshal class
java.lang.Object; nested exception is:
java.lang.ClassNotFoundException: com.myeclipse.ejb3.MyBeanRemote]
at
weblogic.jndi.internal.ExceptionTranslator.toNamingException(ExceptionTranslator.java:74)
at
weblogic.jndi.internal.WLContextImpl.translateException(WLContextImpl.java:439)
at
weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:395)
at
weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:380)
at javax.naming.InitialContext.lookup(InitialContext.java:392) at
Ejb3_Client.MyBeanClient.main(MyBeanClient.java:33) Caused by:
java.rmi.UnmarshalException: failed to unmarshal class
java.lang.Object; nested exception is:
java.lang.ClassNotFoundException: com.myeclipse.ejb3.MyBeanRemote at
weblogic.rjvm.ResponseImpl.unmarshalReturn(ResponseImpl.java:244) at
weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:348)
at
weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:259)
at weblogic.jndi.internal.ServerNamingNode_1030_WLStub.lookup(Unknown
Source) at
weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:392)
... 3 more Caused by: java.lang.ClassNotFoundException:
com.myeclipse.ejb3.MyBeanRemote at
java.net.URLClassLoader$1.run(URLClassLoader.java:200) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:188) at
java.lang.ClassLoader.loadClass(ClassLoader.java:307) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at
java.lang.ClassLoader.loadClass(ClassLoader.java:252) at
weblogic.ejb.container.internal.RemoteBusinessIntfProxy.readObject(RemoteBusinessIntfProxy.java:200)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597) at
java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
at
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1849)
at
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at
java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
at
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
at
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at
weblogic.utils.io.ChunkedObjectInputStream.readObject(ChunkedObjectInputStream.java:197)
at
weblogic.rjvm.MsgAbbrevInputStream.readObject(MsgAbbrevInputStream.java:564)
at
weblogic.utils.io.ChunkedObjectInputStream.readObject(ChunkedObjectInputStream.java:193)
at weblogic.rmi.internal.ObjectIO.readObject(ObjectIO.java:62) at
weblogic.rjvm.ResponseImpl.unmarshalReturn(ResponseImpl.java:240) ...
7 more
I searched a lot but din find the problem why it can't unmarshel remote interface.
the reason for above error mainly because in some java file which implements Serializable interface has been changed you can revert those files to previous version
I am following a tutorial mention on code.google, but my example fails giving the following trace :
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.google.code.morphia.mapping.MappedClass.callLifecycleMethods(MappedClass.java:323)
at com.google.code.morphia.mapping.Mapper.toDBObject(Mapper.java:371)
at com.google.code.morphia.DatastoreImpl.entityToDBObj(DatastoreImpl.java:674)
at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:722)
at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:802)
at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:796)
at models.com.vlist.activity.classes.TestMongoData.testUserData(TestMongoData.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
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.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.code.morphia.mapping.MappedClass.callLifecycleMethods(MappedClass.java:304)
... 28 more
Caused by: java.lang.UnsupportedOperationException: Please override this method for user marked Id field entity: models.com.vlist.activity.classes.User
at play.modules.morphia.Model.setId_(Model.java:284)
at play.modules.morphia.Model.generateId_(Model.java:299)
... 33 more
My example is as following:
import javax.persistence.Entity;
import org.bson.types.ObjectId;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.annotations.Id;
import play.modules.morphia.Model;
#Entity
public class User extends Model {
#Id ObjectId id;
private String firstName;
private String lastName;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName(){
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
}
and
import static org.junit.Assert.*;
import org.junit.Test;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
public class TestMongoData {
#Test
public void testUserData() {
User user = new User();
user.setFirstName("first");
user.setLastName("last");
Morphia morphia = new Morphia();
Datastore ds = morphia.createDatastore("testData");
ds.save(user);
}
}
What could be wrong?
Update:
When I use play test, i see the following:
08:01:55,783 ERROR ~
#66h1bm10d
Internal Server Error (500) for request GET /#tests
Compilation error (In {module:morphia}/app/morphia/Filter.java around line 8)
The file {module:morphia}/app/morphia/Filter.java could not be compiled. Error raised is : The type Filter is already defined
play.exceptions.CompilationException: The type Filter is already defined
at play.classloading.ApplicationCompiler$2.acceptResult(ApplicationCompiler.java:246)
at org.eclipse.jdt.internal.compiler.Compiler.handleInternalException(Compiler.java:672)
at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:516)
at play.classloading.ApplicationCompiler.compile(ApplicationCompiler.java:278)
at play.classloading.ApplicationClassloader.getAllClasses(ApplicationClassloader.java:406)
at play.Play.start(Play.java:453)
at play.Play.detectChanges(Play.java:574)
at play.Invoker$Invocation.init(Invoker.java:186)
at Invocation.HTTP Request(Play!)
The problem comes from your #Entity definition. You're using JPA annotation while you should use the Morphia ones.
On startup, the Morphia plugin will retrieve all classes marked with the morphia Entity annotation and enhance them with various injected model methods. You're receiving this exception because your model class hasn't been enhanced.
If you annotate #Id then play morphia won't enhance your model by providing right implementation for void setId_(Object id) method. Try defining one yourself like this.
#Entity
class User extends Model {
#Id String email;
protected void setId_(Object id) {
}
}
Try removing the #Id ObjectId id; from your model. The Morphia Module for Play Framework will add the id for you.
Then make the fields public and remove the getter/setter methods.
public String firstName;
public String lastName;
Also, your Entity import is incorrect. Try this
import com.google.code.morphia.annotations.Entity;
Try this for a test case:
import static org.junit.Assert.*;
import org.junit.Test;
import play.test.UnitTest;
public class TestMongoData extends UnitTest {
#Test
public void testUserData() {
User user = new User();
user.setFirstName("first");
user.setLastName("last");
user.save();
}
}
It's seems that you have defined the morphia module in the dependency file and in the application conf file.
In the dependencies file : - play -> morphia [1.2.1beta6,)
In the application conf file : module.morphia=${play.path}/modules/morphia
You must removed one of this declaration otherwise the morphia module is loaded twice ...