private void extractJar(JarFile jarFile, File dstDir)
			throws DeploymentException {

		// Extract jar contents to a classpath location
		JarInputStream jarIs = null;
		try {
			jarIs = new JarInputStream(new BufferedInputStream(
					new FileInputStream(jarFile.getName())));

			for (JarEntry entry = jarIs.getNextJarEntry(); jarIs.available() > 0
					&& entry != null; entry = jarIs.getNextJarEntry()) {
				logger.trace("jar entry = " + entry.getName());

				if (entry.isDirectory()) {
					// Create jar directories.
					File dir = new File(dstDir, entry.getName());
					if (!dir.exists()) {
						if (!dir.mkdirs()) {
							logger.debug("Failed to create directory "
									+ dir.getAbsolutePath());
							throw new IOException("Failed to create directory "
									+ dir.getAbsolutePath());
						}
					} else
						logger.trace("Created directory"
								+ dir.getAbsolutePath());
				} else // unzip files
				{
					File file = new File(dstDir, entry.getName());
					File dir = file.getParentFile();
					if (!dir.exists()) {
						if (!dir.mkdirs()) {
							logger.debug("Failed to create directory "
									+ dir.getAbsolutePath());
							throw new IOException("Failed to create directory "
									+ dir.getAbsolutePath());
						} else
							logger.trace("Created directory"
									+ dir.getAbsolutePath());
					}
					pipeStream(jarFile.getInputStream(entry),
							new FileOutputStream(file));

				}
			}
		} catch (Exception e) {
			throw new DeploymentException("failed to extract jar file "
					+ jarFile.getName());
		} finally {
			if (jarIs != null) {
				try {
					jarIs.close();
				} catch (IOException e) {
					logger.error("failed to close jar input stream", e);
				}
			}
		}

	}

This method will extract all the files in the jar file

@param jarFile
the jar file
@param dstDir
the destination where files in the jar file be extracted
@param deployableUnitID
@return
@throws DeploymentException
failed to extract files


private void pipeStream(InputStream is, OutputStream os) throws IOException {
		synchronized (buffer) {
			try {
				for (int bytesRead = is.read(buffer); bytesRead != -1; bytesRead = is
						.read(buffer))
					os.write(buffer, 0, bytesRead);
				is.close();
				os.close();
			} catch (IOException ioe) {
				try {
					is.close();
				} catch (Exception ioexc) {/* do sth? */
				}
				try {
					os.close();
				} catch (Exception ioexc) {/* do sth? */
				}
				throw ioe;
			}
		}
	}

private
void
pipeStream
(
InputStream
is
,
OutputStream
os
)
throws
IOException
{
synchronized
(
buffer
)
{
try
{
for
(
int
bytesRead
=
is
.
read
(
buffer
)
;
bytesRead
!=
1
;
bytesRead
=
is
.
read
(
buffer
)
)
os
.
write
(
buffer
,
0
,
bytesRead
)
;
is
.
close
(
)
;
os
.
close
(
)
;
}
catch
(
IOException
ioe
)
{
try
{
is
.
close
(
)
;
}
catch
(
Exception
ioexc
)
{
/* do sth? */
}
try
{
os
.
close
(
)
;
}
catch
(
Exception
ioexc
)
{
/* do sth? */
}
throw
ioe
;
}
}
}

Pipes data from the input stream into the output stream.

@param is
The InputStream where the data is coming from.
@param os
The OutputStream where the data is going to.
@throws IOException
if reading or writing the data fails.

Pipes data from the input stream into the output stream .


@SuppressWarnings("unchecked")
	public Object putObject(Object key, Object value) {
		return getNode().put(key, value);
	}

@ SuppressWarnings ( "unchecked" ) public Object putObject ( Object key , Object value ) { return getNode ( ) . put ( key , value ) ; }

Puts an object in cache data

@param key
@param value
@return the old object for the specified key, null if key was not mapped


public boolean attachSbbEntity(SbbEntityID sbbEntityId) {
		final Node node = getAttachedSbbsNode(true);
		if (!node.hasChild(sbbEntityId)) {
			node.addChild(Fqn.fromElements(sbbEntityId));
			return true;
		} else {
			return false;
		}
	}

public boolean attachSbbEntity ( SbbEntityID sbbEntityId ) { final Node node = getAttachedSbbsNode ( true ) ; if ( ! node . hasChild ( sbbEntityId ) ) { node . addChild ( Fqn . fromElements ( sbbEntityId ) ) ; return true ; } else { return false ; } }

Tries to attaches an sbb entity

@param sbbEntityId
@return true if it was attached, false if already was attached


public boolean detachSbbEntity(SbbEntityID sbbEntityId) {
		final Node node  = getAttachedSbbsNode(false);
		return node != null ? node.removeChild(sbbEntityId) : false;
	}

public boolean detachSbbEntity ( SbbEntityID sbbEntityId ) { final Node node = getAttachedSbbsNode ( false ) ; return node != null ? node . removeChild ( sbbEntityId ) : false ; }

Detaches an sbb entity

@param sbbEntityId


public boolean noSbbEntitiesAttached() {
		final Node node  = getAttachedSbbsNode(false);
		return node != null ? node.getChildrenNames().isEmpty() : true;
	}

public boolean noSbbEntitiesAttached ( ) { final Node node = getAttachedSbbsNode ( false ) ; return node != null ? node . getChildrenNames ( ) . isEmpty ( ) : true ; }

Verifies if there at least one sbb entity attached

@return false is there are no sbb entities attached, true otherwise


@SuppressWarnings("unchecked")
	public Set<SbbEntityID> getSbbEntitiesAttached() {
		final Node node  = getAttachedSbbsNode(false);
		return node != null ? node.getChildrenNames() : Collections.emptySet();
	}

@ SuppressWarnings ( "unchecked" ) public Set < SbbEntityID > getSbbEntitiesAttached ( ) { final Node node = getAttachedSbbsNode ( false ) ; return node != null ? node . getChildrenNames ( ) : Collections . emptySet ( ) ; }

Return a set with all sbb entities attached.

@return

Return a set with all sbb entities attached .


public boolean attachTimer(TimerID timerID) {
		final Node node = getAttachedTimersNode(true);
		if (!node.hasChild(timerID)) {
			node.addChild(Fqn.fromElements(timerID));
			return true;
		}
		else {
			return false;
		}
	}

public boolean attachTimer ( TimerID timerID ) { final Node node = getAttachedTimersNode ( true ) ; if ( ! node . hasChild ( timerID ) ) { node . addChild ( Fqn . fromElements ( timerID ) ) ; return true ; } else { return false ; } }


public boolean detachTimer(TimerID timerID) {
		final Node node = getAttachedTimersNode(false);
		return node != null ? node.removeChild(timerID) : false;
	}

public boolean detachTimer ( TimerID timerID ) { final Node node = getAttachedTimersNode ( false ) ; return node != null ? node . removeChild ( timerID ) : false ; }


public boolean noTimersAttached() {
		final Node node = getAttachedTimersNode(false);
		return node != null ? node.getChildrenNames().isEmpty() : true;
	}

public boolean noTimersAttached ( ) { final Node node = getAttachedTimersNode ( false ) ; return node != null ? node . getChildrenNames ( ) . isEmpty ( ) : true ; }

Verifies if there at least one timer attached

@return false is there are no timers attached, true otherwise


public Set getAttachedTimers() {
		final Node node = getAttachedTimersNode(false);
		return node != null ? node.getChildrenNames() : Collections.emptySet();
	}

public Set getAttachedTimers ( ) { final Node node = getAttachedTimersNode ( false ) ; return node != null ? node . getChildrenNames ( ) : Collections . emptySet ( ) ; }

Returns the set of timers attached to the ac

@return


public void nameBound(String name) {
		final Node node = getNamesBoundNode(true);
		if (!node.hasChild(name)) {
			node.addChild(Fqn.fromElements(name));
		}
	}

public void nameBound ( String name ) { final Node node = getNamesBoundNode ( true ) ; if ( ! node . hasChild ( name ) ) { node . addChild ( Fqn . fromElements ( name ) ) ; } }

Adds the specified name to the set of names bound to the ac

@param name


public boolean nameUnbound(String name) {
		final Node node = getNamesBoundNode(false);
		return node != null ? node.removeChild(name) : false;
	}

public boolean nameUnbound ( String name ) { final Node node = getNamesBoundNode ( false ) ; return node != null ? node . removeChild ( name ) : false ; }

Removes the specified name from the set of names bound to the ac

@param name


public boolean noNamesBound() {
		final Node node = getNamesBoundNode(false);
		return node != null ? node.getChildrenNames().isEmpty() : true;
	}

public boolean noNamesBound ( ) { final Node node = getNamesBoundNode ( false ) ; return node != null ? node . getChildrenNames ( ) . isEmpty ( ) : true ; }

Verifies if there at least one name bound to the ac

@return false is there are no names bound, true otherwise


public Set getNamesBoundCopy() {
		final Node node = getNamesBoundNode(false);
		return node != null ? node.getChildrenNames() : Collections.emptySet();
	}

public Set getNamesBoundCopy ( ) { final Node node = getNamesBoundNode ( false ) ; return node != null ? node . getChildrenNames ( ) : Collections . emptySet ( ) ; }

Returns the set of names bound to the ac

@return


@SuppressWarnings("unchecked")
	public void setCmpAttribute(String attrName, Object attrValue) {
		final Node node = getCmpAttributesNode(true);
		Node cmpNode = node.getChild(attrName);
		if (cmpNode == null) {
			cmpNode = node.addChild(Fqn.fromElements(attrName));
		}
		cmpNode.put(CMP_ATTRIBUTES_NODE_MAP_KEY, attrValue);
	}

@ SuppressWarnings ( "unchecked" ) public void setCmpAttribute ( String attrName , Object attrValue ) { final Node node = getCmpAttributesNode ( true ) ; Node cmpNode = node . getChild ( attrName ) ; if ( cmpNode == null ) { cmpNode = node . addChild ( Fqn . fromElements ( attrName ) ) ; } cmpNode . put ( CMP_ATTRIBUTES_NODE_MAP_KEY , attrValue ) ; }

Sets the aci cmp attribute

@param attrName
@param attrValue


@SuppressWarnings("unchecked")
	public Object getCmpAttribute(String attrName) {
		final Node node = getCmpAttributesNode(false);
		if(node == null) {
			return null;
		}
		else {
			final Node cmpNode = node.getChild(attrName);
			if (cmpNode != null) {
				return cmpNode.get(CMP_ATTRIBUTES_NODE_MAP_KEY);
			}
			else {
				return null;
			}
		}
	}

@ SuppressWarnings ( "unchecked" ) public Object getCmpAttribute ( String attrName ) { final Node node = getCmpAttributesNode ( false ) ; if ( node == null ) { return null ; } else { final Node cmpNode = node . getChild ( attrName ) ; if ( cmpNode != null ) { return cmpNode . get ( CMP_ATTRIBUTES_NODE_MAP_KEY ) ; } else { return null ; } } }

Retrieves the aci cmp attribute

@param attrName
@return


@SuppressWarnings("unchecked")
	public Map getCmpAttributesCopy() {
		final Node node = getCmpAttributesNode(false);
		if(node == null) {
			return Collections.emptyMap();
		}
		else {
			Map result = new HashMap();
			Node cmpNode = null;
			for (Object obj : node.getChildren()) {
				cmpNode = (Node) obj;
				result.put(cmpNode.getFqn().getLastElement(), cmpNode
						.get(CMP_ATTRIBUTES_NODE_MAP_KEY));
			}
			return result;
		}
	}

@ SuppressWarnings ( "unchecked" ) public Map getCmpAttributesCopy ( ) { final Node node = getCmpAttributesNode ( false ) ; if ( node == null ) { return Collections . emptyMap ( ) ; } else { Map result = new HashMap ( ) ; Node cmpNode = null ; for ( Object obj : node . getChildren ( ) ) { cmpNode = ( Node ) obj ; result . put ( cmpNode . getFqn ( ) . getLastElement ( ) , cmpNode . get ( CMP_ATTRIBUTES_NODE_MAP_KEY ) ) ; } return result ; } }

Retrieves a map copy of the aci attributes set

@return


private static MBeanNotificationInfo[] initNotificationInfo() {
		String[] notificationTypes = new String[] {
				ProfileTableNotification.USAGE_NOTIFICATION_TYPE,
				ResourceAdaptorEntityNotification.USAGE_NOTIFICATION_TYPE,
				SbbNotification.USAGE_NOTIFICATION_TYPE,
				SubsystemNotification.USAGE_NOTIFICATION_TYPE
				};
		return new MBeanNotificationInfo[] { new MBeanNotificationInfo(
				notificationTypes, UsageNotification.class.getName(),
				"JAIN SLEE 1.1 Usage MBean Notification") };

	}

Initiates the notification info for usage mbeans
@return


public void sendUsageNotification(long value, long seqno,
			String usageParameterSetName, String usageParameterName,
			boolean isCounter) {
		UsageNotificationManagerMBeanImpl notificationManager = parent
				.getUsageNotificationManagerMBean(notificationSource);
		if (notificationManager == null
				|| notificationManager
						.getNotificationsEnabled(usageParameterName)) {
			// if the notification manager is null we consider the notification
			// can be sent
			UsageNotification notification = createUsageNotification(value,
					seqno, usageParameterSetName, usageParameterName, isCounter);
			for (ListenerFilterHandbackTriplet triplet : listeners.values()) {
				if (triplet.notificationFilter == null
						|| triplet.notificationFilter
								.isNotificationEnabled(notification)) {
					triplet.notificationListener.handleNotification(
							notification, triplet.handbackObject);
				}
			}
		}
	}

Send the notification.

@param value
@param seqno
@param usageParameterSetName
@param usageParameterName
@param isCounter


private File downloadRemoteDU(URL duURL, File deploymentRoot) throws Exception {
    InputStream in = null;
    OutputStream out = null;

    try {
      // Get the filename out of the URL
      String filename = new File(duURL.getPath()).getName();

      // Prepare for creating the file at deploy folder
      File tempFile = new File(deploymentRoot, filename);

      out = new BufferedOutputStream(new FileOutputStream(tempFile));
      URLConnection conn = duURL.openConnection();
      in = conn.getInputStream();

      // Get the data
      byte[] buffer = new byte[1024];
      int numRead;
      while ((numRead = in.read(buffer)) != -1) {
        out.write(buffer, 0, numRead);
      }

      // Done! Successful.
      return tempFile;
    }
    finally {
      // Do the clean up.
      try {
        if (in != null) {
          in.close();
          in = null;
        }
        if (out != null) {
          out.close();
          out = null;
        }
      }
      catch (IOException ioe) {
        // Shouldn't happen, let's ignore.
      }
    }
  }

Downloads a remote DU to a local folder

@param duURL URL where the DU can be fetched from
@param deploymentRoot the location where it will be saved to
@return a File related to the downloaded DU
@throws Exception


public void updateDeployedComponents() {
    try {
      // Get the SLEE Component Repo
      ComponentRepository componentRepository = sleeContainerDeployer.getSleeContainer().getComponentRepository();

      // First we'll put the components in a temp Collection
      ConcurrentLinkedQueue<String> newDeployedComponents = new ConcurrentLinkedQueue<String>();

      // Get the deployed Profile Specifications
      for (ComponentID componentID: componentRepository.getProfileSpecificationIDs()) {
        newDeployedComponents.add(componentID.toString());
      }

      // Get the deployed Event Types
      for (ComponentID componentID: componentRepository.getEventComponentIDs()) {
        newDeployedComponents.add(componentID.toString());
      }

      // Get the deployed Resource Adaptor Types
      for (ComponentID componentID: componentRepository.getResourceAdaptorTypeIDs()) {
        newDeployedComponents.add(componentID.toString());
      }

      // Get the deployed Resource Adaptors
      for (ComponentID componentID: componentRepository.getResourceAdaptorIDs()) {
        newDeployedComponents.add(componentID.toString());
      }

      // Get the deployed Service Building Blocks (SBBs)
      for (ComponentID componentID: componentRepository.getSbbIDs()) {
        newDeployedComponents.add(componentID.toString());
      }

      // Get the deployed Services
      for (ComponentID componentID: componentRepository.getServiceIDs()) {
        newDeployedComponents.add(componentID.toString());
      }

      // Get the deployed Libraries
      for (ComponentID componentID: componentRepository.getLibraryIDs()) {
        newDeployedComponents.add(componentID.toString());
      }

      ResourceManagement resourceManagement = sleeContainerDeployer.getSleeContainer().getResourceManagement();

      // Get the existing Resource Adaptor Entity links
      String[] entityNames = resourceManagement.getResourceAdaptorEntities();

      for (String entityName : entityNames) {
        newDeployedComponents.addAll(Arrays.asList(resourceManagement.getLinkNames(entityName)));
      }

      // All good.. Make the temp the good one.
      deployedComponents = newDeployedComponents;
    }
    catch (Exception e) {
      logger.warn("Failure while updating deployed components.", e);
    }
  }

Updates the list of components already deployed to SLEE.

Updates the list of components already deployed to SLEE .


public void installDeployableUnit(DeployableUnit du) throws Exception {

    // Update the deployed components from SLEE
    updateDeployedComponents();

    // Check if the DU is ready to be installed
    if (du.isReadyToInstall(true)) {
      // Get and Run the actions needed for installing this DU
      sciAction(du.getInstallActions(), du);

      // Set the DU as installed
      du.setInstalled(true);

      // Add the DU to the installed list
      deployedDUs.add(du);

      // Update the deployed components from SLEE
      updateDeployedComponents();

      // Go through the remaining DUs waiting for installation
      Iterator<DeployableUnit> duIt = waitingForInstallDUs.iterator();

      while (duIt.hasNext()) {
        DeployableUnit waitingDU = duIt.next();

        // If it is ready for installation, follow the same procedure
        if (waitingDU.isReadyToInstall(false)) {
          // Get and Run the actions needed for installing this DU
          sciAction(waitingDU.getInstallActions(), waitingDU);

          // Set the DU as installed
          waitingDU.setInstalled(true);

          // Add the DU to the installed list
          deployedDUs.add(waitingDU);

          // Update the deployed components from SLEE
          updateDeployedComponents();

          // Remove the DU from the waiting list.
          waitingForInstallDUs.remove(waitingDU);

          // Let's start all over.. :)
          duIt = waitingForInstallDUs.iterator();
        }
      }
    }
    else {
      logger.warn("Unable to INSTALL " + du.getDeploymentInfoShortName() + " right now. Waiting for dependencies to be resolved.");

      // The DU can't be installed now, let's wait...
      waitingForInstallDUs.add(du);
    }
  }

Method for installing a Deployable Unit into SLEE.
@param du the Deployable Unit to install.
@throws Exception

Method for installing a Deployable Unit into SLEE .


public void uninstallDeployableUnit(DeployableUnit du) throws Exception {

    // Update the deployed components from SLEE
    updateDeployedComponents();

    // It isn't installed?
    if (!du.isInstalled()) {
      // Then it should be in the waiting list... remove and we're done.
      if (waitingForInstallDUs.remove(du)) {
        logger.info(du.getDeploymentInfoShortName() + " wasn't deployed. Removing from waiting list.");
      }
    }
    // Check if DU components are still present
    else if (!du.areComponentsStillPresent()) {
      logger.info(du.getDeploymentInfoShortName() + " components already removed. Removing DU info.");

      // Process internals of undeployment...
      processInternalUndeploy(du);
    }
    // Check if the DU is ready to be uninstalled
    else if (du.isReadyToUninstall()) {
      // Get and Run the actions needed for uninstalling this DU
      sciAction(du.getUninstallActions(), du);

      // Process internals of undeployment...
      processInternalUndeploy(du);
    }
    else {
      // Have we been her already? If so, don't flood user with log messages...
      if (!waitingForUninstallDUs.contains(du)) {
        // Add it to the waiting list.
        waitingForUninstallDUs.add(du);
        logger.warn("Unable to UNINSTALL " + du.getDeploymentInfoShortName() + " right now. Waiting for dependents to be removed.");
      }
      throw new DependencyException("Unable to undeploy "+du.getDeploymentInfoShortName());
    }
  }

Method for uninstalling a Deployable Unit into SLEE.
@param du the Deployable Unit to install.
@throws Exception

Method for uninstalling a Deployable Unit into SLEE .


private void processInternalUndeploy(DeployableUnit du) throws Exception {
    // Set the DU as not installed
    du.setInstalled(false);

    // Remove if it was present in waiting list
    waitingForUninstallDUs.remove(du);

    // Update the deployed components from SLEE
    updateDeployedComponents();

    // Go through the remaining DUs waiting for uninstallation
    Iterator<DeployableUnit> duIt = waitingForUninstallDUs.iterator();

    while (duIt.hasNext()) {
      DeployableUnit waitingDU = duIt.next();

      // If it is ready for being uninstalled, follow the same procedure
      if (waitingDU.isReadyToUninstall()) {
        // Schedule removal
        sleeContainerDeployer.getSleeSubDeployer().stop(waitingDU.getURL(), waitingDU.getDeploymentInfoShortName());

        // Remove the DU from the waiting list. If it fails, will go back.
        waitingForUninstallDUs.remove(waitingDU);

        // Let's start all over.. :)
        duIt = waitingForUninstallDUs.iterator();
      }
    }
  }

Sets the DU as not installed and remove it from waiting list if present there.
Also, tries to undeploy DU's waiting for dependencies to be removed.

@param du the DeployableUnit that was just removed
@throws Exception

Sets the DU as not installed and remove it from waiting list if present there . Also tries to undeploy DU s waiting for dependencies to be removed .


public String showStatus() {
    // Update the currently deployed components.
    updateDeployedComponents();

    String output = "";

    output += "
Deployable Units Waiting For Install:
";
    for (DeployableUnit waitingDU : waitingForInstallDUs) {
      output += "+-- " + waitingDU.getDeploymentInfoShortName() + "
";
      for (String dependency : waitingDU.getExternalDependencies()) {
        if (!deployedComponents.contains(dependency))
          dependency += " MISSING!";

        output += "  +-- depends on " + dependency + "
";
      }
    }

    output += "
Deployable Units Waiting For Uninstall:
";
    for (DeployableUnit waitingDU : waitingForUninstallDUs) {
      output += "+-- " + waitingDU.getDeploymentInfoShortName() + "
";
    }

    return output;
  }

Method for showing current status of the Deployment Manager.
@return a HTML string with the status.

Method for showing current status of the Deployment Manager .


public boolean isLoggable(LogRecord record)
  {

    Logger logger = getLogger(record);

    if (record.getThrown() != null)
    {
      logWithThrowable(logger, record);
    }
    else
    {
      logWithoutThrowable(logger, record);
    }

    return false;
  }

public boolean isLoggable ( LogRecord record ) { Logger logger = getLogger ( record ) ; if ( record . getThrown ( ) != null ) { logWithThrowable ( logger , record ) ; } else { logWithoutThrowable ( logger , record ) ; } return false ; }

If the message should be logged, convert the JDK 1.4
LogRecord to a Log4J message.

@return false because JDK 1.4 logging should not happen
if this filter is active.

If the message should be logged convert the JDK 1 . 4 LogRecord to a Log4J message .


private Logger getLogger(LogRecord record)
  {
    String loggerName = record.getLoggerName();
    Logger logger = loggerCache.get(loggerName);
    if (logger == null)
    {
      logger = Logger.getLogger(loggerName);
      loggerCache.put(loggerName, logger);
    }

    return logger;
  }

private Logger getLogger ( LogRecord record ) { String loggerName = record . getLoggerName ( ) ; Logger logger = loggerCache . get ( loggerName ) ; if ( logger == null ) { logger = Logger . getLogger ( loggerName ) ; loggerCache . put ( loggerName , logger ) ; } return logger ; }

get the Log4J logger corresponding to the java.util.logger.LogRecord

get the Log4J logger corresponding to the java . util . logger . LogRecord


public Set<SleeComponent> getReferringComponents(SleeComponent component) {

		Set<SleeComponent> result = new HashSet<SleeComponent>();
		for (EventTypeComponent otherComponent : eventTypeComponents.values()) {
			if (!otherComponent.getComponentID().equals(
					component.getComponentID())) {
				if (otherComponent.getDependenciesSet().contains(
						component.getComponentID())) {
					result.add(otherComponent);
				}
			}
		}
		for (LibraryComponent otherComponent : libraryComponents.values()) {
			if (!otherComponent.getComponentID().equals(
					component.getComponentID())) {
				if (otherComponent.getDependenciesSet().contains(
						component.getComponentID())) {
					result.add(otherComponent);
				}
			}
		}
		for (ProfileSpecificationComponent otherComponent : profileSpecificationComponents
				.values()) {
			if (!otherComponent.getComponentID().equals(
					component.getComponentID())) {
				if (otherComponent.getDependenciesSet().contains(
						component.getComponentID())) {
					result.add(otherComponent);
				}
			}
		}
		for (ResourceAdaptorComponent otherComponent : resourceAdaptorComponents
				.values()) {
			if (!otherComponent.getComponentID().equals(
					component.getComponentID())) {
				if (otherComponent.getDependenciesSet().contains(
						component.getComponentID())) {
					result.add(otherComponent);
				}
			}
		}
		for (ResourceAdaptorTypeComponent otherComponent : resourceAdaptorTypeComponents
				.values()) {
			if (!otherComponent.getComponentID().equals(
					component.getComponentID())) {
				if (otherComponent.getDependenciesSet().contains(
						component.getComponentID())) {
					result.add(otherComponent);
				}
			}
		}
		for (SbbComponent otherComponent : sbbComponents.values()) {
			if (!otherComponent.getComponentID().equals(
					component.getComponentID())) {
				if (otherComponent.getDependenciesSet().contains(
						component.getComponentID())) {
					result.add(otherComponent);
				}
			}
		}
		for (ServiceComponent otherComponent : serviceComponents.values()) {
			if (!otherComponent.getComponentID().equals(
					component.getComponentID())) {
				if (otherComponent.getDependenciesSet().contains(
						component.getComponentID())) {
					result.add(otherComponent);
				}
			}
		}
		return result;
	}

public Set < SleeComponent > getReferringComponents ( SleeComponent component ) { Set < SleeComponent > result = new HashSet < SleeComponent > ( ) ; for ( EventTypeComponent otherComponent : eventTypeComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } for ( LibraryComponent otherComponent : libraryComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } for ( ProfileSpecificationComponent otherComponent : profileSpecificationComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } for ( ResourceAdaptorComponent otherComponent : resourceAdaptorComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } for ( ResourceAdaptorTypeComponent otherComponent : resourceAdaptorTypeComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } for ( SbbComponent otherComponent : sbbComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } for ( ServiceComponent otherComponent : serviceComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } return result ; }

Retrieves the component ids for components that refers the specified component


public Set<SbbEntityID> getSbbEntities() {
		final Node node = getNode();
		if (node == null) {
			return Collections.emptySet();
		}
		HashSet<SbbEntityID> result = new HashSet<SbbEntityID>();
		ServiceID serviceID = null;
		for (Object obj : node.getChildrenNames()) {
			serviceID = (ServiceID) obj;
			for (SbbEntityID sbbEntityID : getRootSbbEntityIDs(serviceID)) {
				result.add(sbbEntityID);
				collectSbbEntities(sbbEntityID,result);
			}
		}
		return result;
	}

public Set < SbbEntityID > getSbbEntities ( ) { final Node node = getNode ( ) ; if ( node == null ) { return Collections . emptySet ( ) ; } HashSet < SbbEntityID > result = new HashSet < SbbEntityID > ( ) ; ServiceID serviceID = null ; for ( Object obj : node . getChildrenNames ( ) ) { serviceID = ( ServiceID ) obj ; for ( SbbEntityID sbbEntityID : getRootSbbEntityIDs ( serviceID ) ) { result . add ( sbbEntityID ) ; collectSbbEntities ( sbbEntityID , result ) ; } } return result ; }

Retrieves a set containing sbb entity ids in the factory
cache data

@return


private Permissions getPermissions(Permissions permissions, final CodeSource cs, Principal[] principals) {

		List<PolicyHolderEntry> entries = this.currentPolicy.get().policyHolderEntries;

		for (PolicyHolderEntry phe : entries) {

			// general
			selectPermissions(permissions, cs, principals, phe);

			// FIXME: certs?

		}

		return permissions;
	}

private
Permissions
getPermissions
(
Permissions
permissions
,
final
CodeSource
cs
,
Principal
[
]
principals
)
{
List
<
PolicyHolderEntry
>
entries
=
this
.
currentPolicy
.
get
(
)
.
policyHolderEntries
;
for
(
PolicyHolderEntry
phe
:
entries
)
{
// general
selectPermissions
(
permissions
,
cs
,
principals
,
phe
)
;
// FIXME: certs?
}
return
permissions
;
}


public String getCodeSources() {

		List<String> css = new ArrayList<String>();
		for (PolicyHolderEntry phe : this.currentPolicy.get().policyHolderEntries) {
			css.add(phe.getCodeSource().getLocation() == null ? "default" : phe.getCodeSource().getLocation().toString());
		}

		return Arrays.toString(css.toArray());
	}

public String getCodeSources ( ) { List < String > css = new ArrayList < String > ( ) ; for ( PolicyHolderEntry phe : this . currentPolicy . get ( ) . policyHolderEntries ) { css . add ( phe . getCodeSource ( ) . getLocation ( ) == null ? "default" : phe . getCodeSource ( ) . getLocation ( ) . toString ( ) ) ; } return Arrays . toString ( css . toArray ( ) ) ; }

Some methods to expose info about what is goign on.

Some methods to expose info about what is goign on .


public boolean profileExists(String profileName) {

		boolean result = component.getProfileEntityFramework().findProfile(this.getProfileTableName(), profileName) != null;

		if (logger.isDebugEnabled()) {
			logger.debug("Profile named "+profileName+(result ? "" : " does not")+" exists on table named " + this.getProfileTableName());
		}

		return result;
	}

public
boolean
profileExists
(
String
profileName
)
{
boolean
result
=
component
.
getProfileEntityFramework
(
)
.
findProfile
(
this
.
getProfileTableName
(
)
,
profileName
)
!=
;
if
(
logger
.
isDebugEnabled
(
)
)
{
logger
.
debug
(
"Profile named "
+
profileName
+
(
result
""
:
" does not"
)
+
" exists on table named "
+
this
.
getProfileTableName
(
)
)
;
}
return
result
;
}

Determines if profile is in back end storage == visible to other
compoenents than MBean, if null is passed as argumetn it must check for
any other than defualt?

Determines if profile is in back end storage == visible to other compoenents than MBean if null is passed as argumetn it must check for any other than defualt?


public void remove(boolean isUninstall) throws SLEEException {

		if (logger.isTraceEnabled()) {
			logger.trace("removeProfileTable: removing profileTable="
					+ profileTableName);
		}

		// remove the table profiles, at this stage they may use notification source, lets leave it.
		for (ProfileID profileID : getProfiles()) {
			// don't invoke the profile concrete object, to avoid evil profile lifecycle impls
			// that rollbacks tx, as Test1110251Test
			this.removeProfile(profileID.getProfileName(), false, isUninstall);
		}

		// remove default profile
		if (getDefaultProfileEntity() != null) {
			this.removeProfile(null, false, false);
		}

		// add action after commit to remove tracer and close uncommitted mbeans
		TransactionalAction commitAction = new TransactionalAction() {
			public void execute() {
				// remove notification sources for profile table
				final TraceManagement traceMBeanImpl = sleeContainer.getTraceManagement();
				traceMBeanImpl.deregisterNotificationSource(new ProfileTableNotification(profileTableName));
				// close uncommitted mbeans
				closeUncommittedProfileMBeans();
			}
		};
		sleeContainer.getTransactionManager().getTransactionContext().getAfterCommitActions().add(commitAction);

		if (sleeContainer.getSleeState() == SleeState.RUNNING) {
			endActivity();
		}

		// unregister mbean
		unregisterUsageMBean();

		// remove object pool
		profileManagement.getObjectPoolManagement().removeObjectPool(this, sleeContainer.getTransactionManager());

	}

Triggers remove operation on this profile table.

@throws UnrecognizedProfileTableNameException

Triggers remove operation on this profile table .


public void updateConfigurationProperties(ConfigProperties properties)
			throws InvalidConfigurationException, InvalidStateException {
		if (!component.getDescriptor().getSupportsActiveReconfiguration()
				&& (sleeContainer.getSleeState() != SleeState.STOPPED)
				&& (state == ResourceAdaptorEntityState.ACTIVE || state == ResourceAdaptorEntityState.STOPPING)) {
			throw new InvalidStateException(
					"the value of the supports-active-reconfiguration attribute of the resource-adaptor-class element in the deployment descriptor of the Resource Adaptor of the resource adaptor entity is False and the resource adaptor entity is in the Active or Stopping state and the SLEE is in the Starting, Running, or Stopping state");
		} else {
			object.raConfigurationUpdate(properties);
		}
	}


@SuppressWarnings({ "unchecked", "rawtypes" })
	public void sleeRunning() throws InvalidStateException {
		// if entity is active then activate the ra object
		if (this.state.isActive()) {
			if (setFTContext) {
				setFTContext = false;
				if (object.isFaultTolerant()) {
					// set fault tolerant context, it is a ft ra
					try {
						this.ftResourceAdaptorContext = new FaultTolerantResourceAdaptorContextImpl(name,sleeContainer,(FaultTolerantResourceAdaptor) object.getResourceAdaptorObject());
						object.setFaultTolerantResourceAdaptorContext(ftResourceAdaptorContext);
					}
					catch (Throwable t) {
						logger.error("Got exception invoking setFaultTolerantResourceAdaptorContext(...) for entity "+name, t);
					}
				}
			}
			try {
				object.raActive();
			}
			catch (Throwable t) {
				logger.error("Got exception invoking raActive() for entity "+name, t);
			}
		}
	}

Signals that the container is in RUNNING state


public void sleeStopping() throws InvalidStateException, TransactionRequiredLocalException {
		if (state != null && state.isActive()) {
			try {
				object.raStopping();
			}
			catch (Throwable t) {
				logger.error("Got exception from RA object",t);
			}
			scheduleAllActivitiesEnd();
		}
	}

public
void
sleeStopping
(
)
throws
InvalidStateException
,
TransactionRequiredLocalException
{
if
(
state
!=
&&
state
.
isActive
(
)
)
{
try
{
object
.
raStopping
(
)
;
}
catch
(
Throwable
t
)
{
logger
.
error
(
"Got exception from RA object"
,
t
)
;
}
scheduleAllActivitiesEnd
(
)
;
}
}

Signals that the container is in STOPPING state
@throws TransactionRequiredLocalException


@SuppressWarnings({ "unchecked", "rawtypes" })
	public void activate() throws InvalidStateException {
		if (!this.state.isInactive()) {
			throw new InvalidStateException("entity " + name + " is in state: "
					+ this.state);
		}
		this.state = ResourceAdaptorEntityState.ACTIVE;
		// if slee is running then activate ra object
		if (sleeContainer.getSleeState() == SleeState.RUNNING) {
			if (setFTContext) {
				setFTContext = false;
				if (object.isFaultTolerant()) {
					// set fault tolerant context, it is a ft ra
					try {
						this.ftResourceAdaptorContext = new FaultTolerantResourceAdaptorContextImpl(name,sleeContainer,(FaultTolerantResourceAdaptor) object.getResourceAdaptorObject());
						object.setFaultTolerantResourceAdaptorContext(ftResourceAdaptorContext);
					}
					catch (Throwable t) {
						logger.error("Got exception invoking setFaultTolerantResourceAdaptorContext(...) for entity "+name, t);
					}
				}
			}
			try {
				object.raActive();
			}
			catch (Throwable t) {
				logger.error("Got exception invoking raActive() for entity "+name, t);
			}
		}
	}

Activates the ra entity

@throws InvalidStateException
if the entity is not in INACTIVE state


public void deactivate() throws InvalidStateException, TransactionRequiredLocalException {
		if (!this.state.isActive()) {
			throw new InvalidStateException("entity " + name + " is in state: "
					+ this.state);
		}
		this.state = ResourceAdaptorEntityState.STOPPING;
		if (object.getState() == ResourceAdaptorObjectState.ACTIVE) {
			object.raStopping();
		}
		// tck requires that the method returns with stopping state so do
		// all deactivation logic half a sec later
		TimerTask t = new TimerTask() {
			@Override
			public void run() {
				try {
					cancel();
					if (state == ResourceAdaptorEntityState.STOPPING) {
						if (object.getState() == ResourceAdaptorObjectState.STOPPING) {
							scheduleAllActivitiesEnd();
						}
						else {
							allActivitiesEnded();
						}
					}
				}
				catch (Throwable e) {
					logger.error(e.getMessage(),e);
				}
			}
		};
		resourceAdaptorContext.getTimer().schedule(t,500);
	}

Deactivates the ra entity

@throws InvalidStateException
if the entity is not in ACTIVE state
@throws TransactionRequiredLocalException


private void scheduleAllActivitiesEnd() throws TransactionRequiredLocalException {

		// schedule the end of all activities if the node is the single member of the cluster
		boolean skipActivityEnding = !sleeContainer.getCluster().isSingleMember();

		if (!skipActivityEnding && hasActivities()) {
			logger.info("RA entity "+name+" activities end scheduled.");
			timerTask = new EndAllActivitiesRAEntityTimerTask(this,sleeContainer);
		}
		else {
			allActivitiesEnded();
		}
	}

schedules the ending of all the entity activities, this is needed on ra
entity deactivation or slee container stop, once the process ends it will
invoke allActivitiesEnded to complete those processes
@throws TransactionRequiredLocalException

schedules the ending of all the entity activities this is needed on ra entity deactivation or slee container stop once the process ends it will invoke allActivitiesEnded to complete those processes


public void remove() throws InvalidStateException {
		if (!this.state.isInactive()) {
			throw new InvalidStateException("entity " + name + " is in state: "
						+ this.state);
		}
		object.raUnconfigure();
		if (object.isFaultTolerant()) {
			object.unsetFaultTolerantResourceAdaptorContext();
			ftResourceAdaptorContext.shutdown();
		}
		object.unsetResourceAdaptorContext();
		this.sleeContainer.getTraceManagement()
				.deregisterNotificationSource(this.getNotificationSource());
		state = null;
	}

Removes the entity, it will unconfigure and unset the ra context, the
entity object can not be reused

@throws InvalidStateException

Removes the entity it will unconfigure and unset the ra context the entity object can not be reused


public Object getResourceAdaptorInterface(ResourceAdaptorTypeID raType) {
		return object.getResourceAdaptorInterface(sleeContainer
				.getComponentRepository().getComponentByID(raType)
				.getDescriptor().getResourceAdaptorInterface());
	}

public Object getResourceAdaptorInterface ( ResourceAdaptorTypeID raType ) { return object . getResourceAdaptorInterface ( sleeContainer . getComponentRepository ( ) . getComponentByID ( raType ) . getDescriptor ( ) . getResourceAdaptorInterface ( ) ) ; }

Retrieves the ra interface for this entity and the specified ra type

@param raType
@return


public void serviceActive(ServiceID serviceID) {
		try {
			ReceivableService receivableService = resourceAdaptorContext
					.getServiceLookupFacility().getReceivableService(serviceID);
			if (receivableService.getReceivableEvents().length > 0) {
				object.serviceActive(receivableService);
			}
		} catch (Throwable e) {
			logger.warn("invocation resulted in unchecked exception", e);
		}
	}

Indicates a service was activated, the entity will forward this
notification to the ra object.

@param serviceInfo

Indicates a service was activated the entity will forward this notification to the ra object .


ActivityHandle derreferActivityHandle(ActivityHandle handle) {
		ActivityHandle ah = null;
		if (resourceManagement.getHandleReferenceFactory() != null && handle.getClass() == ActivityHandleReference.class) {
			ActivityHandleReference ahReference = (ActivityHandleReference) handle;
			ah = resourceManagement.getHandleReferenceFactory().getActivityHandle(ahReference);
		}
		else {
			ah = handle;
		}
		return ah;
	}

ActivityHandle derreferActivityHandle ( ActivityHandle handle ) { ActivityHandle ah = null ; if ( resourceManagement . getHandleReferenceFactory ( ) != null && handle . getClass ( ) == ActivityHandleReference . class ) { ActivityHandleReference ahReference = ( ActivityHandleReference ) handle ; ah = resourceManagement . getHandleReferenceFactory ( ) . getActivityHandle ( ahReference ) ; } else { ah = handle ; } return ah ; }

if it is a handle reference it gets the referred handle
@param handle
@return


public void activityEnded(final ActivityHandle handle, int activityFlags) {
		logger.trace("activityEnded( handle = " + handle + " )");
		ActivityHandle ah = null;
		if (handle instanceof ActivityHandleReference) {
			// handle is a ref, derrefer and remove the ref
			ah = resourceManagement.getHandleReferenceFactory().removeActivityHandleReference((ActivityHandleReference) handle);
		}
		else {
			// handle is not a reference
			ah = handle;
		}
		if (ah != null && ActivityFlags.hasRequestEndedCallback(activityFlags)) {
			object.activityEnded(ah);
		}
		if (object.getState() == ResourceAdaptorObjectState.STOPPING) {
			synchronized (this) {
				// the ra object is stopping, check if the timer task is still
				// needed
				if (!hasActivities()) {
					if (timerTask != null) {
						timerTask.cancel();
					}
					allActivitiesEnded();
				}
			}
		}
	}

Callback to notify the entity and possibly the ra object, informing activity handled ended.
@param handle
@param activityFlags

Callback to notify the entity and possibly the ra object informing activity handled ended .


public void raConfigurationUpdate(ConfigProperties properties)
			throws InvalidConfigurationException {

		if (doTraceLogs) {
			logger.trace("raConfigurationUpdate( properties = " + properties
					+ " )");
		}

		verifyConfigProperties(properties);
		object.raConfigurationUpdate(configProperties);
	}

public
void
raConfigurationUpdate
(
ConfigProperties
properties
)
throws
InvalidConfigurationException
{
if
(
doTraceLogs
)
{
logger
.
trace
(
"raConfigurationUpdate( properties = "
+
properties
+
" )"
)
;
}
verifyConfigProperties
(
properties
)
;
object
.
raConfigurationUpdate
(
configProperties
)
;
}

Updates the ra configuration.

@param properties
@throws InvalidConfigurationException
if the configuration, after merging the specified properties
with the current properties values, results in an invalid
configuration


private void verifyConfigProperties(ConfigProperties newProperties)
			throws InvalidConfigurationException {

		if (doTraceLogs) {
			logger.trace("verifyConfigProperties( newProperties = "
					+ newProperties + " )");
		}

		// merge properties
		for (ConfigProperties.Property configProperty : configProperties
				.getProperties()) {
			if (newProperties.getProperty(configProperty.getName()) == null) {
				newProperties.addProperty(configProperty);
			}
		}
		// validate result
		for (ConfigProperties.Property entityProperty : newProperties
				.getProperties()) {
			if (entityProperty.getValue() == null) {
				throw new InvalidConfigurationException("the property "
						+ entityProperty.getName() + " has null value");
			}
		}
		// validate in ra object
		object.raVerifyConfiguration(newProperties);
		// ok, switch config
		configProperties = newProperties;
	}

Merges the current properties values with the new ones and uses the ra to
verify the configuration

@param newProperties
@throws InvalidConfigurationException
if the configuration, after merging the specified properties
with the current properties values, results in an invalid
configuration


public void raStopping() throws InvalidStateException {

		if (doTraceLogs) {
			logger.trace("raStopping()");
		}

		if (state == ResourceAdaptorObjectState.ACTIVE) {
			state = ResourceAdaptorObjectState.STOPPING;
			object.raStopping();
		} else {
			throw new InvalidStateException("ra object is in state " + state);
		}
	}

public
void
raStopping
(
)
throws
InvalidStateException
{
if
(
doTraceLogs
)
{
logger
.
trace
(
"raStopping()"
)
;
}
if
(
state
==
ResourceAdaptorObjectState
.
ACTIVE
)
{
state
=
ResourceAdaptorObjectState
.
STOPPING
;
object
.
raStopping
(
)
;
}
else
{
throw
new
InvalidStateException
(
"ra object is in state "
+
state
)
;
}
}

Requests the stopping of the ra object. If the operation succeeds the ra
will transition to STOPPING state.

@throws InvalidStateException
if the ra object is not in ACTIVE state

Requests the stopping of the ra object . If the operation succeeds the ra will transition to STOPPING state .


public void raInactive() throws InvalidStateException {

		if (doTraceLogs) {
			logger.trace("raInactive()");
		}

		if (state == ResourceAdaptorObjectState.STOPPING) {
			state = ResourceAdaptorObjectState.INACTIVE;
			object.raInactive();
		} else {
			throw new InvalidStateException("ra object is in state " + state);
		}
	}

public
void
raInactive
(
)
throws
InvalidStateException
{
if
(
doTraceLogs
)
{
logger
.
trace
(
"raInactive()"
)
;
}
if
(
state
==
ResourceAdaptorObjectState
.
STOPPING
)
{
state
=
ResourceAdaptorObjectState
.
INACTIVE
;
object
.
raInactive
(
)
;
}
else
{
throw
new
InvalidStateException
(
"ra object is in state "
+
state
)
;
}
}

Requests the deactivation of the ra object. If the operation succeeds the
ra will transition to INACTIVE state.

@throws InvalidStateException
if the ra object is not in STOPPING state

Requests the deactivation of the ra object . If the operation succeeds the ra will transition to INACTIVE state .


public void raUnconfigure() throws InvalidStateException {

		if (doTraceLogs) {
			logger.trace("raUnconfigure()");
		}

		if (state == ResourceAdaptorObjectState.INACTIVE) {
			state = ResourceAdaptorObjectState.UNCONFIGURED;
			object.raUnconfigure();
		} else {
			throw new InvalidStateException("ra object is in state " + state);
		}
	}

public
void
raUnconfigure
(
)
throws
InvalidStateException
{
if
(
doTraceLogs
)
{
logger
.
trace
(
"raUnconfigure()"
)
;
}
if
(
state
==
ResourceAdaptorObjectState
.
INACTIVE
)
{
state
=
ResourceAdaptorObjectState
.
UNCONFIGURED
;
object
.
raUnconfigure
(
)
;
}
else
{
throw
new
InvalidStateException
(
"ra object is in state "
+
state
)
;
}
}

Unconfigures the ra object

@throws InvalidStateException
if the ra object is not in INACTIVE state


public void unsetResourceAdaptorContext() throws InvalidStateException {

		if (doTraceLogs) {
			logger.trace("unsetResourceAdaptorContext()");
		}

		if (state == ResourceAdaptorObjectState.UNCONFIGURED) {
			object.unsetResourceAdaptorContext();
			state = null;
		} else {
			throw new InvalidStateException("ra object is in state " + state);
		}
	}

public
void
unsetResourceAdaptorContext
(
)
throws
InvalidStateException
{
if
(
doTraceLogs
)
{
logger
.
trace
(
"unsetResourceAdaptorContext()"
)
;
}
if
(
state
==
ResourceAdaptorObjectState
.
UNCONFIGURED
)
{
object
.
unsetResourceAdaptorContext
(
)
;
state
=
;
}
else
{
throw
new
InvalidStateException
(
"ra object is in state "
+
state
)
;
}
}

Unsets the context of the ra object.

@throws InvalidStateException
if the ra object is not in UNCONFIGURED state


@SuppressWarnings("unchecked")
	public void unsetFaultTolerantResourceAdaptorContext()
			throws IllegalArgumentException {

		if (doTraceLogs) {
			logger.trace("unsetFaultTolerantResourceAdaptorContext()");
		}

		if (isFaultTolerant()) {
			((FaultTolerantResourceAdaptor<Serializable, Serializable>) this.object)
					.unsetFaultTolerantResourceAdaptorContext();
		} else {
			throw new IllegalArgumentException(
					"RA Object is not fault tolerant!");
		}
	}

Unsets the ft context of the ra object.

@throws IllegalArgumentException
if the ra object is not in fault tolerant

Unsets the ft context of the ra object .


private void buildProfileAttributeMap() throws DeploymentException {
		 HashMap<String, ProfileAttribute> map = new HashMap<String, ProfileAttribute>();
		 Class<?> cmpInterface = getProfileCmpInterfaceClass();
		 String attributeGetterMethodPrefix = "get";
		 for (Method method : cmpInterface.getMethods()) {
			 if (!method.getDeclaringClass().equals(Object.class) && method.getName().startsWith(attributeGetterMethodPrefix)) {
				 String attributeName = method.getName().substring(attributeGetterMethodPrefix.length());
				 switch (attributeName.length()) {
				 case 0:
					throw new DeploymentException("the profile cmp interface class has an invalid attribute getter method name > "+method.getName());
				 case 1:
					attributeName = attributeName.toLowerCase();
					break;
				 default:
					attributeName = attributeName.substring(0, 1).toLowerCase() + attributeName.substring(1);
				 	break;
				 }
				 ProfileAttributeImpl profileAttribute = null;
				 try {
					profileAttribute = new ProfileAttributeImpl(attributeName,method.getReturnType());
				 } catch (Throwable e) {
					throw new DeploymentException("Invalid profile cmp interface attribute getter method definition ( name = "+attributeName+" , type = "+method.getReturnType()+" )",e);
				 }
				 if (isSlee11()) {
					 for (ProfileCMPFieldDescriptor cmpField : getDescriptor().getProfileCMPInterface().getCmpFields()) {
						 if (cmpField.getCmpFieldName().equals(attributeName)) {
							 // TODO add index hints ?
							 profileAttribute.setUnique(cmpField.isUnique());
						 }
					 }
				 }
				 else {
					 for (ProfileIndexDescriptor profileIndex : getDescriptor().getIndexedAttributes()) {
						 if (profileIndex.getName().equals(attributeName)) {
							 profileAttribute.setIndex(true);
							 profileAttribute.setUnique(profileIndex.getUnique());
						 }
					 }
				 }
				 map.put(attributeName, profileAttribute);
			 }
		 }
		 profileAttributeMap = Collections.unmodifiableMap(map);
	}

Builds the profile attribute map using the cmp interface class
@throws DeploymentException


private void resume() {

		// create runnable to resume the event context
		Runnable runnable = new Runnable() {
			public void run() {
				if (scheduledFuture == null) {
					// already resumed
					return;
				}
				// cancel timer task
				scheduledFuture.cancel(false);
				scheduledFuture = null;
				// send events frozen to event router again, will be processed only after this one ends (this one is already being executed)
				for (EventContext ec : barriedEvents) {
					ec.getLocalActivityContext().getExecutorService().routeEvent(ec);
				}
				barriedEvents = null;
				// remove barrier on activity event queue
				event.getLocalActivityContext().getEventQueueManager().removeBarrier(transaction);
				// remove suspension
				suspended = false;
				// continue routing the event related with this context
				event.getLocalActivityContext().getCurrentEventRoutingTask().run();
			}
		};
		// run it using the activity executor service to avoid thread concurrency
		event.getLocalActivityContext().getExecutorService().execute(runnable);
	}

the real logic to resume the event context


@SuppressWarnings("unchecked")
	public Set<ActivityContextHandle> getActivityContextHandles() {
		final Node node = getNode();
		return node != null ? node.getChildrenNames() : Collections.emptySet();
	}

@ SuppressWarnings ( "unchecked" ) public Set < ActivityContextHandle > getActivityContextHandles ( ) { final Node node = getNode ( ) ; return node != null ? node . getChildrenNames ( ) : Collections . emptySet ( ) ; }

Retrieves a set containing all activity context handles in the factory's
cache data

@return

Retrieves a set containing all activity context handles in the factory s cache data


public void remove() {

		Logger logger = getLogger();
		if (logger.isDebugEnabled()) {
			logger.debug("Closing " + toString());
		}
		final MBeanServer mbeanServer = sleeContainer.getMBeanServer();
		try {
			mbeanServer.unregisterMBean(getObjectName());
		} catch (Exception e) {
			logger.error("failed to remove " + toString(), e);
		}
		// remove all usage param
		if (logger.isDebugEnabled()) {
			logger
					.debug("Removing all named usage parameters of "
							+ toString());
		}
		for (String name : usageMBeans.keySet()) {
			try {
				_removeUsageParameterSet(name,false);
			} catch (Throwable e) {
				logger.error(e.getMessage(), e);
			}
		}
		// also remove the default
		try {
			removeUsageParameterSet();
		} catch (Throwable e) {
			logger.error(e.getMessage(), e);
		}
	}


public ObjectName getUsageMBean(String paramSetName)
			throws NullPointerException,
			UnrecognizedUsageParameterSetNameException, ManagementException {
		if (paramSetName == null)
			throw new NullPointerException("Sbb usage param set is null");
		return _getUsageMBean(paramSetName);
	}

Retrieves the object name for the usage param mbean with the specified
name

@param paramSetName
@return
@throws NullPointerException
@throws UnrecognizedUsageParameterSetNameException
@throws ManagementException


public boolean decorateAbstractClass() throws DeploymentException {

    	ClassPool pool = component.getClassPool();
    	ProfileAbstractClassDescriptor abstractClass = component.getDescriptor().getProfileAbstractClass();
    	if (abstractClass == null) {
    		return false;
    	}
    	String abstractClassName = abstractClass.getProfileAbstractClassName();
        try {
            ctClass = pool.get(abstractClassName);
        } catch (NotFoundException nfe) {
            throw new DeploymentException("Could not find Abstract Class: "
                    + abstractClassName, nfe);
        }

        decorateClassJNDIAddToEnvironmentCalls();

        if (isAbstractClassDecorated) {
        	try {
        		String deployDir = component.getDeploymentDir().getAbsolutePath();
        		ctClass.writeFile(deployDir);
        		ctClass.detach();
        		// the file on disk is now in sync with the latest in-memory version
        		if (logger.isDebugEnabled()) {
        			logger.debug("Modified Abstract Class "
        					+ ctClass.getName()
        					+ " generated in the following path "
        					+ deployDir);
        		}
        	} catch (Throwable e) {
        		throw new SLEEException ( e.getMessage(), e);
        	} finally {
        		ctClass.defrost();
        	}
        	return true;
        }
        else {
        	return false;
        }
    }

Decorate the abstract Class

@return true is the class was decorated


public static void fireEvent(SbbEntity sbbEntity, EventTypeID eventTypeID,
			Object eventObject, ActivityContextInterface aci, Address address) {
		fireEvent(sbbEntity, eventTypeID, eventObject, aci, address, null);
	}

public static void fireEvent ( SbbEntity sbbEntity , EventTypeID eventTypeID , Object eventObject , ActivityContextInterface aci , Address address ) { fireEvent ( sbbEntity , eventTypeID , eventObject , aci , address , null ) ; }

The logic to fire an event from an SLEE 1.0 Sbb

@param sbbEntity
an sbb entity with an object assigned
@param eventTypeID
the id of the event to fire
@param eventObject
the event object, can't be null
@param aci
the activity context where the event will be fired, can't be
null
@param address
the optional address to fire the event

The logic to fire an event from an SLEE 1 . 0 Sbb


public static void fireEvent(SbbEntity sbbEntity, EventTypeID eventTypeID,
			Object eventObject, ActivityContextInterface aci, Address address,
			ServiceID serviceID) {

		if (sleeContainer.getCongestionControl().refuseFireEvent()) {
			throw new SLEEException("congestion control refused event");
		}

		// JAIN SLEE (TM) specs - Section 8.4.1
		// The SBB object must have an assigned SBB entity when it invokes this
		// method.
		// Otherwise, this method throws a java.lang.IllegalStateException.
		if (sbbEntity == null || sbbEntity.getSbbObject() == null
				|| sbbEntity.getSbbObject().getState() != SbbObjectState.READY)
			throw new IllegalStateException("SbbObject not assigned!");

		// JAIN SLEE (TM) specs - Section 8.4.1
		// The event ... cannot be null. If ... argument is null, the fire
		// event method throws a java.lang.NullPointerException.
		if (eventObject == null)
			throw new NullPointerException(
					"JAIN SLEE (TM) specs - Section 8.4.1: The event ... cannot be null. If ... argument is null, the fire event method throws a java.lang.NullPointerException.");

		// JAIN SLEE (TM) specs - Section 8.4.1
		// The activity ... cannot be null. If ... argument is null, the fire
		// event method throws a java.lang.NullPointerException.
		if (aci == null)
			throw new NullPointerException(
					"JAIN SLEE (TM) specs - Section 8.4.1: The activity ... cannot be null. If ... argument is null, the fire event method throws a java.lang.NullPointerException.");

		// JAIN SLEE (TM) specs - Section 8.4.1
		// It is a mandatory transactional method (see Section 9.6.1).
		final SleeTransactionManager txManager = sleeContainer.getTransactionManager();
		txManager.mandateTransaction();

		// rebuild the ac from the aci in the 2nd argument of the invoked
		// method, check it's state
		ActivityContext ac = ((org.mobicents.slee.container.activity.ActivityContextInterface) aci)
				.getActivityContext();
		if (logger.isTraceEnabled()) {
			logger.trace("invoke(): firing event on "
					+ ac);
		}

		// exception not in specs by mandated by
		// tests/activities/activitycontext/Test560Test.xml , it's preferable to
		// do double check on here than have the aci fire method throwing it and
		// the ra slee endpoint having to translate it to activity ending
		// exception, it is not common to have custom event firing in sbbs
		if (ac.isEnding()) {
			throw new IllegalStateException("activity context "
					+ ac.getActivityContextHandle() + " is ending");
		}

		final EventRoutingTransactionData transactionData = txManager.getTransactionContext().getEventRoutingTransactionData();
		if (transactionData != null) {
			final EventContext eventBeingDelivered = transactionData.getEventBeingDelivered();
			if (eventBeingDelivered != null && eventBeingDelivered.getEvent() == eventObject) {
				// there is an event being delivered by this tx and it matches the event being fired, lets copy the ref handler
				// fire the event
				ac.fireEvent(eventTypeID, eventObject, (Address) address, serviceID, eventBeingDelivered);
				return;
			}
		}
		// seems it is not a refire
		ac.fireEvent(eventTypeID, eventObject, (Address) address, serviceID, null, null, null);

	}

The logic to fire an event from an SLEE 1.1 Sbb

@param sbbEntity
an sbb entity with an object assigned
@param eventTypeID
the id of the event to fire
@param eventObject
the event object, can't be null
@param aci
the activity context where the event will be fired, can't be
null
@param address
the optional address to fire the event
@param serviceID
the optional service id to fire the event

The logic to fire an event from an SLEE 1 . 1 Sbb


public static Object getProfileCMPMethod(SbbEntity sbbEntity,
			String getProfileCMPMethodName, ProfileID profileID)
			throws UnrecognizedProfileTableNameException,
			UnrecognizedProfileNameException {

		GetProfileCMPMethodDescriptor mGetProfileCMPMethod = sbbEntity.getSbbComponent()
				.getDescriptor().getGetProfileCMPMethods().get(
						getProfileCMPMethodName);
		if (mGetProfileCMPMethod == null)
			throw new AbstractMethodError("Profile CMP Method not found");

		if (sbbEntity.getSbbObject().getState() != SbbObjectState.READY) {
			throw new IllegalStateException(
					"Could not invoke getProfileCMP Method, Sbb Object is not in the READY state!");
		}

		ProfileManagement sleeProfileManager = sleeContainer
				.getSleeProfileTableManager();

		ProfileTable profileTable = sleeProfileManager.getProfileTable(profileID.getProfileTableName());

		if (!profileTable.profileExists(profileID.getProfileName())) {
			throw new UnrecognizedProfileNameException(profileID.toString());
		}

		return profileTable.getProfile(profileID.getProfileName()).getProfileCmpSlee10Wrapper();
	}

Retrieves a profile given the cmp method name and profile id


public static Object getSbbUsageParameterSet(SbbEntity sbbEntity, String name)
			throws UnrecognizedUsageParameterSetNameException {
		if (logger.isTraceEnabled()) {
			logger.trace("getSbbUsageParameterSet(): serviceId = "
					+ sbbEntity.getSbbEntityId().getServiceID() + " , sbbID = "
					+ sbbEntity.getSbbId() + " , name = " + name);
		}
		return getServiceUsageMBeanImpl(sbbEntity.getSbbEntityId().getServiceID())
				.getInstalledUsageParameterSet(sbbEntity.getSbbId(), name);
	}


public static Map getAbstractMethodsFromClass(CtClass sbbAbstractClass) {
    	HashMap abstractMethods = new HashMap();
    	CtMethod[] methods = sbbAbstractClass.getDeclaredMethods();
    	for (int i = 0; i < methods.length; i++) {
    		if (Modifier.isAbstract(methods[i].getModifiers())) {
    			abstractMethods.put(methods[i].getName(), methods[i]);
    		}
    	}

    	return abstractMethods;
    }

public static Map getAbstractMethodsFromClass ( CtClass sbbAbstractClass ) { HashMap abstractMethods = new HashMap ( ) ; CtMethod [ ] methods = sbbAbstractClass . getDeclaredMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { if ( Modifier . isAbstract ( methods [ i ] . getModifiers ( ) ) ) { abstractMethods . put ( methods [ i ] . getName ( ) , methods [ i ] ) ; } } return abstractMethods ; }

Retrieve all abstract methods from a class

@param sbbAbstractClass
the class to extract the abstract methods
@return all abstract methods from a class


public static Map getInterfaceMethodsFromInterface(CtClass interfaceClass,
            Map exceptMethods) {

        HashMap interfaceMethods = new HashMap();
        CtMethod[] methods = interfaceClass.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++)
        {
            if (exceptMethods.get(methods[i].getName()) == null)
            {
                    ConcreteClassGeneratorUtils.logger.trace(methods[i].getName());
                    interfaceMethods.put(getMethodKey(methods[i]), methods[i]);
            }
        }

        Map temp = getSuperClassesAbstractMethodsFromInterface(interfaceClass);
        for (Iterator i= temp.keySet().iterator(); i.hasNext(); )
        {
            String key = (String)i.next();
            if (!exceptMethods.containsKey(key)) {
                    interfaceMethods.put(key, temp.get(key));
            }
        }

        return interfaceMethods;
    }

Retrieve all methods from an interface, including super interfaces, except the ones specified in the provided map
@param interfaceClass
@param exceptMethods
@return

Retrieve all methods from an interface including super interfaces except the ones specified in the provided map


public void createObjectPool(final ProfileTableImpl profileTable,
			final SleeTransactionManager sleeTransactionManager) {

		if (logger.isTraceEnabled()) {
            logger.trace("Creating Pool for " + profileTable);
		}

		createObjectPool(profileTable);

		if (sleeTransactionManager != null) {
			// add a rollback action to remove sbb object pool
			TransactionalAction action = new TransactionalAction() {
				public void execute() {
					if (logger.isDebugEnabled()) {
						logger
								.debug("Due to tx rollback, removing pool for " + profileTable);
					}
					try {
						removeObjectPool(profileTable);
					} catch (Throwable e) {
						logger.error("Failed to remove table's " + profileTable + " object pool", e);
					}
				}
			};
			sleeTransactionManager.getTransactionContext().getAfterRollbackActions().add(action);
		}
	}

Creates an object pool for the specified profile table. If a
transaction manager is used then, and if the tx rollbacks, the pool will
be removed.

@param
@param sleeTransactionManager

Creates an object pool for the specified profile table . If a transaction manager is used then and if the tx rollbacks the pool will be removed .


public void removeObjectPool(final ProfileTableImpl profileTable,
			final SleeTransactionManager sleeTransactionManager) {

		TransactionalAction action = new TransactionalAction() {
			public void execute() {
				if (logger.isTraceEnabled()) {
		            logger.trace("Removing Pool for " + profileTable);
				}

				removeObjectPool(profileTable);
			}
		};

		if (sleeTransactionManager != null) {
			sleeTransactionManager.getTransactionContext().getAfterCommitActions().add(action);
		}
		else {
			action.execute();
		}
	}

public
void
removeObjectPool
(
final
ProfileTableImpl
profileTable
,
final
SleeTransactionManager
sleeTransactionManager
)
{
TransactionalAction
action
=
new
TransactionalAction
(
)
{
public
void
execute
(
)
{
if
(
logger
.
isTraceEnabled
(
)
)
{
logger
.
trace
(
"Removing Pool for "
+
profileTable
)
;
}
removeObjectPool
(
profileTable
)
;
}
}
;
if
(
sleeTransactionManager
!=
)
{
sleeTransactionManager
.
getTransactionContext
(
)
.
getAfterCommitActions
(
)
.
add
(
action
)
;
}
else
{
action
.
execute
(
)
;
}
}

Removes the object pool for the specified profile table. If a
transaction manager is used then the removal is only after the tx commit.

@param sleeTransactionManager
@throws Exception

Removes the object pool for the specified profile table . If a transaction manager is used then the removal is only after the tx commit .


public boolean isSourceOwnerOfAlarm(NotificationSourceWrapper notificationSource, String alarmID) {
		AlarmPlaceHolder aph = this.alarmIdToAlarm.get(alarmID);
		if (aph == null)
			return false;

		return aph.getNotificationSource().getNotificationSource().equals(notificationSource.getNotificationSource());
	}

public boolean isSourceOwnerOfAlarm ( NotificationSourceWrapper notificationSource , String alarmID ) { AlarmPlaceHolder aph = this . alarmIdToAlarm . get ( alarmID ) ; if ( aph == null ) return false ; return aph . getNotificationSource ( ) . getNotificationSource ( ) . equals ( notificationSource . getNotificationSource ( ) ) ; }

NON MBEAN - used only internal, those methods are not exposed via jmx

NON MBEAN - used only internal those methods are not exposed via jmx


public String raiseAlarm(NotificationSourceWrapper notificationSource, String alarmType, String instanceID, AlarmLevel level, String message, Throwable cause) {

		synchronized (notificationSource) {
			if (isAlarmAlive(notificationSource, alarmType, instanceID)) {
				// Alarm a = this.placeHolderToAlarm.get(new
				// AlarmPlaceHolder(notificationSource, alarmType, instanceID));

				Alarm a = null;
				// unconveniant....
				try {
					AlarmPlaceHolder localAPH = new AlarmPlaceHolder(notificationSource, alarmType, instanceID);
					for (Map.Entry<String, AlarmPlaceHolder> e : this.alarmIdToAlarm.entrySet()) {
						if (e.getValue().equals(localAPH)) {
							a = e.getValue().getAlarm();
							break;
						}
					}
				} catch (Exception e) {
					// ignore
				}

				if (a != null) {

					return a.getAlarmID();
				} else {
					return this.raiseAlarm(notificationSource, alarmType, instanceID, level, message, cause);
				}
			} else {
				Alarm a = new Alarm(UUID.randomUUID().toString(), notificationSource.getNotificationSource(), alarmType, instanceID, level, message, cause, System.currentTimeMillis());
				AlarmPlaceHolder aph = new AlarmPlaceHolder(notificationSource, alarmType, instanceID, a);
				this.alarmIdToAlarm.put(a.getAlarmID(), aph);
				// this.placeHolderToAlarm.put(aph, a);
				this.placeHolderToNotificationSource.put(aph, aph.getNotificationSource().getNotificationSource());
				generateNotification(aph, false);
				return a.getAlarmID();
			}
		}

	}

THis methods raises alarm. It MUST not receive AlarmLevel.CLEAR, it has
to be filtered.

@param notificationSource
@param alarmType
@param instanceID
@param level
@param message
@param cause
@return - AlarmId

THis methods raises alarm . It MUST not receive AlarmLevel . CLEAR it has to be filtered .


public static Object getUsageParameterSet(ProfileObjectImpl profileObject,
			String name) throws UnrecognizedUsageParameterSetNameException {
		if (logger.isDebugEnabled()) {
			logger.info("[getUsageParameterSet(" + name + ")] @ "
					+ profileObject);
		}

		if (name == null) {
			throw new NullPointerException(
					"UsageParameterSet name must not be null.");
		}
		ProfileTableImpl profileTable = profileObject
				.getProfileTable();
		Object result = profileTable.getProfileTableUsageMBean()
				.getInstalledUsageParameterSet(name);
		if (result == null) {
			throw new UnrecognizedUsageParameterSetNameException();
		}
		else {
			return result;
		}
	}

Usage methods. Here we can be static for sure. Rest must be tested.

Usage methods . Here we can be static for sure . Rest must be tested .


public javax.slee.management.EventTypeDescriptor getSpecsDescriptor() {
		if (specsDescriptor == null) {
			specsDescriptor = new javax.slee.management.EventTypeDescriptor(getEventTypeID(),getDeployableUnit().getDeployableUnitID(),getDeploymentUnitSource(),descriptor.getLibraryRefs().toArray(new LibraryID[descriptor.getLibraryRefs().size()]),getDescriptor().getEventClassName());
		}
		return specsDescriptor;
	}

public javax . slee . management . EventTypeDescriptor getSpecsDescriptor ( ) { if ( specsDescriptor == null ) { specsDescriptor = new javax . slee . management . EventTypeDescriptor ( getEventTypeID ( ) , getDeployableUnit ( ) . getDeployableUnitID ( ) , getDeploymentUnitSource ( ) , descriptor . getLibraryRefs ( ) . toArray ( new LibraryID [ descriptor . getLibraryRefs ( ) . size ( ) ] ) , getDescriptor ( ) . getEventClassName ( ) ) ; } return specsDescriptor ; }

Retrieves the JAIN SLEE specs event type descriptor
@return


public boolean accepts(URL deployableUnitURL, String deployableUnitName) {
		DeployableUnitWrapper du = new DeployableUnitWrapper(deployableUnitURL, deployableUnitName);

		URL url = du.getUrl();

		if (logger.isTraceEnabled()) {
			logger.trace("Method accepts called for " + url + " [DU: " + deployableUnitName + "]");
		}

		try {
			String fullPath = url.getFile();
			String fileName = fullPath.substring(fullPath.lastIndexOf('/') + 1,
					fullPath.length());

			// Is it in the toAccept list ? Direct accept.
			if (toAccept.containsKey(fileName)) {
				if (logger.isTraceEnabled()) {
					logger.trace("Accepting " + url.toString() + ".");
				}

				return true;
			}
			// If not it the accept list but it's a jar might be a DU jar...
			else if (fileName.endsWith(".jar")) {
				JarFile duJarFile = null;

				try {
					// Try to obtain the DU descriptor, if we got it, we're
					// accepting it!
					if (du.getEntry("META-INF/deployable-unit.xml") != null) {
						if (logger.isTraceEnabled()) {
							logger.trace("Accepting " + url.toString() + ".");
						}

						return true;
					}
				} finally {
					// Clean up!
					if (duJarFile != null) {
						try {
							duJarFile.close();
						} catch (IOException ignore) {
						} finally {
							duJarFile = null;
						}
					}
				}
			}
		} catch (Exception ignore) {
			// Ignore.. will reject.
		}

		// Uh-oh.. looks like it will stay outside.
		return false;
	}

Method for deciding whether or not to accept the file.

Method for deciding whether or not to accept the file .


public void init(URL deployableUnitURL, String deployableUnitName) throws DeploymentException {
		URL url = deployableUnitURL;
		DeployableUnitWrapper du = new DeployableUnitWrapper(deployableUnitURL, deployableUnitName);

		if (logger.isTraceEnabled()) {
			logger.trace("Method init called for " + deployableUnitURL + " [DU: " + deployableUnitName + "]");
		}

		// Get the full path and filename for this du
		String fullPath = du.getFullPath();
		String fileName = du.getFileName();

		try {
			DeployableUnitWrapper duWrapper = null;

			// If we're able to remove it from toAccept was because it was
			// there!
			if ((duWrapper = toAccept.remove(fileName)) != null) {
				// Create a new Deployable Component from this DI.
				DeployableComponent dc = new DeployableComponent(du, url,
						fileName, sleeContainerDeployer);

				// Also get the deployable unit for this (it exists, we've
				// checked!)
				DeployableUnit deployerDU = deployableUnits.get(duWrapper
						.getFileName());

				for (DeployableComponent subDC : dc.getSubComponents()) {
					// Add the sub-component to the DU object.
					deployerDU.addComponent(subDC);
				}
			}
			// If the DU for this component doesn't exists.. it's a new DU!
			else if (fileName.endsWith(".jar")) {
				JarFile duJarFile = null;

				try {
					// Get a reference to the DU jar file
					duJarFile = new JarFile(fullPath);

					// Try to get the Deployable Unit descriptor
					JarEntry duXmlEntry = duJarFile
							.getJarEntry("META-INF/deployable-unit.xml");

					// Got descriptor?
					if (duXmlEntry != null) {
						// Create a new Deployable Unit object.
						DeployableUnit deployerDU = new DeployableUnit(du,sleeContainerDeployer);

						// Let's parse the descriptor to see what we've got...
						DeployableUnitDescriptorFactory dudf = sleeContainerDeployer
								.getSleeContainer().getComponentManagement()
								.getDeployableUnitManagement()
								.getDeployableUnitDescriptorFactory();
						DeployableUnitDescriptor duDesc = dudf.parse(duJarFile
								.getInputStream(duXmlEntry));

						// If the filename is present, an undeploy in on the way... let's wait
						while(deployableUnits.containsKey(fileName)) {
							Thread.sleep(getWaitTimeBetweenOperations());
						}

						// Add it to the deployable units map.
						deployableUnits.put(fileName, deployerDU);

						// Go through each jar entry in the DU descriptor
						for (String componentJarName : duDesc.getJarEntries()) {
							// Might have path... strip it!
							int beginIndex;

							if ((beginIndex = componentJarName.lastIndexOf('/')) == -1)
								beginIndex = componentJarName.lastIndexOf('\\');

							beginIndex++;

							// Got a clean jar name, no paths.
							componentJarName = componentJarName.substring(
									beginIndex, componentJarName.length());

							// Put it in the accept list.
							toAccept.put(componentJarName, du);
						}

						// Do the same as above... but for services
						for (String serviceXMLName : duDesc.getServiceEntries()) {
							// Might have path... strip it!
							int beginIndex;

							if ((beginIndex = serviceXMLName.lastIndexOf('/')) == -1)
								beginIndex = serviceXMLName.lastIndexOf('\\');

							beginIndex++;

							// Got a clean XML filename
							serviceXMLName = serviceXMLName.substring(
									beginIndex, serviceXMLName.length());

							// Add it to the accept list.
							toAccept.put(serviceXMLName, du);
						}
					}
				} finally {
					// Clean up!
					if (duJarFile != null) {
						try {
							duJarFile.close();
						} catch (IOException ignore) {
						} finally {
							duJarFile = null;
						}
					}
				}
			}
		} catch (Exception e) {
			// Something went wrong...
			logger.error("Deployment of " + fileName + " failed. ", e);

			return;
		}
	}

Initializer method for accepted files. Will parse descriptors at this
point.

Initializer method for accepted files . Will parse descriptors at this point .


public void start(URL deployableUnitURL, String deployableUnitName) throws DeploymentException {
		DeployableUnitWrapper du = new DeployableUnitWrapper(deployableUnitURL, deployableUnitName);

		if (logger.isTraceEnabled()) {
			logger.trace("Method start called for " + du.getUrl() + " [DU: " + deployableUnitName + "]");
		}

		try {
			// Get the deployable unit object
			DeployableUnit realDU = deployableUnits.get(du.getFileName());

			// If it exists, install it.
			if (realDU != null) {
				while (isInUndeployList(du.getFileName())) {
					Thread.sleep(getWaitTimeBetweenOperations());
				}
				sleeContainerDeployer.getDeploymentManager().installDeployableUnit(realDU);
			}
		} catch (Exception e) {
			logger.error("", e);
		}
	}

public
void
start
(
URL
deployableUnitURL
,
String
deployableUnitName
)
throws
DeploymentException
{
DeployableUnitWrapper
du
=
new
DeployableUnitWrapper
(
deployableUnitURL
,
deployableUnitName
)
;
if
(
logger
.
isTraceEnabled
(
)
)
{
logger
.
trace
(
"Method start called for "
+
du
.
getUrl
(
)
+
" [DU: "
+
deployableUnitName
+
"]"
)
;
}
try
{
// Get the deployable unit object
DeployableUnit
realDU
=
deployableUnits
.
get
(
du
.
getFileName
(
)
)
;
// If it exists, install it.
if
(
realDU
!=
)
{
while
(
isInUndeployList
(
du
.
getFileName
(
)
)
)
{
Thread
.
sleep
(
getWaitTimeBetweenOperations
(
)
)
;
}
sleeContainerDeployer
.
getDeploymentManager
(
)
.
installDeployableUnit
(
realDU
)
;
}
}
catch
(
Exception
e
)
{
logger
.
error
(
""
,
e
)
;
}
}

This is where the fun begins. Time to deploy!

This is where the fun begins . Time to deploy!


public void stop(URL deployableUnitURL, String deployableUnitName) throws DeploymentException {

		if (logger.isTraceEnabled()) {
			logger.trace("stop( deployableUnitURL = : " + deployableUnitURL+" )");
		}

		DeployableUnitWrapper du = new DeployableUnitWrapper(deployableUnitURL, deployableUnitName);

		DeployableUnit realDU = null;

		String fileName = du.getFileName();

		if ((realDU = deployableUnits.get(du.getFileName())) != null) {
			if (logger.isTraceEnabled()) {
				logger.trace("Got DU: " + realDU.getDeploymentInfoShortName());
			}

			if (!isInUndeployList(fileName)) {
				addToUndeployList(fileName);
			}

			try {
				// Uninstall it
				sleeContainerDeployer.getDeploymentManager().uninstallDeployableUnit(realDU);
				// Remove it from list if successful
				deployableUnits.remove(fileName);
				removeFromUndeployList(fileName);
			} catch (DependencyException e) {
				// ignore, will be tried again once there is another undeployment
			} catch (Exception e) {
				Throwable cause = e.getCause();
				if (cause instanceof InvalidStateException) {
					logger.warn(cause.getLocalizedMessage() + "... WAITING ...");
				} else if (e instanceof DeploymentException) {
					throw new IllegalStateException(e.getLocalizedMessage(), e);
				} else {
					logger.error(e.getMessage(), e);
				}
			}
		}
	}


public String showStatus() throws DeploymentException {
		String output = "";

		output += "
Deployable Units List:
";

		for (String key : deployableUnits.keySet()) {
			output += "<" + key + "> [" + deployableUnits.get(key)
					+ "]
";

			for (String duComponent : deployableUnits.get(key).getComponents()) {
				output += "+-- " + duComponent + "
";
			}
		}

		output += "
To Accept List:
";

		for (String key : toAccept.keySet()) {
			output += "<" + key + "> [" + toAccept.get(key) + "]
";
		}

		output += "
Undeployments running:
";

		for (String undeploy : undeploys) {
			output += "+-- " + undeploy + "
";
		}

		output += "
Deployment Manager Status
";

		output += sleeContainerDeployer.getDeploymentManager().showStatus();

		return output;
	}

public
String
showStatus
(
)
throws
DeploymentException
{
String
output
=
""
;
output
+=
"
Deployable Units List:
"
;
for
(
String
key
:
deployableUnits
.
keySet
(
)
)
{
output
+=
"<"
+
key
+
"> ["
+
deployableUnits
.
get
(
key
)
+
"]
"
;
for
(
String
duComponent
:
deployableUnits
.
get
(
key
)
.
getComponents
(
)
)
{
output
+=
"+-- "
+
duComponent
+
"
"
;
}
}
output
+=
"
To Accept List:
"
;
for
(
String
key
:
toAccept
.
keySet
(
)
)
{
output
+=
"<"
+
key
+
"> ["
+
toAccept
.
get
(
key
)
+
"]
"
;
}
output
+=
"
Undeployments running:
"
;
for
(
String
undeploy
:
undeploys
)
{
output
+=
"+-- "
+
undeploy
+
"
"
;
}
output
+=
"
Deployment Manager Status
"
;
output
+=
sleeContainerDeployer
.
getDeploymentManager
(
)
.
showStatus
(
)
;
return
output
;
}

MBean operation for getting Deployer status.

MBean operation for getting Deployer status .


protected void executeAfterCommitActions() {
		if (afterCommitActions != null) {
			if (trace) {
				logger.trace("Executing after commit actions");
			}
			executeActions(afterCommitActions,trace);
			afterCommitActions = null;
		}
	}

protected
void
executeAfterCommitActions
(
)
{
if
(
afterCommitActions
!=
)
{
if
(
trace
)
{
logger
.
trace
(
"Executing after commit actions"
)
;
}
executeActions
(
afterCommitActions
,
trace
)
;
afterCommitActions
=
;
}
}

Executes actions scheduled after commit succeeds


protected void executeAfterCommitPriorityActions() {
		if (afterCommitPriorityActions != null) {
			if (trace) {
				logger.trace("Executing after commit priority actions");
			}
			executeActions(afterCommitPriorityActions,trace);
			afterCommitPriorityActions = null;
		}
	}

Executes actions scheduled to run first after commit succeeds


protected void executeAfterRollbackActions() {
		if (afterRollbackActions != null) {
			if (trace) {
				logger.trace("Executing rollback actions");
			}
			executeActions(afterRollbackActions,trace);
			afterRollbackActions = null;
		}
	}

protected
void
executeAfterRollbackActions
(
)
{
if
(
afterRollbackActions
!=
)
{
if
(
trace
)
{
logger
.
trace
(
"Executing rollback actions"
)
;
}
executeActions
(
afterRollbackActions
,
trace
)
;
afterRollbackActions
=
;
}
}

Executes actions scheduled for after a rollback


protected void executeBeforeCommitActions() {
		if (beforeCommitActions != null) {
			if (trace) {
				logger.trace("Executing before commit actions");
			}
			executeActions(beforeCommitActions,trace);
			beforeCommitActions = null;
		}
	}

protected
void
executeBeforeCommitActions
(
)
{
if
(
beforeCommitActions
!=
)
{
if
(
trace
)
{
logger
.
trace
(
"Executing before commit actions"
)
;
}
executeActions
(
beforeCommitActions
,
trace
)
;
beforeCommitActions
=
;
}
}

Executes actions scheduled for before commit


protected void executeBeforeCommitPriorityActions() {
		if (beforeCommitPriorityActions != null) {
			if (trace) {
				logger.trace("Executing before commit priority actions");
			}
			executeActions(beforeCommitPriorityActions,trace);
			beforeCommitPriorityActions = null;
		}
	}

Executes actions scheduled for before commit at first


public String[] getDefinedTracerNames() {
		Set<String> names = new HashSet<String>();
		for (TracerImpl t : this.tracers.values()) {
			if (t.isExplicitlySetTracerLevel())
				names.add(t.getTracerName());
		}
		if(names.isEmpty())
			return new String[0];
		return names.toArray(new String[names.size()]);
	}

public String [ ] getDefinedTracerNames ( ) { Set < String > names = new HashSet < String > ( ) ; for ( TracerImpl t : this . tracers . values ( ) ) { if ( t . isExplicitlySetTracerLevel ( ) ) names . add ( t . getTracerName ( ) ) ; } if ( names . isEmpty ( ) ) return new String [ 0 ] ; return names . toArray ( new String [ names . size ( ) ] ) ; }

This method returns tracer names that have been defined explicitly via
setTraceLevel from TraceMBean

@return


public Tracer createTracer(String tracerName, boolean requestedBySource) {

		TracerImpl tparent = null;
		TracerImpl t = tracers.get(tracerName);
		if (t == null) {
			String[] split = tracerName.split("\\.");
			String currentName = "";
			for (String s : split) {
				if (tparent == null) {
					// first loop
					tparent = rootTracer;
					currentName = s;
				} else {
					currentName = currentName + "." + s;
				}
				t = tracers.get(currentName);
				if (t == null) {
					t = new TracerImpl(currentName, tparent, this.notificationSource, this.traceFacility);
					final TracerImpl u = tracers.putIfAbsent(t.getTracerName(), t);
					if (u != null) {
						t = u;
					}
				}
				tparent = t;
			}
		}

		if (requestedBySource)
			t.setRequestedBySource(requestedBySource);
		return t;
	}

public
Tracer
createTracer
(
String
tracerName
,
boolean
requestedBySource
)
{
TracerImpl
tparent
=
;
TracerImpl
t
=
tracers
.
get
(
tracerName
)
;
if
(
t
==
)
{
String
[
]
split
=
tracerName
.
split
(
"\\."
)
;
String
currentName
=
""
;
for
(
String
s
:
split
)
{
if
(
tparent
==
)
{
// first loop
tparent
=
rootTracer
;
currentName
=
s
;
}
else
{
currentName
=
currentName
+
"."
+
s
;
}
t
=
tracers
.
get
(
currentName
)
;
if
(
t
==
)
{
t
=
new
TracerImpl
(
currentName
,
tparent
,
this
.
notificationSource
,
this
.
traceFacility
)
;
final
TracerImpl
u
=
tracers
.
putIfAbsent
(
t
.
getTracerName
(
)
,
t
)
;
if
(
u
!=
)
{
t
=
u
;
}
}
tparent
=
t
;
}
}
if
(
requestedBySource
)
t
.
setRequestedBySource
(
requestedBySource
)
;
return
t
;
}

This method can be called multiple times.

@param tracerName
@param requestedBySource
@return

This method can be called multiple times .


public void removeReplicateData() {
		if (replicatedDataWithFailover != null) {
			replicatedDataWithFailover.remove();
			replicatedDataWithFailover = null;
		}
		if (replicatedData != null) {
			replicatedData.remove();
			replicatedData = null;
		}
	}

public void removeReplicateData ( ) { if ( replicatedDataWithFailover != null ) { replicatedDataWithFailover . remove ( ) ; replicatedDataWithFailover = null ; } if ( replicatedData != null ) { replicatedData . remove ( ) ; replicatedData = null ; } }


public void register() {

		PropertyEditorManager.registerEditor(ComponentID.class,
				ComponentIDPropertyEditor.class);
		PropertyEditorManager.registerEditor(EventTypeID.class,
				ComponentIDPropertyEditor.class);
		PropertyEditorManager.registerEditor(LibraryID.class,
				ComponentIDPropertyEditor.class);
		PropertyEditorManager.registerEditor(ProfileSpecificationID.class,
				ComponentIDPropertyEditor.class);
		PropertyEditorManager.registerEditor(ResourceAdaptorID.class,
				ComponentIDPropertyEditor.class);
		PropertyEditorManager.registerEditor(ResourceAdaptorTypeID.class,
				ComponentIDPropertyEditor.class);
		PropertyEditorManager.registerEditor(SbbID.class,
				ComponentIDPropertyEditor.class);
		PropertyEditorManager.registerEditor(ServiceID.class,
				ComponentIDPropertyEditor.class);

		PropertyEditorManager.registerEditor(ComponentID[].class,
				ComponentIDArrayPropertyEditor.class);
		PropertyEditorManager.registerEditor(EventTypeID[].class,
				ComponentIDArrayPropertyEditor.class);
		PropertyEditorManager.registerEditor(LibraryID[].class,
				ComponentIDArrayPropertyEditor.class);
		PropertyEditorManager.registerEditor(ProfileSpecificationID[].class,
				ComponentIDArrayPropertyEditor.class);
		PropertyEditorManager.registerEditor(ResourceAdaptorID[].class,
				ComponentIDArrayPropertyEditor.class);
		PropertyEditorManager.registerEditor(ResourceAdaptorTypeID[].class,
				ComponentIDArrayPropertyEditor.class);
		PropertyEditorManager.registerEditor(SbbID[].class,
				ComponentIDArrayPropertyEditor.class);
		PropertyEditorManager.registerEditor(ServiceID[].class,
				ComponentIDArrayPropertyEditor.class);

		PropertyEditorManager.registerEditor(DeployableUnitID.class,
				DeployableUnitIDPropertyEditor.class);

		PropertyEditorManager.registerEditor(Level.class,
				LevelPropertyEditor.class);
		PropertyEditorManager.registerEditor(TraceLevel.class,
				TraceLevelPropertyEditor.class);

		PropertyEditorManager.registerEditor(ConfigProperties.class,
				ConfigPropertiesPropertyEditor.class);

		PropertyEditorManager.registerEditor(NotificationSource.class,
				NotificationSourcePropertyEditor.class);

		PropertyEditorManager.registerEditor(Object.class,
				ObjectPropertyEditor.class);

		PropertyEditorManager.registerEditor(ServiceState.class,
				ServiceStatePropertyEditor.class);
		PropertyEditorManager.registerEditor(ResourceAdaptorEntityState.class,
				ResourceAdaptorEntityStatePropertyEditor.class);
		PropertyEditorManager.registerEditor(Address.class,
				AddressPropertyEditor.class);

	}

Register the property editors for jboss jmx console, so non string SLEE api types can be used in specs mbeans methods as args

Register the property editors for jboss jmx console so non string SLEE api types can be used in specs mbeans methods as args


public void process(SleeComponentWithUsageParametersInterface component) throws DeploymentException {

		ClassPool classPool = component.getClassPool();
		String deploymentDir = component.getDeploymentDir().getAbsolutePath();
		Class<?> usageParametersInterface = component
				.getUsageParametersInterface();
		if (usageParametersInterface != null) {
			try {
				// generate the concrete usage param set class
				component
						.setUsageParametersConcreteClass(new ConcreteUsageParameterClassGenerator(
								usageParametersInterface.getName(),
								deploymentDir, classPool)
								.generateConcreteUsageParameterClass());
				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug("Generated usage parameter impl class for "+component);
		        }
				// generate the mbeans
				new ConcreteUsageParameterMBeanGenerator(component)
						.generateConcreteUsageParameterMBean();

				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug("Generated usage mbean (interface and impl) for "+component);
		        }

			} catch (DeploymentException ex) {
				throw ex;
			} catch (Exception ex) {
				throw new DeploymentException(
						"Failed to generate "+component+" usage parameter class", ex);
			}
		}

	}

Generates classes for a slee component, which defines usage parameters
@param component
@throws DeploymentException

Generates classes for a slee component which defines usage parameters


public SbbObjectPoolImpl getObjectPool(ServiceID serviceID, SbbID sbbID) {
		return pools.get(new ObjectPoolMapKey(serviceID,sbbID));
	}

public SbbObjectPoolImpl getObjectPool ( ServiceID serviceID , SbbID sbbID ) { return pools . get ( new ObjectPoolMapKey ( serviceID , sbbID ) ) ; }

Retrieves the object pool for the specified sbb and service.
@param serviceID
@param sbbID
@return

Retrieves the object pool for the specified sbb and service .


public void createObjectPool(final ServiceID serviceID, final SbbComponent sbbComponent,
			final SleeTransactionManager sleeTransactionManager) {

		if (logger.isTraceEnabled()) {
            logger.trace("Creating Pool for  " + serviceID +" and "+ sbbComponent);
		}

		createObjectPool(serviceID,sbbComponent);

		if (sleeTransactionManager != null && sleeTransactionManager.getTransactionContext() != null) {
			// add a rollback action to remove sbb object pool
			TransactionalAction action = new TransactionalAction() {
				public void execute() {
					if (logger.isDebugEnabled()) {
						logger
								.debug("Due to tx rollback, removing pool for " + serviceID +" and "+ sbbComponent);
					}
					try {
						removeObjectPool(serviceID,sbbComponent.getSbbID());
					} catch (Throwable e) {
						logger.error("Failed to remove " + serviceID +" and "+ sbbComponent + " object pool", e);
					}
				}
			};
			sleeTransactionManager.getTransactionContext().getAfterRollbackActions().add(action);
		}
	}

Creates an object pool for the specified service and sbb. If a
transaction manager is used then, and if the tx rollbacks, the pool will
be removed.

@param
@param sleeTransactionManager

Creates an object pool for the specified service and sbb . If a transaction manager is used then and if the tx rollbacks the pool will be removed .


void execute(final ActivityHandle handle)
			throws UnrecognizedActivityHandleException {

		final SleeTransaction tx = super.suspendTransaction();
		try {
			sleeEndpoint._endActivity(handle,tx);
		} finally {
			if (tx != null) {
				super.resumeTransaction(tx);
			}
		}
	}

void execute ( final ActivityHandle handle ) throws UnrecognizedActivityHandleException { final SleeTransaction tx = super . suspendTransaction ( ) ; try { sleeEndpoint . _endActivity ( handle , tx ) ; } finally { if ( tx != null ) { super . resumeTransaction ( tx ) ; } } }

Executes a non transacted End Activity operation.

@param handle
@throws UnrecognizedActivityHandleException

Executes a non transacted End Activity operation .


ActivityContextHandle _startActivity(ActivityHandle handle,
			int activityFlags, final SleeTransaction barrierTx) {

		ActivityContext ac = null;
		if (raEntity.getHandleReferenceFactory() != null
				&& !ActivityFlags.hasSleeMayMarshal(activityFlags)) {
			final ActivityHandleReference reference = raEntity
					.getHandleReferenceFactory().createActivityHandleReference(
							handle);
			try {
				// create activity context with ref instead
				ac = acFactory.createActivityContext(
						new ResourceAdaptorActivityContextHandleImpl(raEntity,
								reference), activityFlags);
			} catch (ActivityAlreadyExistsException e) {
				throw e;
			} catch (RuntimeException e) {
				raEntity.getHandleReferenceFactory()
						.removeActivityHandleReference(reference);
				throw e;
			}
		} else {
			// create activity context
			ac = acFactory.createActivityContext(
					new ResourceAdaptorActivityContextHandleImpl(raEntity,
							handle), activityFlags);
		}
		// suspend activity if needed
		if (barrierTx != null && ac != null) {
			final ActivityEventQueueManager aeqm = ac.getLocalActivityContext().getEventQueueManager();
			aeqm.createBarrier(barrierTx);
			TransactionalAction action = new TransactionalAction() {
				public void execute() {
					aeqm.removeBarrier(barrierTx);
				}
			};
			final TransactionContext tc = barrierTx.getTransactionContext();
			tc.getAfterCommitActions().add(action);
			tc.getAfterRollbackActions().add(action);
		}
		return ac.getActivityContextHandle();
	}

Start activity logic, independent of transaction management.
@param handle
@param activityFlags
@param barrierTx
@return

Start activity logic independent of transaction management .


void _endActivity(ActivityHandle handle, final SleeTransaction barrierTx)
			throws UnrecognizedActivityHandleException {
		final ActivityContextHandle ach = new ResourceAdaptorActivityContextHandleImpl(
				raEntity, handle);
		// get ac
		final ActivityContext ac = acFactory.getActivityContext(ach);
		if (ac != null) {
			// suspend activity if needed
			if (barrierTx != null) {
				final ActivityEventQueueManager aeqm = ac.getLocalActivityContext().getEventQueueManager();
				aeqm.createBarrier(barrierTx);
				TransactionalAction action = new TransactionalAction() {
					public void execute() {
						aeqm.removeBarrier(barrierTx);
					}
				};
				final TransactionContext tc = barrierTx.getTransactionContext();
				tc.getAfterCommitActions().add(action);
				tc.getAfterRollbackActions().add(action);
			}
			// end the activity
			ac.endActivity();
		} else {
			throw new UnrecognizedActivityHandleException(handle.toString());
		}
	}

End activity logic independent of transaction management.
@param handle
@param barrierTx
@throws UnrecognizedActivityHandleException

End activity logic independent of transaction management .


private void checkFireEventPreconditions(ActivityHandle handle,
			FireableEventType eventType, Object event)
			throws NullPointerException, IllegalEventException,
			IllegalStateException {

		if (event == null)
			throw new NullPointerException("event is null");

		if (handle == null)
			throw new NullPointerException("handle is null");

		if (eventType == null) {
			throw new NullPointerException("eventType is null");
		}
		final EventTypeComponent eventTypeComponent = componentRepository
				.getComponentByID(eventType.getEventType());
		if (eventTypeComponent == null) {
			throw new IllegalEventException(
					"event type not installed (more on SLEE 1.1 specs 15.14.8)");
		}

		if (!eventTypeComponent.getEventTypeClass().isAssignableFrom(
				event.getClass())) {
			throw new IllegalEventException(
					"the class of the event object fired is not assignable to the event class of the event type (more on SLEE 1.1 specs 15.14.8) ");
		}

		if (eventType.getClass() != FireableEventTypeImpl.class) {
			throw new IllegalEventException(
					"unknown implementation of FireableEventType");
		}

		if (raEntity.getAllowedEventTypes() != null
				&& !raEntity.getAllowedEventTypes().contains(
						eventType.getEventType())) {
			throw new IllegalEventException(
					"Resource Adaptor configured to not ignore ra type event checking and the event "
							+ eventType.getEventType()
							+ " does not belongs to any of the ra types implemented by the resource adaptor");
		}
	}

Checks that fire event methods can be invoked

@param handle
@param eventType
@param event
@throws NullPointerException
@throws IllegalEventException
@throws IllegalStateException