001    /**
002     *
003     * Licensed to the Apache Software Foundation (ASF) under one or more
004     * contributor license agreements.  See the NOTICE file distributed with
005     * this work for additional information regarding copyright ownership.
006     * The ASF licenses this file to You under the Apache License, Version 2.0
007     * (the "License"); you may not use this file except in compliance with
008     * the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     *  Unless required by applicable law or agreed to in writing, software
013     *  distributed under the License is distributed on an "AS IS" BASIS,
014     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     *  See the License for the specific language governing permissions and
016     *  limitations under the License.
017     */
018    package org.apache.activemq.karaf.commands;
019    
020    import java.lang.reflect.Field;
021    import java.lang.reflect.Type;
022    import java.util.ArrayList;
023    import java.util.HashMap;
024    import java.util.Iterator;
025    import java.util.List;
026    import java.util.Map;
027    
028    import org.apache.felix.gogo.commands.Action;
029    import org.apache.felix.gogo.commands.Argument;
030    import org.apache.felix.gogo.commands.basic.AbstractCommand;
031    import org.apache.felix.gogo.commands.basic.ActionPreparator;
032    import org.apache.felix.gogo.commands.basic.DefaultActionPreparator;
033    import org.apache.felix.service.command.CommandSession;
034    import org.apache.karaf.shell.console.BlueprintContainerAware;
035    import org.apache.karaf.shell.console.BundleContextAware;
036    import org.apache.karaf.shell.console.CompletableFunction;
037    import org.apache.karaf.shell.console.Completer;
038    import org.apache.karaf.shell.console.commands.GenericType;
039    import org.osgi.framework.BundleContext;
040    import org.osgi.service.blueprint.container.BlueprintContainer;
041    import org.osgi.service.blueprint.container.Converter;
042    
043    /**
044     * Base command to process options and wrap native ActiveMQ console commands.
045     */
046    public class ActiveMQCommand extends AbstractCommand implements CompletableFunction
047    {
048        protected BlueprintContainer blueprintContainer;
049        protected Converter blueprintConverter;
050        protected String actionId;
051        protected List<Completer> completers;
052    
053        public void setBlueprintContainer(BlueprintContainer blueprintContainer) {
054            this.blueprintContainer = blueprintContainer;
055        }
056    
057        public void setBlueprintConverter(Converter blueprintConverter) {
058            this.blueprintConverter = blueprintConverter;
059        }
060    
061        public void setActionId(String actionId) {
062            this.actionId = actionId;
063        }
064    
065        @Override
066        public List<Completer> getCompleters() {
067            return completers;
068        }
069    
070        public void setCompleters(List<Completer> completers) {
071            this.completers = completers;
072        }
073    
074        @Override
075        protected ActionPreparator getPreparator() throws Exception {
076            return new ActiveMQActionPreparator();
077        }
078    
079        class ActiveMQActionPreparator extends DefaultActionPreparator {
080            @Override
081            public boolean prepare(Action action, CommandSession session, List<Object> params) throws Exception
082            {
083                Map<Argument, Field> arguments = new HashMap<Argument, Field>();
084                List<Argument> orderedArguments = new ArrayList<Argument>();
085                // Introspect
086                for (Class type = action.getClass(); type != null; type = type.getSuperclass()) {
087                    for (Field field : type.getDeclaredFields()) {
088                        Argument argument = field.getAnnotation(Argument.class);
089                        if (argument != null) {
090                            arguments.put(argument, field);
091                            int index = argument.index();
092                            while (orderedArguments.size() <= index) {
093                                orderedArguments.add(null);
094                            }
095                            if (orderedArguments.get(index) != null) {
096                                throw new IllegalArgumentException("Duplicate argument index: " + index);
097                            }
098                            orderedArguments.set(index, argument);
099                        }
100                    }
101                }
102                // Check indexes are correct
103                for (int i = 0; i < orderedArguments.size(); i++) {
104                    if (orderedArguments.get(i) == null) {
105                        throw new IllegalArgumentException("Missing argument for index: " + i);
106                    }
107                }
108                // Populate
109                Map<Argument, Object> argumentValues = new HashMap<Argument, Object>();
110                int argIndex = 0;
111                for (Iterator<Object> it = params.iterator(); it.hasNext();) {
112                    Object param = it.next();
113                    if (argIndex >= orderedArguments.size()) {
114                        throw new IllegalArgumentException("Too many arguments specified");
115                    }
116                    Argument argument = orderedArguments.get(argIndex);
117                    if (!argument.multiValued()) {
118                        argIndex++;
119                    }
120                    if (argument.multiValued()) {
121                        List<Object> l = (List<Object>) argumentValues.get(argument);
122                        if (l == null) {
123                            l = new ArrayList<Object>();
124                            argumentValues.put(argument, l);
125                        }
126                        l.add(param);
127                    } else {
128                        argumentValues.put(argument, param);
129                    }
130                }
131    
132                for (Map.Entry<Argument, Object> entry : argumentValues.entrySet()) {
133                    Field field = arguments.get(entry.getKey());
134                    Object value = convert(action, session, entry.getValue(), field.getGenericType());
135                    field.setAccessible(true);
136                    field.set(action, value);
137                }
138                return true;
139            }
140    
141            @Override
142            protected Object convert(Action action, CommandSession commandSession, Object o, Type type) throws Exception {
143                return blueprintConverter.convert(o, new GenericType(type));
144            }
145        }
146    
147        @Override
148        public Action createNewAction() {
149            Action action = (Action) blueprintContainer.getComponentInstance(actionId);
150            if (action instanceof BlueprintContainerAware) {
151                ((BlueprintContainerAware) action).setBlueprintContainer(blueprintContainer);
152            }
153            if (action instanceof BundleContextAware) {
154                BundleContext context = (BundleContext) blueprintContainer.getComponentInstance("blueprintBundleContext");
155                ((BundleContextAware) action).setBundleContext(context);
156            }
157            return action;
158        }
159    
160        @Override
161        public Map<String, Completer> getOptionalCompleters() {
162            //TODO implement completers
163            return null;
164        }
165    }