org.codehaus.groovy.tools.shell.Groovysh Java Examples

The following examples show how to use org.codehaus.groovy.tools.shell.Groovysh. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GroovyInterpreter.java    From COMP6237 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public GroovyInterpreter(Binding binding) throws IOException {
	this.binding = binding;
	if (this.binding == null)
		this.binding = new Binding();

	is = new PipedInputStream();
	os = new PipedOutputStream();
	pis = new PipedInputStream(os);
	pos = new PipedOutputStream(is);

	System.setProperty(TerminalFactory.JLINE_TERMINAL, "none");
	AnsiConsole.systemInstall();
	Ansi.setDetector(new AnsiDetector());

	binding.setProperty("out", new ImmediateFlushingPrintWriter(pos));

	shell = new Groovysh(binding, new IO(pis, pos, pos));
	// {
	// @Override
	// public void displayWelcomeBanner(InteractiveShellRunner runner) {
	// // do nothing
	// }
	// };
	shell.getIo().setVerbosity(Verbosity.QUIET);
}
 
Example #2
Source File: SqoopShell.java    From sqoop-on-spark with Apache License 2.0 6 votes vote down vote up
/**
 * Interpret file content in given shell.
 *
 * @param script Script file that should be interpreted
 * @param shell Shell where the script should be interpreted
 * @throws IOException
 */
private static void interpretFileContent(File script, Groovysh shell) throws IOException {
  BufferedReader in = new BufferedReader(new FileReader(script));
  String line;

  // Iterate over all lines and executed them one by one
  while ((line = in.readLine()) != null) {

    // Skip comments and empty lines as we don't need to interpret those
    if(line.isEmpty() || line.startsWith("#")) {
      continue;
    }

    // Render shell and command to get user perception that it was run as usual
    print(shell.renderPrompt());
    println(line);

    // Manually trigger command line parsing
    Object result = shell.execute(line);

    if (result == null) {
      break;
    }
  }
}
 
Example #3
Source File: VertexiumShell.java    From vertexium with Apache License 2.0 6 votes vote down vote up
private Groovysh createShell() {
    final Groovysh shell = getGroovysh();

    // Add a hook to display some status when shutting down...
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        //
        // FIXME: We need to configure JLine to catch CTRL-C for us... Use gshell-io's InputPipe
        //

        if (shell.getHistory() != null) {
            try {
                shell.getHistory().flush();
            } catch (IOException e) {
                System.out.println("Could not flush history.");
            }
        }
    }));

    shell.register(new GetAuthsCommand(shell));
    shell.register(new SetAuthsCommand(shell));
    shell.register(new GetTimeCommand(shell));
    shell.register(new SetTimeCommand(shell));
    shell.register(new NowCommand(shell));
    return shell;
}
 
Example #4
Source File: GroovyShellWrapper.java    From artifactory_ssh_proxy with Apache License 2.0 5 votes vote down vote up
protected void runGroovy() {
    try {
        LOGGER.info("Running groovy shell");
        IO io = new IO(in, out, err);

        LOGGER.info("in: {} out: {}  err: {}", in, out, err);

        // TODO: fix to allow other bindings.
        Binding binding = new Binding();
        binding.setVariable("out", io.out);

        Groovysh groovysh = new Groovysh(binding, io);
        InteractiveShellRunner isr = new InteractiveShellRunner(groovysh, new GroovyPrompt(this));

        isr.setErrorHandler(new OutputStreamErrorHandler(this, err));

        try {
            // groovysh.run((String) null);
            isr.run();
        } catch (Exception e) {
            try (PrintStream ps = new PrintStream(out)) {
                e.printStackTrace(ps);
            }
            this.alive = false;
        }
    } finally {
        this.alive = false;
        destroy();
        callback.onExit(exitValue());
    }
}
 
Example #5
Source File: UtilitiesGremlinPluginTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPluginUtilities() throws Exception {
    final UtilitiesGremlinPlugin plugin = new UtilitiesGremlinPlugin();

    final Groovysh groovysh = new Groovysh();
    groovysh.getInterp().getContext().setProperty("g", TinkerFactory.createClassic());

    final PluggedIn pluggedIn = new PluggedIn(plugin, groovysh, io, false);
    pluggedIn.activate();

    assertThat(groovysh.execute("describeGraph(org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph)").toString(), containsString("IMPLEMENTATION - org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph"));
}
 
Example #6
Source File: UtilitiesGremlinPluginTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFailWithoutUtilitiesPlugin() throws Exception {
    final Groovysh groovysh = new Groovysh();
    try {
        groovysh.execute("describeGraph(g.class)");
        fail("Utilities were not loaded - this should fail.");
    } catch (Exception ignored) {
    }
}
 
Example #7
Source File: AbstractKnoxShellCommand.java    From knox with Apache License 2.0 5 votes vote down vote up
public AbstractKnoxShellCommand(Groovysh shell, String name, String shortcut,
    String desc, String usage, String help) {
  super(shell, name, shortcut);
  this.description = desc;
  this.usage = usage;
  this.help = help;
}
 
Example #8
Source File: VertexiumShell.java    From vertexium with Apache License 2.0 5 votes vote down vote up
private void setGroovyShell(Groovysh groovysh, GroovyShell groovyShell) throws NoSuchFieldException, IllegalAccessException {
    Field interpField = groovysh.getClass().getDeclaredField("interp");
    interpField.setAccessible(true);

    Field shellField = Interpreter.class.getDeclaredField("shell");
    shellField.setAccessible(true);

    Interpreter interpreter = (Interpreter) interpField.get(groovysh);
    shellField.set(interpreter, groovyShell);
}
 
Example #9
Source File: Shell.java    From knox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("PMD.DoNotUseThreads") // we need to define a Thread to be able to register a shutdown hook
public static void main( String... args ) throws Exception {
  PropertyConfigurator.configure( System.getProperty( "log4j.configuration" ) );
  if( args.length > 0 ) {
    if (NON_INTERACTIVE_COMMANDS.contains(args[0])) {
        final String[] arguments = new String[args.length == 1 ? 1:3];
        arguments[0] = args[0];
        if (args.length > 1) {
          arguments[1] = "--gateway";
          arguments[2] = args[1];
        }
        KnoxSh.main(arguments);
    } else {
        GroovyMain.main( args );
    }
  } else {
    Groovysh shell = new Groovysh();
    Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {
        System.out.println("Closing any open connections ...");
        AbstractSQLCommandSupport sqlcmd = (AbstractSQLCommandSupport) shell.getRegistry().getProperty(":ds");
        sqlcmd.closeConnections();
        sqlcmd = (AbstractSQLCommandSupport) shell.getRegistry().getProperty(":sql");
        sqlcmd.closeConnections();
      }
    });
    for( String name : IMPORTS ) {
      shell.execute( "import " + name );
    }
    // register custom groovysh commands
    shell.register(new SelectCommand(shell));
    shell.register(new DataSourceCommand(shell));
    shell.register(new CSVCommand(shell));
    shell.register(new WebHDFSCommand(shell));
    shell.run( null );
  }
}
 
Example #10
Source File: AbstractSQLCommandSupport.java    From knox with Apache License 2.0 4 votes vote down vote up
public AbstractSQLCommandSupport(Groovysh shell, String name, String shortcut) {
  super(shell, name, shortcut);
}
 
Example #11
Source File: AbstractSQLCommandSupport.java    From knox with Apache License 2.0 4 votes vote down vote up
public AbstractSQLCommandSupport(Groovysh shell, String name, String shortcut, String desc, String usage,
    String help) {
  super(shell, name, shortcut, desc, usage, help);
}
 
Example #12
Source File: AbstractKnoxShellCommand.java    From knox with Apache License 2.0 4 votes vote down vote up
public AbstractKnoxShellCommand(Groovysh shell, String name, String shortcut) {
  super(shell, name, shortcut);
}
 
Example #13
Source File: CSVCommand.java    From knox with Apache License 2.0 4 votes vote down vote up
public CSVCommand(Groovysh shell) {
  super(shell, ":CSV", ":csv", DESC, USAGE, DESC);
}
 
Example #14
Source File: DataSourceCommand.java    From knox with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  DataSourceCommand cmd = new DataSourceCommand(new Groovysh());
  List<String> args2 = new ArrayList<>();
  cmd.execute(args2);
}
 
Example #15
Source File: SelectCommand.java    From knox with Apache License 2.0 4 votes vote down vote up
public SelectCommand(Groovysh shell) {
  super(shell, ":SQL", ":sql", DESC, USAGE, DESC);
}
 
Example #16
Source File: MockGroovyGremlinShellEnvironment.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
public MockGroovyGremlinShellEnvironment(final Groovysh groovysh) {
    this(groovysh, null);
}
 
Example #17
Source File: DataSourceCommand.java    From knox with Apache License 2.0 4 votes vote down vote up
public DataSourceCommand(Groovysh shell) {
  super(shell, ":datasources", ":ds", DESC, USAGE, DESC);
}
 
Example #18
Source File: WebHDFSCommand.java    From knox with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  WebHDFSCommand cmd = new WebHDFSCommand(new Groovysh());
  cmd.execute(new ArrayList<>(Arrays.asList(args)));
}
 
Example #19
Source File: WebHDFSCommand.java    From knox with Apache License 2.0 4 votes vote down vote up
public WebHDFSCommand(Groovysh shell) {
  super(shell, ":filesystem", ":fs", DESC, USAGE, DESC);
}
 
Example #20
Source File: LoginCommand.java    From knox with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  LoginCommand cmd = new LoginCommand(new Groovysh());
  List<String> args2 = new ArrayList<>();
  args2.add("https://localhost:8443/gateway");
  cmd.execute(args2);
}
 
Example #21
Source File: LoginCommand.java    From knox with Apache License 2.0 4 votes vote down vote up
public LoginCommand(Groovysh shell) {
  super(shell, ":login", ":lgn");
}
 
Example #22
Source File: MockGroovyGremlinShellEnvironment.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
public MockGroovyGremlinShellEnvironment(final Groovysh groovysh, final IO io) {
    this.groovysh = groovysh;
    this.io = io;
}
 
Example #23
Source File: SparqlRemoteAcceptor.java    From sparql-gremlin with Apache License 2.0 4 votes vote down vote up
public SparqlRemoteAcceptor(final Groovysh shell) {
    this.shell = shell;
}
 
Example #24
Source File: SqlRemoteAcceptor.java    From sql-gremlin with Apache License 2.0 4 votes vote down vote up
public SqlRemoteAcceptor(final Groovysh shell) {
    this.shell = shell;
}
 
Example #25
Source File: VertexiumShell.java    From vertexium with Apache License 2.0 4 votes vote down vote up
/**
 * @param evalString commands that will be executed at startup after loading files given with filenames param
 * @param filenames  files that will be loaded at startup
 */
protected void startGroovysh(Parameters params, Groovysh shell, String evalString, List<String> filenames) {
    int code;
    SecurityManager psm = System.getSecurityManager();
    System.setSecurityManager(new NoExitSecurityManager());

    System.out.println("  _    __          __            _");
    System.out.println(" | |  / /__  _____/ /____  _  __(_)_  ______ ___");
    System.out.println(" | | / / _ \\/ ___/ __/ _ \\| |/_/ / / / / __ `__ \\");
    System.out.println(" | |/ /  __/ /  / /_/  __/>  </ / /_/ / / / / / /   v" + getClass().getPackage().getImplementationVersion());
    System.out.println(" |___/\\___/_/   \\__/\\___/_/|_/_/\\__,_/_/ /_/ /_/");
    System.out.println("");
    System.out.println("Usage:");
    System.out.println("  vertex1=v['vertex1'] - gets the vertex with id 'v1' and assigns it to variable 'v'");
    System.out.println("  vertex1.methods      - gets the methods available on the Vertexium object");
    System.out.println("  vertex1.properties   - gets the properties available on the Vertexium object");
    System.out.println("  vertex1.delete()     - deletes the vertex v1");
    System.out.println("  p1.delete()          - deletes the property currently referenced by p1");
    System.out.println("  q.has('name', 'joe').vertices().each() { println it.id } - execute a query for all vertices with property 'name' equal to 'joe'");
    System.out.println("  g.query('apple', auths).vertices()[0]                    - execute a query for 'apple' and get the first match");
    System.out.println("");
    System.out.println("Global Properties:");
    System.out.println("  g      - the Graph object");
    System.out.println("  q      - a query object");
    System.out.println("  auths  - the currently set query authorizations");
    System.out.println("  time   - the currently set query time");
    System.out.println("  now    - the current time");
    System.out.println("  v      - vertex map (usage: v['v1'])");
    System.out.println("  e      - edge map (usage: e['e1'])");
    System.out.println("  cypher - run a cypher query (usage: cypher(\"\"\"MATCH (n) RETURN n LIMIT 10\"\"\"))");
    try {
        shell.execute("import " + Visibility.class.getPackage().getName() + ".*;");
        shell.execute("import " + GeoPoint.class.getPackage().getName() + ".*;");
        shell.execute("import " + GeoCompare.class.getPackage().getName() + ".*;");
        for (String evalFile : params.evalFiles) {
            shell.execute(String.format(":load '%s'", evalFile));
        }
        code = shell.run(evalString, filenames);
    } finally {
        System.setSecurityManager(psm);
    }

    // Force the JVM to exit at this point, since shell could have created threads or
    // popped up Swing components that will cause the JVM to linger after we have been
    // asked to shutdown

    System.exit(code);
}
 
Example #26
Source File: VertexiumShell.java    From vertexium with Apache License 2.0 4 votes vote down vote up
public Groovysh getGroovysh() {
    return groovysh;
}
 
Example #27
Source File: VertexiumShell.java    From vertexium with Apache License 2.0 4 votes vote down vote up
private void setResultHook(Groovysh groovysh, Closure<Object> resultHook) throws NoSuchFieldException, IllegalAccessException {
    Field resultHookField = Groovysh.class.getDeclaredField("resultHook");
    resultHookField.setAccessible(true);

    resultHookField.set(groovysh, resultHook);
}
 
Example #28
Source File: SetTimeCommand.java    From vertexium with Apache License 2.0 4 votes vote down vote up
public SetTimeCommand(Groovysh shell) {
    super(shell, ":settime", ":st");
}
 
Example #29
Source File: NowCommand.java    From vertexium with Apache License 2.0 4 votes vote down vote up
public NowCommand(Groovysh shell) {
    super(shell, ":now", ":tn");
}
 
Example #30
Source File: GetAuthsCommand.java    From vertexium with Apache License 2.0 4 votes vote down vote up
public GetAuthsCommand(Groovysh shell) {
    super(shell, ":getauths", ":ga");
}