@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); } }
@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); } }
@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)); } }
@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); } }
@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); } } }
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(); }
@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."); } }
@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); }
@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); } }
/** * @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; }
@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; }
@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); } }
@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 } }
@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); } } }
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)); }
@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); } } }
@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); }
@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); }); }
@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"); } }
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); }
@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(); } }
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); }
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); }
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); }
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); }
private Path getPathArg(final ApplicationArguments args, final String commandLineArgName) { return Optional.ofNullable(args.getOptionValues(commandLineArgName)) .orElse(emptyList()) .stream() .findFirst() .map(Paths::get) .orElse(null); }
/** * Ensure certain fields are already saved to the database * * @param applicationArguments */ @Override public void run(final ApplicationArguments applicationArguments) { savePrivileges(); saveRoles(); deletePersistentLogins(); }
/** * 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()); }
@Bean @ConditionalOnMissingBean(CommandLine.class) public CommandLine commandLine(ShellCommandLineParser shellCommandLineParser, ShellProperties shellProperties, ApplicationArguments applicationArguments) throws Exception { return shellCommandLineParser.parse(shellProperties, applicationArguments.getSourceArgs()); }
@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); }
@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); }
@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); }
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)); }
@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); }
@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); } }
@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); }
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(); }
@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); }
@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); } }
@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++; } }