Sun GlassFish Enterprise Server v3 Add-On Component Development Guide

Chapter 4 Extending the asadmin Utility

The asadmin utility is a command-line tool for configuring and administering Enterprise Server. Extending the asadmin utility enables you to provide administrative interfaces for an add-on component that are consistent with the interfaces of other Enterprise Server components. A user can run asadmin subcommands either from a command prompt or from a script. For more information about the asadmin utility, see the asadmin(1M) man page.

The following topics are addressed here:

About the Administrative Command Infrastructure of Enterprise Server

To enable multiple containers to be independently packaged and loaded, the administrative command infrastructure of Enterprise Server provides the following features:

Adding an asadmin Subcommand

An asadmin subcommand identifies the operation or task that a user is to perform. Adding an asadmin subcommand enables the user to perform these tasks and operations through the asadmin utility.

The following topics are addressed here:

Representing an asadmin Subcommand as a Java Class

Each asadmin subcommand that you are adding must be represented as a Java class. To represent an asadmin subcommand as a Java class, write a Java class that implements the org.glassfish.api.admin.AdminCommand interface. Write one class for each subcommand that you are adding. Do not represent multiple asadmin subcommands in a single class.

Annotate the declaration of your implementations of the AdminCommand interface with the org.jvnet.hk2.annotations.Service annotation. The @Service annotation ensures that the following requirements for your implementations are met:

Specifying the Name of an asadmin Subcommand

To specify the name of the subcommand, set the name element of the @Service annotation to the name.


Note –

Subcommand names are case-sensitive.


Subcommands that are supplied in Enterprise Server distributions typically create, delete, and list objects of a particular type. For consistency with the names of subcommands that are supplied in Enterprise Server distributions, follow these conventions when specifying the name of a subcommand:

For example, Enterprise Server provides the following subcommands for creating, deleting, and listing HTTP listeners:

You must also ensure that the name of your subcommand is unique. To obtain a complete list of the names of all asadmin subcommands that are installed, use the list-commands(1) subcommand. For a complete list of asadmin subcommands that are supplied in Enterprise Server distributions, see Sun GlassFish Enterprise Server v3 Reference Manual.

Ensuring That an AdminCommand Implementation Is Stateless

To enable multiple clients to run a subcommand simultaneously, ensure that the implementation of the AdminCommand interface for the subcommand is stateless. To ensure that the implementation of the AdminCommand interface is stateless, annotate the declaration of your implementation with the org.jvnet.hk2.annotations.Scoped annotation. In the @Scoped annotation, set the scope as follows:

Example of Adding an asadmin Subcommand


Example 4–1 Adding an asadmin Subcommand

This example shows the declaration of the class CreateMycontainer that represents an asadmin subcommand that is named create-mycontainer. The subcommand is instantiated for each lookup.

package com.example.mycontainer;

import org.glassfish.api.admin.AdminCommand;
...
import org.jvnet.hk2.annotations.Service;
...
import org.jvnet.hk2.annotations.Scoped;
import org.jvnet.hk2.component.PerLookup;

/**
 * Sample subcommand
 */
@Service(name="create-mycontainer")
@Scoped(PerLookup.class)
public Class CreateMycontainer implements AdminCommand {
…
}

Adding Parameters to an asadmin Subcommand

The parameters of an asadmin subcommand are the options and operands of the subcommand.

The following topics are addressed here:

Representing a Parameter of an asadmin Subcommand

Represent each parameter of a subcommand in your implementation as a field or as the property of a JavaBeansTM specification setter method. Use the property of a setter method for the following reasons:

Identifying a Parameter of an asadmin Subcommand

Identifying a parameter of an asadmin subcommand enables Enterprise Server to perform the following operations at runtime on the parameter:

To identify a parameter of a subcommand, annotate the declaration of the item that is associated with the parameter with the org.glassfish.api.Param annotation. This item is either the field or setter method that is associated with the parameter.

To specify the properties of the parameter, use the elements of the @Param annotation as explained in the sections that follow.

Specifying Whether a Parameter Is an Option or an Operand

Whether a parameter is an option or an operand determines how a user must specify the parameter when running the subcommand:

To specify whether a parameter is an option or an operand, set the primary element of the @Param annotation as follows:

Specifying the Name of an Option

The name of an option is the name that a user must type on the command line to specify the option when running the subcommand.

The name of each option that you add in your implementation of an asadmin subcommand can have a long form and a short form. When running the subcommand, the user specifies the long form and the short form as follows:

For example, the short form and the long form of the name of the option for specifying terse output are as follows:


Note –

Option names are case-sensitive.


Specifying the Long Form of an Option Name

To specify the long form of an option name, set the name element of the @Param annotation to a string that specifies the name. If you do not set this element, the default name depends on how you represent the option.

Specifying the Short Form of an Option Name

To specify the short form of an option name, set the shortName element of the @Param annotation to a single character that specifies the short form of the parameter. The user can specify this character instead of the full parameter name, for example -m instead of --monitor. If you do not set this element, the option has no short form.

Specifying the Acceptable Values of a Parameter

When a user runs the subcommand, the Enterprise Server validates option arguments and operands against the acceptable values that you specify in your implementation.

To specify the acceptable values of a parameter, set the acceptableValues element of the @Param annotation to a string that contains a comma-separated list of acceptable values. If you do not set this element, any string of characters is acceptable.

Specifying the Default Value of a Parameter

The default value of a parameter is the value that is applied if a user omits the parameter when running the subcommand.

To specify the default value of a parameter, set the defaultValue element of the @Param annotation to a string that contains the default value. If you do not set this element, the parameter has no default value.

Specifying Whether a Parameter Is Required or Optional

Whether a parameter is required or optional determines how a subcommand responds if a user omits the parameter when running the subcommand:

To specify whether a parameter is optional or required, set the optional element of the @Param annotation as follows:

Example of Adding Parameters to an asadmin Subcommand


Example 4–2 Adding Parameters to an asadmin Subcommand

This example shows the code for adding parameters to an asadmin subcommand with the properties as shown in the table.

Name 

Represented As 

Acceptable Values 

Default Value 

Optional or Required 

Short Name 

Option or Operand 

--originator

A field that is named originator

Any character string 

None defined 

Required 

None 

Option 

--description

A field that is named mycontainerDescription

Any character string 

None defined 

Optional 

None 

Option 

--enabled

A field that is named enabled

true or false

false

Optional 

None 

Option 

--containername

A field that is named containername

Any character string 

None defined 

Required 

None 

Operand 

...
import org.glassfish.api.Param;
...
{
…
    @Param
    String originator;
    
    @Param(name="description", optional=true)
    …
    String mycontainerDescription
    
    @Param (acceptableValues="true,false", defaultValue="false", optional=true)
    String enabled
    
    @Param(primary=true)
    String containername;
…
}

Adding Message Text Strings to an asadmin Subcommand

A message text string provides useful information to the user about an asadmin subcommand or a parameter.

To provide internationalization support for the text string of a subcommand or parameter, annotate the declaration of the subcommand or parameter with the org.glassfish.api.I18n annotation. The @I18n annotation identifies the resource from the resource bundle that is associated with your implementation.

To add message text strings to an asadmin subcommand, create a plain text file that is named LocalStrings.properties to contain the strings. Define each string on a separate line of the file as follows:

key=string
key

A key that maps the string to a subcommand or a parameter. The format to use for key depends on the target to which the key applies and whether the target is annotated with the @I18n annotation. See the following table.

Target 

Format 

Subcommand or parameter with the @I18n annotation

subcommand-name.command.resource-name

Subcommand without the @I18n annotation

subcommand-name.command

Parameter without the @I18n annotation

subcommand-name.command.param-name

The replaceable parts of these formats are as follows:

subcommand-name

The name of the subcommand.

resource-name

The name of the resource that is specified in the@I18n annotation.

param-name

The name of the parameter.

string

A string without quotes that contains the text of the message.


Note –

To display the message strings to users, you must provide code in your implementation of the execute method to display the text. For more information about implementing the execute method, see Enabling an asadmin Subcommand to Run.



Example 4–3 Adding Message Strings to an asadmin Subcommand

This example shows the code for adding message strings to the create-mycontainer subcommand as follows:

The addition of the parameters originator, description, enabled and containername to the subcommand is shown in Example 4–2.

package com.example.mycontainer;

import org.glassfish.api.admin.AdminCommand;
...
import org.glassfish.api.I18n;
import org.glassfish.api.Param;
import org.jvnet.hk2.annotations.Service;
...
import org.jvnet.hk2.annotations.Scoped;
import org.jvnet.hk2.component.PerLookup;

/**
 * Sample subcommand
 */
@Service(name="create-mycontainer")
@Scoped(PerLookup.class)
public Class CreateMycontainer implements AdminCommand {

    …

    @Param
    String originator;

    @Param(name="description", optional=true)
    @I18n("mydesc")
    String mycontainerDescription
   
    @Param (acceptableValues="true,false", defaultValue="false", optional=true)
    String enabled
    
    @Param(primary=true)
    String containername;
 …

}

The following message text strings are defined in the file LocalStrings.properties for use by the subcommand:

create-mycontainer.command=Creates a custom container
create-mycontainer.command.originator=The originator of the container 
create-mycontainer.command.mydesc=A description of the container
create-mycontainer.command.enabled=Whether the container is enabled or disabled
create-mycontainer.command.containername=The container name

Enabling an asadmin Subcommand to Run

To enable an asadmin subcommand to run, implement the execute method in your implementation of the AdminCommand interface. The declaration of the execute method in your implementation must be as follows.

    public void execute(AdminCommandContext context);

Pass each parameter of the subcommand as a property to your implementation of the execute method. Set the key of the property to the parameter name and set the value of the property to the parameter's value.

In the body of the execute method, provide the code for performing the operation that the command was designed to perform. For examples, see Example 4–6 and Example 4–7.

Setting the Context of an asadmin Subcommand

The org.glassfish.api.admin.AdminCommandContext class provides the following services to an asadmin subcommand:

To set the context of an asadmin subcommand, pass an AdminCommandContext object to the execute method of your implementation.

Changing the Brand in the Enterprise Server CLI

The brand in the Enterprise Server command-line interface (CLI) consists of the product name and release information that are displayed in the following locations:

If you are incorporating Enterprise Server into a new product with an external vendor's own brand name, change the brand in the Enterprise Server CLI.

To change the brand in the Enterprise Server CLI, create an OSGi fragment bundle that contains a plain text file that is named src/main/resources/BrandingVersion.properties.

In the BrandingVersion.properties file, define the following keyword-value pairs:

product_name=product-name
abbrev_product_name=abbrev-product-name
major_version=major-version
minor_version=minor-version
build_id=build-id
version_prefix=version-prefix
version_suffix=version-suffix

Define each keyword-value pair on a separate line of the file. Each value is a text string without quotes.

The meaning of each keyword-value pair is as follows:

product_name=product-name

Specifies the full product name without any release information, for example, Sun GlassFish Enterprise Server.



abbrev_product_name=abbrev-product-name

Specifies an abbreviated form of the product name without any release information, for example, Sun GlassFish.

major_version=major-version

Returns the product major version, for example, 3

minor_version=minor-version

Specifies the product minor version, for example, 0.

build_id=build-id

Specifies the build version, for example, build 17.

version_prefix=version-prefix

Specifies a prefix for the product version, for example, v.

version_suffix=version-suffix

Specifies a suffix for the product version, for example, Prelude.


Example 4–4 BrandingVersion.properties File for Changing the Brand in the Enterprise Server CLI

This example shows the content of the BrandingVersion.properties for defining the product name and release information of Sun GlassFish Enterprise Server v3.0 Prelude, build 17. The abbreviated product name is sun-glassfish.

product_name=Sun GlassFish Enterprise Server
abbrev_product_name=sun-glassfish
major_version=3
minor_version=0
build_id=build 17
version_prefix=v
version_suffix=Prelude

Examples of Extending the asadmin Utility


Example 4–5 asadmin Subcommand With Empty execute Method

This example shows a class that represents the asadmin subcommand create-mycontainer.

The usage statement for this subcommand is as follows:


asadmin create-mycontainer --originator any-character-string
[--description any-character-string]
[--enabled {true|false}]  any-character-string

This subcommand uses injection to specify that a running domain is required.

package com.example.mycontainer;

import org.glassfish.api.admin.AdminCommand;
import org.glassfish.api.admin.AdminCommandContext;
import org.glassfish.api.I18n;
import org.glassfish.api.Param;
import org.jvnet.hk2.annotations.Service;
import org.jvnet.hk2.annotations.Inject;
import org.jvnet.hk2.annotations.Scoped;
import org.jvnet.hk2.component.PerLookup;

/**
 * Sample subcommand
 */
@Service(name="create-mycontainer")
@Scoped(PerLookup.class)
public Class CreateMycontainer implements AdminCommand {

    @Inject
    Domain domain;

    @Param
    String originator;

    @Param(name="description", optional=true)
    @I18n("mydesc")
    String mycontainerDescription

    @Param (acceptableValues="true,false", defaultValue="false", optional=true)
    String enabled
    
    @Param(primary=true)
    String containername;

    /**
     * Executes the subcommand with the subcommand parameters passed as Properties 
     * where the keys are the paramter names and the values the parameter values
     * @param context information 
     */
    public void execute(AdminCommandContext context) {
        // domain and originator are not null
        // mycontainerDescription can be null.
    }
}

The following message text strings are defined in the file LocalStrings.properties for use by the subcommand:

create-mycontainer.command=Creates a custom container
create-mycontainer.command.originator=The originator of the container 
create-mycontainer.command.mydesc=A description of the container
create-mycontainer.command.enabled=Whether the container is enabled or disabled
create-mycontainer.command.containername=The container name


Example 4–6 asadmin Subcommand for Retrieving and Displaying Information

This example shows a class that represents the asadmin subcommand list-runtime-environment. The subcommand determines the operating system or runtime information for Enterprise Server.

The usage statement for this subcommand is as follows:


asadmin list-runtime-environment{runtime|os}
package com.example.env.cli;

import org.glassfish.api.admin.AdminCommand;
import org.glassfish.api.admin.AdminCommandContext;
import org.glassfish.api.ActionReport;
import org.glassfish.api.I18n;
import org.glassfish.api.ActionReport.ExitCode;
import org.glassfish.api.Param;
import org.jvnet.hk2.annotations.Service;
import org.jvnet.hk2.annotations.Inject;
import org.jvnet.hk2.annotations.Scoped;
import org.jvnet.hk2.component.PerLookup;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;

/**
 * Demos asadmin CLI extension
 *
  */
@Service(name="list-runtime-environment")
@Scoped(PerLookup.class)
public class ListRuntimeEnvironmentCommand implements AdminCommand {
    
    // this value can be either runtime or os for our demo
    @Param(primary=true)
    String inParam;
    
    public void execute(AdminCommandContext context) {

        ActionReport report = context.getActionReport();
        report.setActionExitCode(ExitCode.SUCCESS);

        // If the inParam is 'os' then this subcommand returns operating system
        // info and if the inParam is 'runtime' then it returns runtime info.
        // Both of the above are based on mxbeans.

        if ("os".equals(inParam)) {
            OperatingSystemMXBean osmb = ManagementFactory.getOperatingSystemMXBean();
            report.setMessage("Your machine operating system name = " + osmb.getName());
        } else if ("runtime".equals(inParam)) {
            RuntimeMXBean rtmb = ManagementFactory.getRuntimeMXBean();
            report.setMessage("Your JVM name = " + rtmb.getVmName());
        } else {
            report.setActionExitCode(ExitCode.FAILURE);
            report.setMessage("operand should be either 'os' or 'runtime'");
        }

    }
}


Example 4–7 asadmin Subcommand for Updating Configuration Data

This example shows a class that represents the asadmin subcommand configure-greeter-container. The subcommand performs a transaction to update configuration data for a container component. For more information about such transactions, see Creating a Transaction to Update Configuration Data.

The usage statement for this subcommand is as follows:


asadmin configure-greeter-container --instances instances [--language language] [--style style]

The acceptable values and default value of each option of the subcommand are shown in the following table. The table also indicates whether each option is optional or required.

Option 

Acceptable Values 

Default value 

Optional or Required 

--instances

An integer in the range 1–10 

Required 

--language

english, norsk, or francais

norsk

Optional 

--style

formal, casual, or expansive

formal

Optional 

Code for the container component is shown in Example of Adding Container Capabilities.

Code that defines the configuration data for the container component is shown in Examples of Adding Configuration Data for a Component.

package org.glassfish.examples.extension.greeter.config;

import org.glassfish.api.admin.AdminCommand;
import org.glassfish.api.admin.AdminCommandContext;
import org.glassfish.api.Param;
import org.jvnet.hk2.annotations.Service;
import org.jvnet.hk2.annotations.Inject;
import org.jvnet.hk2.config.Transactions;
import org.jvnet.hk2.config.ConfigSupport;
import org.jvnet.hk2.config.SingleConfigCode;
import org.jvnet.hk2.config.TransactionFailure;

import java.beans.PropertyVetoException;

@Service(name = "configure-greeter-container")
public class ConfigureGreeterContainerCommand implements AdminCommand {

    @Param(acceptableValues = "1,2,3,4,5,6,7,8,9,10", defaultValue = "5")
    String instances;
    @Param(acceptableValues = "english,norsk,francais", defaultValue = "norsk",
    optional = true)
    String language;
    @Param(acceptableValues = "formal,casual,expansive", defaultValue = "formal",
    optional = true)
    String style;
    @Inject
    GreeterContainerConfig config;

    public void execute(AdminCommandContext adminCommandContext) {
        try {
            ConfigSupport.apply(new SingleConfigCode<GreeterContainerConfig>() {

                public Object run(GreeterContainerConfig greeterContainerConfig)
                        throws PropertyVetoException, TransactionFailure {
                    greeterContainerConfig.setNumberOfInstances(instances);
                    greeterContainerConfig.setLanguage(language);
                    greeterContainerConfig.setStyle(style);
                    return null;
                }
            }, config);
        } catch (TransactionFailure e) {
        }

    }
}