View Javadoc

1   /*--------------------------------------------------------------------------
2    *  Copyright 2008 utgenome.org
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   *--------------------------------------------------------------------------*/
16  //--------------------------------------
17  // utgb-shell Project
18  //
19  // UTGBShell.java 
20  // Since: Jan 8, 2008
21  //
22  // $URL$ 
23  // $Author$
24  //--------------------------------------
25  package org.utgenome.shell;
26  
27  import java.awt.Dimension;
28  import java.awt.Toolkit;
29  import java.io.BufferedReader;
30  import java.io.File;
31  import java.io.InputStream;
32  import java.io.InputStreamReader;
33  import java.io.PrintWriter;
34  import java.lang.reflect.Modifier;
35  import java.util.List;
36  import java.util.TreeMap;
37  
38  import javax.swing.ImageIcon;
39  import javax.swing.JFrame;
40  import javax.swing.SwingUtilities;
41  
42  import org.xerial.core.XerialException;
43  import org.xerial.util.FileResource;
44  import org.xerial.util.ResourceFilter;
45  import org.xerial.util.bean.BeanUtil;
46  import org.xerial.util.io.VirtualFile;
47  import org.xerial.util.log.LogLevel;
48  import org.xerial.util.log.Logger;
49  import org.xerial.util.opt.Argument;
50  import org.xerial.util.opt.Option;
51  import org.xerial.util.opt.OptionParser;
52  
53  /**
54   * A command line client entry point
55   * 
56   * @author leo
57   * 
58   */
59  public class UTGBShell {
60  	private static Logger _logger = Logger.getLogger(UTGBShell.class);
61  
62  	public static TreeMap<String, UTGBShellSubCommand> subCommandTable = new TreeMap<String, UTGBShellSubCommand>();
63  
64  	/**
65  	 * search sub commands from the this package (org.utgenome.shell)
66  	 */
67  	public static void searchSubCommands() {
68  		String shellPackage = UTGBShell.class.getPackage().getName();
69  		List<VirtualFile> classFileList = FileResource.listResources(shellPackage, new ResourceFilter() {
70  			public boolean accept(String resourcePath) {
71  				return resourcePath.endsWith(".class");
72  			}
73  		});
74  		for (VirtualFile vf : classFileList) {
75  			String logicalPath = vf.getLogicalPath();
76  			int dot = logicalPath.lastIndexOf(".");
77  			if (dot <= 0)
78  				continue;
79  			String className = shellPackage + "." + logicalPath.substring(0, dot).replaceAll("/", ".");
80  			try {
81  				Class<?> c = Class.forName(className, false, UTGBShell.class.getClassLoader());
82  				if (!Modifier.isAbstract(c.getModifiers()) && UTGBShellSubCommandBase.class.isAssignableFrom(c)) {
83  					// found a sub command class
84  					UTGBShellSubCommand subCommand = (UTGBShellSubCommand) c.newInstance();
85  					if (subCommand == null)
86  						continue;
87  					subCommandTable.put(subCommand.name(), subCommand);
88  				}
89  			}
90  			catch (ClassNotFoundException e) {
91  				continue;
92  			}
93  			catch (InstantiationException e) {
94  				_logger.error(e);
95  			}
96  			catch (IllegalAccessException e) {
97  				_logger.error(e);
98  			}
99  		}
100 	}
101 
102 	static {
103 		// search the all available sub commands
104 		searchSubCommands();
105 
106 		// System.setProperty("com.apple.eawt.CocoaComponent.CompatibilityMode", "false");
107 	}
108 
109 	public static class UTGBShellOption {
110 		@Option(symbol = "h", longName = "help", description = "display help message")
111 		private boolean displayHelp = false;
112 
113 		@Option(symbol = "v", longName = "version", description = "display version")
114 		private boolean displayVersion = false;
115 
116 		@Argument(index = 0, required = false)
117 		private String subCommand = null;
118 
119 		@Option(symbol = "l", longName = "loglevel", description = "set log level: TRACE, DEBUG, INFO(default), WARN, ERROR, FATAL")
120 		private LogLevel logLevel = null;
121 
122 		@Option(symbol = "d", longName = "projectDir")
123 		public String projectDir = new File("").getAbsolutePath();
124 
125 		@Option(symbol = "e", longName = "env", varName = "test|development|production", description = "running mode (default: development)")
126 		public String runningMode = "development";
127 
128 		@Option(symbol = "gui", longName = "launch in GUI mode")
129 		public boolean useGUI = false;
130 
131 	}
132 
133 	public static void main(String[] args) {
134 		UTGBShellOption opt = new UTGBShellOption();
135 		OptionParser optionParser = new OptionParser(opt);
136 		optionParser.setIgnoreUnknownOption(true);
137 
138 		try {
139 			optionParser.parse(args);
140 
141 			if (opt.logLevel != null)
142 				Logger.getRootLogger().setLogLevel(opt.logLevel);
143 
144 			Logger.getRootLogger().setOutputWriter(new PrintWriter(System.err));
145 
146 			if (opt.useGUI) {
147 				SwingUtilities.invokeAndWait(new Runnable() {
148 
149 					public void run() {
150 						JFrame f = new JFrame();
151 						f.setTitle("UTGB Toolkit");
152 						ImageIcon imageIcon = new ImageIcon(FileResource.find(UTGBPortableWidget.class, "utgb-icon.png"));
153 						f.setIconImage(imageIcon.getImage());
154 						f.pack();
155 
156 						f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
157 						Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
158 						f.setLocation((int) d.getWidth() / 4, (int) d.getHeight() / 4);
159 						f.setVisible(true);
160 					}
161 				});
162 				return;
163 			}
164 
165 			if (opt.subCommand != null) {
166 				// go to sub command processing
167 				UTGBShellSubCommand subCommand = subCommandTable.get(opt.subCommand);
168 				if (subCommand != null) {
169 					if (opt.displayHelp) {
170 						System.out.println(subCommand.getDetailedDescription());
171 						System.out.println("[available options]");
172 						System.out.println(subCommand.getOptionList());
173 						return;
174 					}
175 					else {
176 						// copy the rest of the command line arguments
177 						subCommand.execute(opt, optionParser.getUnusedArguments());
178 						return;
179 					}
180 				}
181 				else {
182 					System.err.println("unknown subcommand: " + opt.subCommand);
183 				}
184 			}
185 			else {
186 				if (opt.displayHelp) {
187 					// display help message
188 					System.out.println(getProgramInfo());
189 					BufferedReader helpReader = FileResource.open(UTGBShell.class, "help-message.txt");
190 					String line;
191 					while ((line = helpReader.readLine()) != null)
192 						System.out.println(line);
193 					// list command line options
194 					optionParser.printUsage();
195 					// list all sub commands
196 					System.out.println("[sub commands]");
197 					for (String subCommandName : subCommandTable.keySet()) {
198 						UTGBShellSubCommand sc = subCommandTable.get(subCommandName);
199 						System.out.format("  %-10s\t%s", subCommandName, sc.getOneLinerDescription());
200 						System.out.println();
201 					}
202 					return;
203 				}
204 				if (opt.displayVersion) {
205 					System.out.println(getProgramInfo());
206 					return;
207 				}
208 			}
209 
210 			// display a short help message
211 			System.out.println(getProgramInfo());
212 			System.out.println("type --help for a list of the available sub commands.");
213 		}
214 		catch (Exception e) {
215 			System.err.println(e.getMessage());
216 		}
217 		catch (Error e) {
218 			System.err.println(e.getMessage());
219 		}
220 
221 	}
222 
223 	public static String getProgramInfo() {
224 		return "UTGB Shell: version " + getVersion() + " (" + getRevision() + ")";
225 	}
226 
227 	public static String getRevision() {
228 		return getPom().getRevision();
229 	}
230 
231 	private static POM getPom() {
232 		POM pom = new POM();
233 		// read the pom.xml file and extract the version information
234 		try {
235 			// load the pom.xml file copied as a resource
236 			InputStream pomIn = UTGBShell.class.getResourceAsStream("/META-INF/maven/org.utgenome/utgb-shell/pom.xml");
237 			if (pomIn != null) {
238 				BufferedReader pomReader = new BufferedReader(new InputStreamReader(pomIn));
239 				if (pomReader != null)
240 					BeanUtil.populateBeanWithXML(pom, pomReader);
241 			}
242 		}
243 		catch (XerialException e) {
244 			_logger.debug(e);
245 		}
246 		return pom;
247 	}
248 
249 	public static String getVersion() {
250 		return getPom().getVersion();
251 	}
252 }