<commit_before>/**
 *  Copyright (C) 2010 Cloud.com, Inc.  All rights reserved.
 * 
 * This software is licensed under the GNU General Public License v3 or later.
 * 
 * It is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package com.cloud.api;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import com.cloud.agent.manager.AgentManager;
import com.cloud.api.BaseCmd.CommandType;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.consoleproxy.ConsoleProxyManager;
import com.cloud.network.NetworkManager;
import com.cloud.network.security.NetworkGroupManager;
import com.cloud.server.ManagementServer;
import com.cloud.storage.StorageManager;
import com.cloud.storage.snapshot.SnapshotManager;
import com.cloud.template.TemplateManager;
import com.cloud.user.AccountManager;
import com.cloud.utils.DateUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.UserVmManager;

/**
 * A class that dispatches API commands to the appropriate manager for execution.
 */
public class ApiDispatcher {
    private static final Logger s_logger = Logger.getLogger(ApiDispatcher.class.getName());

    private AccountManager _accountMgr;
    private AgentManager _agentMgr;
    private ConfigurationManager _configMgr;
    private ConsoleProxyManager _consoleProxyMgr;
    private ManagementServer _mgmtServer;
    private NetworkGroupManager _networkGroupMgr;
    private NetworkManager _networkMgr;
    private SnapshotManager _snapshotMgr;
    private StorageManager _storageMgr;
    private TemplateManager _templateMgr;
    private UserVmManager _userVmMgr;

    // singleton class
    private static ApiDispatcher s_instance = new ApiDispatcher();

    public static ApiDispatcher getInstance() {
        return s_instance;
    }

    private ApiDispatcher() {
        ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
        _mgmtServer = (ManagementServer)ComponentLocator.getComponent(ManagementServer.Name);
        _accountMgr = locator.getManager(AccountManager.class);
        _agentMgr = locator.getManager(AgentManager.class);
        _configMgr = locator.getManager(ConfigurationManager.class);
        _consoleProxyMgr = locator.getManager(ConsoleProxyManager.class);
        _networkGroupMgr = locator.getManager(NetworkGroupManager.class);
        _networkMgr = locator.getManager(NetworkManager.class);
        _snapshotMgr = locator.getManager(SnapshotManager.class);
        _storageMgr = locator.getManager(StorageManager.class);
        _templateMgr = locator.getManager(TemplateManager.class);
        _userVmMgr = locator.getManager(UserVmManager.class);
    }

    public Long dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map<String, String> params) {
        setupParameters(cmd, params);

        Implementation impl = cmd.getClass().getAnnotation(Implementation.class);
        String methodName = impl.createMethod();
        Object mgr = _mgmtServer;
        switch (impl.manager()) {
        case AccountManager:
            mgr = _accountMgr;
            break;
        case AgentManager:
            mgr = _agentMgr;
            break;
        case ConfigManager:
            mgr = _configMgr;
            break;
        case ConsoleProxyManager:
            mgr = _consoleProxyMgr;
            break;
        case NetworkGroupManager:
            mgr = _networkGroupMgr;
            break;
        case NetworkManager:
            mgr = _networkMgr;
            break;
        case SnapshotManager:
            mgr = _snapshotMgr;
            break;
        case StorageManager:
            mgr = _storageMgr;
            break;
        case TemplateManager:
            mgr = _templateMgr;
            break;
        case UserVmManager:
            mgr = _userVmMgr;
            break;
        }

        try {
            Method method = mgr.getClass().getMethod(methodName, cmd.getClass());
            Object dbObject = method.invoke(mgr, cmd);

            Method getIdMethod = dbObject.getClass().getMethod("getId");
            Object id = getIdMethod.invoke(dbObject);
            
            return (Long)id;
        } catch (NoSuchMethodException nsme) {
            s_logger.warn("Exception executing method " + methodName + " for command " + cmd.getClass().getSimpleName(), nsme);
            throw new CloudRuntimeException("Unable to execute method " + methodName + " for command " + cmd.getClass().getSimpleName() + ", unable to find implementation.");
        } catch (InvocationTargetException ite) {
            s_logger.warn("Exception executing method " + methodName + " for command " + cmd.getClass().getSimpleName(), ite);
            throw new CloudRuntimeException("Unable to execute method " + methodName + " for command " + cmd.getClass().getSimpleName() + ", internal error in the implementation.");
        } catch (IllegalAccessException iae) {
            s_logger.warn("Exception executing method " + methodName + " for command " + cmd.getClass().getSimpleName(), iae);
            throw new CloudRuntimeException("Unable to execute method " + methodName + " for command " + cmd.getClass().getSimpleName() + ", internal error in the implementation.");
        } catch (IllegalArgumentException iArgEx) {
            s_logger.warn("Exception executing method " + methodName + " for command " + cmd.getClass().getSimpleName(), iArgEx);
            throw new CloudRuntimeException("Unable to execute method " + methodName + " for command " + cmd.getClass().getSimpleName() + ", internal error in the implementation.");
        }
    }

    public void dispatch(BaseCmd cmd, Map<String, String> params) {
        setupParameters(cmd, params);

        Implementation impl = cmd.getClass().getAnnotation(Implementation.class);
        String methodName = impl.method();
        Object mgr = _mgmtServer;
        switch (impl.manager()) {
        case AccountManager:
            mgr = _accountMgr;
            break;
        case AgentManager:
            mgr = _agentMgr;
            break;
        case ConfigManager:
            mgr = _configMgr;
            break;
        case ConsoleProxyManager:
            mgr = _consoleProxyMgr;<commit_msg>Throw an exception when the dispatcher can't find the implementation for an API command.<commit_after>/**
 *  Copyright (C) 2010 Cloud.com, Inc.  All rights reserved.
 * 
 * This software is licensed under the GNU General Public License v3 or later.
 * 
 * It is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package com.cloud.api;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import com.cloud.agent.manager.AgentManager;
import com.cloud.api.BaseCmd.CommandType;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.consoleproxy.ConsoleProxyManager;
import com.cloud.network.NetworkManager;
import com.cloud.network.security.NetworkGroupManager;
import com.cloud.server.ManagementServer;
import com.cloud.storage.StorageManager;
import com.cloud.storage.snapshot.SnapshotManager;
import com.cloud.template.TemplateManager;
import com.cloud.user.AccountManager;
import com.cloud.utils.DateUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.UserVmManager;

/**
 * A class that dispatches API commands to the appropriate manager for execution.
 */
public class ApiDispatcher {
    private static final Logger s_logger = Logger.getLogger(ApiDispatcher.class.getName());

    private AccountManager _accountMgr;
    private AgentManager _agentMgr;
    private ConfigurationManager _configMgr;
    private ConsoleProxyManager _consoleProxyMgr;
    private ManagementServer _mgmtServer;
    private NetworkGroupManager _networkGroupMgr;
    private NetworkManager _networkMgr;
    private SnapshotManager _snapshotMgr;
    private StorageManager _storageMgr;
    private TemplateManager _templateMgr;
    private UserVmManager _userVmMgr;

    // singleton class
    private static ApiDispatcher s_instance = new ApiDispatcher();

    public static ApiDispatcher getInstance() {
        return s_instance;
    }

    private ApiDispatcher() {
        ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
        _mgmtServer = (ManagementServer)ComponentLocator.getComponent(ManagementServer.Name);
        _accountMgr = locator.getManager(AccountManager.class);
        _agentMgr = locator.getManager(AgentManager.class);
        _configMgr = locator.getManager(ConfigurationManager.class);
        _consoleProxyMgr = locator.getManager(ConsoleProxyManager.class);
        _networkGroupMgr = locator.getManager(NetworkGroupManager.class);
        _networkMgr = locator.getManager(NetworkManager.class);
        _snapshotMgr = locator.getManager(SnapshotManager.class);
        _storageMgr = locator.getManager(StorageManager.class);
        _templateMgr = locator.getManager(TemplateManager.class);
        _userVmMgr = locator.getManager(UserVmManager.class);
    }

    public Long dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map<String, String> params) {
        setupParameters(cmd, params);

        Implementation impl = cmd.getClass().getAnnotation(Implementation.class);
        String methodName = impl.createMethod();
        Object mgr = _mgmtServer;
        switch (impl.manager()) {
        case AccountManager:
            mgr = _accountMgr;
            break;
        case AgentManager:
            mgr = _agentMgr;
            break;
        case ConfigManager:
            mgr = _configMgr;
            break;
        case ConsoleProxyManager:
            mgr = _consoleProxyMgr;
            break;
        case NetworkGroupManager:
            mgr = _networkGroupMgr;
            break;
        case NetworkManager:
            mgr = _networkMgr;
            break;
        case SnapshotManager:
            mgr = _snapshotMgr;
            break;
        case StorageManager:
            mgr = _storageMgr;
            break;
        case TemplateManager:
            mgr = _templateMgr;
            break;
        case UserVmManager:
            mgr = _userVmMgr;
            break;
        }

        try {
            Method method = mgr.getClass().getMethod(methodName, cmd.getClass());
            Object dbObject = method.invoke(mgr, cmd);

            Method getIdMethod = dbObject.getClass().getMethod("getId");
            Object id = getIdMethod.invoke(dbObject);
            
            return (Long)id;
        } catch (NoSuchMethodException nsme) {
            s_logger.warn("Exception executing method " + methodName + " for command " + cmd.getClass().getSimpleName(), nsme);
            throw new CloudRuntimeException("Unable to execute method " + methodName + " for command " + cmd.getClass().getSimpleName() + ", unable to find implementation.");
        } catch (InvocationTargetException ite) {
            s_logger.warn("Exception executing method " + methodName + " for command " + cmd.getClass().getSimpleName(), ite);
            throw new CloudRuntimeException("Unable to execute method " + methodName + " for command " + cmd.getClass().getSimpleName() + ", internal error in the implementation.");
        } catch (IllegalAccessException iae) {
            s_logger.warn("Exception executing method " + methodName + " for command " + cmd.getClass().getSimpleName(), iae);
            throw new CloudRuntimeException("Unable to execute method " + methodName + " for command " + cmd.getClass().getSimpleName() + ", internal error in the implementation.");
        } catch (IllegalArgumentException iArgEx) {
            s_logger.warn("Exception executing method " + methodName + " for command " + cmd.getClass().getSimpleName(), iArgEx);
            throw new CloudRuntimeException("Unable to execute method " + methodName + " for command " + cmd.getClass().getSimpleName() + ", internal error in the implementation.");
        }
    }

    public void dispatch(BaseCmd cmd, Map<String, String> params) {
        setupParameters(cmd, params);

        Implementation impl = cmd.getClass().getAnnotation(Implementation.class);
        if (impl == null) {
            throw new CloudRuntimeException("Unable to execute command " + cmd.getClass().getName() + ", no implementation specified.");
        }

        String methodName = impl.method();
        Object mgr = _mgmtServer;
        switch (impl.manager()) {
        case AccountManager:
            mgr = _accountMgr;
            break;
        case AgentManager:
            mgr = _agentMgr;
            break;
        case ConfigManager:
            mgr = _configMgr;
            break;
        case ConsoleProxyManager:
            mgr = _consoleProxyMgr;
{'fraction_non_alphanumeric': 0.08573812669494472, 'fraction_numerical': 0.0009735067102426814, 'mean_word_length': 3.000556328233658, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6976469', 'n_tokens_mistral': 3654, 'n_tokens_neox': 3691, 'n_words': 1011}