All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.mycore.frontend.cli.MCRCommandManager Maven / Gradle / Ivy

There is a newer version: 2024.05
Show newest version
/*
 * This file is part of ***  M y C o R e  ***
 * See http://www.mycore.de/ for details.
 *
 * MyCoRe 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
 * (at your option) any later version.
 *
 * MyCoRe 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 MyCoRe.  If not, see .
 */

package org.mycore.frontend.cli;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRClassTools;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;

/**
 * Manages all commands for the Command Line Interface and WebCLI.
 *
 * @author Frank L\u00FCtzenkirchen
 * @author Robert Stephan
 */
public class MCRCommandManager {
    private static final Logger LOGGER = LogManager.getLogger(MCRCommandManager.class);

    protected static TreeMap> knownCommands = new TreeMap<>();

    public MCRCommandManager() {
        try {
            initBuiltInCommands();
            initCommands();
        } catch (Exception ex) {
            handleInitException(ex);
        }
    }

    @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("DM_EXIT")
    protected void handleInitException(Exception ex) {
        MCRCLIExceptionHandler.handleException(ex);
        System.exit(1);
    }

    public static TreeMap> getKnownCommands() {
        return knownCommands;
    }

    protected void initBuiltInCommands() {
        addAnnotatedCLIClass(MCRBasicCommands.class);
    }

    protected void initCommands() {
        // load build-in commands
        initConfiguredCommands("Internal");
        initConfiguredCommands("External");
    }

    /** Read internal and/or external commands */
    protected void initConfiguredCommands(String type) {
        String prefix = "MCR.CLI.Classes." + type;
        Stream> propsWithPrefix = MCRConfiguration2.getPropertiesMap()
            .entrySet()
            .stream()
            .filter(e -> e.getKey().startsWith(prefix));
        Stream classNames = propsWithPrefix
            .map(Map.Entry::getValue)
            .flatMap(MCRConfiguration2::splitValue)
            .filter(s -> !s.isEmpty());
        classNames.forEach(this::loadCommandClass);
    }

    private void loadCommandClass(String commandClassName) {
        LOGGER.debug("Will load commands from the {} class {}", commandClassName, commandClassName);
        try {
            Class cliClass = MCRClassTools.forName(commandClassName);
            if (cliClass.isAnnotationPresent(MCRCommandGroup.class)) {
                addAnnotatedCLIClass(cliClass);
            } else {
                addDefaultCLIClass(commandClassName);
            }

        } catch (ClassNotFoundException cnfe) {
            LOGGER.error("MyCoRe Command Class {} not found.", commandClassName);
        }
    }

    protected void addAnnotatedCLIClass(Class cliClass) {
        String groupName = Optional.ofNullable(cliClass.getAnnotation(MCRCommandGroup.class))
            .map(MCRCommandGroup::name)
            .orElse(cliClass.getSimpleName());
        final Class mcrCommandAnnotation;
        mcrCommandAnnotation = org.mycore.frontend.cli.annotation.MCRCommand.class;
        ArrayList commands = Arrays.stream(cliClass.getMethods())
            .filter(method -> method.getDeclaringClass().equals(cliClass))
            .filter(method -> Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers()))
            .filter(method -> method.isAnnotationPresent(mcrCommandAnnotation))
            .sorted(Comparator.comparingInt(m -> m.getAnnotation(mcrCommandAnnotation).order()))
            .map(MCRCommand::new)
            .collect(Collectors.toCollection(ArrayList::new));
        addCommandGroup(groupName, commands);
    }

    //fixes MCR-1594 deep in the code
    private List addCommandGroup(String groupName, ArrayList commands) {
        return knownCommands.put(groupName, Collections.unmodifiableList(commands));
    }

    protected void addDefaultCLIClass(String className) {
        Object obj = buildInstanceOfClass(className);
        MCRExternalCommandInterface commandInterface = (MCRExternalCommandInterface) obj;
        ArrayList commandsToAdd = commandInterface.getPossibleCommands();
        addCommandGroup(commandInterface.getDisplayName(), commandsToAdd);
    }

    private Object buildInstanceOfClass(String className) {
        try {
            return MCRClassTools.forName(className).getDeclaredConstructor().newInstance();
        } catch (Exception ex) {
            String msg = "Could not instantiate class " + className;
            throw new MCRConfigurationException(msg, ex);
        }
    }

    public List invokeCommand(String command) throws Exception {
        for (List commands : knownCommands.values()) {
            for (MCRCommand currentCommand : commands) {
                long start = System.currentTimeMillis();
                List commandsReturned = currentCommand.invoke(command);
                long end = System.currentTimeMillis();

                if (commandsReturned != null) {
                    long timeNeeded = end - start;
                    MCRCommandLineInterface.output("Command processed (" + timeNeeded + " ms)");
                    MCRCommandStatistics.commandInvoked(currentCommand, timeNeeded);

                    return commandsReturned;
                }
            }
        }

        MCRCommandLineInterface.output("Command not understood:" + command);
        MCRCommandLineInterface.output("Enter 'help' to get a list of commands.");
        return new ArrayList<>();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy