001/* 002 * Syncany, www.syncany.org 003 * Copyright (C) 2011-2016 Philipp C. Heckel <philipp.heckel@gmail.com> 004 * 005 * This program is free software: you can redistribute it and/or modify 006 * it under the terms of the GNU General Public License as published by 007 * the Free Software Foundation, either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU General Public License for more details. 014 * 015 * You should have received a copy of the GNU General Public License 016 * along with this program. If not, see <http://www.gnu.org/licenses/>. 017 */ 018package org.syncany.cli; 019 020import java.util.logging.Level; 021import java.util.logging.Logger; 022 023import org.syncany.util.StringUtil; 024 025/** 026 * The command factory can be used to instantiate a new command from a 027 * command name. The {@link CommandLineClient} uses this class to create 028 * and run commands by mapping a command argument to a corresponding 029 * {@link Command} class. 030 * 031 * @author Philipp C. Heckel (philipp.heckel@gmail.com) 032 */ 033public class CommandFactory { 034 private static final Logger logger = Logger.getLogger(CommandFactory.class.getSimpleName()); 035 036 /** 037 * Maps the given command name to a corresponding {@link Command} class and 038 * instantiates it. The command name is camel-cased and mapped to a FQCN. 039 * 040 * <p>Example: The command 'ls-remote' is mapped to the FQCN 041 * <code>org.syncany.cli.LsRemoteCommand</code>. 042 * 043 * @param commandName Command name, e.g. ls-remote or init 044 * @return Returns a <code>Command</code> instance, or <code>null</code> if the command name cannot be mapped to a class 045 */ 046 public static Command getInstance(String commandName) { 047 String thisPackage = CommandFactory.class.getPackage().getName(); 048 String camelCaseCommandName = StringUtil.toCamelCase(commandName); 049 String fqCommandClassName = thisPackage+"."+camelCaseCommandName+Command.class.getSimpleName(); 050 051 // Try to load! 052 try { 053 Class<?> commandClass = Class.forName(fqCommandClassName); 054 return (Command) commandClass.newInstance(); 055 } 056 catch (Exception ex) { 057 logger.log(Level.INFO, "Could not find operation FQCN " + fqCommandClassName, ex); 058 return null; 059 } 060 } 061}