org.springframework.shell.event.ParseResult Java Examples

The following examples show how to use org.springframework.shell.event.ParseResult. 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: LensSimpleExecutionStrategy.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public Object execute(ParseResult parseResult) throws RuntimeException {
  Assert.notNull(parseResult, "Parse result required");
  logger.info("LensSimpleExecutionStrategy execute method invoked");
  synchronized (this) {
    Assert.isTrue(isReadyForCommands(), "SimpleExecutionStrategy not yet ready for commands");
    Object target = parseResult.getInstance();
    if (target instanceof ExecutionProcessor) {
      ExecutionProcessor processor = ((ExecutionProcessor) target);
      parseResult = processor.beforeInvocation(parseResult);
      try {
        Object result = invoke(parseResult);
        processor.afterReturningInvocation(parseResult, result);
        return result;
      } catch (Throwable th) {
        processor.afterThrowingInvocation(parseResult, th);
        return handleThrowable(th);
      }
    } else {
      return invoke(parseResult);
    }
  }
}
 
Example #2
Source File: GfshExecutionStrategyJUnitTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testGfshExecutionStartegyExecute() throws Exception {

    CommandManager commandManager = null;
    try {
      commandManager = CommandManager.getInstance();
      assertNotNull("CommandManager should not be null.", commandManager);      
      commandManager.add(Commands.class.newInstance());
      GfshParser parser = new GfshParser(commandManager);
      String[] command1Names = ((CliCommand) Commands.class.getMethod(
          COMMAND1_NAME).getAnnotation(CliCommand.class)).value();
      String input =command1Names[0];
      ParseResult parseResult = null;   
      parseResult = parser.parse(input);  
      String[] args = new String[] {command1Names[0]  };
      Gfsh gfsh = Gfsh.getInstance(false, args, new GfshConfig());      
      GfshExecutionStrategy gfshExecutionStrategy = new GfshExecutionStrategy(gfsh);
      Result resultObject = (Result)gfshExecutionStrategy.execute(parseResult);     
      String str  = resultObject.nextLine();      
      assertTrue(str.trim().equals(COMMAND1_SUCESS));      
    } catch (Exception e) {   
      throw e;
    }
  }
 
Example #3
Source File: CustomShellComponent.java    From spring-data-dev-tools with Apache License 2.0 6 votes vote down vote up
public Object execute(ParseResult parseResult) throws RuntimeException {
	Assert.notNull(parseResult, "Parse result required");
	synchronized (mutex) {
		Assert.isTrue(isReadyForCommands(), "SimpleExecutionStrategy not yet ready for commands");
		Object target = parseResult.getInstance();
		if (target instanceof ExecutionProcessor) {
			ExecutionProcessor processor = ((ExecutionProcessor) target);
			parseResult = processor.beforeInvocation(parseResult);
			try {
				Object result = invoke(parseResult);
				processor.afterReturningInvocation(parseResult, result);
				return result;
			} catch (Throwable th) {
				processor.afterThrowingInvocation(parseResult, th);
				return handleThrowable(th);
			}
		} else {
			return invoke(parseResult);
		}
	}
}
 
Example #4
Source File: GfshExecutionStrategyJUnitTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testGfshExecutionStartegyExecute() throws Exception {

    CommandManager commandManager = null;
    try {
      commandManager = CommandManager.getInstance();
      assertNotNull("CommandManager should not be null.", commandManager);      
      commandManager.add(Commands.class.newInstance());
      GfshParser parser = new GfshParser(commandManager);
      String[] command1Names = ((CliCommand) Commands.class.getMethod(
          COMMAND1_NAME).getAnnotation(CliCommand.class)).value();
      String input =command1Names[0];
      ParseResult parseResult = null;   
      parseResult = parser.parse(input);  
      String[] args = new String[] {command1Names[0]  };
      Gfsh gfsh = Gfsh.getInstance(false, args, new GfshConfig());      
      GfshExecutionStrategy gfshExecutionStrategy = new GfshExecutionStrategy(gfsh);
      Result resultObject = (Result)gfshExecutionStrategy.execute(parseResult);     
      String str  = resultObject.nextLine();      
      assertTrue(str.trim().equals(COMMAND1_SUCESS));      
    } catch (Exception e) {   
      throw e;
    }
  }
 
Example #5
Source File: LensSimpleExecutionStrategy.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private Object invoke(ParseResult parseResult) {
  try {
    return ReflectionUtils.invokeMethod(parseResult.getMethod(),
      parseResult.getInstance(), parseResult.getArguments());
  } catch (Throwable th) {
    logger.severe("Command failed " + th);
    return handleThrowable(th);
  }
}
 
Example #6
Source File: CustomShellComponent.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
private Object invoke(ParseResult parseResult) {
	try {
		Method method = parseResult.getMethod();
		ReflectionUtils.makeAccessible(method);
		return ReflectionUtils.invokeMethod(method, parseResult.getInstance(), parseResult.getArguments());
	} catch (Throwable th) {
		logger.severe("Command failed");
		return handleThrowable(th);
	}
}
 
Example #7
Source File: TimedCommand.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
@Override
public ParseResult beforeInvocation(ParseResult invocationContext) {

	watch = new StopWatch();
	watch.start();

	return invocationContext;
}
 
Example #8
Source File: TestableGfsh.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
@Override
protected ExecutionStrategy getExecutionStrategy() {

  final ExecutionStrategy oldStrategy = super.getExecutionStrategy();
  return new ExecutionStrategy() {
    public Object execute(ParseResult parseResult) throws RuntimeException {
      Object obj = null;
      String command = null;
      try {
        String method = parseResult.getMethod().getName();
        String className = parseResult.getInstance().getClass().getCanonicalName();
        command = className + "." + method;
        Util.log("Executing command " + command + " with Gfsh instance " + gfshThreadLocal.get());
        long l1 = System.currentTimeMillis();
        obj = oldStrategy.execute(parseResult);
        long l2 = System.currentTimeMillis();
        Util.log("Completed execution of command " + command + " in " + (l2-l1) + " ms.");
        if(obj!=null){
          Util.log("Command output class is " + obj.getClass());
        }else{
          obj =  "VOID";
        }
      } catch (Exception e) {
        addError("Error running command " , e);
        throw new RuntimeException(e);
      }
      Util.debug("Adding outuut and notifying threads ..");
      addOutput(command, obj);
      if(command.equals(EXIT_SHELL_COMMAND))
        resultLatch.countDown();
      return obj;
    }

    public boolean isReadyForCommands() {
      return oldStrategy.isReadyForCommands();
    }

    public void terminate() {
      oldStrategy.terminate();
      Util.log("GFSH is exiting now, thankyou for using");
    }
  };
}
 
Example #9
Source File: TestableGfsh.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public TestableGfsh(String name, boolean launchShell, String[] args) throws ClassNotFoundException, IOException {
    super(launchShell, args, new TestableGfshConfig(name));
    oldParser = super.getParser();
    resultLatch = new CountDownLatch(1);
    parserHook = new Parser() {

      @Override
      public ParseResult parse(String buffer) {
        Util.debug("In parsing hook .... with input buffer <" + buffer + ">");
        ParseResult result = null;
        try{
          result = oldParser.parse(buffer);
        }catch(Exception e){
          String reason = e.getMessage() != null ? " Reason: "+e.getMessage() + " Exception: " + String.valueOf(e) : " Exception: " + String.valueOf(e);
          addError("Parsing failed...."  + reason + " buffer returned by EIS " + eis.getBufferFormdAfterReading(),e);
          return null;
        }
        if(result==null){
        	addError("Parsing failed....",null);
        }else{
          Util.log("Parse Result is " + result);
        }
        return result;
      }

//      @Override
      public int completeAdvanced(String buffer, int cursor, List<Completion> candidates) {
        return oldParser.completeAdvanced(buffer, cursor, candidates);
      }

      @Override
      public int complete(String buffer, int cursor, List<String> candidates) {
        return oldParser.complete(buffer, cursor, candidates);
      }
    };

    this.name = name;
    Util.debug("Using CommandManager configured with commands "+ this.getCommandNames(""));
    eis = new EventedInputStream();
    output = new ByteArrayOutputStream(1024 * 10);
    PrintStream sysout = new PrintStream(output, true);
    TestableGfsh.setGfshOutErr(sysout);

//    Writer out = new BufferedWriter(new OutputStreamWriter(sysout));  // saj
    wrappedOut = new BufferedWriter(new OutputStreamWriter(sysout));

    try {
      ConsoleReaderWrapper wrapper = new ConsoleReaderWrapper(eis, wrappedOut);
      Util.debug("Reader created is " + wrapper);
      newConsoleReader = wrapper;
      reader = newConsoleReader;
      completorAdaptor = new JLineCompletorAdapterWrapper(getParser(), this);
    } catch (IOException e) {
      e.printStackTrace();
      throw e;
    }
  }
 
Example #10
Source File: TimedCommand.java    From spring-data-dev-tools with Apache License 2.0 4 votes vote down vote up
@Override
public void afterReturningInvocation(ParseResult invocationContext, Object result) {
	stopAndLog();
}
 
Example #11
Source File: TimedCommand.java    From spring-data-dev-tools with Apache License 2.0 4 votes vote down vote up
@Override
public void afterThrowingInvocation(ParseResult invocationContext, Throwable thrown) {
	stopAndLog();
}
 
Example #12
Source File: CommandProcessor.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public ParseResult parseCommand(String commentLessLine) throws CommandProcessingException, IllegalStateException {
  if (commentLessLine != null) {
    return getParser().parse(commentLessLine);
  }
  throw new IllegalStateException("Command String should not be null.");
}
 
Example #13
Source File: CommandStatementImpl.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * @param parseResult the parseResult to set
 */
void setParseResult(ParseResult parseResult) {
  this.parseResult = parseResult;
}
 
Example #14
Source File: CLIMultiStepHelper.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public static Object execCLISteps(LogWrapper logWrapper, Gfsh shell, ParseResult parseResult) {
  CLIStep[] steps = (CLIStep[]) ReflectionUtils.invokeMethod(parseResult.getMethod(), parseResult.getInstance(),
      parseResult.getArguments());
  if (steps != null) {
    boolean endStepReached = false;
    int stepNumber = 0;
    CLIStep nextStep = steps[stepNumber];
    Result lastResult = null;
    SectionResultData nextStepArgs = null;
    while (!endStepReached) {
      try {
        Result result = executeStep(logWrapper, shell, nextStep, parseResult, nextStepArgs);
        String nextStepString = null;
        nextStepString = getNextStep(result);
        nextStepArgs = extractArgumentsForNextStep(result);          
        if (!"END".equals(nextStepString)) {
          String step = nextStepString;
          boolean stepFound = false;
          for (CLIStep s : steps)
            if (step.equals(s.getName())) {
              nextStep = s;
              stepFound = true;
            }
          if (!stepFound) {
            return ResultBuilder.buildResult(ResultBuilder.createErrorResultData().addLine(
                "Wrong step name returned by previous step : " + step));
          }
        } else {
          lastResult = result;
          endStepReached = true;
        }

      } catch (CLIStepExecption e) {
        endStepReached = true;
        lastResult = e.getResult();
      }
    }
    return lastResult;
  } else {
    Gfsh.println("Command returned null steps");
    return ResultBuilder.buildResult(ResultBuilder.createErrorResultData().addLine(
        "Multi-step command Return NULL STEP Array"));
  }
}
 
Example #15
Source File: CLIMultiStepHelper.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private static Result executeStep(LogWrapper logWrapper,
                                  Gfsh shell,
                                  CLIStep nextStep,
                                  ParseResult parseResult,
                                  SectionResultData nextStepArgs)
{
  try {
    if (nextStep instanceof CLIRemoteStep) {        
      if (shell.isConnectedAndReady()) {
        if (GfshParseResult.class.isInstance(parseResult)) {
          GfshParseResult gfshParseResult = (GfshParseResult) parseResult;

          CommandRequest commandRequest = new CommandRequest(gfshParseResult, prepareJSONArgs(shell.getEnv(), nextStepArgs));
          commandRequest.setCustomInput(changeStepName(gfshParseResult.getUserInput(), nextStep.getName()));

          return ResultBuilder.fromJson((String) shell.getOperationInvoker().processCommand(commandRequest));
        } else {
          throw new IllegalArgumentException("Command Configuration/Definition error.");
        }
      } else {
        try{throw new Exception();} catch (Exception ex) {ex.printStackTrace();}
        throw new IllegalStateException(
            "Can't execute a remote command without connection. Use 'connect' first to connect.");
      }
    } else {
      Map<String, String> args = CommandExecutionContext.getShellEnv();
      if (args == null) {
        args = new HashMap<String, String>();
        CommandExecutionContext.setShellEnv(args);
      }
      if (nextStepArgs != null) {
        GfJsonObject argsJSon = nextStepArgs.getSectionGfJsonObject();
        Gfsh.getCurrentInstance().setEnvProperty(CLIMultiStepHelper.STEP_ARGS, argsJSon.toString());
      }
      return nextStep.exec();
    }
  } catch (CLIStepExecption e) {
    logWrapper.severe("CLIStep " + nextStep.getName() + " failed aborting command");
    throw e;
  }
}
 
Example #16
Source File: CommandStatementImpl.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * @return the parseResult
 */
ParseResult getParseResult() {
  return parseResult;
}
 
Example #17
Source File: CommandStatementImpl.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * @param parseResult the parseResult to set
 */
void setParseResult(ParseResult parseResult) {
  this.parseResult = parseResult;
}
 
Example #18
Source File: CommandProcessor.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public ParseResult parseCommand(String commentLessLine) throws CommandProcessingException, IllegalStateException {
  if (commentLessLine != null) {
    return getParser().parse(commentLessLine);
  }
  throw new IllegalStateException("Command String should not be null.");
}
 
Example #19
Source File: CommandStatementImpl.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * @return the parseResult
 */
ParseResult getParseResult() {
  return parseResult;
}
 
Example #20
Source File: TestableGfsh.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public TestableGfsh(String name, boolean launchShell, String[] args) throws ClassNotFoundException, IOException {
    super(launchShell, args, new TestableGfshConfig(name));
    oldParser = super.getParser();
    resultLatch = new CountDownLatch(1);
    parserHook = new Parser() {

      @Override
      public ParseResult parse(String buffer) {
        Util.debug("In parsing hook .... with input buffer <" + buffer + ">");
        ParseResult result = null;
        try{
          result = oldParser.parse(buffer);
        }catch(Exception e){
          String reason = e.getMessage() != null ? " Reason: "+e.getMessage() + " Exception: " + String.valueOf(e) : " Exception: " + String.valueOf(e);
          addError("Parsing failed...."  + reason + " buffer returned by EIS " + eis.getBufferFormdAfterReading(),e);
          return null;
        }
        if(result==null){
        	addError("Parsing failed....",null);
        }else{
          Util.log("Parse Result is " + result);
        }
        return result;
      }

//      @Override
      public int completeAdvanced(String buffer, int cursor, List<Completion> candidates) {
        return oldParser.completeAdvanced(buffer, cursor, candidates);
      }

      @Override
      public int complete(String buffer, int cursor, List<String> candidates) {
        return oldParser.complete(buffer, cursor, candidates);
      }
    };

    this.name = name;
    Util.debug("Using CommandManager configured with commands "+ this.getCommandNames(""));
    eis = new EventedInputStream();
    output = new ByteArrayOutputStream(1024 * 10);
    PrintStream sysout = new PrintStream(output, true);
    TestableGfsh.setGfshOutErr(sysout);

//    Writer out = new BufferedWriter(new OutputStreamWriter(sysout));  // saj
    wrappedOut = new BufferedWriter(new OutputStreamWriter(sysout));

    try {
      ConsoleReaderWrapper wrapper = new ConsoleReaderWrapper(eis, wrappedOut);
      Util.debug("Reader created is " + wrapper);
      newConsoleReader = wrapper;
      reader = newConsoleReader;
      completorAdaptor = new JLineCompletorAdapterWrapper(getParser(), this);
    } catch (IOException e) {
      e.printStackTrace();
      throw e;
    }
  }
 
Example #21
Source File: TestableGfsh.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
@Override
protected ExecutionStrategy getExecutionStrategy() {

  final ExecutionStrategy oldStrategy = super.getExecutionStrategy();
  return new ExecutionStrategy() {
    public Object execute(ParseResult parseResult) throws RuntimeException {
      Object obj = null;
      String command = null;
      try {
        String method = parseResult.getMethod().getName();
        String className = parseResult.getInstance().getClass().getCanonicalName();
        command = className + "." + method;
        Util.log("Executing command " + command + " with Gfsh instance " + gfshThreadLocal.get());
        long l1 = System.currentTimeMillis();
        obj = oldStrategy.execute(parseResult);
        long l2 = System.currentTimeMillis();
        Util.log("Completed execution of command " + command + " in " + (l2-l1) + " ms.");
        if(obj!=null){
          Util.log("Command output class is " + obj.getClass());
        }else{
          obj =  "VOID";
        }
      } catch (Exception e) {
        addError("Error running command " , e);
        throw new RuntimeException(e);
      }
      Util.debug("Adding outuut and notifying threads ..");
      addOutput(command, obj);
      if(command.equals(EXIT_SHELL_COMMAND))
        resultLatch.countDown();
      return obj;
    }

    public boolean isReadyForCommands() {
      return oldStrategy.isReadyForCommands();
    }

    public void terminate() {
      oldStrategy.terminate();
      Util.log("GFSH is exiting now, thankyou for using");
    }
  };
}
 
Example #22
Source File: CLIMultiStepHelper.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private static Result executeStep(LogWrapper logWrapper,
                                  Gfsh shell,
                                  CLIStep nextStep,
                                  ParseResult parseResult,
                                  SectionResultData nextStepArgs)
{
  try {
    if (nextStep instanceof CLIRemoteStep) {        
      if (shell.isConnectedAndReady()) {
        if (GfshParseResult.class.isInstance(parseResult)) {
          GfshParseResult gfshParseResult = (GfshParseResult) parseResult;

          CommandRequest commandRequest = new CommandRequest(gfshParseResult, prepareJSONArgs(shell.getEnv(), nextStepArgs));
          commandRequest.setCustomInput(changeStepName(gfshParseResult.getUserInput(), nextStep.getName()));

          return ResultBuilder.fromJson((String) shell.getOperationInvoker().processCommand(commandRequest));
        } else {
          throw new IllegalArgumentException("Command Configuration/Definition error.");
        }
      } else {
        try{throw new Exception();} catch (Exception ex) {ex.printStackTrace();}
        throw new IllegalStateException(
            "Can't execute a remote command without connection. Use 'connect' first to connect.");
      }
    } else {
      Map<String, String> args = CommandExecutionContext.getShellEnv();
      if (args == null) {
        args = new HashMap<String, String>();
        CommandExecutionContext.setShellEnv(args);
      }
      if (nextStepArgs != null) {
        GfJsonObject argsJSon = nextStepArgs.getSectionGfJsonObject();
        Gfsh.getCurrentInstance().setEnvProperty(CLIMultiStepHelper.STEP_ARGS, argsJSon.toString());
      }
      return nextStep.exec();
    }
  } catch (CLIStepExecption e) {
    logWrapper.severe("CLIStep " + nextStep.getName() + " failed aborting command");
    throw e;
  }
}
 
Example #23
Source File: CLIMultiStepHelper.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public static Object execCLISteps(LogWrapper logWrapper, Gfsh shell, ParseResult parseResult) {
  CLIStep[] steps = (CLIStep[]) ReflectionUtils.invokeMethod(parseResult.getMethod(), parseResult.getInstance(),
      parseResult.getArguments());
  if (steps != null) {
    boolean endStepReached = false;
    int stepNumber = 0;
    CLIStep nextStep = steps[stepNumber];
    Result lastResult = null;
    SectionResultData nextStepArgs = null;
    while (!endStepReached) {
      try {
        Result result = executeStep(logWrapper, shell, nextStep, parseResult, nextStepArgs);
        String nextStepString = null;
        nextStepString = getNextStep(result);
        nextStepArgs = extractArgumentsForNextStep(result);          
        if (!"END".equals(nextStepString)) {
          String step = nextStepString;
          boolean stepFound = false;
          for (CLIStep s : steps)
            if (step.equals(s.getName())) {
              nextStep = s;
              stepFound = true;
            }
          if (!stepFound) {
            return ResultBuilder.buildResult(ResultBuilder.createErrorResultData().addLine(
                "Wrong step name returned by previous step : " + step));
          }
        } else {
          lastResult = result;
          endStepReached = true;
        }

      } catch (CLIStepExecption e) {
        endStepReached = true;
        lastResult = e.getResult();
      }
    }
    return lastResult;
  } else {
    Gfsh.println("Command returned null steps");
    return ResultBuilder.buildResult(ResultBuilder.createErrorResultData().addLine(
        "Multi-step command Return NULL STEP Array"));
  }
}