Ir al contenido
Otras versiones

Cargando…

Crear su propio plugin de Command shell

Para crear su propio adaptador de número de versión debemos crear una nueva clase que implemente la interfaz Command:

package com.openkm.terminal;
import java.util.concurrent.BlockingQueue;
import net.xeoh.plugins.base.Plugin;
import org.apache.commons.cli.Options;
import com.openkm.bean.CommandMessageQueue;
/**
* Command
*
*/
public interface Command extends Plugin, Runnable {
    public abstract void init(String path, String[] args, BlockingQueue<CommandMessageQueue> queue);
    public abstract Options getOptions();
    public abstract String getHelp();
    public abstract boolean isAllowInputReader();
    public abstract void setInputQueue(BlockingQueue<CommandMessageQueue> inputQueue);
    public abstract String getCommandName();
    public abstract String getDescription();
}

La nueva clase debe cargarse en el paquete com.openkm.terminal, porque el sistema de plugins de la aplicación carga desde ahí.

Método Tipo Descripción
init(String path, String[] args, BlockingQueue queue) void Inicializa el objeto.
getOptions() Options Devuelve los parámetros disponibles del comando.
getHelp() String Devuelve la ayuda de la línea de comandos.
boolean isAllowInputReader() boolean Indica si el comando puede procesar valores de entrada.
El parámetro “grep” procesa los resultados de salida de otra línea de comandos. Por ejemplo, “ls grep test”
setInputQueue(BlockingQueue inputQueue) void Establece la cola de entrada que se va a procesar.
Solo tiene sentido cuando isAllowInputReader() devuelve el valor true.
getCommandName() String Devuelve el nombre del comando.
getDescription() String Devuelve la descripción que se muestra en la tabla de plugins.

La línea de comandos utiliza una cola bloqueante entre la ejecución de cada objeto de línea de comandos.

  • La variable finish, cuando es true, indica que el proceso de la cola ha finalizado.
  • La variable error indica que se ha producido algún error cuando su valor es true.
  • La variable message contiene algún mensaje, normalmente un mensaje de error.
package com.openkm.bean;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* CommandMessageQueue
*
*/
public class CommandMessageQueue implements Serializable {
    private static final long serialVersionUID = 1L;
    // path
    public static final String ENVIRONMENT_PARAMETER_PATH = "path";
    // message can be displayed in one row or several rows ( table )
    public static final int TYPE_ROW = 1;
    public static final int TYPE_TABLE = 2;
    // indicate when table date start or ends
    public static final int TABLE_DATA_START = 1;
    public static final int TABLE_DATA_END = 2;
    private String message = "";
    private boolean error = false;
    private boolean finish = false;
    private Map<String, String> envMap = new HashMap<String, String>();
    private int type = TYPE_ROW;
    private int tablePosition = 0;
    /**
     * CommandMessageQueue
     */
    public CommandMessageQueue() {
    }
    /**
     * CommandMessageQueue
     */
    public CommandMessageQueue(String message) {
        this.message = message;
    }
    /**
     * CommandMessageQueue
     */
    public CommandMessageQueue(String message, int tablePosition) {
        this.message = message;
        this.tablePosition = tablePosition;
        switch (tablePosition) {
            case TABLE_DATA_START:
            case TABLE_DATA_END :
                this.type = TYPE_TABLE;
                break;
            default:
                this.type = TYPE_ROW;
                break;
        }
    }
    /**
     * CommandMessageQueue
     */
    public CommandMessageQueue(boolean finish) {
        this.finish = finish;
    }
    /**
     * CommandMessageQueue
     */
    public CommandMessageQueue(boolean error, boolean finish, String message) {
        this.error = error;
        this.finish = finish;
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public boolean isError() {
        return error;
    }
    public void setError(boolean error) {
        this.error = error;
    }
    public boolean isFinish() {
        return finish;
    }
    public void setFinish(boolean finish) {
        this.finish = finish;
    }
    public Map<String, String> getEnvMap() {
        return envMap;
    }
    public int getType() {
        return type;
    }
    public void setType(int type) {
        this.type = type;
    }
    public int getTablePosition() {
        return tablePosition;
    }
    public void setTablePosition(int tablePosition) {
        this.tablePosition = tablePosition;
    }
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("message=").append(message);
        sb.append(", finish=").append(finish);
        sb.append(", error=").append(error);
        sb.append(", envMap=").append(envMap);
        sb.append(", type=").append(type);
        sb.append(", tablePosition=").append(tablePosition);
        sb.append("}");
        return sb.toString();
    }
}
package com.openkm.terminal;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.concurrent.BlockingQueue;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import com.openkm.api.OKMFolder;
import com.openkm.api.OKMRepository;
import com.openkm.bean.CommandMessageQueue;
import com.openkm.core.DatabaseException;
import com.openkm.core.PathNotFoundException;
import com.openkm.core.RepositoryException;
import com.openkm.util.CmdUtils;
import com.openkm.util.PathUtils;
/** *
*/
@PluginImplementation
public class CmdCd implements Command {
    private static final String COMMAND_NAME = "cd";
    private static final String USAGE = COMMAND_NAME+" [UUID|PATH]->folder";
    private BlockingQueue<CommandMessageQueue> queue;
    private String path;
    private String[] args;
    private boolean allowInputReader = false;
    @Override
    public void init(String path, String[] args, BlockingQueue<CommandMessageQueue> queue) {
        this.path = path;
        this.queue = queue;
        this.args = args;
    }
    @Override
    public String getHelp() {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        CmdUtils.printHelp(pw, USAGE, getOptions());
        pw.flush();
        pw.close();
        return sw.toString();
    }
    @Override
    public Options getOptions() {
        Options options = new Options();
        options.addOption("?", "help", false, "display this help and exit");
        return options;
    }
    @Override
    public boolean isAllowInputReader() {
        return allowInputReader;
    }
    @Override
    public void setInputQueue(BlockingQueue<CommandMessageQueue> inputQueue) {
    }
    @Override
    public String getCommandName() {
        return COMMAND_NAME;
    }
    @Override
    public String getDescription() {
        return "Change current working directory";
    }
    @Override
    public void run() {
        CommandLineParser parser = new BasicParser();
        try {
            try {
                CommandLine cmdLine = parser.parse(getOptions(), args);
                String arg[] = cmdLine.getArgs();
                if (cmdLine.hasOption("?") || cmdLine.hasOption("help")) {
                    queue.put(new CommandMessageQueue(false, false, getHelp()));
                } else if (arg.length > 1) {
                    queue.put(new CommandMessageQueue(true, false, COMMAND_NAME+": incorrect arguments"));
                    queue.put(new CommandMessageQueue(true, false, "Try \""+COMMAND_NAME+" -?\" for more information"));
                } else {
                    if (arg.length == 1) {
                        String param = arg[0];
                        if (param.equals("..")) {
                            path = PathUtils.getParent(path);
                        } else if (param.equals(".")) {
                            // Nothing to do here
                        } else {
                            // normalize path
                            path = TerminalUtils.normalizePath(param, path);
                        }
                    } else {
                        path = "/okm:root";
                    }
                    if (OKMRepository.getInstance().hasNode(null, path)) {
                        if (OKMFolder.getInstance().isValid(null, path)) {
                            CommandMessageQueue cmq = new CommandMessageQueue();
                            cmq.getEnvMap().put(CommandMessageQueue.ENVIRONMENT_PARAMETER_PATH, path);
                            queue.put(cmq);
                        } else {
                            queue.put(new CommandMessageQueue(true, false, "Node "+path+" is not a foldermessage"));
                        }
                    } else {
                        queue.put(new CommandMessageQueue(true, false, "Node "+path+" not exists"));
                    }
                }
                queue.put(new CommandMessageQueue(true)); // finish
            } catch (ParseException e) {
                queue.put(new CommandMessageQueue(true, false, COMMAND_NAME + " command arguments parse exception"));
                queue.put(new CommandMessageQueue(true, true, "Try \"" + COMMAND_NAME + " -?\" for more information"));
                e.printStackTrace();
            } catch (RepositoryException e) {
                queue.put(new CommandMessageQueue(true, true, "RepositoryException:"));
                e.printStackTrace();
            } catch (DatabaseException e) {
                queue.put(new CommandMessageQueue(true, true, "DatabaseException:"));
                e.printStackTrace();
            } catch (PathNotFoundException e) {
                queue.put(new CommandMessageQueue(true, true, "PathNotFoundException: " + path));
                e.printStackTrace();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}