List of usage examples for org.springframework.util StopWatch start
public void start() throws IllegalStateException
From source file:com.auditbucket.client.Importer.java
public static void main(String args[]) { try {// www.j a v a 2s .c om ArgumentParser parser = ArgumentParsers.newArgumentParser("ABImport").defaultHelp(true) .description("Import file formats to AuditBucket"); parser.addArgument("-s", "--server").setDefault("http://localhost/ab-engine") .help("Host URL to send files to"); parser.addArgument("-b", "--batch").setDefault(100).help("Default batch size"); parser.addArgument("-x", "--xref").setDefault(false).help("Cross References Only"); parser.addArgument("files").nargs("*").help( "Path and filename of Audit records to import in the format \"[/filepath/filename.ext],[com.import.YourClass],{skipCount}\""); Namespace ns = null; try { ns = parser.parseArgs(args); } catch (ArgumentParserException e) { parser.handleError(e); System.exit(1); } List<String> files = ns.getList("files"); if (files.isEmpty()) { parser.handleError(new ArgumentParserException("No files to parse", parser)); System.exit(1); } String b = ns.getString("batch"); int batchSize = 100; if (b != null && !"".equals(b)) batchSize = Integer.parseInt(b); StopWatch watch = new StopWatch(); watch.start(); logger.info("*** Starting {}", DateFormat.getDateTimeInstance().format(new Date())); long totalRows = 0; for (String file : files) { int skipCount = 0; List<String> items = Arrays.asList(file.split("\\s*,\\s*")); if (items.size() == 0) parser.handleError(new ArgumentParserException("No file arguments to process", parser)); int item = 0; String fileName = null; String fileClass = null; for (String itemArg : items) { if (item == 0) { fileName = itemArg; } else if (item == 1) { fileClass = itemArg; } else if (item == 2) skipCount = Integer.parseInt(itemArg); item++; } logger.debug("*** Calculated process args {}, {}, {}, {}", fileName, fileClass, batchSize, skipCount); totalRows = totalRows + processFile(ns.get("server").toString(), fileName, (fileClass != null ? Class.forName(fileClass) : null), batchSize, skipCount); } endProcess(watch, totalRows); logger.info("Finished at {}", DateFormat.getDateTimeInstance().format(new Date())); } catch (Exception e) { logger.error("Import error", e); } }
From source file:org.tommy.stationery.moracle.core.client.load.StompWebSocketLoadTestClient.java
public static void main(String[] args) throws Exception { // Modify host and port below to match wherever StompWebSocketServer.java is running!! // When StompWebSocketServer starts it prints the selected available String host = "localhost"; if (args.length > 0) { host = args[0];/*from ww w .ja v a2 s . c om*/ } int port = 59984; if (args.length > 1) { port = Integer.valueOf(args[1]); } String url = "http://" + host + ":" + port + "/home"; logger.debug("Sending warm-up HTTP request to " + url); HttpStatus status = new RestTemplate().getForEntity(url, Void.class).getStatusCode(); Assert.state(status == HttpStatus.OK); final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS); final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS); final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS); final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS); final AtomicReference<Throwable> failure = new AtomicReference<Throwable>(); Executor executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE); org.eclipse.jetty.websocket.client.WebSocketClient jettyClient = new WebSocketClient(executor); JettyWebSocketClient webSocketClient = new JettyWebSocketClient(jettyClient); webSocketClient.start(); HttpClient jettyHttpClient = new HttpClient(); jettyHttpClient.setMaxConnectionsPerDestination(1000); jettyHttpClient.setExecutor(new QueuedThreadPool(1000)); jettyHttpClient.start(); List<Transport> transports = new ArrayList<>(); transports.add(new WebSocketTransport(webSocketClient)); transports.add(new JettyXhrTransport(jettyHttpClient)); SockJsClient sockJsClient = new SockJsClient(transports); try { URI uri = new URI("ws://" + host + ":" + port + "/stomp"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, null, sockJsClient); stompClient.setMessageConverter(new StringMessageConverter()); logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users "); StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests"); stopWatch.start(); List<ConsumerStompMessageHandler> consumers = new ArrayList<>(); for (int i = 0; i < NUMBER_OF_USERS; i++) { consumers.add(new ConsumerStompMessageHandler(BROADCAST_MESSAGE_COUNT, connectLatch, subscribeLatch, messageLatch, disconnectLatch, failure)); stompClient.connect(consumers.get(i)); } if (failure.get() != null) { throw new AssertionError("Test failed", failure.get()); } if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) { logger.info("Not all users connected, remaining: " + connectLatch.getCount()); } if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) { logger.info("Not all users subscribed, remaining: " + subscribeLatch.getCount()); } stopWatch.stop(); logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis"); logger.debug("Broadcasting " + BROADCAST_MESSAGE_COUNT + " messages to " + NUMBER_OF_USERS + " users "); stopWatch.start(); ProducerStompMessageHandler producer = new ProducerStompMessageHandler(BROADCAST_MESSAGE_COUNT, failure); stompClient.connect(producer); if (failure.get() != null) { throw new AssertionError("Test failed", failure.get()); } if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) { for (ConsumerStompMessageHandler consumer : consumers) { if (consumer.messageCount.get() < consumer.expectedMessageCount) { logger.debug(consumer); } } } if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) { logger.info("Not all handlers received every message, remaining: " + messageLatch.getCount()); } producer.session.disconnect(); if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) { logger.info("Not all disconnects completed, remaining: " + disconnectLatch.getCount()); } stopWatch.stop(); logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis"); System.out.println("\nPress any key to exit..."); System.in.read(); } catch (Throwable t) { t.printStackTrace(); } finally { webSocketClient.stop(); jettyHttpClient.stop(); } logger.debug("Exiting"); System.exit(0); }
From source file:camel.Main.java
private static void testBatchOfMessages(final ProducerTemplate template, int number, int batch) throws Exception { StopWatch stopWatch = new StopWatch(); stopWatch.start(); for (int i = 0; i < number; i++) { template.requestBody(String.valueOf(i)); }/* ww w. j a v a 2s . c o m*/ stopWatch.stop(); System.out.println(batch + ". Exchanged " + number + " messages in " + stopWatch.getTotalTimeMillis()); }
From source file:example.springdata.redis.sentinel.RedisSentinelApplication.java
private static void startStopWatchIfNotRunning(StopWatch stopWatch) { if (!stopWatch.isRunning()) { stopWatch.start(); }/* w w w. j a v a 2 s. co m*/ }
From source file:org.nebulaframework.grid.Grid.java
/** * Starts {@link ClusterManager} instance with default settings, * read from default properties file./*from www.j a va 2 s.co m*/ * * @return ClusterManager * * @throws IllegalStateException if a Grid Member (Cluster / Node) has * already started with in the current VM. Nebula supports only one Grid * Member per VM. */ public synchronized static ClusterManager startClusterManager() throws IllegalStateException { if (isInitialized()) { // A Grid Member has already started in this VM throw new IllegalStateException("A Grid Memeber Already Started in VM"); } initializeDefaultExceptionHandler(); StopWatch sw = new StopWatch(); try { sw.start(); log.info("ClusterManager Starting..."); // Set Security Manager System.setSecurityManager(new SecurityManager()); // Detect Configuration Properties config = ConfigurationSupport.detectClusterConfiguration(); // Register with any Colombus Servers ClusterDiscoverySupport.registerColombus(config); clusterManager = true; log.debug("Starting up Spring Container..."); applicationContext = new NebulaApplicationContext(CLUSTER_SPRING_CONTEXT, config); log.debug("Spring Container Started"); return (ClusterManager) applicationContext.getBean("clusterManager"); } finally { sw.stop(); log.info("ClusterManager Started Up. " + sw.getLastTaskTimeMillis() + " ms"); } }
From source file:org.nebulaframework.grid.Grid.java
/** * Starts a {@link GridNode} with default settings, read from * default properties file./*from w ww . ja v a 2 s. co m*/ * * @param useConfigDiscovery indicates whether to use information * from configuration to discover * * @return GridNode * * @throws IllegalStateException if a Grid Member (Cluster / Node) has * already started with in the current VM. Nebula supports only one Grid * Member per VM. */ public synchronized static GridNode startGridNode(boolean useConfigDiscovery) throws IllegalStateException { if (isInitialized()) { // A Grid Member has already started in this VM throw new IllegalStateException("A Grid Memeber Already Started in VM"); } initializeDefaultExceptionHandler(); StopWatch sw = new StopWatch(); try { sw.start(); // Set Security Manager System.setSecurityManager(new SecurityManager()); // Detect Configuration Properties config = ConfigurationSupport.detectNodeConfiguration(); log.info("GridNode Attempting Discovery..."); // Discover Cluster If Needed GridNodeDiscoverySupport.discover(config, useConfigDiscovery); checkJMSBroker(config.getProperty(ConfigurationKeys.CLUSTER_SERVICE.value())); log.debug("Starting up Spring Container..."); applicationContext = new NebulaApplicationContext(GRIDNODE_CONTEXT, config); log.debug("Spring Container Started"); node = true; sw.stop(); log.info("GridNode Started Up. " + sw.getLastTaskTimeMillis() + " ms"); return (GridNode) applicationContext.getBean("localNode"); } finally { if (sw.isRunning()) { sw.stop(); } } }
From source file:org.nebulaframework.grid.Grid.java
/** * Starts a Light-weight {@link GridNode} (a GridNode without * Job Execution Support, that is non-worker) with default * settings, read from default properties file. * // w w w.j av a 2 s. c o m * @param useConfigDiscovery indicates whether to use information * from configuration to discover * * @param isGui indicates that the application is a GUI based * application and any disconnection notifications should be * done through message boxes. * * @return GridNode * * @throws IllegalStateException if a Grid Member (Cluster / Node) has * already started with in the current VM. Nebula supports only one Grid * Member per VM. */ public synchronized static GridNode startLightGridNode(boolean useConfigDiscovery, final boolean isGui) throws IllegalStateException { if (isInitialized()) { // A Grid Member has already started in this VM throw new IllegalStateException("A Grid Memeber Already Started in VM"); } initializeDefaultExceptionHandler(); StopWatch sw = new StopWatch(); try { sw.start(); // Set Security Manager System.setSecurityManager(new SecurityManager()); Properties config = ConfigurationSupport.detectNodeConfiguration(); log.info("GridNode Attempting Discovery..."); // Discover Cluster If Needed GridNodeDiscoverySupport.discover(config, useConfigDiscovery); checkJMSBroker(config.getProperty(ConfigurationKeys.CLUSTER_SERVICE.value())); // If we reach here, connection test succeeded log.debug("Starting up Spring Container..."); applicationContext = new NebulaApplicationContext(GRIDNODE_LIGHT_CONTEXT, config); log.debug("Spring Container Started"); node = true; lightweight = true; sw.stop(); log.info("GridNode Started Up. " + sw.getLastTaskTimeMillis() + " ms"); GridNode node = (GridNode) applicationContext.getBean("localNode"); ServiceEventsSupport.addServiceHook(new ServiceHookCallback() { @Override public void onServiceEvent(ServiceMessage message) { log.warn("[GridNode] Disconnected from Cluster"); log.warn("[GridNode] Shutting Down"); if (isGui) { JOptionPane.showMessageDialog(UISupport.activeWindow(), "Disconnected from Cluster, terminating VM"); } System.exit(0); } }, node.getClusterId().toString(), ServiceMessageType.NODE_DISCONNECTED); return node; } finally { if (sw.isRunning()) { sw.stop(); } } }
From source file:com.auditbucket.client.Importer.java
static long processXMLFile(String file, AbRestClient abExporter, XmlMappable mappable, boolean simulateOnly) throws ParserConfigurationException, IOException, SAXException, JDOMException, DatagioException { try {// w w w . j av a 2 s . co m long rows = 0; StopWatch watch = new StopWatch(); StreamSource source = new StreamSource(file); XMLInputFactory xif = XMLInputFactory.newFactory(); XMLStreamReader xsr = xif.createXMLStreamReader(source); mappable.positionReader(xsr); List<CrossReferenceInputBean> referenceInputBeans = new ArrayList<>(); String docType = mappable.getDataType(); watch.start(); try { long then = new DateTime().getMillis(); while (xsr.getLocalName().equals(docType)) { XmlMappable row = mappable.newInstance(simulateOnly); String json = row.setXMLData(xsr); MetaInputBean header = (MetaInputBean) row; if (!header.getCrossReferences().isEmpty()) { referenceInputBeans.add(new CrossReferenceInputBean(header.getFortress(), header.getCallerRef(), header.getCrossReferences())); rows = rows + header.getCrossReferences().size(); } LogInputBean logInputBean = new LogInputBean("system", new DateTime(header.getWhen()), json); header.setLog(logInputBean); //logger.info(json); xsr.nextTag(); writeAudit(abExporter, header, mappable.getClass().getCanonicalName()); rows++; if (rows % 500 == 0 && !simulateOnly) logger.info("Processed {} elapsed seconds {}", rows, new DateTime().getMillis() - then / 1000d); } } finally { abExporter.flush(mappable.getClass().getCanonicalName(), mappable.getABType()); } if (!referenceInputBeans.isEmpty()) { logger.debug("Wrote [{}] cross references", writeCrossReferences(abExporter, referenceInputBeans, "Cross References")); } return endProcess(watch, rows); } catch (XMLStreamException | JAXBException e1) { throw new IOException(e1); } }
From source file:com.auditbucket.client.Importer.java
static long processCSVFile(String file, AbRestClient abExporter, DelimitedMappable mappable, int skipCount, boolean simulateOnly) throws IOException, IllegalAccessException, InstantiationException, DatagioException { StopWatch watch = new StopWatch(); DelimitedMappable row = mappable.newInstance(simulateOnly); int rows = 0; BufferedReader br;/*from w w w . java 2s .c o m*/ br = new BufferedReader(new FileReader(file)); try { CSVReader csvReader = new CSVReader(br, row.getDelimiter()); String[] headerRow = null; String[] nextLine; if (mappable.hasHeader()) { while ((nextLine = csvReader.readNext()) != null) { if (!((nextLine[0].charAt(0) == '#') || nextLine[0].charAt(1) == '#')) { headerRow = nextLine; break; } } } watch.start(); AbRestClient.type type = mappable.getABType(); while ((nextLine = csvReader.readNext()) != null) { if (!nextLine[0].startsWith("#")) { rows++; if (rows >= skipCount) { if (rows == skipCount) logger.info("Starting to process from row {}", skipCount); row = mappable.newInstance(simulateOnly); String jsonData = row.setData(headerRow, nextLine); //logger.info(jsonData); if (type == AbRestClient.type.AUDIT) { MetaInputBean header = (MetaInputBean) row; if (!"".equals(jsonData)) { jsonData = jsonData.replaceAll("[\\x00-\\x09\\x11\\x12\\x14-\\x1F\\x7F]", ""); LogInputBean logInputBean = new LogInputBean("system", new DateTime(), jsonData); header.setLog(logInputBean); } else { // It's all Meta baby - no track information } writeAudit(abExporter, header, mappable.getClass().getCanonicalName()); } else {// Tag if (!"".equals(jsonData)) { TagInputBean tagInputBean = (TagInputBean) row; logger.info(tagInputBean.toString()); writeTag(abExporter, tagInputBean, mappable.getClass().getCanonicalName()); } } if (rows % 500 == 0) { if (!simulateOnly) logger.info("Processed {} ", rows); } } } else { if (rows % 500 == 0 && !simulateOnly) logger.info("Skipping {} of {}", rows, skipCount); } } } finally { abExporter.flush(mappable.getClass().getCanonicalName(), mappable.getABType()); br.close(); } return endProcess(watch, rows); }
From source file:com.swarmcn.user.web.config.SwaggerConfiguration.java
@Bean public Docket swaggerSpringfoxDocket() { log.debug("Starting Swagger"); StopWatch watch = new StopWatch(); watch.start(); Docket swaggerSpringMvcPlugin = new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) .genericModelSubstitutes(ResponseEntity.class).select().build(); watch.stop();// w ww . j av a2s .c o m log.debug("Started Swagger in {} ms", watch.getTotalTimeMillis()); return swaggerSpringMvcPlugin; }