package org.mockejb;
import java.io.Serializable;
import java.security.Identity;
import java.security.Principal;
import java.util.Properties;
import javax.ejb.*;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
public class MockEjbContext implements SessionContext, MessageDrivenContext, EntityContext, Serializable {
private Object homeProxy;
private Object ejbObjectProxy;
private Object primaryKey;
MockEjbContext( final Object homeProxy ){
this.homeProxy = homeProxy;
}
void setEjbObjectProxy( final Object ejbObjectProxy ){
this.ejbObjectProxy = ejbObjectProxy;
}
public boolean isRemote(){
if ( ejbObjectProxy == null )
throw new IllegalStateException( "Can't determine the type. Most likely this EJB has not bean created yet");
return ( EJBObject.class.isAssignableFrom( ejbObjectProxy.getClass() ) );
}
public EJBHome getEJBHome() {
if ( homeProxy == null )
throw new IllegalStateException( "This EJB does not have Home interface");
return (EJBHome) homeProxy;
}
public EJBLocalHome getEJBLocalHome() {
if ( homeProxy == null )
throw new IllegalStateException( "This EJB does not have Local Home interface");
return (EJBLocalHome) homeProxy;
}
public Properties getEnvironment() {
return new Properties();
}
public Identity getCallerIdentity() {
throwMethodNotImplemented( "getCallerIdentity");
return null;
}
public Principal getCallerPrincipal() {
return MockContainer.getUser();
}
public boolean isCallerInRole(Identity arg0) {
throwMethodNotImplemented( "isCallerInRole");
return false;
}
public boolean isCallerInRole(String role) {
return MockContainer.getUser().hasRole( role );
}
public UserTransaction getUserTransaction() throws IllegalStateException {
UserTransaction tran = TransactionManager.getUserTransaction();
return tran;
}
public void setRollbackOnly() throws IllegalStateException {
UserTransaction tran = getUserTransaction();
try {
tran.setRollbackOnly();
}
catch( SystemException se ){
throw new EJBException("Error trying to call setRollbackOnly on transaction", se);
}
}
public boolean getRollbackOnly() throws IllegalStateException {
int status = Status.STATUS_UNKNOWN;
UserTransaction tran = getUserTransaction();
try {
status = tran.getStatus();
}
catch( SystemException se ){
throw new EJBException("Error trying to call getStatus on transaction", se);
}
return( status == Status.STATUS_MARKED_ROLLBACK );
}
public EJBLocalObject getEJBLocalObject() throws IllegalStateException {
return (EJBLocalObject)ejbObjectProxy;
}
public EJBObject getEJBObject() throws IllegalStateException {
return (EJBObject)ejbObjectProxy;
}
private void throwMethodNotImplemented( String methodName ){
throw new MethodNotImplementedException( methodName,
this.getClass().getName() );
}
public Object getPrimaryKey() throws IllegalStateException {
return primaryKey;
}
public void setPrimaryKey( Object primaryKey ){
this.primaryKey = primaryKey;
}
}