0001: /*
0002: * BEGIN_HEADER - DO NOT EDIT
0003: *
0004: * The contents of this file are subject to the terms
0005: * of the Common Development and Distribution License
0006: * (the "License"). You may not use this file except
0007: * in compliance with the License.
0008: *
0009: * You can obtain a copy of the license at
0010: * https://open-esb.dev.java.net/public/CDDLv1.0.html.
0011: * See the License for the specific language governing
0012: * permissions and limitations under the License.
0013: *
0014: * When distributing Covered Code, include this CDDL
0015: * HEADER in each file and include the License file at
0016: * https://open-esb.dev.java.net/public/CDDLv1.0.html.
0017: * If applicable add the following below this CDDL HEADER,
0018: * with the fields enclosed by brackets "[]" replaced with
0019: * your own identifying information: Portions Copyright
0020: * [year] [name of copyright owner]
0021: */
0022:
0023: /*
0024: * @(#)DeploymentService.java
0025: * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved.
0026: *
0027: * END_HEADER - DO NOT EDIT
0028: */
0029: package com.sun.jbi.management.system;
0030:
0031: import com.sun.jbi.ComponentInfo;
0032: import com.sun.jbi.ComponentState;
0033: import com.sun.jbi.ComponentType;
0034: import com.sun.jbi.ServiceAssemblyInfo;
0035: import com.sun.jbi.ServiceAssemblyQuery;
0036: import com.sun.jbi.ServiceAssemblyState;
0037: import com.sun.jbi.ServiceUnitInfo;
0038: import com.sun.jbi.ServiceUnitState;
0039: import com.sun.jbi.ServiceUnitRegistration;
0040: import com.sun.jbi.StringTranslator;
0041: import com.sun.jbi.framework.DeployerMBean;
0042: import com.sun.jbi.framework.EventNotifierCommon;
0043: import com.sun.jbi.management.ComponentMessageHolder;
0044: import com.sun.jbi.management.LocalStringKeys;
0045: import com.sun.jbi.management.MBeanNames;
0046: import com.sun.jbi.management.internal.support.DirectoryUtil;
0047: import com.sun.jbi.management.internal.support.DOMUtil;
0048: import com.sun.jbi.management.message.MessageBuilder;
0049: import com.sun.jbi.management.message.MessageHelper;
0050: import com.sun.jbi.management.descriptor.ServiceAssemblyDescriptor;
0051: import com.sun.jbi.management.registry.data.ServiceAssemblyInfoImpl;
0052: import com.sun.jbi.management.repository.Archive;
0053: import com.sun.jbi.management.repository.ArchiveType;
0054: import com.sun.jbi.management.support.JbiNameInfo;
0055: import com.sun.jbi.management.util.FileHelper;
0056: import com.sun.jbi.messaging.Link;
0057: import com.sun.jbi.messaging.ConnectionManager;
0058:
0059: import java.io.File;
0060: import java.io.FileOutputStream;
0061: import java.io.InputStream;
0062: import java.io.CharArrayReader;
0063: import java.io.IOException;
0064: import java.io.StringReader;
0065: import java.io.StringWriter;
0066: import java.net.URL;
0067: import java.util.ArrayList;
0068: import java.util.Date;
0069: import java.util.HashMap;
0070: import java.util.Iterator;
0071: import java.util.List;
0072: import java.util.Map;
0073: import java.util.Map.Entry;
0074: import java.util.Set;
0075: import java.util.logging.Level;
0076: import java.util.logging.Logger;
0077: import java.util.zip.ZipFile;
0078: import java.util.zip.ZipEntry;
0079: import java.util.Enumeration;
0080:
0081: import javax.jbi.JBIException;
0082: import javax.jbi.management.DeploymentServiceMBean;
0083: import javax.jbi.management.DeploymentException;
0084:
0085: import javax.management.MBeanException;
0086: import javax.management.MBeanServer;
0087: import javax.management.MBeanServerConnection;
0088: import javax.management.ObjectName;
0089: import javax.xml.namespace.QName;
0090: import javax.xml.parsers.DocumentBuilder;
0091: import javax.xml.parsers.DocumentBuilderFactory;
0092:
0093: import org.w3c.dom.Document;
0094: import org.w3c.dom.Element;
0095: import org.w3c.dom.Node;
0096: import org.w3c.dom.NodeList;
0097: import org.xml.sax.InputSource;
0098:
0099: /**
0100: * This is the Deployment Service, which is responsible for the management
0101: * and administration of Service Assemblies.
0102: *
0103: * @author Sun Microsystems, Inc.
0104: */
0105: public class DeploymentService extends ModelSystemService implements
0106: com.sun.jbi.management.DeploymentServiceMBean {
0107: /**
0108: * Management context
0109: */
0110: private static ManagementContext sMContext = null;
0111:
0112: /**
0113: * Management Message Impl
0114: */
0115: private BuildManagementMessageImpl mMImpl = null;
0116:
0117: /*
0118: * JBI deploy root
0119: */
0120: private String dplyRoot = null;
0121:
0122: /**
0123: * file that gets created when a directory is not successfully deleted
0124: */
0125: private static final String PATH_TO_DELETE_ME_FILE = ".DELETE_ME";
0126:
0127: /**
0128: * Handle to StringTranslator for message translation
0129: */
0130: private StringTranslator mTranslator;
0131:
0132: private final JbiNameInfo mJbiNameInfo = new JbiNameInfo(
0133: "DeploymentService");
0134:
0135: /**
0136: * statistics mbean
0137: */
0138: private DeploymentServiceStatisticsMBean mStatisticsMBean;
0139:
0140: /**
0141: * map of SA names to SA stats objects
0142: */
0143: private Map<String, ServiceAssemblyStatistics> mServiceAssemblyStats = new HashMap<String, ServiceAssemblyStatistics>();
0144:
0145: /**
0146: * statistics enable/disable flag
0147: */
0148: private boolean mStatisticsEnabled = true;
0149:
0150: /** lifecycle operation start */
0151: private static String START = "start";
0152:
0153: /** lifecycle operation stop */
0154: private static String STOP = "stop";
0155:
0156: /** lifecycle operation shut down */
0157: private static String SHUTDOWN = "shutDown";
0158:
0159: /** Constructs a <CODE>DeploymentService</CODE>.
0160: * @param anEnv ManagementContext.
0161: */
0162: public DeploymentService(ManagementContext anEnv)
0163: throws JBIException {
0164: sMContext = anEnv;
0165: mMImpl = new BuildManagementMessageImpl();
0166:
0167: mStatisticsMBean = new DeploymentServiceStatistics(this , anEnv
0168: .getEnvironmentContext());
0169:
0170: /*
0171: * Local initialization of this service.
0172: * Local routine is responsible for calling super.initModelSystemService(..).
0173: */
0174: initModelSystemService(anEnv.getEnvironmentContext());
0175:
0176: mTranslator = (StringTranslator) anEnv.getEnvironmentContext()
0177: .getStringTranslator("com.sun.jbi.management");
0178:
0179: //register INITIAL mbean set:
0180:
0181: // add statistics mbean
0182: mInitialMBeans
0183: .replace(
0184: super .mStatisticsMBeanName,
0185: com.sun.jbi.management.system.DeploymentServiceStatisticsMBean.class,
0186: mStatisticsMBean);
0187: mInitialMBeans.register();
0188:
0189: dplyRoot = sMContext.getJbiInstallRoot() + File.separator
0190: + "service-assemblies";
0191: }
0192:
0193: /** local model init - called by constructor - create custom mbeans. */
0194: protected void initModelSystemService(
0195: com.sun.jbi.EnvironmentContext anEnv) {
0196: String loggerName = com.sun.jbi.management.config.LoggerConfigurationFactory.DEPLOYMENT_LOGGER;
0197:
0198: Logger logger = Logger.getLogger(loggerName);
0199:
0200: //initialize the super.
0201: super .initModelSystemService(anEnv, logger, mJbiNameInfo);
0202:
0203: mStatisticsMBean.setLastRestartTime(new Date());
0204: mStatisticsMBean.setEnabled();
0205:
0206: //add DeploymentService MBean to START/STOP mbean set:
0207: mStartMBeans.add(mDeployServiceMBeanName,
0208: com.sun.jbi.management.DeploymentServiceMBean.class,
0209: this );
0210: }
0211:
0212: /**
0213: * Deploy a Service Assembly (SA) to the JBI framework.
0214: * @param saZipURL The URL of the Service Assembly.
0215: * @return A string containing the status of
0216: * Service Assembly deployment including messages from components.
0217: * @throws Exception If failed to deploy an SA.
0218: */
0219: public String deploy(String saZipURL) throws Exception {
0220: String dplyRslt = null;
0221: List cmpTaskRslts = new ArrayList();
0222: boolean saDplyRslt = true;
0223: int numCmps = 0;
0224: int numScssDplyToCmps = 0;
0225: URL saUrl = null;
0226: EventNotifierCommon notifier = sMContext
0227: .getEnvironmentContext().getNotifier();
0228:
0229: try {
0230: if (saZipURL == null) {
0231: String errMsg = mTranslator
0232: .getString(LocalStringKeys.DS_CANNOT_DEPLOY_SA_ZIP_URL_NULL);
0233: String jbiExStr = buildFrmwkExMsg("deploy", null,
0234: errMsg);
0235: throw new Exception(jbiExStr);
0236: }
0237: saUrl = convertToProperURL(saZipURL);
0238: } catch (Exception e) {
0239: throw e;
0240: }
0241:
0242: File ar = new File(saUrl.getFile());
0243: Archive saArchive = new Archive(ar, false);
0244: ServiceAssemblyDescriptor descr = new ServiceAssemblyDescriptor(
0245: saArchive.getJbiXml(false));
0246: String saName = descr.getName();
0247:
0248: if (!mEnv.getPlatformContext().isAdminServer()) {
0249:
0250: ServiceAssemblyInfoImpl saInfo = new ServiceAssemblyInfoImpl();
0251: saInfo.setName(saArchive.getJbiName());
0252: try {
0253: //add archive to repository if not present - repeated deployments
0254: ServiceAssemblyQuery saQuery = getRegistry()
0255: .getServiceAssemblyQuery();
0256: if (!saQuery.getServiceAssemblies().contains(saName)) {
0257: getRegistry().getRepository().addArchive(saArchive);
0258: getRegistry().getUpdater().addServiceAssembly(
0259: saName, saArchive.getFileName(),
0260: saArchive.getUploadTimestamp());
0261: saUrl = new File(saArchive.getPath()).toURL();
0262: } else {
0263: File existingArchive = new File(getRegistry()
0264: .getRepository().findArchive(
0265: ArchiveType.SERVICE_ASSEMBLY,
0266: saName));
0267:
0268: boolean areArchivesIdentical = FileHelper
0269: .areFilesIdentical(existingArchive, ar);
0270: if (!areArchivesIdentical) {
0271: String errMsg = mTranslator
0272: .getString(
0273: LocalStringKeys.DS_SERVICE_ASSEMBLY_WITH_SAME_NAME_EXISTS,
0274: saName);
0275: throw new Exception(errMsg);
0276: }
0277: }
0278:
0279: } catch (JBIException jbiex) {
0280: MessageBuilder msgBuilder = new MessageBuilder(
0281: mTranslator);
0282:
0283: throw new JBIException(msgBuilder
0284: .buildExceptionMessage("deploy", jbiex));
0285: }
0286:
0287: ar.delete();
0288: }
0289:
0290: try {
0291: ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName,
0292: "domain");
0293: List<ServiceUnitInfo> suList = saInfo.getServiceUnitList();
0294: DocumentBuilderFactory dbf = DocumentBuilderFactory
0295: .newInstance();
0296: DocumentBuilder db = dbf.newDocumentBuilder();
0297:
0298: for (ServiceUnitInfo su : suList) {
0299: String suName = null;
0300: String compName = null;
0301: ComponentState cmpState = ComponentState.UNKNOWN;
0302: String suRootPath = null;
0303: boolean skipDeployment = false;
0304:
0305: try {
0306: suName = su.getName();
0307: compName = su.getTargetComponent();
0308: suRootPath = su.getFilePath();
0309:
0310: mLogger.fine("About to deploy service unit "
0311: + suName);
0312:
0313: numCmps++;
0314:
0315: String suJarAbsPath = getRegistry().getRepository()
0316: .findArchive(
0317: ArchiveType.SERVICE_UNIT,
0318: saName + java.io.File.separator
0319: + suName);
0320:
0321: cmpState = getComponentState(compName);
0322: if (cmpState == ComponentState.UNKNOWN) {
0323: String errMsg = mTranslator
0324: .getString(
0325: LocalStringKeys.DS_CANNOT_DEPLOY_SERVICE_UNIT_COMP_NOT_INSTALLED,
0326: suName, compName);
0327: throw new Exception(errMsg);
0328: }
0329:
0330: if (cmpState == ComponentState.SHUTDOWN) {
0331: String errMsg = mTranslator
0332: .getString(
0333: LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_IN_INCORRECT_STATE,
0334: suName, compName);
0335: throw new Exception(errMsg);
0336: }
0337:
0338: boolean isSURegistered = sMContext
0339: .getServiceUnitRegistration()
0340: .isServiceUnitRegistered(compName, suName);
0341:
0342: if (isSURegistered) {
0343: mLogger.finest("Service unit " + suName
0344: + " already registered.");
0345: skipDeployment = true;
0346: }
0347:
0348: mLogger
0349: .fine("Checking the service unit contents for service unit "
0350: + suName);
0351: ServiceUnitInfo aSUInfo = getServiceUnitInfo(
0352: compName, suName);
0353: if ((aSUInfo != null)
0354: && (!saName.equalsIgnoreCase(aSUInfo
0355: .getServiceAssemblyName()))) {
0356: String errMsg = mTranslator
0357: .getString(
0358: LocalStringKeys.DS_CANNOT_DEPLOY_SERVICE_UNIT_DUPLICATE_SU_NAME,
0359: suName, compName);
0360: throw new Exception(errMsg);
0361: }
0362:
0363: boolean isDuplicateSUContents = checkSUContents(
0364: saName, compName, suName, suJarAbsPath);
0365:
0366: if (isDuplicateSUContents) {
0367: String errMsg = mTranslator
0368: .getString(
0369: LocalStringKeys.DS_CANNOT_DEPLOY_SERVICE_UNIT_DUPLICATE_SU_CONTENTS,
0370: suName, compName);
0371: throw new Exception(errMsg);
0372: }
0373:
0374: } catch (Exception e) {
0375: Element elem = getComponentResultXmlFragment(
0376: compName, "deploy", e);
0377: cmpTaskRslts.add(elem);
0378:
0379: // Stop processing and try to deploy
0380: // the next SU in the SA.
0381: continue;
0382: }
0383:
0384: mLogger
0385: .finest("Invoking deploy operation for service unit "
0386: + suName + " and component " + compName);
0387:
0388: String cmpTaskRslt = null;
0389: try {
0390: if (skipDeployment) {
0391: mLogger.fine("Skipping deployment of "
0392: + suName);
0393: numScssDplyToCmps++;
0394: // build a success component-task-result element
0395: String locMsg = mTranslator
0396: .getString(
0397: LocalStringKeys.DS_SERVICE_UNIT_ALREADY_DEPLOYED,
0398: suName);
0399: String scssMsg = buildComponentStatusMsg(
0400: compName, "deploy", suName, locMsg);
0401: Document doc = db.parse(new InputSource(
0402: new StringReader(scssMsg)));
0403: Element elem = DOMUtil.UTIL.getElement(doc,
0404: "component-task-result");
0405: cmpTaskRslts.add(elem);
0406: } else {
0407: DeployerMBean deployer = getComponentDeployerInstance(compName);
0408:
0409: if (deployer != null) {
0410: dplyRslt = deployer.deploy(suName,
0411: suRootPath);
0412: } else {
0413: String errMsg = mTranslator
0414: .getString(
0415: LocalStringKeys.DS_CANNOT_DEPLOY_SU_DEPLOYER_INSTANCE_NULL,
0416: suName, compName, cmpState);
0417: throw new Exception(errMsg);
0418: }
0419:
0420: String suRgstrnRslt = null;
0421:
0422: boolean isSUDplymntScss = checkSUTaskRsltStatus(dplyRslt);
0423: String dplyRsltWithWarning = null;
0424: Document doc = null;
0425:
0426: if (isSUDplymntScss) {
0427: // Emit a notification of the successful deploy
0428: if (null != notifier) {
0429: notifier
0430: .emitServiceUnitNotification(
0431: EventNotifierCommon.EventType.Deployed,
0432: suName, saName,
0433: compName, "");
0434: }
0435:
0436: suRgstrnRslt = registerServiceUnit(
0437: compName, saName, suName,
0438: suRootPath);
0439:
0440: mLogger.finest("Registered service unit "
0441: + suName + " for component "
0442: + compName + " with result "
0443: + suRgstrnRslt);
0444:
0445: if (suRgstrnRslt
0446: .equalsIgnoreCase("SUCCESS")) {
0447: doc = db.parse(new InputSource(
0448: new StringReader(dplyRslt)));
0449: } else {
0450: dplyRsltWithWarning = appendWarningToCmpRslt(
0451: suRgstrnRslt, dplyRslt);
0452: doc = db.parse(new InputSource(
0453: new StringReader(
0454: dplyRsltWithWarning)));
0455: }
0456: numScssDplyToCmps++;
0457: } else {
0458: doc = db.parse(new InputSource(
0459: new StringReader(dplyRslt)));
0460: }
0461:
0462: Element elem = DOMUtil.UTIL.getElement(doc,
0463: "component-task-result");
0464: cmpTaskRslts.add(elem);
0465: }
0466:
0467: } catch (DeploymentException e) {
0468: Element elem = getComponentResultXmlFragment(
0469: compName, "deploy", e);
0470: cmpTaskRslts.add(elem);
0471: }
0472: }
0473:
0474: // check to see if at least one service unit was deployed successfully
0475:
0476: if (numCmps > 0 && numScssDplyToCmps == 0) {
0477: saDplyRslt = false;
0478: }
0479: } catch (DeploymentException de) {
0480: throw new Exception(de.getMessage());
0481: } catch (Exception e) {
0482: String errMsg = mTranslator.getString(
0483: LocalStringKeys.DS_CANNOT_DEPLOY_SERVICE_ASSEMBLY,
0484: saUrl);
0485: String jbiTaskStr = buildFrmwkExMsg("deploy", e, errMsg);
0486: throw new Exception(jbiTaskStr);
0487: }
0488:
0489: String resp = buildResponse(cmpTaskRslts, saDplyRslt, "deploy",
0490: saName);
0491:
0492: if (!saDplyRslt) {
0493: mLogger.info(mTranslator.getString(
0494: LocalStringKeys.DS_DEPLOYMENT_FAILURE, saUrl));
0495:
0496: String saUnzipDir = null;
0497:
0498: if (!mEnv.getPlatformContext().isAdminServer()) {
0499: // -- Complete failure to deploy
0500: // -- Remove from the local registry / repository
0501: try {
0502: getRegistry().getRepository().removeArchive(
0503: ArchiveType.SERVICE_ASSEMBLY, saName);
0504: getRegistry().getUpdater().removeServiceAssembly(
0505: "domain", saName);
0506: } catch (JBIException jbiex) {
0507: mLogger.warning(jbiex.getMessage());
0508: }
0509: }
0510:
0511: // deployment failure requires an exception to be thrown
0512: throw new Exception(resp);
0513: }
0514: String deployMsg = mTranslator.getString(
0515: LocalStringKeys.DS_DEPLOYMENT_SUCCESS, saUrl);
0516: mLogger.info(deployMsg);
0517:
0518: // Emit a notification of the successful deploy
0519: if (null != notifier) {
0520: notifier.emitServiceAssemblyNotification(
0521: EventNotifierCommon.EventType.Deployed, saName,
0522: deployMsg);
0523: }
0524:
0525: try {
0526: // If this is a redeploy the service assembly might be present under the instance.
0527: if (!getRegistry().getServiceAssemblyQuery()
0528: .getServiceAssemblies().contains(saName)) {
0529: getRegistry().getUpdater().addServiceAssembly(saName);
0530: if (isServiceAssemblyEmpty(saName)) {
0531: getRegistry().getUpdater().setServiceAssemblyState(
0532: ServiceAssemblyState.SHUTDOWN, saName);
0533: }
0534:
0535: }
0536: } catch (JBIException jbiex) {
0537: MessageBuilder msgBuilder = new MessageBuilder(mTranslator);
0538:
0539: throw new JBIException(msgBuilder.buildExceptionMessage(
0540: "deploy", jbiex));
0541: }
0542:
0543: return resp;
0544: }
0545:
0546: /**
0547: * Undeploy a Service Assembly from the JBI framework.
0548: * @param saName - service assembly name
0549: * @return A string containing the status of
0550: * Service Assembly undeployment including messages from components.
0551: * @throws Exception if undeploy fails.
0552: */
0553: public String undeploy(String saName) throws Exception {
0554: //default force = false, keep = false ( keep is ignored on the instance )
0555: return undeploy(saName, false, false);
0556: }
0557:
0558: /**
0559: * Get list of deployed service units to the component.
0560: * @param componentName The name of the component.
0561: * @return A string array containing the list of
0562: * service units deployed to the component.
0563: * @throws Exception If component throws an exception
0564: */
0565:
0566: public String[] getDeployedServiceUnitList(String componentName)
0567: throws Exception {
0568: String[] suNameList = null;
0569: Element elem = null;
0570:
0571: try {
0572: MBeanServerConnection mbeanServer = getMBeanServerConnection();
0573: Object resultObject = getDeployerMBeanObjectName(componentName);
0574: if (resultObject == null) {
0575: throw new DeploymentException(
0576: "LIFECYCLE_OBJECTNAME_IS_NULL");
0577: }
0578: ObjectName dplyrObjName = (ObjectName) resultObject;
0579:
0580: DocumentBuilderFactory dbf = DocumentBuilderFactory
0581: .newInstance();
0582: DocumentBuilder db = dbf.newDocumentBuilder();
0583: try {
0584: Object rsltObject = mbeanServer.getAttribute(
0585: dplyrObjName, "Deployments");
0586:
0587: suNameList = (String[]) rsltObject;
0588: } catch (MBeanException mbe) {
0589: DeploymentException de = (DeploymentException) mbe
0590: .getTargetException();
0591: String exMessage = de.getMessage();
0592: Document doc = db.parse(new InputSource(
0593: new StringReader(exMessage)));
0594: elem = DOMUtil.UTIL.getElement(doc,
0595: "component-task-result");
0596: throw de;
0597:
0598: }
0599: } catch (Exception e) {
0600: String errMsg = mTranslator.getString(
0601: LocalStringKeys.DS_CANNOT_GET_SERVICE_UNIT_LIST,
0602: componentName);
0603: String jbiTask = appendCmpExToFrmwkEx(
0604: "getDeployedServiceUnitList", e, errMsg, elem);
0605: throw new Exception(jbiTask);
0606: }
0607:
0608: return suNameList;
0609: }
0610:
0611: /**
0612: * Get the status of deployed service unit.
0613: * @param componentName The name of the component.
0614: * @param serviceUnitName name of the service unit.
0615: * @return A boolean value indicating whether the
0616: * service unit is deployed or not.
0617: * @throws Exception If component throws an exception
0618: */
0619: public boolean isDeployedServiceUnit(String componentName,
0620: String serviceUnitName) throws Exception {
0621: return getServiceUnitInfo(componentName, serviceUnitName) != null;
0622: }
0623:
0624: /**
0625: * Get framework information on a service unit.
0626: * @param compName The ID of the component.
0627: * @param suName The ID of the service unit.
0628: * @return ServiceUnitInfo service unit information.
0629: */
0630: public ServiceUnitInfo getServiceUnitInfo(String compName,
0631: String suName) {
0632: ComponentInfo cInfo;
0633: ServiceUnitInfo suInfo = null;
0634: List suList;
0635:
0636: cInfo = getComponentQuery().getComponentInfo(compName);
0637:
0638: if (cInfo != null) {
0639: suList = cInfo.getServiceUnitList();
0640: for (int i = 0; i < suList.size(); i++) {
0641: ServiceUnitInfo info = (ServiceUnitInfo) suList.get(i);
0642:
0643: if (info.getName().equals(suName)) {
0644: suInfo = info;
0645: break;
0646: }
0647: }
0648: }
0649:
0650: return suInfo;
0651: }
0652:
0653: private String appendCmpExToFrmwkEx(String methodName,
0654: Throwable ex, String errMsg, Element elem) {
0655: String jbiTask = null;
0656: String token = null;
0657:
0658: // FiX ME : STRIP ID FROM MSG and POPULATE TOKEN
0659:
0660: try {
0661: ManagementMessageHolder mmHolder = new ManagementMessageHolder(
0662: "EXCEPTION_MSG");
0663: mmHolder.setTaskName(methodName);
0664: mmHolder.setTaskResult("FAILED");
0665: mmHolder.setExceptionObject(ex);
0666: mmHolder.setLocToken(1, token);
0667: mmHolder.setLocMessage(1, errMsg);
0668: String jbiTaskStr = mMImpl
0669: .buildCompleteExceptionMessage(mmHolder);
0670:
0671: DocumentBuilderFactory dbf = DocumentBuilderFactory
0672: .newInstance();
0673: DocumentBuilder db = dbf.newDocumentBuilder();
0674: Document doc = db.parse(new InputSource(new StringReader(
0675: jbiTaskStr)));
0676: Element jbiTaskElem = DOMUtil.UTIL.getElement(doc,
0677: "jbi-task-result");
0678: Element impElem = (Element) doc.importNode(elem, true);
0679: jbiTaskElem.appendChild(impElem);
0680: StringWriter sw = new StringWriter();
0681: jbiTask = DOMUtil.UTIL.DOM2String(doc, sw);
0682: } catch (Exception e) {
0683: String statusMsg = mTranslator.getString(
0684: LocalStringKeys.DS_DEPLOY_NO_EXCEPTION_MSG,
0685: methodName);
0686: mLogger.warning(statusMsg);
0687: }
0688:
0689: return jbiTask;
0690:
0691: }
0692:
0693: private String buildFrmwkExMsg(String methodName, Throwable ex,
0694: String errMsg) {
0695: String jbiTaskStr = null;
0696:
0697: try {
0698: ManagementMessageHolder mmHolder = new ManagementMessageHolder(
0699: "EXCEPTION_MSG");
0700: mmHolder.setTaskName(methodName);
0701: mmHolder.setTaskResult("FAILED");
0702: String token = MessageBuilder.getMessageToken(errMsg);
0703: mmHolder.setLocToken(1, token);
0704: String msg = MessageBuilder.getMessageString(errMsg);
0705: mmHolder.setLocMessage(1, msg);
0706: if (ex != null) {
0707: mmHolder.setExceptionObject(ex);
0708: }
0709: mmHolder.setFrameworkLocale("en_US");
0710:
0711: jbiTaskStr = mMImpl.buildCompleteExceptionMessage(mmHolder);
0712:
0713: } catch (Exception e) {
0714: String statusMsg = mTranslator.getString(
0715: LocalStringKeys.DS_DEPLOY_NO_EXCEPTION_MSG,
0716: methodName);
0717: mLogger.warning(statusMsg);
0718:
0719: }
0720:
0721: return jbiTaskStr;
0722: }
0723:
0724: /**
0725: * Get the status to see if SU can be deployed based on component state.
0726: * @param componentName The name of the component.
0727: * @return A boolean value indicating whether the
0728: * service unit can be deployed or not.
0729: */
0730: public boolean canDeployToComponent(String componentName) {
0731: ComponentState cmpStatus;
0732: boolean canDeploy = false;
0733:
0734: try {
0735: cmpStatus = getComponentState(componentName);
0736: if (cmpStatus == ComponentState.STARTED) {
0737: canDeploy = true;
0738: }
0739: } catch (Exception e) {
0740: e.printStackTrace();
0741: }
0742:
0743: return canDeploy;
0744:
0745: }
0746:
0747: /**
0748: * Get the XML string indicating service unit deploy/undeploy status.
0749: * @param cmpStatus HashMap containing various elements from components.
0750: * @param rslt Overall result of deployment.
0751: * @param isDeployment Value indicating whether it's deployment or not.
0752: * @return A boolean value indicating whether the
0753: * Application sub-assembly unit is deployed or not.
0754: * @throws Exception If fails to build response string
0755: */
0756: private String buildResponse(List cmpTaskRslts, boolean rslt,
0757: String methodName, String saName) throws Exception {
0758:
0759: String respDoc = null;
0760: Document doc = null;
0761: Element rootElem = null;
0762: Element respElem = null;
0763: String taskRslt = null;
0764:
0765: try {
0766:
0767: String threadId = Thread.currentThread().getName();
0768: DocumentBuilderFactory dbf = DocumentBuilderFactory
0769: .newInstance();
0770: DocumentBuilder db = dbf.newDocumentBuilder();
0771: doc = db.newDocument();
0772: rootElem = doc.createElement("jbi-task");
0773: rootElem.setAttribute("version", "1.0");
0774: rootElem
0775: .setAttribute("xmlns",
0776: "http://java.sun.com/xml/ns/jbi/management-message");
0777: rootElem.setAttribute("xmlns:xsi",
0778: "http://www.w3.org/2001/XMLSchema-instance");
0779: rootElem
0780: .setAttribute("xsi:schemaLocation",
0781: "http://java.sun.com/xml/ns/jbi/management-message ./managementMessage.xsd");
0782: if (rslt) {
0783: taskRslt = "SUCCESS";
0784: } else {
0785: taskRslt = "FAILED";
0786: }
0787:
0788: ManagementMessageHolder mmHolder = new ManagementMessageHolder(
0789: "STATUS_MSG");
0790:
0791: mmHolder.setTaskName(methodName);
0792: mmHolder.setTaskResult(taskRslt);
0793: mmHolder.setFrameworkLocale("en_US");
0794:
0795: respElem = mMImpl.buildFrameworkTaskStatusMessage(doc,
0796: mmHolder);
0797:
0798: doc.appendChild(rootElem);
0799: rootElem.appendChild(respElem);
0800:
0801: Iterator iter = cmpTaskRslts.iterator();
0802:
0803: while (iter.hasNext()) {
0804: Element importedNode = (Element) iter.next();
0805: Element elem = (Element) doc.importNode(importedNode,
0806: true);
0807: respElem.appendChild(elem);
0808: }
0809:
0810: // -- Add a task status msg if deploy is a success / partial success
0811: if (rslt
0812: && (methodName.equalsIgnoreCase("deploy") || methodName
0813: .equalsIgnoreCase("start"))) {
0814: addTaskStatusMsg(doc, saName,
0815: isPartialSuccess(cmpTaskRslts), methodName);
0816: }
0817:
0818: StringWriter sw = new StringWriter();
0819: respDoc = DOMUtil.UTIL.DOM2String(doc, sw);
0820: } catch (Exception e) {
0821: e.printStackTrace();
0822: throw new DeploymentException(
0823: "UNABLE_TO_CREATE_DEPLOY_RESPONSE", e);
0824: }
0825:
0826: return respDoc;
0827: }
0828:
0829: private void addTaskStatusMsg(Document doc, String saName,
0830: boolean isPartialSuccess, String opName) throws Exception {
0831: // no need for a start succeeded message in case of complete success, since this is redundant.
0832: if (!isPartialSuccess && "start".equals(opName)) {
0833: return;
0834: }
0835:
0836: try {
0837: Element jbiTaskElem = DOMUtil.UTIL.getElement(doc,
0838: "jbi-task");
0839: Element jbiTaskRsltElem = DOMUtil.UTIL.getElement(
0840: jbiTaskElem, "jbi-task-result");
0841: Element frmwkTaskRsltElem = DOMUtil.UTIL.getElement(
0842: jbiTaskRsltElem, "frmwk-task-result");
0843: Element frmwkTaskRsltDtlsElem = DOMUtil.UTIL.getElement(
0844: frmwkTaskRsltElem, "frmwk-task-result-details");
0845: Element taskRsltDtlsElem = DOMUtil.UTIL.getElement(
0846: frmwkTaskRsltDtlsElem, "task-result-details");
0847: Element msgTypeElem = doc.createElement("message-type");
0848: Element taskStatMsgElem = doc
0849: .createElement("task-status-msg");
0850: Element msgLocInfoElem = doc.createElement("msg-loc-info");
0851: Element locTokenElem = doc.createElement("loc-token");
0852: Element locMsgElem = doc.createElement("loc-message");
0853: String infoMsg = null;
0854: if (isPartialSuccess) {
0855: DOMUtil.UTIL.setTextData(msgTypeElem, "WARNING");
0856: if ("deploy".equalsIgnoreCase(opName)) {
0857: infoMsg = mTranslator
0858: .getString(
0859: LocalStringKeys.DS_DEPLOY_SCSS_WITH_WRNING_MSG,
0860: saName);
0861: } else if ("start".equalsIgnoreCase(opName)) {
0862: infoMsg = mTranslator
0863: .getString(
0864: LocalStringKeys.DS_START_SCSS_WITH_WRNING_MSG,
0865: saName);
0866: }
0867: } else {
0868: if ("deploy".equalsIgnoreCase(opName)) {
0869: DOMUtil.UTIL.setTextData(msgTypeElem, "INFO");
0870: infoMsg = mTranslator.getString(
0871: LocalStringKeys.DS_DEPLOY_SCSS_INFO_MSG,
0872: saName);
0873: }
0874: }
0875: taskRsltDtlsElem.appendChild(msgTypeElem);
0876: String token = MessageBuilder.getMessageToken(infoMsg);
0877: String msg = MessageBuilder.getMessageString(infoMsg);
0878: DOMUtil.UTIL.setTextData(locTokenElem, token);
0879: DOMUtil.UTIL.setTextData(locMsgElem, msg);
0880: msgLocInfoElem.appendChild(locTokenElem);
0881: msgLocInfoElem.appendChild(locMsgElem);
0882: taskStatMsgElem.appendChild(msgLocInfoElem);
0883: taskRsltDtlsElem.appendChild(taskStatMsgElem);
0884:
0885: } catch (Exception e) {
0886: throw e;
0887: }
0888: }
0889:
0890: /** returns the ObjectName for the lifecycle Mbean of this component.
0891: * @param aCompName id of a binding or engine component
0892: * @return the ObjectName for the lifecycle Mbean.
0893: * @throws Exception If failed to lookup object name
0894: */
0895: public ObjectName getLifeCycleMBeanObjectName(String aCompName)
0896: throws Exception {
0897: try {
0898: MBeanNames mbn = sMContext.getMBeanNames();
0899: ObjectName adminName = mbn.getSystemServiceMBeanName(
0900: "AdminService", mbn.CONTROL_TYPE_ADMIN_SERVICE);
0901: MBeanServerConnection mbeanServer = getMBeanServerConnection();
0902: Object[] params = new Object[1];
0903: params[0] = aCompName;
0904: String[] sig = new String[1];
0905: sig[0] = "java.lang.String";
0906: Object rsltObject = mbeanServer.invoke(adminName,
0907: "getComponentByName", params, sig);
0908: return (ObjectName) rsltObject;
0909: } catch (Exception e) {
0910: String errMsg = mTranslator
0911: .getString(
0912: LocalStringKeys.DS_UNABLE_TO_FIND_LIFECYCLE_MBEAN_OBJECT_NAME,
0913: aCompName);
0914: String jbiTaskStr = buildFrmwkExMsg(
0915: "getLifeCycleMBeanObjectName", e, errMsg);
0916: throw new Exception(jbiTaskStr);
0917: }
0918: }
0919:
0920: /**
0921: * Returns a list of Service Assemblies deployed to the JBI enviroment.
0922: * @return list of Service Assembly names
0923: * @throws Exception If failed to retrieve SA Ids
0924: */
0925: public String[] getDeployedServiceAssemblies() throws Exception {
0926: try {
0927: ServiceAssemblyQuery saQuery = getRegistry()
0928: .getServiceAssemblyQuery();
0929: List<String> saNamesList = saQuery.getServiceAssemblies();
0930: String[] saNames = new String[saNamesList.size()];
0931: saNamesList.toArray(saNames);
0932: return saNames;
0933: } catch (Exception e) {
0934: String errMsg = mTranslator
0935: .getString(LocalStringKeys.DS_UNABLE_TO_FIND_DEPLOYED_SERVICE_ASSEMBLY_NAMES);
0936: String jbiTaskStr = buildFrmwkExMsg(
0937: "getDeployedServiceAssemblies", e, errMsg);
0938: throw new Exception(jbiTaskStr);
0939: }
0940: }
0941:
0942: /**
0943: * Returns a list of Service Assemblies that contain SUs
0944: * for the given component.
0945: * @param componentName Name of the component
0946: * @return list of Service Assembly names
0947: * @throws Exception If fails to retrieve SA Ids
0948: */
0949: public String[] getDeployedServiceAssembliesForComponent(
0950: String componentName) throws Exception {
0951: List saNameList = new ArrayList();
0952: // -- VBD : int k = 0;
0953:
0954: try {
0955: String[] deployedSANameArray = getDeployedServiceAssemblies();
0956: for (int i = 0; i < deployedSANameArray.length; i++) {
0957: String[] compNameArr = getComponentsForDeployedServiceAssembly(deployedSANameArray[i]);
0958: for (int j = 0; j < compNameArr.length; j++) {
0959: if (compNameArr[j].equalsIgnoreCase(componentName)) {
0960: saNameList.add(deployedSANameArray[i]);
0961: }
0962: }
0963: }
0964:
0965: /** Verify Before Delete (VBD)
0966: * if (k == 0)
0967: * {
0968: * String errMsg = mTranslator.getString(
0969: * LocalStringKeys.DS_UNABLE_TO_GET_SERVICE_ASSEMBLY_NAMES_FOR_COMPONENT,
0970: * componentName);
0971: * throw new DeploymentException (errMsg);
0972: * }
0973: */
0974:
0975: } catch (DeploymentException de) {
0976: throw new Exception(de.getMessage());
0977: } catch (Exception e) {
0978: String errMsg = mTranslator
0979: .getString(
0980: LocalStringKeys.DS_UNABLE_TO_GET_SERVICE_ASSEMBLY_NAMES_FOR_COMPONENT,
0981: componentName);
0982: String jbiTaskStr = buildFrmwkExMsg(
0983: "getDeployedServiceAssembliesForComponent", e,
0984: errMsg);
0985: throw new Exception(jbiTaskStr);
0986: }
0987:
0988: String[] saNameArray = new String[saNameList.size()];
0989: saNameList.toArray(saNameArray);
0990: return saNameArray;
0991: }
0992:
0993: /**
0994: * Returns a list of components(to which SUs are targeted for)
0995: * in a Service Assembly.
0996: * @param saName name of the Service Assembly
0997: * @return list of component names
0998: * @throws Exception If fails to retrieve component Ids
0999: */
1000: public String[] getComponentsForDeployedServiceAssembly(
1001: String saName) throws Exception {
1002: try {
1003: List compNameList = new ArrayList();
1004: ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName,
1005: "domain");
1006: List<ServiceUnitInfo> suList = saInfo.getServiceUnitList();
1007: for (ServiceUnitInfo su : suList) {
1008: compNameList.add(su.getTargetComponent());
1009: }
1010: String[] compNameArray = new String[compNameList.size()];
1011: compNameList.toArray(compNameArray);
1012: return compNameArray;
1013: } catch (DeploymentException de) {
1014: de.printStackTrace();
1015: throw new Exception(de.getMessage());
1016: } catch (Exception e) {
1017: String errMsg = mTranslator
1018: .getString(
1019: LocalStringKeys.DS_UNABLE_TO_FIND_COMPONENT_NAMES_FOR_SA,
1020: saName);
1021: String jbiTaskStr = buildFrmwkExMsg(
1022: "getComponentsForDeployedServiceAssembly", e,
1023: errMsg);
1024: throw new Exception(jbiTaskStr);
1025: }
1026: }
1027:
1028: /**
1029: * Returns the descriptor of Service Assembly (SA) deployed.
1030: * @param saName name of the service assembly
1031: * @return descriptor of Service Assembly (SA)
1032: * @throws Exception If fails to retrieve deployment descriptor
1033: */
1034: public String getServiceAssemblyDescriptor(String saName)
1035: throws Exception {
1036: String jbiXmlString = null;
1037: try {
1038: jbiXmlString = getRegistry().getGenericQuery()
1039: .getServiceAssemblyDeploymentDescriptor(saName);
1040: return jbiXmlString;
1041: } catch (Exception e) {
1042: e.printStackTrace();
1043: String errMsg = mTranslator.getString(
1044: LocalStringKeys.DS_SA_DESCRIPTOR_NOT_FOUND, saName);
1045: String jbiTaskStr = buildFrmwkExMsg(
1046: "getServiceAssemblyDescriptor", e, errMsg);
1047: throw new Exception(jbiTaskStr);
1048: }
1049:
1050: }
1051:
1052: /**
1053: * Returns the descriptor of Service Unit(SU) deployed.
1054: * @param saName name of the service assembly
1055: * @param saName name of the service unit
1056: * @return descriptor of Service Unit(SU)
1057: * @throws Exception If fails to retrieve deployment descriptor
1058: */
1059: public String getServiceUnitDescriptor(String saName, String suName)
1060: throws UnsupportedOperationException {
1061: /* This operation is not implemented since the facade DeploymentService
1062: * gets the service unit descriptor from the service assembly archive on
1063: * the DAS directly.
1064: */
1065: throw new UnsupportedOperationException();
1066: }
1067:
1068: /**
1069: * Get the actual state of the component from the ComponentLifeCycleMBean.
1070: * @param compName The ID of the component.
1071: * @return the component state, if the component is not installed a value of
1072: * ComponentState.UNKNOWN is returned.
1073: */
1074: public ComponentState getComponentState(String compName) {
1075: ObjectName compLCName = getComponentLifeCycleMBeanName(compName);
1076: ComponentState cmpStatus = ComponentState.UNKNOWN;
1077:
1078: if (compLCName != null) {
1079: MBeanServer mbnServer = sMContext.getMBeanServer();
1080:
1081: try {
1082: String state = (String) mbnServer.getAttribute(
1083: compLCName, "CurrentState");
1084:
1085: cmpStatus = ComponentState.valueOfLifeCycleState(state);
1086: } catch (javax.management.JMException infex) {
1087: mLogger.warning(infex.toString());
1088: }
1089: }
1090: return cmpStatus;
1091: }
1092:
1093: /**
1094: * Get the actual state of a service unit.
1095: * @param compName The ID of the component.
1096: * @param suName The ID of the service unit.
1097: * @return int value indicating the service unit state.
1098: */
1099: public ServiceUnitState getActualServiceUnitState(String compName,
1100: String suName) {
1101: ServiceUnitState suState = ServiceUnitState.UNKNOWN;
1102:
1103: ComponentState compState = getComponentState(compName);
1104:
1105: // If the component is shutdown, the service unit is in the shutdown state.
1106: if (compState == ComponentState.SHUTDOWN) {
1107: suState = ServiceUnitState.SHUTDOWN;
1108: } else if (compState != ComponentState.UNKNOWN) {
1109: DeployerMBean deployer = getComponentDeployerInstance(compName);
1110:
1111: if (deployer != null) {
1112: suState = deployer.getServiceUnitState(suName);
1113: }
1114: }
1115: return suState;
1116: }
1117:
1118: /**
1119: * Builds a component-task-result XML fragment from the exception.
1120: * @param taskName - task id
1121: * @param compId - component id
1122: * @param e - source Exception to build the component task result from
1123: * @return the component-task-result DOM element.
1124: */
1125: private Element buildComponentExMsg(String taskName, String compId,
1126: Exception e) {
1127: Element elem = null;
1128: StringBuffer sb = new StringBuffer("");
1129: StackTraceElement[] stckTrElem = e.getStackTrace();
1130: if (stckTrElem != null) {
1131: for (int i = 0; i < stckTrElem.length; i++) {
1132: String stckTrace = stckTrElem[i].toString();
1133: sb.append(stckTrace);
1134: sb.append("\n");
1135: }
1136:
1137: }
1138:
1139: String[] msgParams = new String[1];
1140: msgParams[0] = "";
1141: ComponentMessageHolder cmpParams = new ComponentMessageHolder(
1142: "EXCEPTION_MSG");
1143: cmpParams.setComponentName(compId);
1144: cmpParams.setTaskName(taskName);
1145: cmpParams.setTaskResult("FAILED");
1146: String errMsg = e.getMessage();
1147: if (errMsg.startsWith("JBI")) {
1148: cmpParams.setLocToken(1, MessageBuilder
1149: .getMessageToken(errMsg));
1150: String msg = MessageBuilder.getMessageString(errMsg);
1151: cmpParams.setLocMessage(1, msg);
1152: } else {
1153: cmpParams.setLocToken(1, "");
1154: cmpParams.setLocMessage(1, e.getMessage());
1155: }
1156: cmpParams.setLocParam(1, msgParams);
1157: cmpParams.setExceptionObject(e);
1158: cmpParams.setExceptionMessageType("ERROR");
1159:
1160: String cmpMsg = null;
1161: try {
1162: cmpMsg = mMImpl
1163: .buildComponentTaskExceptionMessage(cmpParams);
1164: DocumentBuilderFactory dbf = DocumentBuilderFactory
1165: .newInstance();
1166: DocumentBuilder db = dbf.newDocumentBuilder();
1167: Document doc = db.parse(new InputSource(new StringReader(
1168: cmpMsg)));
1169: elem = DOMUtil.UTIL
1170: .getElement(doc, "component-task-result");
1171: } catch (Exception cmpe) {
1172: cmpe.printStackTrace();
1173: String statusMsg = mTranslator
1174: .getString(LocalStringKeys.DS_DEPLOY_NO_EXCEPTION_MSG);
1175: mLogger.warning(statusMsg);
1176: }
1177:
1178: return elem;
1179:
1180: }
1181:
1182: public String registerServiceUnit(String compName, String saName,
1183: String suName, String suRootPath) throws Exception {
1184: String rgstrTaskStr = "SUCCESS";
1185:
1186: try {
1187: ServiceUnitRegistration suRegistration = sMContext
1188: .getServiceUnitRegistration();
1189: suRegistration.registerServiceUnit(compName, saName,
1190: suName, suRootPath);
1191:
1192: } catch (Throwable t) {
1193: t.printStackTrace();
1194: ComponentMessageHolder cmpMsgHolder = new ComponentMessageHolder(
1195: "STATUS_MSG");
1196: cmpMsgHolder.setComponentName(compName);
1197: cmpMsgHolder.setTaskName("deploy");
1198: cmpMsgHolder.setTaskResult("SUCCESS");
1199: cmpMsgHolder.setStatusMessageType("WARNING");
1200: String errMsg = mTranslator.getString(
1201: LocalStringKeys.DS_REGISTER_SERVICE_UNIT_FAILED,
1202: suName);
1203: String token = MessageBuilder.getMessageToken(errMsg);
1204: cmpMsgHolder.setLocToken(1, token);
1205: String msg = MessageBuilder.getMessageString(errMsg);
1206: cmpMsgHolder.setLocMessage(1, msg);
1207:
1208: try {
1209: rgstrTaskStr = mMImpl
1210: .buildComponentMessage(cmpMsgHolder);
1211: } catch (Exception e) {
1212: throw e;
1213: }
1214: }
1215:
1216: return rgstrTaskStr;
1217:
1218: }
1219:
1220: /**
1221: * @param compName - target component for service unit unregistration
1222: * @param suName - name of service unit to unregister
1223: */
1224: public String unregisterServiceUnit(String compName, String suName)
1225: throws Exception {
1226: String unrgstrTaskStr = "SUCCESS";
1227:
1228: try {
1229: ServiceUnitRegistration suRegistration = sMContext
1230: .getServiceUnitRegistration();
1231: suRegistration.unregisterServiceUnit(compName, suName);
1232:
1233: } catch (Throwable t) {
1234: t.printStackTrace();
1235: ComponentMessageHolder cmpMsgHolder = new ComponentMessageHolder(
1236: "STATUS_MSG");
1237: cmpMsgHolder.setComponentName((String) compName);
1238: cmpMsgHolder.setTaskName("deploy");
1239: cmpMsgHolder.setTaskResult("SUCCESS");
1240: cmpMsgHolder.setStatusMessageType("WARNING");
1241: String errMsg = mTranslator.getString(
1242: LocalStringKeys.DS_UNREGISTER_SERVICE_UNIT_FAILED,
1243: suName);
1244: String token = MessageBuilder.getMessageToken(errMsg);
1245: cmpMsgHolder.setLocToken(1, token);
1246: String msg = MessageBuilder.getMessageString(errMsg);
1247: cmpMsgHolder.setLocMessage(1, msg);
1248:
1249: try {
1250: unrgstrTaskStr = mMImpl
1251: .buildComponentMessage(cmpMsgHolder);
1252: } catch (Exception e) {
1253: throw e;
1254: }
1255: }
1256:
1257: return unrgstrTaskStr;
1258:
1259: }
1260:
1261: /**
1262: * Shut down the DeploymentService.
1263: * @exception javax.jbi.JBIException if the item fails to shut down.
1264: */
1265: public void shutDown() throws javax.jbi.JBIException {
1266: super .shutDown();
1267: }
1268:
1269: private boolean checkSUTaskRsltStatus(String suDeployRslt)
1270: throws Exception {
1271: boolean taskRslt = false;
1272:
1273: try {
1274: DocumentBuilderFactory dbf = DocumentBuilderFactory
1275: .newInstance();
1276: DocumentBuilder db = dbf.newDocumentBuilder();
1277: Document doc = db.parse(new InputSource(new StringReader(
1278: suDeployRslt)));
1279: Element compTaskRsltElem = DOMUtil.UTIL.getElement(doc,
1280: "component-task-result");
1281: Element cmpTaskRsltDtlsElem = DOMUtil.UTIL.getElement(
1282: compTaskRsltElem, "component-task-result-details");
1283: Element taskRsltDtlsElem = DOMUtil.UTIL.getElement(
1284: cmpTaskRsltDtlsElem, "task-result-details");
1285: Element rsltElem = DOMUtil.UTIL.getElement(
1286: taskRsltDtlsElem, "task-result");
1287: String dplyRslt = DOMUtil.UTIL.getTextData(rsltElem);
1288: if (dplyRslt.equalsIgnoreCase("SUCCESS"))
1289: taskRslt = true;
1290: else
1291: taskRslt = false;
1292: } catch (Exception e) {
1293: throw e;
1294: }
1295:
1296: return taskRslt;
1297:
1298: }
1299:
1300: private String appendWarningToCmpRslt(String suRgstrnRslt,
1301: String suDplyRslt) throws Exception {
1302: String cmpTaskRsltStr = null;
1303:
1304: try {
1305: DocumentBuilderFactory dbf = DocumentBuilderFactory
1306: .newInstance();
1307: DocumentBuilder db = dbf.newDocumentBuilder();
1308: Document doc = db.parse(new InputSource(new StringReader(
1309: suDplyRslt)));
1310: Element compTaskRsltElem = DOMUtil.UTIL.getElement(doc,
1311: "component-task-result");
1312: Element cmpTaskRsltDtlsElem = DOMUtil.UTIL.getElement(
1313: compTaskRsltElem, "component-task-result-details");
1314: Element taskRsltDtlsElem = DOMUtil.UTIL.getElement(
1315: cmpTaskRsltDtlsElem, "task-result-details");
1316: Element mtElem = DOMUtil.UTIL.getElement(taskRsltDtlsElem,
1317: "message-type");
1318: Element msgTypeElem = null;
1319: if (mtElem == null) {
1320: msgTypeElem = doc.createElement("message-type");
1321: DOMUtil.UTIL.setTextData(msgTypeElem, "WARNING");
1322: taskRsltDtlsElem.appendChild(msgTypeElem);
1323: }
1324:
1325: Document suRgstrnDoc = db.parse(new InputSource(
1326: new StringReader(suRgstrnRslt)));
1327: Element rgstrnCmpTaskRsltElem = DOMUtil.UTIL.getElement(
1328: suRgstrnDoc, "component-task-result");
1329: Element rgstrnCmpTaskRsltDtlsElem = DOMUtil.UTIL
1330: .getElement(rgstrnCmpTaskRsltElem,
1331: "component-task-result-details");
1332: Element rgstrnTaskRsltDtlsElem = DOMUtil.UTIL.getElement(
1333: rgstrnCmpTaskRsltDtlsElem, "task-result-details");
1334: Element statusMsgElem = DOMUtil.UTIL.getElement(
1335: rgstrnTaskRsltDtlsElem, "task-status-msg");
1336: Element impElem = (Element) doc.importNode(statusMsgElem,
1337: true);
1338: taskRsltDtlsElem.appendChild(impElem);
1339:
1340: StringWriter sw = new StringWriter();
1341: cmpTaskRsltStr = DOMUtil.UTIL.DOM2String(doc, sw);
1342: } catch (Exception e) {
1343: throw e;
1344: }
1345:
1346: return cmpTaskRsltStr;
1347: }
1348:
1349: private String buildComponentStatusMsg(String compName,
1350: String methodName, String suName) {
1351: String compStatusMsg = null;
1352:
1353: ComponentMessageHolder cmpMsgHolder = new ComponentMessageHolder(
1354: "STATUS_MSG");
1355: cmpMsgHolder.setComponentName(compName);
1356: cmpMsgHolder.setTaskName(methodName);
1357: cmpMsgHolder.setTaskResult("SUCCESS");
1358:
1359: String locMsg = mTranslator.getString(
1360: LocalStringKeys.DS_SU_LIFECYCLE_OP_SUCCESS, methodName,
1361: suName);
1362: cmpMsgHolder.setStatusMessageType("INFO");
1363: cmpMsgHolder.setLocToken(1, MessageBuilder
1364: .getMessageToken(locMsg));
1365: cmpMsgHolder.setLocMessage(1, MessageBuilder
1366: .getMessageString(locMsg));
1367: cmpMsgHolder
1368: .setLocParam(1, new String[] { methodName, suName });
1369:
1370: try {
1371: compStatusMsg = mMImpl.buildComponentMessage(cmpMsgHolder);
1372: } catch (Exception exObj) {
1373: String statusMsg = mTranslator
1374: .getString(LocalStringKeys.DS_DEPLOY_NO_EXCEPTION_MSG);
1375: mLogger.warning(statusMsg);
1376: }
1377:
1378: return compStatusMsg;
1379: }
1380:
1381: /**
1382: * This method is used to build a component task result status
1383: * message with SUCCESS as the status and with the given information
1384: * string
1385: * @param compName the component name
1386: * @param methodName the task id
1387: * @param suName the service unit name
1388: * @param info the string that should go in the message
1389: */
1390: private String buildComponentStatusMsg(String compName,
1391: String methodName, String suName, String info) {
1392: String compStatusMsg = null;
1393:
1394: ComponentMessageHolder cmpMsgHolder = new ComponentMessageHolder(
1395: "STATUS_MSG");
1396: cmpMsgHolder.setComponentName(compName);
1397: cmpMsgHolder.setTaskName(methodName);
1398: cmpMsgHolder.setTaskResult("SUCCESS");
1399:
1400: cmpMsgHolder.setStatusMessageType("INFO");
1401: cmpMsgHolder.setLocToken(1, MessageBuilder
1402: .getMessageToken(info));
1403: cmpMsgHolder.setLocMessage(1, MessageBuilder
1404: .getMessageString(info));
1405: cmpMsgHolder
1406: .setLocParam(1, new String[] { methodName, suName });
1407:
1408: try {
1409: compStatusMsg = mMImpl.buildComponentMessage(cmpMsgHolder);
1410: } catch (Exception exObj) {
1411: String statusMsg = mTranslator
1412: .getString(LocalStringKeys.DS_DEPLOY_NO_EXCEPTION_MSG);
1413: mLogger.warning(statusMsg);
1414: }
1415:
1416: return compStatusMsg;
1417: }
1418:
1419: /**
1420: * Get the MBean Server
1421: *
1422: * @return thge MBean Server reference.
1423: */
1424: public MBeanServerConnection getMBeanServerConnection() {
1425: return sMContext.getCentralMBeanServer();
1426: }
1427:
1428: /**
1429: * Starts the service assembly and puts it in
1430: * STARTED state.
1431: * @param serviceAssemblyName - name of the service
1432: * assembly.
1433: * @return Result/Status of this operation.
1434: * @throws Exception if operation fails.
1435: *
1436: */
1437: public String start(String serviceAssemblyName) throws Exception {
1438: HashMap infoMsgElems = null;
1439: String saState = getState(serviceAssemblyName);
1440:
1441: if (!saState.equalsIgnoreCase(DeploymentServiceMBean.STARTED)) {
1442: infoMsgElems = activateConnections(serviceAssemblyName);
1443: }
1444: // for start force = false
1445: String stateChangeRslt = startServiceAssembly(serviceAssemblyName);
1446: String jbiTaskStr = appendMsgsToTaskRslt(stateChangeRslt,
1447: infoMsgElems, "WARNING");
1448: return jbiTaskStr;
1449: }
1450:
1451: /**
1452: * Stops the service assembly and puts it in
1453: * STOPPED state.
1454: * @param serviceAssemblyName - name of the service
1455: * assembly.
1456: * @return Result/Status of this operation.
1457: * @throws Exception if operation fails.
1458: *
1459: */
1460: public String stop(String serviceAssemblyName) throws Exception {
1461: HashMap infoMsgElems = null;
1462: String saState = getState(serviceAssemblyName);
1463: boolean isStarted = false;
1464:
1465: if (saState.equalsIgnoreCase(DeploymentServiceMBean.STARTED)) {
1466: isStarted = true;
1467: } else if (saState
1468: .equalsIgnoreCase(DeploymentServiceMBean.SHUTDOWN)) {
1469: String errMsg = mTranslator
1470: .getString(
1471: LocalStringKeys.DS_CANNOT_STOP_SA_SHUTDOWN_SA_STATE,
1472: serviceAssemblyName, saState);
1473: String jbiExStr = buildFrmwkExMsg("stop", null, errMsg);
1474: throw new Exception(jbiExStr);
1475: }
1476:
1477: return stopServiceAssembly(serviceAssemblyName, isStarted);
1478: }
1479:
1480: /**
1481: * Shutdown the service assembly and puts it in
1482: * SHUTDOWN state.
1483: * @param serviceAssemblyName - name of the service
1484: * assembly.
1485: * @return Result/Status of this operation.
1486: * @throws Exception if operation fails.
1487: *
1488: */
1489: public String shutDown(String serviceAssemblyName) throws Exception {
1490: // default force = false
1491: return shutDown(serviceAssemblyName, false);
1492: }
1493:
1494: /* Returns the state of service assembly.
1495: *
1496: * @param serviceAssemblyName - name of the service assembly.
1497: * @return State of the service assembly.
1498: * @throws Exception if operation fails.
1499: *
1500: */
1501: public String getState(String serviceAssemblyName) throws Exception {
1502: String saState = null;
1503: try {
1504: ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(serviceAssemblyName);
1505:
1506: if (saInfo != null) {
1507: List<ServiceUnitState> suStates = new ArrayList<ServiceUnitState>();
1508:
1509: List<ServiceUnitInfo> suList = saInfo
1510: .getServiceUnitList();
1511: for (ServiceUnitInfo suInfo : suList) {
1512: String suName = suInfo.getName();
1513: String targetComponent = suInfo
1514: .getTargetComponent();
1515:
1516: ServiceUnitState suState = getActualServiceUnitState(
1517: targetComponent, suName);
1518: suStates.add(suState);
1519: }
1520:
1521: if (!suStates.isEmpty()) {
1522: ServiceAssemblyState state = ServiceAssemblyState
1523: .computeServiceAssemblyState(suStates);
1524:
1525: saState = ServiceAssemblyState.convertState(state);
1526: } else {
1527: // -- This could be a service assembly with zero service units
1528: // get the state from the service assembly element
1529: if (isServiceAssemblyEmpty(serviceAssemblyName)) {
1530: ServiceAssemblyState state = getServiceAssemblyInfo(
1531: serviceAssemblyName).getStatus();
1532: saState = ServiceAssemblyState
1533: .convertState(state);
1534: }
1535: }
1536: }
1537: } catch (Exception e) {
1538: if (!e.getMessage().startsWith("<?xml")) {
1539: String frmwkMsg = buildFrmwkExMsg("getState", e, e
1540: .getMessage());
1541: throw new Exception(frmwkMsg);
1542: } else {
1543: throw new Exception(e.getMessage());
1544: }
1545:
1546: }
1547:
1548: if (saState == null) {
1549: // -- Service Assembly is not deployed
1550: String[] params = new String[] { serviceAssemblyName };
1551: String errMsg = mTranslator.getString(
1552: LocalStringKeys.DS_CANNOT_GET_SA_STATE, params);
1553:
1554: MessageBuilder msgBuilder = new MessageBuilder(mTranslator);
1555: String mgtMsg = msgBuilder.buildFrameworkMessage(
1556: "getState", MessageBuilder.TaskResult.FAILED,
1557: MessageBuilder.MessageType.ERROR, msgBuilder
1558: .getMessageString(errMsg), params,
1559: msgBuilder.getMessageToken(errMsg));
1560:
1561: throw new Exception(mgtMsg);
1562: }
1563: mLogger.finest("Deployment service returning state " + saState
1564: + " for service assembly " + serviceAssemblyName);
1565:
1566: return saState;
1567: }
1568:
1569: /*---------------------------------------------------------------------------------*\
1570: * Extended DeploymentServiceMBean ops *
1571: \*---------------------------------------------------------------------------------*/
1572:
1573: /**
1574: * Get the state of a service unit deployed to a component.
1575: * </br>
1576: * If the service unit is deployed to the component then one of the states :
1577: * "Started", "Stopped" or "Shutdown" is returned.
1578: *
1579: * @return the actual state of the deployed service unit or "Unknown".
1580: * @param componentName - the component name
1581: * @param serviceUnitName - name of the service unit
1582: * @exception javax.jbi.JBIException if the component is not installed or if the
1583: * service unit is not deployed to the component.
1584: * @see javax.jbi.management.DeploymentServiceMBean
1585: */
1586: public String getServiceUnitState(String componentName,
1587: String serviceUnitName) throws javax.jbi.JBIException {
1588: ServiceUnitState suState = getActualServiceUnitState(
1589: componentName, serviceUnitName);
1590: return ServiceUnitState.convertState(suState);
1591: }
1592:
1593: /**
1594: * Deploy a Service Assembly from the Repository.
1595: * <br/>
1596: * This is a NOP.
1597: *
1598: * @param serviceAssemblyName - name of the registered service assembly.
1599: * @return a status management message with details on the service assembly deployment.
1600: * @exception javax.jbi.JBIException if the service assembly is not registered or
1601: * deploy fails.
1602: */
1603: public String deployFromRepository(String serviceAssemblyName)
1604: throws javax.jbi.JBIException {
1605: // nop
1606: return serviceAssemblyName;
1607: }
1608:
1609: /**
1610: * Undeploys the given Service Assembly from the JBI environment.
1611: *
1612: * @param serviceAssemblyName name of the Service Assembly that is to be
1613: * undeployed; must be non-null and non-empty
1614: * @param force if this flag is set to true any undeployment errors thrown
1615: * from the component will be ignored as the service assembly is forcefully
1616: * undeployed.
1617: * @return Result/Status of the current undeployment; must conform to
1618: * JBI management result/status XML schema; must be non-null and
1619: * non-empty
1620: * @exception Exception if compelete undeployment fails
1621: */
1622: public String undeploy(String serviceAssemblyName, boolean force)
1623: throws Exception {
1624: // default keep = false, actually keep is a don't care on the instance
1625: return undeploy(serviceAssemblyName, force, false);
1626: }
1627:
1628: /**
1629: * Undeploys the given Service Assembly from the JBI environment.
1630: *
1631: * @param saName name of the Service Assembly that is to be
1632: * undeployed; must be non-null and non-empty
1633: * @param force if this flag is set to true any undeployment errors thrown
1634: * from the component will be ignored as the service assembly is forcefully
1635: * undeployed.
1636: * @param keep if true the service assembly archive should not be removed
1637: * from the domain. If false the archive is removed if the service
1638: * assembly is not deployed on any instances. This flag is ignored on
1639: * the instance.
1640: * @return Result/Status of the current undeployment; must conform to
1641: * JBI management result/status XML schema; must be non-null and
1642: * non-empty
1643: * @exception Exception if compelete undeployment fails
1644: */
1645: public String undeploy(String saName, boolean force, boolean keep)
1646: throws Exception {
1647: String jbiXmlPath = null;
1648: String undplyRslt = null;
1649: Object[] params = null;
1650: List cmpTaskRslts = new ArrayList();
1651: boolean saUnDplyRslt = true;
1652: EventNotifierCommon notifier = sMContext
1653: .getEnvironmentContext().getNotifier();
1654:
1655: try {
1656: // Get information on the service assembly deployed to the instance.
1657: ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName);
1658:
1659: List<ServiceUnitInfo> suList = saInfo.getServiceUnitList();
1660: int numOfSUs = suList.size();
1661: int numOfSUsUndeployed = 0;
1662:
1663: for (ServiceUnitInfo su : suList) {
1664:
1665: String suName = su.getName();
1666: String compName = su.getTargetComponent();
1667: String suRootPath = su.getFilePath();
1668: ComponentState cmpState = ComponentState.UNKNOWN;
1669:
1670: DocumentBuilderFactory dbf = DocumentBuilderFactory
1671: .newInstance();
1672: DocumentBuilder db = dbf.newDocumentBuilder();
1673: try {
1674: // check to make sure SU has been deployed to component
1675: if (!isDeployedServiceUnit(compName, suName)) {
1676: mLogger
1677: .fine("Service unit "
1678: + suName
1679: + " has not been deployed to component "
1680: + compName
1681: + " -- skipping undeploy");
1682: numOfSUsUndeployed++;
1683: continue;
1684: }
1685:
1686: cmpState = getComponentState(compName);
1687: if (cmpState == ComponentState.UNKNOWN) {
1688: String errMsg = mTranslator
1689: .getString(
1690: LocalStringKeys.DS_CANNOT_UNDEPLOY_SERVICE_UNIT_COMP_NOT_INSTALLED,
1691: suName, compName);
1692: throw new Exception(errMsg);
1693: }
1694:
1695: /**
1696: * If the forced flag is set to true, a service assembly can be
1697: * undeployed even when the component is shutdown
1698: */
1699: if (cmpState == ComponentState.SHUTDOWN && !force) {
1700: String errMsg = mTranslator
1701: .getString(
1702: LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_IN_INCORRECT_STATE,
1703: suName, compName);
1704: throw new Exception(errMsg);
1705: }
1706: } catch (Exception e) {
1707: mLogger.warning(e.getMessage());
1708: Element elem = getComponentResultXmlFragment(
1709: compName, "undeploy", e);
1710: cmpTaskRslts.add(elem);
1711:
1712: // Stop processing and try to undeploy
1713: // the next SU in the SA.
1714: continue;
1715: }
1716:
1717: try {
1718: DeployerMBean deployer = getComponentDeployerInstance(compName);
1719:
1720: if (deployer != null) {
1721: undplyRslt = deployer.undeploy(suName,
1722: suRootPath, force);
1723: } else {
1724: String errMsg = mTranslator
1725: .getString(
1726: LocalStringKeys.DS_CANNOT_UNDEPLOY_SU_DEPLOYER_INSTANCE_NULL,
1727: suName, compName, cmpState);
1728: throw new Exception(errMsg);
1729: }
1730:
1731: String suUnRgstrnRslt = null;
1732: boolean isSUUnDplymntScss = checkSUTaskRsltStatus(undplyRslt);
1733: if (isSUUnDplymntScss) {
1734: // Emit a notification of the successful undeploy
1735: if (null != notifier) {
1736: notifier
1737: .emitServiceUnitNotification(
1738: EventNotifierCommon.EventType.Undeployed,
1739: suName, saName, compName,
1740: "");
1741: }
1742: /**
1743: * The force flag does not have to be propagated to the
1744: * unregisterServiceUnit method, since that only
1745: * (a) removes the service unit from the cached components
1746: * service unit list
1747: * (b) removes the service unit entry from the installed
1748: * component in the registry
1749: * Since both (a) and (b) do not interact with the
1750: * actual JBI Component, we do not need to propagate the force flag
1751: */
1752: suUnRgstrnRslt = unregisterServiceUnit(
1753: compName, suName);
1754: if (!suUnRgstrnRslt.equalsIgnoreCase("SUCCESS")) {
1755: undplyRslt = appendWarningToCmpRslt(
1756: suUnRgstrnRslt, undplyRslt);
1757: } else {
1758: // service unit undeployed and unregistered successfully
1759: numOfSUsUndeployed++;
1760: }
1761: }
1762:
1763: Document doc = db.parse(new InputSource(
1764: new StringReader(undplyRslt)));
1765: Element elem = DOMUtil.UTIL.getElement(doc,
1766: "component-task-result");
1767: cmpTaskRslts.add(elem);
1768: } catch (Exception e) {
1769: Element elem = getComponentResultXmlFragment(
1770: compName, "undeply", e);
1771: cmpTaskRslts.add(elem);
1772: }
1773:
1774: if (!mEnv.getPlatformContext().isAdminServer()) {
1775: try {
1776: DirectoryUtil.deleteDir((String) params[1]);
1777: } catch (Exception exObj) {
1778: File deleteMe = new File(suRootPath,
1779: PATH_TO_DELETE_ME_FILE);
1780: try {
1781: FileOutputStream fos = new FileOutputStream(
1782: deleteMe);
1783: fos.close();
1784: } catch (IOException ioe) {
1785: String errMsg = mTranslator
1786: .getString(
1787: LocalStringKeys.DS_DIRECTORY_NOT_MARKED,
1788: suRootPath, ioe
1789: .getMessage());
1790: mLogger.warning(errMsg);
1791: }
1792:
1793: String errMsg = mTranslator
1794: .getString(
1795: LocalStringKeys.DS_DIRECTORY_NOT_REMOVED,
1796: suRootPath);
1797: mLogger.warning(errMsg);
1798: moveToTrash(suRootPath);
1799:
1800: /*
1801: String errMsg = mTranslator.getString(
1802: LocalStringKeys.DS_CANNOT_DELETE_SU_ROOT_PATH,
1803: suRootPath, suName);
1804: mLogger.warning(errMsg); */
1805: }
1806: }
1807: }
1808:
1809: if (numOfSUsUndeployed < numOfSUs) {
1810: saUnDplyRslt = false;
1811: }
1812: } catch (DeploymentException de) {
1813: throw new Exception(de.getMessage());
1814: } catch (Exception e) {
1815: String errMsg = mTranslator
1816: .getString(
1817: LocalStringKeys.DS_CANNOT_UNDEPLOY_SERVICE_ASSEMBLY,
1818: saName);
1819: String jbiTaskStr = buildFrmwkExMsg("undeploy", e, errMsg);
1820: throw new Exception(jbiTaskStr);
1821: }
1822:
1823: if (saUnDplyRslt) {
1824: String mSAUnzipDir = null;
1825:
1826: if (!mEnv.getPlatformContext().isAdminServer()) {
1827: try {
1828: // -- Remove from the local registry / repository
1829: getRegistry().getRepository().removeArchive(
1830: ArchiveType.SERVICE_ASSEMBLY, saName);
1831: getRegistry().getUpdater().removeServiceAssembly(
1832: "domain", saName);
1833: } catch (JBIException jex) {
1834: mLogger.warning(jex.getMessage());
1835: }
1836: }
1837:
1838: }
1839:
1840: String resp = buildResponse(cmpTaskRslts, saUnDplyRslt,
1841: "undeploy", saName);
1842:
1843: if (saUnDplyRslt) {
1844: String statusMsg = mTranslator.getString(
1845: LocalStringKeys.DS_UNDEPLOYMENT_SUCCESS, saName);
1846: mLogger.info(statusMsg);
1847:
1848: // Emit a notification of the successful undeploy
1849: if (null != notifier) {
1850: notifier.emitServiceAssemblyNotification(
1851: EventNotifierCommon.EventType.Undeployed,
1852: saName, statusMsg);
1853: }
1854:
1855: try {
1856: // Remove the service assembly from this instance
1857: getRegistry().getUpdater()
1858: .removeServiceAssembly(saName);
1859: } catch (JBIException jbiex) {
1860: MessageBuilder msgBuilder = new MessageBuilder(
1861: mTranslator);
1862:
1863: throw new JBIException(msgBuilder
1864: .buildExceptionMessage("deploy", jbiex));
1865: }
1866:
1867: //remove the statistics object corresponding to this SA
1868: removeStatsObject(saName);
1869:
1870: return resp;
1871: } else {
1872: String statusMsg = mTranslator.getString(
1873: LocalStringKeys.DS_UNDEPLOYMENT_FAILURE, saName);
1874: mLogger.warning(statusMsg);
1875:
1876: //remove the statistics object corresponding to this SA
1877: removeStatsObject(saName);
1878:
1879: // undeployment failure requires an exception to be thrown
1880: throw new Exception(resp);
1881: }
1882:
1883: }
1884:
1885: /**
1886: * Shut down the service assembly.
1887: *
1888: * @param serviceAssemblyName name of the assembly to be shut down; must be
1889: * non-null and non-empty
1890: * @param force if this flag is true, the service assembly is shutdown forcefully.
1891: * Any exceptions thrown by the component for service unit shutdown are ignored.
1892: * @return result / status string giving the results of shutting down
1893: * each service unit in the assembly; must be non-null and non-empty
1894: * @exception Exception if there is no such assembly
1895: * @exception Exception if the assembly fails to shut down
1896: */
1897: public String shutDown(String serviceAssemblyName, boolean force)
1898: throws Exception {
1899:
1900: String saState = getState(serviceAssemblyName);
1901:
1902: if (saState.equalsIgnoreCase(DeploymentServiceMBean.STARTED)) {
1903: // Need to stop the SA before it is shutdown
1904: stopServiceAssembly(serviceAssemblyName, true);
1905: }
1906:
1907: return stopShutDownServiceAssembly("shutDown",
1908: serviceAssemblyName, force);
1909: }
1910:
1911: /*---------------------------------------------------------------------------------*\
1912: * Private Helpers *
1913: \*---------------------------------------------------------------------------------*/
1914:
1915: /** This method rolls back SU states to SHUTDOWN as a result of a
1916: * failed start operation. This prevents a situation where an SU is
1917: * not successfully started, but it remains in a STOPPED (e.g. init)
1918: * instead of the expected SHUTDWON state.
1919: */
1920: private void rollbackSUInits(List<ServiceUnitInfo> susToRollBack) {
1921: try {
1922: for (ServiceUnitInfo su : susToRollBack) {
1923: String suName = su.getName();
1924: try {
1925: DeployerMBean deployer = getComponentDeployerInstance(su
1926: .getTargetComponent());
1927: deployer.shutDown(suName);
1928: } catch (Exception e) {
1929: Element elem = getComponentResultXmlFragment(su
1930: .getTargetComponent(), "rollbackSUInits", e);
1931: Document doc = mMImpl.createDocument();
1932: doc.appendChild(elem);
1933: StringWriter sw = new StringWriter();
1934: String jbiExStr = DOMUtil.UTIL.DOM2String(doc, sw);
1935: mLogger.warning(jbiExStr);
1936: }
1937: }
1938: } catch (Exception e) {
1939: String jbiExStr = buildFrmwkExMsg("rollbackSUInits", e, e
1940: .getMessage());
1941: mLogger.warning(jbiExStr);
1942: }
1943:
1944: }
1945:
1946: /**
1947: * @param lifecycle operation name - stop/shutDown
1948: * @param saName - name of service assembly to be targeted
1949: * @param force - if true the state change is forceful ( applies only when the
1950: * operation is stop/shutDown )
1951: */
1952: String stopShutDownServiceAssembly(String saLifecycleMthdName,
1953: String saName, boolean force) throws Exception {
1954: EventNotifierCommon notifier = sMContext
1955: .getEnvironmentContext().getNotifier();
1956:
1957: //store the beginning time
1958: Date beginTime = new Date();
1959: Map<String, Long> suTimes = new HashMap<String, Long>();
1960:
1961: List cmpTaskRslts = new ArrayList();
1962: boolean saStateChangeRslt = true;
1963:
1964: try {
1965: int operationCount = 0;
1966: int successCount = 0;
1967:
1968: ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName);
1969: List<ServiceUnitInfo> suList = saInfo.getServiceUnitList();
1970:
1971: if (isServiceAssemblyEmpty(saName)) {
1972: ServiceAssemblyState saState = (saLifecycleMthdName
1973: .equals("stop") ? ServiceAssemblyState.STOPPED
1974: : ServiceAssemblyState.SHUTDOWN);
1975: getRegistry().getUpdater().setServiceAssemblyState(
1976: saState, saName);
1977:
1978: return buildResponse(cmpTaskRslts, saStateChangeRslt,
1979: saLifecycleMthdName, saName);
1980: }
1981:
1982: for (ServiceUnitInfo su : suList) {
1983: String suName = su.getName();
1984: String compName = su.getTargetComponent();
1985:
1986: DocumentBuilderFactory dbf = DocumentBuilderFactory
1987: .newInstance();
1988: DocumentBuilder db = dbf.newDocumentBuilder();
1989: try {
1990: if (!isDeployedServiceUnit(compName, suName)) {
1991: mLogger.fine("Service unit " + suName
1992: + " is not deployed to component "
1993: + compName + " : ignoring command "
1994: + saLifecycleMthdName);
1995: continue;
1996: }
1997:
1998: ComponentState cmpState = getComponentState(compName);
1999: if (cmpState == ComponentState.UNKNOWN) {
2000: String errMsg = mTranslator
2001: .getString(
2002: LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_NOT_INSTALLED,
2003: suName, compName);
2004: throw new Exception(errMsg);
2005: }
2006:
2007: if (cmpState == ComponentState.SHUTDOWN) {
2008: continue;
2009: }
2010: } catch (Exception e) {
2011: Element elem = getComponentResultXmlFragment(
2012: compName, saLifecycleMthdName, e);
2013: cmpTaskRslts.add(elem);
2014:
2015: // Stop processing and try to change the state
2016: // of the next SU in the SA.
2017: continue;
2018: }
2019:
2020: try {
2021: DeployerMBean deployer = getComponentDeployerInstance(compName);
2022: if (getActualServiceUnitState(compName, suName) != ServiceUnitState.SHUTDOWN) {
2023: if (saLifecycleMthdName
2024: .equalsIgnoreCase("stop")) {
2025: long suStopTimeBegin = System
2026: .currentTimeMillis();
2027:
2028: ++operationCount;
2029: deployer.stop(suName);
2030: ++successCount;
2031:
2032: suTimes.put(suName, System
2033: .currentTimeMillis()
2034: - suStopTimeBegin);
2035: } else if (saLifecycleMthdName
2036: .equalsIgnoreCase("shutDown")) {
2037: long suShutdownTimeBegin = System
2038: .currentTimeMillis();
2039:
2040: ++operationCount;
2041: deployer.shutDown(suName, Boolean
2042: .valueOf(force));
2043: ++successCount;
2044:
2045: suTimes.put(suName, System
2046: .currentTimeMillis()
2047: - suShutdownTimeBegin);
2048: }
2049: }
2050:
2051: // build a success component-task-result element
2052: String scssMsg = buildComponentStatusMsg(compName,
2053: saLifecycleMthdName, suName);
2054: Document doc = db.parse(new InputSource(
2055: new StringReader(scssMsg)));
2056: ;
2057: Element elem = DOMUtil.UTIL.getElement(doc,
2058: "component-task-result");
2059: cmpTaskRslts.add(elem);
2060:
2061: } catch (Exception e) {
2062: Element elem = getComponentResultXmlFragment(
2063: compName, saLifecycleMthdName, e);
2064: cmpTaskRslts.add(elem);
2065: }
2066: }
2067:
2068: // stop/shutdown is only successful if all operations succeed
2069: if (successCount < operationCount) {
2070: saStateChangeRslt = false;
2071: }
2072:
2073: } catch (Exception e) {
2074: String errMsg = mTranslator
2075: .getString(
2076: LocalStringKeys.DS_CANNOT_CHANGE_SERVICE_ASSEMBLY_STATE,
2077: saName);
2078: String jbiTaskStr = buildFrmwkExMsg(saLifecycleMthdName, e,
2079: errMsg);
2080: throw new Exception(jbiTaskStr);
2081: }
2082:
2083: String resp = buildResponse(cmpTaskRslts, saStateChangeRslt,
2084: saLifecycleMthdName, null);
2085:
2086: if (!saStateChangeRslt) {
2087: // operation failed completely, throw an exception with result text
2088: throw new Exception(resp);
2089: }
2090:
2091: updateStatistics(saName, saLifecycleMthdName, beginTime,
2092: new Date(), suTimes);
2093:
2094: // Emit a notification of the successful operation
2095: if (null != notifier) {
2096: notifier
2097: .emitServiceAssemblyNotification(
2098: (saLifecycleMthdName.equals("stop") ? EventNotifierCommon.EventType.Stopped
2099: : EventNotifierCommon.EventType.ShutDown),
2100: saName, "");
2101: }
2102: return resp;
2103:
2104: }
2105:
2106: /**
2107: * Start a Service Assembly. All the Service Units are first initialized and then
2108: * started.
2109: *
2110: * From the list of deployed service units only those service units are started,
2111: * which :
2112: * <li>
2113: * <ul> are deployed </ul>
2114: * <ul> are not already started </ul>
2115: * <ul> the target component is installed </ul>
2116: * <ul> the target component is not in the "Shutdown" state </ul>
2117: * </li>
2118: * </br>
2119: * This operation first filters out the service units to be started
2120: *
2121: * @param saName - name of service assembly to be targeted
2122: */
2123: String startServiceAssembly(String saName) throws Exception {
2124:
2125: // Get time this method was entered
2126: Date beginTime = new Date();
2127: Map<String, Long> suTimes = new HashMap<String, Long>();
2128:
2129: String saLifecycleMthdName = "start";
2130: List cmpTaskRslts = new ArrayList();
2131: boolean saStateChangeRslt = true;
2132: EventNotifierCommon notifier = sMContext
2133: .getEnvironmentContext().getNotifier();
2134:
2135: try {
2136: int operationCount = 0;
2137: int successCount = 0;
2138:
2139: ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName);
2140: List<ServiceUnitInfo> suList = saInfo.getServiceUnitList();
2141: List<ServiceUnitInfo> susToInitialize = new ArrayList();
2142: List<ServiceUnitInfo> susToStart = new ArrayList();
2143: List<ServiceUnitInfo> susAlreadyStarted = new ArrayList();
2144: List<ServiceUnitInfo> susToRollBack = new ArrayList();
2145: DocumentBuilderFactory dbf = DocumentBuilderFactory
2146: .newInstance();
2147: DocumentBuilder db = dbf.newDocumentBuilder();
2148:
2149: if (isServiceAssemblyEmpty(saName)) {
2150: getRegistry().getUpdater().setServiceAssemblyState(
2151: ServiceAssemblyState.STARTED, saName);
2152:
2153: return buildResponse(cmpTaskRslts, saStateChangeRslt,
2154: saLifecycleMthdName, saName);
2155: }
2156:
2157: for (ServiceUnitInfo su : suList) {
2158: String suName = su.getName();
2159: String compName = su.getTargetComponent();
2160:
2161: try {
2162: if (!isDeployedServiceUnit(compName, suName)) {
2163: mLogger.fine("Service unit " + suName
2164: + " is not deployed to component "
2165: + compName + " : ignoring command "
2166: + saLifecycleMthdName);
2167: continue;
2168: }
2169:
2170: ComponentState cmpState = getComponentState(compName);
2171:
2172: if (cmpState == ComponentState.UNKNOWN) {
2173: String errMsg = mTranslator
2174: .getString(
2175: LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_NOT_INSTALLED,
2176: suName, compName);
2177: throw new Exception(errMsg);
2178: }
2179:
2180: if (cmpState == ComponentState.SHUTDOWN) {
2181: // this counts as a failed operation, so increment the op counter
2182: ++operationCount;
2183:
2184: String errMsg = mTranslator
2185: .getString(
2186: LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_IN_INCORRECT_STATE,
2187: suName, compName);
2188: throw new Exception(errMsg);
2189: }
2190: } catch (Exception e) {
2191: Element elem = getComponentResultXmlFragment(
2192: compName, saLifecycleMthdName, e);
2193: cmpTaskRslts.add(elem);
2194:
2195: // Stop processing and try to change the state
2196: // of the next SU in the SA.
2197: continue;
2198: }
2199:
2200: ServiceUnitState currSuState = getActualServiceUnitState(
2201: compName, suName);
2202:
2203: switch (currSuState) {
2204: case STARTED:
2205: // -- Service unit already started counts as success;
2206: susAlreadyStarted.add(su);
2207: ++successCount;
2208: break;
2209:
2210: case STOPPED:
2211: // -- No need to init, only start this service unit
2212: susToStart.add(su);
2213: break;
2214:
2215: case SHUTDOWN:
2216: // -- Need to init and start the service unit
2217: susToInitialize.add(su);
2218: break;
2219: default:
2220: continue;
2221: }
2222: }
2223:
2224: // -- Now initialize all the service units ( this is fix for CR 6520614 )
2225: // -- which are to be started first, only sus which were Shutdown are initialized.
2226: for (ServiceUnitInfo su : susToInitialize) {
2227: String suName = su.getName();
2228: String compName = su.getTargetComponent();
2229:
2230: try {
2231: // -- increment op counter for each su life cycle operation
2232: ++operationCount;
2233: /* At this point we have verfied that the Component is installed
2234: * the DeployerInstance cannot be null, since it is available
2235: * once the component is installed ( so is available when component
2236: * is shutdown too )
2237: */
2238: DeployerMBean deployer = getComponentDeployerInstance(compName);
2239: long suInitTime = System.currentTimeMillis();
2240: deployer.init(su.getName(), su.getFilePath());
2241: suTimes.put(suName, Long.valueOf(System
2242: .currentTimeMillis()
2243: - suInitTime));
2244: // -- start only initialized service units.
2245: susToStart.add(su);
2246: // -- if start fails then need to rollback to state before : Shutdown
2247: susToRollBack.add(su);
2248:
2249: } catch (Exception e) {
2250: Element elem = getComponentResultXmlFragment(
2251: compName, saLifecycleMthdName, e);
2252: cmpTaskRslts.add(elem);
2253: }
2254: }
2255:
2256: // -- Start the service units
2257: for (ServiceUnitInfo su : suList) {
2258: String suName = su.getName();
2259: String compName = su.getTargetComponent();
2260:
2261: try {
2262: if (susToStart.contains(su)) {
2263: DeployerMBean deployer = getComponentDeployerInstance(compName);
2264:
2265: Long suInitTime = suTimes.get(suName);
2266: if (null == suInitTime) {
2267: suInitTime = new Long(0);
2268: }
2269: long suStartTime = System.currentTimeMillis();
2270:
2271: deployer.start(suName);
2272:
2273: suTimes.put(suName, Long.valueOf((System
2274: .currentTimeMillis() - suStartTime)
2275: + suInitTime.longValue()));
2276:
2277: if (susToRollBack.contains(su)) {
2278: // -- Start succeeded, no need to rollback this su
2279: susToRollBack.remove(su);
2280: }
2281:
2282: // if we made it here, the operation was successful
2283: ++successCount;
2284: String scssMsg = buildComponentStatusMsg(
2285: compName, saLifecycleMthdName, suName);
2286: Document doc = db.parse(new InputSource(
2287: new StringReader(scssMsg)));
2288: ;
2289: Element elem = DOMUtil.UTIL.getElement(doc,
2290: "component-task-result");
2291: cmpTaskRslts.add(elem);
2292:
2293: } else if (susAlreadyStarted.contains(su)) {
2294: // For SUs that are already in started state, add a component task result
2295: // that says SU already started
2296: String locMsg = mTranslator
2297: .getString(
2298: LocalStringKeys.DS_SERVICE_UNIT_ALREADY_STARTED,
2299: suName);
2300: String scssMsg = buildComponentStatusMsg(
2301: compName, saLifecycleMthdName, suName,
2302: locMsg);
2303: Document doc = db.parse(new InputSource(
2304: new StringReader(scssMsg)));
2305: ;
2306: Element elem = DOMUtil.UTIL.getElement(doc,
2307: "component-task-result");
2308: cmpTaskRslts.add(elem);
2309: }
2310:
2311: } catch (Exception e) {
2312: Element elem = getComponentResultXmlFragment(
2313: compName, saLifecycleMthdName, e);
2314: cmpTaskRslts.add(elem);
2315: }
2316: }
2317:
2318: // start is successful if at least one operation succeeds
2319: if (operationCount > 0 && successCount == 0) {
2320: saStateChangeRslt = false;
2321: }
2322:
2323: /**
2324: * If any service units which were in the Shutdown state could not be started
2325: * successfully, they need to be Shutdown again since they might be in the
2326: * Stopped state
2327: */
2328: if (!susToRollBack.isEmpty()) {
2329: rollbackSUInits(susToRollBack);
2330: }
2331: } catch (Exception e) {
2332: String errMsg = mTranslator
2333: .getString(
2334: LocalStringKeys.DS_CANNOT_CHANGE_SERVICE_ASSEMBLY_STATE,
2335: saName);
2336: String jbiTaskStr = buildFrmwkExMsg(saLifecycleMthdName, e,
2337: errMsg);
2338: throw new Exception(jbiTaskStr);
2339: }
2340:
2341: String resp = buildResponse(cmpTaskRslts, saStateChangeRslt,
2342: saLifecycleMthdName, saName);
2343:
2344: if (!saStateChangeRslt) {
2345: // operation failed completely, throw an exception with result text
2346: throw new Exception(resp);
2347: }
2348:
2349: //update statistics
2350: updateStatistics(saName, START, beginTime, new Date(), suTimes);
2351:
2352: // Emit a notification of the successful start
2353: if (null != notifier) {
2354: notifier.emitServiceAssemblyNotification(
2355: EventNotifierCommon.EventType.Started, saName, "");
2356: }
2357: return resp;
2358: }
2359:
2360: HashMap getConnectionsInfo(Element connectionElem, String saName)
2361: throws DeploymentException {
2362: HashMap connInfo = new HashMap();
2363:
2364: try {
2365: QName intrfName = null;
2366: QName fromSvc = null;
2367: String fromEndpoint = null;
2368: QName toSvc = null;
2369: String toEndpoint = null;
2370:
2371: Element consumerElem = DOMUtil.UTIL.getElement(
2372: connectionElem, "consumer");
2373: Element providerElem = DOMUtil.UTIL.getElement(
2374: connectionElem, "provider");
2375: intrfName = DOMUtil.UTIL.getQualifiedAttributeValue(
2376: consumerElem, "interface-name");
2377: if (intrfName == null || intrfName.toString().equals("")) {
2378: fromSvc = DOMUtil.UTIL.getQualifiedAttributeValue(
2379: consumerElem, "service-name");
2380: fromEndpoint = DOMUtil.UTIL.getAttribute(consumerElem,
2381: "endpoint-name");
2382: connInfo.put("from-service", fromSvc);
2383: connInfo.put("from-endpoint", fromEndpoint);
2384: } else {
2385: connInfo.put("interface-name", intrfName);
2386: }
2387:
2388: toSvc = DOMUtil.UTIL.getQualifiedAttributeValue(
2389: providerElem, "service-name");
2390: toEndpoint = DOMUtil.UTIL.getAttribute(providerElem,
2391: "endpoint-name");
2392: connInfo.put("to-service", toSvc);
2393: connInfo.put("to-endpoint", toEndpoint);
2394:
2395: } catch (Exception e) {
2396: e.printStackTrace();
2397: String jbiExStr = null;
2398: String errMsg = mTranslator.getString(
2399: LocalStringKeys.DS_UNABLE_TO_GET_CONNECTIONS_INFO,
2400: saName);
2401: jbiExStr = buildFrmwkExMsg("getConnectionsInfo", e, errMsg);
2402: throw new DeploymentException(jbiExStr);
2403: }
2404:
2405: return connInfo;
2406:
2407: }
2408:
2409: /**
2410: * Activate Service Connections defined in the specified Service Assembly.
2411: *
2412: * @param saName The name of the Service Assembly.
2413: * @return a HashMap of result messages with the endpoint or interface
2414: * names as the keys.
2415: * @throws Exception if an unrecoverable error occurs.
2416: */
2417: HashMap activateConnections(String saName) throws Exception {
2418: return activateConnections(saName, true);
2419: }
2420:
2421: /**
2422: * Activate Service Connections defined in the specified Service Assembly.
2423: *
2424: * @param saName The name of the Service Assembly.
2425: * @param xmlMsg When set to <code>true</code>, requests that error messages
2426: * returned in the HashMap be in XML management message format. When set to
2427: * false, error messages are in text format.
2428: * @return a HashMap of result messages with the endpoint or interface
2429: * names as the keys.
2430: * @throws Exception if an unrecoverable error occurs.
2431: */
2432: public HashMap activateConnections(String saName, boolean xmlMsg)
2433: throws Exception {
2434: ConnectionManager connMgr = null;
2435: HashMap infoMsgMap = new HashMap();
2436:
2437: Element connctnsElement = getConnectionsElement(saName);
2438: if (connctnsElement == null) {
2439: //There is no connections info. in
2440: //deployment descriptor.
2441: return null;
2442: }
2443:
2444: NodeList nl = DOMUtil.UTIL.getChildElements(connctnsElement,
2445: "connection");
2446: if (nl.getLength() == 0) {
2447: //No connection elements. return
2448: return null;
2449: }
2450:
2451: String fromEndpoint = null;
2452: QName intrfcName = null;
2453:
2454: for (int i = 0; i < nl.getLength(); i++) {
2455: Node connNode = nl.item(i);
2456: if (connNode instanceof Element) {
2457: try {
2458: HashMap connInfo = getConnectionsInfo(
2459: (Element) connNode, saName);
2460: intrfcName = (QName) connInfo.get("interface-name");
2461: QName fromSvc = null;
2462: fromEndpoint = null;
2463: if (intrfcName == null
2464: || intrfcName.toString().equals("")) {
2465: fromSvc = (QName) connInfo.get("from-service");
2466: fromEndpoint = (String) connInfo
2467: .get("from-endpoint");
2468: }
2469: QName toSvc = (QName) connInfo.get("to-service");
2470: String toEndpoint = (String) connInfo
2471: .get("to-endpoint");
2472:
2473: connMgr = sMContext.getConnectionManager();
2474: if (intrfcName != null
2475: && !intrfcName.toString().equals("")) {
2476: connMgr.addInterfaceConnection(intrfcName,
2477: toSvc, toEndpoint);
2478: } else {
2479: Link linkType = getLinkType(fromEndpoint,
2480: saName);
2481: if (linkType == null) {
2482: linkType = Link.STANDARD;
2483: }
2484: connMgr.addEndpointConnection(fromSvc,
2485: fromEndpoint, toSvc, toEndpoint,
2486: linkType);
2487: }
2488:
2489: } catch (DeploymentException de) {
2490: de.printStackTrace();
2491: throw new Exception(de.getMessage());
2492: } catch (Exception exObj) {
2493: exObj.printStackTrace();
2494: String errMsg = mTranslator
2495: .getString(
2496: LocalStringKeys.DS_UNABLE_TO_ACTIVATE_CONNECTION,
2497: saName, exObj.getMessage());
2498: if (xmlMsg) {
2499: Element infoElem = buildFrmwkInfoMsg(errMsg);
2500: if (fromEndpoint != null) {
2501: infoMsgMap.put(fromEndpoint, infoElem);
2502: } else {
2503: infoMsgMap.put(intrfcName, infoElem);
2504: }
2505: } else {
2506: if (fromEndpoint != null) {
2507: infoMsgMap.put(fromEndpoint, errMsg);
2508: } else {
2509: infoMsgMap.put(intrfcName, errMsg);
2510: }
2511: }
2512: }
2513: }
2514: }
2515:
2516: return infoMsgMap;
2517: }
2518:
2519: HashMap deactivateConnections(String saName) throws Exception {
2520: ConnectionManager connMgr = null;
2521: HashMap infoMsgMap = new HashMap();
2522:
2523: Element connctnsElement = getConnectionsElement(saName);
2524: if (connctnsElement == null) {
2525: //There is no connections info. in
2526: //deployment descriptor.
2527: return null;
2528: }
2529:
2530: NodeList nl = DOMUtil.UTIL.getChildElements(connctnsElement,
2531: "connection");
2532: if (nl.getLength() == 0) {
2533: //No connection elements. return
2534: return null;
2535: }
2536:
2537: // TO DO: Fix error messsages
2538: String fromEndpoint = null;
2539: QName intrfcName = null;
2540: for (int i = 0; i < nl.getLength(); i++) {
2541: Node connNode = nl.item(i);
2542: if (connNode instanceof Element) {
2543: try {
2544: HashMap connInfo = getConnectionsInfo(
2545: (Element) connNode, saName);
2546: intrfcName = (QName) connInfo.get("interface-name");
2547: QName fromSvc = null;
2548: fromEndpoint = null;
2549: if (intrfcName == null
2550: || intrfcName.toString().equals("")) {
2551: fromSvc = (QName) connInfo.get("from-service");
2552: fromEndpoint = (String) connInfo
2553: .get("from-endpoint");
2554: }
2555: QName toSvc = (QName) connInfo.get("to-service");
2556: String toEndpoint = (String) connInfo
2557: .get("to-endpoint");
2558:
2559: connMgr = sMContext.getConnectionManager();
2560: if (intrfcName != null
2561: && !intrfcName.toString().equals("")) {
2562: connMgr.removeInterfaceConnection(intrfcName,
2563: toSvc, toEndpoint);
2564: } else {
2565: connMgr.removeEndpointConnection(fromSvc,
2566: fromEndpoint, toSvc, toEndpoint);
2567: }
2568:
2569: } catch (DeploymentException de) {
2570: de.printStackTrace();
2571: throw new Exception(de.getMessage());
2572: } catch (Exception exObj) {
2573: exObj.printStackTrace();
2574: String errMsg = mTranslator
2575: .getString(
2576: LocalStringKeys.DS_UNABLE_TO_DEACTIVATE_CONNECTION,
2577: saName);
2578:
2579: Element infoElem = buildFrmwkInfoMsg(errMsg);
2580:
2581: if (fromEndpoint != null) {
2582: infoMsgMap.put(fromEndpoint, infoElem);
2583: } else {
2584: infoMsgMap.put(intrfcName, infoElem);
2585: }
2586: }
2587: }
2588: }
2589:
2590: return infoMsgMap;
2591: }
2592:
2593: private Element buildFrmwkInfoMsg(String errMsgWithToken) {
2594: Document doc = null;
2595: Element taskStatMsgElem = null;
2596:
2597: try {
2598: doc = mMImpl.createDocument();
2599: taskStatMsgElem = doc.createElement("task-status-msg");
2600: Element msgLocInfoElem = doc.createElement("msg-loc-info");
2601: Element locTokenElem = doc.createElement("loc-token");
2602: Element locMsgElem = doc.createElement("loc-message");
2603: String token = MessageBuilder
2604: .getMessageToken(errMsgWithToken);
2605: String errMsg = MessageBuilder
2606: .getMessageString(errMsgWithToken);
2607: DOMUtil.UTIL.setTextData(locTokenElem, token);
2608: DOMUtil.UTIL.setTextData(locMsgElem, errMsg);
2609: msgLocInfoElem.appendChild(locTokenElem);
2610: msgLocInfoElem.appendChild(locMsgElem);
2611: taskStatMsgElem.appendChild(msgLocInfoElem);
2612:
2613: } catch (Exception e) {
2614: String statusMsg = mTranslator.getString(
2615: LocalStringKeys.DS_DEPLOY_NO_EXCEPTION_MSG,
2616: "buildFrmwkInfoMsg");
2617: mLogger.warning(statusMsg);
2618: }
2619:
2620: return taskStatMsgElem;
2621: }
2622:
2623: private String appendMsgsToTaskRslt(String stateChangeRslt,
2624: HashMap infoMsgElems, String msgType) {
2625: Document doc = null;
2626: String rsltWithInfoMsgs = null;
2627:
2628: try {
2629:
2630: if ((infoMsgElems == null) || (infoMsgElems.size() == 0)) {
2631: return stateChangeRslt;
2632: }
2633:
2634: DocumentBuilderFactory dbf = DocumentBuilderFactory
2635: .newInstance();
2636: DocumentBuilder db = dbf.newDocumentBuilder();
2637: InputSource isrc = new InputSource((new CharArrayReader(
2638: stateChangeRslt.toCharArray())));
2639: doc = db.parse(isrc);
2640: Element frmwkTaskRsltElem = DOMUtil.UTIL.getElement(doc,
2641: "frmwk-task-result");
2642: Element frmwkTskRsltDtlsElem = DOMUtil.UTIL.getElement(
2643: frmwkTaskRsltElem, "frmwk-task-result-details");
2644: Element taskRsltDtlsElem = DOMUtil.UTIL.getElement(
2645: frmwkTskRsltDtlsElem, "task-result-details");
2646: Element msgTypeElem = doc.createElement("message-type");
2647: DOMUtil.UTIL.setTextData(msgTypeElem, msgType);
2648: taskRsltDtlsElem.appendChild(msgTypeElem);
2649: Set keys = infoMsgElems.keySet();
2650: Iterator iter = keys.iterator();
2651:
2652: while (iter.hasNext()) {
2653: Object key = iter.next();
2654: Element elem = (Element) infoMsgElems.get(key);
2655: Element infoMsgElem = (Element) doc.importNode(elem,
2656: true);
2657: taskRsltDtlsElem.appendChild(infoMsgElem);
2658: }
2659:
2660: StringWriter sw = new StringWriter();
2661: rsltWithInfoMsgs = DOMUtil.UTIL.DOM2String(doc, sw);
2662: } catch (Exception e) {
2663: String statusMsg = mTranslator.getString(
2664: LocalStringKeys.DS_DEPLOY_NO_EXCEPTION_MSG,
2665: "appendMsgsToTaskRslt");
2666: mLogger.warning(statusMsg);
2667: e.printStackTrace();
2668: }
2669:
2670: return rsltWithInfoMsgs;
2671: }
2672:
2673: /**
2674: * Utility routine to move an unable-to-delete directory
2675: * into a "Trash" directory.
2676: * @param aDir directory name.
2677: */
2678: private void moveToTrash(String aDir) {
2679: String logMessage = mTranslator.getString(
2680: LocalStringKeys.METHOD_ENTERED, "moveToTrash", "("
2681: + aDir + ")");
2682: mLogger.fine(logMessage);
2683:
2684: String jbiRoot = sMContext.getJbiInstallRoot();
2685:
2686: if ((null == jbiRoot) || ("".equals(jbiRoot))) {
2687: logMessage = mTranslator
2688: .getString(LocalStringKeys.DS_NO_TRASH);
2689: mLogger.warning(logMessage);
2690: return;
2691: }
2692:
2693: jbiRoot += "/Trash";
2694: int dirNum = 1;
2695: String trashRootPath = jbiRoot + "/" + dirNum;
2696: File trashRoot = new File(trashRootPath);
2697: while (trashRoot.exists()) {
2698: dirNum++;
2699: trashRootPath = jbiRoot + "/" + dirNum;
2700: trashRoot = new File(trashRootPath);
2701: }
2702: logMessage = mTranslator.getString(
2703: LocalStringKeys.DS_DEBUG_OUTPUT,
2704: "Creating Trash directory as " + trashRootPath);
2705: mLogger.fine(logMessage);
2706: if (!trashRoot.mkdirs()) {
2707: logMessage = mTranslator.getString(
2708: LocalStringKeys.DS_DEBUG_OUTPUT,
2709: "Cannot create directory " + trashRootPath);
2710: mLogger.warning(logMessage);
2711: return;
2712: }
2713: logMessage = mTranslator.getString(
2714: LocalStringKeys.DS_DEBUG_OUTPUT, "Now about to rename "
2715: + aDir + " to " + trashRootPath + ".");
2716: mLogger.fine(logMessage);
2717: File oldRoot = new File(aDir);
2718: if (!oldRoot.renameTo(trashRoot)) {
2719: logMessage = mTranslator.getString(
2720: LocalStringKeys.DS_DEBUG_OUTPUT,
2721: "Could not rename " + aDir + " to " + trashRootPath
2722: + ".");
2723: mLogger.warning(logMessage);
2724: }
2725: }
2726:
2727: private void deleteSADirectory(String saName) {
2728: String mSAUnzipDir = null;
2729:
2730: try {
2731: // Delete the Service Assembly unzip directory
2732: mSAUnzipDir = sMContext.getJbiInstallRoot()
2733: + File.separator + "system" + File.separator
2734: + "deployment" + File.separator + saName;
2735: DirectoryUtil.deleteDir(mSAUnzipDir);
2736: } catch (Exception e) {
2737: File deleteMe = new File(mSAUnzipDir,
2738: PATH_TO_DELETE_ME_FILE);
2739: try {
2740: FileOutputStream fos = new FileOutputStream(deleteMe);
2741: fos.close();
2742: } catch (IOException ioe) {
2743: String errMsg = mTranslator.getString(
2744: LocalStringKeys.DS_DIRECTORY_NOT_MARKED,
2745: mSAUnzipDir, ioe.getMessage());
2746: mLogger.warning(errMsg);
2747: }
2748:
2749: String errMsg = mTranslator.getString(
2750: LocalStringKeys.DS_DIRECTORY_NOT_REMOVED,
2751: mSAUnzipDir);
2752: mLogger.warning(errMsg);
2753: moveToTrash(mSAUnzipDir);
2754:
2755: }
2756:
2757: }
2758:
2759: private boolean checkSUContents(String currSAName, String compName,
2760: String suName, String currSUJarAbsPath) {
2761: boolean isDuplicateSUContents = false;
2762: String[] saNames = null;
2763:
2764: try {
2765: saNames = getDeployedServiceAssembliesForComponent(compName);
2766: for (int i = 0; i < saNames.length; i++) {
2767: if (!currSAName.equalsIgnoreCase(saNames[i])) {
2768: String saRootDirName = dplyRoot + File.separator
2769: + saNames[i];
2770: File saDir = new File(saRootDirName);
2771: String[] saDirList = saDir.list();
2772: for (int j = 0; j < saDirList.length; j++) {
2773: if (saDirList[j].endsWith(".zip")) {
2774: String dplydSUJarAbsPath = dplyRoot
2775: + File.separator + saNames[i]
2776: + File.separator + saDirList[j];
2777: isDuplicateSUContents = compareBinaryContents(
2778: currSUJarAbsPath, dplydSUJarAbsPath);
2779: if (isDuplicateSUContents) {
2780: break;
2781: }
2782: }
2783: }
2784:
2785: if (isDuplicateSUContents) {
2786: break;
2787: }
2788: }
2789: }
2790:
2791: } catch (Exception e) {
2792: String errMsg = mTranslator.getString(
2793: LocalStringKeys.DS_CANNOT_CHECK_SU_CONTENTS,
2794: suName, currSAName);
2795: String jbiExStr = buildFrmwkExMsg("checkSUContents", e,
2796: errMsg);
2797: mLogger.warning(jbiExStr);
2798:
2799: }
2800:
2801: return isDuplicateSUContents;
2802: }
2803:
2804: private boolean compareBinaryContents(String suJarAbsPath,
2805: String dplydSUJarAbsPath) {
2806: boolean isDuplicate = false;
2807: InputStream isCurrSU = null;
2808: InputStream isDplydSU = null;
2809: ZipFile mCurrSUZip = null;
2810: ZipFile mDplydSUZip = null;
2811:
2812: try {
2813: mCurrSUZip = new ZipFile(suJarAbsPath);
2814: mDplydSUZip = new ZipFile(dplydSUJarAbsPath);
2815: Enumeration eCurrSU = mCurrSUZip.entries();
2816: Enumeration eDplydSU = mDplydSUZip.entries();
2817:
2818: if (mCurrSUZip.size() != mDplydSUZip.size()) {
2819: return isDuplicate;
2820: }
2821:
2822: int numEntries = mCurrSUZip.size();
2823: int duplicateEntries = 0;
2824:
2825: while (eCurrSU.hasMoreElements()) {
2826: ZipEntry zeCurrSU = (ZipEntry) eCurrSU.nextElement();
2827: ZipEntry zeDplydSU = (ZipEntry) eDplydSU.nextElement();
2828: isCurrSU = mCurrSUZip.getInputStream(zeCurrSU);
2829: isDplydSU = mDplydSUZip.getInputStream(zeDplydSU);
2830:
2831: int isCurrSUByte = isCurrSU.read();
2832: int isDplydSUByte = isDplydSU.read();
2833:
2834: while ((isCurrSUByte != -1) && (isDplydSUByte != -1)) {
2835: if (isCurrSUByte != isDplydSUByte) {
2836: break;
2837: }
2838: isCurrSUByte = isCurrSU.read();
2839: isDplydSUByte = isDplydSU.read();
2840: }
2841:
2842: if ((isCurrSUByte == -1) && (isDplydSUByte == -1)) {
2843: duplicateEntries++;
2844: }
2845:
2846: isCurrSU.close();
2847: isDplydSU.close();
2848:
2849: }
2850:
2851: if (numEntries == duplicateEntries) {
2852: isDuplicate = true;
2853: }
2854:
2855: } catch (Exception e) {
2856: try {
2857: if (isCurrSU != null) {
2858: isCurrSU.close();
2859: }
2860:
2861: if (isDplydSU != null) {
2862: isDplydSU.close();
2863: }
2864: } catch (Exception ex) {
2865: String jbiExStr = buildFrmwkExMsg(
2866: "compareBinaryContents", ex, ex.getMessage());
2867: mLogger.warning(jbiExStr);
2868: }
2869:
2870: String errMsg = mTranslator
2871: .getString(
2872: LocalStringKeys.DS_FAILED_COMPARING_BINARY_SU_CONTENTS,
2873: suJarAbsPath, dplydSUJarAbsPath);
2874: String jbiExStr = buildFrmwkExMsg("compareBinaryContents",
2875: e, errMsg);
2876: mLogger.warning(jbiExStr);
2877: } finally {
2878: try {
2879: if (mCurrSUZip != null) {
2880: mCurrSUZip.close();
2881: }
2882:
2883: if (mDplydSUZip != null) {
2884: mDplydSUZip.close();
2885: }
2886: } catch (Exception ex) {
2887: String jbiExStr = buildFrmwkExMsg(
2888: "compareBinaryContents", ex, ex.getMessage());
2889: mLogger.warning(jbiExStr);
2890: }
2891: }
2892:
2893: return isDuplicate;
2894: }
2895:
2896: /**
2897: * Get the ObjectName for the DeployerMBean for the Component.
2898: *
2899: * @param compName name of a binding or engine component
2900: * @return the ObjectName for the component's DeployerMBean, or null.
2901: */
2902: private ObjectName getDeployerMBeanObjectName(String compName) {
2903: ObjectName dmbs[] = sMContext.getAdminServiceHandle()
2904: .getDeployerMBeanNames(compName);
2905:
2906: //TODO: handle multiple mbeans. RT 5/11/05
2907: return (dmbs.length <= 0 ? null : dmbs[0]);
2908: }
2909:
2910: /**
2911: * Eliminate spaces (-> "%20") to handle odd cases like installation
2912: * directories containing a space.
2913: *
2914: * @param installJarURI - String containing URL to convert
2915: * @return - a URL fixing spaces contained within.
2916: * @throws java.net.MalformedURLException if an error occurs
2917: */
2918: private URL convertToProperURL(String installJarURI)
2919: throws java.net.MalformedURLException {
2920: // fix problems commonly occuring with 'file:' URLs on Windows
2921: if (installJarURI.startsWith("file://")) {
2922: return new File(installJarURI.substring(7)).toURL();
2923: }
2924:
2925: if (installJarURI.startsWith("file:" + File.separator)) {
2926: return new File(installJarURI.substring(5)).toURL();
2927: }
2928:
2929: // next case: Windows only, skip over the /
2930: if (installJarURI.startsWith("file:/")) {
2931: return new File(installJarURI.substring(6)).toURL();
2932: }
2933:
2934: if (installJarURI.startsWith("file:")) {
2935: return new File(installJarURI.substring(5)).toURL();
2936: }
2937:
2938: // last ditch effort to handle URLs with non-encoded spaces
2939: try {
2940: return new java.net.URI(installJarURI
2941: .replaceAll(" ", "%20")).toURL();
2942: } catch (java.net.URISyntaxException e) {
2943: throw new java.net.MalformedURLException(e.getMessage());
2944: }
2945: }
2946:
2947: /**
2948: * @return the ServuceUnitInfo of a specific SU from the ServiceUnitInfoList
2949: */
2950: private ServiceUnitInfo findDeploymentUnitInfo(
2951: List<ServiceUnitInfo> suInfoList, String suName) {
2952: ServiceUnitInfo suInfo = null;
2953:
2954: for (ServiceUnitInfo su : suInfoList) {
2955: if (suName.equals(su.getName())) {
2956: suInfo = su;
2957: break;
2958: }
2959: }
2960: return suInfo;
2961: }
2962:
2963: public Iterator listServiceAssemblies(String compName) {
2964: ComponentInfo compInfo = getComponentQuery().getComponentInfo(
2965: compName);
2966: List serviceAssemblies = new ArrayList();
2967:
2968: List<ServiceUnitInfo> suList = compInfo.getServiceUnitList();
2969: //for (int i = 0; i < suList.size(); i++)
2970: for (ServiceUnitInfo su : suList) {
2971: //ServiceUnitInfo su = (ServiceUnitInfo) suList.get(i);
2972: serviceAssemblies.add(su.getServiceAssemblyName());
2973: }
2974:
2975: return serviceAssemblies.iterator();
2976: }
2977:
2978: /**
2979: * Activate the Service Connections if SA state is Started, deactivate the
2980: * connections if state is Stopped or Shutdown.
2981: */
2982: public void updateServiceAssemblyConnections(String compName) {
2983: String saName;
2984: Iterator saList = listServiceAssemblies(compName);
2985:
2986: mLogger
2987: .fine("Updating Service Assembly Connections for component "
2988: + compName);
2989: while (saList.hasNext()) {
2990: saName = (String) saList.next();
2991: updateSAState(saName);
2992: }
2993: }
2994:
2995: /**
2996: * Determines the appropriate state for a service assembly. This code is
2997: * necessary because the component autostart information may only be part
2998: * of the picture for a given SA (which can include multiple SUs, targeted
2999: * at multiple components).
3000: */
3001: public String updateSAState(String saName) {
3002: String fwState; // state of SA based on framework state of SUs
3003:
3004: fwState = DeploymentServiceMBean.SHUTDOWN;
3005: try {
3006: ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName);
3007: List<ServiceUnitInfo> suList = saInfo.getServiceUnitList();
3008:
3009: for (ServiceUnitInfo su : suList) {
3010: String suName = su.getName();
3011: String compName = su.getTargetComponent();
3012: ComponentInfo compInfo;
3013: List compSUs;
3014: ServiceUnitState suState = ServiceUnitState.SHUTDOWN;
3015:
3016: suState = getActualServiceUnitState(compName, suName);
3017:
3018: if (suState == ServiceUnitState.STARTED) {
3019: // all it takes is one SU in STARTED to flip the SA state
3020: fwState = DeploymentServiceMBean.STARTED;
3021: break;
3022: } else if (suState == ServiceUnitState.STOPPED) {
3023: // set the SA state to STOPPED, but keep looking for a started SU
3024: fwState = DeploymentServiceMBean.STOPPED;
3025: }
3026: }
3027:
3028: if (fwState.equals(DeploymentServiceMBean.STARTED)) {
3029: mLogger
3030: .fine("Activating Connections for Service Assembly "
3031: + saName);
3032: activateConnections(saName);
3033: } else {
3034: mLogger
3035: .fine("Deactivating Connections for Service Assembly "
3036: + saName);
3037: deactivateConnections(saName);
3038: }
3039: } catch (Exception ex) {
3040: mLogger
3041: .warning(mTranslator
3042: .getString(
3043: LocalStringKeys.DS_AUTOSTART_CONNECTION_PROCESSING_FAILED,
3044: saName, ex.toString()));
3045: }
3046: return fwState;
3047: }
3048:
3049: /*---------------------------------------------------------------------------------*\
3050: * Private Helpers *
3051: \*---------------------------------------------------------------------------------*/
3052:
3053: /**
3054: * @return true if the service assembly has zero service units
3055: * @param saName - name of the service assembly
3056: */
3057: private boolean isServiceAssemblyEmpty(String saName)
3058: throws Exception {
3059: ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName,
3060: "domain");
3061: return saInfo.getServiceUnitList().isEmpty();
3062: }
3063:
3064: /**
3065: * @return the ServiceAssemblyInfo obtained from the Registry
3066: */
3067: private ServiceAssemblyInfo getServiceAssemblyInfo(String saName,
3068: String target) throws Exception {
3069: ServiceAssemblyQuery saQuery = getRegistry()
3070: .getServiceAssemblyQuery(target);
3071: ServiceAssemblyInfo saInfo = saQuery
3072: .getServiceAssemblyInfo(saName);
3073:
3074: if (saInfo == null) {
3075: String errMsg = mTranslator
3076: .getString(
3077: LocalStringKeys.DS_CANNOT_GET_SA_INFO_INVALID_SA_NAME,
3078: saName);
3079: throw new Exception(errMsg);
3080: }
3081:
3082: return saInfo;
3083: }
3084:
3085: /**
3086: * @return the ServiceAssemblyInfo obtained from the Registry
3087: */
3088: private ServiceAssemblyInfo getServiceAssemblyInfo(String saName)
3089: throws Exception {
3090: ServiceAssemblyQuery saQuery = getRegistry()
3091: .getServiceAssemblyQuery();
3092: ServiceAssemblyInfo saInfo = saQuery
3093: .getServiceAssemblyInfo(saName);
3094:
3095: if (saInfo == null) {
3096: String errMsg = mTranslator
3097: .getString(
3098: LocalStringKeys.DS_CANNOT_GET_SA_INFO_INVALID_SA_NAME,
3099: saName);
3100: throw new Exception(errMsg);
3101: }
3102:
3103: return saInfo;
3104: }
3105:
3106: /**
3107: * Get the Connections Element from the Service Assembly Deployment descriptor
3108: */
3109:
3110: public Element getConnectionsElement(String saName)
3111: throws Exception {
3112: DocumentBuilderFactory dbf = DocumentBuilderFactory
3113: .newInstance();
3114: dbf.setValidating(false);
3115: dbf.setNamespaceAware(true);
3116: DocumentBuilder db = dbf.newDocumentBuilder();
3117:
3118: String saDescriptor = getRegistry().getGenericQuery()
3119: .getServiceAssemblyDeploymentDescriptor(saName);
3120:
3121: org.xml.sax.InputSource ipSrc = new org.xml.sax.InputSource(
3122: new StringReader(saDescriptor));
3123: Document doc = db.parse(ipSrc);
3124: Element saElem = DOMUtil.UTIL.getElement(doc,
3125: "service-assembly");
3126: return DOMUtil.UTIL.getElement(saElem, "connections");
3127: }
3128:
3129: /**
3130: * Get the link-type for the Endpoint from the Service Units in the Service Assembly.
3131: * The DOM processing should be replaced by using JAXB.
3132: *
3133: * @param fromEndpoint - the connection consumer service endpoint
3134: * @param saName - the service assembly name
3135: */
3136: public Link getLinkType(String fromEndpoint, String saName)
3137: throws Exception {
3138: Link linkType = null;
3139:
3140: try {
3141: ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName,
3142: "domain");
3143: List<ServiceUnitInfo> suList = saInfo.getServiceUnitList();
3144:
3145: DocumentBuilderFactory dbf = DocumentBuilderFactory
3146: .newInstance();
3147: dbf.setValidating(false);
3148: dbf.setNamespaceAware(true);
3149: DocumentBuilder db = dbf.newDocumentBuilder();
3150: for (ServiceUnitInfo su : suList) {
3151: String suDescriptor = su.getFilePath() + File.separator
3152: + "META-INF" + File.separator + "jbi.xml";
3153: File jbiXmlFile = new File(suDescriptor);
3154: if (jbiXmlFile.exists()) {
3155: Document doc = db.parse(jbiXmlFile);
3156: Element servicesElem = DOMUtil.UTIL.getElement(doc,
3157: "services");
3158: Element consumesElem = DOMUtil.UTIL.getElement(
3159: servicesElem, "consumes");
3160: if (consumesElem == null) {
3161: return null;
3162: }
3163:
3164: String endpointName = DOMUtil.UTIL.getAttribute(
3165: consumesElem, "endpoint-name");
3166: if (endpointName.equalsIgnoreCase(fromEndpoint)) {
3167: String linkTypeStr = DOMUtil.UTIL.getAttribute(
3168: consumesElem, "link-type");
3169: if (linkTypeStr.equalsIgnoreCase("HARD"))
3170: linkType = Link.HARD;
3171: if (linkTypeStr.equalsIgnoreCase("STANDARD"))
3172: linkType = Link.STANDARD;
3173: if (linkTypeStr.equalsIgnoreCase("SOFT"))
3174: linkType = Link.SOFT;
3175: break;
3176: }
3177: }
3178:
3179: }
3180: } catch (DeploymentException de) {
3181: throw de;
3182: } catch (Exception e) {
3183: String errMsg = mTranslator
3184: .getString(
3185: LocalStringKeys.DS_UNABLE_TO_GET_LINK_TYPE_FROM_SU_DESCRIPTOR,
3186: saName);
3187: String jbiTaskStr = buildFrmwkExMsg("getLinkType", e,
3188: errMsg);
3189: throw new DeploymentException(jbiTaskStr);
3190: }
3191:
3192: return linkType;
3193: }
3194:
3195: /**
3196: * Get the ObjectName of the ComponentLifeCycleMBean on the instance
3197: */
3198: private ObjectName getComponentLifeCycleMBeanName(
3199: String componentName) {
3200:
3201: MBeanNames mbnNames = sMContext.getMBeanNames();
3202:
3203: ObjectName compLCMBean = null;
3204:
3205: ComponentType compType = getComponentType(componentName);
3206:
3207: if (ComponentType.BINDING == compType) {
3208: compLCMBean = mbnNames.getBindingMBeanName(componentName,
3209: MBeanNames.CONTROL_TYPE_LIFECYCLE);
3210: } else {
3211: compLCMBean = mbnNames.getEngineMBeanName(componentName,
3212: MBeanNames.CONTROL_TYPE_LIFECYCLE);
3213: }
3214:
3215: return compLCMBean;
3216: }
3217:
3218: /**
3219: * @return the ComponentType of the component. If the component is not installed
3220: * a null value is returned
3221: */
3222: private ComponentType getComponentType(String componentName) {
3223: ComponentType compType = null;
3224: ComponentInfo compInfo = getComponentQuery().getComponentInfo(
3225: componentName);
3226:
3227: if (compInfo != null) {
3228: compType = compInfo.getComponentType();
3229: }
3230:
3231: return compType;
3232: }
3233:
3234: /**
3235: * Stop a service assembly, this operation is called by the pblic stop() operation
3236: * as well as the public shutDown() operation.
3237: *
3238: * @param serviceAssemblyName - target service assembly name
3239: * @param isStarted - flag indicating if the service assembly is in the started state.
3240: * If the service assembly is in the started state, the service connections need to
3241: * be deactivated.
3242: */
3243: private String stopServiceAssembly(String serviceAssemblyName,
3244: boolean isStarted) throws Exception {
3245: HashMap infoMsgElems = null;
3246:
3247: if (isStarted) {
3248: infoMsgElems = deactivateConnections(serviceAssemblyName);
3249: }
3250:
3251: String stateChangeRslt = stopShutDownServiceAssembly("stop",
3252: serviceAssemblyName, false);
3253: String jbiTaskStr = appendMsgsToTaskRslt(stateChangeRslt,
3254: infoMsgElems, "WARNING");
3255:
3256: return jbiTaskStr;
3257: }
3258:
3259: /**
3260: * @return the DeployerMBean instance for a component
3261: */
3262: private DeployerMBean getComponentDeployerInstance(String compName) {
3263: return sMContext.getEnvironmentContext().getComponentManager()
3264: .getDeployerInstance(compName);
3265: }
3266:
3267: /**
3268: * Return true if the component-task-results indicate partial success.
3269: * <ul>
3270: * <li>If all component-task-results have task-result=SUCCESS -> deployment completely successful</li>
3271: * <li>If one or more ( but not all ) component-task-results have task-result=SUCCESS -> deployment partiallly successful</li>
3272: * </ul>
3273: *
3274: * @param cmpTaskRslts - list of component-task-result elements
3275: * @return true if the component-task-results indicate partial success
3276: */
3277: private boolean isPartialSuccess(List<Element> cmpTaskRslts) {
3278: int successCount = 0;
3279: int numComponentResults = cmpTaskRslts.size();
3280: for (Element cmpResult : cmpTaskRslts) {
3281: Element taskResult = DOMUtil.UTIL.getElement(cmpResult,
3282: "task-result");
3283: String taskResultStr = DOMUtil.UTIL.getTextData(taskResult);
3284: if ("SUCCESS".equalsIgnoreCase(taskResultStr)) {
3285: successCount++;
3286: }
3287: }
3288:
3289: return ((successCount > 0) && (successCount != numComponentResults));
3290: }
3291:
3292: /**
3293: * Checks the exception message for the component result xml. if found,
3294: * the message is converted to dom tree and returned. If the exception
3295: * message is a plain text, the whole exception is converted as a
3296: * dom tree of component result xml fragment
3297: * @param compName jbi component name
3298: * @param taskId task id
3299: * @param ex exception to convert to xml fragment
3300: * @return dom tree with component-task-result as its root element.
3301: */
3302: private Element getComponentResultXmlFragment(String compName,
3303: String taskId, Exception ex) {
3304: String exMessage = ex.getMessage();
3305: Element elem = null;
3306: try {
3307: DocumentBuilderFactory dbf = DocumentBuilderFactory
3308: .newInstance();
3309: DocumentBuilder db = dbf.newDocumentBuilder();
3310: Document doc = db.parse(new InputSource(new StringReader(
3311: exMessage)));
3312: elem = DOMUtil.UTIL
3313: .getElement(doc, "component-task-result");
3314: } catch (Exception e) {
3315: elem = buildComponentExMsg(taskId, compName, ex);
3316: }
3317: return elem;
3318: }
3319:
3320: /**
3321: * This method is used to disable statistics collection in
3322: * deployment service
3323: */
3324: public void disableStatistics() {
3325: mStatisticsEnabled = false;
3326: }
3327:
3328: /**
3329: * This method is used to enable statistics collection in
3330: * deployment service
3331: */
3332: public void enableStatistics() {
3333: mStatisticsEnabled = true;
3334: }
3335:
3336: /**
3337: * This method is used to enable statistics collection in
3338: * deployment service
3339: */
3340: public boolean isStatisticsEnabled() {
3341: return mStatisticsEnabled;
3342: }
3343:
3344: /**
3345: * This method is used to update SA statistics for the given SA
3346: * @param saName sa name
3347: * @param operation operation name
3348: * @param beginTime time when the operation was begun
3349: * @param endTime time when the operation was finished
3350: * @param suTimes map of su names to time taken for su operation
3351: *
3352: */
3353: private void updateStatistics(String saName, String operationName,
3354: Date beginTime, Date endTime, Map<String, Long> suTimes) {
3355:
3356: if (!mStatisticsEnabled) {
3357: return;
3358: }
3359: try {
3360: if (!mServiceAssemblyStats.containsKey(saName)) {
3361: mServiceAssemblyStats.put(saName,
3362: createNewSAStatsObject(saName));
3363: }
3364: ServiceAssemblyStatistics saStats = mServiceAssemblyStats
3365: .get(saName);
3366: if (saStats != null) {
3367: if (operationName.equals(START)) {
3368: mLogger
3369: .finer("Updating startup statistics for service assembly "
3370: + saName);
3371: saStats.updateStartupStatistics(beginTime, endTime,
3372: suTimes);
3373: } else if (operationName.equals(STOP)) {
3374: mLogger
3375: .finer("Updating stop statistics for service assembly "
3376: + saName);
3377: saStats.updateStopStatistics(beginTime, endTime,
3378: suTimes);
3379: } else if (operationName.equals(SHUTDOWN)) {
3380: mLogger
3381: .finer("Updating shutdown statistics for service assembly "
3382: + saName);
3383: saStats.updateShutdownStatistics(beginTime,
3384: endTime, suTimes);
3385: }
3386: }
3387: } catch (Exception ex) {
3388: //we catch all the exceptions here because we do not want a failure in statistics
3389: //collection to affect the normal runtime processing
3390: String message = mTranslator
3391: .getString(
3392: LocalStringKeys.DS_ERROR_IN_COLLECTING_STATISTICS_FOR_SA,
3393: new Object[] { saName });
3394: mLogger.warning(message);
3395: String exceptionMsg = ex.getMessage();
3396: if (exceptionMsg != null) {
3397: mLogger.warning(exceptionMsg);
3398: }
3399: }
3400: }
3401:
3402: /**
3403: * This method is used to create a new ServiceAssembly statistics
3404: * object
3405: * @param saName the service assembly name
3406: * @return ServiceAssemblyStatistics SA stats object
3407: */
3408: private ServiceAssemblyStatistics createNewSAStatsObject(
3409: String saName) {
3410: mLogger
3411: .finer("Creating a new statistics object for service assembly "
3412: + saName);
3413: ServiceAssemblyInfo saInfo;
3414: String instanceName;
3415: ServiceAssemblyStatistics saStats = null;
3416: try {
3417: saInfo = getServiceAssemblyInfo(saName);
3418: instanceName = mEnv.getPlatformContext().getInstanceName();
3419: saStats = new ServiceAssemblyStatistics(saName,
3420: instanceName);
3421: List<ServiceUnitInfo> suInfoList = saInfo
3422: .getServiceUnitList();
3423:
3424: Map<String, ServiceAssemblyStatistics.ServiceUnitStatistics> suList = new HashMap<String, ServiceAssemblyStatistics.ServiceUnitStatistics>();
3425:
3426: for (ServiceUnitInfo suInfo : suInfoList) {
3427: ServiceAssemblyStatistics.ServiceUnitStatistics suStat = saStats.new ServiceUnitStatistics(
3428: suInfo.getName());
3429:
3430: //todo get a list of endpoint names
3431: suStat.setEndpointsList(new ArrayList<String>());
3432: suList.put(suInfo.getName(), suStat);
3433: }
3434: saStats.setServiceUnitList(suList);
3435: } catch (Exception ex) {
3436: //getServiceAssemblyInfo throws Exception
3437: mLogger.warning(ex.getMessage());
3438: return saStats;
3439: }
3440: return saStats;
3441: }
3442:
3443: /**
3444: * This method is used to get statistics for the given SA
3445: * @param saName the servie assembly name
3446: * @return ServiceAssemblyStatistics sa Stats
3447: * @throws RuntimeException is statistics for this SA are not available
3448: */
3449: public ServiceAssemblyStatistics getServiceAssemblyStatistics(
3450: String saName) throws RuntimeException {
3451: mLogger.finer("Getting statistics for service assembly "
3452: + saName);
3453: ServiceAssemblyStatistics saStats = mServiceAssemblyStats
3454: .get(saName);
3455: if (saStats == null) {
3456: String message = mTranslator.getString(
3457: LocalStringKeys.DS_NO_STATS_FOR_SA,
3458: new Object[] { saName });
3459: mLogger.warning(message);
3460: throw new RuntimeException();
3461: }
3462: return saStats;
3463: }
3464:
3465: /**
3466: * This method is used to remove the statistics object of the given SA.
3467: * This object is removed after a SA is undeployed.
3468: * @param saName the service assembly name
3469: */
3470: public void removeStatsObject(String saName) {
3471: mLogger
3472: .finer("Removing statistics object for service assembly "
3473: + saName);
3474: if (mServiceAssemblyStats != null) {
3475: mServiceAssemblyStats.remove(saName);
3476: }
3477: }
3478:
3479: /**
3480: * Bring all Service Assemblies to their desired states. This is done
3481: * only during startup of the runtime, after all components have been
3482: * brought to their desired states. Any failures that occur here are
3483: * logged.
3484: *
3485: * Note: There is a requirement in the JSR208 specification that all
3486: * Service Units must be initialized during startup of the runtime to
3487: * eliminate the need for components to persist SU information. This
3488: * means that for any SUs whose containing SA has a desired state of
3489: * "Shutdown", the SU must be shut down after it is initialized. Here
3490: * is the text from the JSR208 specification:
3491: *
3492: * <code>
3493: * JBI implementations MUST retain the running state of all service unit
3494: * deployments, such that the system can be restarted from a shutdown or
3495: * crash, and all deployments will be restored to their previous running
3496: * state. During component restart, the implementation MUST perform the
3497: * following to restore a service unit to its previous state:
3498: * <ul>
3499: * <li>
3500: * Started. The implementation MUST call init(), followed by start().
3501: * </li>
3502: * <li>
3503: * Stopped. The implementation MUST call init() to restore a service
3504: * unit to the stopped state.
3505: * </li>
3506: * <li>
3507: * Shutdown. The implementation MUST call init() followed by shutDown()
3508: * to restore a service unit to the shutdown state.
3509: * </li>
3510: * In all cases of state restoration, the implementation MUST call init()
3511: * for all service units in the group being restored before any other life
3512: * cycle methods for service units in the group are called
3513: * </code>
3514: *
3515: * In support of the above requirement, this method first initializes ALL
3516: * deployed Service Assemblies. After that, all deployed SAs are brought to
3517: * their desired states, either "Shutdown", "Stopped", or "Started".
3518: */
3519: public void startAllServiceAssemblies() {
3520: // First get a list of all deployed service assemblies
3521:
3522: ServiceAssemblyQuery saQuery = null;
3523: List<String> saNamesList;
3524: try {
3525: saQuery = getRegistry().getServiceAssemblyQuery();
3526: saNamesList = saQuery.getServiceAssemblies();
3527:
3528: } catch (Exception e) {
3529: String errMsg = mTranslator
3530: .getString(LocalStringKeys.DS_UNABLE_TO_FIND_DEPLOYED_SERVICE_ASSEMBLY_NAMES);
3531: mLogger.log(Level.WARNING, errMsg, e);
3532: saNamesList = new ArrayList();
3533: }
3534:
3535: // Now get a list of deployed service assemblies that need to be
3536: // shut down or started. Note that service assemblies with a desired
3537: // state of "stopped" will be handled by initializing them. The list
3538: // is a map of service assembly names to their desired states. We have
3539: // to capture their states here because the init processing updates
3540: // their states.
3541:
3542: HashMap<String, ServiceAssemblyState> saList = new HashMap();
3543: for (String name : saNamesList) {
3544: ServiceAssemblyInfo saInfo = saQuery
3545: .getServiceAssemblyInfo(name);
3546: if (saInfo.getStatus() != ServiceAssemblyState.STOPPED) {
3547: saList.put(name, saInfo.getStatus());
3548: mLogger.fine("Service Assembly " + name
3549: + " with state " + saInfo.getStatus()
3550: + " added to start/shutdown list");
3551: }
3552: }
3553:
3554: int successCount = 0;
3555: int failureCount = 0;
3556:
3557: // Now, initialize all deployed service assemblies
3558:
3559: mLogger.fine("Initializing " + saNamesList.size()
3560: + " Service Assemblies");
3561: for (String name : saNamesList) {
3562: ServiceAssemblyInfo info = saQuery
3563: .getServiceAssemblyInfo(name);
3564: try {
3565: mLogger.fine("Initializing Service Assembly " + name);
3566: initServiceAssembly(name);
3567: } catch (Exception e) {
3568: // convert exception message to text and log it
3569: ++failureCount;
3570: String msg = MessageHelper.getMsgString(e);
3571: mLogger.log(Level.WARNING, msg, e);
3572: }
3573: }
3574:
3575: // Finally, bring all service assemblies in the start/shutdown list
3576: // to the appropriate states
3577:
3578: Iterator<Map.Entry<String, ServiceAssemblyState>> sa = saList
3579: .entrySet().iterator();
3580: while (sa.hasNext()) {
3581: Map.Entry<String, ServiceAssemblyState> entry = (Map.Entry) sa
3582: .next();
3583: String saName = entry.getKey();
3584: ServiceAssemblyState saState = entry.getValue();
3585: try {
3586: if (saState == ServiceAssemblyState.SHUTDOWN) {
3587: mLogger.finer("Shutting down Service Assembly "
3588: + saName);
3589: shutDown(saName);
3590: } else if (saState == ServiceAssemblyState.STARTED) {
3591: mLogger
3592: .finer("Activating Connections for Service Assembly "
3593: + saName);
3594: activateConnections(saName);
3595: mLogger
3596: .finer("Starting Service Assembly "
3597: + saName);
3598: startServiceAssembly(saName);
3599: }
3600: ++successCount;
3601: } catch (Exception e) {
3602: // convert exception message to text and log it
3603: ++failureCount;
3604: String msg = MessageHelper.getMsgString(e);
3605: mLogger.log(Level.WARNING, msg, e);
3606: }
3607: }
3608: mLogger.info(mTranslator.getString(
3609: LocalStringKeys.DS_SA_STARTUP_SUCCESS, successCount));
3610: if (0 < failureCount) {
3611: mLogger
3612: .warning(mTranslator.getString(
3613: LocalStringKeys.DS_SA_STARTUP_ERRORS,
3614: failureCount));
3615: }
3616: }
3617:
3618: /**
3619: * Initialize a Service Assembly. All the Service Units of this Service
3620: * Assembly that satisfy the following criteria are initialized:
3621: * <li>
3622: * <ul> the service unit is deployed </ul>
3623: * <ul> the service unit is not already initialized </ul>
3624: * <ul> the target component is installed </ul>
3625: * <ul> the target component is not in the "Shutdown" state </ul>
3626: * </li>
3627: * </br>
3628: * This operation first filters out the Service Units to be initialized.
3629: *
3630: * @param saName - name of service assembly to be targeted
3631: */
3632: String initServiceAssembly(String saName) throws Exception {
3633: String saLifecycleMthdName = "init";
3634: List cmpTaskRslts = new ArrayList();
3635: boolean saStateChangeRslt = true;
3636:
3637: try {
3638: int operationCount = 0;
3639: int successCount = 0;
3640:
3641: ServiceAssemblyInfo saInfo = getServiceAssemblyInfo(saName);
3642: List<ServiceUnitInfo> suList = saInfo.getServiceUnitList();
3643: List<ServiceUnitInfo> susToInitialize = new ArrayList();
3644:
3645: if (isServiceAssemblyEmpty(saName)) {
3646: getRegistry().getUpdater().setServiceAssemblyState(
3647: ServiceAssemblyState.STOPPED, saName);
3648: return buildResponse(cmpTaskRslts, saStateChangeRslt,
3649: saLifecycleMthdName, saName);
3650: }
3651: for (ServiceUnitInfo su : suList) {
3652: String suName = su.getName();
3653: String compName = su.getTargetComponent();
3654: try {
3655: if (!isDeployedServiceUnit(compName, suName)) {
3656: mLogger
3657: .fine("Service unit "
3658: + suName
3659: + " is not deployed to component "
3660: + compName
3661: + " : ignoring init request");
3662: continue;
3663: }
3664: ComponentState cmpState = getComponentState(compName);
3665: if (cmpState == ComponentState.UNKNOWN) {
3666: String errMsg = mTranslator
3667: .getString(
3668: LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_NOT_INSTALLED,
3669: suName, compName);
3670: mLogger.warning(errMsg);
3671: } else if (cmpState == ComponentState.SHUTDOWN) {
3672: // this counts as a failed operation, increment counter
3673: ++operationCount;
3674: String errMsg = mTranslator
3675: .getString(
3676: LocalStringKeys.DS_CANNOT_CHANGE_SU_STATE_COMP_IN_INCORRECT_STATE,
3677: suName, compName);
3678: mLogger.warning(errMsg);
3679: }
3680: } catch (Exception e) {
3681: Element elem = getComponentResultXmlFragment(
3682: compName, saLifecycleMthdName, e);
3683: cmpTaskRslts.add(elem);
3684: // Stop processing and try to change the state
3685: // of the next SU in the SA.
3686: continue;
3687: }
3688: ServiceUnitState currSuState = getActualServiceUnitState(
3689: compName, suName);
3690: if (ServiceUnitState.SHUTDOWN == currSuState) {
3691: susToInitialize.add(su);
3692: }
3693: }
3694:
3695: // Now initialize all the service units that need to be initialized.
3696:
3697: for (ServiceUnitInfo su : susToInitialize) {
3698: String suName = su.getName();
3699: String compName = su.getTargetComponent();
3700: try {
3701: // -- increment op counter for each su life cycle operation
3702: ++operationCount;
3703: DeployerMBean deployer = getComponentDeployerInstance(compName);
3704: deployer.init(su.getName(), su.getFilePath());
3705: } catch (Exception e) {
3706: Element elem = getComponentResultXmlFragment(
3707: compName, saLifecycleMthdName, e);
3708: cmpTaskRslts.add(elem);
3709: }
3710: }
3711:
3712: // Init is successful if at least one operation succeeds
3713: if (operationCount > 0 && successCount == 0) {
3714: saStateChangeRslt = false;
3715: }
3716: } catch (Exception e) {
3717: String errMsg = mTranslator
3718: .getString(
3719: LocalStringKeys.DS_CANNOT_CHANGE_SERVICE_ASSEMBLY_STATE,
3720: saName);
3721: String jbiTaskStr = buildFrmwkExMsg(saLifecycleMthdName, e,
3722: errMsg);
3723: throw new Exception(jbiTaskStr);
3724: }
3725:
3726: String resp = buildResponse(cmpTaskRslts, saStateChangeRslt,
3727: saLifecycleMthdName, saName);
3728:
3729: if (!saStateChangeRslt) {
3730: // operation failed completely, throw an exception with result text
3731: throw new Exception(resp);
3732: }
3733: return resp;
3734: }
3735: }
|