001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.activemq.console.command;
018    
019    import java.io.BufferedReader;
020    import java.io.File;
021    import java.io.FileInputStream;
022    import java.io.FileNotFoundException;
023    import java.io.FileOutputStream;
024    import java.io.IOException;
025    import java.io.InputStreamReader;
026    import java.nio.ByteBuffer;
027    import java.nio.channels.FileChannel;
028    import java.util.List;
029    
030    import javax.xml.parsers.DocumentBuilder;
031    import javax.xml.parsers.DocumentBuilderFactory;
032    import javax.xml.parsers.ParserConfigurationException;
033    import javax.xml.transform.Result;
034    import javax.xml.transform.Source;
035    import javax.xml.transform.Transformer;
036    import javax.xml.transform.TransformerException;
037    import javax.xml.transform.TransformerFactory;
038    import javax.xml.transform.dom.DOMSource;
039    import javax.xml.transform.stream.StreamResult;
040    import javax.xml.xpath.XPath;
041    import javax.xml.xpath.XPathConstants;
042    import javax.xml.xpath.XPathExpressionException;
043    import javax.xml.xpath.XPathFactory;
044    
045    import org.w3c.dom.Attr;
046    import org.w3c.dom.Element;
047    import org.xml.sax.SAXException;
048    
049    public class CreateCommand extends AbstractCommand {
050    
051        protected final String[] helpFile = new String[] {
052            "Task Usage: Main create path/to/brokerA [create-options]",
053            "Description:  Creates a runnable broker instance in the specified path.",
054            "",
055            "List Options:",
056            "    --amqconf <file path>   Path to ActiveMQ conf file that will be used in the broker instance. Default is: conf/activemq.xml",
057            "    --version               Display the version information.",
058            "    -h,-?,--help            Display the create broker help information.",
059            ""
060        };
061    
062        protected final String DEFAULT_TARGET_ACTIVEMQ_CONF = "conf/activemq.xml"; // default activemq conf to create in the new broker instance
063        protected final String DEFAULT_BROKERNAME_XPATH = "/beans/broker/@brokerName"; // default broker name xpath to change the broker name
064    
065        protected final String[] BASE_SUB_DIRS = { "bin", "conf" }; // default sub directories that will be created
066        protected final String BROKER_NAME_REGEX = "[$][{]brokerName[}]"; // use to replace broker name property holders
067    
068        protected String amqConf = "conf/activemq.xml"; // default conf if no conf is specified via --amqconf
069    
070        // default files to copy from activemq home to the new broker instance
071        protected String[][] fileCopyMap = {
072            { "conf/log4j.properties", "conf/log4j.properties" },
073            { "conf/broker.ks", "conf/broker.ks" },
074            { "conf/broker.ts", "conf/broker.ts" },
075            { "conf/camel.xml", "conf/camel.xml" },
076            { "conf/jetty.xml", "conf/jetty.xml" },
077            { "conf/credentials.properties", "conf/credentials.properties" }
078        };
079    
080        // default files to create 
081        protected String[][] fileWriteMap = {
082            { "winActivemq", "bin/${brokerName}.bat" },
083            { "unixActivemq", "bin/${brokerName}" }
084        };
085    
086    
087        protected String brokerName;
088        protected File amqHome;
089        protected File targetAmqBase;
090    
091        protected void runTask(List<String> tokens) throws Exception {
092            context.print("Running create broker task...");
093            amqHome = new File(System.getProperty("activemq.home"));
094            for (String token : tokens) {
095    
096                targetAmqBase = new File(token);
097                brokerName = targetAmqBase.getName();
098                
099    
100                if (targetAmqBase.exists()) {
101                    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
102                    String resp;
103                    while (true) {
104                        context.print("Target directory (" + targetAmqBase.getCanonicalPath() + ") already exists. Overwrite (y/n): ");
105                        resp = console.readLine();
106                        if (resp.equalsIgnoreCase("y") || resp.equalsIgnoreCase("yes")) {
107                            break;
108                        } else if (resp.equalsIgnoreCase("n") || resp.equalsIgnoreCase("no")) {
109                            return;
110                        }
111                    }
112                }
113    
114                context.print("Creating directory: " + targetAmqBase.getCanonicalPath());
115                targetAmqBase.mkdirs();
116                createSubDirs(targetAmqBase, BASE_SUB_DIRS);
117                writeFileMapping(targetAmqBase, fileWriteMap);
118                copyActivemqConf(amqHome, targetAmqBase, amqConf);
119                copyFileMapping(amqHome, targetAmqBase, fileCopyMap);
120            }
121        }
122    
123        /**
124         * Handle the --amqconf options.
125         *
126         * @param token  - option token to handle
127         * @param tokens - succeeding command arguments
128         * @throws Exception
129         */
130        protected void handleOption(String token, List<String> tokens) throws Exception {
131            if (token.startsWith("--amqconf")) {
132                // If no amqconf specified, or next token is a new option
133                if (tokens.isEmpty() || tokens.get(0).startsWith("-")) {
134                    context.printException(new IllegalArgumentException("Attributes to amqconf not specified"));
135                    return;
136                }
137    
138                amqConf = tokens.remove(0);
139            } else {
140                // Let super class handle unknown option
141                super.handleOption(token, tokens);
142            }
143        }
144    
145        protected void createSubDirs(File target, String[] subDirs) throws IOException {
146            File subDirFile;
147            for (String subDir : BASE_SUB_DIRS) {
148                subDirFile = new File(target, subDir);
149                context.print("Creating directory: " + subDirFile.getCanonicalPath());
150                subDirFile.mkdirs();
151            }
152        }
153    
154        protected void writeFileMapping(File targetBase, String[][] fileWriteMapping) throws IOException {
155            for (String[] fileWrite : fileWriteMapping) {
156                File dest = new File(targetBase, resolveParam(BROKER_NAME_REGEX, brokerName, fileWrite[1]));
157                context.print("Creating new file: " + dest.getCanonicalPath());
158                writeFile(fileWrite[0], dest);
159            }
160        }
161    
162        protected void copyFileMapping(File srcBase, File targetBase, String[][] fileMapping) throws IOException {
163            for (String[] fileMap : fileMapping) {
164                File src = new File(srcBase, fileMap[0]);
165                File dest = new File(targetBase, resolveParam(BROKER_NAME_REGEX, brokerName, fileMap[1]));
166                context.print("Copying from: " + src.getCanonicalPath() + "\n          to: " + dest.getCanonicalPath());
167                copyFile(src, dest);
168            }
169        }
170    
171        protected void copyActivemqConf(File srcBase, File targetBase, String activemqConf) throws IOException, ParserConfigurationException, SAXException, TransformerException, XPathExpressionException {
172            File src = new File(srcBase, activemqConf);
173    
174            if (!src.exists()) {
175                throw new FileNotFoundException("File: " + src.getCanonicalPath() + " not found.");
176            }
177    
178            File dest = new File(targetBase, DEFAULT_TARGET_ACTIVEMQ_CONF);
179            context.print("Copying from: " + src.getCanonicalPath() + "\n          to: " + dest.getCanonicalPath());
180    
181            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
182            Element docElem = builder.parse(src).getDocumentElement();
183    
184            XPath xpath = XPathFactory.newInstance().newXPath();
185            Attr brokerNameAttr = (Attr) xpath.evaluate(DEFAULT_BROKERNAME_XPATH, docElem, XPathConstants.NODE);
186            brokerNameAttr.setValue(brokerName);
187    
188            writeToFile(new DOMSource(docElem), dest);
189        }
190    
191        protected void printHelp() {
192            context.printHelp(helpFile);
193        }
194    
195        // write the default files to create (i.e. script files)
196        private void writeFile(String typeName, File dest) throws IOException {
197            String data;
198            if (typeName.equals("winActivemq")) {
199                data = winActivemqData;
200                data = resolveParam("[$][{]activemq.home[}]", amqHome.getCanonicalPath().replaceAll("[\\\\]", "/"), data);
201                data = resolveParam("[$][{]activemq.base[}]", targetAmqBase.getCanonicalPath().replaceAll("[\\\\]", "/"), data);
202            } else if (typeName.equals("unixActivemq")) {
203                data = unixActivemqData;
204                data = resolveParam("[$][{]activemq.home[}]", amqHome.getCanonicalPath().replaceAll("[\\\\]", "/"), data);
205                data = resolveParam("[$][{]activemq.base[}]", targetAmqBase.getCanonicalPath().replaceAll("[\\\\]", "/"), data);
206            } else {
207                throw new IllegalStateException("Unknown file type: " + typeName);
208            }
209    
210            ByteBuffer buf = ByteBuffer.allocate(data.length());
211            buf.put(data.getBytes());
212            buf.flip();
213    
214            FileChannel destinationChannel = new FileOutputStream(dest).getChannel();
215            destinationChannel.write(buf);
216            destinationChannel.close();
217    
218            // Set file permissions available for Java 6.0 only
219    //        dest.setExecutable(true);
220    //        dest.setReadable(true);
221    //        dest.setWritable(true);
222        }
223    
224        // utlity method to write an xml source to file
225        private void writeToFile(Source src, File file) throws TransformerException {
226            TransformerFactory tFactory = TransformerFactory.newInstance();
227            Transformer fileTransformer = tFactory.newTransformer();
228    
229            Result res = new StreamResult(file);
230            fileTransformer.transform(src, res);
231        }
232    
233        // utility method to copy one file to another
234        private void copyFile(File from, File dest) throws IOException {
235            if (!from.exists()) {
236                return;
237            }
238            FileChannel sourceChannel = new FileInputStream(from).getChannel();
239            FileChannel destinationChannel = new FileOutputStream(dest).getChannel();
240            sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
241            sourceChannel.close();
242            destinationChannel.close();
243        }
244    
245        // replace a property place holder (paramName) with the paramValue
246        private String resolveParam(String paramName, String paramValue, String target) {
247            return target.replaceAll(paramName, paramValue);
248        }
249    
250        // Embedded windows script data
251        private static final String winActivemqData =
252            "@echo off\n"
253                + "set ACTIVEMQ_HOME=\"${activemq.home}\"\n"
254                + "set ACTIVEMQ_BASE=\"${activemq.base}\"\n"
255                + "\n"
256                + "set PARAM=%1\n"
257                + ":getParam\n"
258                + "shift\n"
259                + "if \"%1\"==\"\" goto end\n"
260                + "set PARAM=%PARAM% %1\n"
261                + "goto getParam\n"
262                + ":end\n"
263                + "\n"
264                + "%ACTIVEMQ_HOME%/bin/activemq %PARAM%";
265    
266    
267        // Embedded unix script data
268        private static final String unixActivemqData = "## Figure out the ACTIVEMQ_BASE from the directory this script was run from\n"
269            + "PRG=\"$0\"\n"
270            + "progname=`basename \"$0\"`\n"
271            + "saveddir=`pwd`\n"
272            + "# need this for relative symlinks\n"
273            + "dirname_prg=`dirname \"$PRG\"`\n"
274            + "cd \"$dirname_prg\"\n"
275            + "while [ -h \"$PRG\" ] ; do\n"
276            + "  ls=`ls -ld \"$PRG\"`\n"
277            + "  link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n"
278            + "  if expr \"$link\" : '.*/.*' > /dev/null; then\n"
279            + "    PRG=\"$link\"\n"
280            + "  else\n"
281            + "    PRG=`dirname \"$PRG\"`\"/$link\"\n"
282            + "  fi\n"
283            + "done\n"
284            + "ACTIVEMQ_BASE=`dirname \"$PRG\"`/..\n"
285            + "cd \"$saveddir\"\n"
286            + "\n"
287            + "ACTIVEMQ_BASE=`cd \"$ACTIVEMQ_BASE\" && pwd`\n\n"
288            + "export ACTIVEMQ_HOME=${activemq.home}\n"
289            + "export ACTIVEMQ_BASE=$ACTIVEMQ_BASE\n\n"
290            + "${ACTIVEMQ_HOME}/bin/activemq \"$*\"";
291    
292    }