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.karaf.commands;
018    
019    import java.io.File;
020    import java.io.FileOutputStream;
021    import java.io.IOException;
022    import java.io.InputStream;
023    import java.io.OutputStream;
024    import java.io.PrintStream;
025    import java.util.HashMap;
026    import java.util.Map;
027    import java.util.Scanner;
028    
029    import org.apache.felix.gogo.commands.Option;
030    import org.apache.felix.gogo.commands.Command;
031    import org.apache.karaf.shell.console.OsgiCommandSupport;
032    
033    /**
034     * @version $Rev: 960482 $ $Date: 2010-07-05 10:28:33 +0200 (Mon, 05 Jul 2010) $
035     */
036     @Command(scope="activemq", name="create-broker", description="Creates a broker instance.")
037    public class CreateBrokerCommand extends OsgiCommandSupport {
038        
039        @Option(name = "-n", aliases = {"--name"}, description = "The name of the broker (defaults to localhost).")
040        private String name = "localhost";
041        @Option(name = "-t", aliases = {"--type"}, description = "type of configuration to be used: spring or blueprint (defaults to spring)")
042        private String type = "spring";
043    
044        /*
045         * (non-Javadoc)
046         * @see
047         * org.apache.karaf.shell.console.OsgiCommandSupport#doExecute()
048         */
049        protected Object doExecute() throws Exception {
050    
051            try {
052                String name = getName();
053                File base = new File(System.getProperty("karaf.base"));
054                File deploy = new File(base, "deploy");
055    
056                HashMap<String, String> props = new HashMap<String, String>();
057                props.put("${name}", name);
058    
059                mkdir(deploy);
060                File configFile = new File(deploy, name + "-broker.xml");
061                
062                if (!type.equalsIgnoreCase("spring") && !type.equalsIgnoreCase("blueprint")) {
063                    System.out.println("@|green Unknown type '" + type + "' Using spring by default");
064                    type = "spring";
065                }
066                
067                copyFilteredResourceTo(configFile, type.toLowerCase() + ".xml", props);
068    
069                System.out.println("");
070                System.out.println("Default ActiveMQ Broker (" + name + ") configuration file created at: "
071                               + configFile.getPath());
072                System.out.println("Please review the configuration and modify to suite your needs.  ");
073                System.out.println("");
074    
075            } catch (Exception e) {
076                e.printStackTrace();
077                throw e;
078            }
079    
080            return 0;
081        }
082    
083        private void copyFilteredResourceTo(File outFile, String resource, HashMap<String, String> props)
084            throws Exception {
085            if (!outFile.exists()) {
086                System.out.println("Creating file: @|green " + outFile.getPath() + "|");
087                InputStream is = CreateBrokerCommand.class.getResourceAsStream(resource);
088                try {
089                    // Read it line at a time so that we can use the platform line
090                    // ending when we write it out.
091                    PrintStream out = new PrintStream(new FileOutputStream(outFile));
092                    try {
093                        Scanner scanner = new Scanner(is);
094                        while (scanner.hasNextLine()) {
095                            String line = scanner.nextLine();
096                            line = filter(line, props);
097                            out.println(line);
098                        }
099                    } finally {
100                        safeClose(out);
101                    }
102                } finally {
103                    safeClose(is);
104                }
105            } else {
106                System.out.println("@|red File already exists|. Move it out of the way if you want it re-created: "
107                               + outFile.getPath() + "");
108            }
109        }
110    
111        private void safeClose(InputStream is) throws IOException {
112            if (is == null)
113                return;
114            try {
115                is.close();
116            } catch (Throwable ignore) {
117            }
118        }
119    
120        private void safeClose(OutputStream is) throws IOException {
121            if (is == null)
122                return;
123            try {
124                is.close();
125            } catch (Throwable ignore) {
126            }
127        }
128    
129        private String filter(String line, HashMap<String, String> props) {
130            for (Map.Entry<String, String> i : props.entrySet()) {
131                int p1;
132                while ((p1 = line.indexOf(i.getKey())) >= 0) {
133                    String l1 = line.substring(0, p1);
134                    String l2 = line.substring(p1 + i.getKey().length());
135                    line = l1 + i.getValue() + l2;
136                }
137            }
138            return line;
139        }
140    
141        private void mkdir(File file) {
142            if (!file.exists()) {
143                System.out.println("Creating missing directory: @|green " + file.getPath() + "|");
144                file.mkdirs();
145            }
146        }
147    
148        public String getName() {
149            if (name == null) {
150                File base = new File(System.getProperty("karaf.base"));
151                name = base.getName();
152            }
153            return name;
154        }
155    
156        public void setName(String name) {
157            this.name = name;
158        }
159    
160    }