FileDocCategorySizeDatePackage
DottedNamesCommand.javaAPI DocGlassfish v2 API17315Fri May 04 22:25:10 BST 2007com.sun.enterprise.cli.commands

DottedNamesCommand

public class DottedNamesCommand extends S1ASCommand
This is class handles get, set and list commands
version
$Revision: 1.4 $

Fields Summary
private static final String
GET_COMMAND
private static final String
SET_COMMAND
private static final String
LIST_COMMAND
private static final String
GET_OPERATION
private static final String
LIST_OPERATION
private static final String
GET_MONITORING_OPERATION
private static final String
LIST_MONITORING_OPERATION
private static final String
SET_OPERATION
private static final String
MONITOR_OPTION
private static final String
OBJECT_NAME
private static final String
INTERVAL_OPTION
private static final String
ITERATIONS_OPTION
private static final String
PROPERTY_STRING
private static String
INNER_ARRAY_DELIM
private static String
OUTER_ARRAY_DELIM
Constructors Summary
Methods Summary
public booleancheckPropertyToConvert(java.lang.String param)
This method checks if the element in the dotted name contains "property" or "system-property". If the element is "property" or "system-property" then return true else return false.

param
param - dotted name
return
true if dotted name contains "property" or "system-property" false

        final int index = param.lastIndexOf('.");
        if (index < 0) return false;
        final String elementName = param.substring(index+1);
        if (elementName.matches(PROPERTY_STRING))
            return true;
        else
            return false;
    
private javax.management.Attribute[]collectAllAttributes(java.lang.Object[] results)

		// use a HashMap to eliminate duplicates; use name as the key
		final HashMap	attrs	= new HashMap();
		
		for( int i = 0; i < results.length; ++i )
		{
			final Object	result	= results[ i ];
			
			if ( result instanceof Attribute )
			{
				attrs.put( ((Attribute)result).getName(), result );
			}
			else if ( result instanceof Attribute[] )
			{
				final Attribute[]	list	= (Attribute[])result;
				
				for( int attrIndex = 0; attrIndex < list.length; ++attrIndex )
				{
					final Attribute	attr	= list[ attrIndex ];
					
					attrs.put( attr.getName(), attr );
				}
			}
			else
			{
				assert( result instanceof Exception );
			}
		}
		
		final Attribute[]	attrsArray	= new Attribute[ attrs.size() ];
		attrs.values().toArray( attrsArray );
		Arrays.sort( attrsArray, new AttributeComparator() );
		
		return( attrsArray );
	
public java.lang.StringconvertUnderscoreToHyphen(java.lang.String param)
This method will convert the attribute in the dotted name notation from underscore to hyphen.

param
param - the dotted name to convert
return
the converted string

        int endIndex = param.indexOf('=");
        int begIndex = (endIndex>0)? param.lastIndexOf('.", endIndex):param.lastIndexOf('.");
        if(begIndex<1 || checkPropertyToConvert(param.substring(0,begIndex)))
           return param;
        if(endIndex>0)
           return param.substring(0,begIndex) + param.substring(begIndex,endIndex).replace('_", '-") + param.substring(endIndex);
        else
           return param.substring(0,begIndex) + param.substring(begIndex).replace('_", '-");
    
private voiddisplayResultFromGetOrSet(java.lang.String[] inputs, java.lang.Object[] returnValues)
figure out the returnValue type and call appropriate print methods

params
returnval
throws
CommandException if could not print AttributeList

	// top-level array
	
                               
    	 
            
    	 
    
    	if ( returnValues.length == 1 )
    	{
    		// there was a single string provided as input
    		final Object	result	= returnValues[ 0 ];
    		
	    	if ( result instanceof Exception )
	    	{
	    		throw (Exception) result;
	    	}
			else if ( result.getClass() == Attribute[].class )
			{
				// this must have been the result of a wildcard input
				final Attribute[]	attrs	= (Attribute[])result;
				
				if ( attrs.length == 0 ) 
				{
				    throw new AttributeNotFoundException( getLocalizedString("NoWildcardMatches") );
				}
				
				printMessage( stringify( attrs, OUTER_ARRAY_DELIM ) );
			}
			else
			{
				printMessage( stringify( result, OUTER_ARRAY_DELIM ) );
			}
    	}
    	else
    	{
    		// more than one input String; collect all the resulting Attributes
    		// into one big non-duplicate sorted list and print them.
			final Attribute[]	attrs	= collectAllAttributes( returnValues );
			
    		printMessage(  stringify( attrs, OUTER_ARRAY_DELIM ) );
    		
    		// tell about any failures
    		for( int i = 0; i < returnValues.length; ++i )
    		{
    			if ( returnValues[ i ] instanceof Exception )
    			{
    				final Exception	e	= (Exception)returnValues[ i ];
    				
    				final String msg	= getLocalizedString( "ErrorInGetSet",
    					new Object [] { inputs[ i ], getExceptionMessage( e ) } );
    					
    				printMessage( msg );
    			}
    		}
    	}
    	
		return;
    
private voiddisplayResultFromList(java.lang.String[] result)

        if ( result.length == 0 )
        {
            //need to convert the operands to String for display

            final String displayOperands = stringify(getDottedNamesParam(true),
                                                     INNER_ARRAY_DELIM);
            printMessage(getLocalizedString("EmptyList", new Object[] {
                displayOperands }));
        }
        else
        {
            printMessage( stringify( result, OUTER_ARRAY_DELIM ) );
        }
    
private java.lang.Object[]getDottedNamesParam(boolean convertUnderscore)
get the dotted notation from the operand and convert it to a Object[]

return
Object[]

        final Vector dottedNames = getOperands();
        String [] dottedNamesArray = new String[dottedNames.size()];
        
        for (int ii=0; ii<dottedNames.size(); ii++)
        {
            if (convertUnderscore)
                dottedNamesArray[ii] = convertUnderscoreToHyphen((String)dottedNames.get(ii));
            else
                dottedNamesArray[ii] = (String)dottedNames.get(ii);
        }
        return new Object[]{dottedNamesArray};
        
        //return new Object[] {(String[])dottedNames.toArray(new String[dottedNames.size()])};
    
private java.lang.StringgetExceptionMessage(java.lang.Exception e)

		String msg = null;

		if (e instanceof RuntimeMBeanException) {
			RuntimeMBeanException rmbe = (RuntimeMBeanException) e;
			msg     = rmbe.getTargetException().getLocalizedMessage();
		} else if (e instanceof RuntimeOperationsException) {
			RuntimeOperationsException roe = (RuntimeOperationsException) e;
			msg	= roe.getTargetException().getLocalizedMessage();
		} else {
			msg	= e.getLocalizedMessage();
		}
		if ( msg == null || msg.length() == 0 )
		{
			msg	= e.getMessage();
		}
			
		if ( msg == null || msg.length() == 0 )
		{
			msg	= e.getClass().getName();
		}
		
		return( msg );
	
private java.lang.StringgetOperation()
get the operation to invoke depending on the command name and option if command name is "set" then the operation is dottedNameSet if command name is "get" then the operation is dottedNameGet if the command name is "get" with --monitor option to true, then the operation is dottedNameMonitoringGet all others return null.

return
name of th operation

        if (getName().equals(SET_COMMAND))
            return SET_OPERATION;
        else if (getName().equals(GET_COMMAND))
        {	    
            if (getBooleanOption(MONITOR_OPTION))
                return GET_MONITORING_OPERATION;
            else
                return GET_OPERATION;
        }
        else if (getName().equals(LIST_COMMAND))
        {	    
            if (getBooleanOption(MONITOR_OPTION))
                return LIST_MONITORING_OPERATION;
            else
                return LIST_OPERATION;
        }
        return null;
    
private booleanisIntervalValid()

        
        String interval = getOption(INTERVAL_OPTION);
        
        if(interval == null)
            return true;
        else if((interval != null) && (Integer.parseInt(interval) > 0))
            return true;
        else
        {
            printMessage(getLocalizedString("InvalidInterval", new Object[] {interval}));
            return false;
        }
    
private booleanisIterationValid()

        
        String iterations = getOption(ITERATIONS_OPTION);
        
        if(iterations == null)
            return true;
        else if((iterations != null) && (Integer.parseInt(iterations) > 0))
            return true;
        else
        {
            printMessage(getLocalizedString("InvalidIterations", new Object[] {iterations}));
            return false;
        }
    
private voidprintMessage(java.lang.String msg)

		CLILogger.getInstance().printMessage( msg );
	
public voidrunCommand()
An abstract method that Executes the command

throws
CommandException

		if(!validateOptions())
            return;

		//use http connector
		final MBeanServerConnection mbsc = getMBeanServerConnection(getHost(), 
									    getPort(), 
									    getUser(), 
									    getPassword());
		final Object[] params = getDottedNamesParam(getName().equals(LIST_COMMAND)?
                                                    false:true);
		final String[] types = new String[] {STRING_ARRAY};
        final String operationName = getOperation();
        final String interval = getOption(INTERVAL_OPTION);
        final String iterations = getOption(ITERATIONS_OPTION);
        
		try
		{
			// we always invoke with an array, and so the result is always an Object []
		    final Object[] returnValues = (Object[])mbsc.invoke(new ObjectName(OBJECT_NAME), 
					      		operationName, params, types);
			if ( operationName.indexOf( "List" ) >= 0)
			{
				// a list operation, just print the String []
				displayResultFromList( (String [])returnValues );
			}
            else if(operationName.equals(this.GET_MONITORING_OPERATION) && (interval != null) && (iterations != null))
            {
                String[]	userArgs	= (String [])params[ 0 ];
				displayResultFromGetOrSet( userArgs, returnValues );
                long interval_millis = Integer.parseInt(interval) * 1000;
                int counter = Integer.parseInt(iterations);
                int i = 1;
                do {
                    printMessage("\n");
                    if (i < counter) {
                        try {
                            Thread.currentThread().sleep(interval_millis);
                            Object[] retVals = (Object[]) mbsc.invoke(new ObjectName(OBJECT_NAME), 
                                                                      operationName, 
                                                                      params, 
                                                                      types);
                            userArgs = (String []) params[0];
                            displayResultFromGetOrSet(userArgs, retVals);
                            ++i;
                        } catch (InterruptedException ie) {
                        }
                    }
                }while(i < counter);
            }
			else
			{
				final String[]	userArgs	= (String [])params[ 0 ];
				
				displayResultFromGetOrSet( userArgs, returnValues );
			}
		}
		catch(Exception e)
		{
			final String	msg	= getExceptionMessage( e );
		    if ( msg != null)
		    {
				CLILogger.getInstance().printDetailMessage( msg );
			}
			
		    throw new CommandException(getLocalizedString("CommandUnSuccessful",
								  new Object[] {name} ), e);
		}        
    
private java.lang.Stringstringify(java.lang.Object o)

		return( stringify( o, "\n" ) );
	
private java.lang.Stringstringify(java.lang.Object o, java.lang.String delim)

		String	result	= null;
		
		if ( o == null )
		{
			result	= "";
		}
		else if ( o instanceof Attribute )
		{
			final Attribute	attr	= (Attribute)o;
			
			result	= attr.getName() + " = " +  stringify( attr.getValue(), INNER_ARRAY_DELIM );
		}
		else if ( ClassUtil.objectIsPrimitiveArray( o ) )
		{
		   final Object [] objectList = ArrayConversion.toAppropriateType( o );
		   
		   result	= stringifyArray( objectList, delim );
		}
		else if ( ClassUtil.objectIsArray( o ) )
		{
			result	= stringifyArray( (Object [])o, delim );
		}
		else if ( o instanceof Exception )
		{
			final Exception e	= (Exception)o;
			
			result	= getExceptionMessage( e );
		}
		else
		{
			result	= o.toString();
		}
		
		assert( result != null );
		return( result );
	
private java.lang.StringstringifyArray(java.lang.Object[] a, java.lang.String delim)

		final StringBuffer	buf	= new StringBuffer();
	
		for( int i = 0; i < a.length; ++i )
		{
			buf.append( stringify( a[ i ], INNER_ARRAY_DELIM ) );
			if ( i != a.length - 1 )
			{
				buf.append( delim );
			}
		}
		return( buf.toString() );
	
public booleanvalidateOptions()
This method validates the options for this command

return
boolean returns true if success else returns false
throws
CommandValidationException



                               
        
    
        // if monitor option is specified for a get operation and 
        // the interval and iterations specified along with it, we need to make 
        // sure that the values specified for interval and iterations
        // are valid
        if(getOperation().equals(GET_MONITORING_OPERATION))
        {
            if(!(isIntervalValid() && isIterationValid()))
                return false;
        }
		return super.validateOptions();