1.15.2 Get console command output

Discussion in 'Spigot Plugin Development' started by pfgluigi, Feb 11, 2020.

  1. Hello!
    Im developing a plugin to sync one thing with DDBB but I have a question.

    I want to execute a console command and get the String result to process it and be able to insert the result in the database

    I already have the DDBB connectivity, actions... only need get the string.
    Anyone knows how to do it?
     
  2. Code (Java):
    import java.util.ArrayList;
    import java.util.List;

    import org.apache.logging.log4j.core.LogEvent;
    import org.apache.logging.log4j.core.appender.AbstractAppender;
    import org.apache.logging.log4j.core.layout.PatternLayout;

    public class MessageLogger extends AbstractAppender {
        private boolean isLogging;
        private List<String> loggedData;

        @SuppressWarnings("deprecation")
        public MessageLogger() {
         
            super("YourPluginNameAppenderOrSomething", null, PatternLayout.newBuilder().withPattern("%m%n").build());

            isLogging = false;
            loggedData = new ArrayList<String>();
        }

        public void startLogging() {
            isLogging = true;
        }

        public void stopLogging() {
            isLogging = false;
        }

        public void clearData() {
            loggedData.clear();
        }

        public List<String> getData() {
            return new ArrayList<String>(loggedData);
        }

        public void log(String message) {
            if (isLogging) {
                loggedData.add(message);
            }
        }

        @Override
        public boolean isStarted() {
            return true;
        }

        @Override
        public void append(LogEvent event) {
            log(event.getMessage().getFormattedMessage());
        }
    }
    and then, on plugin load:
    Code (Java):
    MessageLogger cmdLogger = new MessageLogger();

    Logger log = (Logger) LogManager.getRootLogger();
    log.addAppender(cmdLogger);
     
  3. First of all, thx for answer :D

    But, Im trying to understand your code and dont know exactly where I must place the command and where I read it.
    The command will be alwais the same.

    Sorry for my low Java level :(
     
  4. you save somewhere the MessageLogger instance you made in your onEnable method, and when you want to execute a command you perform
    Code (Text):
    yourMessageLoggerInstance.startLogging();
    //execute your command(s) here
    yourMessageLoggerInstance.stopLogging();
    List<String> result = yourMessageLoggerInstance.getData();
    yourMessageLoggerInstance.clearData();