當前位置: 首頁>>代碼示例>>Java>>正文


Java ConsoleReader.addCompleter方法代碼示例

本文整理匯總了Java中jline.console.ConsoleReader.addCompleter方法的典型用法代碼示例。如果您正苦於以下問題:Java ConsoleReader.addCompleter方法的具體用法?Java ConsoleReader.addCompleter怎麽用?Java ConsoleReader.addCompleter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在jline.console.ConsoleReader的用法示例。


在下文中一共展示了ConsoleReader.addCompleter方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: initConsole

import jline.console.ConsoleReader; //導入方法依賴的package包/類
public static ConsoleReader initConsole() throws IOException, InvalidColourException{
	
	Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
	    public void run() {
	    	System.out.print("\033[0m"); // On exit turn off all formatting
	    }
	}));
	
	ConsoleReader console= new ConsoleReader(); 

	try {
		// Autcomplete commands with length > x 
		for(CommandHelp x : CommandList.commandHelpList()){
			if(x.getName().length() > 2){
				console.addCompleter(new StringsCompleter(x.getName()));
			}
		}
	} catch (InvalidCommandLineException e) {
		e.printStackTrace();
	}
	console.setExpandEvents(false);
	return console;
}
 
開發者ID:dariober,項目名稱:ASCIIGenome,代碼行數:24,代碼來源:Main.java

示例2: buildInstance

import jline.console.ConsoleReader; //導入方法依賴的package包/類
public static HeroicInteractiveShell buildInstance(
    final List<CommandDefinition> commands, FileInputStream input
) throws Exception {
    final ConsoleReader reader = new ConsoleReader("heroicsh", input, System.out, null);

    final FileHistory history = setupHistory(reader);

    if (history != null) {
        reader.setHistory(history);
    }

    reader.setPrompt(String.format("heroic> "));
    reader.addCompleter(new StringsCompleter(
        ImmutableList.copyOf(commands.stream().map((d) -> d.getName()).iterator())));
    reader.setHandleUserInterrupt(true);

    return new HeroicInteractiveShell(reader, commands, history);
}
 
開發者ID:spotify,項目名稱:heroic,代碼行數:19,代碼來源:HeroicInteractiveShell.java

示例3: readCommands

import jline.console.ConsoleReader; //導入方法依賴的package包/類
public void readCommands() {
    try {
        console = new ConsoleReader();
        List commandNames = new ArrayList();
        for (Command c : commands) {
            c.setupCompleter();
            commandNames.add(c.names[0]);
        }
        console.addCompleter(new StringsCompleter(commandNames));
        console.setPrompt("proptester> ");
        String line;
        while ((line = console.readLine()) != null) {
            processCommand(line);
        }
    } catch (IOException io) {
        io.printStackTrace();
    }
}
 
開發者ID:Talend,項目名稱:components,代碼行數:19,代碼來源:PropertiesTester.java

示例4: setUpCompletors

import jline.console.ConsoleReader; //導入方法依賴的package包/類
/**
 * sets up the completors that a user can use with tab
 * @param reader  the current reader
 */
private void setUpCompletors(ConsoleReader reader) {
    List<Completer> completors = new LinkedList<>();
    completors.add(new StringsCompleter("create", "start", "stop", "exit", "help", "cls"));
    for (Completer c : completors) {
        reader.addCompleter(c);
    }
}
 
開發者ID:StuPro-TOSCAna,項目名稱:stupro_toscana_vorprojekt,代碼行數:12,代碼來源:Controller.java

示例5: BungeeCord

import jline.console.ConsoleReader; //導入方法依賴的package包/類
@SuppressFBWarnings("DM_DEFAULT_ENCODING")
public BungeeCord() throws IOException
{
    // Java uses ! to indicate a resource inside of a jar/zip/other container. Running Bungee from within a directory that has a ! will cause this to muck up.
    Preconditions.checkState( new File( "." ).getAbsolutePath().indexOf( '!' ) == -1, "Cannot use BungeeCord in directory with ! in path." );

    try
    {
        baseBundle = ResourceBundle.getBundle( "messages" );
    } catch ( MissingResourceException ex )
    {
        baseBundle = ResourceBundle.getBundle( "messages", Locale.ENGLISH );
    }
    File file = new File( "messages.properties" );
    if ( file.isFile() )
    {
        try ( FileReader rd = new FileReader( file ) )
        {
            customBundle = new PropertyResourceBundle( rd );
        }
    }

    // This is a workaround for quite possibly the weirdest bug I have ever encountered in my life!
    // When jansi attempts to extract its natives, by default it tries to extract a specific version,
    // using the loading class's implementation version. Normally this works completely fine,
    // however when on Windows certain characters such as - and : can trigger special behaviour.
    // Furthermore this behaviour only occurs in specific combinations due to the parsing done by jansi.
    // For example test-test works fine, but test-test-test does not! In order to avoid this all together but
    // still keep our versions the same as they were, we set the override property to the essentially garbage version
    // BungeeCord. This version is only used when extracting the libraries to their temp folder.
    System.setProperty( "library.jansi.version", "BungeeCord" );

    AnsiConsole.systemInstall();
    consoleReader = new ConsoleReader();
    consoleReader.setExpandEvents( false );
    consoleReader.addCompleter( new ConsoleCommandCompleter( this ) );

    logger = new BungeeLogger( this );
    System.setErr( new PrintStream( new LoggingOutputStream( logger, Level.SEVERE ), true ) );
    System.setOut( new PrintStream( new LoggingOutputStream( logger, Level.INFO ), true ) );

    if ( !Boolean.getBoolean( "net.md_5.bungee.native.disable" ) )
    {
        if ( EncryptionUtil.nativeFactory.load() )
        {
            logger.info( "Using OpenSSL based native cipher." );
        } else
        {
            logger.info( "Using standard Java JCE cipher. To enable the OpenSSL based native cipher, please make sure you are using 64 bit Ubuntu or Debian with libssl installed." );
        }
        if ( CompressFactory.zlib.load() )
        {
            logger.info( "Using native code compressor" );
        } else
        {
            logger.info( "Using standard Java compressor. To enable zero copy compression, run on 64 bit Linux" );
        }
    }
}
 
開發者ID:WaterfallMC,項目名稱:Waterfall-Old,代碼行數:60,代碼來源:BungeeCord.java

示例6: init

import jline.console.ConsoleReader; //導入方法依賴的package包/類
public void init() {
    System.setProperty("library.jansi.version", "JaPS");

    AnsiConsole.systemInstall();

    try {
        consoleReader = new ConsoleReader();
        consoleReader.setExpandEvents(false);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Setup logging system
    logger = new JaPSLogger(consoleReader);
    System.setErr(new PrintStream(new LoggingOutputStream(logger, Level.SEVERE), true));
    System.setOut(new PrintStream(new LoggingOutputStream(logger, Level.INFO), true));

    // Register command
    commandManager = new CommandManager();
    commandManager.addCommand(new HelpCommand("help", new String[]{"h"}, "Show this output"));
    commandManager.addCommand(new SubCommand("sub", new String[]{"s", "subscribe"}, "Subscribe a channel and view it's prepareCacheSync passing"));
    commandManager.addCommand(new UnsubCommand("unsub", new String[]{}, "Unsubscribe previous subscribed channels"));
    commandManager.addCommand(new EndCommand("end", new String[]{"stop"}, "Shutdown the server"));
    commandManager.addCommand(new SetCommand("set", new String[]{"add"}, "Sets a key and value"));
    commandManager.addCommand(new GetCommand("get", new String[]{}, "Gets a value from a key"));
    commandManager.addCommand(new DeleteCommand("delete", new String[]{"remove", "del", "rm"}, "Gets a value from a key"));
    commandManager.addCommand(new SnapshotCommand("snapshot", new String[]{}, "Takes a memory snapshot"));

    // Autocomplete commands
    consoleReader.addCompleter(new StringsCompleter(commandManager.getCommands().stream().map(Command::getName).collect(Collectors.toList())));

    // Autocomplete files
    consoleReader.addCompleter(new FileNameCompleter());

    logger.info("Initialized");
}
 
開發者ID:JackWhite20,項目名稱:JaPS,代碼行數:37,代碼來源:JaPS.java

示例7: readLine

import jline.console.ConsoleReader; //導入方法依賴的package包/類
private static String readLine(ConsoleReader console) throws IOException {
	ConsoleUtils.begin(31);
	ConsoleUtils.println(">>>");
	ConsoleUtils.end();
	List<Completer> completors = new LinkedList<Completer>();

	// completors.add(new AnsiStringsCompleter("\u001B[1mfoo\u001B[0m",
	// "bar", "\u001B[32mbaz\u001B[0m"));
	CandidateListCompletionHandler handler = new CandidateListCompletionHandler();
	handler.setStripAnsi(true);
	console.setCompletionHandler(handler);
	for (Completer c : completors) {
		console.addCompleter(c);
	}
	// History h = console.getHistory();
	// ("hoge\rhoge");
	StringBuilder sb = new StringBuilder();
	while (true) {
		String line = console.readLine();
		if (line == null) {
			return null;
		}
		if (line.equals("")) {
			return sb.toString();
		}
		sb.append(line);
		sb.append("\n");
	}
	// h = console.getHistory();
}
 
開發者ID:nez-peg,項目名稱:konoha,代碼行數:31,代碼來源:Main.java

示例8: onRun

import jline.console.ConsoleReader; //導入方法依賴的package包/類
@Inject(method = "run", at = @At("HEAD"), cancellable = true, remap = false)
private void onRun(CallbackInfo ci) {
    final ConsoleReader reader = TerminalConsoleAppender.getReader();

    if (reader != null) {
        TerminalConsoleAppender.setFormatter(ConsoleFormatter::format);
        reader.addCompleter(new ConsoleCommandCompleter());

        reader.setPrompt("> ");
        reader.setHandleUserInterrupt(true);

        try {
            String line;
            while (!this.server.isServerStopped() && this.server.isServerRunning()) {
                try {
                    line = reader.readLine();
                    if (line == null) {
                        break;
                    }

                    line = line.trim();
                    final String lineFinal = line;
                    if (!line.isEmpty()) {
                        this.server.addScheduledTask(() -> Canary.getServer().consoleCommand(lineFinal));
                    }
                } catch (IOException e) {
                    Canary.log.error("Exception handling console input", e);
                }
            }
        } catch (UserInterruptException exception) {
            reader.shutdown();
            Canary.commands().parseCommand(Canary.getServer(), "stop", new String[]{ "stop", "Ctrl-C", "at", "console" });
        }

        ci.cancel();
    } else {
        TerminalConsoleAppender.setFormatter(EnumChatFormatting::getTextWithoutFormattingCodes);
    }
}
 
開發者ID:NeptunePowered,項目名稱:NeptuneMod,代碼行數:40,代碼來源:MixinConsoleHandler.java

示例9: run

import jline.console.ConsoleReader; //導入方法依賴的package包/類
private static void run() throws IOException {
    reader = new ConsoleReader();
    reader.addCompleter(new StringsCompleter("compileTest", "evalTest", "-acge", "getEnv()", "eval", "addKey"));

    FileHistory fileHistory = new FileHistory(new File("./sh/history.just"));
    reader.setHistoryEnabled(true);
    reader.setHistory(fileHistory);

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("");
        System.out.println(ANSI_PURPLE + "Have a nice Day~~" + ANSI_RESET);
        try {
            fileHistory.flush();
        } catch (IOException ignored) {
        }
    }));

    String command;
    while ((command = reader.readLine(cyanPrint(JUST_EL))) != null) {

        if (command.equals("")) continue;
        else if (command.trim().equals("-q")) return;
        else if (resolveCommandLine(command)) continue;

        try {

            Queue<Token> tokens = lexer.scanner(command);

            reader.addCompleter(
                    new StringsCompleter(
                            tokens.stream()
                                  .map(Token::getText)
                                  .collect(toList())));

            AstNode node = parser.parser(tokens);

            if (openAst) {
                runAst(node);
            }

            if (openMockEval) {
                runEval(node, env);
            }

            if (openMockGenerate) {
                runCompile(node, env);
            }

        } catch (Throwable e) {
            AnsiConsole.out.println(ansi().fgRed().a(JUST_EL + e.getMessage()).reset().toString());
        }
    }
}
 
開發者ID:lfkdsk,項目名稱:Just-Evaluator,代碼行數:54,代碼來源:JustRepl.java

示例10: handleCommands

import jline.console.ConsoleReader; //導入方法依賴的package包/類
public static boolean handleCommands(DedicatedServer server)
{
    final ConsoleReader reader = TerminalConsoleAppender.getReader();
    if (reader != null)
    {
        TerminalConsoleAppender.setFormatter(new ConsoleFormatter());
        reader.addCompleter(new ConsoleCommandCompleter(server));

        String line;
        while (!server.isServerStopped() && server.isServerRunning())
        {
            try
            {
                line = reader.readLine("> ");
                if (line == null)
                {
                    break;
                }

                line = line.trim();
                if (!line.isEmpty())
                {
                    server.addPendingCommand(line, server);
                }
            }
            catch (IOException e)
            {
                logger.error("Exception handling console input", e);
            }
        }

        return true;
    }
    else
    {
        TerminalConsoleAppender.setFormatter(new Function<String, String>() {

            @Override
            public String apply(String text)
            {
                return TextFormatting.getTextWithoutFormattingCodes(text);
            }

        });
        return false;
    }
}
 
開發者ID:F1r3w477,項目名稱:CustomWorldGen,代碼行數:48,代碼來源:TerminalHandler.java

示例11: interactiveMode

import jline.console.ConsoleReader; //導入方法依賴的package包/類
private static boolean interactiveMode(JavaScriptEngine engine) {
    try {
        ConsoleReader reader = new ConsoleReader();
        reader.setPrompt(PromptNewLine);
        reader.addCompleter(new JavaScriptCompleter(engine));
        reader.setBellEnabled(false);
        reader.setHistoryEnabled(true);

        int lineNo = 1;
        int startLine = lineNo;

        String line;
        String source = "";

        PrintWriter out = new PrintWriter(reader.getOutput());

        boolean bContinueReading = false;

        while (!bExiting && (line = reader.readLine()) != null ) {
            source = source + line + "\n";
            lineNo++;

            bContinueReading = !engine.stringIsCompilableUnit(source);

            if (!bContinueReading) {
                try {
                    Object result = engine.runPartialScript(source, startLine);
                    if (result != null) {
                        out.println(engine.valueToString(result));
                    }
                } catch (ScriptException se) {
                    out.println(se.getMessage());
                }
                startLine = lineNo;
                source = "";
            }

            String prompt;
            if (bContinueReading) {
                prompt = PromptContinueLine;
            } else {
                prompt = PromptNewLine;
            }
            reader.setPrompt(prompt);
        }
        return true;
    } catch (IOException e) {
        System.err.println(e.getMessage());
        return false;
    }
}
 
開發者ID:loadtestgo,項目名稱:pizzascript,代碼行數:52,代碼來源:PizzaScript.java

示例12: setupCompleter

import jline.console.ConsoleReader; //導入方法依賴的package包/類
private void setupCompleter(ConsoleReader reader)
{
  reader.addCompleter(new AggregateCompleter(defaultCompleters()));
}
 
開發者ID:apache,項目名稱:apex-core,代碼行數:5,代碼來源:ApexCli.java

示例13: Init

import jline.console.ConsoleReader; //導入方法依賴的package包/類
private void Init(String accnt, String key, String cont) throws IOException
{
    conReader = new ConsoleReader();
    conReader.setPrompt("AzureShell> ");
    
     List<Completer> completors = new LinkedList<>();
     
    String currFileNameStr = "dir1";

    AzFileProvider azfp = new AzFileProvider();
    StaticUserAuthenticator auth = new StaticUserAuthenticator("", accnt, key);
    AzFileSystemConfigBuilder.getInstance().setUserAuthenticator(azfp.getDefaultFileSystemOptions(), auth); 
    
    DefaultFileSystemManager currMan = new DefaultFileSystemManager();
    currMan.addProvider(AzConstants.AZSBSCHEME, azfp);
    currMan.addProvider("file", new DefaultLocalFileProvider());
    currMan.init(); 
    
    mgr = currMan;
    //cwd = mgr.resolveFile(System.getProperty("user.dir"));c
    String currAzURL = String.format("%s://%s/%s/%s", 
                       AzConstants.AZSBSCHEME, accnt, cont, currFileNameStr);
    cwd = mgr.resolveFile(currAzURL);
    
    completors.add(new FileNameCompleter());
    completors.add(new StringsCompleter(AzConstants.AZSBSCHEME, "file://", currAzURL));
    AggregateCompleter aggComp = new AggregateCompleter(completors);
    ArgumentCompleter argComp = new ArgumentCompleter(aggComp);
    argComp.setStrict(false);
    conReader.addCompleter(argComp);
    
    Path histPath = Paths.get(System.getProperty("user.home"), ".simpleshellhist");
    File histFile = histPath.toFile();
    FileHistory fh = new FileHistory(histFile);
    conReader.setHistory(fh);
    conReader.setHistoryEnabled(true);
    
    Runtime.getRuntime().addShutdownHook(
            new Thread() 
            {
                @Override
                public void run() 
                {
                    try
                    {
                        ((FileHistory)conReader.getHistory()).flush();
                    }
                    catch (IOException ex)
                    {
                        log.error("Error saving history", ex);
                    }
                }
            });
    
}
 
開發者ID:kervinpierre,項目名稱:vfs-azure,代碼行數:56,代碼來源:SimpleShell.java

示例14: run

import jline.console.ConsoleReader; //導入方法依賴的package包/類
@Override
public void run() throws IOException {
           this.setup();
	if (this.getScriptFile() != null && this.getScriptFile().length() > 0) {
		try {
			String[] script = FileIO.read(this.getScriptFile()).split("\n");
                               logger.info(this.getMessages().get("executing_script", new Object[]{new File(this.getScriptFile()).getAbsolutePath()}));
			for (String scriptEntry: script) {
                                   processTask(scriptEntry, this.getLanguageCode());
			}
			logger.info(this.getMessages().get("executed_script", new Object[]{new File(this.getScriptFile()).getAbsolutePath()}));
		}
		catch (Exception e) {
			logger.error(this.getMessages().get("script_error", new Object[]{this.getScriptFile()}));
			logger.error(StackTrace.asString(e));
		}
	}
	String result = "";
       ConsoleReader reader = new ConsoleReader();
       reader.setPrompt(System.getProperty("user.name")+"@"+Host.name()+"> ");
       Collection<String> commands = new LinkedList<String>();
       commands.add("clear");
       commands.add("help");
       Set<String> keySet = this.getVocabulary().getVocabularyProperties().keySet();
	for (Object key: keySet.toArray()) {
		String value = this.getVocabulary().getVocabularyProperties().get(key.toString());
		if (value.split("\\|")[0].equals(this.getLanguageCode())) {
			commands.add(key.toString());
		}
	}
       List<Completer> completors = new LinkedList<Completer>();
       StringsCompleter stringsCompleter = new StringsCompleter(commands);
       completors.add(stringsCompleter);
       for (Completer c : completors) {
           reader.addCompleter(c);
       }
       this.getConsole().writer().write(this.getMessages().get("console_welcome", new Object[]{}));
       this.getConsole().flush();
       while (!(result.equals("exit"))) {
		result = reader.readLine(reader.getPrompt()).toLowerCase().trim();
		 if (result.equals("clear")) {
                reader.clearScreen();
            }
		 else {
			 processTask(result, this.getLanguageCode());
		 }
	}
}
 
開發者ID:rovemonteux,項目名稱:automation_engine,代碼行數:49,代碼來源:Console.java

示例15: main

import jline.console.ConsoleReader; //導入方法依賴的package包/類
public static void main(String[] args) throws IOException {
	try {
		Character mask = null;
		String trigger = null;
		boolean color = false;

		ConsoleReader reader = new ConsoleReader();

		reader.setPrompt("prompt> ");

		if ((args == null) || (args.length == 0)) {
			usage();

			return;
		}

		List<Completer> completors = new LinkedList<Completer>();

		if (args.length > 0) {
			if (args[0].equals("none")) {
			} else if (args[0].equals("files")) {
				completors.add(new FileNameCompleter());
			} else if (args[0].equals("simple")) {
				completors.add(new StringsCompleter("foo", "bar", "baz"));
			} else if (args[0].equals("color")) {
				color = true;
				reader.setPrompt("\u001B[1mfoo\u001B[[email protected]\u001B[[email protected]\u001B[0m> ");
			} else {
				usage();

				return;
			}
		}

		if (args.length == 3) {
			mask = args[2].charAt(0);
			trigger = args[1];
		}

		for (Completer c : completors) {
			reader.addCompleter(c);
		}

		String line;
		PrintWriter out = new PrintWriter(reader.getOutput());

		while ((line = reader.readLine()) != null) {
			if (color) {
				out.println("\u001B[33m======>\u001B[0m\"" + line + "\"");

			} else {
				out.println("======>\"" + line + "\"");
			}
			out.flush();

			// If we input the special word then we will mask
			// the next line.
			if ((trigger != null) && (line.compareTo(trigger) == 0)) {
				line = reader.readLine("password> ", mask);
			}
			if (line.equalsIgnoreCase("quit")
					|| line.equalsIgnoreCase("exit")) {
				break;
			}
			if (line.equalsIgnoreCase("cls")) {
				reader.clearScreen();
			}
		}
	} catch (Throwable t) {
		t.printStackTrace();
	}
}
 
開發者ID:mixaceh,項目名稱:openyu-commons,代碼行數:73,代碼來源:JLineExample.java


注:本文中的jline.console.ConsoleReader.addCompleter方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。