Java/EJB3/Interceptor
Содержание
- 1 annotation override interceptor
- 2 Around InvokeMethod
- 3 EJB Tutorial from JBoss: Callback Listener
- 4 EJB Tutorial from JBoss: Interceptor
- 5 Get Ejb Info From InvocationContext
- 6 Get Set Parameters In InvocationContext
- 7 interceptor stateless
- 8 Mark Interceptors For A Remote Method
- 9 Use Interceptors To Check Permission
annotation override interceptor
<source lang="java">
/*
* The contents of this file are subject to the terms * of the Common Development and Distribution License * (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the license at * https://glassfish.dev.java.net/public/CDDLv1.0.html or * glassfish/bootstrap/legal/CDDLv1.0.txt. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * Header Notice in each file and include the License file * at glassfish/bootstrap/legal/CDDLv1.0.txt. * If applicable, add the following below the CDDL Header, * with the fields enclosed by brackets [] replaced by * you own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. */
package enterprise.annotation_override_interceptor_appclient; import java.util.List; import javax.ejb.EJB; import enterprise.annotation_override_interceptor_ejb.*; public class StatelessSessionAppClient {
@EJB private static StatelessSession sless; public static void main(String args[]) { try { sless.initUpperCase("hello, World!!"); sless.initLowerCase("Build.xml"); } catch (Exception badEx) { badEx.printStackTrace(); } List<String> upperList = sless.getInterceptorNamesFor("initUpperCase"); printList("initUpperCase", upperList); try { sless.isOddNumber(7); } catch (Exception badEx) { badEx.printStackTrace(); } List<String> isOddNumberList = sless.getInterceptorNamesFor("isOddNumber"); printList("isOddNumber", isOddNumberList); } private static void printList(String msg, List<String> list) { System.out.print("Interceptors invoked for " + msg + "(): "); String delimiter = ""; for (String str : list) { System.out.print(delimiter + str); delimiter = ", "; } System.out.println("}"); }
}
/*
* The contents of this file are subject to the terms * of the Common Development and Distribution License * (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the license at * https://glassfish.dev.java.net/public/CDDLv1.0.html or * glassfish/bootstrap/legal/CDDLv1.0.txt. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * Header Notice in each file and include the License file * at glassfish/bootstrap/legal/CDDLv1.0.txt. * If applicable, add the following below the CDDL Header, * with the fields enclosed by brackets [] replaced by * you own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. */
package enterprise.annotation_override_interceptor_ejb; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import javax.ejb.Stateless; import javax.interceptor.Interceptors; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; // This bean uses two interceptors to validate // the input to its (only) business method. // Note that a single interceptor would suffice // but to demonstrate the use of interceptor // chaining, we use two interceptors @Stateless @Interceptors({ArgumentsChecker.class}) public class StatelessSessionBean
implements StatelessSession { private static final String KEY = "interceptorNameList"; private static Map<String, List<String>> interceptorNamesForMethod = new HashMap<String, List<String>>(); //The bean interceptor method just caches the interceptor names // in a map which is queried in the getInterceptorNamesFor() method @AroundInvoke private Object intercept(InvocationContext invCtx) throws Exception { System.out.println("Entered aroundInvoke for Bean"); Map<String, Object> ctxData = invCtx.getContextData(); List<String> interceptorNameList = (List<String>) ctxData.get(KEY); if (interceptorNameList == null) { interceptorNameList = new ArrayList<String>(); ctxData.put(KEY, interceptorNameList); } //Add this interceptor also to the list of interceptors invoked!! interceptorNameList.add("StatelessSessionBean"); //Cache the interceptor name list in a map that can be queried later String methodName = invCtx.getMethod().getName(); synchronized (interceptorNamesForMethod) { interceptorNamesForMethod.put(methodName, interceptorNameList); } return invCtx.proceed(); } // This business method is called after the interceptor methods. // Hence it is guaranteed that the argument to this method is not null // and it starts with a letter public String initUpperCase(String val) { String first = val.substring(0, 1); return first.toUpperCase() + val.substring(1); } // This business method is called after the interceptor methods. // Hence it is guaranteed that the argument to this method is not null // and it starts with a letter public String initLowerCase(String val) { String first = val.substring(0, 1); return first.toLowerCase() + val.substring(1); } //Note:- // Since this method takes a int as a parameter, the ArgumentChecker // inteceptor is disabled in the ejb-jar.xml for this method. public boolean isOddNumber(int val) { return ((val % 2) != 0); } /** * Only the default interceptor is used to intercept this method */ public List<String> getInterceptorNamesFor(String methodName) { return interceptorNamesForMethod.get(methodName); }
} /*
* The contents of this file are subject to the terms * of the Common Development and Distribution License * (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the license at * https://glassfish.dev.java.net/public/CDDLv1.0.html or * glassfish/bootstrap/legal/CDDLv1.0.txt. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * Header Notice in each file and include the License file * at glassfish/bootstrap/legal/CDDLv1.0.txt. * If applicable, add the following below the CDDL Header, * with the fields enclosed by brackets [] replaced by * you own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. */
package enterprise.annotation_override_interceptor_ejb; import java.util.List; import javax.ejb.Remote; @Remote public interface StatelessSession {
public String initUpperCase(String val) throws BadArgumentException; public String initLowerCase(String val) throws BadArgumentException; public boolean isOddNumber(int val) throws BadArgumentException; public List<String> getInterceptorNamesFor(String methodName);
} /*
* The contents of this file are subject to the terms * of the Common Development and Distribution License * (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the license at * https://glassfish.dev.java.net/public/CDDLv1.0.html or * glassfish/bootstrap/legal/CDDLv1.0.txt. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * Header Notice in each file and include the License file * at glassfish/bootstrap/legal/CDDLv1.0.txt. * If applicable, add the following below the CDDL Header, * with the fields enclosed by brackets [] replaced by * you own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. */
package enterprise.annotation_override_interceptor_ejb; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.lang.reflect.Method; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; /**
* This is the default interceptor */
public class NullChecker {
@AroundInvoke public Object checkIfNull(InvocationContext ctx) throws Exception { Map<String, Object> ctxData = ctx.getContextData(); List<String> interceptorNameList = (List<String>) ctxData.get("interceptorNameList"); if (interceptorNameList == null) { interceptorNameList = new ArrayList<String>(); ctxData.put("interceptorNameList", interceptorNameList); } //Now add this interceptor name to the list interceptorNameList.add("NullChecker"); Method method = ctx.getMethod(); Object param = ctx.getParameters()[0]; if (param == null) { // An interceptor can throw any runtime exception or // application exceptions that are allowed in the // throws clause of the business method throw new BadArgumentException("Illegal argument: null"); } // Proceed to the next interceptor OR business method return ctx.proceed(); }
}
</source>
Around InvokeMethod
<source lang="java">
File: Employee.java import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PostRemove; @Entity public class Employee implements java.io.Serializable {
private int id; private String firstName; private String lastName; @Id @GeneratedValue public int getId() { return id; }
@PostRemove public void postRemove() { System.out.println("@PostRemove"); } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String first) { this.firstName = first; } public String getLastName() { return lastName; } public void setLastName(String last) { this.lastName = last; }
}
File: EmployeeService.java import javax.ejb.Stateless; import javax.interceptor.Interceptors; @Stateless public class EmployeeService implements EmployeeServiceLocal, EmployeeServiceRemote {
public EmployeeService() { } @Interceptors(Profiler.class) public void doAction() { System.out.println("do Action"); }
}
File: EmployeeServiceLocal.java
import java.util.Collection; import javax.ejb.Local; @Local public interface EmployeeServiceLocal {
public void doAction();
}
File: EmployeeServiceRemote.java
import java.util.Collection;
import javax.ejb.Remote;
@Remote
public interface EmployeeServiceRemote{
public void doAction();
}
File: Profiler.java import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; public class Profiler {
@AroundInvoke public Object profile(InvocationContext invocation) throws Exception { long startTime = System.currentTimeMillis(); try { return invocation.proceed(); } finally { long endTime = System.currentTimeMillis() - startTime; System.out.println("Method " + invocation.getMethod() + " took " + endTime + " (ms)"); } }
}
File: jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099
File: Main.java import java.util.Date; import javax.naming.InitialContext;
public class Main {
public static void main(String[] a) throws Exception { EmployeeServiceRemote service = null; // Context compEnv = (Context) new InitialContext().lookup("java:comp/env"); // service = (HelloService)new InitialContext().lookup("java:comp/env/ejb/HelloService"); service = (EmployeeServiceRemote) new InitialContext().lookup("EmployeeService/remote");
service.doAction(); }
}
</source>
EJB Tutorial from JBoss: Callback Listener
<source lang="java">
File: CustomerCallbackListener.java /*
* JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */
package org.jboss.tutorial.callback.bean; import javax.persistence.PreRemove; import javax.persistence.PostRemove; import javax.persistence.PreUpdate; import javax.persistence.PostUpdate; import javax.persistence.PostLoad; import javax.persistence.PrePersist; import javax.persistence.PostPersist; /**
* @author
EJB Tutorial from JBoss: Interceptor
<source lang="java">
File: AccountsCancelInterceptor.java /*
* JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */
package org.jboss.tutorial.interceptor.bean; import javax.interceptor.InvocationContext; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; import javax.jms.QueueSender; import javax.jms.QueueSession; import javax.jms.Session; /**
* * @author
Get Ejb Info From InvocationContext
<source lang="java">
File: Employee.java import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PostRemove; @Entity public class Employee implements java.io.Serializable {
private int id; private String firstName; private String lastName; @Id @GeneratedValue public int getId() { return id; }
@PostRemove public void postRemove() { System.out.println("@PostRemove"); } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String first) { this.firstName = first; } public String getLastName() { return lastName; } public void setLastName(String last) { this.lastName = last; }
}
File: EmployeeBean.java import javax.ejb.Stateful; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; @Stateful public class EmployeeBean implements EmployeeServiceLocal, EmployeeServiceRemote {
public EmployeeBean() { } public void doAction() { System.out.println("Processing..."); } @AroundInvoke public Object TimerLog(InvocationContext ctx) throws Exception { String beanClassName = ctx.getClass().getName(); String businessMethodName = ctx.getMethod().getName(); String target = beanClassName + "." + businessMethodName; long startTime = System.currentTimeMillis(); System.out.println("Invoking " + target); try { return ctx.proceed(); } finally { System.out.println("Exiting " + target); long totalTime = System.currentTimeMillis() - startTime; System.out.println("Business method " + businessMethodName + "in " + beanClassName + "takes " + totalTime + "ms to execute"); } }
}
File: EmployeeServiceLocal.java import javax.ejb.Local; import javax.ejb.Remote;
@Local public interface EmployeeServiceLocal{
public void doAction();
}
File: EmployeeServiceRemote.java import javax.ejb.Remote; @Remote public interface EmployeeServiceRemote {
public void doAction();
}
File: jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099
File: Main.java import javax.ejb.EJB; import javax.naming.InitialContext; public class Main {
public static void main(String[] a) throws Exception { EmployeeServiceRemote service = null; // Context compEnv = (Context) new InitialContext().lookup("java:comp/env"); // service = (HelloService)new InitialContext().lookup("java:comp/env/ejb/HelloService"); service = (EmployeeServiceRemote) new InitialContext().lookup("EmployeeBean/remote"); service.doAction(); }
}
</source>
Get Set Parameters In InvocationContext
<source lang="java">
File: EmployeeBean.java
import javax.ejb.Stateless; import javax.interceptor.Interceptors; @Stateless @Interceptors( { MyInterceptor.class }) public class EmployeeBean implements EmployeeServiceLocal, EmployeeServiceRemote {
public EmployeeBean() { }
public Long addBid(String userId,Long itemId,Double bidPrice) { System.out.println("Bid for " + itemId + " received with price" + bidPrice); return 0L; }
}
File: EmployeeServiceLocal.java
import javax.ejb.Local; import javax.jws.WebParam; @Local public interface EmployeeServiceLocal {
public Long addBid(String userId,Long itemId,Double bidPrice);
}
File: EmployeeServiceRemote.java import javax.ejb.Remote;
@Remote public interface EmployeeServiceRemote {
public Long addBid(String userId,Long itemId,Double bidPrice);
}
File: MyInterceptor.java import javax.annotation.Resource; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; public class MyInterceptor {
@Resource private javax.ejb.SessionContext ctx; @AroundInvoke public Object checkUserRole(InvocationContext ic) throws Exception { System.out.println("Interceptor invoked for " + ic.getMethod().getName()); if (ic.getMethod().getName().equals("addBid") && (((String) (ic.getContextData().get("MemberStatus"))).equals("Gold"))) { Object[] params = ic.getParameters(); params[2] = new Double((Double) params[2] * 0.99); System.out.println("DiscountVerifier Reducing Price by 1 percent"); ic.setParameters(params); } return ic.proceed(); }
}
File: Employee.java
import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PostRemove; @Entity public class Employee implements java.io.Serializable {
private int id; private String firstName; private String lastName; @Id @GeneratedValue public int getId() { return id; }
@PostRemove public void postRemove() { System.out.println("@PostRemove"); } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String first) { this.firstName = first; } public String getLastName() { return lastName; } public void setLastName(String last) { this.lastName = last; }
}
File: Main.java import javax.ejb.EJB; import javax.naming.InitialContext;
public class Main {
public static void main(String[] a) throws Exception { EmployeeServiceRemote service = null; // Context compEnv = (Context) new InitialContext().lookup("java:comp/env"); // service = (HelloService)new // InitialContext().lookup("java:comp/env/ejb/HelloService"); service = (EmployeeServiceRemote) new InitialContext().lookup("EmployeeBean/remote");
service.addBid("userId",1L,0.1);
}
}
File: jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099
</source>
interceptor stateless
Mark Interceptors For A Remote Method
<source lang="java">
File: Employee.java
import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PostRemove; @Entity public class Employee implements java.io.Serializable {
private int id; private String firstName; private String lastName; @Id @GeneratedValue public int getId() { return id; }
@PostRemove public void postRemove() { System.out.println("@PostRemove"); } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String first) { this.firstName = first; } public String getLastName() { return lastName; } public void setLastName(String last) { this.lastName = last; }
}
File: EmployeeBean.java
import javax.ejb.Stateless; import javax.interceptor.Interceptors; @Stateless @Interceptors( { MyInterceptor.class }) public class EmployeeBean implements EmployeeServiceLocal, EmployeeServiceRemote {
public EmployeeBean() { } @Interceptors(MyInterceptor.class) public Long addBid(String userId,Long itemId,Double bidPrice) { System.out.println("Bid for " + itemId + " received with price" + bidPrice); return 0L; }
}
File: EmployeeServiceLocal.java
import javax.ejb.Local; import javax.jws.WebParam; @Local public interface EmployeeServiceLocal {
public Long addBid(String userId,Long itemId,Double bidPrice);
}
File: EmployeeServiceRemote.java import javax.ejb.Remote;
@Remote public interface EmployeeServiceRemote {
public Long addBid(String userId,Long itemId,Double bidPrice);
}
File: MyInterceptor.java import javax.annotation.Resource; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; public class MyInterceptor {
@Resource private javax.ejb.SessionContext ctx; @AroundInvoke public Object checkUserRole(InvocationContext ic) throws Exception { System.out.println("*** CheckPermission Interceptor invoked for " + ic.getTarget() + " ***"); if (!ctx.isCallerInRole("admin")) { throw new SecurityException("User: "" + ctx.getCallerPrincipal().getName() + "" does not have permissions for method " + ic.getMethod()); } return ic.proceed(); }
}
File: Main.java import javax.ejb.EJB; import javax.naming.InitialContext;
public class Main {
public static void main(String[] a) throws Exception { EmployeeServiceRemote service = null; // Context compEnv = (Context) new InitialContext().lookup("java:comp/env"); // service = (HelloService)new // InitialContext().lookup("java:comp/env/ejb/HelloService"); service = (EmployeeServiceRemote) new InitialContext().lookup("EmployeeBean/remote");
service.addBid("userId",1L,0.1);
}
}
File: jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099
</source>
Use Interceptors To Check Permission
<source lang="java">
File: EmployeeBean.java
import javax.ejb.Stateless; import javax.interceptor.Interceptors; @Stateless @Interceptors( { MyInterceptor.class }) public class EmployeeBean implements EmployeeServiceLocal, EmployeeServiceRemote {
public EmployeeBean() { } public Long addBid(String userId,Long itemId,Double bidPrice) { System.out.println("Bid for " + itemId + " received with price" + bidPrice); return 0L; }
}
File: EmployeeServiceLocal.java
import javax.ejb.Local; import javax.jws.WebParam; @Local public interface EmployeeServiceLocal {
public Long addBid(String userId,Long itemId,Double bidPrice);
}
File: EmployeeServiceRemote.java import javax.ejb.Remote;
@Remote public interface EmployeeServiceRemote {
public Long addBid(String userId,Long itemId,Double bidPrice);
}
File: MyInterceptor.java import javax.annotation.Resource; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; public class MyInterceptor {
@Resource private javax.ejb.SessionContext ctx; @AroundInvoke public Object checkUserRole(InvocationContext ic) throws Exception { System.out.println("*** CheckPermission Interceptor invoked for " + ic.getTarget() + " ***"); if (!ctx.isCallerInRole("admin")) { throw new SecurityException("User: "" + ctx.getCallerPrincipal().getName() + "" does not have permissions for method " + ic.getMethod()); } return ic.proceed(); }
}
File: Employee.java
import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PostRemove; @Entity public class Employee implements java.io.Serializable {
private int id; private String firstName; private String lastName; @Id @GeneratedValue public int getId() { return id; }
@PostRemove public void postRemove() { System.out.println("@PostRemove"); } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String first) { this.firstName = first; } public String getLastName() { return lastName; } public void setLastName(String last) { this.lastName = last; }
}
File: Main.java import javax.ejb.EJB; import javax.naming.InitialContext;
public class Main {
public static void main(String[] a) throws Exception { EmployeeServiceRemote service = null; // Context compEnv = (Context) new InitialContext().lookup("java:comp/env"); // service = (HelloService)new // InitialContext().lookup("java:comp/env/ejb/HelloService"); service = (EmployeeServiceRemote) new InitialContext().lookup("EmployeeBean/remote");
service.addBid("userId",1L,0.1);
}
}
File: jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099
</source>