I'm hoping someone can give me a hint at what's going on here with this exception. I'm putting together an environment where i can test out j_security_check with JSF and what I'm noticing is when i redeploy my application without restarting glassfish i see this error. I thought it would be perfectly safe to just redeploy the war but my setup is hosed until glassfish is restarted and war redeployed. I'm worried that this will becomes an issue later down the road. Any advise?
I'm using Glassfish 3.1.2, NetBeans 7.1.2...
com.sun.faces.mgbean.ManagedBeanCreationException: An error occurred performing resource injection on managed bean userController
at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:229)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:105)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:103)
at com.sun.el.parser.AstValue.getValue(AstValue.java:179)
at com.sun.el.parser.AstDeferredExpression.getValue(AstDeferredExpression.java:63)
at com.sun.el.parser.AstCompositeExpression.getValue(AstCompositeExpression.java:68)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:224)
at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIOutput.getValue(UIOutput.java:169)
at com.sun.faces.renderkit.html_basic.OutputLinkRenderer.getValue(OutputLinkRenderer.java:182)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
at com.sun.faces.renderkit.html_basic.OutputLinkRenderer.renderAsActive(OutputLinkRenderer.java:191)
at com.sun.faces.renderkit.html_basic.OutputLinkRenderer.encodeBegin(OutputLinkRenderer.java:107)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:820)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1755)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
Caused by: com.sun.faces.spi.InjectionProviderException: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting invoke lifecycle method private void avenger.UserController.startup()
at org.glassfish.faces.integration.GlassFishInjectionProvider.invokePostConstruct(GlassFishInjectionProvider.java:231)
at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:223)
... 56 more
Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting invoke lifecycle method private void avenger.UserController.startup()
at org.glassfish.faces.integration.GlassFishInjectionProvider.invokeLifecycleMethod(GlassFishInjectionProvider.java:393)
at org.glassfish.faces.integration.GlassFishInjectionProvider.invokePostConstruct(GlassFishInjectionProvider.java:306)
at org.glassfish.faces.integration.GlassFishInjectionProvider.invokePostConstruct(GlassFishInjectionProvider.java:229)
... 57 more
Caused by: java.security.PrivilegedActionException: java.lang.reflect.InvocationTargetException
at java.security.AccessController.doPrivileged(Native Method)
at org.glassfish.faces.integration.GlassFishInjectionProvider.invokeLifecycleMethod(GlassFishInjectionProvider.java:376)
... 59 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.glassfish.faces.integration.GlassFishInjectionProvider$2.run(GlassFishInjectionProvider.java:382)
... 61 more
Caused by: java.lang.ClassCastException: avenger.MyUser cannot be cast to avenger.MyUser
at avenger.UserController.updateUserList(UserController.java:103)
at avenger.UserController.startup(UserController.java:39)
Here are portions of my web.xml
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<security-constraint>
<display-name>Admin</display-name>
<web-resource-collection>
<web-resource-name>Admin Views</web-resource-name>
<description/>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
</security-constraint>
<security-role>
<description/>
<role-name>ADMIN</role-name>
</security-role>
<security-role>
<description/>
<role-name>USER</role-name>
</security-role>
my management bean
#ManagedBean(eager = true)
#SessionScoped
public class UserController implements Serializable {
/**
* Creates a new instance of UserBean
*/
public UserController() {}
#PostConstruct
private void startup() {
System.out.println("inilitiazing UserController");
updateUserList();
}
#PreDestroy
private void shutdown() {
System.out.println("destroying UserController");
Utils.stopEntityManager();
}
private static final long serialVersionUID = 1L;
#Override
public int hashCode() {
int hash = 5;
hash = 67 * hash + (this.userList != null ? this.userList.hashCode() : 0);
hash = 67 * hash + (this.cUser != null ? this.cUser.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UserController other = (UserController) obj;
if (this.userList != other.userList && (this.userList == null || !this.userList.equals(other.userList))) {
return false;
}
if (this.cUser != other.cUser && (this.cUser == null || !this.cUser.equals(other.cUser))) {
return false;
}
return true;
}
//the current user
MyUser cUser = new MyUser();
public MyUser getMyUser() { return cUser; }
public void setMyUser(MyUser cUser) {this.cUser = cUser;}
//the new user
MyUser nUser = new MyUser();
public MyUser getNewUser() { return nUser; }
public void setNewUser(MyUser nUser) {this.nUser = nUser;}
// list of current users
List userList = new LinkedList();
public void setUserList(List uList) {userList = uList;}
public List getUserList() {return userList;}
public String updateUserList() {
System.out.println("updateUserList()" );
EntityManager em = Utils.getEntityManager();
//Query q = em.createNamedQuery("MyUser.findAll");
Query q = em.createQuery("Select u FROM MyUser u", MyUser.class);
userList = q.getResultList();
for (MyUser cu : userList) {
String groupList = "";
for (Grouptable gt : cu.getGrouptableList()) {
groupList += ":"+gt.getGrouptablePK().getGroupid();
}
cu.setGrouplist(groupList);
}
return "users.xhtml";
}
public boolean usernameExist() {
return false;
}
public String resetNewUser() {
nUser = new MyUser();
return "createuser.xhtml";
}
public String createNewUser () {
System.out.println("attempting to create account with\n"
+ "\tusername: " + nUser.getUsername() +"\n"
+ "\tpassword: "+nUser.getPassword() +"\n"
+ "\tfirst name: "+nUser.getFirstName()+"\n"
+ "\tlast name: "+nUser.getLastName()+"\n");
//TODO: check if newUser already exist if so send message to user
// set the hashed password
MessageDigest md = null;
byte [] digest;
try { md = MessageDigest.getInstance("MD5"); }
catch (NoSuchAlgorithmException ex) {
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("nUser"+nUser);
//System.out.println("cUser.password"+cUser.getPassword());
digest = md.digest(nUser.getPassword().getBytes());
nUser.setPassword(Utils.toHex(digest));
System.out.println("creating user: " + nUser.getUsername() +
" password: "+nUser.getPassword());
EntityManager em = Utils.getEntityManager();
em.getTransaction().begin();
em.persist(nUser);
em.getTransaction().commit();
updateUserList();
return "users.xhtml";
}
public String deleteUser () {
System.out.println("deleting user: "+cUser.getUsername());
EntityManager em = Utils.getEntityManager();
cUser = em.find(MyUser.class, cUser.getUsername());
em.getTransaction().begin();
em.remove(cUser);
em.getTransaction().commit();
//em.close();
return "users.xhtml";
}
public String deleteSelectedUsers () {
for (MyUser cu : userList) {
if (cu.getSelected()) {
System.out.println("Planning to remove: "+cu);
}
}
EntityManager em = Utils.getEntityManager();
for (MyUser cu : userList) {
if (cu.getUsername().equalsIgnoreCase("ADMIN") && cu.getSelected()) {
System.out.println("admin account can not be deleted");
continue;
}
if (cu.getSelected()) {
MyUser targetUser = em.find(MyUser.class, cu.getUsername());
System.out.println("removing user: "+cu.toString());
em.getTransaction().begin();
em.remove(targetUser);
em.getTransaction().commit();
}
}
updateUserList();
return "users.xhtml";
}
public String login() {
System.out.println("user attempting to login...");
System.out.println("username: "+cUser.getUsername());
System.out.println("password: "+cUser.getPassword());
// set the hashed password
MessageDigest md = null;
byte [] digest;
try { md = MessageDigest.getInstance("MD5"); }
catch (NoSuchAlgorithmException ex) {
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
}
digest = md.digest(cUser.getPassword().getBytes());
cUser.setPassword(Utils.toHex(digest));
MyUser userFound = Utils.getEntityManager().find(MyUser.class, cUser.getUsername());
if (userFound == null) {
System.err.println("user does not exist");
return null;
}
if (!userFound.getPassword().equalsIgnoreCase(cUser.getPassword())) {
System.err.println("Incorrect Password");
return null;
}
return "users.xhtml";
// FacesContext context = FacesContext.getCurrentInstance();
// HttpServletRequest request = (HttpServletRequest) context.getExternalContext();
// try {
// request.login(this.cUser.getFirstName(), this.cUser.getPassword());
// this.cUser = Utils.getEntityManager().find(MyUser.class,this.cUser.getUsername());
// } catch (ServletException e) {
// context.addMessage(null, new FacesMessage("Unknown login"));
// }
}
public MyUser getUser() {
if (cUser==null) {
Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
if (principal != null) {
//cUser = userDAO.find(principal.getName()); // Find User by j_username
cUser = Utils.getEntityManager().find(MyUser.class, principal.getName());
}
}
return cUser;
}
}
my init.sql for JavaDB
create table usertable (
username varchar(128) NOT NULL CONSTRAINT USER_PK PRIMARY KEY ,
password varchar(128) NOT NULL,
firstname varchar(128) NOT NULL,
lastname varchar(128) NOT NULL
);
create table grouptable(
username varchar(128) NOT NULL,
groupid varchar(128) NOT NULL,
CONSTRAINT GROUP_PK PRIMARY KEY(username, groupid),
CONSTRAINT USER_FK FOREIGN KEY(username) REFERENCES usertable(username)
ON DELETE CASCADE ON UPDATE RESTRICT
);
insert into usertable(username,password,firstname,lastname)
values ('admin', '21232f297a57a5a743894a0e4a801fc3','','');
insert into grouptable(username,groupid) values ('admin', 'USER');
insert into grouptable(username,groupid) values ('admin', 'ADMIN');
i created my connection pool and jdbcRealm using instructions from:
http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html
Related
I am trying to call a secured EJB method on server load but I am getting exception:
09:49:58,011 ERROR [org.jboss.as.ejb3.invocation] (ServerService Thread Pool -- 54) JBAS014134: EJB Invocation failed on component SecuredEJB for method public java.lang.String org.jboss.as.quickstarts.ejb_security.SecuredEJB.getSecurityInfo(): javax.ejb.EJBAccessException: JBAS014502: Invocation on method: public java.lang.String org.jboss.as.quickstarts.ejb_security.SecuredEJB.getSecurityInfo() of bean: SecuredEJB is not allowed
at org.jboss.as.ejb3.security.AuthorizationInterceptor.processInvocation(AuthorizationInterceptor.java:114) [jboss-as-ejb3-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ejb3.security.SecurityContextInterceptor.processInvocation(SecurityContextInterceptor.java:86) [jboss-as-ejb3-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ejb3.component.interceptors.ShutDownInterceptorFactory$1.processInvocation(ShutDownInterceptorFactory.java:64) [jboss-as-ejb3-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation(LoggingInterceptor.java:59) [jboss-as-ejb3-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50) [jboss-as-ee-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation(AdditionalSetupInterceptor.java:55) [jboss-as-ejb3-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ee.component.TCCLInterceptor.processInvocation(TCCLInterceptor.java:45) [jboss-as-ee-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ee.component.ViewService$View.invoke(ViewService.java:185) [jboss-as-ee-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.as.ee.component.ViewDescription$1.processInvocation(ViewDescription.java:185) [jboss-as-ee-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ee.component.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:73) [jboss-as-ee-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.as.quickstarts.ejb_security.SecuredEJB$$$view1.getSecurityInfo(Unknown Source) [classes:]
at org.jboss.as.quickstarts.ejb_security.SecuredEJBServlet.init(SecuredEJBServlet.java:55) [classes:]
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1194) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1100) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3593) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
at org.apache.catalina.core.StandardContext.start(StandardContext.java:3802) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
at org.jboss.as.web.deployment.WebDeploymentService.doStart(WebDeploymentService.java:163) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.as.web.deployment.WebDeploymentService.access$000(WebDeploymentService.java:61) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.as.web.deployment.WebDeploymentService$1.run(WebDeploymentService.java:96) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [rt.jar:1.7.0_55]
at java.util.concurrent.FutureTask.run(FutureTask.java:262) [rt.jar:1.7.0_55]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_55]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_55]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_55]
at org.jboss.threads.JBossThread.run(JBossThread.java:122) [jboss-threads-2.1.2.Final-redhat-1.jar:2.1.2.Final-redhat-1]
My project structure is:
SecuredEJBServlet.java
#SuppressWarnings("serial")
#WebServlet("/SecuredEJBServlet")
#ServletSecurity(#HttpConstraint(rolesAllowed = "quickstarts"))
public class SecuredEJBServlet extends HttpServlet {
#EJB
private SecuredEJB securedEJB;
#Override
public void init(javax.servlet.ServletConfig arg0) throws javax.servlet.ServletException{
Subject s = CMnJAASLogin.loginMethod();
runAs(s);
super.init(arg0);
System.out.println("Inside init...");
securedEJB.getName();
//securedEJB.getSecurityInfo();
}
private void runAs(Subject s){
Subject.doAs(s, new PrivilegedAction<Object>() {
#Override
public Object run() {
System.out.println("Inside privileged action");
securedEJB.getSecurityInfo();
return null;
}
});
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
securedEJB.getName();
String principal = securedEJB.getSecurityInfo();
...
}
SecuredEJB.java
#Stateless
#DeclareRoles("java")
#SecurityDomain("custom")
public class SecuredEJB {
#Resource
private SessionContext ctx;
#RolesAllowed({ "java" })
public String getSecurityInfo() {
Principal principal = ctx.getCallerPrincipal();
return principal.toString();
}
#PermitAll
public void getName(){
System.out.println(principal.getName());
}
}
CMnAuthenticator.java
public class CMnAuthenticator extends UsernamePasswordLoginModule{
#Override
protected String getUsersPassword() throws LoginException {
return "java";
}
#Override
protected boolean validatePassword(String passwordWant, String passwordHave){
return true;
}
#Override
protected Group[] getRoleSets() throws LoginException {
HashMap setsMap = new HashMap();
String groupName = "Roles";
Group group = (Group) setsMap.get(groupName);
if (group == null) {
group = new SimpleGroup(groupName);
setsMap.put(groupName, group);
}
try {
Principal p = super.createIdentity("quickstarts");
group.addMember(p);
}
catch (Exception e) {
e.printStackTrace();
}
Group[] roleSets = new Group[setsMap.size()];
setsMap.values().toArray(roleSets);
return roleSets;
}
}
CMnEJBAuthenticator.java
public class CMnEJBAuthenticator extends UsernamePasswordLoginModule {
#Override
protected String getUsersPassword() throws LoginException {
return "java";
}
#Override
protected boolean validatePassword(String passwordWant, String passwordHave){
return true;
}
#Override
protected Group[] getRoleSets() throws LoginException {
System.out.println("Inside CMnEJBAuthenticator:getRoleSets...");
HashMap setsMap = new HashMap();
String groupName = "Roles";
Group group = (Group) setsMap.get(groupName);
if (group == null) {
group = new SimpleGroup(groupName);
setsMap.put(groupName, group);
}
try {
Principal p = super.createIdentity("java");
group.addMember(p);
}
catch (Exception e) {
e.printStackTrace();
}
Group[] roleSets = new Group[setsMap.size()];
setsMap.values().toArray(roleSets);
return roleSets;
}
}
jboss-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss-web>
<jboss-web xmlns="http://www.jboss.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.jboss.org/schema/jbossas
http://www.jboss.org/schema/jbossas/jboss-web_7_2.xsd">
<!-- Configure usage of the security domain "other" -->
<security-domain>servlet-security-quickstart</security-domain>
<disable-audit>true</disable-audit>
</jboss-web>
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- Configure login to be HTTP Basic -->
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>RealmUsersRoles</realm-name>
</login-config>
<servlet>
<servlet-name>bootstrap</servlet-name>
<servlet-class>org.jboss.as.quickstarts.ejb_security.SecuredEJBServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>bootstrap</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
standalone.xml
<security-domain name="custom" cache-type="default">
<authentication>
<login-module code="org.jboss.as.quickstarts.ejb_security.others.CMnEJBAuthenticator" flag="required">
<module-option name="unauthenticatedIdentity" value="Super"/>
</login-module>
</authentication>
</security-domain>
<security-domain name="servlet-security-quickstart" cache-type="default">
<authentication>
<login-module code="org.jboss.as.quickstarts.ejb_security.others.CMnAuthenticator" flag="required">
<module-option name="unauthenticatedIdentity" value="Super"/>
</login-module>
</authentication>
</security-domain>
Jaas Authentication:
package org.jboss.as.quickstarts.ejb_security.others;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.LoginContext;
import java.io.IOException;
public class CMnJAASLogin {
public static Subject loginMethod(){
LoginContext lc = null;
CallbackHandler cabHndlr = new CallbackHandler() {
#Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
NameCallback nc = (NameCallback) callbacks[i];
nc.setName("java");
} else if (callbacks[i] instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) callbacks[i];
pc.setPassword("java".toCharArray());
} else {
throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
}
}
}
};
try {
lc = new LoginContext("custom", cabHndlr);
lc.login();
return lc.getSubject();
}catch(Exception ex){
ex.printStackTrace();
}
return null;
}
}
Any idea what I am missing?
Note: I am working on JBoss EAP 6.4 and java 1.7
Adding #RunAs("java") to Servlet class solves this immediate problem.
But in case, i need to deny access for other users, RunAs annotation won't help there.
So, I am required to solve it in this way(if no user is calling the method/ejb/servlet, use "java" else use that users' role.
I have not tried this, but §15.3.1 of the servlet spec says that you just need to add a run-as element to your servlet definition in the web.xml:
<servlet>
<servlet-name>bootstrap</servlet-name>
<servlet-class>org.jboss.as.quickstarts.ejb_security.SecuredEJBServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<run-as>java</run-as>
</servlet>
However, it is not completely clear whether or not the actual authenticated principal will be propagated to the EJBs for the normally authenticated servlet calls. You will have to try it and see.
I solved it after using org.jboss.security.ClientLoginModule in AppConfigurationProperty.
Finally, JAAS class looks like this:
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CMnJAASLogin {
public static LoginContext loginMethod() {
LoginContext lc = null;
CallbackHandler cabHndlr = new CallbackHandler() {
#Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
NameCallback nc = (NameCallback) callbacks[i];
nc.setName("java");
} else if (callbacks[i] instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) callbacks[i];
pc.setPassword("java".toCharArray());
} else {
throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
}
}
}
};
try {
String configurationName = "JBoss Test";
Configuration config = new JBossJaasConfiguration(configurationName);
lc = new LoginContext(configurationName, new Subject(), cabHndlr, config);
return lc;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
static class JBossJaasConfiguration extends Configuration {
private final String configurationName;
JBossJaasConfiguration(String configurationName) {
this.configurationName = configurationName;
}
#Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
if (!configurationName.equals(name)) {
throw new IllegalArgumentException("Unexpected configuration name '" + name + "'");
}
return new AppConfigurationEntry[]{
createClientLoginModuleConfigEntry(),
};
}
private AppConfigurationEntry createClientLoginModuleConfigEntry() {
Map<String, String> options = new HashMap<String, String>();
options.put("multi-threaded", "true");
options.put("restore-login-identity", "true");
return new AppConfigurationEntry("org.jboss.security.ClientLoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
}
}
}
Whole project is uploaded to: https://github.com/shekharswaraj/EJBSecurity
NOTE: It is just a test project with many hard coded values. The whole project has been modified on top of ejb-security project from EAP6.4 quickstart.
Good morning.
I have a problem when I try to perform logout in the authenticated system via a digital certificate.
To better describe the problem is as follows:
The browser presented the certificates for authentication check box, selecting and providing the PIN for the certificate selected the system performs login normally. The problem is when the user triggers the logout button, it invalidates the session and redirects to the login screen again. However when the user clicks the button that redirects to a restricted area the browser should resubmit the certificate selection box, but the same goes direct, using the certificate information selected in the previous login.
If we stop the server or close and open the browser it will prompt the choice of certificate again.
standalone.xml:
<subsystem xmlns="urn:jboss:domain:web:1.1" default-virtual-server="default-host" native="false">
<connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http" redirect-port="8443"/>
<connector name="https" protocol="HTTP/1.1" scheme="https" socket-binding="https" secure="true">
<ssl key-alias="localhost" verify-client="true"/>
</connector>
<virtual-server name="default-host" enable-welcome-root="true">
<alias name="localhost"/>
<alias name="example.com"/>
</virtual-server>
web.xml:
<filter>
<filter-name>Authentication X509Certificate Filter</filter-name>
<filter-class>br.gov.sp.sefin.desif.security.servlet.AuthX509CertificateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Authentication X509Certificate Filter</filter-name>
<url-pattern>/pages/*</url-pattern>
</filter-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>pages/*</web-resource-name>
<url-pattern>/pages/*</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>CLIENT-CERT</auth-method>
</login-config>
Filter authentication AuthX509CertificateFilter :
public class AuthX509CertificateFilter implements Filter {
private static final String MS_005 = "MS_005";
private static final String URI_DEFINIR_IF = "/internet/pages/home.xhtml";
private Principal authenticatedUser;
#Inject
private RepresentanteBO representanteBO;
#Inject
private InstituicaoFinanceiraBO instituicaoFinanceiraBO;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
Object attrSessionValid = req.getSession().getAttribute("sessionValid");
Object attrSessionAuthenticated = req.getSession().getAttribute("authenticated");
Object attrSessionInstituicaoFinanceira = req.getSession().getAttribute("instituicaoFinanceiraInternet");
Boolean sessionValid = (Boolean) (attrSessionValid != null ? attrSessionValid : Boolean.FALSE);
Boolean sessionAuthenticated = (Boolean) (attrSessionAuthenticated != null ? attrSessionAuthenticated : Boolean.FALSE);
if(!sessionValid || (URI_DEFINIR_IF.equals(req.getRequestURI()) && attrSessionInstituicaoFinanceira == null)) {
X509Certificate certs[] = (X509Certificate[] )req.getAttribute("javax.servlet.request.X509Certificate");
if(certs != null) {
X509Certificate t = (X509Certificate) certs[0];
Principal subjectDN = t.getSubjectDN();
authenticatedUser = subjectDN;
sessionAuthenticated = validarAutenticacao(subjectDN, req, resp);
chain.doFilter(new HttpServletRequestWrapper(req) {
#Override
public Principal getUserPrincipal() {
return authenticatedUser;
}
}, response);
}
} else {
Principal userPrincipal = req.getUserPrincipal();
if(userPrincipal != null) {
sessionAuthenticated = validarAutenticacao(userPrincipal, req, resp);
}
chain.doFilter(new HttpServletRequestWrapper(req) {
#Override
public Principal getUserPrincipal() {
return authenticatedUser;
}
}, response);
}
if(!resp.isCommitted() && !sessionAuthenticated) {
Object attribute = req.getSession().getAttribute("cpfCnpj");
if(attribute != null)
req.getSession().setAttribute(MS_005, MessagePtBrUtil.recupera(MS_005, UtilFormatter.formatarCPF((String) attribute)));
RequestDispatcher dispatcher = req.getRequestDispatcher("../login.xhtml");
dispatcher.forward(req, resp);
}
}
public void atualizarDadosDeSessao(HttpServletRequest req, Boolean sessionValid, Boolean sessionAuthenticated) {
req.getSession().setAttribute("sessionValid", sessionValid);
req.getSession().setAttribute("authenticated", sessionAuthenticated);
}
public Boolean validarAutenticacao(Principal userPrincipal, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Boolean sessionValid = Boolean.TRUE;
Boolean sessionAuthenticated = Boolean.TRUE;
String[] cn = userPrincipal.getName().split(",");
String cpfCnpj = cn[0].split(":")[1];
req.getSession().setAttribute("cpfCnpj", cpfCnpj);
BigInteger raizCnpj = new BigInteger(cpfCnpj.substring(0, 8));
if(cpfCnpj.length() == 14 && instituicaoFinanceiraBO.verificarInstituicaoFinanceiraRaizCnpj(raizCnpj)) {
RequestDispatcher dispatcher = req.getRequestDispatcher("../pages/home.xhtml");
dispatcher.forward(req, resp);
} else {
BigInteger cpf = new BigInteger(cpfCnpj);
if(representanteBO.verificarRepresentanteInstituicaoFinanceira(cpf)) {
RequestDispatcher dispatcher = req.getRequestDispatcher("../pages/autenticarusuario/definirInstituicaoFinanceira.xhtml?cpf="+cpf);
dispatcher.forward(req, resp);
} else { // não tem instituição financeira vinculada ao CPF
sessionValid = Boolean.FALSE; sessionAuthenticated = Boolean.FALSE;
}
}
atualizarDadosDeSessao(req, sessionValid, sessionValid);
return sessionValid && sessionAuthenticated;
}
#Override
public void destroy() {
}
}
Logout method:
public void sair() {
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
this.inserirLogAuditoriaLogout();
context.invalidateSession();
HttpServletRequest request = (HttpServletRequest) context.getRequest();
request.getSession().setAttribute("sessionValid", Boolean.FALSE);
request.getSession().setAttribute("authenticated", Boolean.FALSE);
try {
request.logout();
context.redirect("/internet/login.xhtml");
} catch (IOException e) {
new IOException();
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I've tried using some javascript solutions to perform the cleaning of the certificate for authentication data stored in the browser. Example:
window.crypto.logout();
document.execCommand("ClearAuthenticationCache");
function logOut()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.timeout = 2000; // 2 seconds
xmlHttp.onreadystatechange = function ()
{
if (xmlHttp.readyState == 4)
{
console.log("status: "+xmlHttp.status);
console.log("response: '"+xmlHttp.responseText+"'");
}
};
xmlHttp.open("GET", "/internet/login.xhtml", true);
xmlHttp.send();
}
But did not work.
Please if anyone has been there and succeeded in solve it present your solution.
I hope I can have been clear in the description of the problem. I am available to best describes it.
I thank you so much attention.
I have a JSF application that uses several java classes to do dynamic compilation of java code.
Code is written in a text area and compiled by pressing an h:commandButton via Ajax.
Problem occurs when i press more than 2 or 3 times to compile different codes.
Here is the stack trace :
javax.faces.application.ViewExpiredException: viewId:/home.xhtml - View /home.xhtml could not be restored.
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:210)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:121)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Unknown Source)
If i set the attribute transient=true to f:view, the problem stops since the state is not saved, but that restricts me from using other functionality like saving my source file in database for user to retrieve in later time.
home.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Home Page</title>
</h:head>
<h:body>
<f:view transient="true">
<h:form prependId="false">
<h:panelGrid columns="1">
<h:inputTextarea id="codeArea" rows="25" cols="70" value="#{user.userInputCode}" />
<h:outputText id="messages" value="#{user.compilationMessages}"/>
</h:panelGrid>
<h:commandButton value="Compile">
<f:ajax execute="codeArea" render="messages" listener="#{user.compileCode()}"/>
</h:commandButton>
</h:form>
</f:view>
</h:body>
</html>
UserBean
#Named(value = "user")
#SessionScoped
public class UserBean implements Serializable {
private String userInputCode;
private String compilationMessages;
private CompilerBean compiler;
public UserBean() {
compiler = new CompilerBean();
userInputCode = compiler.getDefaultCodeModel();
}
public String getUserInputCode() {
return userInputCode;
}
public void setUserInputCode(String userInputCode) {
this.userInputCode = userInputCode;
}
public String getCompilationMessages() {
return compilationMessages;
}
public void compileCode() throws Exception {
if (!compiler.isValidClass(userInputCode)) {
compilationMessages = "Please provide a correct class format";
} else {
if (compiler.compile(userInputCode)) {
compilationMessages = "Compilation Success!";
} else {
compilationMessages = compiler.getDiagnosticMessages();
}
}
}
Compiler
public class CompilerBean implements CompilationInterface {
private JavaCompiler compiler;
private DiagnosticCollector diagCollector;
private StandardJavaFileManager fileManager;
private String sourceFile;
public CompilerBean() {
sourceFile = DEFAULT_SOURCEFILE;
}
public boolean compile(String inputCode) throws Exception {
compiler = ToolProvider.getSystemJavaCompiler();
diagCollector = new DiagnosticCollector();
fileManager = compiler.getStandardFileManager(diagCollector, null, null);
File outputFile = new File(CLASS_FILES_PATH);
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(outputFile));
String className = extractClassName(inputCode);
sourceFile = className + JAVA_POSTFIX;
JavaFileObject sourceObject = new CompilerJavaObject(sourceFile, inputCode);
Iterable<? extends JavaFileObject> fileObjects = Arrays.asList(sourceObject);
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagCollector, null, null, fileObjects);
deleteCompiledFiles();
return task.call();
}
public String getDiagnosticMessages() {
String message = "";
List<Diagnostic> diagErrors = diagCollector.getDiagnostics();
for (Diagnostic d : diagErrors) {
message = ("Error: " + d.getLineNumber() + " Cause: " + d.getMessage(null));
}
return message;
}
private void deleteCompiledFiles() {
File f = new File(CLASS_FILES_PATH);
for (File classFile : f.listFiles()) {
classFile.delete();
}
}
public String getDefaultCodeModel() {
return DEFAULT_CLASS_MODEL;
}
public String getSourceFile() {
return sourceFile;
}
/*
* Extracts the class name from the input code
*/
private String extractClassName(String input) {
String className = input.replaceAll(COMMENTS_REGEX, "");
className = className.replaceAll(IMPORTS_REGEX, "");
className = className.replaceAll(CLASS_BODY, "");
className = className.replaceAll(CLASS_REGEX, "").trim();
return className;
}
/*
* Checks if the input code is in a valid class format
*/
public boolean isValidClass(String input) {
Pattern pat1 = Pattern.compile(COMMENTS_REGEX);
Pattern pat2 = Pattern.compile(IMPORTS_REGEX);
Pattern pat3 = Pattern.compile(CLASS_REGEX);
Matcher m1 = pat1.matcher(input);
Matcher m2 = pat2.matcher(input);
Matcher m3 = pat3.matcher(input);
return m3.lookingAt() || m1.lookingAt() || m2.lookingAt();
}
}
Compiler uses 2 more class an Interface with some String constants and a class that extends SimpleJavaFileObject
There are a few approaches you can take:
Turn partial-state saving true in web.xml
<context-param>
<param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
<param-value>true</param-value>
</context-param>
Increase the number of logical views in session. Note that JSF caches your views and there is a limit to that cache.
<context-param>
<param-name>com.sun.faces.NUMBER_OF_LOGICAL_VIEWS_IN_SESSION</param-name>
<param-value>50</param-value>
</context-param>
In cases where the above doesn't solve your problem, write a handler for ViewExpiredException and restore the view programatically. This will refresh your view on the client side(might not be the best user experience, though)
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.application.ViewHandlerWrapper;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
public class MyViewExpiredHandler extends ViewHandlerWrapper {
private ViewHandler wrapped;
private static Map<String, Boolean> viewsToProcess = new HashMap<String, Boolean>();
//assuming these xhtmls throw ViewExpiredException
static {
viewsToProcess.put("/view/xxxx.xhtml", true);
viewsToProcess.put("/view/aaa.xhtml", true);
viewsToProcess.put("/view/yyy.xhtml", true);
}
public MyViewExpiredHandler(ViewHandler parent) {
this.wrapped = parent;
}
#Override
public ViewHandler getWrapped() {
return wrapped;
}
#Override
public UIViewRoot restoreView(FacesContext context, String viewId) {
UIViewRoot viewRoot = super.restoreView(context, viewId);
if(viewsToProcess.containsKey(viewId) && viewRoot == null) {
viewRoot = super.createView(context, viewId);
super.initView(context);
try {
super.renderView(context, viewRoot);
} catch (FacesException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return viewRoot;
}
}
I re factor and move JSF managed bean from one package to another package in Netbeans JSF application. Intermittently I get an error stating that the moved bean is not found in the previous location. I clean and build several times. Still the issue persists. I restarted the GlassFish and even the computer. I find in project including the generate sources, but I could not locate any reference to that Bean. I add the current location to the faces-config.xml, still no result.
The Previous Package is com.divudi.bean
New Package is com.divudi.bean.lab
The Error Message is
SEVERE: Exception while loading the app : com/divudi/bean/CollectingCentreController
java.lang.NoClassDefFoundError: com/divudi/bean/CollectingCentreController
at java.lang.Class.getDeclaringClass(Native Method)
at java.lang.Class.getEnclosingClass(Class.java:1107)
at java.lang.Class.getSimpleBinaryName(Class.java:1242)
at java.lang.Class.isMemberClass(Class.java:1232)
at org.jboss.weld.util.reflection.Reflections.isNonStaticInnerClass(Reflections.java:139)
at org.jboss.weld.bootstrap.BeanDeployer.addClass(BeanDeployer.java:78)
at org.jboss.weld.bootstrap.BeanDeployer.addClasses(BeanDeployer.java:123)
at org.jboss.weld.bootstrap.BeanDeployment.createBeans(BeanDeployment.java:184)
at org.jboss.weld.bootstrap.WeldBootstrap.deployBeans(WeldBootstrap.java:350)
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:179)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:128)
at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:277)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:460)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:461)
at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:212)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.ClassNotFoundException: com.divudi.bean.CollectingCentreController
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
... 41 more
The Bean is (Before Adding to faces-config.xml, where annotation is used)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.divudi.bean.lab;
import com.divudi.bean.SessionController;
import com.divudi.bean.UtilityController;
import com.divudi.data.InstitutionType;
import com.divudi.entity.Institution;
import com.divudi.facade.InstitutionFacade;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
/**
*
* #author www.divudi.com
*/
#ManagedBean
public class CollectingCentreController {
/**
* Creates a new instance of CollectingCentreController
*/
public CollectingCentreController() {
}
private static final long serialVersionUID = 1L;
#ManagedProperty(value = "#{sessionController}")
SessionController sessionController;
#EJB
private InstitutionFacade ejbFacade;
List<Institution> selectedItems;
private Institution current;
private List<Institution> items = null;
String selectText = "";
public List<Institution> getSelectedItems() {
selectedItems = getFacade().findBySQL("select c from Institution c where c.retired=false and i.institutionType = com.divudi.data.InstitutionType.CollectingCentre and upper(c.name) like '%" + getSelectText().toUpperCase() + "%' order by c.name");
return selectedItems;
}
public void prepareAdd() {
current = new Institution();
current.setInstitutionType(InstitutionType.CollectingCentre);
}
public void setSelectedItems(List<Institution> selectedItems) {
this.selectedItems = selectedItems;
}
public String getSelectText() {
return selectText;
}
private void recreateModel() {
items = null;
}
public void saveSelected() {
if (getCurrent().getId() != null && getCurrent().getId() > 0) {
getFacade().edit(current);
UtilityController.addSuccessMessage("savedOldSuccessfully");
} else {
current.setCreatedAt(Calendar.getInstance(TimeZone.getTimeZone("IST")).getTime());
current.setCreater(sessionController.getLoggedUser());
getFacade().create(current);
UtilityController.addSuccessMessage("savedNewSuccessfully");
}
recreateModel();
getItems();
}
public void setSelectText(String selectText) {
this.selectText = selectText;
}
public InstitutionFacade getEjbFacade() {
return ejbFacade;
}
public void setEjbFacade(InstitutionFacade ejbFacade) {
this.ejbFacade = ejbFacade;
}
public SessionController getSessionController() {
return sessionController;
}
public void setSessionController(SessionController sessionController) {
this.sessionController = sessionController;
}
public Institution getCurrent() {
if (current == null) {
current = new Institution();
current.setInstitutionType(InstitutionType.CollectingCentre);
}
return current;
}
public void setCurrent(Institution current) {
this.current = current;
}
public void delete() {
if (current != null) {
current.setRetired(true);
current.setRetiredAt(Calendar.getInstance(TimeZone.getTimeZone("IST")).getTime());
current.setRetirer(sessionController.getLoggedUser());
getFacade().edit(current);
UtilityController.addSuccessMessage("DeleteSuccessfull");
} else {
UtilityController.addSuccessMessage("NothingToDelete");
}
recreateModel();
getItems();
current = null;
getCurrent();
}
private InstitutionFacade getFacade() {
return ejbFacade;
}
public List<Institution> getItems() {
// items = getFacade().findAll("name", true);
String sql = "SELECT i FROM Institution i where i.retired=false and i.institutionType = com.divudi.data.InstitutionType.CollectingCentre order by i.name";
items = getEjbFacade().findBySQL(sql);
if (items == null) {
items = new ArrayList<Institution>();
}
return items;
}
}
This question already has answers here:
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
(18 answers)
Closed 7 years ago.
I know there is something wrong with the managedBean but i cant figure out what it is
When I try departmentManagedBean.department.faculty.facultyName from the jsf page it gives a null pointer like this:
javax.el.PropertyNotFoundException: /administrator/department/DepartmentRegistration.xhtml #30,260 value="#{departmentRequestBean.department.faculty.facultyName}": Target Unreachable, 'null' returned null
javax.el.PropertyNotFoundException: /administrator/department/DepartmentRegistration.xhtml #30,260 value="#{departmentRequestBean.department.faculty.facultyName}": Target Unreachable, 'null' returned null
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:100)
at org.richfaces.component.util.InputUtils.findConverter(InputUtils.java:123)
at org.richfaces.component.util.InputUtils$1.getConverterByProperty(InputUtils.java:56)
at org.richfaces.component.util.InputUtils.getConvertedValue(InputUtils.java:148)
at org.richfaces.component.util.InputUtils.getConvertedValue(InputUtils.java:137)
at org.richfaces.renderkit.InputRendererBase.getConvertedValue(InputRendererBase.java:50)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030)
at javax.faces.component.UIInput.validate(UIInput.java:960)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1233)
at javax.faces.component.UIInput.processValidators(UIInput.java:698)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIForm.processValidators(UIForm.java:253)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1172)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:636)
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "DepartmentID")
private Integer departmentID;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "DepartmentName")
private String departmentName;
#JoinColumn(name = "FacultyName", referencedColumnName = "FacultyName")
#ManyToOne(optional = false, fetch = FetchType.EAGER)
public Faculty faculty;
public Faculty getFaculty() {
return faculty;
}
public void setFaculty(Faculty faculty) {
this.faculty = faculty;
}
public Department() {
}
public Department(Integer departmentID) {
this.departmentID = departmentID;
}
public Department(Integer departmentID, String departmentName) {
this.departmentID = departmentID;
this.departmentName = departmentName;
}
public Integer getDepartmentID() {
return departmentID;
}
public void setDepartmentID(Integer departmentID) {
this.departmentID = departmentID;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
}
public class DepartmentSessionBean {
#PersistenceContext(unitName = "ApplicationPU")
private EntityManager em;
public void persist(Department department) {
em.persist(department);
}
}
public class Faculty implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "FacultyID")
private Integer facultyID;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "FacultyName")
private String facultyName;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "faculty", fetch = FetchType.EAGER)
private List<Department> departmentList;
public Faculty() {
}
public Faculty(Integer facultyID) {
this.facultyID = facultyID;
}
public Faculty(Integer facultyID, String facultyName) {
this.facultyID = facultyID;
this.facultyName = facultyName;
}
public Integer getFacultyID() {
return facultyID;
}
public void setFacultyID(Integer facultyID) {
this.facultyID = facultyID;
}
public String getFacultyName() {
return facultyName;
}
public void setFacultyName(String facultyName) {
this.facultyName = facultyName;
}
public List<Department> getDepartmentList() {
return departmentList;
}
public void setDepartmentList(List<Department> departmentList) {
this.departmentList = departmentList;
}
}
This is the ManagedBean that I need a solution with please:
#ViewScoped public class DepartmentRequestBean {
#EJB
private DepartmentSessionBean departmentSessionBean;
private Department department = new Department();
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public void save(){
departmentSessionBean.persist(department);
}
public DepartmentRequestBean() {
this.faculty = new Faculty();
}}
value="#{departmentRequestBean.department.faculty.facultyName}": Target Unreachable, 'null' returned null
This basically means that one of the following values
#{departmentRequestBean.department}
#{departmentRequestBean.department.faculty}
returned null during processing of the form submit. As you've explicitly created the Department yourself, then it can only mean that Faculty is still null.
To fix it properly, replace in DepartmentRequestBean
private Department department = new Department();
by
private Department department;
#PostConstruct
public void init() {
department = new Department();
department.setFaculty(new Faculty());
}
initialize your department class in backing bean like this way
public Department getDepartment() {
if(department == null){
department = (Department)super.getInstance(Department.class);
}
return department;
}
this will create a new department object if the object become null