I encountered above exception after migrating an application from QuartzMDB with quartz-ra.rar to EJB Timers in Jboss AS 6.1 . (As a part of upgrading application to wildfly 8.1)
Exception is occurred at a job that uses following ejb.
#Stateless
#TransactionAttribute(TransactionAttributeType.REQUIRED)
#RolesAllowed({"admin"})
public class PlatformPluginBean implements PlatformPluginRemote {
// some code here
public Collection<PlatformPlugin> getPlugins() {
return new ArrayList<PlatformPlugin>(schemaToPlugin.values());
}
}
Following is the job before migration which worked fine.
#MessageDriven(activationConfig = {
#ActivationConfigProperty(propertyName = "cronTrigger", propertyValue = "0 0 * * * ?"),
#ActivationConfigProperty(propertyName = "jobName", propertyValue = "PruneJob")})
#ResourceAdapter("quartz-ra.rar")
#RunAs("admin")
public class PruneJob implements Job {
#EJB
private PlatformPluginRemote platformPluginRemote;
#Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
for (PlatformPlugin platformPlugin: platformPluginRemote.getPlugins()) {
// some stuff here
}
}
}
Following is the job after changing to ejb auto timer.
#Stateless
#RunAs("admin")
public class PruneJob {
#EJB
private PlatformPluginRemote platformPluginRemote;
#Schedule(hour="*", minute="0", persistent=false)
public void execute() {
for (PlatformPlugin platformPlugin: platformPluginRemote.getPlugins()) {
// some stuff here
}
}
}
The exception is occurred at platformPluginRemote.getPlugins() call.
#RunAs("admin") annotation doesn't seem to work for some reason (jboss bug?)
Same can be done by adding following code before the call to ejb.
SecurityContextAssociation.getSecurityContext().setOutgoingRunAs(new RunAsIdentity("admin", "admin"));
There's this issue reported in JBoss 5 which also affects jboss as 6.1, to fix it you can add in file JBOSS_HOME/serve/<instance>/deploy/ejb3-interceptors-aop.xml the org.jboss.ejb3.security.RunAsSecurityInterceptorFactory interceptor:
eg:
<! - The additional MDB specific ones ->
<interceptor-ref name = "org.jboss.ejb3.ENCPropagationInterceptor" />
<interceptor-ref name = "org.jboss.ejb3.security.RunAsSecurityInterceptorFactory" />
<interceptor-ref name = "CMTTx" />
<interceptor-ref name = "org.jboss.ejb3.stateless.StatelessInstanceInterceptor" />
<interceptor-ref name = "org.jboss.ejb3.tx.BMTTxInterceptorFactory" />
<interceptor-ref name = "org.jboss.ejb3.AllowedOperationsInterceptor" />
<interceptor-ref name = "org.jboss.ejb3.entity.TransactionScopedEntityManagerInterceptor" />
In practice it has presented me some problems, not all invocations the role is propagated and some times authorization error occurs.
Alternatively you can use Subject.doAs() in execute() method of the MDB. Do not forget to add the login module ClientLoginModule in your security domain.
Related
I am working whith JSF (Primeface) and j2ee on weblogic.
So, i have two different flows in my application:
Flow configuration:
public class RequestFlow implements Serializable {
#Produces
#FlowDefinition
public Flow defineFlow(#FlowBuilderParameter FlowBuilder flowBuilder) {
String flowId = "requestFlow";
flowBuilder.id("", flowId);
flowBuilder.viewNode(flowId, "/inside/customer/request/flow/requestFlow.xhtml").markAsStartNode();
flowBuilder.viewNode("requestFlowCart", "/inside/customer/request/flow/requestFlowCart.xhtml");
flowBuilder.viewNode("requestFlowCheckout", "/inside/customer/request/flow/requestFlowCheckout.xhtml");
flowBuilder.returnNode("finishRequest").fromOutcome("/inside/customer/request/requests.xhtml");
return flowBuilder.getFlow();
}
}
CDI's flow bean:
#Named
#FlowScoped("requestFlow")
public class RequestFlowBean implements Serializable {
//some logic
}
Second configuration:
public class OrderFlow implements Serializable {
#Produces
#FlowDefinition
public Flow defineFlow(#FlowBuilderParameter FlowBuilder flowBuilder) {
String flowId = "orderFlow";
flowBuilder.id("", flowId);
flowBuilder.viewNode(flowId, "/inside/customer/order/flow/orderFlow.xhtml").markAsStartNode();
flowBuilder.viewNode("orderFlowSelectRequests", "/inside/customer/order/flow/orderFlowSelectRequests.xhtml");
flowBuilder.viewNode("orderFlowReviewRequests", "/inside/customer/order/flow/orderFlowReviewRequests.xhtml");
flowBuilder.viewNode("orderFlowCheckoutOrder", "/inside/customer/order/flow/orderFlowCheckoutOrder.xhtml");
flowBuilder.returnNode("finishOrder").fromOutcome("/inside/customer/order/orders.xhtml");
return flowBuilder.getFlow();
}
}
CDI's flow bean:
#Named
#FlowScoped("orderFlow")
public class OrderFlowBean implements Serializable {
//some logic
}
My Case:
User opens page where by clicking h:button starts the "requestFlow" (doesn't finish it!)
Using menu navigates to another page, by clicking h:button tries to start the "orderFlow".
Problem:
"OrderFlow" wasn't start without any error in console! And the first flow still in memory, but according documentation it have to be destroyed.
So, I want to be able create a new FlowScoped bean when other one was not finished.
Any suggestions?
So, exactly in 2 month i found the answer.
The trick is how you start your flow. If you want to run new JSF flow, while didn't finish other one, you have to remove from JSF context previous instances of any flow. In order to do it, you have add method in controller:
public String initFlow() {
FacesContext context = FacesContext.getCurrentInstance();
FlowHandler handler = context.getApplication().getFlowHandler();
ExternalContext extContext = context.getExternalContext();
String sessionKey = extContext.getClientWindow().getId() + "_flowStack";
Map<String, Object> sessionMap = extContext.getSessionMap();
if (sessionMap.containsKey(sessionKey)) {
sessionMap.remove(sessionKey);
}
handler.transition(context, null, handler.getFlow(context, "", getFlowName()), null, "");
return getFlowName();
}
And start flow page in the next way:
<p:commandButton value="Start Flow"
action="#{controller.initFlow}"/>
</p:panelGrid>
I would like to pass an value to a managed bean under the hood. So I have this managed bean:
#ManagedBean(name = "mbWorkOrderController")
#SessionScoped
public class WorkOrderController {
// more attributes...
private WorkOrder workOrderCurrent;
// more code here...
public WorkOrder getWorkOrderCurrent() {
return workOrderCurrent;
}
public void setWorkOrderCurrent(WorkOrder workOrderCurrent) {
this.workOrderCurrent = workOrderCurrent;
}
}
It holds a parameter workOrderCurrent of the custom type WorkOrder. The class WorkOrder has an attribute applicant of type String.
At the moment I am using a placeholder inside my inputtext to show the user, what he needs to type inside an inputText.
<p:inputText id="applicant"
value="#{mbWorkOrderController.workOrderCurrent.applicant}"
required="true" maxlength="6"
placeholder="#{mbUserController.userLoggedIn.username}" />
What I want to do, is to automatically pass the value of mbUserController.userLoggedIn.username to mbWorkOrderController.workOrderCurrent.applicant and remove the inputText for applicant completely from my form.
I tried to use c:set:
<c:set value="#{mbUserController.userLoggedIn.username}" target="#{mbWorkOrderController}" property="workOrderCurrent.applicant" />
But unfortunatelly I get a javax.servlet.ServletException with the message:
The class 'WorkOrderController' does not have the property 'workOrderCurrent.applicant'.
Does anybody have an advice?
The class 'WorkOrderController' does not have the property 'workOrderCurrent.applicant'.
Your <c:set> syntax is incorrect.
<c:set value="#{mbUserController.userLoggedIn.username}"
target="#{mbWorkOrderController}"
property="workOrderCurrent.applicant" />
You seem to be thinking that the part..
value="#{mbWorkOrderController.workOrderCurrent.applicant}"
..works under the covers as below:
WorkOrderCurrent workOrderCurrent = mbWorkOrderController.getWorkOrderCurrent();
workOrderCurrent.setApplicant(applicant);
mbWorkOrderController.setWorkOrderCurrent(workOrderCurrent);
This isn't true. It works under the covers as below:
mbWorkOrderController.getWorkOrderCurrent().setApplicant(applicant);
The correct <c:set> syntax is therefore as below:
<c:set value="#{mbUserController.userLoggedIn.username}"
target="#{mbWorkOrderController.workOrderCurrent}"
property="applicant" />
That said, all of this isn't the correct solution to the concrete problem you actually tried to solve. You should perform model prepopulating in the model itself. This can be achieved by using #ManagedProperty to reference another bean property and by using #PostConstruct to perform initialization based on it.
#ManagedBean(name = "mbWorkOrderController")
#SessionScoped
public class WorkOrderController {
#ManagedProperty("#{mbUserController.userLoggedIn}")
private User userLoggedIn;
#PostConstruct
public void init() {
workOrderCurrent.setApplicant(userLoggedIn.getUsername());
}
// ...
}
Perhaps you could explain the context a bit more, but here's another solution. If you're navigating from another page, you can pass some identifier of work WorkOrder in the URL, like this http://host:port/context/page.xhtml?workOrderId=1.
Then, you can set the identifier in the managed bean like this:
<h:html>
<f:viewParam name="workOrderId" value="#{mbWorkOrderController.id}"/>
</h:html>
You'll have to add a new property to your bean:
public class WorkOrderController {
private long id;
public long getId() { return id; }
public void setId(long id) { this.id = id; }
// ...
}
And then, after the property has been set by JSF, you can find the work order in a lifecycle event:
<h:html>
<f:viewParam name="workOrderId" value="#{mbWorkOrderController.id}"/>
<f:event type="preRenderView" listener="#{mbWorkOrderController.findWorkOrder()}"/>
</h:html>
public class WorkOrderController {
private long id;
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public void findWorkOrder() {
this.workOrderCurrent = null /* some way of finding the work order */
}
// ...
}
This strategy has the advantage of letting you have bookmarkable URLs.
I am trying to achieve the following :
EJB3 Singleton
#Singleton
#Startup
public class SomeSingleton implements SomeSingletonLocal {
// Entity Manager injection
private EntityManager _entity_manager;
#Override
#Asynchronous
public void createScenario(){
method1();
method2();
// ...
}
public void method1(){
// Persist an Event in a Database.
}
public void method2(){
// Persist an Event in a Database.
}
}
Managed Bean
#ManagedBean
#RequestScoped
public class SomeManagedBean{
// Entity Manager injection
private EntityManager _entity_manager;
#EJB
private SomeSingletonRemote _singleton;
public void createScenario(){
_singleton.createScenario();
}
public List<Event> getEventList(){
// Retrieve events from database
}
}
JSF view
<h:form>
<p:commandButton value="Start Long Stuff"
actionListener="#{SomeManagedBean.createScenario}" />
<h:outputText id="count" value="#{SomeManagedBean.getEventList.size()}" />
<p:poll interval="1" update="count" />
</h:form>
log
->SomeManagedBean.getEventList()
<-SomeManagedBean.getEventList() // Size = 0
// Buton clicked
->SomeManagedBean.createScenario()
->SomeSingleton.createScenario()
<-SomeManagedBean.createScenario()
->SomeManagedBean.getEventList() // will end at the end of SomeSingleton.createScenario
->SomeSingleton.method1()
<-SomeSingleton.method1() // persist
...
->SomeSingleton.methodN()
<-SomeSingleton.methodN() // persist
<-SomeSingleton.createScenario()
<-SomeManagedBean.getEventList() // size = N
I expected at least one call to getEventList between two methodI() call (ie. each second). When it enters in SomeSingleton.createScenario(), I dont know why getEventList is paused.
It looks like there is a lock with the entity manager or the transaction inside createScenario. Is that a reentrance problem ?
A #Singleton is indeed by default read/write locked. This is not strictly related to transactions, but to concurrency. See also a.o. Java EE 7 tutorial on the subject.
One way to solve it is to set the #ConcurrencyManagement to BEAN. This way you basically tell the container to not worry about concurrency at all and that you take all responsibility on your own.
#Singleton
#ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class SomeSingleton {}
Another way is to explicitly set #Lock to READ on the class or the read-only methods so that they can concurrently be invoked. Only when a method with an explicit #Lock(LockType.WRITE) is invoked on the same instance, then the lock will occur.
#Singleton
#Lock(LockType.READ)
public class SomeSingleton {}
How can I ovveride CustomerStateRequestProcessor#resolveAuthenticatedCustomer function in broadleaf?
I tried this:-
#Component("blCustomerStateRequestProcessor")
public class MyCustomerStateRequestProcessor extends
CustomerStateRequestProcessor {
#Resource(name = "blCustomerService")
protected CustomerService customerService;
#Override
public Customer resolveAuthenticatedCustomer(Authentication authentication) {
if (authentication instanceof OpenIDAuthenticationToken) {
OpenIDAuthenticationToken openIDAuthenticationToken = (OpenIDAuthenticationToken) authentication;
if (openIDAuthenticationToken.isAuthenticated()) {
return (Customer) openIDAuthenticationToken.getPrincipal();
} else {
return null;
}
} else {
return super.resolveAuthenticatedCustomer(authentication);
}
}
}
Added context component scan :-
<context:component-scan base-package="org.broadleafcommerce.common.web.security,com.mycompany.web.request.processor" />
This resulted in :-
org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'blCustomerStateRequestProcessor' for bean class [org.broadleafcommerce.profile.web.core.security.CustomerStateRequestProcessor] conflicts with existing, non-compatible bean definition of same name and class [com.mycompany.web.request.processor.MyCustomerStateRequestProcessor]
I am trying to overrid resolveAuthenticatedCustomer method for OpenIdAuthenticationToken.
Thanks
Rather than use component-scanning to redefine the bean, remove that annotation and do it via XML instead.
So your class definition would change to:
public class MyCustomerStateRequestProcessor extends
CustomerStateRequestProcessor {
...
}
And then in any of your applicationContext.xml files (except for the servlet one) add this:
<bean id="blCustomerStateRequestProcessor" class="com.yourcompany.site.web.MyCustomerStateRequestProcessor" />
Note that this pattern is the same for overriding any Broadleaf-defined beans.
The view and bean were working until I tried to fix non-standard names, and I've now broken the connection between the two. Oddly, the "back" button has the correct link, but content just doesn't show, nor log. Why doesn't Detail.getComments() execute?
I've been going through the weld docs and trying to better understand #Inject. There seems to be a lifecycle problem which I don't understand, either. If it's not lifecycle, then I cannot even speculate as to why Detail.getComments() never shows in the glassfish logs:
INFO: MessageBean.getModel..
INFO: SingletonNNTP.returning messages..
INFO: MessageBean.getModel..
INFO: SingletonNNTP.returning messages..
INFO: MessageBean.getModel..
INFO: SingletonNNTP.returning messages..
INFO: Detail..
INFO: Detail.getId..null
INFO: Detail.getId..SETTING DEFAULT ID
INFO: Detail.onLoad..2000
INFO: Detail.getId..2000
INFO: Detail.getId..2000
INFO: Detail.setId..2000
INFO: Detail.getId..2019
INFO: ..Detail.setId 2019
INFO: Detail.back..
INFO: Detail.getId..2019
INFO: ..Detail.back 2,018
INFO: Detail.getId..2019
The value 2000 is a default, which only happens when id==null, which it never should. It should pull in that attribute right away. So, I'm not sure whether that's a problem with the scope (I only just now found out that CDI doesn't support #SessionScoped), the lifecycle, or something else. Perhaps I need to use #Inject on that variable?
The view, detail.xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<body>
<f:metadata>
<f:viewParam name="id" id="id" value="#{detail.id}" />
</f:metadata>
<ui:composition template="./complexTemplate.xhtml">
<ui:define name="top">
<h:link value="back" outcome="detail" includeViewParams="true">
<f:param name="id" value="#{detail.back}"/>
</h:link>
<ui:define name="content">
<h:outputText value="#{detail.content}" rendered="false"/>
</ui:define>
<ui:define name="bottom">
bottom
</ui:define>
</ui:composition>
</body>
</html>
and the backing bean:
package net.bounceme.dur.nntp;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ConversationScoped;
import javax.inject.Named;
import javax.mail.Message;
#Named
#ConversationScoped
public class Detail implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(Detail.class.getName());
private static final Level level = Level.INFO;
private String id = null; //should never get default value in getter
private Message message = null;
private SingletonNNTP nntp = SingletonNNTP.INSTANCE;
private String forward = null; //id + 1
private String back = null; //id - 1
private String content = null; //message.content
public Detail() {
logger.log(level, "Detail..");
}
#PostConstruct
private void onLoad() {
logger.log(level, "Detail.onLoad..{0}", getId());
}
public Message getMessage() {
logger.log(level, "Detail.getMessage..");
return message;
}
public void setMessage(Message message) {
logger.log(level, "Detail.setMessage..");
this.message = message;
}
public String getId() {
logger.log(level, "Detail.getId..{0}", id);
if (id == null) {
logger.log(level, "Detail.getId..SETTING DEFAULT ID");
id = String.valueOf(2000);
}
return id;
}
public void setId(String id) throws Exception {
logger.log(level, "Detail.setId..{0}", getId());
this.id = id;
logger.log(level, "..Detail.setId {0}", getId());
}
public String getForward() {
logger.log(level, "Detail.forward..");
int f = Integer.parseInt(getId());
f = f + 1;
logger.log(level, "..Detail.forward {0}", f);
forward = String.valueOf(f);
return forward;
}
public void setForward(String forward) {
this.forward = forward;
}
public String getBack() {
logger.log(level, "Detail.back..");
int b = Integer.parseInt(getId());
b = b - 1;
logger.log(level, "..Detail.back {0}", b);
back = String.valueOf(b);
return back;
}
public void setBack(String back) {
this.back = back;
}
public String getContent() throws Exception {
logger.log(level, "Detail.getContent..{0}", getId());
message = nntp.getMessage(Integer.parseInt(getId()));
content = message.getContent().toString();
return content;
}
public void setContent(String content) {
this.content = content;
}
}
which never seems to have, according to the above logs, Detail.getContent() invoked, despite that being part of the view: <h:outputText value="#{detail.content}" rendered="false"/>
It's odd in that Detail.content() was getting invoked prior to my changing this class to better follow naming conventions. I'm going through some Weld and Oracle Java EE 6 docs, but don't at all mind being directed to a fine manual. The docs I find describing this are invariably using #ManagedBeans, however, which I am not. There seem many gotchas, as described in this answer by #Kawu.
Adding #Inject to the id field causes a deploy error:
init:
deps-module-jar:
deps-ear-jar:
deps-jar:
library-inclusion-in-archive:
library-inclusion-in-manifest:
compile:
compile-jsps:
In-place deployment at /home/thufir/NetBeansProjects/NNTPjsf/build/web
Initializing...
deploy?DEFAULT=/home/thufir/NetBeansProjects/NNTPjsf/build/web&name=NNTPjsf&contextroot=/NNTPjsf&force=true failed on GlassFish Server 3.1.2
Error occurred during deployment: Exception while loading the app : WELD-001408 Unsatisfied dependencies for type [String] with qualifiers [#Default] at injection point [[field] #Inject private net.bounceme.dur.nntp.Detail.id]. Please see server.log for more details.
/home/thufir/NetBeansProjects/NNTPjsf/nbproject/build-impl.xml:749: The module has not been deployed.
See the server log for details.
BUILD FAILED (total time: 9 seconds)
Surely, injecting a String isn't the problem, perhaps it's a bug.
I understand your frustration, and I see that the problem is more your setup / understanding in general. But still, it's pretty hard to find any real questions to answer, maybe you can try to split your problems next time.
Here are some answers:
Why doesn't Detail.getComments() execute?
Hm, maybe because it's not in the bean? I guess that you are refrerring to detail.getContent instead?
which never seems to have, according to the above logs,
Detail.getContent() invoked, despite that being part of the view:
Try rendered = true :-)
#PostConstruct
private void onLoad() {
logger.log(level, "Detail.onLoad..{0}", getId());
}
You've put an awful lot of logic into the getter. Try debugging with the field, not with the getter...
The value 2000 is a default, which only happens when id==null, which it never should.
It looks like private String id = null; is a perfect explanation why id will be null.
Try to keep in mind that modern frameworks like JSF, CDI and Java EE do a lot of stuff behind the scenes, using reflection, proxies and interceptors. Don't rely on classical understanding of when (and how often) a constructor is called, for example.
Again, consider moving your initialisation logic away from the getter. #PostConstruct would be the place that the fathers of the Java EE-spec had chosen for it.
To be honest: Nothing looks extremely wrong, but your code is kind of messy, and extremely hard to understand and to follow.
Try removing all indirections like this one...
int b = Integer.parseInt(getId());
... and everything will look much better.
Oh, and is there a specific reason why you declare a fixed log-level for the whole class? Try something like this
private static final Logger LOG = Logger.getLogger(Some.class);
...
LOG.info("...");
Hope that gives you a start. Feel free to post further questions, preferably a bit shorter and with single, isolated aspects to answer.