Getting error while connecting to jpa using micronaut-data-hibernate-jpa library - jpa

I want to use JPA for micronaut. For that I am using io.micronaut.data:micronaut-data-hibernate-jpa:1.0.0.M1 library. Whenever I run my application and hit the endpoint to get the data, I get the following error:
{
message: "Internal Server Error: No backing RepositoryOperations configured for repository. Check your configuration and try again"
}
I tried looking up for errors but I couldn't find one. Attaching my files here. Please help.
build.gradle
plugins {
id "net.ltgt.apt-eclipse" version "0.21"
id "com.github.johnrengelman.shadow" version "5.0.0"
id "application"
}
version "0.1"
group "micronaut.test"
repositories {
mavenCentral()
maven { url "https://jcenter.bintray.com" }
}
configurations {
// for dependencies that are needed for development only
developmentOnly
}
dependencies {
annotationProcessor platform("io.micronaut:micronaut-bom:$micronautVersion")
annotationProcessor "io.micronaut:micronaut-inject-java"
annotationProcessor "io.micronaut:micronaut-validation"
annotationProcessor "org.projectlombok:lombok:1.16.20"
annotationProcessor 'io.micronaut.data:micronaut-data-processor:1.0.0.M1'
implementation platform("io.micronaut:micronaut-bom:$micronautVersion")
compile 'io.micronaut.data:micronaut-data-hibernate-jpa:1.0.0.M1'
implementation "io.micronaut:micronaut-inject"
implementation "io.micronaut:micronaut-validation"
implementation "io.micronaut:micronaut-runtime"
implementation "io.micronaut:micronaut-http-server-netty"
implementation "io.micronaut:micronaut-http-client"
implementation 'nl.topicus:spanner-jdbc:1.1.5'
runtimeOnly "ch.qos.logback:logback-classic:1.2.3"
testAnnotationProcessor platform("io.micronaut:micronaut-bom:$micronautVersion")
testAnnotationProcessor "io.micronaut:micronaut-inject-java"
testImplementation "org.junit.jupiter:junit-jupiter-api"
testCompile "org.junit.jupiter:junit-jupiter-engine:5.1.0"
testImplementation "io.micronaut.test:micronaut-test-junit5"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine"
}
test.classpath += configurations.developmentOnly
mainClassName = "micronaut.test.Application"
// use JUnit 5 platform
test {
useJUnitPlatform()
}
tasks.withType(JavaCompile){
options.encoding = "UTF-8"
options.compilerArgs.add('-parameters')
}
shadowJar {
mergeServiceFiles()
}
run.classpath += configurations.developmentOnly
run.jvmArgs('-noverify', '-XX:TieredStopAtLevel=1', '-Dcom.sun.management.jmxremote')
Repository:
package micronaut.test.repo;
import io.micronaut.data.annotation.Repository;
import io.micronaut.data.repository.CrudRepository;
import micronaut.test.entity.Partner;
#Repository
public interface PartnerRepository extends CrudRepository<Partner,Integer> {
}
Service:
package micronaut.test.service;
import micronaut.test.entity.Partner;
import micronaut.test.repo.PartnerRepository;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
#Singleton
public class SpannerService {
private PartnerRepository partnerRepository;
#Inject
public SpannerService(PartnerRepository partnerRepository) {
this.partnerRepository = partnerRepository;
}
public List<Partner> getPartners() {
return (List<Partner>) partnerRepository.findAll();
}
}
Controller:
package micronaut.test.controller;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Produces;
import micronaut.test.entity.Partner;
import micronaut.test.service.SpannerService;
import javax.inject.Inject;
import java.util.List;
#Controller("/micronaut")
public class MainController {
private SpannerService spannerService;
#Inject
public MainController(SpannerService spannerService) {
this.spannerService = spannerService;
}
#Get("/data")
#Produces(MediaType.APPLICATION_JSON)
public List<Partner> getPartners() {
return spannerService.getPartners();
}
}
stacktrace:
io.micronaut.context.exceptions.ConfigurationException: No backing RepositoryOperations configured for repository. Check your configuration and try again
at io.micronaut.data.intercept.DataIntroductionAdvice.findInterceptor(DataIntroductionAdvice.java:108)
at io.micronaut.data.intercept.DataIntroductionAdvice.intercept(DataIntroductionAdvice.java:76)
at io.micronaut.aop.MethodInterceptor.intercept(MethodInterceptor.java:40)
at io.micronaut.aop.chain.InterceptorChain.proceed(InterceptorChain.java:150)
at micronaut.test.repo.PartnerRepository$Intercepted.findAll(Unknown Source)
at micronaut.test.service.SpannerService.getPartners(SpannerService.java:22)
at micronaut.test.controller.MainController.getPartners(MainController.java:32)
at micronaut.test.controller.$MainControllerDefinition$$exec2.invokeInternal(Unknown Source)
at io.micronaut.context.AbstractExecutableMethod.invoke(AbstractExecutableMethod.java:144)
at io.micronaut.context.DefaultBeanContext$BeanExecutionHandle.invoke(DefaultBeanContext.java:2792)
at io.micronaut.web.router.AbstractRouteMatch.execute(AbstractRouteMatch.java:235)
at io.micronaut.web.router.RouteMatch.execute(RouteMatch.java:122)
at io.micronaut.http.server.netty.RoutingInBoundHandler.lambda$buildResultEmitter$19(RoutingInBoundHandler.java:1408)
at io.reactivex.internal.operators.flowable.FlowableCreate.subscribeActual(FlowableCreate.java:71)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.internal.operators.flowable.FlowableMap.subscribeActual(FlowableMap.java:37)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.internal.operators.flowable.FlowableSwitchIfEmpty.subscribeActual(FlowableSwitchIfEmpty.java:32)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14868)
at io.micronaut.http.context.ServerRequestTracingPublisher.lambda$subscribe$0(ServerRequestTracingPublisher.java:52)
at io.micronaut.http.context.ServerRequestContext.with(ServerRequestContext.java:52)
at io.micronaut.http.context.ServerRequestTracingPublisher.subscribe(ServerRequestTracingPublisher.java:52)
at io.reactivex.internal.operators.flowable.FlowableFromPublisher.subscribeActual(FlowableFromPublisher.java:29)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.reactivex.internal.operators.flowable.FlowableSubscribeOn$SubscribeOnSubscriber.run(FlowableSubscribeOn.java:82)
at io.reactivex.internal.schedulers.ExecutorScheduler$ExecutorWorker$BooleanRunnable.run(ExecutorScheduler.java:288)
at io.reactivex.internal.schedulers.ExecutorScheduler$ExecutorWorker.run(ExecutorScheduler.java:253)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: io.micronaut.context.exceptions.NoSuchBeanException: No bean of type [io.micronaut.data.operations.RepositoryOperations] exists. Make sure the bean is not disabled by bean requirements (enable trace logging for 'io.micronaut.context.condition' to check) and if the bean is enabled then ensure the class is declared a bean and annotation processing is enabled (for Java and Kotlin the 'micronaut-inject-java' dependency should be configured as an annotation processor).
at io.micronaut.context.DefaultBeanContext.getBeanInternal(DefaultBeanContext.java:1903)
at io.micronaut.context.DefaultBeanContext.getBean(DefaultBeanContext.java:582)
at io.micronaut.data.intercept.DataIntroductionAdvice.findInterceptor(DataIntroductionAdvice.java:105)
... 43 common frames omitted

Micronaut currently supports only Tomcat JDBC, Apache DBCP2 and Hikari data sources providers out of the box (see https://micronaut-projects.github.io/micronaut-sql/latest/guide/#jdbc).
You can add this line into your build.gradle which adds Tomcat JDBC Data Source provider implementation into your project:
runtime "io.micronaut.configuration:micronaut-jdbc-tomcat"
Or you can choose another implementations like Apache DBCP2:
runtime "io.micronaut.configuration:micronaut-jdbc-dbcp"
Or Hikari:
runtime "io.micronaut.configuration:micronaut-jdbc-hikari"
For nl.topicus:spanner-jdbc data source provider you have to implement your own DatasourceFactory and DatasourceConfiguration for Micronaut because there is no one yet.
You can inspire your self in io.micronaut.configuration:micronaut-jdbc-tomcat. Sources are here: https://github.com/micronaut-projects/micronaut-sql/tree/master/jdbc-tomcat/src/main/java/io/micronaut/configuration/jdbc/tomcat
For example DatasourceFactory can then look like this:
#Factory
public class DatasourceFactory implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(DatasourceFactory.class);
private List<nl.topicus.jdbc.CloudSpannerDataSource> dataSources = new ArrayList<>(2);
private final DataSourceResolver dataSourceResolver;
/**
* Default constructor.
* #param dataSourceResolver The data source resolver
*/
public DatasourceFactory(#Nullable DataSourceResolver dataSourceResolver) {
this.dataSourceResolver = dataSourceResolver == null ? DataSourceResolver.DEFAULT : dataSourceResolver;
}
/**
* #param datasourceConfiguration A {#link DatasourceConfiguration}
* #return An Apache Tomcat {#link DataSource}
*/
#Context
#EachBean(DatasourceConfiguration.class)
public DataSource dataSource(DatasourceConfiguration datasourceConfiguration) {
nl.topicus.jdbc.CloudSpannerDataSource ds = new nl.topicus.jdbc.CloudSpannerDataSource();
ds.setJdbcUrl(datasourceConfiguration.getJdbcUrl());
...
dataSources.add(ds);
return ds;
}
#Override
#PreDestroy
public void close() {
for (nl.topicus.jdbc.CloudSpannerDataSource dataSource : dataSources) {
try {
dataSource.close();
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Error closing data source [" + dataSource + "]: " + e.getMessage(), e);
}
}
}
}
}
Anyway you can still use Google Cloud Spanner DB with Data Source providers like Hikari and Apache DBCP2. For example:
runtime 'nl.topicus:spanner-jdbc:1.1.5'
runtime "io.micronaut.configuration:micronaut-jdbc-hikari"
The first line adds JDBC driver and the second line adds Data Source provider which will use the spanner-jdbc JDBC driver.

It is known that the Google Cloud Spanner uses another dialect than other databases for Hibernate ORM. I think that this dialect is pretty new. Take a look over this repository 1. Maybe it will be useful for you, not necessary for solving your current issue, but giving you some other perspective.

Related

"java.lang.NoClassDefFoundError: Could not initialize class org.codehaus.groovy.vmplugin.v7.Java7" error when I try to run a REST Assured test class

I have JDK 1.8 installed and below is the class I run in Eclipse:
import io.restassured.RestAssured;
import static org.hamcrest.Matchers.equalTo;
import static io.restassured.RestAssured.given;
public class test {
public static void main(String[] args) {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
given()
.queryParam("posts", "1")
.body("")
.when()
.get()
.then()
.assertThat().statusCode(200)
.body("userId", equalTo(2));
}
}
I get the following error:
java.lang.NoClassDefFoundError: Could not initialize class org.codehaus.groovy.vmplugin.v7.Java7
at org.codehaus.groovy.vmplugin.VMPluginFactory.<clinit>(VMPluginFactory.java:43)
at org.codehaus.groovy.reflection.GroovyClassValueFactory.<clinit>(GroovyClassValueFactory.java:35)
at org.codehaus.groovy.reflection.ClassInfo.<clinit>(ClassInfo.java:107)
at org.codehaus.groovy.reflection.ReflectionCache.getCachedClass(ReflectionCache.java:95)
at org.codehaus.groovy.reflection.ReflectionCache.<clinit>(ReflectionCache.java:39)
at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.registerMethods(MetaClassRegistryImpl.java:209)
at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.<init>(MetaClassRegistryImpl.java:107)
at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.<init>(MetaClassRegistryImpl.java:85)
at groovy.lang.GroovySystem.<clinit>(GroovySystem.java:36)
at org.codehaus.groovy.runtime.InvokerHelper.<clinit>(InvokerHelper.java:86)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.createMap(ScriptBytecodeAdapter.java:635)
at io.restassured.internal.ResponseParserRegistrar.<init>(ResponseParserRegistrar.groovy)
at io.restassured.RestAssured.<clinit>(RestAssured.java:346)
at test.main(test.java:12)
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class org.codehaus.groovy.reflection.ReflectionCache
at org.codehaus.groovy.runtime.dgmimpl.NumberNumberMetaMethod.<clinit>(NumberNumberMetaMethod.java:33)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)
at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:350)
at java.base/java.lang.Class.newInstance(Class.java:645)
at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.createMetaMethodFromClass(MetaClassRegistryImpl.java:257)
at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.<init>(MetaClassRegistryImpl.java:110)
at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.<init>(MetaClassRegistryImpl.java:85)
at groovy.lang.GroovySystem.<clinit>(GroovySystem.java:36)
at org.codehaus.groovy.runtime.InvokerHelper.<clinit>(InvokerHelper.java:86)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.createMap(ScriptBytecodeAdapter.java:635)
at io.restassured.internal.ResponseParserRegistrar.<init>(ResponseParserRegistrar.groovy)
at io.restassured.RestAssured.<clinit>(RestAssured.java:346)
at test.main(test.java:12)
Run mvn dependency:tree to view the whole dependency tree. You check if you see a problem here.
And try upgrading the maven-plugin version.

JAX-RS not responding at all (404)

I'm using Eclipse 2020-03, Gradle and Tomcat. all I did follows.
Installing gradle through eclipse marketplace.
making gradle project.
adding those on build.gradle dependencies
dependencies {
// This dependency is exported to consumers, that is to say found on their compile classpath.
api 'org.apache.commons:commons-math3:3.6.1'
// This dependency is used internally, and not exposed to consumers on their own compile classpath.
implementation 'com.google.guava:guava:28.2-jre'
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.27'
compile group: 'org.glassfish.jersey.inject', name: 'jersey-hk2', version: '2.27'
compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.4.0-b180830.0359'
compile group: 'org.glassfish.jersey.media', name: 'jersey-media-json-jackson', version: '2.27'
}
adding "rest" package on src/main/java
adding ApplicationConfig.java and RestApiService.java on rest package.
ApplicationConfig.java
package rest;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("/api")
public class ApplicationConfig extends Application {
#Override
public Map<String, Object> getProperties(){
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("jersey.config.server.provider.packages", "A_UnivG.rest");
return properties;
}
}
RestApiService.java
package rest;
import java.util.logging.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import Data.*;
#Path("/Data")
public class RestApiService {
Logger logger = Logger.getLogger("RestApiService");
IntegrationDAO dao = new IntegrationDAO();
#GET
#Path("hello")
#Produces(MediaType.TEXT_PLAIN)
public String getHello() {return "Hello";}
}
and when I try to request http://localhost:portnumber/A_UnivG/api/Data/hello it spits out only 404 error.
cannot figure out why.
My project works with plain jsp files. I have a JSP page which uses DAO Read but it works just fine. well, that shouldn't be a problem I just tried hello world and it doesn't work at all.

When deploying a new feature config files are not loaded before bundles are started

I'm evaluating jboss fuse (using version 6.2.1.redhat-084), and i've run into the following issue:
I have a number of features in my project
Each feature has a configuration file
The feature repository file looks like this:
.
<?xml version="1.0" encoding="UTF-8"?>
<features name="myservice-features" xmlns="http://karaf.apache.org/xmlns/features/v1.2.0">
<feature name="myservice-common" version="${project.version}">
<configfile finalname="etc/com.myorg.myservice_common.cfg" override="true">mvn:com.myorg/myservice-common/${project.version}/cfg/${build.environment}</configfile>
<bundle start-level="100" dependency="true">mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.javax-cache-api/1.0.0_1</bundle>
<bundle start-level="100" dependency="true">mvn:org.apache.camel/camel-velocity/${camel.version}</bundle>
<bundle start-level="110">mvn:com.myorg/myservice-common/${project.version}</bundle>
</feature>
<feature name="myservice-impl" version="${project.version}">
<feature>myservice-common</feature>
<configfile finalname="etc/com.myorg.myservice.cfg" override="true">mvn:com.myorg/myservice-impl/${project.version}/cfg/${build.environment}</configfile>
<bundle start-level="200">mvn:com.hazelcast/hazelcast/${hazelcast.version}</bundle>
<bundle start-level="200">mvn:com.hazelcast/hazelcast-client/${hazelcast.version}</bundle>
<bundle start-level="220">mvn:com.myorg/myservice-impl/${project.version}</bundle>
</feature>
</features>
The service uses blueprint property placeholder with the corresponding PID to initialize the properties in the camel context
The issue is that when deploying the features in a profile, the configuration files are picked up by org.apache.felix.fileinstall only after the bundles are attempted to be resolved, and I run into the following exception:
.
2016-12-15 10:07:38,384 | ERROR | oyer-49-thread-1 | BlueprintContainerImpl | 23 - org.apache.aries.blueprint.core - 1.4.4 | Unable to start blueprint container for bundle otc-trade-service-impl/1.0.0.SNAPSHOT
org.osgi.service.blueprint.container.ComponentDefinitionException: Unable to initialize bean .camelBlueprint.factory.myservice-impl-context
at org.apache.aries.blueprint.container.BeanRecipe.runBeanProcInit(BeanRecipe.java:714)[23:org.apache.aries.blueprint.core:1.4.4]
...
Caused by: java.lang.IllegalArgumentException: Property placeholder key: xxxxx not found
at org.apache.camel.blueprint.BlueprintPropertiesParser.parseProperty(BlueprintPropertiesParser.java:164)
at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.doGetPropertyValue(DefaultPropertiesParser.java:306)[198:org.apache.camel.camel-core:2.15.1.redhat-621084]
at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.getPropertyValue(DefaultPropertiesParser.java:246)[198:org.apache.camel.camel-core:2.15.1.redhat-621084]
at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.readProperty(DefaultPropertiesParser.java:154)[198:org.apache.camel.camel-core:2.15.1.redhat-621084]
at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.doParse(DefaultPropertiesParser.java:113)[198:org.apache.camel.camel-core:2.15.1.redhat-621084]
at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.parse(DefaultPropertiesParser.java:97)[198:org.apache.camel.camel-core:2.15.1.redhat-621084]
at org.apache.camel.component.properties.DefaultPropertiesParser.parseUri(DefaultPropertiesParser.java:62)
at org.apache.camel.component.properties.PropertiesComponent.parseUri(PropertiesComponent.java:178)
at org.apache.camel.component.properties.PropertiesComponent.parseUri(PropertiesComponent.java:129)
at org.apache.camel.impl.DefaultCamelContext.resolvePropertyPlaceholders(DefaultCamelContext.java:1956)
at org.apache.camel.model.ProcessorDefinitionHelper.resolvePropertyPlaceholders(ProcessorDefinitionHelper.java:734)
at org.apache.camel.model.RouteDefinitionHelper.initRouteInputs(RouteDefinitionHelper.java:379)
... 47 more
This looks similar to issue https://issues.jboss.org/browse/ENTESB-593; however, looks like the 'fix' to that issue involved only having the configuration files copied into the ${karaf.base}/etc folder, but not actually triggering and synchronizing on karaf configuration manager before starting the bundles
I'm a bit stuck with this issue. Obviously I could just set 'start="false"' for my bundles and manually start all the camel context bundles after profile deployment, but I'd like to know if there is a more optimal solution.
I've come up up with the following hacky workaround so far:
Add a dependency for org.osgi:org.osgi.compendium:5.0.0 and org.osgi:org.osgi.core:5.0.0
Create the following BundleActivator class:
.
package com.myorg.common;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Dictionary;
public class ConfigurationActivator implements BundleActivator {
public static final String BUNDLE_CONFIGURATION_WATCH = "bundle.configuration.watch";
public static final String BUNDLE_SYMBOLIC_NAME = "bundle.symbolic.name";
private static final Logger LOG = LoggerFactory.getLogger(ConfigurationActivator.class);
private ServiceRegistration<org.osgi.service.cm.ConfigurationListener> listenerReg;
public void start(BundleContext context) throws Exception {
LOG.debug("Bundle " + context.getBundle().getSymbolicName() + " starting");
listenerReg = context.registerService(org.osgi.service.cm.ConfigurationListener.class,
new ConfigurationListener(context), null);
}
public void stop(BundleContext context) throws Exception {
LOG.debug("Bundle " + context.getBundle().getSymbolicName() + " stopping");
if (listenerReg != null) {
listenerReg.unregister();
}
}
public class ConfigurationListener implements org.osgi.service.cm.ConfigurationListener {
private BundleContext bundleContext;
public ConfigurationListener(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
public void configurationEvent(ConfigurationEvent configurationEvent) {
try {
if (configurationEvent.getType() == ConfigurationEvent.CM_UPDATED) {
LOG.debug("Configuration update event: " + configurationEvent.getPid());
Bundle bundle = bundleContext.getBundle();
LOG.trace("Bundle " + bundle.getSymbolicName() + " state: " + bundle.getState());
try {
Configuration configuration = bundleContext.getService(configurationEvent.getReference()).getConfiguration(configurationEvent.getPid());
if (configuration != null) {
Dictionary<String, Object> properties = configuration.getProperties();
if (properties != null) {
if (Boolean.TRUE.toString().equals(properties.get(BUNDLE_CONFIGURATION_WATCH))
&& bundle.getSymbolicName().equals(properties.get(BUNDLE_SYMBOLIC_NAME))) {
LOG.info("Updating bundle " + bundle.getSymbolicName() + " due to configuration change");
bundle.update();
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} catch (IllegalStateException se) {
LOG.warn("Bundle context has been invalidated");
}
}
}
}
Add this bundle activator to the bundle manifest
Add the following properties to your configuration file:
bundle.configuration.watch=true
bundle.symbolic.name=<bundle-name>
Deploy the feature. If the configuration has changed after the bundle has already attempted to start, the bundle will be updated
This still feels inelegant to me due to two reasons:
Additional configuration properties
The original issue will still cause confusing error messages in the logs during deployment
Can anyone suggest a better answer?

javax.naming.NoInitialContextException 2

I have create an EJB program with 2 interfaces, 1 persistente class and 1 stateless class which implement the 2 interfaces (Remote interface and Local interface)
After that I've create a Java Client with 1 class and I add jboss-client.jar to classpath of java client app and jboss-ejb-client.properties files. But when I run the java client it's generate an error.
I need your help to fix it. Thank you.
ClientEJB.java
package main;
import java.util.Properties;
import javax.naming.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import metier.ICatalogueRemote;
import metier.Produit;
public class ClientEJB {
public static void main(String[] args) {
try{
Properties p = new Properties();
p.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
Context ctx = new InitialContext(p);
ICatalogueRemote stub = (ICatalogueRemote) ctx.lookup("ejb:/CatalogueEJB/CAT!metier.ICatalogueRemote");
stub.addProduit(new Produit("HP",8000));
stub.addProduit(new Produit("Clé usb ZTE", 5000));
stub.addProduit(new Produit("HP ProBook 4700", 10000));
}catch(NamingException ex){
ex.printStackTrace();
}
}
}
# jboss-ejb-client.properties
#
endpoint.name=client-endpoint
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host=127.0.0.1
remote.connection.default.port = 1234
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
#remote.connection.default.username=root
#remote.connection.default.password=
ERROR MESSAGE GENERATE WHEN I RUN THE APPLICATION
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at main.ClientEJB.main(ClientEJB.java:18)
you need one more jndi.properties file including below code
java.naming.factory.url.pkgs=org.jboss.ejb.client.naming
java.naming.provider.url=remote://cie-pftestvm2:4447
java.naming.security.principal=jmstest
java.naming.security.credentials=admin#123

Java EE 6 + JPA - Exception: Message Driven Bean cant be managed bean

I create an Enterprise Application CustomerApp that also generated two projects CustomerApp-ejb and CustomerApp-war. In the CustomerApp-ejb, I create a SessionBean call CustomerSessionBean.java as below.
package com.customerapp.ejb;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
#LocalBean
public class CustomerSessionBean {
#PersistenceContext(unitName = "CustomerApp-ejbPU")
private EntityManager em;
public void persist(Object object) {
em.persist(object);
}
}
Now I can deploy CustomerApp-war just fine. But as soon as I create a Message Driven Bean, I cant deploy CustomerApp-war anymore. When I create NotificationBean.java (message driven bean), In the project destination option, I click add, and have NotificationQueue for the Destination Name and Destination Type is Queue. Below are the code
package com.customerapp.mdb;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
#MessageDriven(mappedName = "jms/NotificationQueue", activationConfig = {
#ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class NotificationBean implements MessageListener {
public NotificationBean() {
}
public void onMessage(Message message) {
}
}
The server log said Message Driven Bean cant be managed bean. Well I did not mean it to be managed bean. I did not have #ManagedBean in the code????
EDIT: Here is the server log
[#|2010-06-03T10:02:08.172-0400|SEVERE|glassfishv3.0|javax.enterprise.system.core.com.sun.enterprise.v3.server|_ThreadID=24;_ThreadName=Thread-1;|Exception while loading the app org.glassfish.deployment.common.DeploymentException: Message Driven Beans can't be Managed Beans
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:169)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:125)
at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:224)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:338)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:183)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:272)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:305)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:320)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1176)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$900(CommandRunnerImpl.java:83)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1235)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1224)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:365)
at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:204)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:166)
at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:100)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:245)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at java.lang.Thread.run(Thread.java:637)
Caused by: org.jboss.weld.DefinitionException: Message Driven Beans can't be Managed Beans
at org.jboss.weld.bean.SessionBean.checkEJBTypeAllowed(SessionBean.java:313)
at org.jboss.weld.bean.SessionBean.initialize(SessionBean.java:122)
at org.jboss.weld.bootstrap.AbstractBeanDeployer.deploy(AbstractBeanDeployer.java:111)
at org.jboss.weld.bootstrap.BeanDeployment.deployBeans(BeanDeployment.java:151)
at org.jboss.weld.bootstrap.WeldBootstrap.deployBeans(WeldBootstrap.java:367)
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:167)
... 30 more
The Exception is DeploymentException: Message Driven Beans can't be Managed Beans
This is a bug in GlassFish 3.0 which is fixed in 3.0.1.
workaround: remove the beans.xml (but this will disable CDI)
real solution: download a promoted build of GlassFish 3.0.1 (the problem is reported as being fixed in version 3.0.1-b9 so any superior version should work)
Below the initial answer:
Where is the MDB located? Did you put it in the CustomerApp-ejb?
What do you mean by Now I can deploy CustomerApp-war just fine? You're supposed to deploy the Enterprise application (CustomerApp).
What do you see in the GlassFish logs when the deployment fails?