Input: / * ( non - Javadoc ) [CODESPLIT] public void fireEvent ( Object event , EventTypeID eventType , ExternalActivityHandle activityHandle , Address address ) throws NullPointerException , UnrecognizedActivityException , UnrecognizedEventException , ResourceException { if ( service == null ) { throw new ResourceException ( "Connection is in closed state" ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "fireEvent(event=" + event + ",eventType=" + eventType + ",activityHandle=" + activityHandle + ",address=" + address + ")" ) ; } this . service . fireEvent ( event , eventType , activityHandle , address ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public EventTypeID getEventTypeID ( String name , String vendor , String version ) throws UnrecognizedEventException , ResourceException { if ( service == null ) { throw new ResourceException ( "Connection is in closed state" ) ; } return service . getEventTypeID ( name , vendor , version ) ; }


Input:
/ * ( non - Javadoc ) [CODESPLIT] public SleeConnection getConnection ( ) throws ResourceException { //this method is listed as MBean method, upon lookup in jmx console it will create connection, its a possible leak
 //with list.
 synchronized ( connectionList ) { SleeConnectionImpl conn ; if ( connectionList . size ( ) > 0 ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Using connection from pool." ) ; } conn = ( SleeConnectionImpl ) connectionList . remove ( 0 ) ; conn . start ( this . service ) ; } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Creating new connection." ) ; } conn = new SleeConnectionImpl ( this . service , this ) ; } return conn ; } }


Input: Invoked from pool . [CODESPLIT] public void setProfileContext ( ProfileContextImpl profileContext ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "[setProfileContext] " + this ) ; } if ( profileContext == null ) { throw new NullPointerException ( "Passed context must not be null." ) ; } if ( state != ProfileObjectState . DOES_NOT_EXIST ) { throw new IllegalStateException ( "Wrong state: " + this . state + ",on profile set context operation, for profile table: " + this . profileTable . getProfileTableName ( ) + " with specification: " + this . profileTable . getProfileSpecificationComponent ( ) . getProfileSpecificationID ( ) ) ; } this . profileContext = profileContext ; this . profileContext . setProfileObject ( this ) ; if ( profileConcreteClassInfo . isInvokeSetProfileContext ( ) ) { final ClassLoader oldClassLoader = SleeContainerUtils . getCurrentThreadClassLoader ( ) ; try { final ClassLoader cl = this . profileTable . getProfileSpecificationComponent ( ) . getClassLoader ( ) ; if ( System . getSecurityManager ( ) != null ) { AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { Thread . currentThread ( ) . setContextClassLoader ( cl ) ; return null ; } } ) ; } else { Thread . currentThread ( ) . setContextClassLoader ( cl ) ; } try { if ( isSlee11 ) { try { profileConcrete . setProfileContext ( profileContext ) ; } catch ( RuntimeException e ) { runtimeExceptionOnProfileInvocation ( e ) ; } } } catch ( Exception e ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "Exception encountered while setting profile context for profile table: " + this . profileTable . getProfileTableName ( ) + " with specification: " + this . profileTable . getProfileSpecificationComponent ( ) . getProfileSpecificationID ( ) , e ) ; } } finally { if ( System . getSecurityManager ( ) != null ) { AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; return null ; } } ) ; } else { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; } } } state = ProfileObjectState . POOLED ; }


Input: initialize state from default profile [CODESPLIT] private void profileInitialize ( String profileName ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "[profileInitialize] " + this + " , profileName = " + profileName ) ; } if ( this . state != ProfileObjectState . POOLED ) { throw new SLEEException ( this . toString ( ) ) ; } if ( profileName == null ) { // default profile creation // create instance of entity profileEntity = profileEntityFramework . getProfileEntityFactory ( ) . newInstance ( profileTable . getProfileTableName ( ) , null ) ; // change state this . state = ProfileObjectState . PROFILE_INITIALIZATION ; // invoke life cycle method on profile if ( profileConcreteClassInfo . isInvokeProfileInitialize ( ) ) { try { profileConcrete . profileInitialize ( ) ; } catch ( RuntimeException e ) { runtimeExceptionOnProfileInvocation ( e ) ; } } } else { // load the default profile entity if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Copying state from default profile on object " + this ) ; } profileEntity = cloneEntity ( profileTable . getDefaultProfileEntity ( ) ) ; profileEntity . setProfileName ( profileName ) ; } // mark entity as dirty and for creation profileEntity . create ( ) ; profileEntity . setDirty ( true ) ; }


Input: Invoked when pool removes object [CODESPLIT] public void unsetProfileContext ( ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "[unsetProfileContext] " + this ) ; } if ( state == ProfileObjectState . POOLED && profileConcreteClassInfo . isInvokeUnsetProfileContext ( ) ) { final ClassLoader oldClassLoader = SleeContainerUtils . getCurrentThreadClassLoader ( ) ; try { final ClassLoader cl = profileTable . getProfileSpecificationComponent ( ) . getClassLoader ( ) ; if ( System . getSecurityManager ( ) != null ) { AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { Thread . currentThread ( ) . setContextClassLoader ( cl ) ; return null ; } } ) ; } else { Thread . currentThread ( ) . setContextClassLoader ( cl ) ; } if ( isSlee11 ) { try { profileConcrete . unsetProfileContext ( ) ; } catch ( RuntimeException e ) { runtimeExceptionOnProfileInvocation ( e ) ; } } profileContext . setProfileObject ( null ) ; state = ProfileObjectState . DOES_NOT_EXIST ; } finally { if ( System . getSecurityManager ( ) != null ) { AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; return null ; } } ) ; } else { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; } } } }


Input: Retrieves the local representation for this profile object [CODESPLIT] public ProfileLocalObject getProfileLocalObject ( ) { final Class < ? > profileLocalObjectConcreteClass = profileTable . getProfileSpecificationComponent ( ) . getProfileLocalObjectConcreteClass ( ) ; ProfileLocalObject profileLocalObject = null ; if ( profileLocalObjectConcreteClass == null ) { profileLocalObject = new ProfileLocalObjectImpl ( this ) ; } else { try { profileLocalObject = ( ProfileLocalObject ) profileLocalObjectConcreteClass . getConstructor ( ProfileObjectImpl . class ) . newInstance ( this ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } return profileLocalObject ; }


Input: Fires a profile added or updated event if the profile object state is ready and the persistent state is dirty [CODESPLIT] public void fireAddOrUpdatedEventIfNeeded ( ) { if ( state == ProfileObjectState . READY ) { if ( profileEntity . isDirty ( ) ) { // check the table fires events and the object is not assigned to a default profile if ( profileTable . doesFireEvents ( ) && profileEntity . getProfileName ( ) != null && profileTable . getSleeContainer ( ) . getSleeState ( ) == SleeState . RUNNING ) { // Fire a Profile Added or Updated Event ActivityContext ac = profileTable . getActivityContext ( ) ; AbstractProfileEvent event = null ; if ( profileEntity . isCreate ( ) ) { if ( persisted ) { event = new ProfileAddedEventImpl ( profileEntity , profileTable . getProfileManagement ( ) ) ; persisted = false ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "firing profile added event for profile named " + profileEntity ) ; } } else { return ; } } else { event = new ProfileUpdatedEventImpl ( profileEntitySnapshot , profileEntity , profileTable . getProfileManagement ( ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "firing profile updated event for profile named " + profileEntity ) ; } } ac . fireEvent ( event . getEventTypeID ( ) , event , event . getProfileAddress ( ) , null , null , null , null ) ; } } } }


Input: Retrieves the profile cmp slee 1 . 0 wrapper for this profile object [CODESPLIT] public AbstractProfileCmpSlee10Wrapper getProfileCmpSlee10Wrapper ( ) { if ( profileCmpSlee10Wrapper == null ) { try { profileCmpSlee10Wrapper = ( AbstractProfileCmpSlee10Wrapper ) profileTable . getProfileSpecificationComponent ( ) . getProfileCmpSlee10WrapperClass ( ) . getConstructor ( ProfileObjectImpl . class ) . newInstance ( this ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } return profileCmpSlee10Wrapper ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { final ServiceID serviceID = new ServiceID ( in . readUTF ( ) , in . readUTF ( ) , in . readUTF ( ) ) ; activityHandle = new ServiceActivityHandleImpl ( serviceID ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void writeExternal ( ObjectOutput out ) throws IOException { final ServiceID serviceID = activityHandle . getServiceID ( ) ; out . writeUTF ( serviceID . getName ( ) ) ; out . writeUTF ( serviceID . getVendor ( ) ) ; out . writeUTF ( serviceID . getVersion ( ) ) ; }


Input: Retrieves the JAIN SLEE specs descriptor [CODESPLIT] public javax . slee . management . LibraryDescriptor getSpecsDescriptor ( ) { if ( specsDescriptor == null ) { final LibraryID [ ] libraryIDs = descriptor . getLibraryRefs ( ) . toArray ( new LibraryID [ descriptor . getLibraryRefs ( ) . size ( ) ] ) ; final JarDescriptor [ ] jars = descriptor . getJars ( ) . toArray ( new JarDescriptor [ descriptor . getJars ( ) . size ( ) ] ) ; String [ ] libraryJars = new String [ jars . length ] ; int i = 0 ; for ( JarDescriptor jar : jars ) { libraryJars [ i ++ ] = jar . getJarName ( ) ; } specsDescriptor = new javax . slee . management . LibraryDescriptor ( getLibraryID ( ) , getDeployableUnit ( ) . getDeployableUnitID ( ) , getDeploymentUnitSource ( ) , libraryIDs , libraryJars ) ; } return specsDescriptor ; }


Input: Creates a class with the desired name and linked to the mentioned interfaces . [CODESPLIT] public static CtClass createClass ( String className , String [ ] interfaces ) throws Exception { if ( className == null ) { throw new NullPointerException ( "Class name cannot be null" ) ; } CtClass clazz = classPool . makeClass ( className ) ; if ( interfaces != null && interfaces . length > 0 ) { clazz . setInterfaces ( classPool . get ( interfaces ) ) ; } return clazz ; }


Input: Create the links with possible interfaces [CODESPLIT] public static void createInterfaceLinks ( CtClass concreteClass , String [ ] interfaceNames ) { if ( interfaceNames != null && interfaceNames . length > 0 ) { try { for ( String interfaceName : interfaceNames ) { boolean found = false ; for ( CtClass existingInterfaces : concreteClass . getInterfaces ( ) ) { if ( existingInterfaces . getName ( ) . equals ( interfaceName ) ) found = true ; } if ( ! found ) concreteClass . addInterface ( classPool . get ( interfaceName ) ) ; } } catch ( NotFoundException e ) { e . printStackTrace ( ) ; } } }


Input: Create the inheritance link with the absract class provided by the developer [CODESPLIT] public static void createInheritanceLink ( CtClass concreteClass , String superClassName ) { if ( superClassName != null && superClassName . length ( ) >= 0 ) { try { concreteClass . setSuperclass ( classPool . get ( superClassName ) ) ; } catch ( CannotCompileException e ) { e . printStackTrace ( ) ; } catch ( NotFoundException e ) { e . printStackTrace ( ) ; } } }


Input: Adds a field of the desired type to the declaring class . [CODESPLIT] public static CtField addField ( CtClass fieldType , String fieldName , CtClass declaringClass ) throws CannotCompileException { return addField ( fieldType , fieldName , declaringClass , Modifier . PRIVATE ) ; }


Input: Adds a field of the desired type to the declaring class . [CODESPLIT] public static CtField addField ( CtClass fieldType , String fieldName , CtClass declaringClass , int modifier ) throws CannotCompileException { return addField ( fieldType , fieldName , declaringClass , modifier , null ) ; }


Input: Adds a field of the desired type to the declaring class . [CODESPLIT] public static CtField addField ( CtClass fieldType , String fieldName , CtClass declaringClass , int modifier , String initializerExpr ) throws CannotCompileException { CtField field = new CtField ( fieldType , decapitalize ( fieldName ) , declaringClass ) ; field . setModifiers ( modifier ) ; if ( initializerExpr != null ) { declaringClass . addField ( field , CtField . Initializer . byExpr ( initializerExpr ) ) ; } else { declaringClass . addField ( field ) ; } return field ; }


Input: Generates a getter for the field ( get<FieldName > ) and adds it to the declaring class . [CODESPLIT] public static CtMethod generateGetter ( CtField field , String interceptorAccess ) throws NotFoundException , CannotCompileException { String getterName = "get" + capitalize ( field . getName ( ) ) ; CtMethod getter = CtNewMethod . getter ( getterName , field ) ; if ( interceptorAccess != null ) getter . setBody ( interceptorAccess + "." + getterName + "($$);" ) ; field . getDeclaringClass ( ) . addMethod ( getter ) ; return getter ; }


Input: Generates a setter for the field ( get<FieldName > ) and adds it to the declaring class . [CODESPLIT] public static CtMethod generateSetter ( CtField field , String interceptorAccess ) throws NotFoundException , CannotCompileException { String setterName = "set" + capitalize ( field . getName ( ) ) ; CtMethod setter = CtNewMethod . setter ( setterName , field ) ; if ( interceptorAccess != null ) setter . setBody ( interceptorAccess + "." + setterName + "($$);" ) ; field . getDeclaringClass ( ) . addMethod ( setter ) ; return setter ; }


Input: Generates getter and setter for the field ( get / set<FieldName > ) and adds them to the declaring class . [CODESPLIT] public static void generateGetterAndSetter ( CtField field , String interceptorAccess ) throws NotFoundException , CannotCompileException { generateGetter ( field , interceptorAccess ) ; generateSetter ( field , interceptorAccess ) ; }


Input: Adds the selected annotation to the Object along with the specified memberValues . [CODESPLIT] public static void addAnnotation ( String annotation , LinkedHashMap < String , Object > memberValues , Object toAnnotate ) { if ( toAnnotate instanceof CtClass ) { CtClass classToAnnotate = ( CtClass ) toAnnotate ; ClassFile cf = classToAnnotate . getClassFile ( ) ; ConstPool cp = cf . getConstPool ( ) ; AnnotationsAttribute attr = ( AnnotationsAttribute ) cf . getAttribute ( AnnotationsAttribute . visibleTag ) ; if ( attr == null ) { attr = new AnnotationsAttribute ( cp , AnnotationsAttribute . visibleTag ) ; } Annotation a = new Annotation ( annotation , cp ) ; if ( memberValues != null ) { addMemberValuesToAnnotation ( a , cp , memberValues ) ; } attr . addAnnotation ( a ) ; cf . addAttribute ( attr ) ; } else if ( toAnnotate instanceof CtMethod ) { CtMethod methodToAnnotate = ( CtMethod ) toAnnotate ; MethodInfo mi = methodToAnnotate . getMethodInfo ( ) ; ConstPool cp = mi . getConstPool ( ) ; AnnotationsAttribute attr = ( AnnotationsAttribute ) mi . getAttribute ( AnnotationsAttribute . visibleTag ) ; if ( attr == null ) { attr = new AnnotationsAttribute ( cp , AnnotationsAttribute . visibleTag ) ; } Annotation a = new Annotation ( annotation , cp ) ; if ( memberValues != null ) { addMemberValuesToAnnotation ( a , cp , memberValues ) ; } attr . addAnnotation ( a ) ; mi . addAttribute ( attr ) ; } else if ( toAnnotate instanceof CtField ) { CtField fieldToAnnotate = ( CtField ) toAnnotate ; FieldInfo fi = fieldToAnnotate . getFieldInfo ( ) ; ConstPool cp = fi . getConstPool ( ) ; AnnotationsAttribute attr = ( AnnotationsAttribute ) fi . getAttribute ( AnnotationsAttribute . visibleTag ) ; if ( attr == null ) { attr = new AnnotationsAttribute ( cp , AnnotationsAttribute . visibleTag ) ; } Annotation a = new Annotation ( annotation , cp ) ; if ( memberValues != null ) { addMemberValuesToAnnotation ( a , cp , memberValues ) ; } attr . addAnnotation ( a ) ; fi . addAttribute ( attr ) ; } else { throw new UnsupportedOperationException ( "Unknown object type: " + toAnnotate . getClass ( ) ) ; } }


Input: Private method to add member values to annotation [CODESPLIT] private static void addMemberValuesToAnnotation ( Annotation annotation , ConstPool cp , LinkedHashMap < String , Object > memberValues ) { // Get the member value object for ( String mvName : memberValues . keySet ( ) ) { Object mvValue = memberValues . get ( mvName ) ; MemberValue mv = getMemberValue ( mvValue , cp ) ; annotation . addMemberValue ( mvName , mv ) ; } }


Input: This method returns the aci for the specified activity if exists it should be invoked by each impl of methods of an ra type aci factory . [CODESPLIT] protected ActivityContextInterface getACI ( Object activity ) throws NullPointerException , UnrecognizedActivityException , FactoryException { if ( activity == null ) { throw new NullPointerException ( "null activity object" ) ; } ActivityHandle handle = null ; for ( ResourceAdaptorEntity raEntity : sleeContainer . getResourceManagement ( ) . getResourceAdaptorEntitiesPerType ( resourceAdaptorTypeID ) ) { handle = raEntity . getResourceAdaptorObject ( ) . getActivityHandle ( activity ) ; if ( handle != null ) { ActivityContextHandle ach = new ResourceAdaptorActivityContextHandleImpl ( raEntity , handle ) ; ActivityContext ac = sleeContainer . getActivityContextFactory ( ) . getActivityContext ( ach ) ; if ( ac != null ) { return ac . getActivityContextInterface ( ) ; } break ; } } throw new UnrecognizedActivityException ( activity . toString ( ) ) ; }


Input: Retrieves the component javassist class pool [CODESPLIT] public ClassPool getClassPool ( ) { if ( classPool == null ) { if ( classLoader == null ) { throw new IllegalStateException ( "can't init javassit classpool, there is no class loader set for the component" ) ; } classPool = new ClassPool ( ) ; // add class path for domain and dependencies classPool . appendClassPath ( new LoaderClassPath ( classLoaderDomain ) ) ; for ( ClassLoader domainDependencies : classLoaderDomain . getAllDependencies ( ) ) { classPool . appendClassPath ( new LoaderClassPath ( domainDependencies ) ) ; } // add class path also for slee  classPool . appendClassPath ( new LoaderClassPath ( classLoaderDomain . getParent ( ) ) ) ; } return classPool ; }


Input: Specifies the the Deployable Unit this component belongs . This method also sets the reverse relation adding the component to the deployable unit [CODESPLIT] public void setDeployableUnit ( DeployableUnit deployableUnit ) throws AlreadyDeployedException { if ( this . deployableUnit != null ) { throw new IllegalStateException ( "deployable unit already set. du = " + this . deployableUnit ) ; } this . deployableUnit = deployableUnit ; if ( ! addToDeployableUnit ( ) ) { throw new AlreadyDeployedException ( "unable to install du having multiple components with id " + getComponentID ( ) ) ; } }


Input: Indicates that the component was undeployed and thus should clean up any resources [CODESPLIT] public void undeployed ( ) { classLoader = null ; if ( classLoaderDomain != null ) { classLoaderDomain . clear ( ) ; classLoaderDomain = null ; } if ( classPool != null ) { classPool . clean ( ) ; classPool = null ; } if ( permissions != null ) { permissions . clear ( ) ; permissions = null ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] public void init ( URL deployableUnitURL , String deployableUnitName ) throws DeploymentException { synchronized ( this ) { if ( ! shutdown ) { sleeSubDeployer . init ( deployableUnitURL , deployableUnitName ) ; } } }


Input: / * ( non - Javadoc ) [CODESPLIT] public void start ( URL deployableUnitURL , String deployableUnitName ) throws DeploymentException { synchronized ( this ) { if ( ! shutdown ) { sleeSubDeployer . start ( deployableUnitURL , deployableUnitName ) ; } else { if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Ignoring deploy invoked from external deployer, SLEE in shutdown" ) ; } } }


Input:
Creates a { @link ReceivableServiceImpl } instance from the specified service component [CODESPLIT] private ReceivableService createReceivableService ( ServiceComponent serviceComponent ) { ComponentRepository componentRepository = container . getComponentRepository ( ) ; HashSet < ReceivableEvent > resultSet = new HashSet < ReceivableEvent > ( ) ; for ( SbbID sbbID : serviceComponent . getSbbIDs ( componentRepository ) ) { SbbComponent sbbComponent = componentRepository . getComponentByID ( sbbID ) ; for ( EventEntryDescriptor eventEntry : sbbComponent . getDescriptor ( ) . getEventEntries ( ) . values ( ) ) { EventTypeID eventTypeID = eventEntry . getEventReference ( ) ; final Set < EventTypeID > allowedEventTypes = raEntity . getAllowedEventTypes ( ) ; if ( allowedEventTypes == null || allowedEventTypes . contains ( eventTypeID ) ) { /*
					 * The Service Lookup Facility will only return Service
					 * event type information forthe event types referenced by
					 * the resource adaptor types implemented by the Resource
					 * Adaptor.
					 */ ReceivableEventImpl receivableEventImpl = new ReceivableEventImpl ( eventTypeID , eventEntry . getResourceOption ( ) , eventEntry . isInitialEvent ( ) ) ; // add it if it's not in the set or if it is but initial // event is set (this way if there is a conflict the one // with initial as true wins) if ( ! resultSet . contains ( receivableEventImpl ) || receivableEventImpl . isInitialEvent ( ) ) { resultSet . add ( receivableEventImpl ) ; } } } } return new ReceivableServiceImpl ( serviceComponent . getServiceID ( ) , resultSet . toArray ( new ReceivableEventImpl [ resultSet . size ( ) ] ) ) ; }


Input: Executes a non transacted start activity operation . [CODESPLIT] void execute ( final ActivityHandle handle , final int activityFlags , boolean suspendActivity ) throws SLEEException { final SleeTransaction tx = super . suspendTransaction ( ) ; ActivityContextHandle ach = null ; try { ach = sleeEndpoint . _startActivity ( handle , activityFlags , suspendActivity ? tx : null ) ; } finally { if ( tx != null ) { super . resumeTransaction ( tx ) ; // the activity was started out of the tx but it will be suspended, if the flags request the unreferenced callback then // we can load the ac now, which will schedule a check for references in the end of the tx, this ensures that the callback is received if no events are fired or  // events are fired but not handled, that is, no reference is ever ever created if ( ach != null && ActivityFlags . hasRequestSleeActivityGCCallback ( activityFlags ) ) { acFactory . getActivityContext ( ach ) ; } } } }


Input: Get the { [CODESPLIT] public Collator getCollator ( ) { if ( collator == null ) { collator = Collator . getInstance ( locale ) ; if ( hasStrength ) collator . setStrength ( strength ) ; if ( hasDecomposition ) collator . setDecomposition ( decomposition ) ; } return collator ; }


Input: ##################### [CODESPLIT] public static QueryWrapper parseDynamicQuery ( QueryExpression query ) { ArrayList < Object > params = new ArrayList < Object > ( ) ; long s = System . currentTimeMillis ( ) ; String sqlQuery = "SELECT * " + parseDynamicQuery ( query , 0 , null , params ) ; logger . info ( "Query :: SQL[" + sqlQuery + "]" ) ; long e = System . currentTimeMillis ( ) ; logger . info ( "Query :: Parsed in " + ( e - s ) + "ms." ) ; return new QueryWrapper ( sqlQuery , params ) ; }


Input: ###################### [CODESPLIT] private static String replaceLast ( String sourceString , String toBeReplaced , String replacement ) { StringBuilder x = new StringBuilder ( sourceString ) ; int liof = x . lastIndexOf ( toBeReplaced ) ; if ( liof >= 0 ) x . replace ( liof , liof + 4 , replacement ) ; return new String ( x ) ; }


Input:
This methods validate component which has usage parameter interface . Its interface for methods . In case of 1 . 1 components parameters list must match evey method defined . In case of 1 . 0 components parameters list MUST be empty . It does not validate get usage method those [CODESPLIT] static boolean validateUsageParameterInterface ( ComponentID id , boolean isSlee11 , Class < ? > usageInterface , List < UsageParameterDescriptor > parameters ) { boolean passed = true ; String errorBuffer = new String ( "" ) ; try { if ( ! usageInterface . isInterface ( ) ) { passed = false ; errorBuffer = appendToBuffer ( id , "Usage parameter interface class is not an interface" , "11.2" , errorBuffer ) ; return passed ; } // Interface constraints
 if ( isSlee11 && usageInterface . getPackage ( ) == null ) { passed = false ; errorBuffer = appendToBuffer ( id , "Usage parameter interface must be declared in pacakge name space." , "11.2" , errorBuffer ) ; } if ( ! Modifier . isPublic ( usageInterface . getModifiers ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( id , "Usage parameter interface must be declared as public." , "11.2" , errorBuffer ) ; } // parameters check
 Set < String > ignore = new HashSet < String > ( ) ; ignore . add ( "java.lang.Object" ) ; Map < String , Method > interfaceMethods = ClassUtils . getAllInterfacesMethods ( usageInterface , ignore ) ; Map < String , UsageParameterDescriptor > localParametersMap = new HashMap < String , UsageParameterDescriptor > ( ) ; Set < String > identifiedIncrement = new HashSet < String > ( ) ; Set < String > identifiedGetIncrement = new HashSet < String > ( ) ; Set < String > identifiedSample = new HashSet < String > ( ) ; Set < String > identifiedGetSample = new HashSet < String > ( ) ; // this is for 1.1, get and increment methods must match with type
 // validate parameter names if we are slee11
 if ( isSlee11 ) for ( UsageParameterDescriptor usage : parameters ) { char c = usage . getName ( ) . charAt ( 0 ) ; if ( ! Character . isLowerCase ( c ) ) { passed = false ; errorBuffer = appendToBuffer ( id , "Parameter name must start with lower case character and be start of valid jva identifier, parameter name from descriptor: " + usage . getName ( ) , "11.2" , errorBuffer ) ; } localParametersMap . put ( usage . getName ( ) , usage ) ; } // at the end we have to have empty list
 for ( Entry < String , Method > entry : interfaceMethods . entrySet ( ) ) { // String declaredLongMethodName = entry.getKey();
 Method m = entry . getValue ( ) ; String declaredMethodName = m . getName ( ) ; String declaredPrameterName = null ; Character c = null ; // he we just do checks, methods against constraints
 // we remove them from parameters map, there is something left
 // or not present in map in case of 1.1
 // some variable that we need to store info about method
 boolean isIncrement = false ; boolean isGetIncrement = false ; boolean isGetSample = false ; boolean isSample = false ; // 1.0 comp
 if ( declaredMethodName . startsWith ( _SAMPLE_METHOD_PREFIX ) ) { declaredPrameterName = declaredMethodName . replaceFirst ( _SAMPLE_METHOD_PREFIX , "" ) ; c = declaredPrameterName . charAt ( 0 ) ; isSample = true ; // 1.0 comp
 } else if ( declaredMethodName . startsWith ( _INCREMENT_METHOD_PREFIX ) ) { declaredPrameterName = declaredMethodName . replaceFirst ( _INCREMENT_METHOD_PREFIX , "" ) ; c = declaredPrameterName . charAt ( 0 ) ; isIncrement = true ; // 1.1 only
 } else if ( declaredMethodName . startsWith ( _GET_METHOD_PREFIX ) ) { declaredPrameterName = declaredMethodName . replaceFirst ( _GET_METHOD_PREFIX , "" ) ; c = declaredPrameterName . charAt ( 0 ) ; if ( ! isSlee11 ) { passed = false ; errorBuffer = appendToBuffer ( id , "Wrong method declared in parameter usage interface. Get method for counter parameter types are allowed only in JSLEE 1.1, method: " + declaredMethodName , "11.2.X" , errorBuffer ) ; } if ( m . getReturnType ( ) . getName ( ) . compareTo ( "javax.slee.usage.SampleStatistics" ) == 0 ) { isGetSample = true ; } else { // we asume thats increment get
 isGetIncrement = true ; } } else { passed = false ; errorBuffer = appendToBuffer ( id , "Wrong method decalred in parameter usage interface. Methods must start with either \"get\", \"sample\" or \"increment\", method: " + declaredMethodName , "11.2.X" , errorBuffer ) ; continue ; } if ( ! Character . isUpperCase ( c ) ) { passed = false ; errorBuffer = appendToBuffer ( id , "Method stripped of prefix, either \"get\", \"sample\" or \"increment\", must have following upper case character,method: " + declaredMethodName , "11.2" , errorBuffer ) ; } declaredPrameterName = Introspector . decapitalize ( declaredPrameterName ) ; if ( ! isValidJavaIdentifier ( declaredPrameterName ) ) { passed = false ; errorBuffer = appendToBuffer ( id , "Parameter name must be valid java identifier: " + declaredPrameterName , "11.2" , errorBuffer ) ; } // well we have indentified parameter, lets store;
 if ( isIncrement ) { if ( identifiedIncrement . contains ( declaredMethodName ) ) { passed = false ; errorBuffer = appendToBuffer ( id , "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName , "11.2" , errorBuffer ) ; } else { identifiedIncrement . add ( declaredPrameterName ) ; if ( ! validateParameterSetterSignatureMethod ( id , m , "11.2.3" ) ) { passed = false ; } } } else if ( isGetIncrement ) { if ( identifiedGetIncrement . contains ( declaredMethodName ) ) { passed = false ; errorBuffer = appendToBuffer ( id , "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName , "11.2" , errorBuffer ) ; } else { identifiedGetIncrement . add ( declaredPrameterName ) ; if ( ! validateParameterGetterSignatureMethod ( id , m , "11.2.2" , Long . TYPE ) ) { passed = false ; } } } else if ( isGetSample ) { if ( identifiedGetSample . contains ( declaredMethodName ) ) { passed = false ; errorBuffer = appendToBuffer ( id , "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName , "11.2" , errorBuffer ) ; } else { identifiedGetSample . add ( declaredPrameterName ) ; if ( ! validateParameterGetterSignatureMethod ( id , m , "11.2.4" , javax . slee . usage . SampleStatistics . class ) ) { passed = false ; } } } else if ( isSample ) { if ( identifiedSample . contains ( declaredMethodName ) ) { passed = false ; errorBuffer = appendToBuffer ( id , "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName , "11.2" , errorBuffer ) ; } else { identifiedSample . add ( declaredPrameterName ) ; if ( ! validateParameterSetterSignatureMethod ( id , m , "11.2.1" ) ) { passed = false ; errorBuffer = appendToBuffer ( id , "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName , "11.2" , errorBuffer ) ; } } } // UFFF, lets start the play
 // /uh its a bit complicated
 } // we siganture here is ok, return types also, no duplicates, left:
 // 1. cross check field types that we found - sample vs increments -
 // there cant be doubles
 // 2. remove all from list, if something is left, bam, we lack one
 // method or have to many :)
 Set < String > agregatedIncrement = new HashSet < String > ( ) ; Set < String > agregatedSample = new HashSet < String > ( ) ; agregatedIncrement . addAll ( identifiedGetIncrement ) ; agregatedIncrement . addAll ( identifiedIncrement ) ; agregatedSample . addAll ( identifiedGetSample ) ; agregatedSample . addAll ( identifiedSample ) ; Set < String > tmp = new HashSet < String > ( agregatedSample ) ; tmp . retainAll ( agregatedIncrement ) ; if ( ! tmp . isEmpty ( ) ) { // ugh, its the end
 passed = false ; errorBuffer = appendToBuffer ( id , "Usage parameters can be associated only with single type - increment or sample, offending parameters: " + Arrays . toString ( tmp . toArray ( ) ) , "11.2" , errorBuffer ) ; return passed ; } if ( isSlee11 ) { tmp . clear ( ) ; tmp . addAll ( agregatedSample ) ; tmp . addAll ( agregatedIncrement ) ; // localParametersMap.size()!=0 - cause we can have zero of them
 // - usage-parameter may not be present so its generation is
 // turned off
 if ( localParametersMap . size ( ) != tmp . size ( ) && localParametersMap . size ( ) != 0 ) { passed = false ; String errorPart = null ; if ( localParametersMap . size ( ) > tmp . size ( ) ) { // is there any bettter way?
 for ( String s : localParametersMap . keySet ( ) ) tmp . remove ( s ) ; errorPart = "More parameters are defined in descriptor, offending parameters: " + Arrays . toString ( tmp . toArray ( ) ) ; } else { for ( String s : tmp ) localParametersMap . remove ( s ) ; errorPart = "More parameters are defined in descriptor, offending parameters: " + Arrays . toString ( localParametersMap . keySet ( ) . toArray ( ) ) ; } errorBuffer = appendToBuffer ( id , "Failed to map descriptor defined usage parameters against interface class methods. " + errorPart , "11.2" , errorBuffer ) ; } } } finally { if ( ! passed ) { logger . error ( errorBuffer ) ; // System.err.println(errorBuffer);
 } } return passed ; }


Input: Searches for provided interface in passed Class object - it can be class or interface . If it finds it return instance of it . [CODESPLIT] public static Class checkInterfaces ( Class classOrInterfaceWithInterfaces , String interfaceSearched ) { Class returnValue = null ; if ( classOrInterfaceWithInterfaces . getName ( ) . compareTo ( interfaceSearched ) == 0 ) { return classOrInterfaceWithInterfaces ; } // we do check only on get interfaces for ( Class iface : classOrInterfaceWithInterfaces . getInterfaces ( ) ) { if ( iface . getName ( ) . compareTo ( interfaceSearched ) == 0 ) { returnValue = iface ; } else { returnValue = checkInterfaces ( iface , interfaceSearched ) ; } if ( returnValue != null ) break ; } if ( ! classOrInterfaceWithInterfaces . isInterface ( ) && returnValue == null ) { Class superClass = classOrInterfaceWithInterfaces . getSuperclass ( ) ; if ( superClass != null ) { returnValue = checkInterfaces ( superClass , interfaceSearched ) ; } } return returnValue ; }


Input: Returns methods of this interface and all super interfaces [CODESPLIT] public static Map < String , Method > getAllInterfacesMethods ( Class xInterfaceClass , Set < String > ignore ) { HashMap < String , Method > abstractMethods = new HashMap < String , Method > ( ) ; Method [ ] methods = null ; Class [ ] superInterfaces ; superInterfaces = xInterfaceClass . getInterfaces ( ) ; for ( Class superInterface : superInterfaces ) { if ( ! ignore . contains ( superInterface . getName ( ) ) ) abstractMethods . putAll ( getAllInterfacesMethods ( superInterface , ignore ) ) ; } methods = xInterfaceClass . getDeclaredMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { abstractMethods . put ( getMethodKey ( methods [ i ] ) , methods [ i ] ) ; } return abstractMethods ; }


Input: } [CODESPLIT] public static Method getMethodFromMap ( String name , Class [ ] parameters , Map < String , Method > ... methods ) { String key = name + Arrays . toString ( parameters ) ; for ( Map < String , Method > m : methods ) { if ( m . containsKey ( key ) ) { return m . get ( key ) ; } else { } } return null ; }


Input: Creates an InputSource with a SystemID corresponding to a local dtd file . [CODESPLIT] public InputSource resolveEntity ( String publicId , String systemId ) throws SAXException , IOException { URL resourceURL = resources . get ( publicId ) ; if ( resourceURL != null ) { InputStream resourceStream = resourceURL . openStream ( ) ; InputSource is = new InputSource ( resourceStream ) ; is . setPublicId ( publicId ) ; is . setSystemId ( resourceURL . toExternalForm ( ) ) ; return is ; } return null ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public void setTraceLevel ( ComponentID componentId , Level level ) throws NullPointerException , UnrecognizedComponentException , ManagementException { if ( componentId == null ) throw new NullPointerException ( "null component Id" ) ; this . traceFacility . checkComponentID ( componentId ) ; this . traceFacility . setTraceLevel ( componentId , level ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public Level getTraceLevel ( ComponentID componentId ) throws NullPointerException , UnrecognizedComponentException , ManagementException { if ( componentId == null ) throw new NullPointerException ( " null component Id " ) ; return this . traceFacility . getTraceLevel ( componentId ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public MBeanNotificationInfo [ ] getNotificationInfo ( ) { if ( this . traceFacility == null ) return null ; String [ ] notificationTypes = this . traceFacility . getNotificationTypes ( ) ; return new MBeanNotificationInfo [ ] { new MBeanNotificationInfo ( notificationTypes , TraceMBean . TRACE_NOTIFICATION_TYPE , "SLEE Spec 1.0, #13.4. SBBs use the Trace Facility to generate trace messages intended for " + "consumption by external management clients, such as a network management console or a management policy engine." ) } ; }


Input:
/ * ( non - Javadoc ) [CODESPLIT] public TraceLevel getTraceLevel ( NotificationSource src , String tracerName ) throws NullPointerException , InvalidArgumentException , UnrecognizedNotificationSourceException , ManagementException { if ( src == null ) { throw new NullPointerException ( "NotificationSource must not be null!" ) ; } if ( ! this . isNotificationSourceDefined ( src ) ) { throw new UnrecognizedNotificationSourceException ( "Notification source not recognized: " + src ) ; } TracerImpl . checkTracerName ( tracerName , src ) ; if ( ! this . isTracerDefined ( src , tracerName ) ) { //FIXME: what is valid tracer name? JDOC contradicts that not existing tracer name is invalid
 this . createTracer ( src , tracerName , false ) ; } TracerStorage ts = this . tracerStorage . get ( src ) ; if ( ts == null ) { throw new ManagementException ( "NotificationSource has been uninstalled from SLEE. Can not create tracer." ) ; } try { return ts . getTracerLevel ( tracerName ) ; } catch ( Exception e ) { throw new ManagementException ( "Failed to get trace level due to: " , e ) ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] public String [ ] getTracersSet ( NotificationSource src ) throws NullPointerException , UnrecognizedNotificationSourceException , ManagementException { if ( src == null ) { throw new NullPointerException ( "NotificationSource must nto be null!" ) ; } if ( ! this . isNotificationSourceDefined ( src ) ) { throw new UnrecognizedNotificationSourceException ( "Notification source not recognized: " + src ) ; } TracerStorage ts = this . tracerStorage . get ( src ) ; if ( ts == null ) { throw new ManagementException ( "NotificationSource has been uninstalled from SLEE. Can not create tracer." ) ; } return ts . getDefinedTracerNames ( ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public String [ ] getTracersUsed ( NotificationSource src ) throws NullPointerException , UnrecognizedNotificationSourceException , ManagementException { if ( src == null ) { throw new NullPointerException ( "NotificationSource must nto be null!" ) ; } if ( ! this . isNotificationSourceDefined ( src ) ) { throw new UnrecognizedNotificationSourceException ( "Notification source not recognized: " + src ) ; } TracerStorage ts = this . tracerStorage . get ( src ) ; if ( ts == null ) { throw new ManagementException ( "NotificationSource has been uninstalled from SLEE. Can not create tracer." ) ; } return ts . getRequestedTracerNames ( ) ; }


Input:
/ * ( non - Javadoc ) [CODESPLIT] public void setTraceLevel ( NotificationSource src , final String tracerName , TraceLevel lvl ) throws NullPointerException , UnrecognizedNotificationSourceException , InvalidArgumentException , ManagementException { if ( src == null ) { throw new NullPointerException ( "NotificationSource must nto be null!" ) ; } if ( lvl == null ) { throw new NullPointerException ( "TraceLevel must not be null!" ) ; } if ( ! this . isNotificationSourceDefined ( src ) ) { throw new UnrecognizedNotificationSourceException ( "Notification source not recognized: " + src ) ; } TracerImpl . checkTracerName ( tracerName , src ) ; if ( ! this . isTracerDefined ( src , tracerName ) ) { //FIXME: what is valid tracer name? JDOC contradicts that not existing tracer name is invalid
 this . createTracer ( src , tracerName , false ) ; } final TracerStorage ts = this . tracerStorage . get ( src ) ; if ( ts == null ) { throw new ManagementException ( "NotificationSource has been uninstalled from SLEE. Can not create tracer." ) ; } try { try { final SleeTransactionManager sleeTransactionManager = sleeContainer . getTransactionManager ( ) ; if ( sleeTransactionManager . getTransaction ( ) != null ) { final TraceLevel _oldLevel = ts . getTracerLevel ( tracerName ) ; TransactionalAction action = new TransactionalAction ( ) { TraceLevel oldLevel = _oldLevel ; public void execute ( ) { try { ts . setTracerLevel ( oldLevel , tracerName ) ; } catch ( InvalidArgumentException e ) { logger . error ( e . getMessage ( ) , e ) ; } } } ; sleeTransactionManager . getTransactionContext ( ) . getAfterRollbackActions ( ) . add ( action ) ; } } catch ( SystemException e ) { e . printStackTrace ( ) ; } ts . setTracerLevel ( lvl , tracerName ) ; } catch ( Exception e ) { throw new ManagementException ( "Failed to set trace level due to: " , e ) ; } }


Input:
This checks if tracer name is ok . It must not be null ; [CODESPLIT] public static void checkTracerName ( String tracerName , NotificationSource notificationSource ) throws IllegalArgumentException { if ( tracerName . compareTo ( "" ) == 0 ) { // This is root
 return ; } // String[] splitName = tracerName.split("\\.");
 StringTokenizer stringTokenizer = new StringTokenizer ( tracerName , "." , true ) ; int fqdnPartIndex = 0 ; // if(splitName.length==0)
 // {
 // throw new IllegalArgumentException("Passed tracer:" + tracerName +
 // ", name for source: " + notificationSource + ", is illegal");
 // }
 String lastToken = null ; while ( stringTokenizer . hasMoreTokens ( ) ) { String token = stringTokenizer . nextToken ( ) ; if ( lastToken == null ) { // this is start
 lastToken = token ; } if ( lastToken . compareTo ( token ) == 0 && token . compareTo ( "." ) == 0 ) { throw new IllegalArgumentException ( "Passed tracer:" + tracerName + ", name for source: " + notificationSource + ", is illegal" ) ; } if ( token . compareTo ( "." ) != 0 ) { for ( int charIndex = 0 ; charIndex < token . length ( ) ; charIndex ++ ) { Character c = token . charAt ( charIndex ) ; if ( Character . isLetter ( c ) || Character . isDigit ( c ) ) { // Its ok?
 } else { throw new IllegalArgumentException ( "Passed tracer:" + tracerName + " Token[" + token + "], name for source: " + notificationSource + ", is illegal, contains illegal character: " + charIndex ) ; } } fqdnPartIndex ++ ; } lastToken = token ; } if ( lastToken . compareTo ( "." ) == 0 ) { throw new IllegalArgumentException ( "Passed tracer:" + tracerName + ", name for source: " + notificationSource + ", is illegal" ) ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] public void registerNotificationSource ( final NotificationSource src ) { if ( ! this . tracerStorage . containsKey ( src ) ) { TracerStorage ts = new TracerStorage ( src , this ) ; this . tracerStorage . put ( src , ts ) ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] public boolean isTracerDefined ( NotificationSource src , String tracerName ) throws ManagementException { TracerStorage ts = this . tracerStorage . get ( src ) ; if ( ts == null ) { throw new ManagementException ( "NotificationSource has been uninstalled from SLEE. Can not create tracer." ) ; } return ts . isTracerDefined ( tracerName ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public Tracer createTracer ( NotificationSource src , String tracerName , boolean createdBySource ) throws NullPointerException , InvalidArgumentException { TracerImpl . checkTracerName ( tracerName , src ) ; TracerStorage ts = this . tracerStorage . get ( src ) ; if ( ts == null ) { throw new IllegalStateException ( "NotificationSource has been uninstalled from SLEE. Can not create tracer." ) ; } return ts . createTracer ( tracerName , createdBySource ) ; }


Input: Method that does lookup and creates PLOs [CODESPLIT] public static Collection < ProfileLocalObject > handle ( ProfileTableImpl profileTable , String queryName , Object [ ] arguments ) throws NullPointerException , TransactionRequiredLocalException , SLEEException , UnrecognizedQueryNameException , AttributeTypeMismatchException , InvalidArgumentException { return profileTable . getProfilesByStaticQuery ( queryName , arguments ) ; }


Input:
Installs a JAIN SLEE DU . [CODESPLIT] public DeployableUnitImpl build ( String url , File deploymentRoot , ComponentRepository componentRepository ) throws DeploymentException , AlreadyDeployedException , MalformedURLException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Building DU from " + url ) ; } DeployableUnitID deployableUnitID = new DeployableUnitID ( url ) ; if ( deploymentRoot == null ) { throw new NullPointerException ( "null deploymentRoot" ) ; } URL sourceUrl = new URL ( url ) ; // support remote deployment
 if ( sourceUrl . getProtocol ( ) . equals ( "http" ) || sourceUrl . getProtocol ( ) . equals ( "https" ) ) { try { // Fetch the remote file to a temporary location
 File downloadedFile = downloadRemoteDU ( sourceUrl , deploymentRoot ) ; // Update the pointers from URL and String
 sourceUrl = downloadedFile . toURI ( ) . toURL ( ) ; url = sourceUrl . toString ( ) ; } catch ( Exception e ) { throw new DeploymentException ( "Failed to retrieve remote DU file : " + sourceUrl . getFile ( ) , e ) ; } } // create jar file
 JarFile deployableUnitJar = null ; try { deployableUnitJar = new JarFile ( sourceUrl . getFile ( ) ) ; } catch ( IOException e ) { throw new DeploymentException ( "Failed to open DU file as JAR file: " + sourceUrl . getFile ( ) , e ) ; } // get and parse du descriptor
 JarEntry duXmlEntry = deployableUnitJar . getJarEntry ( "META-INF/deployable-unit.xml" ) ; if ( duXmlEntry == null ) { throw new DeploymentException ( "META-INF/deployable-unit.xml was not found in " + deployableUnitJar . getName ( ) ) ; } DeployableUnitDescriptorFactoryImpl descriptorFactory = componentManagement . getComponentDescriptorFactory ( ) . getDeployableUnitDescriptorFactory ( ) ; DeployableUnitDescriptorImpl deployableUnitDescriptor = null ; try { deployableUnitDescriptor = descriptorFactory . parse ( deployableUnitJar . getInputStream ( duXmlEntry ) ) ; } catch ( IOException e ) { try { deployableUnitJar . close ( ) ; } catch ( IOException e1 ) { logger . error ( e . getMessage ( ) , e ) ; } throw new DeploymentException ( "Failed to get DU descriptor DU inputstream from JAR file " + sourceUrl . getFile ( ) , e ) ; } // create the du dir
 File deploymentDir = createTempDUDeploymentDir ( deploymentRoot , deployableUnitID ) ; // build du object
 DeployableUnitImpl deployableUnit = null ; try { deployableUnit = new DeployableUnitImpl ( deployableUnitID , deployableUnitDescriptor , componentRepository , deploymentDir ) ; // build each du jar component
 for ( String jarFileName : deployableUnitDescriptor . getJarEntries ( ) ) { for ( SleeComponent sleeComponent : duComponentBuilder . buildComponents ( jarFileName , deployableUnitJar , deployableUnit . getDeploymentDir ( ) ) ) { sleeComponent . setDeployableUnit ( deployableUnit ) ; if ( componentRepository . isInstalled ( sleeComponent . getComponentID ( ) ) ) { throw new AlreadyDeployedException ( "Component " + sleeComponent . getComponentID ( ) + " already deployed" ) ; } sleeComponent . setDeploymentUnitSource ( jarFileName ) ; } } // build each du service component
 for ( String serviceDescriptorFileName : deployableUnitDescriptor . getServiceEntries ( ) ) { for ( ServiceComponentImpl serviceComponent : duServiceComponentBuilder . buildComponents ( serviceDescriptorFileName , deployableUnitJar ) ) { serviceComponent . setDeployableUnit ( deployableUnit ) ; if ( componentRepository . isInstalled ( serviceComponent . getComponentID ( ) ) ) { throw new AlreadyDeployedException ( "Component " + serviceComponent . getComponentID ( ) + " already deployed" ) ; } // set the direct reference to the sbb component
 serviceComponent . setRootSbbComponent ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( serviceComponent . getDescriptor ( ) . getRootSbbID ( ) ) ) ; serviceComponent . setDeploymentUnitSource ( serviceDescriptorFileName ) ; } } // get a set with all components of the DU
 Set < SleeComponent > duComponentsSet = deployableUnit . getDeployableUnitComponents ( ) ; // now that all components are built we need to
 for ( SleeComponent sleeComponent : duComponentsSet ) { // check if all
 // dependencies are available
 checkDependencies ( sleeComponent , deployableUnit ) ; // build its class loader
 createClassLoader ( ( AbstractSleeComponent ) sleeComponent ) ; } // load the provided classes for the component
 for ( SleeComponent sleeComponent : duComponentsSet ) { loadAndSetNonGeneratedComponentClasses ( ( AbstractSleeComponent ) sleeComponent ) ; } //boolean secEnabled = SleeContainer.isSecurityEnabled();
 // validate each component
 for ( SleeComponent sleeComponent : duComponentsSet ) { ClassLoader componentClassLoader = sleeComponent . getClassLoader ( ) ; ClassLoader oldClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { if ( componentClassLoader != null ) { Thread . currentThread ( ) . setContextClassLoader ( componentClassLoader ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Validating " + sleeComponent ) ; } if ( ! sleeComponent . validate ( ) ) { throw new DeploymentException ( sleeComponent . toString ( ) + " validation failed, check logs for errors found" ) ; } //Make permissions object, this instruments codebase etc, and store POJOs in component.
 //if(secEnabled)
 //{
 sleeComponent . processSecurityPermissions ( ) ; //}
 } catch ( Throwable e ) { throw new DeploymentException ( "failed to validate " + sleeComponent , e ) ; } finally { if ( componentClassLoader != null ) { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; } } } try { deployableUnitJar . close ( ) ; } catch ( IOException e ) { logger . error ( "failed to close deployable jar from " + url , e ) ; } return deployableUnit ; } catch ( Throwable e ) { if ( deployableUnit == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Deleting deployable unit temp dir " + deploymentDir ) ; } deploymentDir . delete ( ) ; } if ( e instanceof DeploymentException ) { throw ( DeploymentException ) e ; } else if ( e instanceof AlreadyDeployedException ) { throw ( AlreadyDeployedException ) e ; } else { throw new DeploymentException ( "failed to build deployable unit" , e ) ; } } }


Input:
Loads all non SLEE generated classes from the component class loader to the component those will be needed for validation or runtime purposes [CODESPLIT] private void loadAndSetNonGeneratedComponentClasses ( AbstractSleeComponent sleeComponent ) throws DeploymentException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Loading classes for component " + sleeComponent ) ; } ClassLoader oldClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { ComponentClassLoaderImpl componentClassLoader = sleeComponent . getClassLoader ( ) ; if ( componentClassLoader != null ) { // change class loader
 Thread . currentThread ( ) . setContextClassLoader ( componentClassLoader ) ; // load and set non generated component classes
 if ( sleeComponent instanceof EventTypeComponentImpl ) { EventTypeComponentImpl component = ( EventTypeComponentImpl ) sleeComponent ; Class < ? > eventTypeClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getEventClassName ( ) ) ; component . setEventTypeClass ( eventTypeClass ) ; } else if ( sleeComponent instanceof ProfileSpecificationComponentImpl ) { ProfileSpecificationComponentImpl component = ( ProfileSpecificationComponentImpl ) sleeComponent ; Class < ? > profileCmpInterfaceClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getProfileCMPInterface ( ) . getProfileCmpInterfaceName ( ) ) ; component . setProfileCmpInterfaceClass ( profileCmpInterfaceClass ) ; if ( component . getDescriptor ( ) . getProfileLocalInterface ( ) != null ) { Class < ? > profileLocalInterfaceClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getProfileLocalInterface ( ) . getProfileLocalInterfaceName ( ) ) ; component . setProfileLocalInterfaceClass ( profileLocalInterfaceClass ) ; } if ( component . getDescriptor ( ) . getProfileManagementInterface ( ) != null ) { Class < ? > profileManagementInterfaceClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getProfileManagementInterface ( ) ) ; component . setProfileManagementInterfaceClass ( profileManagementInterfaceClass ) ; } if ( component . getDescriptor ( ) . getProfileAbstractClass ( ) != null ) { boolean decoratedClass = new ProfileAbstractClassDecorator ( component ) . decorateAbstractClass ( ) ; Class < ? > profileAbstractClass = null ; if ( decoratedClass ) { // need to ensure we load the class from disk, not one coming from SLEE shared class loading domain
 profileAbstractClass = componentClassLoader . loadClassLocally ( component . getDescriptor ( ) . getProfileAbstractClass ( ) . getProfileAbstractClassName ( ) ) ; } else { profileAbstractClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getProfileAbstractClass ( ) . getProfileAbstractClassName ( ) ) ; } component . setProfileAbstractClass ( profileAbstractClass ) ; } String mProfileTableInterface = component . getDescriptor ( ) . getProfileTableInterface ( ) ; if ( mProfileTableInterface != null ) { component . setProfileTableInterfaceClass ( componentClassLoader . loadClass ( mProfileTableInterface ) ) ; } UsageParametersInterfaceDescriptor mUsageParametersInterface = component . getDescriptor ( ) . getProfileUsageParameterInterface ( ) ; if ( mUsageParametersInterface != null ) { component . setUsageParametersInterface ( componentClassLoader . loadClass ( mUsageParametersInterface . getUsageParametersInterfaceName ( ) ) ) ; } } else if ( sleeComponent instanceof ResourceAdaptorComponentImpl ) { ResourceAdaptorComponentImpl component = ( ResourceAdaptorComponentImpl ) sleeComponent ; Class < ? > resourceAdaptorClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getResourceAdaptorClassName ( ) ) ; component . setResourceAdaptorClass ( resourceAdaptorClass ) ; MUsageParametersInterface mUsageParametersInterface = component . getDescriptor ( ) . getResourceAdaptorUsageParametersInterface ( ) ; if ( mUsageParametersInterface != null ) { component . setUsageParametersInterface ( componentClassLoader . loadClass ( mUsageParametersInterface . getUsageParametersInterfaceName ( ) ) ) ; } } else if ( sleeComponent instanceof ResourceAdaptorTypeComponentImpl ) { ResourceAdaptorTypeComponentImpl component = ( ResourceAdaptorTypeComponentImpl ) sleeComponent ; if ( component . getDescriptor ( ) . getActivityContextInterfaceFactoryInterface ( ) != null ) { Class < ? > activityContextInterfaceFactoryInterface = componentClassLoader . loadClass ( component . getDescriptor ( ) . getActivityContextInterfaceFactoryInterface ( ) ) ; component . setActivityContextInterfaceFactoryInterface ( activityContextInterfaceFactoryInterface ) ; } } else if ( sleeComponent instanceof SbbComponentImpl ) { SbbComponentImpl component = ( SbbComponentImpl ) sleeComponent ; // before loading the abstract class, we may have to decorate it
 boolean decoratedClass = new SbbAbstractClassDecorator ( component ) . decorateAbstractSbb ( ) ; Class < ? > abstractSbbClass = null ; if ( decoratedClass ) { // need to ensure we load the class from disk, not one coming from SLEE shared class loading domain
 abstractSbbClass = componentClassLoader . loadClassLocally ( component . getDescriptor ( ) . getSbbAbstractClass ( ) . getSbbAbstractClassName ( ) ) ; } else { abstractSbbClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getSbbAbstractClass ( ) . getSbbAbstractClassName ( ) ) ; } component . setAbstractSbbClass ( abstractSbbClass ) ; SbbLocalInterfaceDescriptor mSbbLocalInterface = component . getDescriptor ( ) . getSbbLocalInterface ( ) ; if ( mSbbLocalInterface != null ) { component . setSbbLocalInterfaceClass ( componentClassLoader . loadClass ( mSbbLocalInterface . getSbbLocalInterfaceName ( ) ) ) ; } String mSbbActivityContextInterface = component . getDescriptor ( ) . getSbbActivityContextInterface ( ) ; if ( mSbbActivityContextInterface != null ) { component . setActivityContextInterface ( componentClassLoader . loadClass ( mSbbActivityContextInterface ) ) ; } UsageParametersInterfaceDescriptor mUsageParametersInterface = component . getDescriptor ( ) . getSbbUsageParametersInterface ( ) ; if ( mUsageParametersInterface != null ) { component . setUsageParametersInterface ( componentClassLoader . loadClass ( mUsageParametersInterface . getUsageParametersInterfaceName ( ) ) ) ; } } } } catch ( NoClassDefFoundError e ) { throw new DeploymentException ( "Component " + sleeComponent . getComponentID ( ) + " requires a class that was not found" , e ) ; } catch ( ClassNotFoundException e ) { throw new DeploymentException ( "Component " + sleeComponent . getComponentID ( ) + " requires a class that was not found" , e ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; } }


Input: Checks if all dependencies of a DU component exists [CODESPLIT] private void checkDependencies ( SleeComponent sleeComponent , DeployableUnitImpl deployableUnit ) throws DependencyException { for ( ComponentID componentID : sleeComponent . getDependenciesSet ( ) ) { if ( componentID instanceof EventTypeID ) { if ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( ( EventTypeID ) componentID ) == null ) { throw new DependencyException ( "Component " + sleeComponent . getComponentID ( ) + " depends on " + componentID + " which is not available in the component repository or in the deployable unit" ) ; } } else if ( componentID instanceof LibraryID ) { if ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( ( LibraryID ) componentID ) == null ) { throw new DependencyException ( "Component " + sleeComponent . getComponentID ( ) + " depends on " + componentID + " which is not available in the component repository or in the deployable unit" ) ; } } else if ( componentID instanceof ProfileSpecificationID ) { if ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( ( ProfileSpecificationID ) componentID ) == null ) { throw new DependencyException ( "Component " + sleeComponent . getComponentID ( ) + " depends on " + componentID + " which is not available in the component repository or in the deployable unit" ) ; } } else if ( componentID instanceof ResourceAdaptorID ) { if ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( ( ResourceAdaptorID ) componentID ) == null ) { throw new DependencyException ( "Component " + sleeComponent . getComponentID ( ) + " depends on " + componentID + " which is not available in the component repository or in the deployable unit" ) ; } } else if ( componentID instanceof ResourceAdaptorTypeID ) { if ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( ( ResourceAdaptorTypeID ) componentID ) == null ) { throw new DependencyException ( "Component " + sleeComponent . getComponentID ( ) + " depends on " + componentID + " which is not available in the component repository or in the deployable unit" ) ; } } else if ( componentID instanceof SbbID ) { if ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( ( SbbID ) componentID ) == null ) { throw new DependencyException ( "Component " + sleeComponent . getComponentID ( ) + " depends on " + componentID + " which is not available in the component repository or in the deployable unit" ) ; } } else if ( componentID instanceof ServiceID ) { throw new SLEEException ( "Component " + sleeComponent . getComponentID ( ) + " depends on a service component " + componentID + " which is not available in the component repository or in the deployable unit" ) ; } } }


Input:
Creates the directory that will be used for unpacking the child jars for a given DU . [CODESPLIT] private File createTempDUDeploymentDir ( File deploymentRoot , DeployableUnitID deployableUnitID ) { try { // first create a dummy file to gurantee uniqueness. I would have
 // been nice if the File class had a createTempDir() method
 // IVELIN -- do not use jarName here because windows cannot see the
 // path (exceeds system limit)
 File tempFile = File . createTempFile ( "restcomm-slee-du-" , "" , deploymentRoot ) ; File tempDUDeploymentDir = new File ( tempFile . getAbsolutePath ( ) + "-contents" ) ; if ( ! tempDUDeploymentDir . exists ( ) ) { tempDUDeploymentDir . mkdirs ( ) ; } else { throw new SLEEException ( "Dir " + tempDUDeploymentDir + " already exists, unable to create deployment dir for DU " + deployableUnitID ) ; } tempFile . delete ( ) ; return tempDUDeploymentDir ; } catch ( IOException e ) { throw new SLEEException ( "Failed to create deployment dir for DU " + deployableUnitID , e ) ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] public void addEventContext ( EventContextHandle handle , EventContext eventContext ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Adding event context " + eventContext + " to datasource. Event context handle is " + handle ) ; } dataSource . put ( handle , eventContext ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public EventContextData newEventContextData ( EventTypeID eventTypeId , Object event , ActivityContext ac , Address address , ServiceID serviceID , EventProcessingSucceedCallback succeedCallback , EventProcessingFailedCallback failedCallback , EventUnreferencedCallback unreferencedCallback , ReferencesHandler referencesHandler ) { return new DefaultEventContextData ( eventTypeId , event , ac , address , serviceID , succeedCallback , failedCallback , unreferencedCallback , referencesHandler ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public void removeEventContext ( EventContextHandle handle ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Removing event context from datasource. Event context handle is " + handle ) ; } dataSource . remove ( handle ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public void run ( ) { if ( System . getSecurityManager ( ) != null ) { AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { routeQueuedEvent ( ) ; return null ; } } ) ; } else { routeQueuedEvent ( ) ; } }


Input:
Delivers to SBBs an event off the top of the queue for an activity context [CODESPLIT] private void routeQueuedEvent ( ) { boolean debugLogging = logger . isDebugEnabled ( ) ; final SleeTransactionManager txMgr = container . getTransactionManager ( ) ; ClassLoader oldClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { final LocalActivityContext lac = eventContext . getLocalActivityContext ( ) ; final EventRoutingTask activityCurrentEventRoutingTask = lac . getCurrentEventRoutingTask ( ) ; EventContext activityCurrentEventContext = activityCurrentEventRoutingTask == null ? null : activityCurrentEventRoutingTask . getEventContext ( ) ; if ( activityCurrentEventContext == null ) { if ( debugLogging ) logger . debug ( "\n\n\nStarting routing for " + eventContext ) ; activityCurrentEventContext = eventContext ; // activity has no event routing task set  lac . setCurrentEventRoutingTask ( this ) ; EventTypeComponent eventTypeComponent = container . getComponentRepository ( ) . getComponentByID ( eventContext . getEventTypeId ( ) ) ; if ( eventTypeComponent == null ) { logger . error ( "Unable to route event, the related component is not installed" ) ; eventContext . eventProcessingFailed ( FailureReason . OTHER_REASON ) ; return ; } // setup initial event processing if ( eventContext . getService ( ) != null ) { ServiceComponent serviceComponent = container . getComponentRepository ( ) . getComponentByID ( eventContext . getService ( ) ) ; if ( eventTypeComponent . getActiveServicesWhichDefineEventAsInitial ( ) . contains ( serviceComponent ) ) { activityCurrentEventContext . getActiveServicesToProcessEventAsInitial ( ) . add ( serviceComponent ) ; } } else { Set < ServiceComponent > services = eventTypeComponent . getActiveServicesWhichDefineEventAsInitial ( ) ; if ( services != null ) { activityCurrentEventContext . getActiveServicesToProcessEventAsInitial ( ) . addAll ( services ) ; } } } else { if ( activityCurrentEventContext . isSuspendedNotTransacted ( ) ) { if ( debugLogging ) logger . debug ( "\n\n\nFreezing (due to suspended context) the routing for " + eventContext ) ; activityCurrentEventContext . barrierEvent ( eventContext ) ; return ; } else { if ( debugLogging ) logger . debug ( "\n\n\nResuming the routing for" + eventContext ) ; // needed to ensure tests/events/eventcontext/Test1108039Test.xml passes // the test must be fixed Thread . sleep ( 10 ) ; } } LinkedList < ServiceComponent > serviceComponents = activityCurrentEventContext . getActiveServicesToProcessEventAsInitial ( ) ; if ( debugLogging ) logger . debug ( "Active services which define " + eventContext . getEventTypeId ( ) + " as initial: " + serviceComponents ) ; boolean finished ; SbbEntityID rootSbbEntityId ; ClassLoader invokerClassLoader ; SbbEntity sbbEntity ; SbbObject sbbObject ; ServiceComponent serviceComponent ; boolean keepSbbEntityIfTxRollbacks ; NextSbbEntityFinder . Result nextSbbEntityFinderResult ; ActivityContext ac = null ; Exception caught = null ; Set < SbbEntityID > sbbEntitiesThatHandledCurrentEvent ; boolean deliverEvent ; boolean rollbackTx ; boolean rollbackOnlySet ; boolean sbbHandledEvent = false ; do { // For each SBB that is attached to this activity context and active service to process event as initial rootSbbEntityId = null ; invokerClassLoader = null ; sbbEntity = null ; sbbObject = null ; serviceComponent = null ; keepSbbEntityIfTxRollbacks = false ; nextSbbEntityFinderResult = null ; finished = false ; ac = null ; caught = null ; deliverEvent = true ; rollbackTx = true ; rollbackOnlySet = false ; try { /*
					 * Start of SLEE Originated Invocation Sequence
					 * ============================================== This
					 * sequence consists of either: 1) One "Op Only" SLEE
					 * Originated Invocation - in the case that it's a
					 * straightforward event routing for the sbb entity. 2) One
					 * "Op and Remove" SLEE Originated Invocation - in the case
					 * it's an event routing to a root sbb entity that ends up
					 * in a remove to the same entity since the attachment count
					 * goes to zero after the event invocation 3) One "Op Only"
					 * followed by one "Remove Only" SLEE Originated Invocation -
					 * in the case it's an event routing to a non-root sbb
					 * entity that ends up in a remove to the corresponding root
					 * entity since the root attachment count goes to zero after
					 * the event invocation Each Invocation Sequence is handled
					 * in it's own transaction. All exception handling for each
					 * invocation sequence is handled here. Any exceptions that
					 * propagate up aren't necessary to be caught. -Tim
					 */ // If this fails then we propagate up since there's nothing to roll-back anyway txMgr . begin ( ) ; sbbEntitiesThatHandledCurrentEvent = activityCurrentEventContext . getSbbEntitiesThatHandledEvent ( ) ; try { // load ac ac = container . getActivityContextFactory ( ) . getActivityContext ( eventContext . getActivityContextHandle ( ) , true ) ; if ( ac == null ) { logger . error ( "Unable to route event " + eventContext + ". The activity context is gone" ) ; try { eventContext . eventProcessingFailed ( FailureReason . OTHER_REASON ) ; txMgr . commit ( ) ; } catch ( Throwable e ) { logger . error ( e . getMessage ( ) , e ) ; } return ; } if ( routingPhase == RoutingPhase . DELIVERING ) { // calculate highest priority attached sbb entity that needs to handle the event try { nextSbbEntityFinderResult = nextSbbEntityFinder . next ( ac , eventContext , sbbEntitiesThatHandledCurrentEvent , container ) ; } catch ( Exception e ) { logger . warn ( "Failed to find next sbb entity to deliver the event " + eventContext + " in " + ac . getActivityContextHandle ( ) , e ) ; } // calculate highest priority service to process event as initial if ( ! serviceComponents . isEmpty ( ) ) { serviceComponent = serviceComponents . getFirst ( ) ; } // compare highest priority sbb entity already attached with highest priority service to process event as initial if ( nextSbbEntityFinderResult == null ) { if ( serviceComponent != null ) { if ( debugLogging ) logger . debug ( "No sbb entities attached, which didn't already route the event, but " + serviceComponent + " defines the event type as initial, starting initial event processing" ) ; // let the service process event as initial serviceComponents . removeFirst ( ) ; sbbEntity = initialEventProcessor . processInitialEvent ( serviceComponent , eventContext , container , ac ) ; // if service returned no sbb entity and there are no more service components we are done if ( sbbEntity == null && serviceComponents . isEmpty ( ) ) { finished = true ; } } else { // nothing else to route finished = true ; if ( debugLogging ) logger . debug ( "No sbb entities attached, which didn't already route the event, and no services left to process the event as initial" ) ; } } else { if ( serviceComponent != null && serviceComponent . getDescriptor ( ) . getDefaultPriority ( ) >= nextSbbEntityFinderResult . sbbEntity . getPriority ( ) ) { if ( debugLogging ) logger . debug ( "Found an sbb entity attached, which didn't already route the event, but " + serviceComponent + " defines the event type as initial and has the same or higher priority, starting initial event processing" ) ; // the service has higher or equal priority as the sbb entity, let the service process the eventas initial serviceComponents . removeFirst ( ) ; sbbEntity = initialEventProcessor . processInitialEvent ( serviceComponent , eventContext , container , ac ) ; } else { if ( debugLogging ) logger . debug ( "Found an sbb entity attached, which didn't already route the event, and either there are no more services, which defines the event type as initial, or their priorities is lower than the attached sbb entity found" ) ; sbbEntity = nextSbbEntityFinderResult . sbbEntity ; // in this case it needs to find out if the sbb entity should receive the event or not // it may be an activity end event and the attached sbb entity does not receives such event deliverEvent = nextSbbEntityFinderResult . deliverEvent ; } } } if ( sbbEntity != null ) { sbbEntitiesThatHandledCurrentEvent . add ( sbbEntity . getSbbEntityId ( ) ) ; if ( debugLogging ) { logger . debug ( "Highest priority SBB entity, which is attached to the ac " + eventContext . getActivityContextHandle ( ) + " , to deliver the event: " + sbbEntity . getSbbEntityId ( ) ) ; } // CHANGE CLASS LOADER invokerClassLoader = sbbEntity . getSbbComponent ( ) . getClassLoader ( ) ; Thread . currentThread ( ) . setContextClassLoader ( invokerClassLoader ) ; if ( ! sbbEntity . getSbbEntityId ( ) . isRootSbbEntity ( ) ) { rootSbbEntityId = sbbEntity . getSbbEntityId ( ) . getRootSBBEntityID ( ) ; } SleeThreadLocals . setInvokingService ( sbbEntity . getSbbEntityId ( ) . getServiceID ( ) ) ; // we deliver the event in case it is an initial // event processing or if the highest priority // attached sbb entity should do it (in activity // end event it may not if the service id was // set in the event firing, or if the sbb entity // does not declares the event in sbb descriptor if ( deliverEvent ) { sbbEntity . assignSbbObject ( ) ; sbbObject = sbbEntity . getSbbObject ( ) ; if ( sbbEntity . isCreated ( ) && ! txMgr . getRollbackOnly ( ) ) { keepSbbEntityIfTxRollbacks = true ; } // GET AND CHECK EVENT MASK FOR THIS SBB ENTITY Set < EventTypeID > eventMask = sbbEntity . getMaskedEventTypes ( eventContext . getActivityContextHandle ( ) ) ; if ( eventMask == null || ! eventMask . contains ( eventContext . getEventTypeId ( ) ) ) { // TIME TO INVOKE THE EVENT HANDLER METHOD sbbObject . setSbbInvocationState ( SbbInvocationState . INVOKING_EVENT_HANDLER ) ; ac . beforeDeliveringEvent ( eventContext ) ; if ( debugLogging ) { logger . debug ( "---> Invoking event handler: ac=" + eventContext . getActivityContextHandle ( ) + " , sbbEntity=" + sbbEntity . getSbbEntityId ( ) + " , sbbObject=" + sbbObject ) ; } sbbEntity . invokeEventHandler ( eventContext , ac , activityCurrentEventContext ) ; sbbHandledEvent = true ; if ( debugLogging ) { logger . debug ( "<--- Invoked event handler: ac=" + eventContext . getActivityContextHandle ( ) + " , sbbEntity=" + sbbEntity . getSbbEntityId ( ) + " , sbbObject=" + sbbObject ) ; } // check to see if the transaction is marked for // rollback if it is then we need to get out of // here soon as we can. rollbackOnlySet = txMgr . getRollbackOnly ( ) ; if ( ! rollbackOnlySet ) { // TODO understand why the invoking state is not changed if rollback is set sbbObject . setSbbInvocationState ( SbbInvocationState . NOT_INVOKING ) ; } } else { if ( debugLogging ) { logger . debug ( "Not invoking event handler since event is masked" ) ; } } } if ( ! rollbackOnlySet ) { // IF IT'S AN ACTIVITY END EVENT DETACH SBB ENTITY HERE if ( eventContext . isActivityEndEvent ( ) && activityCurrentEventContext . getSbbEntitiesThatHandledEvent ( ) . contains ( sbbEntity . getSbbEntityId ( ) ) ) { if ( debugLogging ) { logger . debug ( "The event is an activity end event, detaching ac=" + eventContext . getActivityContextHandle ( ) + " , sbbEntity=" + sbbEntity . getSbbEntityId ( ) ) ; } ac . detachSbbEntity ( sbbEntity . getSbbEntityId ( ) ) ; sbbEntity . afterACDetach ( eventContext . getActivityContextHandle ( ) ) ; } // CHECK IF WE CAN CLAIM THE ROOT SBB ENTITY if ( rootSbbEntityId != null ) { SbbEntity rootSbbEntity = container . getSbbEntityFactory ( ) . getSbbEntity ( rootSbbEntityId , false ) ; if ( rootSbbEntity == null || rootSbbEntity . getAttachmentCount ( ) != 0 ) { if ( debugLogging ) { logger . debug ( "Not removing sbb entity " + sbbEntity . getSbbEntityId ( ) + " , the attachment count is not 0" ) ; } // the root sbb entity is not be claimed rootSbbEntityId = null ; } } else { // it's a root sbb if ( ! sbbEntity . isRemoved ( ) && sbbEntity . getAttachmentCount ( ) == 0 ) { if ( debugLogging ) { logger . debug ( "Removing sbb entity " + sbbEntity . getSbbEntityId ( ) + " , the attachment count is not 0" ) ; } // If it's the same entity then this is an // "Op and // Remove Invocation Sequence" // so we do the remove in the same // invocation // sequence as the Op container . getSbbEntityFactory ( ) . removeSbbEntity ( sbbEntity , true ) ; } } } } } catch ( Exception e ) { logger . error ( "Caught exception while routing " + eventContext , e ) ; if ( sbbEntity != null ) { sbbObject = sbbEntity . getSbbObject ( ) ; } caught = e ; } catch ( Throwable e ) { // not an exception, wrap it in exception so sbb learns about it logger . error ( "Caught throwable while routing " + eventContext , e ) ; if ( sbbEntity != null ) { sbbObject = sbbEntity . getSbbObject ( ) ; } caught = new SLEEException ( "Caught throwable!" , e ) ; } // do a final check to see if there is another SBB to // deliver. // We don't want to waste another loop. Note that // rollback // will not has any impact on this because the // ac.DeliveredSet // is not in the cache. if ( ! finished ) { if ( serviceComponents . isEmpty ( ) ) { // no more services to process event as initial try { if ( nextSbbEntityFinder . next ( ac , eventContext , sbbEntitiesThatHandledCurrentEvent , container ) == null ) { //if (nextSbbEntityFinder.next(ac, de.getEventTypeId(),de.getService(),sbbEntitiesThatHandledCurrentEvent) == null && sbbEntitiesThatHandledCurrentEvent.contains(sbbEntity.getSbbEntityID())) { // no more attached sbb entities to route the event finished = true ; } } catch ( Throwable e ) { if ( debugLogging ) { logger . debug ( "failed to get next attached sbb entity to handle event" , e ) ; } } } } boolean invokeSbbRolledBack = handleRollback . handleRollback ( sbbObject , caught , invokerClassLoader , txMgr ) ; boolean invokeSbbRolledBackRemove = false ; ClassLoader rootInvokerClassLoader = null ; SbbEntity rootSbbEntity = null ; if ( ! invokeSbbRolledBack && rootSbbEntityId != null ) { /*
						 * If we get here this means that we need to do a
						 * cascading remove of the root sbb entity - since the
						 * original invocation was done on a non-root sbb entity
						 * then this is done in a different SLEE originated
						 * invocation, but inside the same SLEE originated
						 * invocation sequence. Confused yet? This is case 3) in
						 * my previous comment - the SLEE originated invocation
						 * sequence contains two SLEE originated invocations:
						 * One "Op Only" and One "Remove Only" This is the
						 * "Remove Only" part. We don't bother doing this if we
						 * already need to rollback
						 */ caught = null ; try { rootSbbEntity = container . getSbbEntityFactory ( ) . getSbbEntity ( rootSbbEntityId , false ) ; if ( rootSbbEntity != null ) { container . getSbbEntityFactory ( ) . removeSbbEntity ( rootSbbEntity , false ) ; } } catch ( Exception e ) { logger . error ( "Failure while routing event; third phase. Event Posting [" + eventContext + "]" , e ) ; caught = e ; } // We have no target sbb object in a Remove Only SLEE // originated invocation // FIXME emmartins review invokeSbbRolledBackRemove = handleRollback . handleRollback ( null , caught , rootSbbEntity . getSbbComponent ( ) . getClassLoader ( ) , txMgr ) ; } /*
					 * We are now coming to the end of the SLEE originated
					 * invocation sequence We may need to run sbbRolledBack This
					 * is done in the same tx if there is no target sbb entity
					 * in any of the SLEE originated invocations making up this
					 * SLEE originated invocation sequence Otherwise we do it in
					 * a separate tx for each SLEE originated invocation that
					 * has a target sbb entity. In other words we might have a
					 * maximum of 2 sbbrolledback callbacks invoked in separate
					 * tx in the case this SLEE Originated Invocation Sequence
					 * contained an Op Only and a Remove Only (since these have
					 * different target sbb entities) Pretty obvious really! ;)
					 */ if ( invokeSbbRolledBack && sbbEntity == null ) { // We do it in this tx handleSbbRollback . handleSbbRolledBack ( null , sbbObject , null , null , invokerClassLoader , false , container , false ) ; } else if ( sbbEntity != null && ! txMgr . getRollbackOnly ( ) && sbbEntity . getSbbObject ( ) != null ) { sbbEntity . passivateAndReleaseSbbObject ( ) ; //fixes https://github.com/RestComm/jain-slee/issues/53 /* add new tx action before tx commit in which
						 * get all sbb entities in the tx context except target sbb entity
						 * and invoke passivateAndReleaseSbbObject method if the sbb object is not null
						 */ final Collection coll = txMgr . getTransactionContext ( ) . getData ( ) . keySet ( ) ; final SbbEntityID ongoingEntID = sbbEntity . getSbbEntityId ( ) ; TransactionalAction removeLoadedSBBAction = new TransactionalAction ( ) { @ Override public void execute ( ) { for ( Object obj : coll ) { if ( obj instanceof SbbEntityID ) { if ( ! obj . equals ( ongoingEntID ) ) { SbbEntity currentEntity = ( SbbEntity ) txMgr . getTransactionContext ( ) . getData ( ) . get ( obj ) ; if ( currentEntity . getSbbObject ( ) != null ) { currentEntity . passivateAndReleaseSbbObject ( ) ; } } } } } } ; txMgr . getTransactionContext ( ) . getBeforeCommitPriorityActions ( ) . add ( removeLoadedSBBAction ) ; } if ( txMgr . getRollbackOnly ( ) ) { if ( debugLogging ) { logger . trace ( "Rolling back SLEE Originated Invocation Sequence" ) ; } txMgr . rollback ( ) ; } else { if ( finished ) { switch ( routingPhase ) { case DELIVERING : // last tx for this event delivering and it is going to commit (hopefully) // if it has a unrefrenced callback which is tx aware try to take advantage of that  // and do post processing in this tx, in the worst (and unexpected) scenario // the tx will rollback and we will do another spin, due to setting gotSbb as true if ( eventContext . routedRequiresTransaction ( ) ) { finished = false ; routingPhase = RoutingPhase . DELIVERED ; eventContext . routed ( ) ; } break ; case DELIVERED : if ( eventContext . routedRequiresTransaction ( ) ) { // we had bad luck and last tx rollbacked, repeat action finished = false ; eventContext . routed ( ) ; } break ; default : logger . error ( "Unknown routing phase!!!" ) ; break ; } } if ( debugLogging ) { logger . trace ( "Committing SLEE Originated Invocation Sequence" ) ; } txMgr . commit ( ) ; // if we are not in delivering mode anymore and tx commits then we allow the loop to exit if ( routingPhase != RoutingPhase . DELIVERING ) { finished = true ; } } /*
					 * Now we invoke sbbRolledBack for each SLEE originated
					 * invocation that had a target sbb entity in a new tx - the
					 * new tx creating is handled inside the handleSbbRolledBack
					 * method
					 */ if ( invokeSbbRolledBack && sbbEntity != null ) { // Firstly for the "Op only" or "Op and Remove" part if ( debugLogging ) { logger . trace ( "Invoking sbbRolledBack for Op Only or Op and Remove" ) ; } //FIXME: baranowb: de is passed for test: tests/sbb/abstractclass/SbbRolledBackNewTransaction.xml handleSbbRollback . handleSbbRolledBack ( sbbEntity , null , eventContext , ac , invokerClassLoader , false , container , keepSbbEntityIfTxRollbacks ) ; } if ( invokeSbbRolledBackRemove ) { // Now for the "Remove Only" if appropriate handleSbbRollback . handleSbbRolledBack ( rootSbbEntity , null , null , null , rootInvokerClassLoader , true , container , keepSbbEntityIfTxRollbacks ) ; } /*
					 * A note on exception handling here- Any exceptions thrown
					 * further further up that need to be caught in order to
					 * handle rollback or otherwise maintain consistency of the
					 * SLEE state are all handled further up I.e. We *do not*
					 * need to call rollback here. So any exceptions that get
					 * here do not result in the SLEE being in an inconsistent
					 * state, therefore we just log them and carry on.
					 */ rollbackTx = false ; } catch ( RuntimeException e ) { logger . error ( "Unhandled RuntimeException in event router: " , e ) ; } catch ( Exception e ) { logger . error ( "Unhandled Exception in event router: " , e ) ; } catch ( Error e ) { logger . error ( "Unhandled Error in event router: " , e ) ; throw e ; // Always rethrow errors } catch ( Throwable t ) { logger . error ( "Unhandled Throwable in event router: " , t ) ; } finally { try { // FIXME this should not be possible, check if this is ever called by tck!!! final Transaction forgottenTx = txMgr . getTransaction ( ) ; if ( forgottenTx != null ) { logger . error ( "HOUSTON WE HAVE A PROBLEM! Transaction " + forgottenTx + " left open in event routing." ) ; if ( rollbackTx ) { txMgr . rollback ( ) ; } else { txMgr . commit ( ) ; } } } catch ( SystemException se ) { logger . error ( se . getMessage ( ) , se ) ; } if ( sbbEntity != null ) { if ( debugLogging ) { logger . debug ( "Finished routing for " + eventContext + "\n\n\n" ) ; } } } SleeThreadLocals . setInvokingService ( null ) ; if ( activityCurrentEventContext . isSuspendedNotTransacted ( ) ) { if ( debugLogging ) logger . debug ( "Suspended routing for " + eventContext + "\n\n\n" ) ; return ; } } while ( ! finished ) ; /*
			 * End of SLEE Originated Invocation Sequence
			 * ==========================================
			 *
			 */ eventContext . eventProcessingSucceed ( sbbHandledEvent ) ; // we got to the end of the event routing, remove from local ac lac . setCurrentEventRoutingTask ( null ) ; if ( ! eventContext . routedRequiresTransaction ( ) ) { eventContext . routed ( ) ; } } catch ( Exception e ) { logger . error ( "Unhandled Exception in event router top try" , e ) ; } Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { // read ra entity name final String raEntityName = in . readUTF ( ) ; // read activity handle this . raEntity = SleeContainer . lookupFromJndi ( ) . getResourceManagement ( ) . getResourceAdaptorEntity ( raEntityName ) ; if ( raEntity == null ) { throw new IOException ( "RA Entity with name " + raEntityName + " not found." ) ; } // read activity handle boolean handleReference = in . readBoolean ( ) ; if ( handleReference ) { // a reference activityHandle = new ActivityHandleReference ( null , ( Address ) in . readObject ( ) , in . readUTF ( ) ) ; } else { final Marshaler marshaler = raEntity . getMarshaler ( ) ; if ( marshaler != null ) { activityHandle = marshaler . unmarshalHandle ( in ) ; } else { throw new IOException ( "marshaller from RA is null" ) ; } } }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void writeExternal ( ObjectOutput out ) throws IOException { // write ra entity name out . writeUTF ( raEntity . getName ( ) ) ; // write activity handle if ( activityHandle . getClass ( ) == ActivityHandleReference . class ) { // a reference out . writeBoolean ( true ) ; final ActivityHandleReference reference = ( ActivityHandleReference ) activityHandle ; out . writeObject ( reference . getAddress ( ) ) ; out . writeUTF ( reference . getId ( ) ) ; } else { out . writeBoolean ( false ) ; final Marshaler marshaler = raEntity . getMarshaler ( ) ; if ( marshaler != null ) { marshaler . marshalHandle ( activityHandle , out ) ; } else { throw new IOException ( "marshaller from RA is null" ) ; } } }


Input:
Generates the concrete profile entity class and a profile entity array attr value class for each attribute that is an array [CODESPLIT] public void generateClasses ( ) { try { ProfileSpecificationDescriptor profileDescriptor = profileComponent . getDescriptor ( ) ; String deployDir = profileComponent . getDeploymentDir ( ) . getAbsolutePath ( ) ; ProfileCMPInterfaceDescriptor cmpInterface = profileDescriptor . getProfileCMPInterface ( ) ; // define the concrete profile entity class name String concreteProfileEntityClassName = cmpInterface . getProfileCmpInterfaceName ( ) + "_PE" ; // create javassist class CtClass concreteProfileEntityClass = ClassGeneratorUtils . createClass ( concreteProfileEntityClassName , new String [ ] { cmpInterface . getProfileCmpInterfaceName ( ) , Serializable . class . getName ( ) } ) ; // set inheritance ClassGeneratorUtils . createInheritanceLink ( concreteProfileEntityClass , ProfileEntity . class . getName ( ) ) ; // annotate with @Entity ClassGeneratorUtils . addAnnotation ( Entity . class . getName ( ) , new LinkedHashMap < String , Object > ( ) , concreteProfileEntityClass ) ; // annotate the @IdClass LinkedHashMap < String , Object > idClassMVs = new LinkedHashMap < String , Object > ( ) ; idClassMVs . put ( "value" , JPAProfileId . class ) ; ClassGeneratorUtils . addAnnotation ( IdClass . class . getName ( ) , idClassMVs , concreteProfileEntityClass ) ; Set < String > uniqueConstraints = new HashSet < String > ( ) ; // override @id & @basic getter methods String getProfileNameMethodSrc = "public String getProfileName() { return super.getProfileName(); }" ; CtMethod getProfileNameMethod = CtNewMethod . make ( getProfileNameMethodSrc , concreteProfileEntityClass ) ; ClassGeneratorUtils . addAnnotation ( Id . class . getName ( ) , new LinkedHashMap < String , Object > ( ) , getProfileNameMethod ) ; concreteProfileEntityClass . addMethod ( getProfileNameMethod ) ; String getTableNameMethodSrc = "public String getTableName() { return super.getTableName(); }" ; CtMethod getTableNameMethod = CtNewMethod . make ( getTableNameMethodSrc , concreteProfileEntityClass ) ; ClassGeneratorUtils . addAnnotation ( Id . class . getName ( ) , new LinkedHashMap < String , Object > ( ) , getTableNameMethod ) ; concreteProfileEntityClass . addMethod ( getTableNameMethod ) ; // generate the getters/setters in the profile entity // gather the fieldNames of array type attributes ClassPool pool = profileComponent . getClassPool ( ) ; CtClass cmpInterfaceClass = pool . get ( cmpInterface . getProfileCmpInterfaceName ( ) ) ; CtClass listClass = pool . get ( List . class . getName ( ) ) ; Map < String , Class < ? > > profileEntityArrayAttrValueClassMap = new HashMap < String , Class < ? > > ( ) ; for ( CtMethod method : cmpInterfaceClass . getMethods ( ) ) { if ( ! method . getDeclaringClass ( ) . getName ( ) . equals ( Object . class . getName ( ) ) && method . getName ( ) . startsWith ( "get" ) ) { String fieldName = Introspector . decapitalize ( method . getName ( ) . replaceFirst ( "get" , "" ) ) ; boolean array = method . getReturnType ( ) . isArray ( ) ; CtClass returnType = array ? listClass : method . getReturnType ( ) ; CtField genField = ClassGeneratorUtils . addField ( returnType , fieldName , concreteProfileEntityClass ) ; // see issue #23: [Profiles] getting correct fieldName from method of ProfileCMP interface fieldName = genField . getName ( ) ; String pojoCmpAccessorSufix = ClassGeneratorUtils . getPojoCmpAccessorSufix ( genField . getName ( ) ) ; // create the getter CtMethod ctMethod = CtNewMethod . getter ( "get" + pojoCmpAccessorSufix , genField ) ; ProfileAttribute profileAttribute = profileComponent . getProfileAttributes ( ) . get ( fieldName ) ; concreteProfileEntityClass . addMethod ( ctMethod ) ; if ( array ) { // we need to generate a class for this attribute, to hold the one to many relation Class < ? > profileAttributeArrayValueClass = generateProfileAttributeArrayValueClass ( concreteProfileEntityClass , fieldName , profileAttribute . isUnique ( ) ) ; profileEntityArrayAttrValueClassMap . put ( fieldName , profileAttributeArrayValueClass ) ; // add the annotations of one to many association with array attr value class LinkedHashMap < String , Object > map = new LinkedHashMap < String , Object > ( ) ; map . put ( "targetEntity" , profileAttributeArrayValueClass ) ; // FIXME see comment on generation of avv, it is possible to work wituout a join table but needs more work // THE MAPPEDBY IS REQUIRED FOR THE RELATION WITHOUT A JOIN TABLE map . put ( "mappedBy" , "owner" ) ; map . put ( "cascade" , new CascadeType [ ] { CascadeType . ALL } ) ; ClassGeneratorUtils . addAnnotation ( OneToMany . class . getName ( ) , map , ctMethod ) ; // we need to add a special hibernate annotation because the jpa cascade delete only deletes from join table, not the orphan row at the PEAAV table map = new LinkedHashMap < String , Object > ( ) ; map . put ( "value" , new org . hibernate . annotations . CascadeType [ ] { org . hibernate . annotations . CascadeType . DELETE_ORPHAN } ) ; ClassGeneratorUtils . addAnnotation ( Cascade . class . getName ( ) , map , ctMethod ) ; // make setter from src /*String setterSrc =
    				  "public void set"+ pojoCmpAccessorSufix + "("+List.class.getName()+" value) {" +
    				  "  System.out.println(\"PEAAV setter: "+genField.getName()+" = \"+this."+genField.getName()+"+\" value = \"+value);" +
    				  "  if (this."+genField.getName()+" != null) { " +
    				  "    this."+genField.getName()+".clear(); " +
    				  "    if (value != null) { " +
					  "      for ("+Iterator.class.getName()+" i = value.iterator(); i.hasNext();) { " +
					  "        " + profileAttributeArrayValueClass.getName()+" otherArrayValue = ("+profileAttributeArrayValueClass.getName()+") i.next(); " +
					  "        " + profileAttributeArrayValueClass.getName()+" thisArrayValue = new "+profileAttributeArrayValueClass.getName()+"(); " +
					  "        thisArrayValue.setString( otherArrayValue.getString() ); " +
					  "        thisArrayValue.setSerializable( ("+Serializable.class.getName()+") "+ObjectCloner.class.getName()+".makeDeepCopy(otherArrayValue.getSerializable()) ); " +
					  "        this."+genField.getName()+".add(thisArrayValue); " +
					  "      }" +
					  "    }" +
    		          "  } else { " +
    		          "    this."+genField.getName()+" = value; " +
    		          "  }" +
					  "}";
    			  ctMethod = CtMethod.make(setterSrc, concreteProfileEntityClass);
    			  concreteProfileEntityClass.addMethod(ctMethod);
    			  */ } else { // not an array, just add column annotation with or without unique constraint if ( profileAttribute . isUnique ( ) ) { // just collect uniqueConstraints attributtes uniqueConstraints . add ( Introspector . decapitalize ( pojoCmpAccessorSufix ) ) ; } //String , primitive types , Array , Date will not be modified , only serialized data LinkedHashMap < String , Object > map = new LinkedHashMap < String , Object > ( ) ; if ( ! returnType . isPrimitive ( ) && ! returnType . getName ( ) . equals ( "java.lang.String" ) ) map . put ( "length" , 512 ) ; ClassGeneratorUtils . addAnnotation ( Column . class . getName ( ) , map , ctMethod ) ; } // add usual setter ctMethod = CtNewMethod . setter ( "set" + pojoCmpAccessorSufix , genField ) ; concreteProfileEntityClass . addMethod ( ctMethod ) ; } } String tableName = "SLEE_PE_" + profileComponent . getProfileCmpInterfaceClass ( ) . getSimpleName ( ) + "_" + Math . abs ( ( long ) profileComponent . getComponentID ( ) . hashCode ( ) ) ; addTableAnnotation ( tableName , uniqueConstraints , concreteProfileEntityClass ) ; jpaProfileDataSource . setProfileEntityArrayAttrValueClassMap ( profileEntityArrayAttrValueClassMap ) ; // write and load profile entity class if ( logger . isDebugEnabled ( ) ) logger . debug ( "Writing PROFILE ENTITY CONCRETE CLASS ( " + concreteProfileEntityClass . getName ( ) + " ) to: " + deployDir ) ; concreteProfileEntityClass . writeFile ( deployDir ) ; jpaProfileDataSource . setProfileEntityClass ( Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( concreteProfileEntityClass . getName ( ) ) ) ; concreteProfileEntityClass . defrost ( ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } }