0001: /**
0002: * $Id: AdminBaseCommand.java,v 1.43 2007/01/26 03:47:13 portalbld Exp $
0003: * Copyright 2004 Sun Microsystems, Inc. All
0004: * rights reserved. Use of this product is subject
0005: * to license terms. Federal Acquisitions:
0006: * Commercial Software -- Government Users
0007: * Subject to Standard License Terms and
0008: * Conditions.
0009: *
0010: * Sun, Sun Microsystems, the Sun logo, and Sun ONE
0011: * are trademarks or registered trademarks of Sun Microsystems,
0012: * Inc. in the United States and other countries.
0013: */package com.sun.portal.admin.cli.commands;
0014:
0015: import java.io.*;
0016:
0017: import java.lang.IllegalArgumentException;
0018:
0019: import java.util.logging.Logger;
0020: import java.util.logging.Level;
0021: import java.util.LinkedList;
0022: import java.util.TreeSet;
0023: import java.util.HashSet;
0024: import java.util.Vector;
0025: import java.util.Set;
0026: import java.util.HashMap;
0027: import java.util.Map;
0028: import java.util.ArrayList;
0029: import java.util.List;
0030: import java.util.StringTokenizer;
0031: import java.util.Properties;
0032: import java.text.MessageFormat;
0033: import java.util.Iterator;
0034: import java.util.Locale;
0035:
0036: import java.net.UnknownHostException;
0037:
0038: // JMX
0039: import javax.management.*;
0040: import javax.management.remote.JMXConnector;
0041:
0042: // Admin Common
0043: import com.sun.portal.admin.common.context.PSConfigContext;
0044: import com.sun.portal.admin.common.context.PSConfigContextImpl;
0045: import com.sun.portal.admin.common.util.AdminClientUtil;
0046: import com.sun.portal.admin.common.InstanceAttributes;
0047: import com.sun.portal.log.common.PortalLogManager;
0048: import com.sun.portal.log.common.PortalLogger;
0049: import com.sun.portal.admin.common.PSMBeanException;
0050: import com.sun.portal.admin.common.util.AdminUtil;
0051: import com.sun.portal.admin.cli.commands.sra.GenericSRACommand;
0052:
0053: import com.sun.portal.fabric.util.FileUtil;
0054: import com.sun.portal.util.Platform;
0055:
0056: // CLI framework
0057: import com.sun.enterprise.cli.framework.*;
0058:
0059: /**
0060: * This is the base class for all psadmin utility's subcommands. This
0061: * class defines the common options that are used by all of the
0062: * psadmin subcommands and also defines convenient methods that can be
0063: * called by all the subcommand classes.
0064: */
0065: public abstract class AdminBaseCommand extends Command implements
0066: AdminCLIConstants {
0067: public static String cliLogFileName;
0068: public static String mbeanLogFileName;
0069: public static final String FS = Platform.fs;
0070:
0071: private String pasHost;
0072: private String pasDomain;
0073:
0074: // Name of the connection property file
0075: public static final String PAS_SETTINGS_FILE = "pasconnect.properties";
0076:
0077: private CommandEnvironment cenv = CommandEnvironment.getInstance();
0078:
0079: static {
0080: // Initialize logging for CLI
0081: PortalLogManager manager = new PortalLogManager();
0082: manager.init("debug.com.sun.portal.admin.cli");
0083: try {
0084: cliLogFileName = manager
0085: .getLogFileName("debug.com.sun.portal.admin.cli");
0086: mbeanLogFileName = manager
0087: .getLogFileName("debug.com.sun.portal");
0088: } catch (Exception fe) {
0089: //System.out.println("file not found");
0090: }
0091:
0092: }
0093: public static Logger logger = PortalLogger
0094: .getLogger(AdminBaseCommand.class);
0095:
0096: public final static String INTERACTIVE = "interactive";
0097: public final static String OBJECT_NAME = "objectname";
0098: public final static String RESOURCE_ID = "resourceid";
0099: public final static String RESOURCE_TYPE = "resourcetype";
0100: public final static String DOMAIN_MBEAN_OBJECT_NAME = "DomainMBeanObjectName";
0101: public final static String PORTAL_MBEAN_OBJECT_NAME = "PortalMBeanObjectName";
0102: public final static String INSTANCE_MBEAN_OBJECT_NAME = "InstanceMBeanObjectName";
0103: public final static String DOMAIN_RESOURCE_MBEAN_OBJECT_NAME = "DomainResourceMBeanObjectName";
0104: public final static String PORTAL_RESOURCE_MBEAN_OBJECT_NAME = "PortalResourceMBeanObjectName";
0105: public final static String INSTANCE_RESOURCE_MBEAN_OBJECT_NAME = "InstanceResourceMBeanObjectName";
0106:
0107: public final static String OPERATION = "operation";
0108: public final static String PARAMS = "params";
0109: public final static String PARAM_TYPES = "paramtypes";
0110: public final static String RETURN_TYPE = "returntype";
0111: public final static String DISPLAY_TYPE = "displaytype";
0112: public final static String ATTRIBUTE_LIST_CLASS = AttributeList.class
0113: .getName();
0114: public final static String PROPERTIES_CLASS = Properties.class
0115: .getName();
0116: public final static String BOOLEAN_CLASS = Boolean.class.getName();
0117: public final static String PRIMITIVE_BOOLEAN_CLASS = boolean.class
0118: .getName();
0119: public final static String STRING_ARRAY = (new String[] {})
0120: .getClass().getName();
0121: public final static String INTEGER_CLASS = Integer.class.getName();
0122: public final static String LIST_CLASS = List.class.getName();
0123:
0124: public final static String PARAM_DELIMITER = ",";
0125: public final static String PARAM_VALUE_DELIMITER = "=";
0126: public final static String PROPERTY_DELIMITER = ":";
0127: public final static String PROPERTY_FILE = "LocalStrings";
0128: public static final String ERROR_GET_INSTANCE_HOST = "error.psadmin.unknown.host";
0129:
0130: protected LocalStringsManager commandLocalStringsManager = null;
0131:
0132: //private member variables
0133: private String m_password;
0134: private String m_instanceId;
0135: private Properties m_webConfigProp;
0136: private String m_portalId;
0137: private String m_domainId;
0138: private String m_portalUri;
0139:
0140: //In multimode environment, m_connector and m_mbsc only needs to
0141: //be initialize once
0142: private static JMXConnector m_connector;
0143: private static MBeanServerConnection m_mbsc;
0144:
0145: public AdminBaseCommand() {
0146: setupPASConnection();
0147: }
0148:
0149: public static Logger getLogger() {
0150: return logger;
0151: }
0152:
0153: /*----------------------------------------------------------------
0154: * Validate methods.
0155: *----------------------------------------------------------------*/
0156: public boolean validateOptions() throws CommandValidationException {
0157: try {
0158: validatePassword();
0159: setOutput();
0160: } catch (Exception e) {
0161: throw new CommandValidationException(e.getMessage());
0162: }
0163: return true;
0164: }
0165:
0166: /**
0167: * Validate the non-sra commands.
0168: *
0169: * If a system has only SRA installed, then only sra, logger, or
0170: * monitoring commands can be executed. If the user attempt to
0171: * execute any other commands, throws exception.
0172: *
0173: * @exception CLIException
0174: */
0175: protected void validateNonSRACommand() throws CommandException {
0176: boolean isLocal = false;
0177: PSConfigContext cc = getPSConfigContext();
0178:
0179: try {
0180: isLocal = getHost().equals(DEFAULT_HOST)
0181: || AdminClientUtil.isLocal(getHost());
0182: } catch (Exception e) {
0183: }
0184:
0185: if (isLocal && cc != null) {
0186: if (AdminClientUtil.isOnlySRAInstalled(cc)) {
0187: if (!(this instanceof GenericSRACommand)
0188: && getName().indexOf("logger") == -1
0189: && getName().indexOf("monitoring") == -1) {
0190: throw new CommandException(
0191: getLocalizedString(ERROR_NON_SRA_VALIDATION_FAILED));
0192: }
0193: }
0194: }
0195: }
0196:
0197: /**
0198: * Validate the sra commands.
0199: *
0200: * If a system does not has SRA installed, and the user attempt to
0201: * execute a sra command, throws exception.
0202: *
0203: * @exception CLIException
0204: */
0205: protected void validateSRACommand() throws CommandException {
0206: boolean isLocal = false;
0207: PSConfigContext cc = getPSConfigContext();
0208: try {
0209: isLocal = getHost().equals(DEFAULT_HOST)
0210: || AdminClientUtil.isLocal(getHost());
0211: } catch (Exception e) {
0212: }
0213:
0214: if (isLocal && cc != null) {
0215: if (!AdminClientUtil.isSRAInstalled(cc)
0216: && (getName().indexOf("sra") != -1)
0217: && (!getName()
0218: .equalsIgnoreCase("switch-sra-status"))) {
0219: throw new CommandException(
0220: getLocalizedString(ERROR_SRA_VALIDATION_FAILED));
0221: }
0222: }
0223: }
0224:
0225: /**
0226: * Loads and validates the passwords from the password file.
0227: *
0228: * This method will read the password from the password file. The
0229: * password should be specified as the following syntax:
0230: * PSADMIN_PASSWORD=<password>
0231: *
0232: * @exception CLIException If password file is not presented,
0233: * is not existed, or is not readable.
0234: */
0235: protected void validatePassword() throws CommandException {
0236: final String passwordFileName = getOption(OPT_PASSWORDFILE);
0237:
0238: if (passwordFileName == null) {
0239: return;
0240: }
0241:
0242: File file = new File(passwordFileName);
0243: if (!file.exists() || !file.canRead()) {
0244: throw new CommandException(getLocalizedString(
0245: ERROR_PASSWORD_FILE_NOT_EXIST_OR_NOT_READABLE,
0246: new Object[] { passwordFileName }));
0247: }
0248:
0249: if (file.exists() && file.length() <= 0) {
0250: throw new CommandException(getLocalizedString(
0251: ERROR_PASSWORD_FILE_SIZE_ZERO,
0252: new Object[] { passwordFileName }));
0253: }
0254:
0255: try {
0256: java.io.BufferedReader reader = new java.io.BufferedReader(
0257: new java.io.FileReader(file));
0258: String line = reader.readLine();
0259: while (line != null) {
0260: line = line.trim();
0261: //do not want to read empty string
0262: if (line.length() > 0) {
0263: m_password = line;
0264: break;
0265: }
0266: line = reader.readLine();
0267: }
0268:
0269: reader.close();
0270: } catch (IOException e) {
0271: throw new CommandException(
0272: getLocalizedString(ERROR_PASSWORD_READ_ERROR));
0273: }
0274: }
0275:
0276: /**
0277: * Validates the portal-id option.
0278: *
0279: * @exception CLIException If the psConfig option is not presented or if the
0280: * format is invalid
0281: */
0282: protected void validatePortalId() throws CommandException {
0283: m_portalId = getOption(OPT_PORTAL_ID);
0284:
0285: if (!(getName().equals("create-portal"))) {
0286: List portalList = getPortalNames();
0287: boolean found = false;
0288: Iterator iter = portalList.iterator();
0289: while (iter.hasNext()) {
0290: String id = (String) iter.next();
0291: if (id.equalsIgnoreCase(m_portalId)) {
0292: found = true;
0293: }
0294: }
0295: if (!found) {
0296: throw new CommandException(
0297: getLocalizedString(ERROR_INVALID_PORTAL_ID));
0298: }
0299: }
0300:
0301: //portalId can be an ASCII alphanumeric string which
0302: //contains only letters, digits and hyphens.
0303: if (m_portalId != null
0304: && m_portalId.matches(".*[^a-zA-Z0-9-].*")) {
0305: throw new CommandException(
0306: getLocalizedString(ERROR_PORTAL_ID_INVALID_FORMAT));
0307: }
0308: }
0309:
0310: /**
0311: * Validates the portal-id option.
0312: *
0313: * @exception CLIException If the psConfig option is not presented or if the
0314: * format is invalid
0315: */
0316: protected void validatePortalUri() throws CommandException {
0317: m_portalUri = getOption(OPT_PORTAL_URI);
0318:
0319: // The uri should start with "/"
0320: if (m_portalUri != null && !m_portalUri.startsWith("/")) {
0321: throw new CommandException(
0322: getLocalizedString(ERROR_PORTAL_URI_INVALID_FORMAT));
0323: }
0324: }
0325:
0326: /**
0327: * Validates the instance option.
0328: *
0329: * @exception CLIException If the psConfig option is not presented or if the
0330: * format is invalid
0331: */
0332: protected void validateInstance() throws CommandException {
0333: String instance = getOption(OPT_INSTANCE_ID);
0334:
0335: List instanceList = getInstanceNames(m_portalId);
0336: if (!instanceList.contains(instance)) {
0337: throw new CommandException(
0338: getLocalizedString(ERROR_INVALID_INSTANCE_ID));
0339: }
0340: }
0341:
0342: /**
0343: * Validates the instance option.
0344: *
0345: * @exception CLIException If the psConfig option is not presented or if the
0346: * format is invalid
0347: */
0348: protected boolean isExistingInstance() throws CommandException {
0349: String instance = getOption(OPT_INSTANCE_ID);
0350:
0351: List instanceList = getInstanceNames(m_portalId);
0352: if (instanceList.contains(instance)) {
0353: return true;
0354: } else {
0355: return false;
0356: }
0357: }
0358:
0359: /**
0360: * Validates the searchserver-id option.
0361: *
0362: * @exception CLIException If the psConfig option is not presented or if the
0363: * format is invalid
0364: */
0365: protected void validateSearchServerID() throws CommandException {
0366: String option = getOption(OPT_SEARCHSERVER_ID);
0367:
0368: List l = getSearchServers();
0369: boolean found = false;
0370: Iterator i = l.iterator();
0371: while (i.hasNext()) {
0372: String id = (String) i.next();
0373: if (id.equalsIgnoreCase(option)) {
0374: found = true;
0375: }
0376: }
0377: if (!found) {
0378: throw new CommandException(
0379: getLocalizedString(ERROR_INVALID_SEARCHSERVER_ID));
0380: }
0381: }
0382:
0383: /*----------------------------------------------------------------
0384: * Get option methods.
0385: *----------------------------------------------------------------*/
0386:
0387: /**
0388: * Gets the admin user id.
0389: *
0390: * @return The admin user id.
0391: */
0392: protected String getUserId() {
0393: return getOption(OPT_ADMIN_USER);
0394: }
0395:
0396: /**
0397: * Gets the admin user password.
0398: *
0399: * @return The admin user password.
0400: */
0401: protected String getPassword() throws CommandValidationException {
0402: if (m_password == null) {
0403: m_password = getInteractiveOption(OPT_PASSWORDFILE,
0404: getLocalizedString(PASSWORD_PROMPT), true);
0405: }
0406: return m_password;
0407: }
0408:
0409: /**
0410: * If interactive is true, then prompt the user for the option value.
0411: * @param optionName - name of option.
0412: * @param prompt -- the string that will be used to prompt the user
0413: * @throws CommandException if option value cannot be read in interactive mode.
0414: * @throws CommandValidationException is interactive is false and the option
0415: * value is null.
0416: * @return option value
0417: */
0418: protected String getInteractiveOption(String optionName,
0419: String prompt, boolean interactive)
0420: throws CommandValidationException {
0421: String optionValue = getOption(optionName);
0422: //if option value is null and interactive option is true
0423: //then prompt the user for the password.
0424: if (optionValue == null && interactive) {
0425: try {
0426: InputsAndOutputs.getInstance().getUserOutput().print(
0427: prompt);
0428: optionValue = new CliUtil().getPassword();
0429: } catch (java.lang.NoClassDefFoundError e) {
0430: optionValue = readInput();
0431: } catch (java.lang.UnsatisfiedLinkError e) {
0432: optionValue = readInput();
0433: } catch (Exception e) {
0434: throw new CommandValidationException(e);
0435: }
0436: } else if ((optionValue == null) && !interactive)
0437: throw new CommandValidationException(getLocalizedString(
0438: "OptionIsRequired", new Object[] { optionName }));
0439: return optionValue;
0440: }
0441:
0442: /**
0443: * Get input from user.
0444: */
0445: private String readInput() {
0446: try {
0447: return InputsAndOutputs.getInstance().getUserInput()
0448: .getLine();
0449: } catch (IOException ioe) {
0450: return null;
0451: }
0452: }
0453:
0454: /**
0455: * Gets the host name.
0456: *
0457: * If --hostname is given, use it; else check if pasHost is set in
0458: * the pasconnect.properties file; else return localhost.
0459: *
0460: * @return The host name.
0461: */
0462: protected String getHost() {
0463: String host = null;
0464: if (getOption(OPT_HOST) == null) {
0465: host = pasHost;
0466: } else {
0467: host = getOption(OPT_HOST);
0468: }
0469: if (host == null || host.length() == 0) {
0470: host = DEFAULT_HOST;
0471: }
0472: return host;
0473: }
0474:
0475: /**
0476: * Gets the Portal ID.
0477: *
0478: * @return The Portal ID.
0479: */
0480: protected String getPortalId() {
0481:
0482: return getOption(OPT_PORTAL_ID);
0483: }
0484:
0485: /**
0486: * Gets the Portal URI.
0487: *
0488: * @return The Portal URI.
0489: */
0490: protected String getPortalUri() {
0491:
0492: return getOption(OPT_PORTAL_URI) != null ? getOption(OPT_PORTAL_URI)
0493: : "/portal";
0494: }
0495:
0496: /**
0497: * Gets the Portal Domain ID.
0498: *
0499: * @return The Portal ID.
0500: */
0501: protected String getDomainId() {
0502:
0503: if (pasDomain == null || pasDomain.length() == 0) {
0504:
0505: pasDomain = getOption(OPT_DOMAIN_ID) != null ? getOption(OPT_DOMAIN_ID)
0506: : AdminClientUtil.DEFAULT_DOMAIN;
0507: }
0508:
0509: return pasDomain;
0510: }
0511:
0512: /**
0513: * Gets the Search Server ID.
0514: *
0515: * @return The Search Server ID.
0516: */
0517: protected String getSearchServerId() {
0518: return getOption(OPT_SEARCHSERVER_ID) != null ? getOption(OPT_SEARCHSERVER_ID)
0519: : "";
0520: }
0521:
0522: /**
0523: * Gets the Portal Server Instance ID.
0524: *
0525: * @return The Portal ID.
0526: */
0527: protected String getInstanceId() {
0528:
0529: return getOption(OPT_INSTANCE_ID);
0530: }
0531:
0532: /**
0533: * Gets the web configuration properties.
0534: *
0535: * @return The <code>Properties</code> object of the web configuration
0536: * properties.
0537: */
0538: protected Properties getWebConfigProp() throws CommandException {
0539: String webConfig = getOption(OPT_WEB_CONFIG);
0540: if (webConfig == null) {
0541: throw new CommandException(getLocalizedString(
0542: ERROR_FILE_NOT_FOUND, new Object[] { webConfig }));
0543: }
0544: return createPropertiesParam(webConfig);
0545: }
0546:
0547: /**
0548: * For an given option, gets the string value, and returns a list
0549: * of values.
0550: * <p>
0551: * The syntax for the string value is: '"val1" "val2" "val3"',
0552: * and the returned values will be: "val1","val2","val3". If the
0553: * option has only one value, that value will be returned in the List.
0554: *
0555: * @return The <code>List</code> object of multiple strings.
0556: */
0557: protected List getMultiValueOption(String optionName)
0558: throws CommandException {
0559: return getMultiValueFromString(getOption(optionName));
0560: }
0561:
0562: /**
0563: * For an given <code>String</code>, returns a list of
0564: * values.
0565: * <p>
0566: * The syntax for the String is: '"val1" "val2" "val3"',
0567: * and the returned values will be: "val1","val2","val3". If the
0568: * option has only one value, that value will be returned in the List.
0569: *
0570: * @return The <code>List</code> object of multiple strings.
0571: */
0572: protected List getMultiValueFromString(String value)
0573: throws CommandException {
0574: List valueList = new ArrayList();
0575: if (value != null) {
0576: CLITokenizer ct = new CLITokenizer(value, " ");
0577: while (ct.hasMoreTokens()) {
0578: valueList.add(ct.nextTokenWithoutEscapeAndQuoteChars());
0579: }
0580: }
0581: return valueList;
0582: }
0583:
0584: /**
0585: * Checks if psadmin is connecting a remote PAS.
0586: *
0587: * This method does not throw exception in case of error, it will
0588: * return true and assume the cacao server is running on the
0589: * local host.
0590: */
0591: protected boolean isLocal() {
0592: boolean isLocal = true;
0593: try {
0594: isLocal = AdminUtil.isLocal(getHost());
0595: } catch (UnknownHostException ue) {
0596: //do nothing
0597: }
0598: return isLocal;
0599: }
0600:
0601: /*----------------------------------------------------------------
0602: * Miscellaneous methods.
0603: *----------------------------------------------------------------*/
0604:
0605: public void setEnvironment(String opt, String value) {
0606: cenv.setEnvironment(opt, value);
0607: }
0608:
0609: public Object getAttribute(MBeanServerConnection mbs,
0610: ObjectName obj, String attribute) {
0611: try {
0612: return mbs.getAttribute(obj, attribute);
0613: } catch (Exception e) {
0614: logger.log(Level.SEVERE,
0615: "Failed to get mbean server attribute.", e);
0616: return null;
0617: }
0618: }
0619:
0620: protected List getPortalNames() throws CommandException {
0621:
0622: List pNames = new ArrayList();
0623:
0624: try {
0625: m_mbsc = getMBeanServerConnection(getUserId(),
0626: getPassword(), getHost());
0627:
0628: ObjectName portalPat = AdminClientUtil
0629: .getPortalsPattern(AdminClientUtil.DEFAULT_DOMAIN);
0630: Set objNames = m_mbsc.queryNames(portalPat, null);
0631: Iterator iter = objNames.iterator();
0632: while (iter.hasNext()) {
0633: pNames.add(getAttribute(m_mbsc, (ObjectName) iter
0634: .next(), "ID"));
0635: }
0636: } catch (CommandException ce) {
0637: throw ce;
0638: } catch (Exception ex) {
0639: logger.log(Level.SEVERE, "PSALI_CSPACC0010", ex);
0640: throw new CommandException(
0641: getLocalizedString(ERROR_GET_PORTALS));
0642: }
0643: return pNames;
0644: }
0645:
0646: protected List getInstanceNames(String portalId)
0647: throws CommandException {
0648:
0649: List iNames = new ArrayList();
0650:
0651: try {
0652: m_mbsc = getMBeanServerConnection(getUserId(),
0653: getPassword(), getHost());
0654:
0655: ObjectName instancePat = AdminClientUtil
0656: .getPortalServerInstancesPattern(
0657: AdminClientUtil.DEFAULT_DOMAIN, portalId);
0658: Set objNames = m_mbsc.queryNames(instancePat,
0659: new ObjectName(""));
0660: Iterator iter = objNames.iterator();
0661: while (iter.hasNext()) {
0662: String instance = (String) m_mbsc.getAttribute(
0663: (ObjectName) iter.next(), "ID");
0664: iNames.add(instance);
0665: }
0666: } catch (CommandException ce) {
0667: throw ce;
0668: } catch (Exception ex) {
0669: logger.log(Level.SEVERE, "PSALI_CSPACC0010", ex);
0670: Object tokens[] = new Object[] { portalId };
0671: throw new CommandException(getLocalizedString(
0672: ERROR_GET_INSTANCES, tokens));
0673: }
0674: return iNames;
0675: }
0676:
0677: /**
0678: * Get all hosts that has portal instances for this portal.
0679: */
0680: public Set getInstanceHosts(MBeanServerConnection msc,
0681: String portalId) throws CommandException {
0682: List instances = getInstanceNames(portalId);
0683: Set hosts = new TreeSet();
0684: Iterator it = instances.iterator();
0685: try {
0686: while (it.hasNext()) {
0687: String instance = (String) it.next();
0688:
0689: // gets instance object name
0690: ObjectName iObjectName = AdminClientUtil
0691: .getInstanceMBeanObjectName(getDomainId(),
0692: portalId, instance);
0693: String host = (String) msc.getAttribute(iObjectName,
0694: "Host");
0695:
0696: if (!hosts.contains(host)) {
0697: hosts.add(host);
0698: }
0699: }
0700: } catch (Exception ex) {
0701: logger.log(Level.SEVERE, "PSALI_CSPACC0010", ex);
0702: Object tokens[] = { portalId };
0703: throw new CommandException(getLocalizedString(
0704: ERROR_GET_INSTANCE_HOST, tokens));
0705: }
0706: return hosts;
0707: }
0708:
0709: protected List getSearchServers() throws CommandException {
0710: List l = new ArrayList();
0711: try {
0712: MBeanServerConnection msc = getMBeanServerConnection(
0713: getUserId(), getPassword(), getHost());
0714:
0715: ObjectName on = AdminClientUtil
0716: .getSearchServerPattern(AdminClientUtil.DEFAULT_DOMAIN);
0717: Set objects = msc.queryNames(on, new ObjectName(""));
0718:
0719: Iterator i = objects.iterator();
0720: while (i.hasNext()) {
0721: on = (ObjectName) i.next();
0722: String searchServerID = (String) msc.getAttribute(on,
0723: "ID");
0724: l.add(searchServerID);
0725: }
0726: } catch (CommandException ce) {
0727: throw ce;
0728: } catch (Exception ex) {
0729: throw new CommandException(
0730: getLocalizedString(ERROR_GET_SEARCHSERVERS));
0731: }
0732: return l;
0733: }
0734:
0735: /**
0736: * This method uses the local LocalStringManager object to get
0737: * the localized string. If not found in the local
0738: * LocalStringsManager (Key not found), then get the message from
0739: * the framework command LocalStringsManager.
0740: *
0741: * @param key, the string to be localized
0742: */
0743: protected String getLocalizedString(String key) {
0744: String retStr = LocalStringsManager.DEFAULT_STRING_VALUE;
0745: try {
0746: if (commandLocalStringsManager != null) {
0747: retStr = commandLocalStringsManager.getString(key);
0748: }
0749:
0750: if (retStr.equals(LocalStringsManager.DEFAULT_STRING_VALUE)) {
0751: LocalStringsManager lsm = LocalStringsManagerFactory
0752: .getCommandLocalStringsManager();
0753: retStr = lsm.getString(key);
0754: }
0755: } catch (CommandValidationException ce) {
0756: //return default string
0757: }
0758:
0759: return retStr;
0760:
0761: }
0762:
0763: /**
0764: * This method uses the local LocalStringsManager object to get
0765: * the localized string. If not found in the local
0766: * LocalStringsManager (Key not found), then get the message from
0767: * the framework command LocalStringsManager.
0768: *
0769: * @param key, the string to be localized
0770: * @param toInsert, the strings to be inserted in the placeholders
0771: */
0772: protected String getLocalizedString(String key, Object[] toInsert) {
0773: String retStr = LocalStringsManager.DEFAULT_STRING_VALUE;
0774: try {
0775: if (commandLocalStringsManager != null) {
0776: retStr = commandLocalStringsManager.getString(key,
0777: toInsert);
0778: }
0779: if (retStr.equals(LocalStringsManager.DEFAULT_STRING_VALUE)) {
0780: LocalStringsManager lsm = LocalStringsManagerFactory
0781: .getCommandLocalStringsManager();
0782: retStr = lsm.getString(key, toInsert);
0783: }
0784: } catch (CommandValidationException ce) {
0785: //return default string
0786: }
0787:
0788: return retStr;
0789: }
0790:
0791: /**
0792: * If output option is set, set output to the file, otherwise set
0793: * output to standard output.
0794: *
0795: */
0796: protected void setOutput() {
0797: InputsAndOutputs inAndOut = InputsAndOutputs.getInstance();
0798: String output = getOption(OPT_OUTPUT);
0799:
0800: try {
0801: if (output != null) {
0802: inAndOut.setUserOutputFile(output);
0803: }
0804: } catch (IOException ie) {
0805: CLILogger.getInstance().printDebugMessage(
0806: getLocalizedString(ERROR_OUTPUT));
0807: // use default output
0808: }
0809:
0810: }
0811:
0812: /**
0813: * Gets the ps config context.
0814: *
0815: * @return The <code>PSConfigContext</code> object.
0816: */
0817: protected PSConfigContext getPSConfigContext()
0818: throws CommandException {
0819:
0820: PSConfigContext configCtx = null;
0821: try {
0822: configCtx = new PSConfigContextImpl(
0823: AdminClientUtil.DEFAULT_DOMAIN);
0824: } catch (Exception e) {
0825: throw new CommandException(
0826: getLocalizedString(ERROR_PORTAL_CONFIGURATION));
0827: }
0828:
0829: return configCtx;
0830: }
0831:
0832: /**
0833: * Gets the <code>MBeanServerConntection</code>. Client of this
0834: * method is responsible for calling the
0835: * <code>closeMBeanServerConnection()</code> method
0836: * to close the connection to the <code>MBeanServer</code>.
0837: *
0838: * This method will use the passed in id, password, and host
0839: * information to get authentication from the mbean server
0840: * container and returns the <code>MBeanServerConnection</code>.
0841: *
0842: * @param id The admin user id.
0843: * @param pwd The admin user password.
0844: * @param host The host name from where the
0845: * <code>MBeanServer</code> is running.
0846: *
0847: * @return The <code>MBeanServerConntion</code>
0848: * @exception CommandException If the authentication fails.
0849: */
0850: protected MBeanServerConnection getMBeanServerConnection(String id,
0851: String pwd, String host) throws CommandException {
0852:
0853: validateNonSRACommand();
0854:
0855: if (m_mbsc != null) {
0856: return m_mbsc;
0857: }
0858:
0859: try {
0860: // Unknown connection with our SASL/PLAIN authenticationID
0861: if (m_connector == null) {
0862: m_connector = AdminClientUtil.getJMXConnector(host,
0863: getDomainId(), id, pwd);
0864: }
0865:
0866: m_mbsc = m_connector.getMBeanServerConnection();
0867:
0868: return m_mbsc;
0869: } catch (SecurityException se) {
0870: logger.log(Level.SEVERE, "PSALI_CSPACC0011", se);
0871: throw new CommandException(
0872: getLocalizedString(ERROR_SECURITY_VIOLATION), se);
0873:
0874: } catch (Exception e) {
0875: if (e.getCause() != null
0876: && e.getCause() instanceof SecurityException) {
0877: logger.log(Level.SEVERE, "PSALI_CSPACC0011", e
0878: .getCause());
0879: throw new CommandException(
0880: getLocalizedString(ERROR_SECURITY_VIOLATION), e
0881: .getCause());
0882: } else {
0883: logger.log(Level.SEVERE, "PSALI_CSPACC0010", e);
0884: throw new CommandException(
0885: getLocalizedString(ERROR_CONNECTION_ERROR));
0886: }
0887: }
0888:
0889: }
0890:
0891: /**
0892: * Closes the client connection to its server. Any attempt to use
0893: * the <code>MBeanServerConnection</code> after this call will get
0894: * an exception.
0895: */
0896: protected void closeMBeanServerConnection() throws CommandException {
0897: String multimodeRunning = System
0898: .getProperty(PSADMIN_MULTI_MODE_RUNNING);
0899: boolean isMultimodeRunning = (multimodeRunning == null) ? false
0900: : multimodeRunning.equals("true");
0901:
0902: try {
0903: if (isMultimodeRunning == false && m_connector != null) {
0904: m_connector.close();
0905: m_connector = null;
0906: m_mbsc = null;
0907: }
0908: } catch (IOException ie) {
0909: logger.log(Level.SEVERE, "PSALI_CSPACC0003", ie);
0910: throw new CommandException(
0911: getLocalizedString(ERROR_CLOSING_CONNECTION_ERROR));
0912: }
0913: }
0914:
0915: private void setupPASConnection() {
0916: try {
0917: PSConfigContext cc = getPSConfigContext();
0918: File pf = new File(cc.getPSConfigDir(), PAS_SETTINGS_FILE);
0919: if (!pf.exists()) {
0920: String src = cc.getPSBaseDir() + FS + "template" + FS
0921: + PAS_SETTINGS_FILE;
0922: String des = cc.getPSConfigDir() + FS
0923: + PAS_SETTINGS_FILE;
0924: FileUtil.copyFile(src, des);
0925: }
0926:
0927: FileInputStream fi = new FileInputStream(pf);
0928: Properties pasSettings = new Properties();
0929: if (fi != null) {
0930: pasSettings.load(fi);
0931: pasHost = pasSettings.getProperty("pas.host", "")
0932: .trim();
0933: pasDomain = pasSettings.getProperty("pas.domain", "")
0934: .trim();
0935: fi.close();
0936: }
0937: } catch (Exception e) {
0938: // Cannot load the connection settings file
0939: // Ignore and proceed. psadmin will connect to local mbean server
0940: }
0941: }
0942:
0943: /**
0944: * Check for the existence of the file in the file system
0945: * @param parent - the parent directory containing the file
0946: * @param fileName - the name of the file to check for existence
0947: * @return File handler
0948: */
0949: protected File checkForFileExistence(String parent, String fileName)
0950: throws CommandException {
0951: if (fileName == null)
0952: return null;
0953: File file = null;
0954: if (parent == null)
0955: file = new File(fileName);
0956: else
0957: file = new File(parent, fileName);
0958: if (file.canRead() == false) {
0959: throw new CommandException(getLocalizedString(
0960: "FileDoesNotExist", new Object[] { fileName }));
0961: }
0962: return file;
0963: }
0964:
0965: /*----------------------------------------------------------------
0966: * Methods to handle properties in CLIDescriptor.xml
0967: *----------------------------------------------------------------*/
0968:
0969: /**
0970: * Returns the Object name string from the properties
0971: * @return Object name else returns null
0972: */
0973: protected ObjectName getObjectName() throws CommandException {
0974: final String objectName = (String) ((Vector) getProperty(OBJECT_NAME))
0975: .get(0);
0976: final String objectNameStr = replacePattern(objectName);
0977:
0978: ObjectName on = null;
0979: try {
0980: //if the objectname is a domain mbean, portal mbean, or
0981: // instance mbean.
0982: if (objectNameStr.equals(DOMAIN_MBEAN_OBJECT_NAME)) {
0983: on = AdminClientUtil
0984: .getPortalDomainMBeanObjectName(getDomainId());
0985: } else if (objectNameStr.equals(PORTAL_MBEAN_OBJECT_NAME)) {
0986: on = AdminClientUtil.getPortalMBeanObjectName(
0987: getDomainId(), getPortalId());
0988: } else if (objectNameStr.equals(INSTANCE_MBEAN_OBJECT_NAME)) {
0989: on = AdminClientUtil.getInstanceMBeanObjectName(
0990: getDomainId(), getPortalId(), getInstanceId());
0991: } else {
0992: // if the objectname is a domain resource mbean,
0993: // portal resource mbean, or instance resource mbean
0994: LinkedList path = new LinkedList();
0995:
0996: final String resourceType = (String) ((Vector) getProperty(RESOURCE_TYPE))
0997: .get(0);
0998:
0999: if (objectNameStr
1000: .equals(DOMAIN_RESOURCE_MBEAN_OBJECT_NAME)) {
1001: path.addFirst(getDomainId());
1002: Vector v = (Vector) getProperty(RESOURCE_ID);
1003: for (int i = 0; i < v.size(); i++) {
1004: String resourceId = (String) v.get(i);
1005: resourceId = replacePattern(resourceId);
1006: path.addFirst(resourceId);
1007: }
1008: } else if (objectNameStr
1009: .equals(PORTAL_RESOURCE_MBEAN_OBJECT_NAME)) {
1010: String resourceId = (String) ((Vector) getProperty(RESOURCE_ID))
1011: .get(0);
1012: resourceId = replacePattern(resourceId);
1013:
1014: path.addFirst(getDomainId());
1015: path.addFirst(getPortalId());
1016: path.addFirst(resourceId);
1017: } else if (objectNameStr
1018: .equals(INSTANCE_RESOURCE_MBEAN_OBJECT_NAME)) {
1019: String resourceId = (String) ((Vector) getProperty(RESOURCE_ID))
1020: .get(0);
1021: resourceId = replacePattern(resourceId);
1022:
1023: path.addFirst(getDomainId());
1024: path.addFirst(getPortalId());
1025: path.addFirst(getInstanceId());
1026: path.addFirst(resourceId);
1027: }
1028:
1029: on = AdminClientUtil.getResourceMBeanObjectName(
1030: resourceType, path);
1031: }
1032: if (on == null) {
1033: // otherwise just use the object name string
1034: on = new ObjectName(objectNameStr);
1035: }
1036: } catch (MalformedObjectNameException me) {
1037: throw new CommandException(
1038: getLocalizedString(ERROR_OBJECT_NAME), me);
1039: }
1040:
1041: CLILogger.getInstance().printDebugMessage(
1042: "Object Name = [" + on.toString() + "]");
1043: return on;
1044: }
1045:
1046: /*
1047: * Returns the Params from the properties
1048: * @return params returns params
1049: */
1050: protected Object[] getParamsInfo() throws CommandException,
1051: CommandValidationException {
1052: final Vector params = (Vector) getProperty(PARAMS);
1053: final String[] typesInfo = getTypesInfo();
1054: Object[] paramsInfo = params == null ? null : new Object[params
1055: .size()];
1056: for (int i = 0; params != null && i < params.size(); i++) {
1057: String paramStr = (String) params.get(i);
1058: CLILogger.getInstance().printDebugMessage(
1059: "Types Info [" + i + "] = " + typesInfo[i]);
1060: CLILogger.getInstance().printDebugMessage(
1061: "ATTRIBUTE_LIST_CLASS = "
1062: + this .ATTRIBUTE_LIST_CLASS);
1063: if (typesInfo[i].equals(ATTRIBUTE_LIST_CLASS)) {
1064: paramsInfo[i] = getAttributeList(paramStr);
1065: } else if (typesInfo[i].equals(PROPERTIES_CLASS)) {
1066: paramsInfo[i] = createPropertiesParam((String) params
1067: .get(i));
1068: } else if (typesInfo[i].equals(INTEGER_CLASS)) {
1069: paramsInfo[i] = createIntegerParam((String) params
1070: .get(i));
1071: } else if (typesInfo[i].equals(BOOLEAN_CLASS)) {
1072: if (createBooleanVal((String) params.get(i)) != null)
1073: paramsInfo[i] = createBooleanVal((String) params
1074: .get(i));
1075: } else if (typesInfo[i].equals(LIST_CLASS)) {
1076: paramsInfo[i] = getMultiValueFromString(replacePattern((String) params
1077: .get(i)));
1078: } else if (typesInfo[i].equals(STRING_ARRAY)) {
1079: paramsInfo[i] = createStringArrayParam((String) params
1080: .get(i));
1081: } else {
1082: CLILogger.getInstance().printDebugMessage(
1083: (String) params.get(i));
1084: paramsInfo[i] = replacePattern((String) params.get(i));
1085:
1086: CLILogger.getInstance().printDebugMessage(
1087: "ParamsInfo = " + paramsInfo[i]);
1088: }
1089: }
1090: return paramsInfo;
1091: }
1092:
1093: /*
1094: * Returns the Param types from the properties
1095: * @return paramTypes returns param types
1096: */
1097: protected String[] getTypesInfo() {
1098: Vector typesList = (Vector) getProperty(PARAM_TYPES);
1099: String types[] = typesList == null ? null
1100: : new String[typesList.size()];
1101: CLILogger.getInstance().printDebugMessage("Types = ");
1102: for (int i = 0; typesList != null && i < typesList.size(); i++) {
1103: types[i] = (String) typesList.get(i);
1104: CLILogger.getInstance().printDebugMessage(types[i] + ",");
1105: }
1106: CLILogger.getInstance().printDebugMessage("");
1107: return types;
1108: }
1109:
1110: /*
1111: * Returns the Operation name from the properties
1112: * @return operationName returns operation name
1113: */
1114: protected String getOperationName() throws CommandException {
1115: String operationName = (String) ((Vector) getProperty(OPERATION))
1116: .get(0);
1117: String operationNameStr = replacePattern(operationName);
1118: CLILogger.getInstance().printDebugMessage(
1119: "OperationName = " + operationNameStr);
1120: return operationNameStr;
1121: }
1122:
1123: /*
1124: * Returns the Return type from the properties
1125: * @return returnType returns return type
1126: */
1127: protected String getReturnType() {
1128: String returnType = (String) ((Vector) getProperty(RETURN_TYPE))
1129: .get(0);
1130: CLILogger.getInstance().printDebugMessage(
1131: "ReturnType = " + returnType);
1132: return returnType;
1133: }
1134:
1135: /*
1136: * Formulate and Returns the attributes list from the given string
1137: * @return AttributeList returns attributes list
1138: */
1139: private AttributeList getAttributeList(String paramStr)
1140: throws CommandException {
1141: AttributeList attrList = new AttributeList();
1142: StringTokenizer paramsTokenizer = new StringTokenizer(paramStr,
1143: PARAM_DELIMITER);
1144: int size = paramsTokenizer.countTokens();
1145: for (int i = 0; i < size; i++) {
1146: final String nameValue = paramsTokenizer.nextToken();
1147: final String nameValueStr = replacePattern(nameValue);
1148: if (nameValueStr == null)
1149: continue;
1150: final int index = getDelimeterIndex(nameValueStr,
1151: PARAM_VALUE_DELIMITER, 0);
1152: final String attrName = nameValueStr.substring(0, index);
1153: final String attrValue = nameValueStr.substring(index + 1);
1154: //do not add to attribute list if value is empty
1155: if (attrValue.length() > 0) {
1156: CLILogger.getInstance().printDebugMessage(
1157: "**Attr Name = " + attrName + ", Value = "
1158: + attrValue);
1159: attrList.add(new Attribute(attrName, attrValue));
1160: }
1161: }
1162: return attrList;
1163: }
1164:
1165: /**
1166: * Formulate and Returns Properties from the given string
1167: * @return Properties
1168: */
1169: protected Properties createPropertiesParam(String propertyVal)
1170: throws CommandException {
1171:
1172: final String propertyStr = replacePattern(propertyVal);
1173: if (propertyStr == null) {
1174: return null;
1175: }
1176:
1177: Properties properties = new Properties();
1178: try {
1179: properties.load(new FileInputStream(propertyStr));
1180: } catch (FileNotFoundException fnfe) {
1181: throw new CommandException(getLocalizedString(
1182: ERROR_FILE_NOT_FOUND, new Object[] { propertyStr }));
1183: } catch (IOException ioe) {
1184: Object[] tokens = { ioe.toString() };
1185: throw new CommandException(getLocalizedString(
1186: ERROR_READING_FILE, new Object[] { propertyStr }));
1187: }
1188: return properties;
1189: }
1190:
1191: protected boolean hasWebLogicAdminServerInstance(String portalId) {
1192: boolean hasWebLogicAdminServerInstance = false;
1193: Map valuesMap = null;
1194: try {
1195: List instances = getInstanceNames(portalId);
1196: if (!instances.isEmpty()) {
1197: String instName = (String) instances.get(0);
1198: Set attrKeys = new HashSet();
1199: attrKeys.add(InstanceAttributes.WEB_CONTAINER_TYPE);
1200: Object[] params = {
1201: AdminClientUtil.PORTAL_SERVER_INSTANCE_MBEAN_TYPE,
1202: attrKeys };
1203: String[] signature = { "java.lang.String",
1204: "java.util.Set" };
1205:
1206: ObjectName objName = AdminClientUtil
1207: .getInstanceMBeanObjectName(
1208: AdminClientUtil.DEFAULT_DOMAIN,
1209: portalId, instName);
1210:
1211: valuesMap = (Map) getMBeanServerConnection(getUserId(),
1212: getPassword(), getHost())
1213: .invoke(objName, "getMultipleAttributeValues",
1214: params, signature);
1215: }
1216: } catch (Exception e) {
1217: System.out.println(e);
1218: logger.log(Level.SEVERE, "PSALI_CSPACCP0001", e);
1219: }
1220: if (valuesMap != null) {
1221: String wcType = getValueFromMap(
1222: InstanceAttributes.WEB_CONTAINER_TYPE, valuesMap);
1223: if (wcType != null && wcType.length() != 0
1224: & (wcType.indexOf("BEA") != -1)) {
1225: hasWebLogicAdminServerInstance = true;
1226: }
1227: }
1228: return hasWebLogicAdminServerInstance;
1229: }
1230:
1231: private String getValueFromMap(String key, Map valuesMap) {
1232: String value = "";
1233: Set valueSet = (Set) valuesMap.get(key);
1234: if (valueSet != null) {
1235: value = valueSet.toString();
1236: }
1237: return value;
1238: }
1239:
1240: /**
1241: * Formulate and Returns Boolean from the given string
1242: * @param booleanVal
1243: * @return Boolean
1244: */
1245: private Boolean createBooleanVal(String booleanVal)
1246: throws CommandException {
1247: String booleanStr = replacePattern(booleanVal);
1248: return Boolean.valueOf(booleanStr);
1249: }
1250:
1251: /**
1252: * Formulate and Returns a Integer from the given string
1253: * @return Integer
1254: */
1255: private Integer createIntegerParam(String paramStr)
1256: throws CommandException {
1257: Integer in = new Integer(0);
1258: String str = replacePattern(paramStr);
1259:
1260: try {
1261: if (str != null) {
1262: in = new Integer(str);
1263: }
1264: } catch (NumberFormatException nf) {
1265: throw new CommandException(
1266: getLocalizedString(ERROR_OPTION_INTEGER_IS_REQUIRED));
1267: }
1268: return in;
1269: }
1270:
1271: /**
1272: * Formulate and Returns a List from the given string
1273: * @return List
1274: */
1275: private List createListParam(String str) throws CommandException {
1276: final String strArrayVal = replacePattern(str);
1277: List list = new ArrayList();
1278: if (strArrayVal != null && !strArrayVal.equals("null")) {
1279: final StringTokenizer tokenizer = new StringTokenizer(
1280: strArrayVal, PARAM_DELIMITER);
1281: while (tokenizer.hasMoreTokens()) {
1282: list.add(tokenizer.nextToken());
1283: }
1284: }
1285: return list;
1286: }
1287:
1288: /**
1289: * Formulate and Returns StringArray from the given string
1290: * @return str
1291: */
1292: private String[] createStringArrayParam(String str)
1293: throws CommandException {
1294: final String strArrayVal = replacePattern(str);
1295: CLILogger.getInstance().printDebugMessage(
1296: "strArrayVal value = \"" + strArrayVal + "\"");
1297: if ((strArrayVal == null) || (strArrayVal.equals(""))
1298: || (strArrayVal.equals("null")))
1299: return null;
1300:
1301: final CLITokenizer cliTokenizer = new CLITokenizer(strArrayVal,
1302: PROPERTY_DELIMITER);
1303: String[] strArray = new String[cliTokenizer.countTokens()];
1304: int ii = 0;
1305: while (cliTokenizer.hasMoreTokens()) {
1306: strArray[ii++] = cliTokenizer
1307: .nextTokenWithoutEscapeAndQuoteChars();
1308: }
1309: return strArray;
1310: }
1311:
1312: /**
1313: * handles return value from mbean
1314: * @param returnval
1315: */
1316: protected void handleReturnValue(Object returnval) {
1317: if (returnval == null)
1318: return;
1319: Class cl = returnval.getClass();
1320: if (cl.isArray()) {
1321: if (cl == new ObjectName[0].getClass()) {
1322: final ObjectName[] objs = (ObjectName[]) returnval;
1323: if (objs.length == 0) {
1324: CLILogger.getInstance().printDetailMessage(
1325: getLocalizedString("NoElementsToList"));
1326: return;
1327: }
1328:
1329: final String displayType = (String) ((Vector) getProperty(DISPLAY_TYPE))
1330: .get(0);
1331: for (int ii = 0; ii < objs.length; ii++) {
1332: ObjectName objectName = (ObjectName) objs[ii];
1333: CLILogger.getInstance().printDebugMessage(
1334: "ObjectName = " + objectName);
1335: CLILogger.getInstance().printMessage(
1336: objectName.getKeyProperty(displayType));
1337: }
1338: } else {
1339: final Object[] objs = (Object[]) returnval;
1340: if (objs.length == 0) {
1341: CLILogger.getInstance().printDetailMessage(
1342: getLocalizedString("NoElementsToList"));
1343: return;
1344: }
1345:
1346: for (int ii = 0; ii < objs.length; ii++) {
1347: CLILogger.getInstance().printMessage(
1348: objs[ii].toString());
1349: }
1350: }
1351: } else {
1352: final Object obj = (Object) returnval;
1353: CLILogger.getInstance().printMessage(obj.toString());
1354: }
1355:
1356: }
1357:
1358: }
|