[jboss-cvs] JBossAS SVN: r89257 - in projects/fresh/trunk: fresh-shell and 2 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Thu May 21 14:52:02 EDT 2009


Author: ispringer
Date: 2009-05-21 14:52:02 -0400 (Thu, 21 May 2009)
New Revision: 89257

Added:
   projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/
   projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/AbstractProfileServiceExe.java
   projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsGetExe.java
   projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsLsCExe.java
   projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsLsDExe.java
   projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsSetExe.java
Modified:
   projects/fresh/trunk/fresh-jar/src/main/resources/META-INF/fresh-jboss-beans.xml
   projects/fresh/trunk/fresh-shell/pom.xml
Log:
add some Fresh commands for accessing the Profile Service


Modified: projects/fresh/trunk/fresh-jar/src/main/resources/META-INF/fresh-jboss-beans.xml
===================================================================
--- projects/fresh/trunk/fresh-jar/src/main/resources/META-INF/fresh-jboss-beans.xml	2009-05-21 18:31:51 UTC (rev 89256)
+++ projects/fresh/trunk/fresh-jar/src/main/resources/META-INF/fresh-jboss-beans.xml	2009-05-21 18:52:02 UTC (rev 89257)
@@ -201,6 +201,18 @@
             touch /bin/alias
             setffld /bin/alias mime cp2-shell/executable
             setattr /bin/alias Class org.jboss.fresh.shell.commands.AliasExe
+            touch /bin/pslsd
+            setffld /bin/pslsd mime cp2-shell/executable
+            setattr /bin/pslsd Class org.jboss.fresh.shell.commands.profileservice.PsLsDExe
+            touch /bin/pslsc
+            setffld /bin/pslsc mime cp2-shell/executable
+            setattr /bin/pslsc Class org.jboss.fresh.shell.commands.profileservice.PsLsCExe
+            touch /bin/psget
+            setffld /bin/psget mime cp2-shell/executable
+            setattr /bin/psget Class org.jboss.fresh.shell.commands.profileservice.PsGetExe
+            touch /bin/psset
+            setffld /bin/psset mime cp2-shell/executable
+            setattr /bin/psset Class org.jboss.fresh.shell.commands.profileservice.PsSetExe
             mkdir /etc
             mkdir /etc/shell
             mkdir /usr

Modified: projects/fresh/trunk/fresh-shell/pom.xml
===================================================================
--- projects/fresh/trunk/fresh-shell/pom.xml	2009-05-21 18:31:51 UTC (rev 89256)
+++ projects/fresh/trunk/fresh-shell/pom.xml	2009-05-21 18:52:02 UTC (rev 89257)
@@ -44,6 +44,27 @@
         <artifactId>jboss-aop-mc-int</artifactId>
       </dependency>
 
+      <dependency>
+        <groupId>org.jboss.integration</groupId>
+        <artifactId>jboss-profileservice-spi</artifactId>
+        <version>5.1.0.GA</version>
+        <!--<scope>provided</scope>-->
+      </dependency>
+
+      <dependency>
+        <groupId>org.jboss.man</groupId>
+        <artifactId>jboss-managed</artifactId>
+        <version>2.1.0.SP1</version>          
+        <!--<scope>provided</scope>-->
+      </dependency>
+
+      <dependency>
+        <groupId>org.jboss.man</groupId>
+        <artifactId>jboss-metatype</artifactId>
+        <version>2.1.0.SP1</version>
+        <!--<scope>provided</scope>-->
+      </dependency>
+
     <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>

Added: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/AbstractProfileServiceExe.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/AbstractProfileServiceExe.java	                        (rev 0)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/AbstractProfileServiceExe.java	2009-05-21 18:52:02 UTC (rev 89257)
@@ -0,0 +1,86 @@
+package org.jboss.fresh.shell.commands.profileservice;
+
+import java.util.Properties;
+import java.io.File;
+import java.io.PrintWriter;
+
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+import org.apache.log4j.Logger;
+
+import org.jboss.fresh.shell.AbstractExecutable;
+import org.jboss.fresh.io.PrintWriter2;
+import org.jboss.profileservice.spi.ProfileService;
+import org.jboss.deployers.spi.management.ManagementView;
+
+/**
+ * @author Ian Springer
+ */
+public abstract class AbstractProfileServiceExe extends AbstractExecutable {
+    private static final String PROFILE_SERVICE_JNDI_NAME = "ProfileService";
+
+    private final transient Logger log = Logger.getLogger(this.getClass());
+
+    private ProfileService profileService;
+
+    protected abstract String getVersion();
+    protected abstract void printHelp(String exePath, PrintWriter out);
+
+    protected void handleUsageError(String exePath, PrintWriter2 out, String errorMessage)
+    {
+        if (errorMessage != null) {
+            handleError(out, errorMessage);
+            out.println();
+        }
+        printHelp(exePath, out);
+    }
+
+    protected void handleError(PrintWriter2 out, String errorMessage)
+    {
+        if (canThrowEx())
+        {
+            throw new RuntimeException(errorMessage);
+        }
+        else
+        {
+            out.println(errorMessage);
+        }
+    }
+
+    protected void printVersion(String exePath, PrintWriter2 out)
+    {
+        String exeName = new File(exePath).getName();
+        out.println(exeName + ", version: " + getVersion());
+    }
+
+    protected ProfileService getProfileService() {
+        if (this.profileService == null) {
+            InitialContext initialContext = createInitialContext(null);
+            this.profileService = (ProfileService) lookup(initialContext, PROFILE_SERVICE_JNDI_NAME);                   
+        }
+        ManagementView managementView = this.profileService.getViewManager();
+        managementView.load();
+        return this.profileService;
+    }
+
+    private InitialContext createInitialContext(Properties env) {
+        InitialContext initialContext;
+        this.log.debug("Creating JNDI InitialContext with env [" + env + "]...");
+        try {
+            initialContext = new InitialContext(env);
+        } catch (NamingException e) {
+            throw new RuntimeException("Failed to create JNDI InitialContext.", e);
+        }
+        this.log.debug("Created JNDI InitialContext [" + initialContext + "].");
+        return initialContext;
+    }
+
+    private Object lookup(InitialContext initialContext, String name) {
+        try {
+            return initialContext.lookup(name);
+        } catch (NamingException e) {
+            throw new RuntimeException("Failed to lookup JNDI name '" + name + "' from InitialContext.", e);
+        }
+    }
+}
\ No newline at end of file


Property changes on: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/AbstractProfileServiceExe.java
___________________________________________________________________
Name: svn:mime-type
   + text/plain
Name: svn:keywords
   + Date Author Id Revision HeadURL
Name: svn:eol-style
   + LF

Added: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsGetExe.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsGetExe.java	                        (rev 0)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsGetExe.java	2009-05-21 18:52:02 UTC (rev 89257)
@@ -0,0 +1,254 @@
+package org.jboss.fresh.shell.commands.profileservice;
+
+import java.io.PrintWriter;
+import java.io.File;
+import java.io.Serializable;
+import java.util.Comparator;
+import java.util.Map;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.HashMap;
+
+import org.jboss.deployers.spi.management.ManagementView;
+import org.jboss.fresh.io.BufferWriter;
+import org.jboss.fresh.io.PrintWriter2;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.api.annotation.ViewUse;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.SimpleValue;
+import org.jboss.metatype.api.values.EnumValue;
+import org.jboss.metatype.api.types.MetaType;
+
+/**
+ * A FRESH command for getting Profile Service ManagedComponent properties.
+ *
+ * @author Ian Springer
+ */
+public class PsGetExe extends AbstractProfileServiceExe
+{
+    private static final String VERSION = "$Revision$";
+
+    protected String getVersion()
+    {
+        return VERSION;
+    }
+
+    protected void printHelp(String exePath, PrintWriter out)
+    {
+        String exeName = new File(exePath).getName();
+        out.println("Usage: " + exeName + " [OPTIONS] COMPONENT_TYPE COMPONENT_NAME PROPERTY");
+        out.println("Get either all properties or a single property for the specified component, where");
+        out.println("COMPONENT_TYPE is of the form <type>:<subtype> (e.g. JMSDestination:Queue), ");
+        out.println("and PROPERTY is either * for all properties or <name> for the property named name.");
+        out.println("  -h, --help                       display this help and exit");
+        out.println("  -m, --metadata                   display property metadata");
+        out.println("  -V, --version                    print version information and exit");
+        out.close();
+        return;
+    }
+
+    protected void process(String exePath, String[] args) throws Exception
+    {
+        PrintWriter2 out = new PrintWriter2(new BufferWriter(getStdOut()));
+
+        if (helpRequested()) {
+            handleUsageError(exePath, out, null);
+        }
+
+        if (args.length < 3) {
+            handleUsageError(exePath, out, "Too few arguments.");
+        }
+
+        String[] invalidOptions = getInvalidSwitches(args, "hmV", new String[]{"help", "metadata", "version"});
+        if (invalidOptions.length > 0)
+        {
+            StringBuilder sb = new StringBuilder("Unknown or invalid option(s):");
+            for (String invalidOption : invalidOptions)
+            {
+                sb.append(" ").append(invalidOption);
+            }
+            handleUsageError(exePath, out, sb.toString());
+        }
+        
+        if (isSwitchActive(args, "V", "version"))
+        {
+            printVersion(exePath, out);
+            return;
+        }
+
+        boolean metadata = false;
+        if (isSwitchActive(args, "m", "metadata"))
+        {
+            metadata = true;
+        }
+
+        String componentTypeString = null;
+        String componentName = null;
+        String propertyName = null;
+        for (int i = 0; i < args.length; i++)
+        {
+            if (!args[i].startsWith("-"))
+            {
+                if (i != (args.length - 3)) {
+                    printHelp(exePath, out);
+                    return;
+                }
+                componentTypeString = args[i];
+                componentName = args[i + 1];
+                propertyName = args[i + 2];
+                break;
+            }
+        }
+
+        String[] tokens = componentTypeString.split(":");
+        if (tokens.length != 2)
+        {
+            handleUsageError(exePath, out, "Invalid component type '" + componentTypeString
+                    + "' - type must be in the form <type>:<subtype> (e.g. JMSDestination:Queue)");
+            return;
+        }
+        String type = tokens[0];
+        String subtype = tokens[1];
+        ComponentType componentType = new ComponentType(type, subtype);
+
+        ManagementView managementView = getProfileService().getViewManager();
+        ManagedComponent component = managementView.getComponent(componentName, componentType);
+        if (component == null) {
+            handleError(out, "Component with type '" + componentTypeString + " and name '"
+                    + componentName + "' not found.");
+            return;
+        }
+
+        Map<String,ManagedProperty> properties;
+        if (propertyName.equals("*")) {
+            properties = component.getProperties();
+        } else {
+            properties = new HashMap();
+            ManagedProperty prop = component.getProperty(propertyName);
+            if (prop == null) {
+                handleError(out, "Property '" + propertyName + "' not found.");
+                return;
+            }
+            properties.put(prop.getName(), prop);
+        }
+        out.print(toString(properties, metadata));
+    }
+
+    public static String toString(Map<String, ManagedProperty> managedProps, boolean metadata)
+    {
+        StringBuilder buf = new StringBuilder();
+        List<ManagedProperty> props = new ArrayList<ManagedProperty>(managedProps.values());
+        Collections.sort(props, new ManagedPropertyComparator()); // sort by name
+        for (ManagedProperty managedProperty : props)
+        {
+            buf.append(managedProperty.getName()).append("=").append(toString(managedProperty.getValue()));            
+            if (metadata) {
+                buf.append(" (");
+                EnumSet<ViewUse> viewUses = getViewUses(managedProperty);
+                buf.append("viewUses=").append(viewUses);
+                buf.append(", readOnly=").append(managedProperty.isReadOnly());
+                buf.append(", mandatory=").append(managedProperty.isMandatory());
+                buf.append(", removed=").append(managedProperty.isRemoved());
+                if (!managedProperty.getName().equals(managedProperty.getMappedName()))
+                    buf.append(", mappedName=").append(managedProperty.getMappedName());                
+                buf.append(", type=").append(managedProperty.getMetaType());
+                buf.append(")");
+            }
+            // TODO: What line separator should we use? (client might be remote)
+            buf.append("\n");
+        }
+        return buf.toString();
+    }
+
+    private static String toString(MetaValue metaValue)
+    {
+        if (metaValue == null) {
+            return "<null>";
+        }
+        MetaType metaType = metaValue.getMetaType();
+        if (metaType.isSimple()) {
+            SimpleValue simpleValue = (SimpleValue)metaValue;
+            Serializable innerValue = simpleValue.getValue();
+            return (innerValue != null) ? innerValue.toString() : "<null>";
+        } else if (metaType.isSimple()) {
+            EnumValue enumValue = (EnumValue)metaValue;
+            String innerValue = enumValue.getValue();
+            return (innerValue != null) ? innerValue : "<null>";
+        } else {
+            // TODO: Decide how to display complex values.
+            /*if (metaValue.getMetaType().isCollection())
+            {
+                CollectionValue collectionValue = (CollectionValue)metaValue;
+                buffer.append(collectionValue).append("\n");
+                for (int i = 0; i < indentLevel; i++) buffer.append("  ");
+                buffer.append("Elements:\n");
+                indentLevel++;
+                for (MetaValue elementMetaValue : collectionValue.getElements())
+                    convertMetaValueToString(elementMetaValue, buffer, true, indentLevel);
+            }
+            else if (metaValue.getMetaType().isComposite())
+            {
+                CompositeValue compositeValue = (CompositeValue)metaValue;
+                buffer.append(compositeValue).append("\n");
+                for (int i = 0; i < indentLevel; i++) buffer.append("  ");
+                buffer.append("Items:\n");
+                indentLevel++;
+                for (String key : compositeValue.getMetaType().keySet()) {
+                    for (int i = 0; i < indentLevel; i++) buffer.append("  ");
+                    buffer.append(key).append("=");
+                    convertMetaValueToString(compositeValue.get(key), buffer, false, indentLevel);
+                }
+            }*/
+            return("<complex>");
+        }
+    }
+
+    public static EnumSet<ViewUse> getViewUses(ManagedProperty managedProperty)
+    {
+        EnumSet<ViewUse> viewUses = EnumSet.noneOf(ViewUse.class);
+        for (ViewUse viewUse : ViewUse.values())
+        {
+            if (managedProperty.hasViewUse(viewUse))
+                viewUses.add(viewUse);
+        }
+        return viewUses;
+    }
+
+    private static class ManagedPropertyComparator implements Comparator<ManagedProperty>
+    {
+        /**
+         * Use viewUse as primary sort field and name as secondary sort field.
+         */
+        public int compare(ManagedProperty prop1, ManagedProperty prop2)
+        {
+            ViewUse prop1ViewUse = getPrimaryViewUse(prop1);
+            ViewUse prop2ViewUse = getPrimaryViewUse(prop2);
+            if (prop1ViewUse == null)
+                return (prop2ViewUse == null) ? 0 : -1;
+            if (prop2ViewUse == null)
+                return 1;
+            int result = prop1ViewUse.name().compareTo(prop2ViewUse.name());
+            if (result == 0)
+                result = prop1.getName().compareTo(prop2.getName()); // break the tie
+            return result;
+        }
+
+        private static ViewUse getPrimaryViewUse(ManagedProperty managedProperty)
+        {
+            ViewUse viewUse;
+            if (managedProperty.hasViewUse(ViewUse.CONFIGURATION))
+                viewUse = ViewUse.CONFIGURATION;
+            else if (managedProperty.hasViewUse(ViewUse.RUNTIME))
+                viewUse = ViewUse.RUNTIME;
+            else if (managedProperty.hasViewUse(ViewUse.STATISTIC))
+                viewUse = ViewUse.STATISTIC;
+            else
+                viewUse = null;
+            return viewUse;
+        }
+    }
+}
\ No newline at end of file


Property changes on: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsGetExe.java
___________________________________________________________________
Name: svn:mime-type
   + text/plain
Name: svn:keywords
   + Date Author Id Revision HeadURL
Name: svn:eol-style
   + LF

Added: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsLsCExe.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsLsCExe.java	                        (rev 0)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsLsCExe.java	2009-05-21 18:52:02 UTC (rev 89257)
@@ -0,0 +1,133 @@
+package org.jboss.fresh.shell.commands.profileservice;
+
+import java.io.PrintWriter;
+import java.io.File;
+import java.util.Comparator;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.jboss.deployers.spi.management.ManagementView;
+import org.jboss.fresh.io.BufferWriter;
+import org.jboss.fresh.io.PrintWriter2;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.ManagedComponent;
+
+/**
+ * A FRESH command for listing Profile Service ManagedComponents.
+ *
+ * @author Ian Springer
+ */
+public class PsLsCExe extends AbstractProfileServiceExe
+{
+    private static final String VERSION = "$Revision$";
+
+    protected String getVersion()
+    {
+        return VERSION;
+    }
+
+    protected void printHelp(String exePath, PrintWriter out)
+    {
+        String exeName = new File(exePath).getName();
+        out.println("Usage: " + exeName + " [options]");
+        out.println("List managed components. Components are sorted by type, and then by name.");
+        out.println("  -h, --help                       display this help and exit");
+        out.println("  -t, --type       TYPE:SUBTYPE    list only components with type TYPE:SUBTYPE");
+        out.println("                                   (e.g. JMSDestination:Queue); wildcards may");
+        out.println("                                   also be used (e.g. JMSDestination:*)");
+        out.println("  -V, --version                    print version information and exit");        
+        out.close();
+        return;
+    }
+
+    protected void process(String exePath, String[] args) throws Exception
+    {
+        PrintWriter2 out = new PrintWriter2(new BufferWriter(getStdOut()));
+
+        if (helpRequested()) {
+            handleUsageError(exePath, out, null);
+        }
+        
+        String[] invalidOptions = getInvalidSwitches(args, "htV", new String[]{"help", "type", "version"});
+        if (invalidOptions.length > 0)
+        {
+            StringBuilder sb = new StringBuilder("Unknown or invalid option(s):");
+            for (String invalidOption : invalidOptions)
+            {
+                sb.append(" ").append(invalidOption);
+            }
+            handleUsageError(exePath, out, sb.toString());
+        }
+
+        ComponentType componentType = null;
+        if (isSwitchActive(args, "t", "type"))
+        {
+            String typeString = getSwitchValue(args, "t", "type");
+            if (typeString == null)
+            {
+                handleUsageError(exePath, out, "The -t/--type option requires an argument.");
+                return;
+            }
+            String[] tokens = typeString.split(":");
+            if (tokens.length != 2)
+            {
+                handleUsageError(exePath, out, "Invalid type '" + typeString
+                        + "' - type must be in the form TYPE:SUBTYPE (e.g. JMSDestination:Queue)");
+                return;
+            }
+            String type = tokens[0];
+            String subtype = tokens[1];
+            componentType = new ComponentType(type, subtype);
+        }
+
+        if (isSwitchActive(args, "V", "version"))
+        {
+            printVersion(exePath, out);
+            return;
+        }
+
+        ManagementView managementView = getProfileService().getViewManager();
+
+        Comparator<ManagedComponent> componentComparator = new Comparator<ManagedComponent>()
+        {
+            public int compare(ManagedComponent component1, ManagedComponent component2)
+            {
+                int value = new ComponentTypeComparator().compare(component1.getType(), component2.getType());
+                // If the types were equal, do a secondary sort by name.
+                return (value != 0) ? value : component1.getName().compareTo(component2.getName());
+            }
+
+            class ComponentTypeComparator implements Comparator<ComponentType>
+            {
+                public int compare(ComponentType type1, ComponentType type2)
+                {
+                    int value = type1.getType().compareTo(type2.getType());
+                    // If the categories (e.g. JMSDestination) were equal, do a secondary sort by subtype (e.g. Queue).
+                    return (value != 0) ? value : type1.getSubtype().compareTo(type2.getSubtype());
+                }
+            }
+        };
+
+        // Use a TreeSet so we can sort at insertion time. Our Comparator's compare() impl compares both component
+        // types and names, which combined are globally unique, so we can safely use a Set rather than a List.
+        Set<ManagedComponent> components = new TreeSet<ManagedComponent>(componentComparator);
+
+        if (componentType != null)
+        {
+            components.addAll(managementView.getComponentsForType(componentType));
+        }
+        else
+        {
+            for (ComponentType type : managementView.getComponentTypes())
+            {
+                components.addAll(managementView.getComponentsForType(type));
+            }
+        }
+
+        for (ManagedComponent component : components)
+        {
+            ComponentType type = component.getType();
+            out.println(component.getName() + " (type: " + type.getType() + ":" + type.getSubtype() + ")");
+        }
+    }
+}
\ No newline at end of file


Property changes on: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsLsCExe.java
___________________________________________________________________
Name: svn:mime-type
   + text/plain
Name: svn:keywords
   + Date Author Id Revision HeadURL
Name: svn:eol-style
   + LF

Added: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsLsDExe.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsLsDExe.java	                        (rev 0)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsLsDExe.java	2009-05-21 18:52:02 UTC (rev 89257)
@@ -0,0 +1,154 @@
+package org.jboss.fresh.shell.commands.profileservice;
+
+import java.io.PrintWriter;
+import java.io.File;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.Comparator;
+
+import org.jboss.deployers.spi.management.ManagementView;
+import org.jboss.fresh.io.BufferWriter;
+import org.jboss.fresh.io.PrintWriter2;
+import org.jboss.managed.api.ManagedDeployment;
+import org.jboss.profileservice.spi.NoSuchDeploymentException;
+
+/**
+ * A FRESH command for listing Profile Service ManagedDeployments.
+ *
+ * @author Ian Springer
+ */
+public class PsLsDExe extends AbstractProfileServiceExe
+{
+    private static final String VERSION = "$Revision$";
+
+    protected String getVersion()
+    {
+        return VERSION;
+    }
+
+    protected void printHelp(String exePath, PrintWriter out)
+    {
+        String exeName = new File(exePath).getName();
+        out.println("Usage: " + exeName + " [options] [rootDeploymentName]");
+        out.println("List managed deployments. If a root deployment is specified, its child deployments are listed, ");
+        out.println("otherwise all deployments are listed. Deployments are sorted by type, and then by name.");
+        out.println("  -h, --help                display this help and exit");
+        out.println("  -t, --type       TYPE     list only deployments with type TYPE (e.g. war)");
+        out.println("  -V, --version             print version information and exit");        
+        out.close();
+        return;
+    }
+
+    protected void process(String exePath, String[] args) throws Exception
+    {
+        PrintWriter2 out = new PrintWriter2(new BufferWriter(getStdOut()));
+
+        if (helpRequested()) {
+            handleUsageError(exePath, out, null);
+        }
+
+        String[] invalidOptions = getInvalidSwitches(args, "htV", new String[]{"help", "type", "version"});
+        if (invalidOptions.length > 0)
+        {
+            StringBuilder sb = new StringBuilder("Unknown or invalid option(s):");
+            for (String invalidOption : invalidOptions)
+            {
+                sb.append(" ").append(invalidOption);
+            }
+            handleUsageError(exePath, out, sb.toString());
+        }
+
+        if (isSwitchActive(args, "V", "version"))
+        {
+            printVersion(exePath, out);
+            return;
+        }
+
+        String type = null;
+        if (isSwitchActive(args, "t", "type"))
+        {
+            type = getSwitchValue(args, "t", "type");
+            if (type == null)
+            {
+                handleUsageError(exePath, out, "The -t/--type option requires an argument.");
+                return;
+            }
+        }
+
+        String rootDeploymentName = null;
+        for (int i = 0; i < args.length; i++)
+        {
+            if (!args[i].startsWith("-"))
+            {
+                if ((i == 0) ||
+                    (!args[i - 1].equals("-t") && !args[i - 1].equals("--type")))
+                {
+                    rootDeploymentName = args[i];
+                    if (i != (args.length - 1)) {
+                        handleUsageError(exePath, out, "Only one root deployment name can be specified.");
+                        return;
+                    }
+                    break;
+                }
+            }
+        }
+
+        ManagementView managementView = getProfileService().getViewManager();
+
+        ManagedDeployment rootDeployment = (rootDeploymentName != null) ?
+                managementView.getDeployment(rootDeploymentName) : null;
+
+        Comparator<ManagedDeployment> deploymentComparator = new Comparator<ManagedDeployment>() {
+            public int compare(ManagedDeployment deployment1, ManagedDeployment deployment2)
+            {
+                // Use "\uFFFF" as the type for deployments with no types, to ensure those deployments are at the end of
+                // the sorted set.
+                String type1 = (deployment1.getTypes() != null) ? deployment1.getTypes().iterator().next() : "\uFFFF";
+                String type2 = (deployment2.getTypes() != null) ? deployment2.getTypes().iterator().next() : "\uFFFF";
+                int value = type1.compareTo(type2);
+                // If the types were equal, do a secondary sort by name.
+                return (value != 0) ? value : deployment1.getName().compareTo(deployment2.getName());
+            }
+        };
+
+        // Use a TreeSet so we can sort at insertion time. Our Comparator's compare() impl compares deployment names,
+        // which are globally unique, so we can safely use a Set rather than a List.
+        Set<ManagedDeployment> deployments = new TreeSet<ManagedDeployment>(deploymentComparator);
+        if (rootDeployment != null)
+        {
+            for (ManagedDeployment childDeployment : rootDeployment.getChildren())
+            {
+                if (type == null || (childDeployment.getTypes() != null && childDeployment.getTypes().contains(type)))
+                {
+                    deployments.add(childDeployment);
+                }
+            }
+        }
+        else
+        {
+            if (type != null)
+            {
+                deployments.addAll(managementView.getDeploymentsForType(type));
+            }
+            else
+            {
+                for (String deploymentName : managementView.getDeploymentNames())
+                {
+                    try
+                    {
+                        deployments.add(managementView.getDeployment(deploymentName));
+                    }
+                    catch (NoSuchDeploymentException e)
+                    {
+                        out.println("ERROR: Deployment named '" + deploymentName + "' not found.");
+                    }
+                }
+            }
+        }
+
+        for (ManagedDeployment deployment : deployments)
+        {
+            out.println(deployment.getName() + " (types: " + deployment.getTypes() + ")");
+        }
+    }
+}


Property changes on: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsLsDExe.java
___________________________________________________________________
Name: svn:mime-type
   + text/plain
Name: svn:keywords
   + Date Author Id Revision HeadURL
Name: svn:eol-style
   + LF

Added: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsSetExe.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsSetExe.java	                        (rev 0)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsSetExe.java	2009-05-21 18:52:02 UTC (rev 89257)
@@ -0,0 +1,303 @@
+package org.jboss.fresh.shell.commands.profileservice;
+
+import java.io.PrintWriter;
+import java.io.File;
+import java.io.Serializable;
+import java.util.Comparator;
+import java.util.Map;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.EnumSet;
+
+import org.jboss.deployers.spi.management.ManagementView;
+import org.jboss.fresh.io.BufferWriter;
+import org.jboss.fresh.io.PrintWriter2;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.api.annotation.ViewUse;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.SimpleValue;
+import org.jboss.metatype.api.values.EnumValue;
+import org.jboss.metatype.api.values.SimpleValueSupport;
+import org.jboss.metatype.api.values.EnumValueSupport;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.types.SimpleMetaType;
+import org.jboss.metatype.api.types.EnumMetaType;
+
+/**
+ * A FRESH command for setting Profile Service ManagedComponent properties.
+ *
+ * @author Ian Springer
+ */
+public class PsSetExe extends AbstractProfileServiceExe
+{
+    private static final String VERSION = "$Revision$";
+
+    protected String getVersion()
+    {
+        return VERSION;
+    }
+
+    protected void printHelp(String exePath, PrintWriter out)
+    {
+        String exeName = new File(exePath).getName();
+        out.println("Usage: " + exeName + " [OPTIONS] COMPONENT_TYPE COMPONENT_NAME PROPERTY=VALUE");
+        out.println("Set a property on the specified component to the specified value, where");
+        out.println("COMPONENT_TYPE is of the form <type>:<subtype> (e.g. JMSDestination:Queue).");
+        out.println("  -h, --help                       display this help and exit");
+        out.println("  -V, --version                    print version information and exit");
+        out.close();
+        return;
+    }
+
+    protected void process(String exePath, String[] args) throws Exception
+    {
+        PrintWriter2 out = new PrintWriter2(new BufferWriter(getStdOut()));
+
+        if (helpRequested()) {
+            handleUsageError(exePath, out, null);
+        }
+
+        if (args.length < 3) {
+            handleUsageError(exePath, out, "Too few arguments.");
+        }
+
+        String[] invalidOptions = getInvalidSwitches(args, "hV", new String[]{"help", "version"});
+        if (invalidOptions.length > 0)
+        {
+            StringBuilder sb = new StringBuilder("Unknown or invalid option(s):");
+            for (String invalidOption : invalidOptions)
+            {
+                sb.append(" ").append(invalidOption);
+            }
+            handleUsageError(exePath, out, sb.toString());
+        }
+
+        if (isSwitchActive(args, "V", "version"))
+        {
+            printVersion(exePath, out);
+            return;
+        }
+
+        String componentTypeString = null;
+        String componentName = null;
+        String propertyNameValue = null;
+        for (int i = 0; i < args.length; i++)
+        {
+            if (!args[i].startsWith("-"))
+            {
+                if (i != (args.length - 3)) {
+                    printHelp(exePath, out);
+                    return;
+                }
+                componentTypeString = args[i];
+                componentName = args[i + 1];
+                propertyNameValue = args[i + 2];
+                break;
+            }
+        }
+
+        String[] tokens = componentTypeString.split(":");
+        if (tokens.length != 2)
+        {
+            handleUsageError(exePath, out, "Invalid component type '" + componentTypeString
+                    + "' - type must be in the form TYPE:SUBTYPE (e.g. JMSDestination:Queue)");
+            return;
+        }
+        String type = tokens[0];
+        String subtype = tokens[1];
+        ComponentType componentType = new ComponentType(type, subtype);
+
+        tokens = propertyNameValue.split("=");
+        if (tokens.length != 2)
+        {
+            handleUsageError(exePath, out, "Invalid property '" + propertyNameValue
+                    + "' - must be in the form PROPERTY=VALUE (e.g. name=Foo)");
+            return;
+        }
+        String propertyName = tokens[0];
+        String propertyValue = tokens[1];
+
+        ManagementView managementView = getProfileService().getViewManager();
+        ManagedComponent component = managementView.getComponent(componentName, componentType);
+        if (component == null) {
+            handleError(out, "Component with type '" + componentTypeString + " and name '"
+                    + componentName + "' not found.");
+            return;
+        }
+
+        ManagedProperty property = component.getProperty(propertyName);
+        if (property == null) {
+            handleError(out, "Property '" + propertyName + "' not found.");
+            return;
+        }
+        MetaType metaType = property.getMetaType();
+        if (!metaType.isSimple() && !metaType.isEnum()) {
+            handleError(out, "Property '" + propertyNameValue + "' has type '" + metaType
+                    + "'. This command only supports setting simples and enums.");
+            return;
+        }
+
+        MetaValue newValue;
+        if (metaType.isSimple()) {
+            // String value is non-null, so we can massage it into the proper type for the SimpleMetaValue's inner value.
+            SimpleMetaType simpleMetaType = (SimpleMetaType)metaType;
+            Serializable innerValue;
+            if (simpleMetaType.equals(SimpleMetaType.STRING) || simpleMetaType.equals(SimpleMetaType.NAMEDOBJECT))
+                innerValue = propertyValue;
+            else if (simpleMetaType.equals(SimpleMetaType.BOOLEAN) || simpleMetaType.equals(SimpleMetaType.BOOLEAN_PRIMITIVE))
+                innerValue = Boolean.valueOf(propertyValue);
+            else if (simpleMetaType.equals(SimpleMetaType.BYTE) || simpleMetaType.equals(SimpleMetaType.BYTE_PRIMITIVE))
+                innerValue = Byte.valueOf(propertyValue);
+            else if (simpleMetaType.equals(SimpleMetaType.CHARACTER) || simpleMetaType.equals(SimpleMetaType.CHARACTER_PRIMITIVE))
+            {
+                if (propertyValue.length() != 1)
+                    throw new IllegalStateException("String value '" + propertyValue + " cannot be converted to a character.");
+                innerValue = propertyValue.charAt(0);
+            }
+            else if (simpleMetaType.equals(SimpleMetaType.DOUBLE) || simpleMetaType.equals(SimpleMetaType.DOUBLE_PRIMITIVE))
+                innerValue = Double.valueOf(propertyValue);
+            else if (simpleMetaType.equals(SimpleMetaType.FLOAT) || simpleMetaType.equals(SimpleMetaType.FLOAT_PRIMITIVE))
+                innerValue = Float.valueOf(propertyValue);
+            else if (simpleMetaType.equals(SimpleMetaType.INTEGER) || simpleMetaType.equals(SimpleMetaType.INTEGER_PRIMITIVE))
+                innerValue = Integer.valueOf(propertyValue);
+            else if (simpleMetaType.equals(SimpleMetaType.LONG) || simpleMetaType.equals(SimpleMetaType.LONG_PRIMITIVE))
+                innerValue = Long.valueOf(propertyValue);
+            else if (simpleMetaType.equals(SimpleMetaType.SHORT) || simpleMetaType.equals(SimpleMetaType.SHORT_PRIMITIVE))
+                innerValue = Short.valueOf(propertyValue);
+            else
+                throw new IllegalStateException("Unsupported MetaType: " + simpleMetaType);
+            newValue = new SimpleValueSupport(simpleMetaType, innerValue);
+        } else if (metaType.isEnum()) {
+            EnumMetaType enumMetaType = (EnumMetaType)metaType;
+            if (!enumMetaType.getValidValues().contains(propertyValue)) {
+                handleError(out, "'" + propertyValue + "' is not a valid value for enum property '" + propertyNameValue
+                        + "'.");
+                return;
+            }
+            newValue = new EnumValueSupport(enumMetaType, propertyValue);
+        } else {
+            // This should never happen.
+            throw new IllegalStateException(metaType.toString());
+        }
+        property.setValue(newValue);
+    }
+
+    public static String convertPropertiesToString(Map<String, ManagedProperty> managedProps, boolean metadata)
+    {
+        StringBuilder buf = new StringBuilder();
+        List<ManagedProperty> props = new ArrayList<ManagedProperty>(managedProps.values());
+        Collections.sort(props, new ManagedPropertyComparator()); // sort by name
+        for (ManagedProperty managedProperty : props)
+        {
+            buf.append(managedProperty.getName()).append("=").append(toString(managedProperty.getValue()));
+            if (metadata) {
+                buf.append(" (");
+                EnumSet<ViewUse> viewUses = getViewUses(managedProperty);
+                buf.append("viewUses=").append(viewUses);
+                buf.append(", readOnly=").append(managedProperty.isReadOnly());
+                buf.append(", mandatory=").append(managedProperty.isMandatory());
+                buf.append(", removed=").append(managedProperty.isRemoved());
+                if (!managedProperty.getName().equals(managedProperty.getMappedName()))
+                    buf.append(", mappedName=").append(managedProperty.getMappedName());
+                Object value = managedProperty.getValue();
+                if (value != null && !(value instanceof MetaValue))
+                    throw new IllegalStateException("Value of ManagedProperty [" + managedProperty.getName()
+                            + "] is not a MetaValue - it is a " + value.getClass().getName() + ".");
+                buf.append(", type=").append(managedProperty.getMetaType());
+                buf.append(")");
+            }
+        }
+        return buf.toString();
+    }
+
+    private static String toString(MetaValue metaValue)
+    {
+        if (metaValue == null) {
+            return "<null>";
+        }
+        MetaType metaType = metaValue.getMetaType();
+        if (metaType.isSimple()) {
+            SimpleValue simpleValue = (SimpleValue)metaValue;
+            Serializable innerValue = simpleValue.getValue();
+            return (innerValue != null) ? innerValue.toString() : "<null>";
+        } else if (metaType.isSimple()) {
+            EnumValue enumValue = (EnumValue)metaValue;
+            String innerValue = enumValue.getValue();
+            return (innerValue != null) ? innerValue : "<null>";
+        } else {
+            // TODO: Decide how to display complex values.
+            /*if (metaValue.getMetaType().isCollection())
+            {
+                CollectionValue collectionValue = (CollectionValue)metaValue;
+                buffer.append(collectionValue).append("\n");
+                for (int i = 0; i < indentLevel; i++) buffer.append("  ");
+                buffer.append("Elements:\n");
+                indentLevel++;
+                for (MetaValue elementMetaValue : collectionValue.getElements())
+                    convertMetaValueToString(elementMetaValue, buffer, true, indentLevel);
+            }
+            else if (metaValue.getMetaType().isComposite())
+            {
+                CompositeValue compositeValue = (CompositeValue)metaValue;
+                buffer.append(compositeValue).append("\n");
+                for (int i = 0; i < indentLevel; i++) buffer.append("  ");
+                buffer.append("Items:\n");
+                indentLevel++;
+                for (String key : compositeValue.getMetaType().keySet()) {
+                    for (int i = 0; i < indentLevel; i++) buffer.append("  ");
+                    buffer.append(key).append("=");
+                    convertMetaValueToString(compositeValue.get(key), buffer, false, indentLevel);
+                }
+            }*/
+            return("<complex>");
+        }
+    }
+
+    public static EnumSet<ViewUse> getViewUses(ManagedProperty managedProperty)
+    {
+        EnumSet<ViewUse> viewUses = EnumSet.noneOf(ViewUse.class);
+        for (ViewUse viewUse : ViewUse.values())
+        {
+            if (managedProperty.hasViewUse(viewUse))
+                viewUses.add(viewUse);
+        }
+        return viewUses;
+    }
+
+    private static class ManagedPropertyComparator implements Comparator<ManagedProperty>
+    {
+        /**
+         * Use viewUse as primary sort field and name as secondary sort field.
+         */
+        public int compare(ManagedProperty prop1, ManagedProperty prop2)
+        {
+            ViewUse prop1ViewUse = getPrimaryViewUse(prop1);
+            ViewUse prop2ViewUse = getPrimaryViewUse(prop2);
+            if (prop1ViewUse == null)
+                return (prop2ViewUse == null) ? 0 : -1;
+            if (prop2ViewUse == null)
+                return 1;
+            int result = prop1ViewUse.name().compareTo(prop2ViewUse.name());
+            if (result == 0)
+                result = prop1.getName().compareTo(prop2.getName()); // break the tie
+            return result;
+        }
+
+        private static ViewUse getPrimaryViewUse(ManagedProperty managedProperty)
+        {
+            ViewUse viewUse;
+            if (managedProperty.hasViewUse(ViewUse.CONFIGURATION))
+                viewUse = ViewUse.CONFIGURATION;
+            else if (managedProperty.hasViewUse(ViewUse.RUNTIME))
+                viewUse = ViewUse.RUNTIME;
+            else if (managedProperty.hasViewUse(ViewUse.STATISTIC))
+                viewUse = ViewUse.STATISTIC;
+            else
+                viewUse = null;
+            return viewUse;
+        }
+    }
+}
\ No newline at end of file


Property changes on: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/profileservice/PsSetExe.java
___________________________________________________________________
Name: svn:mime-type
   + text/plain
Name: svn:keywords
   + Date Author Id Revision HeadURL
Name: svn:eol-style
   + LF




More information about the jboss-cvs-commits mailing list