PAX-CDI + Drool + #Inject #KSession #KReleaseId Not working - cdi

The pax cdi + weld + drool not working getting the following exception
WELD-001408: Unsatisfied dependencies for type KieSession with qualifiers #KSession
https://salaboy.com/2015/10/20/back-to-the-basics-getting-started-with-drools-6-3-0-final/

Posted the solution in this
PAX-CDI + Drool

Related

How to resolve multi-module classpath beans in Quarkus?

In Spring it's possible to define bean dependencies in separate modules, which are then resolved via the classpath at runtime. Is it possible to do something similar in Quarkus?
For example, a multi-module setup that looks like this:
- service
- service-test
- service-artifact
In Spring it's possible to define #Configuration in the service module, that resolves concrete dependencies at runtime via the classpath of its current context, either service-test or service-artifact, allowing injection of dummy or test dependencies when under test, and real ones in the production artifact.
For example, a class in service requires an instance of SomeInterface. The implementation of SomeInterface is defined in either the -test or -artifact module. The service module has no direct dependency on either the -test or -artifact modules.
Some code:
In the service module:
#ApplicationScoped
class OrderService(private val repository: OrderRepository) {
fun process(order: Order) {
repository.save(order)
}
}
interface OrderRepository {
fun save(order: Order)
}
In the service-test module:
class InMemoryOrderRepository : OrderRepository {
val orders = mutableListOf<Order>()
override fun save(order: Order) {
orders.add(order)
}
}
class OrderServiceTestConfig {
#ApplicationScoped
fun orderRepository(): OrderRepository {
return InMemoryOrderRepository()
}
}
#QuarkusTest
class OrderServiceTest {
#Inject
private lateinit var service: OrderService
#Test
fun `injected order service with resolved repository dependency`() {
// This builds and runs OK
service.process(Order("some_test_order"))
}
}
Where I have tried to replicate a Spring-style setup as above in Quarkus, ArC validation is failing with UnsatisfiedResolutionException on the build of the service module, even though everywhere it is actually consumed provides the correct dependencies; a test successfully resolves the dependency and passes.
How do I achieve the separation of dependency interface from the implementation, and keep ArC validation happy, with Quarkus?
(Note: this behaviour occurs with Java and Maven also.)
I have included a maven example here. Note that ./mvnw install fails with the UnsatisfiedResolutionException but that it's possible to build and run the test successfully using ./mvnw test.
Build files:
root project build.gradle.kts:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.3.72"
kotlin("plugin.allopen") version "1.3.72"
}
allprojects {
group = "my-group"
version = "1.0.0-SNAPSHOT"
repositories {
mavenLocal()
mavenCentral()
}
}
subprojects {
apply {
plugin("kotlin")
plugin("kotlin-allopen")
}
java {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
allOpen {
annotation("javax.ws.rs.Path")
annotation("javax.enterprise.context.ApplicationScoped")
annotation("io.quarkus.test.junit.QuarkusTest")
}
apply {
plugin("kotlin")
}
dependencies {
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = JavaVersion.VERSION_11.toString()
kotlinOptions.javaParameters = true
}
}
build.gradle.kts for service:
import io.quarkus.gradle.tasks.QuarkusDev
plugins {
id("io.quarkus") version "1.9.1.Final"
}
apply {
plugin("io.quarkus")
}
dependencies {
implementation(project(":common:model"))
implementation(enforcedPlatform("io.quarkus:quarkus-universe-bom:1.9.1.Final"))
implementation("io.quarkus:quarkus-kotlin")
}
build.gradle.kts for service-test:
import io.quarkus.gradle.tasks.QuarkusDev
plugins {
id("io.quarkus") version "1.9.1.Final"
}
apply {
plugin("io.quarkus")
}
dependencies {
implementation(project(":service"))
implementation(enforcedPlatform("io.quarkus:quarkus-universe-bom:1.9.1.Final"))
implementation("io.quarkus:quarkus-kotlin")
testImplementation("io.quarkus:quarkus-junit5")
}
Try to use instance injection (java example):
import javax.enterprise.inject.Instance;
...
#Inject
Instance<MyBeanClass> bean;
...
bean.get(); // for a single bean
bean.stream(); // for a collection
Unfortunately, Quarkus has a bit different way of creating and injecting beans as in Spring.
It's using "simplified bean discovery", and that means that the beans are scanned on the classpath during the build time, but only those that have annotations considered as "discovery mode", are taken into the account.
Those would be: #ApplicationScoped, #SessionScoped, #ConversationScoped and #RequestScoped, #Interceptor and #Decorator more described here
In addition to that, beans must not have the visibility boundaries.
In you'd like to use beans from other modules, create configuration within that module annotated with #Dependent and create beans with #Producer annotation and one of the above annotations.
But notice, despite that, some beans are treated by Quarkus in a special way (ex. all beans that have #Path annotation) and those should be annotated preferably with #ApplicationScope, using either constructor, or field injection. Produced by #Producer methods won't allow for all the magic that Quarkus is doing.
If you'd like some more quarkus dependant beans, ex. the bean that bounds a configuration (using #ConfigMapping annotated beans), in addition you need to have either beans.xml in your META-INF directory, or which seems easier to add the jandex index to your build system:
plugins {
id("io.quarkus") version "2.14.1.Final"
id("org.kordamp.gradle.jandex") version "1.0.0"
}
Summary: don't use configuration beans as in spring, only the constructor/field injection, and to have beans discovered from different modules, add the jandex index file using plugin.

Is it possible to debug for duplicate Ids?

I'm getting a duplicate id error but I can't figure out which element is meant.
java.lang.IllegalStateException: duplicate Id for a component pb_1_WAR_TEST_INSTANCE_1234_:_viewRoot:mainForm:tableOverview:j_id66
I know it has to be in tableOverview but the element with the ID:
j_id66 can not be found. When I search for it in my browser, I can only find elements with higher Id's like,
pb_1_WAR_TEST_INSTANCE_1234_:_viewRoot:mainForm:tableOverview:j_id67
Is there any way to find out which one is meant?
It's most likely a <h:column> or <rich:column>.
Quick way to find out the exact component is findComponent():
UIComponent component = context.getViewRoot().findComponent("pb_1_WAR_TEST_INSTANCE_1234_:_viewRoot:mainForm:tableOverview:j_id66");
System.out.println(component); // HtmlColumn?
Alternatively, just print out the JSF component tree. JSF 2.x offers <ui:debug> for this, in JSF 1.x you have to write custom code which traverses and prints UIViewRoot and all its children recursively. Here's a kickoff example:
public static void print(UIComponent component) {
System.out.println(component.getId() + " = " + component.getClass());
for (UIComponent child : component.getChildren()) {
print(child);
}
}
print(context.getViewRoot());
As to your concrete problem, it's most likely caused by binding a component to a bean which is not in the request scope. Don't do that.
See also:
How does the 'binding' attribute work in JSF? When and how should it be used?
Binding attribute causes duplicate component ID found in the view

Groovy: WSClient throwing JAXBException

I am trying to call a simple public Web Service with WSClient in a Groovy script, but it explodes when initializing ...
TestService.groovy:
#Grab(group='org.codehaus.groovy.modules', module='groovyws', version='0.5.2')
import groovyx.net.ws.WSClient
def proxy = new WSClient("http://www.w3schools.com/webservices/tempconvert.asmx?WSDL", this.class.classLoader)
proxy.initialize();
def result = proxy.CelsiusToFahrenheit(0)
println "You are probably freezing at ${result} degrees Farhenheit"
The error message:
SEVERE: Could not compile java files for http://www.w3schools.com/webservices/tempconvert.asmx?WSDL.
Caught: java.lang.IllegalStateException: Unable to create JAXBContext for generated packages: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: javax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.class or jaxb.index
java.lang.IllegalStateException: Unable to create JAXBContext for generated pack
ages: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: jav
ax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.class or j
axb.index
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:343)
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:196)
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:175)
at groovyx.net.ws.AbstractCXFWSClient.createClient(AbstractCXFWSClient.java:229)
at groovyx.net.ws.WSClient.initialize(WSClient.java:108)
at groovyx.net.ws.IWSClient$initialize.call(Unknown Source)
at TestService.run(TestService.groovy:5)
Caused by: javax.xml.bind.JAXBException: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: javax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.class or jaxb.index - with linked exception:
[javax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.classor jaxb.index]
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:340)
... 6 more
Caused by: javax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.class or jaxb.index
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:197)
... 7 more
Any hint? Why should I have a jaxb.index?
Just discovered that the problem occurs with Java 1.7 (jdk1.7.0_21)... it's OK when running with Java 6 (jdk1.6.0_31)
Any hint to work with Java 7?
As noted on the GroovyWS page, GroovyWS is currently dormant. You could do the same thing (albeit with a wordier syntax) using the groovy-wslite library:
#Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='0.8.0')
import wslite.soap.*
def client = new SOAPClient('http://www.w3schools.com/webservices/tempconvert.asmx')
def response = client.send(SOAPAction:'http://tempuri.org/CelsiusToFahrenheit') {
body {
CelsiusToFahrenheit('xmlns':'http://tempuri.org/') {
Celsius('0')
}
}
}
def result = response.CelsiusToFahrenheitResponse.CelsiusToFahrenheitResult.text()
println "You are probably freezing at ${result} degrees Farhenheit"
Note that this requires you to look at the WSDL to get the SOAP message namespace, unlike the GroovyWS version of the code. But it works!

Sun/Oracle JAXB RI bug?

EDIT #1: I used JAXB RI 2.2.6 (latest as of today 12/06/12), and I
observe the same behavior :-(
I am using JAXB for unmarshalling XML payloads.
When I pass an invalid payload for the first time via Unmarshaller, I get the following type of error:
javax.xml.bind.UnmarshalException: Unable to create an instance of foo.bar.FooBarType
- with linked exception:
[java.lang.InstantiationException]
On the next line in my code (in the catch() block), I try the same Unmarshaller instance and give a valid payload, where I get following type of error:
java.lang.ClassCastException: foo.bar.SomeAType cannot be cast to foo.bar.SomeBType
On the next line (again in the subsequent catch()), I try the same Unmarshaller instance and again give the same valid payload, which unmarshals fine!
Has anyone experienced this kind of behavior with JAXB? Am I hitting a bug here? Where to look/dig?
Here are the details of the manifest of JAXB jar that I am using:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.0
Created-By: 1.5.0_12-b04 (Sun Microsystems Inc.)
Specification-Title: Java Architecture for XML Binding
Specification-Version: 2.1
Specification-Vendor: Sun Microsystems, Inc.
Implementation-Title: JAXB Reference Implementation
Implementation-Version: 2.1.12
Implementation-Vendor: Sun Microsystems, Inc.
Implementation-Vendor-Id: com.sun
Extension-Name: com.sun.xml.bind
Build-Id: hudson-jaxb-ri-2.1-833
Class-Path: jaxb-api.jar activation.jar jsr173_1.0_api.jar jaxb1-impl.jar
Name: com.sun.xml.bind.v2.runtime
Implementation-Version: hudson-jaxb-ri-2.1-833
Thank you much in advance!
EDIT #2: It's not possible to paste everything, but here's the gist of what it is looking like:
final JAXBContext jaxbContext = JAXBContext.newInstance(FooRequestType.class);
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<FooRequestType> result = null;
try {
//try unmarshalling invalid payload.
result = unmarshaller.unmarshal(invalidPayload.getDocumentElement(), FooRequestType.class);
}catch(Exception e1){
try {
//now try unmarshalling valid payload . ##NOTE: If you try unmarshalling Invalid Payload here, it will fail again.
result = unmarshaller.unmarshal(validPayload.getDocumentElement(), FooRequestType.class);
} catch(Exception e2){
//try again unmarshalling valid payload
result = unmarshaller.unmarshal(validPayload.getDocumentElement(), FooRequestType.class);
System.out.println("Result:=" + result.getValue());
System.out.println("Successfully unmarshalled. Exiting with (0)");
System.exit(0);
}
}
System.out.println("Not expecting to reach here.Exiting with (1)");
System.exit(1);
EDIT #3: Ran the same piece of code by using EclipseLink MOXy as the JAXB Impl; and it behaves correctly.
I opened a bug on Sun/Oracle JAXB RI: http://java.net/jira/browse/JAXB-931

JSF 1.2 Impl - custom component issue - WebSphere v7.0, migrated from v6.1, Array index out of range: 12

We're experiencing a JSF issue migrating one of our apps from WebSphere 6.1 (JSF 1.1 Impl) to WebSphere 7.0( JSF 1.2 Impl, Sun Impl [default in v7.0]). The app uses an IBM jar which IBM tell me is a widget providing custom IBM JSF functionality and tags etc (jsf-ibm.jar), and we have what we believe is the required ver for JSF 1.2 Impl support.
When we hit the app we get an error around a custom component which has a backing UI class. The app loads ok when we access initially but when we hit any buttons on the control or anywhere else we get the following exception (below). The custom component is a paging control and is added to the page as below:
<appname:dataTableNav id="navTable1" dataComponent="#{appSession.cLog.cLogLine}" pageSize="#{appSession.cLogPreferences.pageSize}" startingIndex="#{appSession.caseLog.cLogPref.startingIndex}" actionListener="#{pc_Log.handleSelectedPageEvent}" backImage="images/arrow_previous.gif"forwardImage="images/arrow_next.gif" pageStyleClass="resultlinks" currentPageStyleClass="selectedPage"/>
IBM suggested the issue is that the JSF 1.2 Impl is having trouble rendering the custom control, as JSF 1.1 behaves differently than 1.2 when saving / serializing custom control states etc, and rendering again. They suggested we were missing the saveState & restoreState methods in the backing UI class which I added but to no success, ie our code snippet below and code reference url for such:
** Ref url:
http://blog.evolutionarydawn.com/2009/06/11/custom-jsf-component-12/
** Our code snippet:
public Object saveState(FacesContext context) {
System.out.println("Out .. In DataTableNavigatorUI.saveState-Begin!");
Object values[] = new Object[5];
values[0] = super.saveState(context);
values[1] = forwardImage;
values[2] = backImage;
values[3] = pageStyleClass;
values[4] = currentPageStyleClass;
System.out.println("Out .. In DataTableNavigatorUI.saveState-Exit!");
return ((Object) (values));
}
public void restoreState(FacesContext context, Object state) {
System.out.println("Out .. In DataTableNavigatorUI.restoreState-Begin!");
Object values[] = (Object[])state;
super.restoreState(context, values[0]);
forwardImage = (String) values[1];
backImage = (String) values[2];
pageStyleClass = (String) values[3];
currentPageStyleClass = (String) values[4];
System.out.println("Out .. In DataTableNavigatorUI.restoreState-Exit!");
}
From IBM support:
The component class is missing the saveState and
restoreState methods. This will result in this custom component's
state to not be saved and restored which I believe is leading to the
ArrayIndexOutOfBoundsException.
I can see this code is getting called when debugging and via logging and can debug each method when called and can inspect the values which are getting captured and restored (when I inspect via debug).
As u can see from the stack trace below the app seems to be falling over within the JSF framework code, so not sure if we need to modify our code with what the framework needs!?
So we're at a complete loss and so would welcome any ideas, solutions or feedback.
Thanks & Regards,
Stephen
Exception stack trace:
[8/13/12 15:01:24:101 BST] 00000029 servlet E com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0068E: Uncaught exception created in one of the service methods of the servlet Faces Servlet in application spocs-ear. Exception created : javax.servlet.ServletException: Array index out of range: 12
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:277)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1663)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1597)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:131)
at com.ourapp.ourapp2.ourapp3.web.filter.LogonFilter.doFilter(LogonFilter.java:173)
at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:188)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:116)
at com.ourapp.ourapp2.ourapp3.web.filter.UploadMultipartFilter.doFilter(UploadMultipartFilter.java:61)
at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:188)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:116)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:77)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:908)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:934)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:502)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:179)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3826)
at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:931)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1583)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:186)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:445)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:504)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:301)
at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:83)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1563)
Caused by: java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 12
at javax.faces.component.UIComponentBase.processRestoreState(UIComponentBase.java:1167)
at javax.faces.component.UIComponentBase.processRestoreState(UIComponentBase.java:1171)
at javax.faces.component.UIComponentBase.processRestoreState(UIComponentBase.java:1171)
at javax.faces.component.UIComponentBase.processRestoreState(UIComponentBase.java:1171)
at com.sun.faces.application.StateManagerImpl.restoreView(StateManagerImpl.java:205)
at com.sun.faces.application.ViewHandlerImpl.restoreView(ViewHandlerImpl.java:337)
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:176)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:104)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
... 31 more
Did you use Rational Application Developer to develop your JSF application?
What version of jsf-ibm.jar are you using? look at the JAR's manifest file.
A bug, demonstrating a similar behaviour, was fixed with the JWL implementation included in RAD 8.0.4.1 so if you used RAD 8.0.4 or below to create your JSF application, you might want to migrate to 8.0.4.1 and update the JWL libraries.

Resources