Java 类org.springframework.boot.ApplicationArguments 实例源码

项目:spring-cloud-skipper    文件:HelpAwareShellApplicationRunner.java   
@Override
public void run(ApplicationArguments args) throws Exception {
    if (ShellUtils.hasHelpOption(args)) {
        String usageInstructions;

        final Reader reader = new InputStreamReader(getInputStream(HelpAwareShellApplicationRunner.class, "/usage.txt"));

        try {
            usageInstructions = FileCopyUtils.copyToString(new BufferedReader(reader));
            usageInstructions.replaceAll("(\\r|\\n)+", System.getProperty("line.separator"));
        }
        catch (Exception ex) {
            throw new IllegalStateException("Cannot read stream", ex);
        }
        System.out.println(usageInstructions);
    }
}
项目:spring-cloud-skipper    文件:InitializeConnectionApplicationRunner.java   
@Override
public void run(ApplicationArguments args) throws Exception {
    // user just wants to print help, do not try
    // to init connection. HelpAwareShellApplicationRunner simply output
    // usage and InteractiveModeApplicationRunner forces to run help.
    if (ShellUtils.hasHelpOption(args)) {
        return;
    }

    Target target = new Target(skipperClientProperties.getServerUri(), skipperClientProperties.getUsername(),
            skipperClientProperties.getPassword(), skipperClientProperties.isSkipSslValidation());

    // Attempt connection (including against default values) but do not crash the shell on
    // error
    try {
        targetHolder.changeTarget(target, null);
    }
    catch (Exception e) {
        resultHandler.handleResult(e);
    }

}
项目:spring-cloud-skipper    文件:InteractiveModeApplicationRunner.java   
@Override
public void run(ApplicationArguments args) throws Exception {
    // if we have args, assume one time run
    ArrayList<String> argsToShellCommand = new ArrayList<>();
    for (String arg : args.getSourceArgs()) {
        // consider client connection options as non command args
        if (!arg.contains("spring.cloud.skipper.client")) {
            argsToShellCommand.add(arg);
        }
    }
    if (argsToShellCommand.size() > 0) {
        if (ShellUtils.hasHelpOption(args)) {
            // going into 'help' mode. HelpAwareShellApplicationRunner already
            // printed usage, we just force running just help.
            argsToShellCommand.clear();
            argsToShellCommand.add("help");
        }
    }

    if (!argsToShellCommand.isEmpty()) {
        InteractiveShellApplicationRunner.disable(environment);
        shell.run(new StringInputProvider(argsToShellCommand));
    }
}
项目:circus-train    文件:HousekeepingRunner.java   
@Override
public void run(ApplicationArguments args) {
  Instant deletionCutoff = new Instant().minus(housekeeping.getExpiredPathDuration());
  LOG.info("Housekeeping at instant {} has started", deletionCutoff);
  CompletionCode completionCode = CompletionCode.SUCCESS;
  try {
    housekeepingService.cleanUp(deletionCutoff);
    LOG.info("Housekeeping at instant {} has finished", deletionCutoff);
  } catch (Exception e) {
    completionCode = CompletionCode.FAILURE;
    LOG.error("Housekeeping at instant {} has failed", deletionCutoff, e);
    throw e;
  } finally {
    Map<String, Long> metricsMap = ImmutableMap
        .<String, Long> builder()
        .put("housekeeping", completionCode.getCode())
        .build();
    metricSender.send(metricsMap);
  }
}
项目:f5-marathon-autoscale    文件:AutoscaleService.java   
@Override
public void run(ApplicationArguments args) throws InterruptedException {
    while (true) {
        try {
            if(LOG.isDebugEnabled()) {
                LOG.debug(" In Run: " + System.currentTimeMillis());
            }
            marathonSDService.updateServiceData();
            f5ScraperService.updateF5Stats();
            for (Map.Entry<String, F5ScraperService.F5Stats> stats : f5ScraperService.getF5StatsMap().entrySet()) {
                LOG.info("Service id: " + stats.getKey()
                        + " serviceConfig: " + stats.getValue());
                if (isScalable(stats.getValue())) {
                    scaleIfRequired(stats);
                }
            }
            isHealthy = true;
        } catch (Exception e) {
            isHealthy = false;
            LOG.error("Exception", e);
        } finally {
            waitFor(props.getService().getSchedulingIntervalInSecs() * 1000);
        }
    }
}
项目:JavaSamples    文件:MessageService.java   
public void run(ApplicationArguments args) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                long time = System.currentTimeMillis();
                producer.sendHeightQueue("lowQueue message " + time);
                producer.sendMiddleQueue("middleQueue message " + time);
                producer.sendLowQueue("lowQueue message " + time);

                producer.publishHeightTopic("heightTopic message " + time);
                producer.publishMiddleTopic("middleTopic message " + time);
                producer.publishLowTopic("lowTopic message " + time);

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).run();
}
项目:turing    文件:TurOnStartup.java   
@Override
public void run(ApplicationArguments arg0) throws Exception {
    final String FIRST_TIME = "FIRST_TIME";

    if (turConfigVarRepository.findById(FIRST_TIME) == null) {

        System.out.println("First Time Configuration ...");

        turLocaleOnStartup.createDefaultRows();
        turNLPVendorOnStartup.createDefaultRows();
        turNLPEntityOnStartup.createDefaultRows();
        turNLPVendorEntityOnStartup.createDefaultRows();
        turNLPFeatureOnStartup.createDefaultRows();
        turNLPInstanceOnStartup.createDefaultRows();
        turMLVendorOnStartup.createDefaultRows();
        turMLInstanceOnStartup.createDefaultRows();
        turSEVendorOnStartup.createDefaultRows();
        turSEInstanceOnStartup.createDefaultRows();
        turDataGroupStartup.createDefaultRows();
        turSNSiteOnStartup.createDefaultRows();
        turConfigVarOnStartup.createDefaultRows();

        System.out.println("Configuration finished.");
    }

}
项目:poe4j    文件:DataExtractor.java   
@Override
public void run(ApplicationArguments args) throws Exception {
    DataFileReader<BaseItemTypes> baseItemTypeReader = dataFileReaderFactory.create(BaseItemTypes.class);
    DataFileReader<ComponentAttributeRequirement> attrReqReader = dataFileReaderFactory.create(ComponentAttributeRequirement.class);

    List<ItemData> items = baseItemTypeReader.read()
            .filter(row -> row.getInheritsFrom().contains("Abstract"))
            .flatMap(baseItemType -> {
                return attrReqReader.read()
                        .filter(componentAttributeRequirement -> componentAttributeRequirement.getBaseItemTypesKey().equals(baseItemType));
            }).map(ItemData::new)
            .collect(toList());

    File outFile = Paths.get("item-data.json").toFile();
    log.info("Writing to {}", outFile.getAbsolutePath());
    objectMapper.writerWithDefaultPrettyPrinter().writeValue(outFile, items);
}
项目:bootiful-banners    文件:BootifulBannersApplication.java   
@Override
public void run(ApplicationArguments args) throws Exception {
    ImageBanner imageBanner = new ImageBanner(
            this.resolveInputImage());

    int maxWidth = this.properties.getMaxWidth();
    double aspectRatio = this.properties.getAspectRatio();
    boolean invert = this.properties.isInvert();
    Resource output = this.properties.getOutput();

    String banner = imageBanner.printBanner(maxWidth, aspectRatio, invert);
    if (output != null) {
        try (PrintWriter pw = new PrintWriter(output.getFile(), "UTF-8")) {
            pw.println(banner);
        }
    } else {
        System.out.println(banner);
    }
}
项目:spring-cloud-task    文件:TaskLifecycleListener.java   
/**
 * @param taskRepository The repository to record executions in.
 */
public TaskLifecycleListener(TaskRepository taskRepository,
        TaskNameResolver taskNameResolver,
        ApplicationArguments applicationArguments, TaskExplorer taskExplorer,
        TaskProperties taskProperties) {
    Assert.notNull(taskRepository, "A taskRepository is required");
    Assert.notNull(taskNameResolver, "A taskNameResolver is required");
    Assert.notNull(taskExplorer, "A taskExplorer is required");
    Assert.notNull(taskProperties, "TaskProperties is required");

    this.taskRepository = taskRepository;
    this.taskNameResolver = taskNameResolver;
    this.applicationArguments = applicationArguments;
    this.taskExplorer = taskExplorer;
    this.taskProperties = taskProperties;
}
项目:spring-cloud-consul    文件:TestConsumer.java   
@Override
public void run(ApplicationArguments args) throws Exception {
    logger.info("Consumer running with binder {}", binder);
    SubscribableChannel consumerChannel = new ExecutorSubscribableChannel();
    consumerChannel.subscribe(new MessageHandler() {
        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            messagePayload = (String) message.getPayload();
            logger.info("Received message: {}", messagePayload);
        }
    });
    String group = null;

    if (args.containsOption("group")) {
        group = args.getOptionValues("group").get(0);
    }

    binder.bindConsumer(ConsulBinderTests.BINDING_NAME, group, consumerChannel,
            new ConsumerProperties());
    isBound = true;
}
项目:train-simulator    文件:App.java   
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
  boolean mapsProvided = applicationArguments.containsOption("maps");
  if (mapsProvided) {
    List<String> maps = applicationArguments.getOptionValues("maps");
    maps.forEach(map -> AppConfig.experimentMaps.addAll(Arrays.asList(map.split(","))));
    List<String> toRemove = new ArrayList<>();
    AppConfig.experimentMaps.forEach(file -> {
      File f = new File(file);
      if (f.isDirectory()) {
        toRemove.add(file);
        List<String> files = Arrays
            .stream(f.listFiles((dir, name) -> name.toLowerCase().endsWith(".yaml")))
            .map(File::getAbsolutePath).collect(Collectors.toList());
        AppConfig.experimentMaps.addAll(files);
      }
    });
    AppConfig.experimentMaps.removeAll(toRemove);
  }
  boolean resultsDir = applicationArguments.containsOption("results");
  if (resultsDir) {
    List<String> outDirs = applicationArguments.getOptionValues("results");
    if (outDirs.size() > 1) {
      throw new IllegalArgumentException("Cannot have more than 1 results directories");
    }
    AppConfig.outputDir = outDirs.get(0);
  }
}
项目:syndesis    文件:Application.java   
@Override
@SuppressFBWarnings("DM_EXIT")
public void run(ApplicationArguments args) {
    try {
        System.out.println("To: "+to); //NOPMD
        generateIntegrationProject(new File(to));
    } catch (IOException e) {
        e.printStackTrace(); //NOPMD
        System.exit(1); //NOPMD
    }
}
项目:circus-train    文件:ComparisonApplication.java   
@Override
public void run(ApplicationArguments args) {
  LOG.info("{} tables to compare.", tableReplications.size());
  for (TableReplication tableReplication : tableReplications) {
    try {
      TableComparator tableComparison = tableComparisonFactory.newInstance(tableReplication);
      tableComparison.run();
    } catch (Throwable t) {
      LOG.error("Failed.", t);
    }
  }

}
项目:circus-train    文件:ComparisonToolArgs.java   
private void validate(ApplicationArguments args) {
  List<String> optionValues = args.getOptionValues(OUTPUT_FILE);
  if (optionValues == null) {
    throw new IllegalArgumentException("Missing --" + OUTPUT_FILE + " argument");
  } else if (optionValues.isEmpty()) {
    throw new IllegalArgumentException("Missing --" + OUTPUT_FILE + " argument value");
  }
  outputFile = new File(optionValues.get(0));
}
项目:circus-train    文件:FilterToolApplication.java   
@Override
public void run(ApplicationArguments args) {
  LOG.info("{} tables to replicate.", tableReplications.size());
  for (TableReplication tableReplication : tableReplications) {
    try {
      FilterGenerator filterGenerator = filterGeneratorFactory.newInstance(tableReplication);
      filterGenerator.run();
    } catch (Throwable t) {
      LOG.error("Failed.", t);
    }
  }

}
项目:circus-train    文件:Locomotive.java   
@Override
public void run(ApplicationArguments args) {
  locomotiveListener.circusTrainStartUp(args.getSourceArgs(), EventUtils.toEventSourceCatalog(sourceCatalog),
      EventUtils.toEventReplicaCatalog(replicaCatalog, security));
  CompletionCode completionCode = CompletionCode.SUCCESS;
  Builder<String, Long> metrics = ImmutableMap.builder();
  replicationFailures = 0;
  long replicated = 0;

  LOG.info("{} tables to replicate.", tableReplications.size());
  for (TableReplication tableReplication : tableReplications) {
    String summary = getReplicationSummary(tableReplication);
    LOG.info("Replicating {} replication mode '{}'.", summary, tableReplication.getReplicationMode());
    try {
      Replication replication = replicationFactory.newInstance(tableReplication);
      tableReplicationListener.tableReplicationStart(EventUtils.toEventTableReplication(tableReplication),
          replication.getEventId());
      replication.replicate();
      LOG.info("Completed replicating: {}.", summary);
      tableReplicationListener.tableReplicationSuccess(EventUtils.toEventTableReplication(tableReplication),
          replication.getEventId());
    } catch (Throwable t) {
      replicationFailures++;
      completionCode = CompletionCode.FAILURE;
      LOG.error("Failed to replicate: {}.", summary, t);
      tableReplicationListener.tableReplicationFailure(EventUtils.toEventTableReplication(tableReplication),
          EventUtils.EVENT_ID_UNAVAILABLE, t);
    }
    replicated++;
  }

  metrics.put("tables_replicated", replicated);
  metrics.put(completionCode.getMetricName(), completionCode.getCode());
  Map<String, Long> metricsMap = metrics.build();
  metricSender.send(metricsMap);
  locomotiveListener.circusTrainShutDown(completionCode, metricsMap);
}
项目:IPPR2016    文件:StartUpRunner.java   
@Async
@Transactional
@Override
public void run(final ApplicationArguments args) throws Exception {
  LOG.info(
      "##################################################################################################################");
  LOG.info("Start up of already running processes and users");

  final List<ProcessInstance> processes = Lists.newArrayList(
      processInstanceRepository.getProcessesWithState(ProcessInstanceState.ACTIVE.name()));

  processes.stream()
      .map(process -> PatternsCS.ask(processSupervisorActor,
          new ProcessWakeUpMessage.Request(process.getPiId()), Global.TIMEOUT)
          .toCompletableFuture())
      .forEachOrdered(response -> {
        futures.add(response);
        handleProcessResponse(response);
      });

  final Set<Subject> subjects =
      processes.stream().map(ProcessInstance::getSubjects).flatMap(List::stream)
          .filter(subject -> subject.getUser() != null).collect(Collectors.toSet());

  subjects.stream()
      .map(subject -> PatternsCS.ask(userSupervisorActor,
          new UserActorWakeUpMessage.Request(subject.getUser()), Global.TIMEOUT)
          .toCompletableFuture())
      .forEachOrdered(response -> {
        futures.add(response);
        handleUserResponse(response);
      });

  CompletableFuture.allOf(Iterables.toArray(futures, CompletableFuture.class)).thenRun(() -> {
    final List<SubjectState> subjectStatesWithTimeout =
        subjectStateRepository.getSubjectStatesWithTimeout();
    subjectStatesWithTimeout.stream().forEach(this::notifyTimeoutScheduler);
  });
}
项目:IPPR2016    文件:AbstractExample.java   
@Override
public void run(final ApplicationArguments args) throws Exception {
  if (exampleConfiguration.isInsertExamplesEnabled()) {
    LOG.info(
        "#######################################################################################################");
    LOG.info("Test data for example process: {}", getName());
    createData();
    LOG.info(
        "#######################################################################################################");
  } else {
    LOG.info("Examples won't be inserted since 'ippr.insert-examples.enabled' is false");
  }
}
项目:spring-boot-greendogdelivery-casadocodigo    文件:RepositoryTest.java   
public void run(ApplicationArguments applicationArguments) throws Exception {

        System.out.println(">>> Iniciando carga de dados...");
        Cliente fernando = new Cliente(ID_CLIENTE_FERNANDO,"Fernando Boaglio","Sampa");
        Cliente zePequeno = new Cliente(ID_CLIENTE_ZE_PEQUENO,"Zé Pequeno","Cidade de Deus");       

        Item dog1 = new Item(ID_ITEM1,"Green Dog tradicional",25d);
        Item dog2 = new Item(ID_ITEM2,"Green Dog tradicional picante",27d);
        Item dog3 = new Item(ID_ITEM3,"Green Dog max salada",30d);

        List<Item> listaPedidoFernando1 = new ArrayList<Item>();
        listaPedidoFernando1.add(dog1);

        List<Item> listaPedidoZePequeno1 = new ArrayList<Item>();
        listaPedidoZePequeno1.add(dog2);
        listaPedidoZePequeno1.add(dog3);

        Pedido pedidoDoFernando = new Pedido(ID_PEDIDO1,fernando,listaPedidoFernando1,dog1.getPreco());
        fernando.novoPedido(pedidoDoFernando);

        Pedido pedidoDoZepequeno = new Pedido(ID_PEDIDO2,zePequeno,listaPedidoZePequeno1, dog2.getPreco()+dog3.getPreco());
        zePequeno.novoPedido(pedidoDoZepequeno);

        System.out.println(">>> Pedido 1 - Fernando : "+ pedidoDoFernando);
        System.out.println(">>> Pedido 2 - Ze Pequeno: "+ pedidoDoZepequeno);


        clienteRepository.saveAndFlush(zePequeno);
        System.out.println(">>> Gravado cliente 2: "+zePequeno);

        List<Item> listaPedidoFernando2 = new ArrayList<Item>();
        listaPedidoFernando2.add(dog2);
        Pedido pedido2DoFernando  = new Pedido(ID_PEDIDO3,fernando,listaPedidoFernando2,dog2.getPreco());
        fernando.novoPedido(pedido2DoFernando);
        clienteRepository.saveAndFlush(fernando);
        System.out.println(">>> Pedido 2 - Fernando : "+ pedido2DoFernando);
        System.out.println(">>> Gravado cliente 1: "+fernando);

    }
项目:hippo    文件:PublicationSystemMigrator.java   
@Override
public void run(final ApplicationArguments args) throws Exception {

    if (args.getOptionNames().isEmpty() || args.containsOption(HELP_FLAG)) {
        printUsageInfo();
        return;
    }

    executionConfigurator.initExecutionParameters(args);

    logExecutionParameters();

    try {
        migrationTasks.stream()
            .peek(migrationTask -> {
                if (!migrationTask.isRequested()) {
                    log.debug("Skipping {} - not requested", migrationTask.getClass().getSimpleName());
                }
            })
            .filter(MigrationTask::isRequested).forEach(MigrationTask::execute);

    } catch (final Exception e) {
        log.error("Migration has failed.", e);
    } finally {
        migrationReport.generate();
        migrationReport.logErrors();

        logExecutionParameters();
    }

}
项目:hippo    文件:ExecutionConfigurator.java   
private void initHippoImportDir(final ApplicationArguments args) {
    Path pathArg = getPathArg(args, HIPPO_IMPORT_DIR);
    if (pathArg == null) {
        pathArg = Paths.get(MIGRATOR_TEMP_DIR_PATH.toString(), HIPPO_IMPORT_DIR_DEFAULT_NAME);
    }

    executionParameters.setHippoImportDir(pathArg);
}
项目:hippo    文件:ExecutionConfigurator.java   
private void initDownloadDir(final ApplicationArguments args) {
    Path pathArg = getPathArg(args, NESSTAR_ATTACHMENT_DOWNLOAD_FOLDER);
    if (pathArg == null) {
        pathArg = Paths.get(MIGRATOR_TEMP_DIR_PATH.toString(), ATTACHMENT_DOWNLOAD_DIR_NAME_DEFAULT);
    }

    executionParameters.setNesstarAttachmentDownloadDir(pathArg);
}
项目:hippo    文件:ExecutionConfigurator.java   
private void initTaxonomyDefinitionOutputPath(final ApplicationArguments args) {
    Path pathArg = getPathArg(args, TAXONOMY_DEFINITION_OUTPUT_PATH);
    if (pathArg == null) {
        pathArg = Paths.get(MIGRATOR_TEMP_DIR_PATH.toString(), HIPPO_IMPORT_DIR_DEFAULT_NAME);
    }

    executionParameters.setTaxonomyDefinitionOutputPath(pathArg);
}
项目:hippo    文件:ExecutionConfigurator.java   
private void initMigrationReportOutputPath(ApplicationArguments args) {
    Path pathArg = getPathArg(args, MIGRATION_REPORT_PATH);
    if (pathArg == null) {
        pathArg = Paths.get(MIGRATOR_TEMP_DIR_PATH.toString(), REPORTS_DIR_NAME, MIGRATION_REPORT_FILENAME_DEFAULT);
    }
    executionParameters.setMigrationReportFilePath(pathArg);
}
项目:hippo    文件:ExecutionConfigurator.java   
private Path getPathArg(final ApplicationArguments args, final String commandLineArgName) {
    return Optional.ofNullable(args.getOptionValues(commandLineArgName))
        .orElse(emptyList())
        .stream()
        .findFirst()
        .map(Paths::get)
        .orElse(null);
}
项目:Sound.je    文件:DatabaseLoader.java   
/**
 * Ensure certain fields are already saved to the database
 *
 * @param applicationArguments
 */
@Override
public void run(final ApplicationArguments applicationArguments) {
    savePrivileges();
    saveRoles();
    deletePersistentLogins();
}
项目:mybatis-migrations-spring-boot-autoconfigure    文件:MyBatisMigrationsAutoConfiguration.java   
/**
 * CLI handler bean
 * @param springApplicationArguments for CLI args
 * @return constructed MyBatisMigrationsCliHandler bean
 */
@Bean(name = MY_BATIS_MIGRATIONS_CLI_HANDLER_BEAN)
@ConditionalOnMissingBean
public MyBatisMigrationsCliHandler myBatisMigrationsCliHandler(
        ApplicationArguments springApplicationArguments) {
    return new MyBatisMigrationsCliHandler(springApplicationArguments.getSourceArgs());
}
项目:spring-cloud-dashboard    文件:BaseShellAutoConfiguration.java   
@Bean
@ConditionalOnMissingBean(CommandLine.class)
public CommandLine commandLine(ShellCommandLineParser shellCommandLineParser,
                            ShellProperties shellProperties,
                            ApplicationArguments applicationArguments) throws Exception {
    return shellCommandLineParser.parse(shellProperties, applicationArguments.getSourceArgs());
}
项目:artifactory-resource    文件:OutCommand.java   
@Override
public void run(ApplicationArguments args) throws Exception {
    OutRequest request = this.systemInput.read(OutRequest.class);
    Directory directory = Directory.fromArgs(args);
    OutResponse response = this.handler.handle(request, directory);
    this.systemOutput.write(response);
}
项目:artifactory-resource    文件:InCommand.java   
@Override
public void run(ApplicationArguments args) throws Exception {
    InRequest request = this.systemInput.read(InRequest.class);
    Directory directory = Directory.fromArgs(args);
    InResponse response = this.handler.handle(request, directory);
    this.systemOutput.write(response);
}
项目:artifactory-resource    文件:CommandProcessor.java   
@Override
public void run(ApplicationArguments args) throws Exception {
    List<String> nonOptionArgs = args.getNonOptionArgs();
    Assert.state(!nonOptionArgs.isEmpty(), "No command argument specified");
    String request = nonOptionArgs.get(0);
    this.commands.stream().filter((c) -> c.getName().equals(request)).findFirst()
            .orElseThrow(() -> new IllegalStateException(
                    "Unknown command '" + request + "'"))
            .run(args);
}
项目:artifactory-resource    文件:Directory.java   
public static Directory fromArgs(ApplicationArguments args) {
    List<String> nonOptionArgs = args.getNonOptionArgs();
    Assert.state(nonOptionArgs.size() >= 2, "No directory argument specified");
    return new Directory(nonOptionArgs.get(1));
}
项目:artifactory-resource    文件:DirectoryTests.java   
@Test
public void createFromArgsShouldUseArgument() throws Exception {
    File file = this.temporaryFolder.newFolder();
    String path = StringUtils.cleanPath(file.getPath());
    ApplicationArguments args = new DefaultApplicationArguments(
            new String[] { "in", path });
    Directory directory = Directory.fromArgs(args);
    assertThat(directory.getFile()).isEqualTo(file);
}
项目:openshift-ldapsync    文件:Application.java   
@Override
public void run(ApplicationArguments args) throws Exception {
    synchronize();

    if (args.containsOption("adhoc")) {
        LOG.info("Run only one import. Don't starting scheduler");
        System.exit(0);
    }
}
项目:JavaSamples    文件:Application.java   
@Override
public void run(ApplicationArguments args) throws Exception {
    if (args.getSourceArgs().length > 0 ) {
        System.out.println(myService.getMessage(args.getSourceArgs().toString()));
    }else{
        System.out.println(myService.getMessage());
    }

    System.exit(0);
}
项目:JavaSamples    文件:MessageService.java   
public void run(ApplicationArguments args) {
        List<UserEntity> userList = userMapper.getAll();

        System.out.println(userList.get(0).toString());
        System.out.println(JSON.toJSONString(userList));

        UserEntity userEntity = new UserEntity();
        userEntity.setUserName("test");
        userEntity.setPassWord("abcde");
        userEntity.setUserSex(UserSexEnum.WOMAN);
        userEntity.setNickName("test");
        userMapper.insert(userEntity);

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                while (true) {
//                    long time = System.currentTimeMillis();
//                    producer.sendHeightQueue("lowQueue message " + time);
//                    producer.sendMiddleQueue("middleQueue message " + time);
//                    producer.sendLowQueue("lowQueue message " + time);
//
//                    producer.publishHeightTopic("heightTopic message " + time);
//                    producer.publishMiddleTopic("middleTopic message " + time);
//                    producer.publishLowTopic("lowTopic message " + time);
//
//                    try {
//                        Thread.sleep(1000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }).run();
    }
项目:lyre    文件:LyreRunner.java   
@Override
public void run(ApplicationArguments args) throws Exception {

    SpringApplication app = new SpringApplication(Lyre.class);
    String[] arguments = RunnerUtils.buildArguments(app.getMainApplicationClass().getAnnotation(EnableLyre.class));
    app.setMainApplicationClass(Lyre.class);
    app.setBannerMode(Banner.Mode.OFF);
    app.run(arguments);
}
项目:waggle-dance    文件:MetaStoreProxyServer.java   
@Override
public void run(ApplicationArguments args) throws Exception {
  if (isRunning()) {
    throw new RuntimeException("Can't run more than one instance");
  }

  final boolean isCliVerbose = waggleDanceConfiguration.isVerbose();

  try {
    String msg = "Starting WaggleDance on port " + waggleDanceConfiguration.getPort();
    LOG.info(msg);
    if (waggleDanceConfiguration.isVerbose()) {
      System.err.println(msg);
    }

    // Add shutdown hook.
    Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {
        String shutdownMsg = "Shutting down WaggleDance.";
        LOG.info(shutdownMsg);
        if (isCliVerbose) {
          System.err.println(shutdownMsg);
        }
      }
    });

    AtomicBoolean startedServing = new AtomicBoolean();
    startWaggleDance(ShimLoader.getHadoopThriftAuthBridge(), startLock, startCondition, startedServing);
  } catch (Throwable t) {
    // Catch the exception, log it and rethrow it.
    LOG.error("WaggleDance Thrift Server threw an exception...", t);
    throw new Exception(t);
  }
}
项目:grpc-java-by-example    文件:Cmd.java   
@Autowired
public Cmd(ApplicationArguments args, @Qualifier("discoveryClientChannelFactory") GrpcChannelFactory channelFactory,
           DiscoveryClient discoveryClient) {
  discoveryClient.getServices();
  Channel channel = channelFactory.createChannel("EchoService");

  int i = 0;
  while (true) {
    EchoServiceGrpc.EchoServiceBlockingStub stub = EchoServiceGrpc.newBlockingStub(channel);
    EchoOuterClass.Echo response = stub.echo(EchoOuterClass.Echo.newBuilder().setMessage("Hello " + i).build());
    System.out.println("sent message #" + i);
    System.out.println("got response: " + response);
    i++;
  }
}