picocli.CommandLine.ExecutionException Java Examples

The following examples show how to use picocli.CommandLine.ExecutionException. 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: BlocksSubCommand.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  parentCommand.parentCommand.configureLogging(false);
  LOG.info("Export {} block data to file {}", format, blocksExportFile.toPath());

  checkCommand(this, startBlock, endBlock);
  final Optional<MetricsService> metricsService = initMetrics(parentCommand);

  final BesuController controller = createBesuController();
  try {
    if (format == BlockExportFormat.RLP) {
      exportRlpFormat(controller);
    } else {
      throw new ParameterException(
          spec.commandLine(), "Unsupported format: " + format.toString());
    }
  } catch (final IOException e) {
    throw new ExecutionException(
        spec.commandLine(), "An error occurred while exporting blocks.", e);
  } finally {
    metricsService.ifPresent(MetricsService::stop);
  }
}
 
Example #2
Source File: ExampleInterface.java    From picocli with Apache License 2.0 6 votes vote down vote up
private static int execute(String[] args) {
    final CommandLine cmd = new CommandLine(ExampleInterface.class);
    cmd.setExecutionStrategy(new IExecutionStrategy() {
        public int execute(ParseResult parseResult) throws ExecutionException, ParameterException {
            Integer result = CommandLine.executeHelpRequest(parseResult);
            if (result != null) {
                return result;
            }
            // invoke the business logic
            ExampleInterface exampleInterface = cmd.getCommand();
            businessLogic(exampleInterface);
            return cmd.getCommandSpec().exitCodeOnSuccess();
        }
    });
    return cmd.execute(args);
}
 
Example #3
Source File: ExampleInterface.java    From picocli with Apache License 2.0 6 votes vote down vote up
private static int execute(String[] args) {
    final CommandLine cmd = new CommandLine(ExampleInterface.class);
    cmd.setExecutionStrategy(new IExecutionStrategy() {
        public int execute(ParseResult parseResult) throws ExecutionException, ParameterException {
            Integer result = CommandLine.executeHelpRequest(parseResult);
            if (result != null) {
                return result;
            }
            // invoke the business logic
            ExampleInterface exampleInterface = cmd.getCommand();
            businessLogic(exampleInterface);
            return cmd.getCommandSpec().exitCodeOnSuccess();
        }
    });
    return cmd.execute(args);
}
 
Example #4
Source File: HopRun.java    From hop with Apache License 2.0 6 votes vote down vote up
private void runWorkflow( CommandLine cmd, ILogChannel log, WorkflowExecutionConfiguration configuration, WorkflowMeta workflowMeta ) {
  try {
    String runConfigurationName = workflowMeta.environmentSubstitute(configuration.getRunConfiguration());
    IWorkflowEngine<WorkflowMeta> workflow = WorkflowEngineFactory.createWorkflowEngine( runConfigurationName, metadataProvider, workflowMeta );
    workflow.initializeVariablesFrom( null );
    workflow.getWorkflowMeta().setInternalHopVariables( workflow );
    workflow.injectVariables( configuration.getVariablesMap() );

    workflow.setLogLevel( configuration.getLogLevel() );

    // Explicitly set parameters
    for ( String parameterName : configuration.getParametersMap().keySet() ) {
      workflowMeta.setParameterValue( parameterName, configuration.getParametersMap().get( parameterName ) );
    }

    // Also copy the parameters over...
    //
    workflow.copyParametersFrom( workflowMeta );
    workflowMeta.activateParameters();
    workflow.activateParameters();

    workflow.startExecution();
  } catch ( Exception e ) {
    throw new ExecutionException( cmd, "Error running workflow locally", e );
  }
}
 
Example #5
Source File: HopRun.java    From hop with Apache License 2.0 6 votes vote down vote up
private void runPipeline( CommandLine cmd, ILogChannel log, PipelineExecutionConfiguration configuration, PipelineMeta pipelineMeta ) {
  try {
    String pipelineRunConfigurationName = pipelineMeta.environmentSubstitute( configuration.getRunConfiguration() );
    IPipelineEngine<PipelineMeta> pipeline = PipelineEngineFactory.createPipelineEngine( pipelineRunConfigurationName, metadataProvider, pipelineMeta );
    pipeline.initializeVariablesFrom( null );
    pipeline.getPipelineMeta().setInternalHopVariables( pipeline );
    pipeline.injectVariables( configuration.getVariablesMap() );

    pipeline.setLogLevel( configuration.getLogLevel() );
    pipeline.setMetadataProvider( metadataProvider );

    // Also copy the parameters over...
    //
    pipeline.copyParametersFrom( pipelineMeta );
    pipelineMeta.activateParameters();
    pipeline.activateParameters();

    // Run it!
    //
    pipeline.prepareExecution();
    pipeline.startThreads();
    pipeline.waitUntilFinished();
  } catch ( Exception e ) {
    throw new ExecutionException( cmd, "Error running pipeline locally", e );
  }
}
 
Example #6
Source File: HopRun.java    From hop with Apache License 2.0 5 votes vote down vote up
private void runPipeline( CommandLine cmd, ILogChannel log ) {

    try {
      calculateRealFilename();

      // Run the pipeline with the given filename
      //
      PipelineMeta pipelineMeta = new PipelineMeta( realFilename, metadataProvider, true, variables );

      // Configure the basic execution settings
      //
      PipelineExecutionConfiguration configuration = new PipelineExecutionConfiguration();

      // Overwrite if the user decided this
      //
      parseOptions( cmd, configuration, pipelineMeta );

      // configure the variables and parameters
      //
      configureParametersAndVariables( cmd, configuration, pipelineMeta, pipelineMeta );

      // Before running, do we print the options?
      //
      if ( printingOptions ) {
        printOptions( configuration );
      }

      // Now run the pipeline using the run configuration
      //
      runPipeline( cmd, log, configuration, pipelineMeta );

    } catch ( Exception e ) {
      throw new ExecutionException( cmd, "There was an error during execution of pipeline '" + filename + "'", e );
    }
  }
 
Example #7
Source File: SubcommandTests.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testExecutionStrategy_BeforeSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    commandLine.addSubcommand("main", createNestedCommand());
    IExecutionStrategy original = commandLine.getExecutionStrategy();
    assertTrue(original instanceof CommandLine.RunLast);
    IExecutionStrategy strategy = new IExecutionStrategy() {
        public int execute(ParseResult parseResult) throws ExecutionException, ParameterException {
            return 0;
        }
    };
    commandLine.setExecutionStrategy(strategy);
    assertEquals(strategy, commandLine.getExecutionStrategy());

    int childCount = 0;
    int grandChildCount = 0;
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertEquals("subcommand added before IS impacted", strategy, sub.getExecutionStrategy());
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertEquals("subsubcommand added before IS impacted", strategy, sub.getExecutionStrategy());
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #8
Source File: SubcommandTests.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testExecutionStrategy_AfterSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    IExecutionStrategy original = commandLine.getExecutionStrategy();
    assertTrue(original instanceof CommandLine.RunLast);
    IExecutionStrategy strategy = new IExecutionStrategy() {
        public int execute(ParseResult parseResult) throws ExecutionException, ParameterException {
            return 0;
        }
    };
    commandLine.setExecutionStrategy(strategy);
    assertEquals(strategy, commandLine.getExecutionStrategy());

    int childCount = 0;
    int grandChildCount = 0;
    commandLine.addSubcommand("main", createNestedCommand());
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertTrue("subcommand added afterwards is not impacted", sub.getExecutionStrategy() instanceof CommandLine.RunLast);
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertTrue("subcommand added afterwards is not impacted", subsub.getExecutionStrategy() instanceof CommandLine.RunLast);
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #9
Source File: HopRun.java    From hop with Apache License 2.0 5 votes vote down vote up
/**
 * Set the variables and parameters
 *
 * @param cmd
 * @param configuration
 * @param namedParams
 */
private void parseParametersAndVariables( CommandLine cmd, IExecutionConfiguration configuration, INamedParams namedParams ) {
  try {
    String[] availableParameters = namedParams.listParameters();
    if ( parameters != null ) {
      for ( String parameter : parameters ) {
        String[] split = parameter.split( "=" );
        String key = split.length > 0 ? split[ 0 ] : null;
        String value = split.length > 1 ? split[ 1 ] : null;

        if ( key != null ) {
          // We can work with this.
          //
          if ( Const.indexOfString( key, availableParameters ) < 0 ) {
            // A variable
            //
            configuration.getVariablesMap().put( key, value );
          } else {
            // A parameter
            //
            configuration.getParametersMap().put( key, value );
          }
        }
      }
    }
  } catch ( Exception e ) {
    throw new ExecutionException( cmd, "There was an error during execution of pipeline '" + filename + "'", e );
  }
}
 
Example #10
Source File: HopRun.java    From hop with Apache License 2.0 5 votes vote down vote up
private void runWorkflow( CommandLine cmd, ILogChannel log ) {
  try {
    calculateRealFilename();

    // Run the workflow with the given filename
    //
    WorkflowMeta workflowMeta = new WorkflowMeta( variables, realFilename, metadataProvider );

    // Configure the basic execution settings
    //
    WorkflowExecutionConfiguration configuration = new WorkflowExecutionConfiguration();

    // Overwrite the run configuration with optional command line options
    //
    parseOptions( cmd, configuration, workflowMeta );

    // Certain Hop plugins rely on this.  Meh.
    //
    ExtensionPointHandler.callExtensionPoint( log, HopExtensionPoint.HopUiWorkflowBeforeStart.id, new Object[] { configuration, null, workflowMeta, null } );

    // Before running, do we print the options?
    //
    if ( printingOptions ) {
      printOptions( configuration );
    }

    runWorkflow( cmd, log, configuration, workflowMeta );

  } catch ( Exception e ) {
    throw new ExecutionException( cmd, "There was an error during execution of workflow '" + filename + "'", e );
  }
}
 
Example #11
Source File: GenericCli.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
public void run(String[] argv) {
  try {
    execute(argv);
  } catch (ExecutionException ex) {
    printError(ex.getCause() == null ? ex : ex.getCause());
    System.exit(-1);
  }
}
 
Example #12
Source File: HopRun.java    From hop with Apache License 2.0 5 votes vote down vote up
private void initialize( CommandLine cmd ) {
  try {
    // Set some System properties if there were any
    //
    if (systemProperties!=null) {
      for ( String parameter : systemProperties ) {
        String[] split = parameter.split( "=" );
        String key = split.length > 0 ? split[ 0 ] : null;
        String value = split.length > 1 ? split[ 1 ] : null;
        if ( StringUtils.isNotEmpty( key ) && StringUtils.isNotEmpty( value ) ) {
          System.setProperty( key, value );
        }
      }
    }

    // Picks up these system settings in the variables
    //
    buildVariableSpace();

    // Set up the metadata to use
    //
    metadataProvider = HopMetadataUtil.getStandardHopMetadataProvider(variables);

    HopEnvironment.init();
  } catch ( Exception e ) {
    throw new ExecutionException( cmd, "There was a problem during the initialization of the Hop environment", e );
  }
}
 
Example #13
Source File: HopRun.java    From hop with Apache License 2.0 5 votes vote down vote up
public void run() {
  validateOptions();

  try {
    ExtensionPointHandler.callExtensionPoint( log, HopExtensionPoint.HopRunInit.id, this );

    initialize( cmd );

    log = new LogChannel( "HopRun" );
    log.setLogLevel( determineLogLevel() );
    log.logDetailed( "Start of Hop Run" );

    // Allow plugins to modify the elements loaded so far, before a pipeline or workflow is even loaded
    //
    ExtensionPointHandler.callExtensionPoint( log, HopExtensionPoint.HopRunStart.id, this );

    if ( isPipeline() ) {
      runPipeline( cmd, log );
    }
    if ( isWorkflow() ) {
      runWorkflow( cmd, log );
    }

    ExtensionPointHandler.callExtensionPoint( log, HopExtensionPoint.HopRunEnd.id, this );
  } catch ( Exception e ) {
    throw new ExecutionException( cmd, "There was an error during execution of file '" + filename + "'", e );
  }
}
 
Example #14
Source File: HopConfig.java    From hop with Apache License 2.0 5 votes vote down vote up
public void run() {

    try {
      LogChannel logChannel = new LogChannel( "hop-config" );
      logChannel.setSimplified( true );
      log = logChannel;
      variables = Variables.getADefaultVariableSpace();
      buildMetadataProvider();

      boolean actionTaken = false;

      Map<String, Object> mixins = cmd.getMixins();
      for (String key : mixins.keySet()) {
        Object mixin = mixins.get( key );
        if (mixin instanceof IConfigOptions) {
          IConfigOptions configOptions = (IConfigOptions) mixin;

          actionTaken = configOptions.handleOption( log, metadataProvider, variables ) || actionTaken;
        }
      }

      if (!actionTaken) {
        cmd.usage( System.out );
      }

    } catch ( Exception e ) {
      throw new ExecutionException( cmd, "There was an error handling options", e );
    }
  }
 
Example #15
Source File: BesuCommand.java    From besu with Apache License 2.0 5 votes vote down vote up
public BesuController buildController() {
  try {
    return getControllerBuilder().build();
  } catch (final Exception e) {
    throw new ExecutionException(this.commandLine, e.getMessage(), e);
  }
}
 
Example #16
Source File: ConfigOptionSearchAndRunHandler.java    From besu with Apache License 2.0 5 votes vote down vote up
private Optional<File> findConfigFile(
    final ParseResult parseResult, final CommandLine commandLine) {
  if (parseResult.hasMatchedOption(configFileOptionName)) {
    final OptionSpec configFileOption = parseResult.matchedOption(configFileOptionName);
    try {
      return Optional.of(configFileOption.getter().get());
    } catch (final Exception e) {
      throw new ExecutionException(commandLine, e.getMessage(), e);
    }
  }

  return Optional.empty();
}
 
Example #17
Source File: ConfigOptionSearchAndRunHandler.java    From besu with Apache License 2.0 5 votes vote down vote up
@Override
public List<Object> handle(final ParseResult parseResult) throws ExecutionException {
  final CommandLine commandLine = parseResult.asCommandLineList().get(0);
  final Optional<File> configFile = findConfigFile(parseResult, commandLine);
  commandLine.setDefaultValueProvider(createDefaultValueProvider(commandLine, configFile));
  commandLine.parseWithHandlers(
      resultHandler, exceptionHandler, parseResult.originalArgs().toArray(new String[0]));
  return new ArrayList<>();
}
 
Example #18
Source File: BlocksSubCommand.java    From besu with Apache License 2.0 5 votes vote down vote up
private BesuController createController() {
  try {
    // Set some defaults
    return parentCommand
        .parentCommand
        .getControllerBuilder()
        // set to mainnet genesis block so validation rules won't reject it.
        .clock(Clock.fixed(Instant.ofEpochSecond(startTime), ZoneOffset.UTC))
        .miningParameters(getMiningParameters())
        .build();
  } catch (final Exception e) {
    throw new ExecutionException(new CommandLine(parentCommand), e.getMessage(), e);
  }
}
 
Example #19
Source File: RLPSubCommand.java    From besu with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the stdin or from a file if one is specified by {@link #jsonSourceFile} then goes to
 * {@link #encode(String)} this data
 */
private void readInput() {
  // if we have an output file defined, print to it
  // otherwise print to defined output, usually standard output.
  StringBuilder jsonData = new StringBuilder();

  if (jsonSourceFile != null) {
    try {
      BufferedReader reader = Files.newBufferedReader(jsonSourceFile.toPath(), UTF_8);

      String line;
      while ((line = reader.readLine()) != null) jsonData.append(line);
    } catch (IOException e) {
      throw new ExecutionException(spec.commandLine(), "Unable to read JSON file.");
    }
  } else {
    // get JSON data from standard input
    try (Scanner scanner = new Scanner(parentCommand.in, UTF_8.name())) {
      while (scanner.hasNextLine()) {
        jsonData.append(String.join("", scanner.nextLine().split("\\s")));
      }
    }
  }

  // next step is to encode the value
  encode(jsonData.toString());
}
 
Example #20
Source File: PicocliBaseScript.java    From picocli with Apache License 2.0 3 votes vote down vote up
/**
 * If an Exception occurs during {@link #runRunnableSubcommand(List)}, or {@link #runScriptBody()}
 * then this gets called to report the problem.
 * The default behavior is to throw a new {@code ExecutionException} wrapping the specified exception.
 *
 * @param commandLine The CommandLine instance
 * @param args The argument array
 * @param ex The Exception that occurred
 * @return The value that Script.run should return when overriding this method
 * @throws ExecutionException wrapping the specified exception by default
 */
public Object handleExecutionException(CommandLine commandLine, String[] args, Exception ex) {
    if (ex instanceof ExecutionException) {
        throw (ExecutionException) ex;
    }
    throw new ExecutionException(commandLine, ex.toString(), ex);
}