id
stringlengths
36
36
text
stringlengths
1
1.25M
4a7a8c68-8eab-4d45-9aaa-f717864f1a18
public void rollDice(boolean newRound) { int xPadding = (dimX-(DIE_SIZE*5))/6;//padding distance, total width minus total dice widths, all divided by 6 (# paddings required- 4 in between dice and 2 on ends.) int xEndPadd = (dimX%5)/2; //create and store DieFaces for(int i = 1; i <= 5; i++) { // reroll the highlighted dice if not a new round roll if (!newRound) { if (dice[i-1].highlighted) { continue; //is highlighted, so keeping die and moving to next } } //store die coords dieCoords[i-1][0] = (i==1?xEndPadd:0)+DIE_SIZE*(i-1)+(xPadding<0?0:xPadding*i);//last part is incase window is too small, which will make padding negative and dice overlapping, this will prevent it. dieCoords[i-1][1] = dieY_coord; random = generator.nextInt(6)+1; //create actual die object switch(random) { case 1: dice[i-1] = new Die1(dieCoords[i-1][0],dieCoords[i-1][1], false); break; case 2: dice[i-1] = new Die2(dieCoords[i-1][0],dieCoords[i-1][1], false); break; case 3: dice[i-1] = new Die3(dieCoords[i-1][0],dieCoords[i-1][1], false); break; case 4: dice[i-1] = new Die4(dieCoords[i-1][0],dieCoords[i-1][1], false); break; case 5: dice[i-1] = new Die5(dieCoords[i-1][0],dieCoords[i-1][1], false); break; case 6: dice[i-1] = new Die6(dieCoords[i-1][0],dieCoords[i-1][1], false); break; } } repaint(); }
8ce9ee8a-a2c4-4899-b91f-244e415cee2c
public int[] highlightDie(int eX, int eY, boolean hover) { int dieX, dieY; for(int i = 0; i < 5; i++) { dieX = this.dieCoords[i][0]; dieY = this.dieCoords[i][1]; if ( eX >= dieX && eX <= dieX+DIE_SIZE && eY >= dieY && eY <= dieY+DIE_SIZE ) { if (hover) { dice[i].highlightHover(true); int[] returnArray = {dieX, dieY}; repaint(); //return coords of die location to use in listener class as a way of knowing which die is currently highlighted return returnArray; } else { dice[i].highlight(); repaint(); } } } return null; }
a8b9e82a-3db3-4d88-aacc-4f4458f81a1b
public void diceHighlightHoverOff() { for(int i = 0; i < 5; i++) dice[i].highlightHover(false); repaint(); }
19ce34ca-0106-4a5e-896d-33d2be69dcd1
public Die[] getDieArray() { return dice; }
f89f7f75-cf73-4419-9b06-4f1b6c233063
public static void redirect(String out, String err){ //PrintStream sysout=System.out; //PrintStream syserr=System.err; File stdout=new File(out); File stderr=new File(err); try { System.setOut(new PrintStream(new FileOutputStream(stdout))); System.setErr(new PrintStream(new FileOutputStream(stderr))); } catch (FileNotFoundException e) { e.printStackTrace(); } }
dad3542d-905c-4c58-9359-689bf5444adb
public static File findSiblingResource(Class<?> cls, String FileName) { String path = null; try { //如果不用toURI,当文件路径中有空格时,以下方法就会出错,因为getResource返回的URL会把空格转化成 %20 URL url=cls.getResource(FileName); path = url.toURI().getPath(); } catch (URISyntaxException e) { e.printStackTrace(); } File file = new File(path); return file; }
474b0d0a-174a-404f-800f-03a59d5a9412
public static File findRootResource(Class<?> cls, String FileName) { String path = null; try { //如果不用toURI,当文件路径中有空格时,以下方法就会出错,因为getResource返回的URL会把空格转化成 %20 URL url=cls.getClassLoader().getResource(FileName); path = url.toURI().getPath(); } catch (URISyntaxException e) { e.printStackTrace(); } File file = new File(path); return file; }
75383cdb-2f84-4392-bdbd-8ac5347c44fc
public static String readFile(File f, Charset encoding) { String path = f.getAbsolutePath(); byte[] encoded = null; try { encoded = Files.readAllBytes(Paths.get(path)); } catch (IOException e) { e.printStackTrace(); } String content = encoding.decode(ByteBuffer.wrap(encoded)).toString(); Msg.userMsgLn("你的SQL是: \n" + content); return content; }
fcdc402a-240b-4110-bd51-d514682e7bb8
public static SqlResults compactSQLFromFile(File f) { Scanner sc = null; SqlResults sqlResults = new SqlResults(); try { sc = new Scanner(f); } catch (FileNotFoundException e) { e.printStackTrace(); } while (sc.hasNextLine()) { String l = sc.nextLine().trim(); // ignore comments and empty line if (l.startsWith("--") || l.isEmpty()) { continue; } sqlResults.compat.append(l + " "); sqlResults.full.append(l + "\n"); } sc.close(); return sqlResults; }
b31fc6fd-9ea3-4736-96f4-95220dd1b952
public static void debugMsg(Class<?> c, String msg) { if (Context.DEBUG_MSG) { System.out.printf("DEBUG: [%-20s] %s\n", c, msg); } }
aea701a2-ed09-4f1a-9946-6be859bc76f7
public static void debugSep() { if (Context.DEBUG_MSG) System.out.println("DEBUG: *********************************************"); }
78a2ad1d-dfbc-430a-8cf5-8e5cda9f43c3
public static void userMsgLn(String msg) { if (Context.USER_MSG) { System.out.println(msg); } }
c10a0155-5638-487b-b50e-18dc061a59ee
public static void userMsgF(String format, Object... args) { if (Context.USER_MSG) { System.out.printf(format, args); } }
32108e6f-ed57-4c08-afba-e8f462da9606
public static void userSep(int numberOfColumns, char chr) { if (Context.USER_MSG) for (int i = 0; i < 21 * numberOfColumns; i++) { System.out.print(chr); } System.out.println(); }
9fd17f8c-95e1-4bc6-a184-a54af405393d
private SQL() { }
c44b8fe7-047a-4d1b-a7f6-1cc9faee9760
public static String produceMius(String userInput, String answer) { userInput = userInput.replaceAll(";", ""); String selectList = SQL.getSelectList(answer); Msg.debugMsg(SQL.class, "User Input sql is: " + userInput); Msg.debugMsg(SQL.class, "select list is: " + selectList); String newSQL = null; if (userInput.toLowerCase().contains("where")) { // this is when user input is "select * from * where *" newSQL = answer + " and " + selectList + " not in (" + userInput + ");"; } else { // this is when user input is "select * from *" newSQL = answer + " where " + selectList + " not in (" + userInput + ");"; } Msg.debugMsg(SQL.class, "Set Minus sql is: " + newSQL); return newSQL; }
885465d6-38dc-4efe-a6b7-f9967d5d6f99
public static String getSelectList(String SQL) { // 这个变量如果是全局变量,就会影响到第一个JUnit测试后面的测试 // 这就是为什么JUnit测试单独测试都可以 // 但是一放到一起就不行了 boolean start = false; Scanner sc = new Scanner(SQL); ArrayList<String> selectList = new ArrayList<String>(); String str = null; while (sc.hasNext()) { str = sc.next().replaceAll(",$", "").trim(); //Msg.debugMsg(SQL.class, "str=" + str + "]"); if (!start) { if (str.equals("select")) { start = true; } continue; } if (str.equals("from")) { break; } //Msg.debugMsg(SQL.class, "add[" + str + "]"); selectList.add(str); } sc.close(); String result = selectList.toString().replace('[', '(').replace(']', ')'); return result; }
5db72695-8f7d-48eb-9356-c5b216dd667b
public static String findAnwer(String qNum) { Properties prop = new Properties(); String answer = null; try { //load a properties file prop.load(new FileInputStream(FileIO.findSiblingResource(SQL.class, "Answers"))); answer = prop.getProperty(qNum); } catch (IOException ex) { ex.printStackTrace(); } Msg.debugMsg(SQL.class, "Answer found is: " + answer); return answer; }
4f66a066-b1cf-47f2-8c5d-5e57d1812475
public C3P0(String Driver, String URL, String user, String pass, String cleanUp) { this.cleanUPSQL = cleanUp; try { Class.forName(Driver); logger.debug("Driver loaded"); connectionPool = new ComboPooledDataSource(); connectionPool.setDriverClass(Driver); //loads the jdbc driver } catch (Exception e) { e.printStackTrace(); } connectionPool.setJdbcUrl(URL); connectionPool.setUser(user); connectionPool.setPassword(pass); // the settings below are optional -- c3p0 can work with defaults connectionPool.setMinPoolSize(5); connectionPool.setAcquireIncrement(5); connectionPool.setMaxPoolSize(20); }
8231a05d-277f-4d6c-af10-1b9586041981
public void shutdown() { try { cleanUP(connectionPool.getConnection(), cleanUPSQL, FileIO.findRootResource(C3P0.class, "dropDB.sql")); connectionPool.close(); } catch (SQLException e) { e.printStackTrace(); } }
9965ea8b-db2d-4981-8ce6-b38eedb03015
public void update(String expression) { try { update(connectionPool.getConnection(), expression, null); } catch (SQLException e) { e.printStackTrace(); } }
947992ff-59d2-4d7d-88a2-18e1f2ef78cb
public void batchUpdate(File f) { try { update(connectionPool.getConnection(), null, f); } catch (SQLException e) { e.printStackTrace(); } }
a73ce7f5-ad48-4f80-b539-d7d470ca1257
public boolean query(String sql, boolean showResult) { boolean result = false; try { result = query(connectionPool.getConnection(), sql, showResult); } catch (SQLException e) { e.printStackTrace(); } return result; }
5276ebb6-ec69-4dd9-aedf-586ae6fe25e2
public NOPOOL(String driver, String URL, String user, String pass, String cleanUp) { this.URL = URL; this.user = user; this.pass = pass; this.cleanUp = cleanUp; try { Class.forName(driver); } catch (Exception e) { e.printStackTrace(); } }
0350e1a7-ffb5-4ae7-b24d-90d3369a31e6
public void shutdown() { try { cleanUP(DriverManager.getConnection(URL, user, pass), cleanUp, FileIO.findRootResource(BONECP.class, "dropDB.sql")); } catch (SQLException e) { e.printStackTrace(); } }
6a1710b1-ecce-4a9f-9df8-4263eab85419
public boolean query(String sql, boolean showResult) { boolean result = false; try { result = query(DriverManager.getConnection(URL, user, pass), sql, showResult); } catch (SQLException e) { e.printStackTrace(); } return result; }
1cbf68a7-969b-4c22-8106-4a86f35ad2df
public void update(String expression) { try { update(DriverManager.getConnection(URL, user, pass), expression, null); } catch (SQLException e) { e.printStackTrace(); } }
2f03e38c-c064-44d1-a4ab-b68c344528b9
public void batchUpdate(File f) { try { update(DriverManager.getConnection(URL, user, pass), null, f); } catch (SQLException e) { e.printStackTrace(); } }
a6a289cb-2904-474c-abdf-acb07a9770a4
public BONECP(String Driver, String URL, String user, String pass, String cleanUp) { this.cleanUPSQL = cleanUp; try { Class.forName(Driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } BoneCPConfig config = new BoneCPConfig(); config.setJdbcUrl(URL); config.setUsername(user); config.setPassword(pass); config.setCloseConnectionWatch(true); //config.setMinConnectionsPerPartition(5); //config.setMaxConnectionsPerPartition(10); config.setPartitionCount(1); try { connectionPool = new BoneCP(config); } catch (SQLException e) { e.printStackTrace(); } }
9244d083-7f10-4ace-aab2-6ffe3a63667b
public void shutdown() { try { cleanUP(connectionPool.getConnection(), cleanUPSQL, FileIO.findRootResource(BONECP.class, "dropDB.sql")); connectionPool.shutdown(); } catch (SQLException e) { e.printStackTrace(); } }
5180388b-4862-498e-a3a5-29e30b27eae9
public void update(String expression) { try { update(connectionPool.getConnection(), expression, null); } catch (SQLException e) { e.printStackTrace(); } }
a9bd03c3-a9f8-469b-b1b6-5a2be89f3fb1
public void batchUpdate(File f) { try { update(connectionPool.getConnection(), null, f); } catch (SQLException e) { e.printStackTrace(); } }
d5de21e9-9f82-4903-94e6-e4c1bf5b1d40
public boolean query(String sql, boolean showResult) { boolean result = false; try { result = query(connectionPool.getConnection(), sql, showResult); } catch (SQLException e) { e.printStackTrace(); } return result; }
e0e3b062-1399-4679-9d52-ae7c31e01bf0
public DBCP(String driver, String url, String user, String pass, String cleanUp) { try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } Properties dbcpProperties = new Properties(); dbcpProperties.put("url", url); dbcpProperties.put("username", user); dbcpProperties.put("password", pass); try { connectionPool = (BasicDataSource) BasicDataSourceFactory.createDataSource(dbcpProperties); } catch (Exception e) { e.printStackTrace(); } this.cleanUpSQL = cleanUp; }
425309df-3896-4b97-9496-b09458a4133b
public void shutdown() { try { cleanUP(connectionPool.getConnection(),cleanUpSQL, FileIO.findRootResource(BONECP.class, "dropDB.sql")); } catch (SQLException e) { e.printStackTrace(); } }
caedd6f7-6f0e-4893-a562-145aa04e0f1f
public void update(String expression) { try { update(connectionPool.getConnection(), expression, null); } catch (SQLException e) { e.printStackTrace(); } }
8dc1dcc9-141b-44b4-b490-4ab011e0be34
public void batchUpdate(File f) { try { update(connectionPool.getConnection(), null, f); } catch (SQLException e) { e.printStackTrace(); } }
29b4e150-860d-4286-91fd-ffdaa02d8432
public boolean query(String sql, boolean showResult) { boolean result = false; try { result = query(connectionPool.getConnection(), sql, showResult); } catch (SQLException e) { e.printStackTrace(); } return result; }
8dc5814c-ef43-47a6-8c89-7e26ad17e060
protected DB() {}
265f1ca1-4b24-49ba-840c-bfe392d48544
public void cleanUP(Connection conn, String sql, File f) { logger.info("clean SQL: " + sql); logger.info("clean file:" + f); update(conn, sql, f); }
dfdb786a-b85b-44d9-9ef7-b0c8628fb0ff
public void update(Connection conn, String sql, File f) { Statement st = null; Scanner sc = null; try { conn.setAutoCommit(false); st = conn.createStatement(); // statements if (f != null && f.isFile()) { sc = new Scanner(f); StringBuilder sqlBuilder = new StringBuilder(); while (sc.hasNextLine()) { String sqlLine = sc.nextLine().trim(); if (sqlLine.startsWith("--")) { continue; } sqlBuilder.append(sqlLine + ' '); if (!sqlLine.contains(";")) { continue; } String finalSQL = sqlBuilder.toString(); st.addBatch(finalSQL); sqlBuilder = new StringBuilder(); } } if (sql != null && !sql.isEmpty()) { st.addBatch(sql); } logger.debug("START BATCH UPDATE"); st.executeBatch(); conn.commit(); //set it back to true so that MySQL+BoneCP doesn't hang at "executeBatch()" //the 2nd time this method is called conn.setAutoCommit(true); } catch (Exception e) { e.printStackTrace(); } finally { try { if (sc != null) { sc.close(); } logger.debug("Closed Scanner"); if (st != null) { st.close(); } logger.debug("Closed Statement"); if (conn != null) { conn.close(); } conn = null; logger.debug("Closed Connection"); } catch (Exception e) { e.printStackTrace(); } } }
d162bebe-7303-4259-8892-61181030cab7
public boolean query(Connection conn, String sql, boolean showResult) { Statement st = null; ResultSet rs = null; boolean hasContent = false; try { st = conn.createStatement(); rs = st.executeQuery(sql); hasContent = !rs.isBeforeFirst(); if (showResult) { showResultSetContent(rs); } return hasContent; } catch (SQLException e) { e.printStackTrace(); } finally { try { if (st != null) { st.close(); } if (rs != null) { rs.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } return hasContent; }
528f82af-37f8-4e81-9693-09ab9c432560
private void showResultSetContent(ResultSet rs) throws SQLException { ResultSetMetaData rsMetaData = rs.getMetaData(); int numberOfColumns = rsMetaData.getColumnCount(); Msg.userMsgLn("你的SQL的结果是:"); Msg.userSep(numberOfColumns, '-'); for (int i = 1; i <= numberOfColumns; i++) { String name = rsMetaData.getColumnName(i); Msg.userMsgF("%-20s|", name); } Msg.userMsgLn(""); Msg.userSep(numberOfColumns, '-'); while (rs.next()) { for (int i = 0; i < numberOfColumns; i++) { Msg.userMsgF("%-20s|", rs.getObject(i + 1)); } Msg.userMsgLn(""); } Msg.userSep(numberOfColumns, '-'); }
0485e43e-1f2d-4566-b2b4-21a060961d09
public boolean query(String sql, boolean ShowResult);
14b256c1-1c29-4bb2-8097-30ee954bdba0
public void shutdown();
0538fa08-80e4-48fb-8b0a-0a755a5864e0
public void update(String sql);
4702389a-b709-4347-adf6-c3c606de34f0
public void batchUpdate(File file);
7ea46fc4-b9ca-4831-8a51-e6689f1ac888
public static DBFrameWork getMyDB() { return myDB; }
581476c3-c9ef-4e6b-9da9-6a2372f31074
public boolean testSQL(int sqlFileNumber) { try { Thread.sleep(Context.INTERVAL_JUNIT); } catch (InterruptedException e) { e.printStackTrace(); } logger.info("SQL 测试 [" + sqlFileNumber + "]***************"); // get the file name of both user file and squeal practice number File userFile = FileIO.findRootResource(JunitTests.class, sqlFileNumber + ".sql"); SqlResults userSQL = FileIO.compactSQLFromFile(userFile); //get the compact and full version of user input sql String compactSQL = userSQL.compat.toString(); String fullSQL = userSQL.full.toString(); if (compactSQL.trim().isEmpty()) { Msg.userMsgLn("你没有输入任何的SQL, 需要输入SQL才能看到结果"); return false; } Msg.userMsgLn("你输入的SQL是:\n" + fullSQL); try { myDB.query(compactSQL, true); } catch (Exception e) { e.printStackTrace(); } String answer = SQL.findAnwer("sql" + sqlFileNumber); String newSQL = SQL.produceMius(compactSQL, answer); boolean result = false; try { result = myDB.query(newSQL, false); } catch (Exception e) { e.printStackTrace(); } return result; }
adbb889a-278e-4df8-be4f-b6d177ae9281
@BeforeClass public static void initDB() { //CNST.initDB(); }
7415e4f6-4aee-4908-8576-b4991a04a7e7
@AfterClass public static void shutDownDB() { try { myDB.shutdown(); } catch (Exception e) { e.printStackTrace(); } }
cfb7ced2-fb56-4783-ae80-5d4b89d25317
@Test public void testSQL0() { assertTrue(testSQL(0)); }
b6840e1a-1d53-4647-b6d3-b70da035b3e5
@Test public void testSQL1() { assertTrue(testSQL(1)); }
98a6436c-2887-4708-a3b8-dd2e114070eb
@Test public void testSQL2() { assertTrue(testSQL(2)); }
cb8d3f52-4963-4104-849d-a5853ee17e11
@Test public void testSQL3() { assertTrue(testSQL(3)); }
e02496c4-ce7c-45f6-99e5-9bac99afaf26
@Test public void testSQL4() { assertTrue(testSQL(4)); }
9f9e24d0-8d9e-474d-ae1b-c5eb2d686915
@Test public void testSQL5() { assertTrue(testSQL(5)); }
04fde606-7e7d-42f8-b64a-dcc853fe1e35
@Test public void testSQL6() { assertTrue(testSQL(6)); }
66015b45-42a8-4583-9fcc-eadb2180ceda
public static void main(String[] args) { registerShutdownHook(); LogConfiguration.withLogConfiguration(() -> { LOGGER.info("Starting up..."); ZkVmWatcher vmWatcher = new ZkVmWatcher(10000, 1000); Thread vmWatcherThread = new Thread(vmWatcher); vmWatcherThread.setDaemon(true); vmWatcherThread.start(); synchronized (shutdownLock) { while (!shutdown) { try { shutdownLock.wait(100); } catch (InterruptedException e) { } } } LOGGER.info("Shutting down..."); vmWatcher.shutdown(); try { vmWatcherThread.join(100); } catch (InterruptedException e) { } LOGGER.info("Shutdown complete"); }); }
50269db6-d1a5-41ef-b6b4-a40ecffbe260
private static void registerShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread(() ->{ synchronized (shutdownLock) { shutdown = true; shutdownLock.notifyAll(); } try { Thread.sleep(100); } catch (InterruptedException e) { } })); }
535696c0-0707-4f4d-9da4-537ebdfd6dc5
public void setValue(long value) { this.value = value; }
100d5fdc-ea0a-4855-b036-7d1a3f97f608
@Override public Long getValue() { return value; }
62772f74-3cb9-4ada-92c2-c507bcdf434a
public static void collectMetrics(String prefix, MBeanServerConnection con, MetricsCollection metrics) { collectMemoryPoolMetrics(prefix, con, metrics); collectMemoryMetrics(prefix, con, metrics); collectGCMetrics(prefix, con, metrics); collectThreadMetrics(prefix, con, metrics); collectBufferPoolMetrics(prefix, con, metrics); collectCompilationMetrics(prefix, con, metrics); collectClassLoadingMetrics(prefix, con, metrics); collectOSMetrics(prefix, con, metrics); }
cce29ab0-75d4-438e-b017-e10ae328c532
private static void collectMemoryPoolMetrics(String prefix, MBeanServerConnection con, MetricsCollection metrics) { Set<ObjectName> memoryPoolBeanNames = queryNames(con, "java.lang:type=MemoryPool,name=*", null); memoryPoolBeanNames.forEach(n -> { Map<String, Object> attributes = getBeanAttributes(con, n, "Name", "Usage", "PeakUsage", "CollectionUsage", "UsageThreshold", "UsageThresholdCount", "UsageThresholdSupported", "CollectionUsageThreshold", "CollectionUsageThresholdCount", "CollectionUsageThresholdSupported", "Valid"); if (!attributes.containsKey("Name") || !attributes.containsKey("Valid")) { return; } String poolName = ((String) attributes.get("Name")).replaceAll("\\s", ""); Boolean valid = (Boolean) attributes.get("Valid"); if (!valid) { return; } if (attributes.containsKey("CollectionUsage") && attributes.get("CollectionUsage") != null) { CompositeData collectionUsage = (CompositeData) attributes.get("CollectionUsage"); if (collectionUsage.containsKey("committed")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "collectionUsage.committed")) .setValue((Long) collectionUsage.get("committed")); } if (collectionUsage.containsKey("max")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "collectionUsage.max")) .setValue((Long) collectionUsage.get("max")); } if (collectionUsage.containsKey("init")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "collectionUsage.init")) .setValue((Long) collectionUsage.get("init")); } if (collectionUsage.containsKey("used")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "collectionUsage.used")) .setValue((Long) collectionUsage.get("used")); } } if (attributes.containsKey("PeakUsage") && attributes.get("PeakUsage") != null) { CompositeData collectionUsage = (CompositeData) attributes.get("PeakUsage"); if (collectionUsage.containsKey("committed")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "peakUsage.committed")) .setValue((Long) collectionUsage.get("committed")); } if (collectionUsage.containsKey("max")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "peakUsage.max")) .setValue((Long) collectionUsage.get("max")); } if (collectionUsage.containsKey("init")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "peakUsage.init")) .setValue((Long) collectionUsage.get("init")); } if (collectionUsage.containsKey("used")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "peakUsage.used")) .setValue((Long) collectionUsage.get("used")); } } if (attributes.containsKey("Usage") && attributes.get("Usage") != null) { CompositeData collectionUsage = (CompositeData) attributes.get("Usage"); if (collectionUsage.containsKey("committed")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "usage.committed")) .setValue((Long) collectionUsage.get("committed")); } if (collectionUsage.containsKey("max")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "usage.max")) .setValue((Long) collectionUsage.get("max")); } if (collectionUsage.containsKey("init")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "usage.init")) .setValue((Long) collectionUsage.get("init")); } if (collectionUsage.containsKey("used")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "usage.used")) .setValue((Long) collectionUsage.get("used")); } } if (attributes.containsKey("UsageThresholdSupported") && (Boolean) attributes.get("UsageThresholdSupported")) { if (attributes.containsKey("UsageThreshold")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "usageThreshold")) .setValue((Long) attributes.get("UsageThreshold")); } if (attributes.containsKey("UsageThresholdCount")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "usageThresholdCount")) .setValue((Long) attributes.get("UsageThresholdCount")); } } if (attributes.containsKey("CollectionUsageThresholdSupported") && (Boolean) attributes.get("CollectionUsageThresholdSupported")) { if (attributes.containsKey("CollectionUsageThreshold")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "collectionUsageThreshold")) .setValue((Long) attributes.get("CollectionUsageThreshold")); } if (attributes.containsKey("CollectionUsageThresholdCount")) { metrics.numericGauge(memoryPoolMetricName(prefix, poolName, "collectionUsageThresholdCount")) .setValue((Long) attributes.get("CollectionUsageThresholdCount")); } } }); }
0c48e586-7c63-4c3d-87f0-54b0513ec2d7
private static void collectMemoryMetrics(String prefix, MBeanServerConnection con, MetricsCollection metrics) { Set<ObjectName> memoryBeanNames = queryNames(con, "java.lang:type=Memory", null); if (memoryBeanNames.isEmpty()) { return; } ObjectName name = memoryBeanNames.iterator().next(); Map<String, Object> attributes = getBeanAttributes(con, name, "ObjectPendingFinalizationCount", "HeapMemoryUsage", "NonHeapMemoryUsage"); if (attributes.containsKey("HeapMemoryUsage") && attributes.get("HeapMemoryUsage") != null) { CompositeData heapMemoryUsage = (CompositeData) attributes.get("HeapMemoryUsage"); if (heapMemoryUsage.containsKey("committed")) { metrics.numericGauge(memoryMetricName(prefix, "heap.committed")) .setValue((Long) heapMemoryUsage.get("committed")); } if (heapMemoryUsage.containsKey("init")) { metrics.numericGauge(memoryMetricName(prefix, "heap.init")) .setValue((Long) heapMemoryUsage.get("init")); } if (heapMemoryUsage.containsKey("max")) { metrics.numericGauge(memoryMetricName(prefix, "heap.max")) .setValue((Long) heapMemoryUsage.get("max")); } if (heapMemoryUsage.containsKey("used")) { metrics.numericGauge(memoryMetricName(prefix, "heap.used")) .setValue((Long) heapMemoryUsage.get("used")); } } if (attributes.containsKey("NonHeapMemoryUsage") && attributes.get("NonHeapMemoryUsage") != null) { CompositeData nonHeapMemoryUsage = (CompositeData) attributes.get("NonHeapMemoryUsage"); if (nonHeapMemoryUsage.containsKey("committed")) { metrics.numericGauge(memoryMetricName(prefix, "nonHeap.committed")) .setValue((Long) nonHeapMemoryUsage.get("committed")); } if (nonHeapMemoryUsage.containsKey("init")) { metrics.numericGauge(memoryMetricName(prefix, "nonHeap.init")) .setValue((Long) nonHeapMemoryUsage.get("init")); } if (nonHeapMemoryUsage.containsKey("max")) { metrics.numericGauge(memoryMetricName(prefix, "nonHeap.max")) .setValue((Long) nonHeapMemoryUsage.get("max")); } if (nonHeapMemoryUsage.containsKey("used")) { metrics.numericGauge(memoryMetricName(prefix, "nonHeap.used")) .setValue((Long) nonHeapMemoryUsage.get("used")); } } if (attributes.containsKey("ObjectPendingFinalizationCount")) { metrics.numericGauge(memoryMetricName(prefix, "objectPendingFinalizationCount")) .setValue((Integer) attributes.get("ObjectPendingFinalizationCount")); } }
fc533295-f76d-4d17-9934-e85ef337367c
private static void collectGCMetrics(String prefix, MBeanServerConnection con, MetricsCollection metrics) { Set<ObjectName> gcBeanNames = queryNames(con, "java.lang:type=GarbageCollector,name=*", null); gcBeanNames.forEach(n -> { Map<String, Object> attributes = getBeanAttributes(con, n, "Name", "CollectionCount", "CollectionTime", "Valid"); if (!attributes.containsKey("Name") || !attributes.containsKey("Valid")) { return; } String gcName = ((String) attributes.get("Name")).replaceAll("\\s", ""); Boolean valid = (Boolean) attributes.get("Valid"); if (!valid) { return; } if (attributes.containsKey("CollectionCount")) { metrics.numericGauge(gcMetricName(prefix, gcName, "collectionCount")) .setValue((Long) attributes.get("CollectionCount")); } if (attributes.containsKey("CollectionTime")) { metrics.numericGauge(gcMetricName(prefix, gcName, "collectionTime")) .setValue((Long) attributes.get("CollectionTime")); } }); }
5af553a1-46f9-4deb-9696-4d6256704a58
private static void collectThreadMetrics(String prefix, MBeanServerConnection con, MetricsCollection metrics) { Set<ObjectName> threadingBeanNames = queryNames(con, "java.lang:type=Threading", null); if (threadingBeanNames.isEmpty()) { return; } ObjectName name = threadingBeanNames.iterator().next(); Map<String, Object> attributes = getBeanAttributes(con, name, "ThreadCount", "TotalStartedThreadCount", "PeakThreadCount", "DaemonThreadCount"); if (attributes.containsKey("DaemonThreadCount")) { metrics.numericGauge(threadMetricName(prefix, "daemonThreadCount")) .setValue((Integer) attributes.get("DaemonThreadCount")); } if (attributes.containsKey("PeakThreadCount")) { metrics.numericGauge(threadMetricName(prefix, "peakThreadCount")) .setValue((Integer) attributes.get("PeakThreadCount")); } if (attributes.containsKey("ThreadCount")) { metrics.numericGauge(threadMetricName(prefix, "threadCount")) .setValue((Integer) attributes.get("ThreadCount")); } if (attributes.containsKey("TotalStartedThreadCount")) { metrics.numericGauge(threadMetricName(prefix, "totalStartedThreadCount")) .setValue((Long) attributes.get("TotalStartedThreadCount")); } }
4ed8266b-d1db-49ce-a3eb-2b2aa598ae69
private static void collectBufferPoolMetrics(String prefix, MBeanServerConnection con, MetricsCollection metrics) { Set<ObjectName> booferPoolBeanNames = queryNames(con, "java.nio:type=BufferPool,name=*", null); booferPoolBeanNames.forEach(n -> { Map<String, Object> attributes = getBeanAttributes(con, n, "Name", "Count", "TotalCapacity", "MemoryUsed"); if (!attributes.containsKey("Name")) { return; } String poolName = ((String) attributes.get("Name")).replaceAll("\\s", ""); if (attributes.containsKey("Count")) { metrics.numericGauge(bufferPoolMetricName(prefix, poolName, "count")) .setValue((Long) attributes.get("Count")); } if (attributes.containsKey("TotalCapacity")) { metrics.numericGauge(bufferPoolMetricName(prefix, poolName, "totalCapacity")) .setValue((Long) attributes.get("TotalCapacity")); } if (attributes.containsKey("MemoryUsed")) { metrics.numericGauge(bufferPoolMetricName(prefix, poolName, "memoryUsed")) .setValue((Long) attributes.get("MemoryUsed")); } }); }
657a5cda-a8b8-4c32-8709-1174c1827fe5
private static void collectCompilationMetrics(String prefix, MBeanServerConnection con, MetricsCollection metrics) { Set<ObjectName> compilationBeanNames = queryNames(con, "java.lang:type=Compilation", null); if (compilationBeanNames.isEmpty()) { return; } ObjectName name = compilationBeanNames.iterator().next(); Map<String, Object> attributes = getBeanAttributes(con, name, "TotalCompilationTime"); if (attributes.containsKey("TotalCompilationTime")) { metrics.numericGauge(compilationMetricName(prefix, "totalCompilationTime")) .setValue((Long) attributes.get("TotalCompilationTime")); } }
270e2d72-b8ae-4f56-9da3-051d1208a1ee
private static void collectClassLoadingMetrics(String prefix, MBeanServerConnection con, MetricsCollection metrics) { Set<ObjectName> classLoadingBeanNames = queryNames(con, "java.lang:type=ClassLoading", null); if (classLoadingBeanNames.isEmpty()) { return; } ObjectName name = classLoadingBeanNames.iterator().next(); Map<String, Object> attributes = getBeanAttributes(con, name, "TotalLoadedClassCount", "LoadedClassCount", "UnloadedClassCount"); if (attributes.containsKey("TotalLoadedClassCount")) { metrics.numericGauge(classLoadingMetricName(prefix, "totalLoadedClassCount")) .setValue((Long) attributes.get("TotalLoadedClassCount")); } if (attributes.containsKey("LoadedClassCount")) { metrics.numericGauge(classLoadingMetricName(prefix, "loadedClassCount")) .setValue((Integer) attributes.get("LoadedClassCount")); } if (attributes.containsKey("UnloadedClassCount")) { metrics.numericGauge(classLoadingMetricName(prefix, "unloadedClassCount")) .setValue((Long) attributes.get("UnloadedClassCount")); } }
7883a368-5cb3-4b4d-97b6-7e2cfaa7acf6
private static void collectOSMetrics(String prefix, MBeanServerConnection con, MetricsCollection metrics) { Set<ObjectName> osBeanNames = queryNames(con, "java.lang:type=OperatingSystem", null); if (osBeanNames.isEmpty()) { return; } ObjectName name = osBeanNames.iterator().next(); Map<String, Object> attributes = getBeanAttributes(con, name, "OpenFileDescriptorCount", "MaxFileDescriptorCount", "CommittedVirtualMemorySize", "TotalSwapSpaceSize", "FreeSwapSpaceSize", "ProcessCpuTime", "FreePhysicalMemorySize", "TotalPhysicalMemorySize", "SystemCpuLoad", "ProcessCpuLoad", "SystemLoadAverage"); if (attributes.containsKey("SystemLoadAverage")) { metrics.floatingGauge(osMetricName(prefix, "systemLoadAverage")) .setValue((Double) attributes.get("SystemLoadAverage")); } if (attributes.containsKey("ProcessCpuLoad")) { metrics.floatingGauge(osMetricName(prefix, "processCpuLoad")) .setValue((Double) attributes.get("ProcessCpuLoad")); } if (attributes.containsKey("SystemCpuLoad")) { metrics.floatingGauge(osMetricName(prefix, "systemCpuLoad")) .setValue((Double) attributes.get("SystemCpuLoad")); } if (attributes.containsKey("TotalPhysicalMemorySize")) { metrics.numericGauge(osMetricName(prefix, "totalPhysicalMemorySize")) .setValue((Long) attributes.get("TotalPhysicalMemorySize")); } if (attributes.containsKey("FreePhysicalMemorySize")) { metrics.numericGauge(osMetricName(prefix, "freePhysicalMemorySize")) .setValue((Long) attributes.get("FreePhysicalMemorySize")); } if (attributes.containsKey("ProcessCpuTime")) { metrics.numericGauge(osMetricName(prefix, "processCpuTime")) .setValue((Long) attributes.get("ProcessCpuTime")); } if (attributes.containsKey("FreeSwapSpaceSize")) { metrics.numericGauge(osMetricName(prefix, "freeSwapSpaceSize")) .setValue((Long) attributes.get("FreeSwapSpaceSize")); } if (attributes.containsKey("TotalSwapSpaceSize")) { metrics.numericGauge(osMetricName(prefix, "totalSwapSpaceSize")) .setValue((Long) attributes.get("TotalSwapSpaceSize")); } if (attributes.containsKey("CommittedVirtualMemorySize")) { metrics.numericGauge(osMetricName(prefix, "committedVirtualMemorySize")) .setValue((Long) attributes.get("CommittedVirtualMemorySize")); } if (attributes.containsKey("MaxFileDescriptorCount")) { metrics.numericGauge(osMetricName(prefix, "maxFileDescriptorCount")) .setValue((Long) attributes.get("MaxFileDescriptorCount")); } if (attributes.containsKey("OpenFileDescriptorCount")) { metrics.numericGauge(osMetricName(prefix, "openFileDescriptorCount")) .setValue((Long) attributes.get("OpenFileDescriptorCount")); } }
2fea4a11-4f34-4618-93bb-6e329c2391e9
private static String memoryPoolMetricName(String prefix, String pool, String metric) { return prefix + ".memoryPools." + pool + "." + metric; }
3d981030-a2a7-4152-afd0-d0326a7f3bb7
private static String memoryMetricName(String prefix, String metric) { return prefix + ".memory." + metric; }
af0b7540-baee-4c66-a10c-ff0002ad6ad3
private static String gcMetricName(String prefix, String gc, String metric) { return prefix + ".gc." + gc + "." + metric; }
a450607f-cbc8-46be-9590-1df2df87d54a
private static String threadMetricName(String prefix, String metric) { return prefix + ".thread." + metric; }
c4f29613-ab65-42c8-a40f-4976eef93bbc
private static String bufferPoolMetricName(String prefix, String pool, String metric) { return prefix + ".bufferPools." + pool + "." + metric; }
9ee372d0-0ebc-4f27-8d0c-4208245d9508
private static String compilationMetricName(String prefix, String metric) { return prefix + ".compilation." + metric; }
80e7a08c-6683-4bc3-8612-87c1d0926269
private static String classLoadingMetricName(String prefix, String metric) { return prefix + ".classLoading." + metric; }
f7bb4f76-6c59-49be-b09b-0974aef282e5
private static String osMetricName(String prefix, String metric) { return prefix + ".os." + metric; }
f0cec2a3-f27e-4ac3-9719-572aa6e24b71
public static void collectMetrics(String prefix, MBeanServerConnection con, MetricsCollection metrics) { collectStandaloneServerMetrics(prefix, con, metrics); collectStandaloneServerDataTreeMetrics(prefix, con, metrics); }
bda2da37-5b94-4ce8-94c9-1d113fc6ea32
private static void collectStandaloneServerMetrics(String prefix, MBeanServerConnection con, MetricsCollection metrics) { Set<ObjectName> zkServerBeanNames = queryNames(con, "org.apache.ZooKeeperService:name0=StandaloneServer_port*", Query.isInstanceOf(Query.value("org.apache.zookeeper.server.ZooKeeperServerBean"))); if (zkServerBeanNames.isEmpty()) { return; } ObjectName name = zkServerBeanNames.iterator().next(); Map<String, Object> attributes = getBeanAttributes(con, name, "NumAliveConnections", "OutstandingRequests", "PacketsReceived", "PacketsSent", "MinRequestLatency", "AvgRequestLatency", "MaxRequestLatency"); if (attributes.containsKey("NumAliveConnections")) { metrics.numericGauge(standaloneServerMetricName(prefix, "numAliveConnections")) .setValue((Long) attributes.get("NumAliveConnections")); } if (attributes.containsKey("OutstandingRequests")) { metrics.numericGauge(standaloneServerMetricName(prefix, "outstandingRequests")) .setValue((Long) attributes.get("OutstandingRequests")); } if (attributes.containsKey("PacketsReceived")) { metrics.numericGauge(standaloneServerMetricName(prefix, "packetsReceived")) .setValue((Long) attributes.get("PacketsReceived")); } if (attributes.containsKey("PacketsSent")) { metrics.numericGauge(standaloneServerMetricName(prefix, "packetsSent")) .setValue((Long) attributes.get("PacketsSent")); } if (attributes.containsKey("MinRequestLatency")) { metrics.numericGauge(standaloneServerMetricName(prefix, "minRequestLatency")) .setValue((Long) attributes.get("MinRequestLatency")); } if (attributes.containsKey("AvgRequestLatency")) { metrics.numericGauge(standaloneServerMetricName(prefix, "avgRequestLatency")) .setValue((Long) attributes.get("AvgRequestLatency")); } if (attributes.containsKey("MaxRequestLatency")) { metrics.numericGauge(standaloneServerMetricName(prefix, "maxRequestLatency")) .setValue((Long) attributes.get("MaxRequestLatency")); } }
c94f8a27-7d33-4dc8-8f2b-dbcc3ac2b15f
private static void collectStandaloneServerDataTreeMetrics(String prefix, MBeanServerConnection con, MetricsCollection metrics) { Set<ObjectName> zkDataTreeBeanNames = queryNames(con, "org.apache.ZooKeeperService:name0=StandaloneServer_port*,name1=InMemoryDataTree", Query.isInstanceOf(Query.value("org.apache.zookeeper.server.DataTreeBean"))); if (zkDataTreeBeanNames.isEmpty()) { return; } ObjectName name = zkDataTreeBeanNames.iterator().next(); Map<String, Object> attributes = getBeanAttributes(con, name, "NodeCount", "WatchCount"); if (attributes.containsKey("NodeCount")) { metrics.numericGauge(standaloneServerNodeTreeMetricName(prefix, "nodeCount")) .setValue((Integer) attributes.get("NodeCount")); } if (attributes.containsKey("WatchCount")) { metrics.numericGauge(standaloneServerNodeTreeMetricName(prefix, "watchCount")) .setValue((Integer) attributes.get("WatchCount")); } }
05159fb7-0373-47d9-a496-1bf67d48b577
private static String standaloneServerMetricName(String prefix, String metric) { return prefix + ".zk.standaloneServer." + metric; }
f7f1c203-14e7-4f86-9814-045d5bdae737
private static String standaloneServerNodeTreeMetricName(String prefix, String metric) { return prefix + ".zk.standaloneServer.nodeTree." + metric; }
2fe18fc4-3c4d-4c4e-ba4b-e60fc09e7e75
private MetricsCollection() { }
b72ac7c5-4457-4fa5-ab80-04010280a954
public static void withMetrics(Function1V<MetricsCollection> handler) { MetricsCollection collection = new MetricsCollection(); try { handler.apply(collection); } finally { collection.unregisterAllMetrics(); } }
afa1484d-e507-408a-9eed-01005bbbf445
public Counter counter(String name) { return registeredCounters.computeIfAbsent(name, k -> MetricsRegistryHolder.getRegistry().counter(k)); }
1bb814ff-bbfe-47bc-8bbf-f4eeff1d0d5e
public Histogram histogram(String name) { return registeredHistograms.computeIfAbsent(name, k -> MetricsRegistryHolder.getRegistry().histogram(k)); }
f6b50fe0-4c24-4016-a817-dea1c7c3f6a8
public Meter meter(String name) { return registeredMeters.computeIfAbsent(name, k -> MetricsRegistryHolder.getRegistry().meter(k)); }
ef7327f0-1c93-4930-bf40-5c6d9de79016
public Timer timer(String name) { return registeredTimers.computeIfAbsent(name, k -> MetricsRegistryHolder.getRegistry().timer(k)); }
ba73b480-72b7-42d4-a721-fd8a7fa78aeb
public NumericGauge numericGauge(String name) { return registeredNumericGauges.computeIfAbsent(name, k -> { Gauge gauge = MetricsRegistryHolder.getRegistry().getGauges().get(k); if (gauge instanceof NumericGauge) { return (NumericGauge) gauge; } if (gauge == null) { try { return MetricsRegistryHolder.getRegistry().register(k, new NumericGauge()); } catch (IllegalArgumentException e) { Gauge addedGauge = MetricsRegistryHolder.getRegistry().getGauges().get(k); if (addedGauge instanceof NumericGauge) { return (NumericGauge) addedGauge; } } } throw new IllegalArgumentException(k + " is already used for a different type of metric"); }); }
0d6c5ed7-3a9f-459f-9bde-40ac02437f51
public FloatingGauge floatingGauge(String name) { return registeredFloatingGauges.computeIfAbsent(name, k -> { Gauge gauge = MetricsRegistryHolder.getRegistry().getGauges().get(k); if (gauge instanceof FloatingGauge) { return (FloatingGauge) gauge; } if (gauge == null) { try { return MetricsRegistryHolder.getRegistry().register(k, new FloatingGauge()); } catch (IllegalArgumentException e) { Gauge addedGauge = MetricsRegistryHolder.getRegistry().getGauges().get(k); if (addedGauge instanceof FloatingGauge) { return (FloatingGauge) addedGauge; } } } throw new IllegalArgumentException(k + " is already used for a different type of metric"); }); }
6bcd0db5-3aa9-4ffd-8468-2a9e0378ade1
private void unregisterAllMetrics() { registeredCounters.keySet().forEach(m -> MetricsRegistryHolder.getRegistry().remove(m)); registeredHistograms.keySet().forEach(m -> MetricsRegistryHolder.getRegistry().remove(m)); registeredMeters.keySet().forEach(m -> MetricsRegistryHolder.getRegistry().remove(m)); registeredTimers.keySet().forEach(m -> MetricsRegistryHolder.getRegistry().remove(m)); registeredNumericGauges.keySet().forEach(m -> MetricsRegistryHolder.getRegistry().remove(m)); registeredFloatingGauges.keySet().forEach(m -> MetricsRegistryHolder.getRegistry().remove(m)); }
a514de50-461b-4a6a-a582-906865fa0942
public static MetricRegistry getRegistry() { return metricRegistry; }
6e599990-11b2-48e6-bf37-c58931d1f4b6
public void setValue(double value) { this.value = value; }
8d9eb6d9-d535-4f56-ba9f-726d3e524de3
@Override public Double getValue() { return value; }
a548c6d9-0021-472d-9111-0ec44a5adf79
public static void withLogConfiguration(Function0V body) { setUp(); try { body.apply(); } finally { tearDown(); } }
33f50087-cc81-45cb-b125-aa5466f5422e
private static void setUp() { LoggerContext logCtx = (LoggerContext) LoggerFactory.getILoggerFactory(); PatternLayoutEncoder logEncoder = new PatternLayoutEncoder(); logEncoder.setContext(logCtx); logEncoder.setPattern("%-12date{YYYY-MM-dd HH:mm:ss.SSS} %-5level - %msg%n"); logEncoder.start(); ConsoleAppender<ILoggingEvent> logConsoleAppender = new ConsoleAppender<>(); logConsoleAppender.setContext(logCtx); logConsoleAppender.setName("console"); logConsoleAppender.setEncoder(logEncoder); logConsoleAppender.start(); logEncoder = new PatternLayoutEncoder(); logEncoder.setContext(logCtx); logEncoder.setPattern("%-12date{YYYY-MM-dd HH:mm:ss.SSS} %-5level - %msg%n"); logEncoder.start(); RollingFileAppender<ILoggingEvent> logFileAppender = new RollingFileAppender<>(); logFileAppender.setContext(logCtx); logFileAppender.setName("logFile"); logFileAppender.setEncoder(logEncoder); logFileAppender.setAppend(true); logFileAppender.setFile("logs/logfile.log"); TimeBasedRollingPolicy<ILoggingEvent> logFilePolicy = new TimeBasedRollingPolicy<>(); logFilePolicy.setContext(logCtx); logFilePolicy.setParent(logFileAppender); logFilePolicy.setFileNamePattern("logs/logfile-%d{yyyy-MM-dd_HH}.log"); logFilePolicy.setMaxHistory(7); logFilePolicy.start(); logFileAppender.setRollingPolicy(logFilePolicy); logFileAppender.start(); Logger log = logCtx.getLogger("Main"); log.setAdditive(false); log.setLevel(Level.INFO); log.addAppender(logConsoleAppender); log.addAppender(logFileAppender); }
6f482ce7-ef4a-45c0-86d4-3fd8f432e0c3
private static void tearDown() { try { LoggerContext logCtx = (LoggerContext) LoggerFactory.getILoggerFactory(); logCtx.stop(); } catch (Exception e) { // Just ignore this } }
f5b59664-0512-4476-b24b-4c58acee4141
private MBeanServerConnectionProvider() { }