List of usage examples for java.lang StringBuilder StringBuilder
@HotSpotIntrinsicCandidate
public StringBuilder()
From source file:com.linkedin.pinotdruidbenchmark.DruidResponseTime.java
public static void main(String[] args) throws Exception { if (args.length != 4 && args.length != 5) { System.err.println(// ww w .j av a 2 s . com "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional)."); return; } File queryDir = new File(args[0]); String resourceUrl = args[1]; int warmUpRounds = Integer.parseInt(args[2]); int testRounds = Integer.parseInt(args[3]); File resultDir; if (args.length == 4) { resultDir = null; } else { resultDir = new File(args[4]); if (!resultDir.exists()) { if (!resultDir.mkdirs()) { throw new RuntimeException("Failed to create result directory: " + resultDir); } } } File[] queryFiles = queryDir.listFiles(); assert queryFiles != null; Arrays.sort(queryFiles); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(resourceUrl); httpPost.addHeader("content-type", "application/json"); for (File queryFile : queryFiles) { StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFile))) { int length; while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) { stringBuilder.append(new String(CHAR_BUFFER, 0, length)); } } String query = stringBuilder.toString(); httpPost.setEntity(new StringEntity(query)); System.out.println( "--------------------------------------------------------------------------------"); System.out.println("Running query: " + query); System.out.println( "--------------------------------------------------------------------------------"); // Warm-up Rounds System.out.println("Run " + warmUpRounds + " times to warm up..."); for (int i = 0; i < warmUpRounds; i++) { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpResponse.close(); System.out.print('*'); } System.out.println(); // Test Rounds System.out.println("Run " + testRounds + " times to get response time statistics..."); long[] responseTimes = new long[testRounds]; long totalResponseTime = 0L; for (int i = 0; i < testRounds; i++) { long startTime = System.currentTimeMillis(); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpResponse.close(); long responseTime = System.currentTimeMillis() - startTime; responseTimes[i] = responseTime; totalResponseTime += responseTime; System.out.print(responseTime + "ms "); } System.out.println(); // Store result. if (resultDir != null) { File resultFile = new File(resultDir, queryFile.getName() + ".result"); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); try (BufferedInputStream bufferedInputStream = new BufferedInputStream( httpResponse.getEntity().getContent()); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) { int length; while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) { bufferedWriter.write(new String(BYTE_BUFFER, 0, length)); } } httpResponse.close(); } // Process response times. double averageResponseTime = (double) totalResponseTime / testRounds; double temp = 0; for (long responseTime : responseTimes) { temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime); } double standardDeviation = Math.sqrt(temp / testRounds); System.out.println("Average response time: " + averageResponseTime + "ms"); System.out.println("Standard deviation: " + standardDeviation); } } }
From source file:com.khartec.waltz.jobs.sample.EndUserAppMaker.java
public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class); OrganisationalUnitDao organisationalUnitDao = ctx.getBean(OrganisationalUnitDao.class); DSLContext dsl = ctx.getBean(DSLContext.class); EndUserAppService endUserService = ctx.getBean(EndUserAppService.class); List<Long> ids = IdUtilities.toIds(organisationalUnitDao.findAll()); String[] subjects = { "Trade", "Risk", "Balance", "PnL", "Rate", "Fines", "Party", "Confirmations", "Settlement", "Instruction", "Person", "Profit", "Margin", "Finance", "Account" }; String[] types = { "Report", "Summary", "Draft", "Calculations", "Breaks", "Record", "Statement", "Information", "Pivot" }; String[] tech = { "MS ACCESS", "MS EXCEL", "VBA" }; dsl.delete(END_USER_APPLICATION).execute(); final Long[] idCounter = { 1L }; ids.forEach(ouId -> {//from w ww . j a va2 s . c o m for (int i = 0; i < new Random().nextInt(100) + 40; i++) { EndUserApplicationRecord record = dsl.newRecord(END_USER_APPLICATION); String name = new StringBuilder().append(randomPick(subjects)).append(" ") .append(randomPick(subjects)).append(" ").append(randomPick(types)).append(" ") .append(randomPick(types)).toString(); record.setName(name); record.setDescription("About the " + name + " End user app"); record.setKind(randomPick(tech)); record.setRiskRating(randomPick(RiskRating.values()).name()); record.setLifecyclePhase(randomPick(LifecyclePhase.values()).name()); record.setOrganisationalUnitId(ouId); record.setId(idCounter[0]++); record.insert(); } }); }
From source file:com.yahoo.labs.samoa.topology.impl.StormTopologySubmitter.java
public static void main(String[] args) throws IOException { Properties props = StormSamoaUtils.getProperties(); String uploadedJarLocation = props.getProperty(StormJarSubmitter.UPLOADED_JAR_LOCATION_KEY); if (uploadedJarLocation == null) { logger.error("Invalid properties file. It must have key {}", StormJarSubmitter.UPLOADED_JAR_LOCATION_KEY); return;/*w w w .ja v a 2s . co m*/ } List<String> tmpArgs = new ArrayList<String>(Arrays.asList(args)); int numWorkers = StormSamoaUtils.numWorkers(tmpArgs); args = tmpArgs.toArray(new String[0]); StormTopology stormTopo = StormSamoaUtils.argsToTopology(args); Config conf = new Config(); conf.putAll(Utils.readStormConfig()); conf.putAll(Utils.readCommandLineOpts()); conf.setDebug(false); conf.setNumWorkers(numWorkers); String profilerOption = props.getProperty(StormTopologySubmitter.YJP_OPTIONS_KEY); if (profilerOption != null) { String topoWorkerChildOpts = (String) conf.get(Config.TOPOLOGY_WORKER_CHILDOPTS); StringBuilder optionBuilder = new StringBuilder(); if (topoWorkerChildOpts != null) { optionBuilder.append(topoWorkerChildOpts); optionBuilder.append(' '); } optionBuilder.append(profilerOption); conf.put(Config.TOPOLOGY_WORKER_CHILDOPTS, optionBuilder.toString()); } Map<String, Object> myConfigMap = new HashMap<String, Object>(conf); StringWriter out = new StringWriter(); try { JSONValue.writeJSONString(myConfigMap, out); } catch (IOException e) { System.out.println("Error in writing JSONString"); e.printStackTrace(); return; } Config config = new Config(); config.putAll(Utils.readStormConfig()); String nimbusHost = (String) config.get(Config.NIMBUS_HOST); NimbusClient nc = new NimbusClient(nimbusHost); String topologyName = stormTopo.getTopologyName(); try { System.out.println("Submitting topology with name: " + topologyName); nc.getClient().submitTopology(topologyName, uploadedJarLocation, out.toString(), stormTopo.getStormBuilder().createTopology()); System.out.println(topologyName + " is successfully submitted"); } catch (AlreadyAliveException aae) { System.out.println("Fail to submit " + topologyName + "\nError message: " + aae.get_msg()); } catch (InvalidTopologyException ite) { System.out.println("Invalid topology for " + topologyName); ite.printStackTrace(); } catch (TException te) { System.out.println("Texception for " + topologyName); te.printStackTrace(); } }
From source file:com.linkedin.pinotdruidbenchmark.DruidThroughput.java
@SuppressWarnings("InfiniteLoopStatement") public static void main(String[] args) throws Exception { if (args.length != 3 && args.length != 4) { System.err.println(/*from ww w . j ava 2s. c o m*/ "3 or 4 arguments required: QUERY_DIR, RESOURCE_URL, NUM_CLIENTS, TEST_TIME (seconds)."); return; } File queryDir = new File(args[0]); String resourceUrl = args[1]; final int numClients = Integer.parseInt(args[2]); final long endTime; if (args.length == 3) { endTime = Long.MAX_VALUE; } else { endTime = System.currentTimeMillis() + Integer.parseInt(args[3]) * MILLIS_PER_SECOND; } File[] queryFiles = queryDir.listFiles(); assert queryFiles != null; Arrays.sort(queryFiles); final int numQueries = queryFiles.length; final HttpPost[] httpPosts = new HttpPost[numQueries]; for (int i = 0; i < numQueries; i++) { HttpPost httpPost = new HttpPost(resourceUrl); httpPost.addHeader("content-type", "application/json"); StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFiles[i]))) { int length; while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) { stringBuilder.append(new String(CHAR_BUFFER, 0, length)); } } String query = stringBuilder.toString(); httpPost.setEntity(new StringEntity(query)); httpPosts[i] = httpPost; } final AtomicInteger counter = new AtomicInteger(0); final AtomicLong totalResponseTime = new AtomicLong(0L); final ExecutorService executorService = Executors.newFixedThreadPool(numClients); for (int i = 0; i < numClients; i++) { executorService.submit(new Runnable() { @Override public void run() { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { while (System.currentTimeMillis() < endTime) { long startTime = System.currentTimeMillis(); CloseableHttpResponse httpResponse = httpClient .execute(httpPosts[RANDOM.nextInt(numQueries)]); httpResponse.close(); long responseTime = System.currentTimeMillis() - startTime; counter.getAndIncrement(); totalResponseTime.getAndAdd(responseTime); } } catch (IOException e) { e.printStackTrace(); } } }); } executorService.shutdown(); long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() < endTime) { Thread.sleep(REPORT_INTERVAL_MILLIS); double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND; int count = counter.get(); double avgResponseTime = ((double) totalResponseTime.get()) / count; System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: " + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms"); } }
From source file:SheetStructure.java
public static void main(String[] args) { HttpURLConnection connection = null; StringBuilder response = new StringBuilder(); //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome //Feel free to use which ever library you prefer. ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String accessToken = "";//Insert your access token here. try {//from w ww . j a v a 2 s . com System.out.println("Starting HelloSmartsheet2: Betty's Bake Sale..."); //First Create a new sheet. String sheetName = "Betty's Bake Sale"; //We will be using POJOs to represent the REST request objects. We will convert these to and from JSON using Jackson JSON. //Their structure directly relates to the JSON that gets passed through the API. //Note that these POJOs are included as static inner classes to keep this to one file. Normally they would be broken out. Sheet newSheet = new Sheet(); newSheet.setName(sheetName); newSheet.setColumns(Arrays.asList(new Column("Baked Goods", "TEXT_NUMBER", null, true, null), new Column("Baker", "CONTACT_LIST", null, null, null), new Column("Price Per Item", "TEXT_NUMBER", null, null, null), new Column("Gluten Free?", "CHECKBOX", "FLAG", null, null), new Column("Status", "PICKLIST", null, null, Arrays.asList("Started", "Finished", "Delivered")))); connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); Result<Sheet> newSheetResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); newSheet = newSheetResult.getResult(); System.out.println("Sheet " + newSheet.getName() + " created, id: " + newSheet.getId()); //Now add a column: String columnName = "Delivery Date"; System.out.println("Adding column " + columnName + " to " + sheetName); Column newColumn = new Column(columnName, "DATE", 5); connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newColumn); Result<Column> newColumnResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Column>>() { }); System.out.println( "Column " + newColumnResult.getResult().getTitle() + " added to " + newSheet.getName()); //Next, we will get the list of Columns from the API. We could figure this out based on what the server has returned in the result, but we'll just ask the API for it. System.out.println("Fetching " + newSheet.getName() + " sheet columns..."); connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); List<Column> allColumns = mapper.readValue(connection.getInputStream(), new TypeReference<List<Column>>() { }); System.out.println("Fetched."); //Now we will be adding rows System.out.println("Inserting rows into " + newSheet.getName()); List<Row> rows = new ArrayList<Row>(); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Brownies"), new Cell(allColumns.get(1).id, "julieann@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Finished")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Snickerdoodles"), new Cell(allColumns.get(1).id, "stevenelson@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"), new Cell(allColumns.get(5).id, "2013-09-04")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Rice Krispy Treats"), new Cell(allColumns.get(1).id, "rickthames@example.com"), new Cell(allColumns.get(2).id, "$.50"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Started")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Muffins"), new Cell(allColumns.get(1).id, "sandrassmart@example.com"), new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Finished")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Chocolate Chip Cookies"), new Cell(allColumns.get(1).id, "janedaniels@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"), new Cell(allColumns.get(5).id, "2013-09-05")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Ginger Snaps"), new Cell(allColumns.get(1).id, "nedbarnes@example.com"), new Cell(allColumns.get(2).id, "$.50"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Unknown", false)))); //Note that this one is strict=false. This is because "Unknown" was not one of the original options when the column was created. RowWrapper rowWrapper = new RowWrapper(); rowWrapper.setToBottom(true); rowWrapper.setRows(rows); connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), rowWrapper); Result<List<Row>> newRowsResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Added " + newRowsResult.getResult().size() + " rows to " + newSheet.getName()); //Move a row to the top. System.out.println("Moving row 6 to the top."); RowWrapper moveToTop = new RowWrapper(); moveToTop.setToTop(true); connection = (HttpURLConnection) new URL( ROW_URL.replace(ID, "" + newRowsResult.getResult().get(5).getId())).openConnection(); connection.setRequestMethod("PUT"); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), moveToTop); mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Row 6 moved to top."); //Insert empty rows for spacing rows = new ArrayList<Row>(); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Delivered")))); rowWrapper = new RowWrapper(); rowWrapper.setToBottom(true); rowWrapper.setRows(rows); connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), rowWrapper); Result<List<Row>> spacerRowsResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Added " + spacerRowsResult.getResult().size() + " rows to " + newSheet.getName()); //Move Delivered rows to be children of the last spacer row. System.out.println("Moving delivered rows to Delivered section..."); Long[] deliveredRowIds = new Long[] { newRowsResult.result.get(1).getId(), newRowsResult.result.get(4).getId() }; RowWrapper parentRowLocation = new RowWrapper(); parentRowLocation.setParentId(spacerRowsResult.getResult().get(1).getId()); for (Long deliveredId : deliveredRowIds) { System.out.println("Moving " + deliveredId + " to Delivered."); connection = (HttpURLConnection) new URL(ROW_URL.replace(ID, "" + deliveredId)).openConnection(); connection.setRequestMethod("PUT"); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), parentRowLocation); mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Row id " + deliveredId + " moved."); } System.out.println("Appending additional rows to items in progress..."); List<Row> siblingRows = new ArrayList<Row>(); siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Scones"), new Cell(allColumns.get(1).id, "tomlively@example.com"), new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Finished")))); siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Lemon Bars"), new Cell(allColumns.get(1).id, "rickthames@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Started")))); rowWrapper = new RowWrapper(); rowWrapper.setSiblingId(newRowsResult.getResult().get(3).getId()); rowWrapper.setRows(siblingRows); connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), rowWrapper); Result<List<Row>> siblingRowsResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Added " + siblingRowsResult.getResult().size() + " rows to " + newSheet.getName()); System.out.println("Moving Status column to index 1..."); Column statusColumn = allColumns.get(4); Column moveColumn = new Column(); moveColumn.setIndex(1); moveColumn.setTitle(statusColumn.title); moveColumn.setSheetId(newSheet.getId()); moveColumn.setType(statusColumn.getType()); connection = (HttpURLConnection) new URL(COLUMN_URL.replace(ID, "" + statusColumn.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); connection.setRequestMethod("PUT"); mapper.writeValue(connection.getOutputStream(), moveColumn); Result<Column> movedColumnResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Column>>() { }); System.out.println("Moved column " + movedColumnResult.getResult().getId()); System.out.println("Completed Hellosmartsheet2: Betty's Bake Sale."); } catch (IOException e) { InputStream is = ((HttpURLConnection) connection).getErrorStream(); if (is != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; try { response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); Result<?> result = mapper.readValue(response.toString(), Result.class); System.err.println(result.message); } catch (IOException e1) { e1.printStackTrace(); } } e.printStackTrace(); } catch (Exception e) { System.out.println("Something broke: " + e.getMessage()); e.printStackTrace(); } }
From source file:ca.uqac.info.trace.TraceGenerator.java
public static void main(String[] args) { // Parse command line arguments Options options = setupOptions();//from www .ja v a2 s . com CommandLine c_line = setupCommandLine(args, options); int verbosity = 0, max_events = 1000000; if (c_line.hasOption("h")) { showUsage(options); System.exit(ERR_OK); } String generator_name = "simplerandom"; if (c_line.hasOption("g")) { generator_name = c_line.getOptionValue("generator"); } long time_per_msg = 1000; if (c_line.hasOption("i")) { time_per_msg = Integer.parseInt(c_line.getOptionValue("i")); } if (c_line.hasOption("verbosity")) { verbosity = Integer.parseInt(c_line.getOptionValue("verbosity")); } if (c_line.hasOption("e")) { max_events = Integer.parseInt(c_line.getOptionValue("e")); } String feeder_params = ""; if (c_line.hasOption("parameters")) { feeder_params = c_line.getOptionValue("parameters"); } MessageFeeder mf = instantiateFeeder(generator_name, feeder_params); if (mf == null) { System.err.println("Unrecognized feeder name"); System.exit(ERR_ARGUMENTS); } // Trap Ctrl-C to send EOT before shutting down Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { char EOT = 4; System.out.print(EOT); } }); for (int num_events = 0; mf.hasNext() && num_events < max_events; num_events++) { long time_begin = System.nanoTime(); String message = mf.next(); StringBuilder out = new StringBuilder(); out.append(message); System.out.print(out.toString()); long time_end = System.nanoTime(); long duration = time_per_msg - (long) ((time_end - time_begin) / 1000000f); if (duration > 0) { try { Thread.sleep(duration); } catch (InterruptedException e) { } } if (verbosity > 0) { System.err.print("\r" + num_events + " " + duration + "/" + time_per_msg); } } }
From source file:com.bolingcavalry.StreamingJob.java
public static void main(String[] args) throws Exception { // ?/* ww w . j a v a2 s . c o m*/ final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.addSource(new WikipediaEditsSource()) //??key .keyBy((KeySelector<WikipediaEditEvent, String>) wikipediaEditEvent -> wikipediaEditEvent.getUser()) //?5 .timeWindow(Time.seconds(15)) //?key???? .aggregate( new AggregateFunction<WikipediaEditEvent, Tuple3<String, Integer, StringBuilder>, Tuple3<String, Integer, StringBuilder>>() { @Override public Tuple3<String, Integer, StringBuilder> createAccumulator() { //ACC return new Tuple3<>("", 0, new StringBuilder()); } @Override public Tuple3<String, Integer, StringBuilder> add(WikipediaEditEvent wikipediaEditEvent, Tuple3<String, Integer, StringBuilder> tuple3) { StringBuilder sbud = tuple3.f2; //?"Details "? //?? if (StringUtils.isBlank(sbud.toString())) { sbud.append("Details : "); } else { sbud.append(" "); } //?? return new Tuple3<>(wikipediaEditEvent.getUser(), wikipediaEditEvent.getByteDiff() + tuple3.f1, sbud.append(wikipediaEditEvent.getByteDiff())); } @Override public Tuple3<String, Integer, StringBuilder> getResult( Tuple3<String, Integer, StringBuilder> tuple3) { return tuple3; } @Override public Tuple3<String, Integer, StringBuilder> merge( Tuple3<String, Integer, StringBuilder> tuple3, Tuple3<String, Integer, StringBuilder> acc1) { //??? return new Tuple3<>(tuple3.f0, tuple3.f1 + acc1.f1, tuple3.f2.append(acc1.f2)); } }) //?????key??? .map((MapFunction<Tuple3<String, Integer, StringBuilder>, String>) tuple3 -> tuple3.toString()) //?STDOUT .print(); // env.execute("Flink Streaming Java API Skeleton"); }
From source file:org.openeclass.EclassMobile.java
public static void main(String[] args) { try {/*from w w w .j a va 2 s . co m*/ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://myeclass/modules/mobile/mlogin.php"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("uname", mUsername)); nvps.add(new BasicNameValuePair("pass", mPassword)); httppost.setEntity(new UrlEncodedFormEntity(nvps)); System.out.println("twra tha kanei add"); System.out.println("prin to response"); HttpResponse response = httpclient.execute(httppost); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) System.out.println("Invalid response from server: " + status.toString()); System.out.println("meta to response"); Header[] head = response.getAllHeaders(); for (int i = 0; i < head.length; i++) System.out.println("to head exei " + head[i]); System.out.println("Login form get: " + response.getStatusLine()); HttpEntity entity = response.getEntity(); InputStream ips = entity.getContent(); BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8"), 1024); StringBuilder sb = new StringBuilder(); String s = ""; while ((s = buf.readLine()) != null) { sb.append(s); } System.out.println("to sb einai " + sb.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.datastax.sparql.ConsoleCompiler.java
public static void main(final String[] args) throws IOException { //args = "/examples/modern1.sparql"; final Options options = new Options(); options.addOption("f", "file", true, "a file that contains a SPARQL query"); options.addOption("g", "graph", true, "the graph that's used to execute the query [classic|modern|crew|kryo file]"); // TODO: add an OLAP option (perhaps: "--olap spark"?) final CommandLineParser parser = new DefaultParser(); final CommandLine commandLine; try {// ww w . j ava2 s . c o m commandLine = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); printHelp(1); return; } final InputStream inputStream = commandLine.hasOption("file") ? new FileInputStream(commandLine.getOptionValue("file")) : System.in; final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); final StringBuilder queryBuilder = new StringBuilder(); if (!reader.ready()) { printHelp(1); } String line; while (null != (line = reader.readLine())) { queryBuilder.append(System.lineSeparator()).append(line); } final String queryString = queryBuilder.toString(); final Graph graph; if (commandLine.hasOption("graph")) { switch (commandLine.getOptionValue("graph").toLowerCase()) { case "classic": graph = TinkerFactory.createClassic(); break; case "modern": graph = TinkerFactory.createModern(); System.out.println("Modern Graph Created"); break; case "crew": graph = TinkerFactory.createTheCrew(); break; default: graph = TinkerGraph.open(); System.out.println("Graph Created"); long startTime = System.nanoTime(); graph.io(IoCore.gryo()).readGraph(commandLine.getOptionValue("graph")); long endTime = System.nanoTime(); System.out.println("Time taken to load graph from kyro file: " + (endTime - startTime) / 1000000 + " mili seconds"); break; } } else { graph = TinkerFactory.createModern(); } final Traversal<Vertex, ?> traversal = SparqlToGremlinCompiler.convertToGremlinTraversal(graph, queryString); printWithHeadline("SPARQL Query", queryString); printWithHeadline("Traversal (prior execution)", traversal); Bytecode traversalByteCode = traversal.asAdmin().getBytecode(); //JavaTranslator.of(graph.traversal()).translate(traversalByteCode); System.out.println("the Byte Code : " + traversalByteCode.toString()); printWithHeadline("Result", String.join(System.lineSeparator(), JavaTranslator.of(graph.traversal()) .translate(traversalByteCode).toStream().map(Object::toString).collect(Collectors.toList()))); printWithHeadline("Traversal (after execution)", traversal); }
From source file:Pong.java
public static void main(String... args) throws Exception { System.setProperty("os.max.pid.bits", "16"); Options options = new Options(); options.addOption("i", true, "Input chronicle path"); options.addOption("n", true, "Number of entries to write"); options.addOption("w", true, "Number of writer threads"); options.addOption("r", true, "Number of reader threads"); options.addOption("x", false, "Delete the output chronicle at startup"); CommandLine cmd = new DefaultParser().parse(options, args); final Path output = Paths.get(cmd.getOptionValue("o", "/tmp/__test/chr")); final long maxCount = Long.parseLong(cmd.getOptionValue("n", "10000000")); final int writerThreadCount = Integer.parseInt(cmd.getOptionValue("w", "4")); final int readerThreadCount = Integer.parseInt(cmd.getOptionValue("r", "4")); final boolean deleteOnStartup = cmd.hasOption("x"); if (deleteOnStartup) { FileUtil.removeRecursive(output); }//from w w w . j av a 2 s .c o m final Chronicle chr = ChronicleQueueBuilder.vanilla(output.toFile()).build(); final ExecutorService executor = Executors.newFixedThreadPool(4); final List<Future<?>> futures = new ArrayList<>(); final long totalCount = writerThreadCount * maxCount; final long t0 = System.nanoTime(); for (int i = 0; i != readerThreadCount; ++i) { final int tid = i; futures.add(executor.submit((Runnable) () -> { try { IntLongMap counts = HashIntLongMaps.newMutableMap(); ExcerptTailer tailer = chr.createTailer(); final StringBuilder sb1 = new StringBuilder(); final StringBuilder sb2 = new StringBuilder(); long count = 0; while (count != totalCount) { if (!tailer.nextIndex()) continue; final int id = tailer.readInt(); final long val = tailer.readStopBit(); final long longValue = tailer.readLong(); sb1.setLength(0); sb2.setLength(0); tailer.read8bitText(sb1); tailer.read8bitText(sb2); if (counts.addValue(id, 1) - 1 != val || longValue != 0x0badcafedeadbeefL || !StringInterner.isEqual("FooBar", sb1) || !StringInterner.isEqual("AnotherFooBar", sb2)) { System.out.println("Unexpected value " + id + ", " + val + ", " + Long.toHexString(longValue) + ", " + sb1.toString() + ", " + sb2.toString()); return; } ++count; if (count % 1_000_000 == 0) { long t1 = System.nanoTime(); System.out.println(tid + " " + (t1 - t0) / 1e6 + " ms"); } } } catch (IOException e) { e.printStackTrace(); } })); } for (Future f : futures) { f.get(); } executor.shutdownNow(); final long t1 = System.nanoTime(); System.out.println("Done. Rough time=" + (t1 - t0) / 1e6 + " ms"); }