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

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?

Related

Liberty class loading issues or problem with hibernate (migrating tomcat app on liberty)?

i have to deploy a multi-module application in ear on Liberty Server 20 in my Eclipse. This application use hibernate as provider jpa2 and Derby client + driver derby-10.12.1.1.jar(as shared fileset). Persistence.xml is configured with non jta.
This is server.xml:
<enterpriseApplication id="rubrica-ear" location="rubrica-ear.ear" name="rubrica-ear"/>
<dataSource jndiName="jdbc/TestappDS" type="javax.sql.ConnectionPoolDataSource">
<properties.derby.client createDatabase="false" databaseName=".rubrica"></properties.derby.client>
<jdbcDriver>
<library>
<fileset dir="C:\programmiMio\java-eclipse\drivers" id="shared"></fileset>
</library>
</jdbcDriver>
</dataSource>
My .rubrica db location is in /usr/home.
Because I dont want to start a server derby on console but automatically, i do taht in a #WebListener class:
#WebListener
public class ReqListener implements ServletContextListener {
static final Logger log = LoggerFactory.getLogger(ReqListener.class);
PrintWriter pw = new PrintWriter(System.out);
private NetworkServerControl derbyserver;
#Override
public void contextInitialized(ServletContextEvent arg0) {
try {
String userHomeDir = System.getProperty("user.home", ".");
String systemDir = userHomeDir + "/.rubrica";
// Set the db system directory and startup Server Derby for incoming connections.
System.setProperty("derby.system.home", systemDir);//il db viene salvato qui
derbyserver = new NetworkServerControl(InetAddress.getByName("localhost"), 1527);
derbyserver.start(pw);
log.info("Apache derby settings ok");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error(e.getMessage());
}
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
if (derbyserver!=null){
...
}
}
When i deploy i get this error
[ERROR] An error occurred in the org.hibernate.ejb.HibernatePersistence persistence provider when attempting to create the entity manager factory of the testapp persistence unit container. The following error occurred: java.lang.NullPointerException
at org.hibernate.engine.jdbc.spi.TypeInfo.extractTypeInfo(TypeInfo.java:128)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:163)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849)
at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:67)
at com.ibm.ws.jpa.management.JPAPUnitInfo.createEMFactory(JPAPUnitInfo.java:919)
at [internal classes]
When I debug on Liberty i see that Hibernate classes running before the #WebListener code (this is not the same thing in Tomcat), how can i resolve this issue? Something about class loading settings?
I try derby Embedded instead, but problem still araise again, in server.xml:
<properties.derby.embedded createDatabase="create" databaseName="C:/Users/myuser/.rubrica" shutdownDatabase="false"/>
<jdbcDriver>
<library>
<fileset dir="C:\programmiMio\java-eclipse\drivers" id="shared-libs"/>
</library>
</jdbcDriver>
Thanks
Roberto

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

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.

How to use replicated Infinispan cache in Wildfly standalone-full-ha

I would like to use a replicated Infinispan cache using two Wildfly standalone instances. I want to insert a value on one node and I should be able to read it on the other node.
Here's what I tried:
I unzipped the full WF10 distribution using two different virtual
maschines running Debian Jessie.
I run both maschines with the standalone-full-ha.xml config.
I changed the binding from localhost to the IP adresses of the VMs -
all ports are reachable from outside.
I added another cache by inserting the following code to the config:
<subsystem xmlns="urn:jboss:domain:infinispan:4.0">
<cache-container name="monitor" default-cache="default">
<transport lock-timeout="60000"/>
<replicated-cache name="default" mode="SYNC">
<transaction mode="BATCH"/>
</replicated-cache>
</cache-container>
...
The rest of the configuration is not modified.
On both nodes I get the following log entries (my interpretation is -
both nodes see each other):
2016-03-13 11:19:43,160 INFO [org.infinispan.remoting.transport.jgroups.JGroupsTransport] (MSC service thread 1-1) ISPN000094: Received new cluster view for channel monitor: [wf1|5] (2) [wf1, wf2]
On one node I created a cache writer. On the other node a cache
reader is deployed:
#Singleton
#Startup
public class CacheWriter {
private final static Logger LOG = LoggerFactory.getLogger(CacheWriter.class);
#Resource(lookup = "java:jboss/infinispan/container/monitor")
private EmbeddedCacheManager cacheManager;
private Cache<String, String> cache;
#PostConstruct
public void init() {
cache = cacheManager.getCache();
LOG.info("Cache name: " + cache.getName());
}
#Schedule(hour = "*", minute = "*", second = "0", persistent = false)
public void createDateString() {
Long date = new Date().getTime();
updateCache("date", date.toString());
}
public void updateCache(String key, String value) {
if (cache.containsKey("date")) {
LOG.info("Update date value: " + value);
cache.put(key, value);
} else {
LOG.info("Create date value: " + value);
cache.put(key, value);
}
}
}
#Singleton
#Startup
public class CacheReader {
private final static Logger LOG = LoggerFactory.getLogger(CacheReader.class);
#Resource(lookup = "java:jboss/infinispan/container/monitor")
private EmbeddedCacheManager cacheManager;
private Cache<String, String> cache;
#PostConstruct
public void init() {
cache = cacheManager.getCache();
LOG.info("Cache name: " + cache.getName());
}
#Schedule(hour = "*", minute = "*", second = "10", persistent = false)
public void readDateString() {
LOG.info("Cache size: " + cache.keySet().size());
if (cache.containsKey("date")) {
LOG.info("The date value is: " + cache.get("date"));
} else {
LOG.warn("No date value found");
}
}
}
The values on the writer are inserted but there are no cache modifications on the reader node and the cache size is always 0. I tried the TCP and the UDP stack. What am I missing? Can you help me.
Thanks in advance.
Try to directly inject a cache reference (not populating it through the CacheManager). As I understand, this is only way to compel infinispan container to start it in the new WildFly 10.
#Resource(lookup = "java:jboss/infinispan/cache/monitor/default")
private Cache<String, String> cache;
By careful with the JNDI name (default one) or specify it explicitly in configuration
Instead of injecting CacheManager you should inject each cache instance. While doing, keep in mind the following points.
Make sure to enter the correct JNDI name. To avoid any confusion you could explicitly mention the JNDI name in the configuration
Add the transport tag to the cache-container. This is needed for replicated or distributed mode.
Sample Configuration in standalone-full-ha.xml
<cache-container name="replicated_cache" default-cache="default" module="org.wildfly.clustering.server" jndi-name="infinispan/replicated_cache">
<transport lock-timeout="60000"/>
<replicated-cache name="customer" mode="SYNC" jndi-name="infinispan/replicated_cache/customer">
<transaction locking="OPTIMISTIC" mode="FULL_XA"/>
<eviction strategy="NONE"/>
</replicated-cache>
</cache-container>
Inject the resource as follows
#Resource(lookup = "java:jboss/infinispan/replicated_cache/customer")
private Cache<String, Customer> customerCache;

How to run servlets in eclipse

i am new to eclipse environment. I downloaded eclipse helios and tomcat 6. I configured them properly. Now my job is to create servlet for some sign in form. I have been given some existing servlet file from my company. I just need to modify it. Could anybody tell me how to run my existing servlet file? How to connect the file with my mysql table?
Steps to create java web application:
1.Create new Dynamic Web Project
2.Copy existing servlet file to src folder
3.Create web.xml file in WebContent/WEB-INF folder
4.Configure web.xml, for example:
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.ru/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/javaee http://java.sun.ru/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>test.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
replace test.HelloServlet by your servlet class, servlet name also may be replaced
5.Open Server view in Eclipse, add new Tomcat Server using context menu, publish the project and run server.
From your question, I'm guessing you need a way of connecting a servlet to a MySQL database. If that is the case, then below are the steps:
Use the MySQL jdbc driver for making the connection. You can download the jdbc driver for MySQL from here and then put the driver jar file into the classpath.
You need to create the table in MySQL database and then connect it through JDBC to show all the records present there. Below is the structure:
CREATE TABLE `servlet` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(256) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*Data for the table `servlet` */
insert into `servlet`(`id`,`name`) values (1,'sandeep'),(2,'amit'),(3,'anusmita'), (4,'vineet');
Create the servlet and connect to the database:
// *DataBase Connectivity from the Servlet.
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConnection extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("Servlet JDBC");
out.println("");
out.println(" Servlet JDBC");
out.println("");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://192.168.10.59:3306/example","root","root");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM servlet");
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("\t\t\t");
out.print(rs.getObject(2).toString());
out.print("");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}
}
I think you get the idea by now.

rmi java.lang.ClassNotFoundException: RMIServerImpl_Stub

when i start rmiserver implementation class it displays this error message
Remote exception: java.rmi.ServerException: RemoteException occurred in server t
hread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested excep
tion is:
java.lang.ClassNotFoundException: RMIServerImpl_Stub
commands ran
start rmiregistry
start java -Djava.security.policy=policyfile RMIServerImpl
what can i do to resolve this. Please help
This is my rmi server code
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
public class RMIServerImpl extends UnicastRemoteObject
implements RMIServer {
RMIServerImpl() throws RemoteException {
super();
}
public static void main(String args[]) {
try {
System.setSecurityManager(new RMISecurityManager());
RMIServerImpl Server = new RMIServerImpl();
Naming.rebind("SAMPLE-SERVER", Server);
System.out.println("Server waiting.....");
} catch (java.net.MalformedURLException mue) {
System.out.println("Malformed URL: " + mue.toString());
} catch (RemoteException re) {
System.out.println("Remote exception: " + re.toString());
}
}
}
Sounds like you didn't run the rmic compiler to generate stubs and skeletons.
It's been so long since I've done raw RMI by hand that I don't know if that step is still required. But it was the last time I did RMI.
If you did run rmic, then I'd guess that you didn't package the stub and skeleton properly with the server and client sides. If you can find those .class files, check your packaging and deployment.