Repository navigation
Expand file tree
/
Copy pathcodeReview2.json
More file actions
133 lines (133 loc) · 105 KB
/
Copy pathcodeReview2.json
File metadata and controls
133 lines (133 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
{
"conv": {
"id": "8ed63031-5a89-4b18-b7a5-1b770b4349f3",
"name": "provide an updated comprehensive code review",
"lastModified": 1769703693100,
"currNode": "cb10d7e6-615c-45b3-8162-c68292101c1e"
},
"messages": [
{
"convId": "8ed63031-5a89-4b18-b7a5-1b770b4349f3",
"role": "user",
"content": "provide an updated comprehensive code review",
"type": "text",
"timestamp": 1769703693144,
"thinking": "",
"toolCalls": "",
"children": [],
"extra": [
{
"type": "TEXT",
"name": "install.bat",
"content": "@set ARTIFACT=BandWidthTester\n@set VERSION=1.0-SNAPSHOT\n@set WITHDEP=jar-with-dependencies\n@for /F %%a in ('echo prompt $E^| cmd') do @set \"ESC=%%a\"\n\n@echo ^[%ESC%[42mSTAGE 1%ESC%[0m^] %ESC%[33m-----------------------^<%ESC%[0m %ESC%[42mBUILDING%ESC%[0m ... %ESC%[33m^>-----------------------%ESC%[0m\n\n@cmd /c mvn clean package\n\n@echo [%ESC%[42mSTAGE 2%ESC%[0m] %ESC%[33m----------------------- ^<%ESC%[0m %ESC%[42mInstalling%ESC%[0m: %ESC%[35m/usr/local/bin/${ARTIFACT}.jar %ESC%[0m %ESC%[33m^>-----------------------%ESC%[0m\ncopy target\\%ARTIFACT%-%VERSION%-%WITHDEP%.jar %USERPROFILE%/bin/%ARTIFACT%.jar\n\n"
},
{
"type": "TEXT",
"name": "README.md",
"content": " <H1>BandWidthTester</H1>\n <p>\n <br/>\n <LI>\n Uses iperf3 asynchronously for real-time performance measurements\n at the command-line\n </LI>\n </p>\n <H1>\n EXAMPLE USAGE\n </H1>\n <br/>\n <pre>\n$ LANG=C TERM=dumb java -jar BandWidthTester-1.0-SNAPSHOT.jar localhost\nExecuting command /usr/local/bin/iperf3 --forceflush --connect-timeout 3000 -c localhost -O 2 -P 8 -t 10 : |...*\nConnecting to host localhost, port 5201\n Local Host/IP: ::1 remote Host/IP: ::1 Remote Port: 5201\n ------------------------------------------------------------------------------\n....... 0.00-1.00 70.6 Gbits/sec (omitted)\n... Running 1.00-1.00 40.6 Gbits/sec\n... Running 1.00-2.00 80.1 Gbits/sec\n... Running 2.00-3.00 84.1 Gbits/sec\n... Running 3.00-4.00 88.7 Gbits/sec\n... Running 4.00-5.00 89.1 Gbits/sec\n... Running 5.00-6.00 87.0 Gbits/sec\n... Running 6.00-7.00 88.8 Gbits/sec\n... Running 7.00-8.00 78.2 Gbits/sec\n... Running 8.00-9.00 79.4 Gbits/sec\n Running 9.00-10.00 76.4 Gbits/sec\n\n ------------------------------------------------------------------------------\nResults: 0.00-10.00 83.3 Gbits/sec sender\nResults: 0.00-10.00 83.3 Gbits/sec receiver\nReturn Code: 000\n</pre>\n\n"
},
{
"type": "TEXT",
"name": "TerminalType.java",
"content": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage org.jaa.bandwidthtester;\n\n\n/**\n *\n * @author jerry\n */\n@SuppressWarnings(\"unused\")\npublic class TerminalType\n{\n public String ANSI_LINE = \"─\";\n public String BOTTOM_LEFT_CORNER = \"└\";\n public String BOTTOM_RIGHT_CORNER = \"┘\";\n public String LEFT_COLUMN_LINE = \"├\";\n public String RIGHT_COLUMN_LINE = \"┤\";\n public String TOP_LEFT_CORNER = \"┌\";\n public String TOP_RIGHT_CORNER = \"┐\";\n public String VERTICAL_BAR = \"│\";\n public String FANCY_RIGHT_ARROW = \"\\ue0b4\";\n public String FANCY_LEFT_ARROW = \"\\ue0b6\";\n\n private TERM m_term;\n private boolean m_utf;\n \n \n protected enum TERM {ANSI, DUMB}\n\n TerminalType()\n {\n m_term = TERM.ANSI;\n m_utf = true;\n\n \n String termEnv = System.getenv(\"TERM\");\n if (termEnv == null) termEnv = System.getProperty(\"TERM\");\n String lang = System.getenv(\"LANG\");\n if (lang == null) lang = System.getProperty(\"LANG\"); \n if ((termEnv == null) || termEnv.isEmpty() || termEnv.equalsIgnoreCase(\"dumb\")) {\n m_term = TERM.DUMB;\n }\n if ((lang == null) || !lang.toLowerCase().contains(\"utf\")) {\n m_utf = false;\n }\n\n // Windows has special Handling and escape sequence processing\n if (OS.getMyOS() == OS.OSTypes.WINDOWS) {\n m_utf = true;\n m_term = TERM.ANSI;\n }\n\n if (!m_utf) {\n VERTICAL_BAR = \"|\";\n BOTTOM_LEFT_CORNER = \"+\";\n BOTTOM_RIGHT_CORNER = \"+\";\n TOP_LEFT_CORNER = \"+\";\n TOP_RIGHT_CORNER = \"+\";\n LEFT_COLUMN_LINE = \"+\";\n RIGHT_COLUMN_LINE = \"+\";\n ANSI_LINE = \"-\";\n FANCY_RIGHT_ARROW=\")\";\n FANCY_LEFT_ARROW=\"(\";\n }\n }\n\n \n\n public boolean isAnsiTerm() { return (m_term == TERM.ANSI); }\n public boolean isUTF() { return m_utf; }\n @SuppressWarnings(\"ClassEscapesDefinedScope\")\n public TERM getTerm() { return this.m_term; }\n \n}\n"
},
{
"type": "TEXT",
"name": "ResultDetails.java",
"content": "package org.jaa.bandwidthtester;\n\nimport java.util.Date;\n\npublic class ResultDetails {\n String min = \"N/A\";\n String max = \"N/A\";\n String avg = \"N/A\";\n int rc = -1;\n Date runDate = new Date();\n\n public ResultDetails() {}\n\n @Override\n public String toString() {\n\n return String.format(\"Result=%d, min=%s, max=%s, avg=%s\", rc, min, max, avg);\n }\n\n\n public void setMin(String min) { this.min = min; }\n public void setMax(String max) { this.max = max; }\n public void setAvg(String avg) { this.avg = avg; }\n public void setRc(int rc) { this.rc = rc; }\n public Date getRunDate() { return runDate; }\n public int getRc() { return rc; }\n public void setRunDate(Date runDate) { this.runDate = runDate; }\n public String getMin() { return min; }\n public String getMax() { return max; }\n public String getAvg() { return avg; }\n\n}\n"
},
{
"type": "TEXT",
"name": "OS.java",
"content": "package org.jaa.bandwidthtester;\n\n\nimport com.sun.jna.Function;\nimport com.sun.jna.platform.win32.WinDef.BOOL;\nimport com.sun.jna.platform.win32.WinDef.DWORD;\nimport com.sun.jna.platform.win32.WinDef.DWORDByReference;\nimport com.sun.jna.platform.win32.WinDef.UINT;\nimport com.sun.jna.platform.win32.WinDef.UINTByReference;\nimport com.sun.jna.platform.win32.WinNT.HANDLE;\n\nimport java.io.FileDescriptor;\nimport java.io.FileOutputStream;\nimport java.io.PrintStream;\nimport java.nio.charset.StandardCharsets;\n\n/**\n *\n * @author jerry\n */\npublic final class OS\n{\n @SuppressWarnings(\"unused\")\n protected enum OSTypes\n {\n LINUX,\n MAC,\n WINDOWS,\n UNKNOWN\n }\n\n private static OSTypes myOS;\n\n private OS()\n {\n String os = System.getProperty(\"os.name\");\n // System.out.printf(\"os = '%s'\\n\", os);\n switch (os.toLowerCase().substring(0, 3))\n {\n case \"mac\":\n myOS = OSTypes.MAC;\n break;\n case \"lin\":\n myOS = OSTypes.LINUX;\n break;\n case \"win\":\n myOS = OSTypes.WINDOWS;\n break;\n default:\n myOS = OSTypes.UNKNOWN;\n break;\n }\n }\n \n @SuppressWarnings(\"ClassEscapesDefinedScope\")\n public static OSTypes getMyOS() {\n return myOS;\n }\n \n \n /**\n * On Windows, in order to get ANSI escape sequence colors, and some other\n * required terminal output, we resort to calling into\n * Following documented APIs from:\n * Console Developer's guide & API Reference - 05/18/2021\n * <li></li><a href=\"https://learn.microsoft.com/en-us/windows/console/setconsolemode\">...</a></li>\n * <li></li><a href=\"https://learn.microsoft.com/en-us/windows/console/setconsoleoutputcp\">...</a></li>\n *\n * @param myArgs - Arguments from command-line\n */\n public static void setWindowsConsoleMode(Args myArgs) {\n if (myArgs.verbose) System.out.printf(\"setting Windows Console Mode: myOS.getMyOS() = '%s' ? \", getMyOS());\n if (myOS == OSTypes.WINDOWS) {\n if (myArgs.verbose) System.out.println(\"YES\");\n try {\n // Set output mode to handle virtual terminal sequences\n try {\n if (myArgs.verbose) System.out.println(\"On Windows we are forcing Java to use UTF\");\n System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out), true, StandardCharsets.UTF_8));\n } catch (Exception e) {\n System.out.println(\"Cannot properly set Windows Code Page to UTF, output may be garbled!\");\n }\n Function GetStdHandleFunc = Function.getFunction(\"kernel32\", \"GetStdHandle\");\n DWORD STD_OUTPUT_HANDLE = new DWORD(-11);\n HANDLE hOut = (HANDLE) GetStdHandleFunc.invoke(HANDLE.class, new Object[]{STD_OUTPUT_HANDLE});\n\n DWORDByReference p_dwMode = new DWORDByReference(new DWORD(0));\n Function GetConsoleModeFunc = Function.getFunction(\"kernel32\", \"GetConsoleMode\");\n GetConsoleModeFunc.invoke(BOOL.class, new Object[]{hOut, p_dwMode});\n\n int ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4;\n DWORD dwMode = p_dwMode.getValue();\n dwMode.setValue(dwMode.intValue() | ENABLE_VIRTUAL_TERMINAL_PROCESSING);\n Function SetConsoleModeFunc = Function.getFunction(\"kernel32\", \"SetConsoleMode\");\n SetConsoleModeFunc.invoke(BOOL.class, new Object[]{hOut, dwMode});\n\n if (myArgs.verbose) System.out.println(\"And now we force Windows to also use the Code Page for UTF\");\n UINTByReference p_wCodePageID = new UINTByReference(new UINT(0));\n UINT wCodePageID = p_wCodePageID.getValue();\n wCodePageID.setValue(65001);\n Function SetConsoleOutputCP = Function.getFunction(\"kernel32\", \"SetConsoleOutputCP\");\n SetConsoleOutputCP.invoke(BOOL.class, new Object[]{wCodePageID});\n\n } catch (NoClassDefFoundError ne) {\n System.out.println(\"Running on Windows without console mode, characters can be garbled.\");\n }\n } else {\n if (myArgs.verbose) System.out.println(\"NO\");\n }\n }\n\n}\n"
},
{
"type": "TEXT",
"name": "MonitorIPerf3Output.java",
"content": "/*\n * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license\n * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template\n */\npackage org.jaa.bandwidthtester;\n\n/**\n *\n * @author jerry\n */\npublic class MonitorIPerf3Output {\n private static final String WORD_DELIMITER_RE = \"[ \\t]++\";\n protected static final int leftColumnMarker = 30;\n protected static int rightColumnMarker;\n\n static void processLine(String line, ConnectionDetails conn, Args args) {\n String local;\n String localPort;\n String connected;\n String to;\n String remotePort;\n String ID;\n if (args.debug) {\n System.out.printf(\"LINE: '%s'\\n\", line);\n }\n int firstLeftBracket = line.indexOf(\"[\");\n int firstRightBracket = line.indexOf(\"]\");\n if (firstLeftBracket >= 0 && firstRightBracket > firstLeftBracket) {\n ID = line.substring(firstLeftBracket + 1, firstRightBracket);\n String[] restOfLine = line.substring(firstRightBracket + 1).split(WORD_DELIMITER_RE);\n if (ID.contains(\"ID\")) {\n if (!conn.isGathered()) {\n if (args.verbose) {\n System.out.printf(\"ID Separator: %s\\n\", line);\n }\n System.out.printf(\"%s Local Host/IP: %s%s%s remote Host/IP: %s%s%s Remote Port: %s%d%s\\n\", \n AnsiCodes.getCR(args.getTermType()),\n AnsiCodes.ANSI_COLOR.RED.getBoldCode(args.getTermType()), conn.getLocalHost(), AnsiCodes.getReset(args.getTermType()), \n AnsiCodes.ANSI_COLOR.GREEN.getCode(args.getTermType()), conn.getRemoteHost(), AnsiCodes.getReset(args.getTermType()), \n AnsiCodes.ANSI_COLOR.GREEN.getCode(args.getTermType()), conn.getRemotePort(), AnsiCodes.getReset(args.getTermType()));\n conn.setGathered(true);\n conn.setResultEntry(0);\n }\n }\n if (!conn.isGathered()) {\n if (restOfLine.length == 10) {\n conn.setLocalHost(restOfLine[2]);\n conn.setLocalPort(restOfLine[4]);\n conn.setRemoteHost(restOfLine[7]);\n conn.setRemotePort(restOfLine[9]);\n local = restOfLine[1];\n localPort = restOfLine[3];\n connected = restOfLine[5];\n to = restOfLine[6];\n remotePort = restOfLine[8];\n if (args.debug) {\n System.out.printf(\"[first=%s] id='%s', local='%s', localHost='%s', lport='%s', localPort='%d', connected='%s', to='%s', remoteHost='%s', rport='%s', remotePort='%d'\\n\", conn.isGathered(), ID, local, conn.getLocalHost(), localPort, conn.getLocalPort(), connected, to, conn.getRemoteHost(), remotePort, conn.getRemotePort());\n }\n } else {\n // Other iperf3 information\n if (!line.trim().isEmpty()) {\n System.out.println();\n System.out.print(line);\n }\n }\n } else {\n // connIsGathered\n if (restOfLine.length >= 7) {\n String interval = restOfLine[1];\n String intervalUnit = restOfLine[2];\n String transfer = restOfLine[3];\n String transferUnit = restOfLine[4];\n String bitRate = restOfLine[5];\n String bitRateUnit = restOfLine[6];\n String sendOrReceive = \"\";\n if (restOfLine.length > 7) sendOrReceive = restOfLine[7];\n if (restOfLine.length > 8) sendOrReceive = restOfLine[8];\n if (restOfLine.length > 9) sendOrReceive = restOfLine[9];\n if (restOfLine.length > 10) sendOrReceive = restOfLine[10];\n sendOrReceive = sendOrReceive.trim();\n if (!sendOrReceive.toLowerCase().contains(\"sender\") && !sendOrReceive.toLowerCase().contains(\"receiv\") && !sendOrReceive.toLowerCase().contains(\"omit\")) {\n sendOrReceive = \"\";\n }\n if (args.verbose) {\n System.out.printf(\"id='%s', interval='%s', intervalUnit='%s', transfer='%s', transferUnit='%s', bitRate='%s', bitRateUnit='%s', sendOrReceive='%s'\\n\", \n ID, interval, intervalUnit, transfer, transferUnit, bitRate, bitRateUnit, sendOrReceive);\n }\n \n String color1 = AnsiCodes.ANSI_COLOR.BLUE.getBoldCode(args.getTermType()); \n String color2 = AnsiCodes.ANSI_COLOR.BLUE.getCode(args.getTermType()); \n String time = \" Running \";\n boolean done = false;\n String columnSet = AnsiCodes.gotoColumn(args.getTermType(), 4);\n if (ID.contains(\"SUM\") || conn.isSingleThread()) {\n double bitRateValue = -1;\n try { bitRateValue = Double.parseDouble(bitRate); } catch (NumberFormatException ignored) { }\n if (sendOrReceive.isEmpty()) { \n conn.setMaxBitsBytesPerSec(bitRateValue, bitRateUnit);\n conn.setMinBitsBytesPerSec(bitRateValue, bitRateUnit);\n }\n switch (sendOrReceive.toLowerCase()) {\n case \"(omitted)\":\n if (conn.isLastOmitted() || conn.getResultEntry() == 0) {\n System.out.printf(\"%s%s\", AnsiCodes.getCR(args.getTermType()), AnsiCodes.getClearToEOL(args.getTermType()));\n }\n time = \" Skipping \";\n if (args.getTermType().isAnsiTerm()) {\n System.out.printf(\"%s%s%s\", \n AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.gotoColumn(args.getTermType(), MonitorIPerf3Output.leftColumnMarker - 2),\n \" \");\n }\n conn.setLastOmitted(true);\n break;\n case \"sender\":\n case \"receiver\":\n conn.setLastOmitted(false);\n columnSet = AnsiCodes.gotoColumn(args.getTermType(), 3);\n if (conn.isFinished()) {\n if (conn.isLastOmitted() || conn.getResultEntry() == 0) {\n System.out.printf(\"%s%s\", AnsiCodes.getCR(args.getTermType()), AnsiCodes.getClearToEOL(args.getTermType()));\n }\n conn.setFinished();\n time = \"Results: \"; \n conn.setSummaryResults(true);\n } else {\n time = \" => \"; \n System.out.println();\n done = true;\n }\n if (args.verbose) System.out.printf(\"sender/receiver interval = '%s'\\n\", interval);\n color1 = AnsiCodes.ANSI_COLOR.GREEN.getReverseBoldCode(args.getTermType());\n color2 = AnsiCodes.ANSI_COLOR.BLUE.getReverseBoldCode(args.getTermType());\n break;\n default:\n conn.incrementResultEntry(); \n if (conn.isLastOmitted() || conn.getResultEntry() == 0) {\n System.out.printf(\"%s%s\", AnsiCodes.getCR(args.getTermType()), AnsiCodes.getClearToEOL(args.getTermType()));\n }\n conn.setLastOmitted(false);\n sendOrReceive = \"\";\n }\n\n StringBuilder fmtString = new StringBuilder();\n String bitRateColor = AnsiCodes.ANSI_COLOR.GREEN.getReverseBoldCode(args.getTermType());\n if (bitRateValue == 0) {\n bitRateColor = AnsiCodes.ANSI_COLOR.RED.getReverseBoldCode(args.getTermType());\n }\n fmtString.append(\"%s\"); // goto column 4\n fmtString.append(\"%s%s%-12.12s%s\"); // time, color1, interval, reset\n fmtString.append(\" %s\"); // gotoColumn cm + times + 2\n fmtString.append(\" %s%,9.2f%s\"); // reverse Highlight, bitRate, reset\n fmtString.append(\" %s%-10.10s%s\"); // bold, bitRateUnit, reset\n fmtString.append(\" %s%s%s\"); // color2, sendOrReceive, reset\n fmtString.append(\"%s\"); // clear to EOL\n //conn.setLastResult(bitRateValue + \" \" + bitRateUnit);\n ResultDetails result = new ResultDetails();\n result.setAvg(bitRateValue + \" \" + bitRateUnit);\n\n conn.setResultDetails(result);\n System.out.printf(fmtString.toString(), \n columnSet,\n time, color1, interval, AnsiCodes.getReset(args.getTermType()), \n AnsiCodes.gotoColumn(args.getTermType(), leftColumnMarker + args.times + 2),\n bitRateColor, bitRateValue, AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.getBold(args.getTermType()), bitRateUnit, AnsiCodes.getReset(args.getTermType()),\n color2, sendOrReceive, AnsiCodes.getReset(args.getTermType()), \n AnsiCodes.getClearToEOL(args.getTermType()));\n if (!args.getTermType().isAnsiTerm()) {\n System.out.println();\n }\n else if (!done && conn.isFinished()) {\n printProgress(conn, args);\n }\n if (done) {\n columnSet = AnsiCodes.gotoColumn(args.getTermType(), leftColumnMarker);\n // System.out.printf(\"%s%s\", AnsiCodes.getCR(args.getTermType()), AnsiCodes.getClearToEOL(args.getTermType())); \n System.out.println();\n if (conn.getMinBitsBytesPerSec() != null) {\n System.out.printf(\"%s[%s%s%s]%s%s\\n\",\n columnSet,\n AnsiCodes.ANSI_COLOR.RED.getReverseBoldCode(args.getTermType()),\n \"Min\",\n AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.gotoColumn(args.getTermType(), leftColumnMarker + args.times + 3),\n conn.getMinBitsBytesPerSec());\n conn.disableColors();\n result.setMin(conn.getMinBitsBytesPerSec());\n conn.enableColors();\n } else {\n System.out.println();\n }\n if (conn.getMaxBitsBytesPerSec() != null) {\n System.out.printf(\"%s[%s%s%s]%s%s\\n\",\n columnSet,\n AnsiCodes.ANSI_COLOR.BLUE.getReverseBoldCode(args.getTermType()),\n \"Max\",\n AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.gotoColumn(args.getTermType(), leftColumnMarker + args.times + 3),\n conn.getMaxBitsBytesPerSec());\n conn.disableColors();\n result.setMax(conn.getMaxBitsBytesPerSec());\n conn.enableColors();\n\n } else {\n System.out.println();\n }\n System.out.print(\" \");\n printLine(args, 78);\n }\n \n }\n } else {\n if (args.debug) {\n System.out.printf(\"Incorrect number of words: = %d:\", restOfLine.length);\n System.out.printf(\"'%s'\\n\", line);\n }\n }\n }\n } else {\n if (!Launcher.EOF.equals(line) && \n !line.startsWith(\"- -\") && \n !line.toLowerCase().contains(\"iperf done\") && \n !line.trim().isEmpty()) {\n System.out.printf(\"%s\\n\", line);\n }\n }\n }\n \n protected static void printLine(Args args, int col) {\n for (int j = 0; j < col; j++) {\n System.out.printf(\"%s\", AnsiCodes.getHorizontalLine(args.getTermType()));\n }\n System.out.println();\n }\n \n private static void printProgress(ConnectionDetails conn, Args args) {\n if (args.isVerbose() || args.isDebug()) return;\n String leftBracket = \"[\";\n String rightBracket = \"]\";\n\n int column1 = leftColumnMarker + conn.getResultEntry();\n int column2 = column1 - 1;\n String arrow = args.getTermType().FANCY_RIGHT_ARROW;\n if (args.reverse) {\n leftBracket = \"(\";\n column1 = rightColumnMarker - conn.getResultEntry();\n arrow = args.getTermType().FANCY_LEFT_ARROW;\n column2 = column1 + 1;\n } else {\n rightBracket = \")\";\n }\n if (conn.isLastOmitted() || conn.getResultEntry() == 0) {\n column1 = leftColumnMarker;\n column2 = leftColumnMarker;\n }\n String fmt = \"%s\" + // goto column1\n \"%s%s%s\" + // green, arrow, reset\n \"%s%s%s\" + // goto column2, reverse, space\n \"%s\"; // reset\n System.out.printf(fmt,\n AnsiCodes.gotoColumn(args.getTermType(), column1),\n AnsiCodes.ANSI_COLOR.YELLOW.getCode(args.getTermType()), arrow, AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.gotoColumn(args.getTermType(), column2),\n AnsiCodes.ANSI_COLOR.YELLOW.getReverseHighlightCode(args.getTermType()), \" \",\n AnsiCodes.getReset(args.getTermType()));\n\n System.out.printf(\"%s%s%s%s\",\n AnsiCodes.gotoColumn(args.getTermType(), leftColumnMarker),\n leftBracket,\n AnsiCodes.gotoColumn(args.getTermType(), rightColumnMarker),\n rightBracket);\n if (conn.getResultEntry() >= args.times) {\n if (!args.reverse) {\n System.out.printf(\"%s%s%s%s%s%s%s%s\",\n AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.gotoColumn(args.getTermType(), rightColumnMarker - 1),\n AnsiCodes.ANSI_COLOR.YELLOW.getReverseHighlightCode(args.getTermType()), \" \",\n AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.ANSI_COLOR.YELLOW.getCode(args.getTermType()),\n arrow,\n AnsiCodes.getReset(args.getTermType()));\n } else {\n System.out.printf(\"%s%s%s%s%s%s%s\",\n AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.gotoColumn(args.getTermType(), leftColumnMarker),\n AnsiCodes.ANSI_COLOR.YELLOW.getCode(args.getTermType()),\n arrow,\n AnsiCodes.ANSI_COLOR.YELLOW.getReverseHighlightCode(args.getTermType()),\n \" \",\n AnsiCodes.getReset(args.getTermType()));\n }\n } else {\n if (args.getTermType().isAnsiTerm()) {\n int restingColumn = MonitorIPerf3Output.leftColumnMarker + conn.getResultEntry() + 1;\n if (args.reverse) {\n restingColumn = MonitorIPerf3Output.rightColumnMarker - conn.getResultEntry() - 1;\n }\n System.out.printf(\"%s%s\", \n AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.gotoColumn(args.getTermType(), restingColumn));\n }\n }\n }\n \n\n}\n"
},
{
"type": "TEXT",
"name": "Launcher.java",
"content": "/*\n * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license\n * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template\n */\npackage org.jaa.bandwidthtester;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.concurrent.ArrayBlockingQueue;\n\n\n\n/**\n *\n * @author jerry\n */\npublic class Launcher\n implements Runnable\n{\n private final BufferedReader m_in;\n private final ArrayBlockingQueue<String> m_lines;\n private Exception m_e;\n public static final String EOF = \"EOF\";\n \n public Launcher(InputStream in, ArrayBlockingQueue<String> lines) {\n m_in = new BufferedReader(new InputStreamReader(in));\n m_lines = lines;\n }\n \n @Override\n public void run()\n {\n String line;\n try {\n do {\n line = m_in.readLine();\n if (line != null) {\n m_lines.offer(line);\n }\n } while (line != null);\n m_lines.add(EOF); \n } catch(IOException e) {\n System.out.printf(\"Error: %s\\n\", e);\n e.printStackTrace(System.out);\n m_e = e;\n }\n }\n\n\n public Exception getException() { return m_e; }\n \n\n\n}\n"
},
{
"type": "TEXT",
"name": "IPerf3Monitor.java",
"content": "/*\n * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license\n * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template\n */\npackage org.jaa.bandwidthtester;\n\nimport java.util.Date;\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.TimeUnit;\n\n/**\n *\n * @author jerry\n */\nclass IPerf3Monitor {\n protected static final String[] tick = {\"-\", \"/\", \"+\", \"\\\\\"};\n protected static String startProgress = \"|\";\n protected static String progress = \"-\"; \n protected static String progressRight = \">\";\n protected static String doneProcessing = \"*\";\n\n protected static int run(String[] iperf3cmdLine, Args args, ResultDetails resultDetails, boolean showCommand) {\n\n ArrayBlockingQueue<String> outputLines = new ArrayBlockingQueue<>(1000);\n ArrayBlockingQueue<String> errorLines = new ArrayBlockingQueue<>(1000);\n long pollInterval = 100;\n\n String line;\n Executor e = new Executor();\n ConnectionDetails conn = new ConnectionDetails(args);\n\n\n startProgress = \"Running: \" + AnsiCodes.ANSI_COLOR.GREEN.getBoldCode(args.getTermType()) + \"[\" + AnsiCodes.getReset(args.getTermType());\n progress = \" \";\n progressRight = args.getTermType().FANCY_RIGHT_ARROW;\n doneProcessing = progressRight;\n\n conn.setIsSingleThread(args.single);\n conn.setTimePeriod(args.times);\n conn.setVerbose(args.verbose);\n MonitorIPerf3Output.rightColumnMarker = MonitorIPerf3Output.leftColumnMarker + conn.getTimePeriod() + 1;\n int rc = -1;\n\n\n try {\n e.execCommand(iperf3cmdLine, outputLines, errorLines, args, showCommand);\n boolean waitForResult = true;\n int iter = 0;\n System.out.printf(\"%s \", startProgress);\n Date start = new Date();\n boolean stalled = false;\n while (!stalled) {\n\n // If iperf3 starts to stall out, indicate this.\n line = outputLines.poll(pollInterval, TimeUnit.MILLISECONDS);\n if (line != null) {\n if (waitForResult) {\n System.out.printf(\"%s%s%s%s%s\\n\",\n AnsiCodes.getBackSpace(args.getTermType()),\n AnsiCodes.getClearToEOL(args.getTermType()),\n AnsiCodes.ANSI_COLOR.GREEN.getCode(args.getTermType()),\n doneProcessing,\n AnsiCodes.getReset(args.getTermType()));\n waitForResult = false;\n// } else {\n// System.out.printf(\"%s\",\n// AnsiCodes.gotoColumn(args.getTermType(), MonitorIPerf3Output.leftColumnMarker + conn.getResultEntry() + 1));\n }\n if (Launcher.EOF.equals(line)) {\n break;\n } \n MonitorIPerf3Output.processLine(line, conn, args);\n start = new Date();\n\n } else {\n if (!conn.isGathered()) {\n if (args.getTermType().isAnsiTerm()) {\n System.out.printf(\"%s%s%s%s%s%s%s\",\n AnsiCodes.getBackSpace(args.getTermType()),\n AnsiCodes.ANSI_COLOR.GREEN.getReverseHighlightCode(args.getTermType()),\n progress,\n AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.ANSI_COLOR.GREEN.getCode(args.getTermType()),\n progressRight,\n AnsiCodes.getReset(args.getTermType()));\n } else {\n System.out.print(\".\");\n }\n }\n Date end = new Date();\n if (conn.isGathered() && !conn.isSummaryResults()) {\n int restingColumn = MonitorIPerf3Output.leftColumnMarker + conn.getResultEntry() + 1;\n if (args.reverse) {\n restingColumn = MonitorIPerf3Output.rightColumnMarker - conn.getResultEntry() - 1;\n }\n if ((end.getTime() - start.getTime()) > TimeUnit.SECONDS.toMillis(5)) {\n stalled = true;\n } else if ((end.getTime() - start.getTime()) > TimeUnit.MILLISECONDS.toMillis(500)) {\n if (args.getTermType().isAnsiTerm()) {\n System.out.printf(\"%s%s%s%s%s%s\",\n AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.gotoColumn(args.getTermType(), MonitorIPerf3Output.leftColumnMarker - 2),\n AnsiCodes.ANSI_COLOR.RED.getCode(args.getTermType()),\n tick[iter % tick.length],\n AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.gotoColumn(args.getTermType(), restingColumn));\n } else {\n System.out.print(\"X\");\n }\n }\n else {\n if (args.getTermType().isAnsiTerm()) {\n System.out.printf(\"%s%s%s%s\",\n AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.gotoColumn(args.getTermType(), MonitorIPerf3Output.leftColumnMarker - 2),\n tick[iter % tick.length],\n AnsiCodes.gotoColumn(args.getTermType(), restingColumn));\n } else {\n System.out.print(\".\");\n }\n }\n iter++;\n }\n }\n }\n\n int errorCounter = 0;\n while (true) {\n line = errorLines.poll(100, TimeUnit.MILLISECONDS);\n if (line != null) {\n if (Launcher.EOF.equals(line)) {\n break;\n } else {\n if (line.toLowerCase().contains(\"unknown option\")) {\n System.out.printf(\"%s%s%s: [%sOutput will not be buffered%s]\\n\",\n AnsiCodes.ANSI_COLOR.PURPLE.getCode(args.getTermType()), line, AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.ANSI_COLOR.GREY.getHighlightCode(args.getTermType()), AnsiCodes.getReset(args.getTermType()));\n return -999;\n }\n if (errorCounter == 0) {\n System.out.printf(\"\\n%sErrors%s:\\n\",\n AnsiCodes.ANSI_COLOR.RED.getHighlightCode(args.getTermType()), AnsiCodes.getReset(args.getTermType()));\n }\n System.out.printf(\"\\t%s%s%s\\n\", \n AnsiCodes.ANSI_COLOR.RED.getCode(args.getTermType()), line, AnsiCodes.getReset(args.getTermType())); \n }\n errorCounter++; \n }\n }\n\n System.out.printf(\"%s\", AnsiCodes.gotoColumn(args.getTermType(), 0));\n if (stalled) {\n System.out.print(\" \");\n MonitorIPerf3Output.printLine(args, 80);\n System.out.printf(\" STALLED: %s%03d%s\\n\", AnsiCodes.ANSI_COLOR.RED.getCode(args.getTermType()), 999, AnsiCodes.getReset(args.getTermType()));\n } else {\n rc = e.getCommandReturnCode(args);\n if (rc == 0) {\n System.out.printf(\" Return Code: %s%03d%s [Avg=%s%s%s]\\n\",\n AnsiCodes.ANSI_COLOR.GREEN.getCode(args.getTermType()),\n rc,\n AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.getBold(args.getTermType()),\n conn.getResultDetails().getAvg(),\n AnsiCodes.getReset(args.getTermType()));\n } else {\n System.out.print(\" \");\n MonitorIPerf3Output.printLine(args, 80);\n System.out.printf(\" Return Code: %s%03d%s\\n\",\n AnsiCodes.ANSI_COLOR.RED.getCode(args.getTermType()), rc, AnsiCodes.getReset(args.getTermType()));\n }\n }\n } catch (Exception ex) {\n System.out.printf(\"Main Exception: %s\\n\", ex);\n ex.printStackTrace(System.out);\n rc = -1;\n }\n ResultDetails rr = conn.getResultDetails();\n resultDetails.setAvg(rr.getAvg());\n resultDetails.setMin(rr.getMin());\n resultDetails.setMax(rr.getMax());\n resultDetails.setRc(rr.getRc());\n return rc;\n }\n\n \n}\n"
},
{
"type": "TEXT",
"name": "Executor.java",
"content": "/*\n * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license\n * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template\n */\npackage org.jaa.bandwidthtester;\n\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.stream.Collectors;\n\n\n/**\n *\n * @author jerry\n */\npublic class Executor {\n\n Launcher m_launcherOut;\n Launcher m_launcherErr;\n Thread m_outThread;\n Thread m_errThread;\n Process m_proc;\n \n public void execCommand(String[] cmdLine, ArrayBlockingQueue<String> outputLines, ArrayBlockingQueue<String> errorLines, Args myArgs, boolean showCommand) {\n try {\n Runtime runtime = Runtime.getRuntime();\n m_proc = runtime.exec(cmdLine);\n m_launcherOut = new Launcher(m_proc.getInputStream(), outputLines);\n m_outThread = new Thread(m_launcherOut);\n \n m_launcherErr = new Launcher(m_proc.getErrorStream(), errorLines);\n m_errThread = new Thread(m_launcherErr);\n if (showCommand) {\n String output =\n Arrays.stream(cmdLine)\n .map(s ->\n \"'\"\n + AnsiCodes.ANSI_COLOR.BLUE.getCode(myArgs.getTermType())\n + s\n + AnsiCodes.getReset(myArgs.getTermType())\n + \"'\")\n .collect(Collectors.joining(\" \"));\n System.out.printf(\"\\n%siperf3 command-line%s:\\n ==> %s\\n\",\n AnsiCodes.ANSI_COLOR.GREEN.getCode(myArgs.getTermType()),\n AnsiCodes.getReset(myArgs.getTermType()),\n output);\n }\n\n m_outThread.start();\n m_errThread.start();\n if (myArgs.debug) {\n System.out.printf(\"My Thread = '%s'\\n\", Thread.currentThread().getName());\n System.out.printf(\"Out Thread='%s'\\n\", m_outThread.getName());\n System.out.printf(\"Error Thread='%s'\\n\", m_errThread.getName());\n }\n \n } catch (IOException ex) {\n System.out.println(\"Exception occurred while executing the command \" +\n Arrays.toString(cmdLine) + \" :\\n\" +\n ex.getMessage());\n }\n } \n \n \n public int getCommandReturnCode(Args myArgs) throws Exception {\n int exitCode = -999;\n try {\n m_proc.waitFor();\n m_outThread.join();\n m_errThread.join();\n exitCode = m_proc.exitValue();\n Exception threadExcep;\n if((threadExcep = m_launcherOut.getException()) != null) { throw threadExcep; }\n if((threadExcep = m_launcherErr.getException()) != null) { throw threadExcep; }\n } catch (InterruptedException ex) {\n System.out.printf(\"Exception in getreturncode: %s\\n\", ex);\n ex.printStackTrace(System.out);\n }\n if (myArgs.verbose) System.out.printf(\"Return Code = %d\\n\", exitCode);\n return exitCode;\n }\n}\n"
},
{
"type": "TEXT",
"name": "ConnectionDetails.java",
"content": "/*\n * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license\n * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template\n */\npackage org.jaa.bandwidthtester;\n\n/**\n *\n * @author jerry\n */\npublic class ConnectionDetails {\n\n private static final double kb = 1024.0;\n private static final double mb = kb * kb;\n private static final double gb = kb * mb;\n private static final double tb = kb * gb;\n\n private String minColor = \"\";\n private String maxColor = \"\";\n private String defaultUnitFormat = \" %-10.10s \";\n private String defaultValFormat = \" %,8.2f\";\n private boolean isColored = true;\n\n public void disableColors() {\n minColor = \"\";\n maxColor = \"\";\n defaultUnitFormat = \" %s\";\n defaultValFormat = \"%.2f\";\n isColored = false;\n }\n\n public void enableColors() {\n minColor = AnsiCodes.ANSI_COLOR.RED.getReverseBoldCode(m_myArgs.getTermType());\n maxColor = AnsiCodes.ANSI_COLOR.BLUE.getReverseBoldCode(m_myArgs.getTermType());\n defaultUnitFormat = \" %-10.10s \";\n defaultValFormat = \" %,8.2f\";\n isColored = true;\n }\n private String m_localHost = \"\";\n private String m_remoteHost = \"\";\n private int m_localPort = -1;\n private int m_remotePort = -1;\n private int m_timePeriod = 0;\n private int m_resultEntry = 0;\n private boolean m_gathered = false;\n private boolean m_summaryResults = false;\n private boolean m_singleThread = false;\n protected double m_maxBytesPerSec = Double.MIN_VALUE;\n protected double m_minBytesPerSec = Double.MAX_VALUE;\n protected double m_maxBitsPerSec = Double.MIN_VALUE;\n protected double m_minBitsPerSec = Double.MAX_VALUE;\n protected boolean m_isBytesUnit = true;\n private boolean m_verbose = false;\n private boolean m_lastOmitted = false;\n private ResultDetails m_resultDetails = new ResultDetails();\n private final Args m_myArgs;\n\n public ResultDetails getResultDetails() { return m_resultDetails; }\n public void setResultDetails(ResultDetails resultDetails) { m_resultDetails = resultDetails; }\n\n\n public boolean isLastOmitted() { return m_lastOmitted; }\n\n public boolean isVerbose() { return m_verbose; }\n public boolean isGathered() { return m_gathered; }\n public boolean isSingleThread() { return m_singleThread; }\n public boolean isFinished() { return (m_resultEntry != -999); }\n public boolean isSummaryResults() { return m_summaryResults; }\n public String getLocalHost() { return m_localHost; }\n public int getRemotePort() { return m_remotePort; }\n public int getLocalPort() { return m_localPort; }\n public int getTimePeriod() { return m_timePeriod; }\n public String getRemoteHost() { return m_remoteHost; }\n public int getResultEntry() { return m_resultEntry; }\n public String getDefaultUnitFormat() { return defaultUnitFormat; }\n public String getDefaultValFormat() { return defaultValFormat; }\n public boolean isColored() { return isColored; }\n\n\n /**\n * Constructor\n * @param args Command line arguments\n */\n public ConnectionDetails(Args args) {\n m_myArgs = args;\n enableColors();\n }\n\n public String getMinBitsBytesPerSec() {\n String result = \"N/A\";\n if (m_isBytesUnit) {\n if (m_minBytesPerSec != Double.MAX_VALUE) {\n result = String.format(\"%s%s\",\n minColor,\n convertToHumanReadable(m_myArgs, m_minBytesPerSec, true,\n getDefaultUnitFormat(), getDefaultValFormat(),\n isColored()));\n }\n } else {\n if (m_minBitsPerSec != Double.MAX_VALUE) {\n result = String.format(\"%s%s\",\n minColor,\n convertToHumanReadable(m_myArgs, m_minBitsPerSec, false,\n getDefaultUnitFormat(), getDefaultValFormat(),\n isColored()));\n }\n }\n\n return result;\n }\n public String getMaxBitsBytesPerSec() {\n String result = \"N/A\";\n if (m_isBytesUnit) {\n if (m_maxBytesPerSec != Double.MIN_VALUE) {\n result = String.format(\"%s%s\",\n maxColor,\n convertToHumanReadable(m_myArgs, m_maxBytesPerSec, true,\n getDefaultUnitFormat(), getDefaultValFormat(),\n isColored()));\n }\n } else {\n if (m_maxBitsPerSec != Double.MIN_VALUE) {\n result = String.format(\"%s%s\",\n maxColor,\n convertToHumanReadable(m_myArgs, m_maxBitsPerSec, false,\n getDefaultUnitFormat(), getDefaultValFormat(),\n isColored()));\n }\n }\n return result;\n }\n \n public void setMaxBitsBytesPerSec(double value, String unit) {\n double[] converted = convertUnitToBitsAndBytes(value, unit);\n double maxBitsPerSec = converted[0];\n double maxBytesPerSec = converted[1];\n if (!m_isBytesUnit) {\n if (isVerbose()) System.out.printf(\"\\tsetMaxBitsPerSec(%.2f %s): [current max bits/sec = %.0f] \",\n value, unit,\n ((m_maxBitsPerSec != Double.MIN_VALUE) ? m_maxBitsPerSec : -1));\n if (maxBitsPerSec != -1 && maxBitsPerSec > m_maxBitsPerSec) {\n if (isVerbose()) System.out.printf(\" [Setting maxBitsPerSec to %.0f bits/sec (orig = %s)] \", maxBitsPerSec, unit);\n m_maxBitsPerSec = maxBitsPerSec;\n }\n } else {\n if (isVerbose()) System.out.printf(\"\\tsetMaxBytesPerSec(%.2f %s): [current max bytes/sec = %.0f] \",\n value, unit,\n ((m_maxBytesPerSec != Double.MIN_VALUE) ? m_maxBytesPerSec : -1));\n\n if (maxBytesPerSec != -1 && maxBytesPerSec > m_maxBytesPerSec) {\n if (isVerbose()) System.out.printf(\" [Setting maxBytesPerSec to %.0f bytes/sec (orig = %s)] \", maxBytesPerSec, unit);\n m_maxBytesPerSec = maxBytesPerSec;\n }\n }\n if (isVerbose()) System.out.println();\n }\n\n public void setMinBitsBytesPerSec(double value, String unit) {\n\n double[] converted = convertUnitToBitsAndBytes(value, unit);\n double minBitsPerSec = converted[0];\n double minBytesPerSec = converted[1];\n if (!m_isBytesUnit) {\n if (isVerbose()) System.out.printf(\"\\tsetMinBitsPerSec(%.2f %s): [current min bits/sec = %.0f] \",\n value, unit,\n ((m_minBitsPerSec != Double.MAX_VALUE) ? m_minBitsPerSec : -1));\n if (minBitsPerSec != -1 && minBitsPerSec < m_minBitsPerSec) {\n if (isVerbose()) System.out.printf(\" [Setting minBitsPerSec to %.0f bits/sec (orig = %s)] \", minBitsPerSec, unit);\n m_minBitsPerSec = minBitsPerSec;\n }\n } else {\n if (isVerbose()) System.out.printf(\"\\tsetMinBytesPerSec(%.2f %s): [current min bytes/sec = %.0f] \",\n value, unit,\n ((m_minBytesPerSec != Double.MAX_VALUE) ? m_minBytesPerSec : -1));\n if (minBytesPerSec != -1 && minBytesPerSec < m_minBytesPerSec) {\n if (isVerbose()) System.out.printf(\" [Setting minBytesPerSec to %.0f bytes/sec (orig = %s)] \", minBytesPerSec, unit);\n m_minBytesPerSec = minBytesPerSec;\n }\n }\n if (isVerbose()) System.out.println();\n }\n\n private double[] convertUnitToBitsAndBytes(double value, String unit) {\n double[] result = new double[2];\n double bits = -1;\n double bytes = -1;\n switch (unit.trim().toLowerCase()) {\n case \"bytes/sec\": bytes = value; break;\n case \"kbytes/sec\": bytes = value * kb; break;\n case \"mbytes/sec\": bytes = value * mb; break;\n case \"gbytes/sec\": bytes = value * gb; break;\n case \"tbytes/sec\": bytes = value * tb; break;\n\n case \"bits/sec\": bits = value; m_isBytesUnit = false; break;\n case \"kbits/sec\": bits = value * kb; m_isBytesUnit = false; break;\n case \"mbits/sec\": bits = value * mb; m_isBytesUnit = false; break;\n case \"gbits/sec\": bits = value * gb; m_isBytesUnit = false; break;\n case \"tbits/sec\": bits = value * tb; m_isBytesUnit = false; break;\n default:\n throw new IllegalArgumentException(\"Invalid unit: \" + unit);\n }\n result[0] = bits;\n result[1] = bytes;\n return result;\n }\n\n public static String convertToHumanReadable(Args args, double val, boolean bitsOrBytes, String fmt1, String fmt2, boolean isColor) {\n if (args.isDebug()) System.out.printf(\"Normalizing val = %,f, kb = %,f\\n\", val, kb);\n if (val <= 0) {\n if (isColor) return (\"- - - - -\" + AnsiCodes.getReset(args.getTermType()));\n else return \"STALLED\";\n }\n String tbString = \"Tbits\";\n String gbString = \"Gbits\";\n String mbString = \"Mbits\";\n String kbString = \"Kbits\";\n String bString = \"bits\";\n if (bitsOrBytes) {\n // Tbytes/sec\n // 1234567890\n tbString = \"TBytes\";\n gbString = \"GBytes\";\n mbString = \"MBytes\";\n kbString = \"KBytes\";\n bString = \"Bytes\";\n }\n double tbVal = val / tb;\n double gBVal = val / gb;\n double mBVal = val / mb;\n double kBVal = val / kb;\n\n String unitString;\n double valUnits;\n if (tbVal > 1.0) {\n valUnits = tbVal;\n unitString = tbString;\n } else if (gBVal > 1.0) {\n valUnits = gBVal;\n unitString = gbString;\n } else if (mBVal > 1.0) {\n valUnits = mBVal;\n unitString = mbString;\n } else if (kBVal > 1.0) {\n valUnits = kBVal;\n unitString = kbString;\n } else {\n valUnits = val;\n unitString = bString;\n }\n unitString += \"/sec\";\n return String.format(fmt2 + \"%s%s\" + fmt1 + \"%s\",\n valUnits,\n AnsiCodes.getReset(args.getTermType()),\n AnsiCodes.getBold(args.getTermType()),\n unitString,\n AnsiCodes.getReset(args.getTermType()));\n\n }\n\n\n public void setLastOmitted(boolean lastOmitted) { m_lastOmitted = lastOmitted; }\n public void setVerbose(boolean verbose) { m_verbose = verbose; }\n public void setGathered(boolean gathered) { m_gathered = gathered; }\n public void setTimePeriod(int timePeriod) { m_timePeriod = timePeriod; }\n public void setSummaryResults(boolean summaryResults) { m_summaryResults = summaryResults; }\n public void setLocalHost(String localHost) { m_localHost = localHost; }\n public void setRemoteHost(String remoteHost) { m_remoteHost = remoteHost; }\n public void setIsSingleThread(boolean singleThread) { m_singleThread = singleThread; }\n public void setResultEntry(int resultEntry) { m_resultEntry = resultEntry; }\n public void incrementResultEntry() { m_resultEntry++; }\n public void setFinished() { m_resultEntry = -999; } \n public void setLocalPort(String localPort) { \n try {\n m_localPort = Integer.parseInt(localPort);\n } catch (NumberFormatException n) {\n m_localPort = -1;\n }\n }\n \n public void setRemotePort(String remotePort) { \n try {\n m_remotePort = Integer.parseInt(remotePort);\n } catch (NumberFormatException n) {\n m_remotePort = -1;\n }\n }\n\n\n\n\n}\n"
},
{
"type": "TEXT",
"name": "BandwidthTester.java",
"content": "package org.jaa.bandwidthtester;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.PrintStream;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.*;\n\n/**\n *\n * @author jerry\n */\npublic class BandwidthTester {\n private static final String[] iperf3Executables = {\n \"/usr/jaalocal/bin/iperf3\",\n \"/usr/local/bin/iperf3\",\n \"/usr/bin/iperf3\",\n \"/bin/iperf3\",\n \"/opt/local/bin/iperf3\",\n \"C:/Program Files/iperf3.17.1_64/iperf3.exe\",\n \"C:/Program Files/iperf3-3.17.1_64/iperf3.exe\",\n \"C:/Program Files/iperf3.12_64/iperf3.exe\",\n \"C:/Program Files/iperf-3.1.3-win64/iperf3.exe\"};\n\n private static final List<ResultDetails> averageResults = new ArrayList<>();\n private static TerminalType termType = null;\n private static Args myArgs = null;\n private static boolean cleanExit = false;\n\n /**\n * @return find the preferred iperf3 executable\n */\n private static String findIPerf3() {\n String ip = null;\n for (String exe : iperf3Executables) {\n File f = new File(exe);\n if (f.exists() && f.canExecute()) {\n ip = exe;\n break;\n }\n }\n if (ip == null) {\n System.out.println(\"Cannot find iperf3!\");\n System.exit(1);\n }\n return ip;\n }\n\n\n /**\n * @param myArgs Command-line arguments\n * @param noBuffer whether to use buffering (iperf3 will not buffer output)\n * @return command-line arguments for iperf3\n */\n private static String[] prepareIPerfExe(Args myArgs, boolean noBuffer) {\n List<String> args = new ArrayList<>();\n String[] ret = {\n findIPerf3(),\n (!noBuffer ? \"--forceflush\" : \"\"),\n (!noBuffer ? \"--connect-timeout\" : \"\"),\n (!noBuffer ? \"3000\" : \"\"),\n \"-c\",\n myArgs.client,\n myArgs.omit,\n myArgs.parallel,\n \"-t\",\n Integer.toString(myArgs.times),\n (myArgs.reverse ? \"-R\" : \"\"),\n };\n args.addAll(Arrays.asList(ret));\n args.addAll(Arrays.asList(myArgs.getRemainingArgs()));\n return args.toArray(new String[0]);\n }\n\n\n public static void main(String[] args) {\n Runtime.getRuntime().addShutdownHook(new Thread(() -> {\n if (!cleanExit) System.out.println(\"\\n\\033[31mShutdown hook ran\\033[0m!\");\n }));\n\n termType = new TerminalType();\n myArgs = processArgs(args);\n if (myArgs.client.isEmpty()) {\n System.out.print(\"Must supply iperf3 server name: \");\n Scanner sc = new Scanner(System.in);\n myArgs.client = sc.nextLine();\n if (myArgs.client.isEmpty()) {\n usage();\n return;\n }\n }\n\n myArgs.setTermType(termType);\n OS.setWindowsConsoleMode(myArgs);\n int rc = -999;\n\n\n String[] iperf3cmdLine = prepareIPerfExe(myArgs, false);\n\n\n if (myArgs.repeat == 0) {\n System.out.printf(\"\\n[%s%s%s]%s%15.15s%s%s: \",\n AnsiCodes.ANSI_COLOR.GREEN.getReverseBoldCode(myArgs.getTermType()),\n new Date(),\n AnsiCodes.getReset(myArgs.getTermType()),\n AnsiCodes.ANSI_COLOR.PURPLE.getReverseBoldCode(myArgs.getTermType()),\n \" \",\n \"Executing\",\n AnsiCodes.getReset(myArgs.getTermType()));\n ResultDetails resultDetails = new ResultDetails();\n rc = IPerf3Monitor.run(iperf3cmdLine, myArgs, resultDetails, true);\n if (rc == 999) {\n iperf3cmdLine = prepareIPerfExe(myArgs, true);\n IPerf3Monitor.run(iperf3cmdLine, myArgs, resultDetails, true);\n }\n\n } else {\n int loop = 0;\n\n while (loop < myArgs.getRepeat()) {\n boolean showOutput = (loop == 0);\n Date currentDate = new Date();\n System.out.printf(\"\\n[%s%s%s]%s%15.15s%s%d%s%d%40.40s%s: \",\n AnsiCodes.ANSI_COLOR.GREEN.getReverseBoldCode(myArgs.getTermType()),\n currentDate,\n AnsiCodes.getReset(myArgs.getTermType()),\n AnsiCodes.ANSI_COLOR.PURPLE.getReverseBoldCode(myArgs.getTermType()),\n \" \",\n \"Execution #\",\n loop + 1,\n \" of \",\n myArgs.repeat,\n \" \",\n AnsiCodes.getReset(myArgs.getTermType()));\n ResultDetails resultDetails = new ResultDetails();\n rc = IPerf3Monitor.run(iperf3cmdLine, myArgs, resultDetails, showOutput);\n if (rc == -999) {\n iperf3cmdLine = prepareIPerfExe(myArgs, true);\n continue;\n }\n loop++;\n resultDetails.setRunDate(currentDate);\n averageResults.add(resultDetails);\n System.out.print(\" \");\n MonitorIPerf3Output.printLine(myArgs, 78);\n if (loop < (myArgs.getRepeat())) {\n System.out.print(\"pause between runs: 2 seconds ... \");\n try { //noinspection BusyWait\n Thread.sleep(2000); } catch (InterruptedException ignored) { /**/ }\n System.out.println(\"Done.\");\n }\n }\n }\n displayResults();\n cleanExit = true;\n System.exit(rc);\n }\n\n\n private static void displayResults() {\n if (termType == null || myArgs == null || averageResults.isEmpty()) return;\n Path resultsFile = Paths.get(\"results.txt\");\n try (PrintStream out = new PrintStream(Files.newOutputStream(resultsFile))) {\n System.out.printf(\"\\n\\n%sResults%s: [\\n\",\n AnsiCodes.ANSI_COLOR.PURPLE.getReverseBoldCode(myArgs.getTermType()),\n AnsiCodes.getReset(myArgs.getTermType()));\n out.println(\"\\n\\nResults: [\");\n for (int i = 0; i < averageResults.size(); i++) {\n ResultDetails r = averageResults.get(i);\n String color = AnsiCodes.ANSI_COLOR.RED.getCode(myArgs.getTermType());\n if (r.getRc() == 0) color = AnsiCodes.ANSI_COLOR.GREEN.getCode(myArgs.getTermType());\n String returnString = ((r.getRc() == 0) ? \"OK\" : (\"Error=\" + r.getRc()));\n LocalDateTime localDateTime = r.getRunDate().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime();\n String isoDate = localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);\n out.printf(\"\\t {%19.19s} => %s [%s]\",\n isoDate,\n returnString,\n r);\n\n\n System.out.printf(\"\\t {%s%19.19s%s} => %s%s%s [%s%s%s]\",\n AnsiCodes.ANSI_COLOR.BLUE.getCode(myArgs.getTermType()),\n isoDate,\n AnsiCodes.getReset(myArgs.getTermType()),\n color,\n returnString,\n AnsiCodes.getReset(myArgs.getTermType()),\n AnsiCodes.getBold(myArgs.getTermType()),\n r,\n AnsiCodes.getReset(myArgs.getTermType()));\n\n if (i < averageResults.size() - 1) { System.out.print(\", \"); }\n System.out.println();\n out.println();\n }\n System.out.print(\"\\n\\t ]\\n\");\n out.print(\"\\n\\t ]\\n\");\n averageResults.clear();\n System.out.printf(\"Output is saved to file: %s%s%s\\n\",\n AnsiCodes.ANSI_COLOR.BLUE.getCode(myArgs.getTermType()),\n resultsFile.toAbsolutePath(),\n AnsiCodes.getReset(myArgs.getTermType()));\n } catch (IOException e) {\n System.err.printf(\"Error writing to %s: %s\\n\", resultsFile.toAbsolutePath(), e.getMessage());\n }\n }\n \n private static Args processArgs(String[] a) {\n \n Args args = new Args();\n args.client = \"\";\n args.omit = \"-O 2\";\n args.parallel = \"-P 8\";\n args.times = 10;\n int argc = 0;\n while (argc < a.length) {\n String arg = a[argc];\n String argVal = null;\n if (argc < a.length - 1) {\n argVal = a[argc+1];\n }\n if (!arg.startsWith(\"-\") && argc == 0) {\n args.client = arg;\n } else {\n String argSwitch = arg;\n if (arg.length() > 2) {\n argSwitch = arg.substring(0,2);\n }\n switch (argSwitch) {\n case \"-R\":\n args.reverse = true;\n break;\n case \"-O\":\n if (arg.length() > 2) {\n args.omit = arg;\n } else {\n if (argVal != null) {\n args.omit = \"-O \" + argVal;\n argc++;\n } else {\n usage();\n }\n }\n break;\n case \"-c\":\n if (arg.length() > 2) {\n args.client = arg.substring(2);\n } else {\n if (argVal != null) {\n args.client = argVal;\n argc++;\n } else {\n usage();\n }\n }\n break;\n case \"-P\":\n if (arg.length() > 2) {\n args.parallel = arg;\n if (arg.substring(2).equals(\"1\")) {\n args.single = true;\n }\n } else {\n if (argVal != null) {\n if (argVal.equals(\"1\")) {\n args.single = true;\n }\n args.parallel = \"-P \" + argVal;\n argc++; \n } else {\n usage();\n }\n }\n break;\n case \"-t\":\n if (arg.length() > 2) {\n try {\n args.times = Integer.parseInt(arg.substring(2));\n } catch (NumberFormatException ne) {\n System.out.printf(\"Invalid numeric format for '-t': %s\\n\", arg);\n usage();\n }\n } else {\n if (argVal != null) {\n try {\n args.times = Integer.parseInt(argVal);\n argc++;\n } catch (NumberFormatException e) {\n System.out.printf(\"Invalid numeric format for '-t': %s\\n\", argVal);\n usage();\n }\n } else {\n usage();\n }\n }\n break;\n case \"-l\":\n if (arg.length() > 2) {\n try {\n args.repeat = Integer.parseInt(arg.substring(2));\n } catch (NumberFormatException ne) {\n System.out.printf(\"Invalid numeric format for '-l': %s\\n\", arg);\n usage();\n }\n } else {\n if (argVal!= null) {\n try {\n args.repeat = Integer.parseInt(argVal);\n } catch (NumberFormatException e) {\n System.out.printf(\"Invalid numeric format for '-l': %s\\n\", argVal);\n usage();\n }\n } else {\n usage();\n }\n argc++;\n }\n break;\n case \"-v\":\n args.verbose=true;\n break;\n case \"-d\":\n args.debug=true;\n args.verbose=true;\n break;\n default:\n args.remainingArgs.append(arg).append(\" \");\n break;\n }\n }\n argc++;\n }\n return args;\n }\n\n private static void usage() {\n System.out.println(\"Bad command-line arguments!\");\n System.exit(1);\n }\n}\n"
},
{
"type": "TEXT",
"name": "Args.java",
"content": "package org.jaa.bandwidthtester;\n\n/*\n * Click njbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license\n * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template\n */\n\n/**\n *\n * @author jerry\n */\n\npublic class Args {\n public String client;\n public String omit;\n public String parallel;\n public int times=0;\n public int repeat=0;\n public boolean verbose = false;\n public boolean debug = false;\n public boolean single = false;\n public boolean reverse = false;\n \n public final StringBuilder remainingArgs = new StringBuilder();\n \n private TerminalType m_termType;\n public void setTermType(TerminalType termType) { m_termType = termType; }\n public TerminalType getTermType() { return m_termType; }\n public boolean isVerbose() { return verbose; }\n public boolean isDebug() { return debug; }\n\n public int getRepeat() { return repeat; }\n public String[] getRemainingArgs() {\n return remainingArgs.toString().split(\"\\\\s+\");\n }\n}\n"
},
{
"type": "TEXT",
"name": "AnsiCodes.java",
"content": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage org.jaa.bandwidthtester;\n\n\n/**\n *\n * @author jerry\n */\npublic final class AnsiCodes\n{\n\n private AnsiCodes() { /**/ }\n\n private static final String ANSI_BOLD = \"\\033[1m\";\n\n private static final String ANSI_RESET = \"\\033[0m\";\n private static final String ANSI_CLEAR_TO_EOL = \"\\033[K\";\n private static final String CR = \"\\015\";\n private static final String BACKSPACE = \"\\010\";\n\n\n\n public static String getHorizontalLine(TerminalType term) { return term.ANSI_LINE; }\n public static String getBold(TerminalType term) { return (term.isAnsiTerm() ? ANSI_BOLD : \"\"); }\n public static String getClearToEOL(TerminalType term) { return (term.isAnsiTerm() ? ANSI_CLEAR_TO_EOL : \"\"); }\n public static String getCR(TerminalType term) { return (term.isAnsiTerm() ? CR: \"\"); }\n\n public static String getReset(TerminalType term) { return (term.isAnsiTerm() ? ANSI_RESET : \"\"); }\n public static String getBackSpace(TerminalType term) { return (term.isAnsiTerm() ? BACKSPACE : \"\"); }\n\n\n public static String gotoColumn(TerminalType term, int col) { return (term.isAnsiTerm() ? String.format(\"\\033[%dG\", col) : \"\"); }\n // standard ANSI color sequences\n @SuppressWarnings(\"unused\")\n public enum ANSI_COLOR\n {\n BLACK, RED, GREEN, YELLOW, BLUE, PURPLE, CYAN, GREY;\n private static final int BASE_COLOR_CODE = 30;\n private static final int BASE_HIGHLIGHT_CODE = 40;\n\n public int getValue() { return this.ordinal(); }\n public String getCode(TerminalType termType) { return ((termType.getTerm() == TerminalType.TERM.ANSI) ? String.format(\"\\033[%dm\", getValue() + BASE_COLOR_CODE) : \"\"); }\n public String getBoldCode(TerminalType termType) { return (termType.getTerm() == TerminalType.TERM.ANSI ? String.format(\"\\033[%d;1m\", getValue() + BASE_COLOR_CODE) : \"\"); }\n public String getHighlightCode(TerminalType termType) { return ((termType.getTerm() == TerminalType.TERM.ANSI) ? String.format(\"\\033[%dm\", getValue() + BASE_HIGHLIGHT_CODE) : \"\"); }\n public String getReverseHighlightCode(TerminalType termType) { return ((termType.getTerm() == TerminalType.TERM.ANSI) ? String.format(\"\\033[%d;1m\", getValue() + BASE_HIGHLIGHT_CODE) : \"\"); }\n public String getReverseBoldCode(TerminalType termType) { return ((termType.getTerm() == TerminalType.TERM.ANSI) ? String.format(\"\\033[%d;7m\", getValue() + BASE_COLOR_CODE) : \"\"); }\n }\n}\n\n\n"
},
{
"type": "TEXT",
"name": "results.txt",
"content": "\n\nResults: [\n\t {2025-11-28T11:48:17} => OK [min=1.42\u001b[0m\u001b[1m Gbits/sec\u001b[0m, max=1.54\u001b[0m\u001b[1m Gbits/sec\u001b[0m, avg=1.49 Gbits/sec]\n\t {2025-11-28T11:48:23} => OK [min=1.43\u001b[0m\u001b[1m Gbits/sec\u001b[0m, max=1.51\u001b[0m\u001b[1m Gbits/sec\u001b[0m, avg=1.46 Gbits/sec]\n\t {2025-11-28T11:48:29} => OK [min=1.46\u001b[0m\u001b[1m Gbits/sec\u001b[0m, max=1.49\u001b[0m\u001b[1m Gbits/sec\u001b[0m, avg=1.47 Gbits/sec]\n\t {2025-11-28T11:48:35} => OK [min=1.28\u001b[0m\u001b[1m Gbits/sec\u001b[0m, max=1.43\u001b[0m\u001b[1m Gbits/sec\u001b[0m, avg=1.38 Gbits/sec]\n\n\t ]\n"
},
{
"type": "TEXT",
"name": "run.sh",
"content": "#!/usr/bin/env bash\nARTIFACT=BandWidthTester\nVERSION=1.0-SNAPSHOT\nWITHDEP=all\nprintf \"[\\033[32;7mSTAGE 1\\033[0m] \\033[33m-------------------------------<\\033[0m \\033[32;7mBUILDING\\033[0m ... \\033[33m>-------------------------------\\033[0m\\n\"\n\ngradle clean shadowJar; RC=$?\nif [[ $RC -eq 0 ]]; then\n echo\n echo\n if [[ $RC -eq 0 ]]; then\n printf \"[\\033[32;7mSTAGE 2\\033[0m] \\033[33m--------------------------------<\\033[0m \\033[32;7mRUNNING\\033[0m ... \\033[33m>-------------------------------\\033[0m\\n\"\n\tjava -jar build/libs/BandWidthTester-1.0-SNAPSHOT-all.jar \"$@\"\n fi\t\n echo\n if [[ $RC -eq 0 ]]; then\n printf \"[\\033[32;7mCOMPLETE\\033[0m] \\033[32;1mSUCCESS\\033[0m\\n\"\n else\n printf \"[\\033[32;7mCOMPLETE\\033[0m] \\0033[31;1mFAILED\\033[0m\\n\"\n fi\nelse\n printf \"[\\033[31;7mCOMPLETE\\033[0m] \\033[31;1mFAILED\\033[0m\\n\"\nfi\necho\n"
},
{
"type": "TEXT",
"name": "newTestBandWidth.sh",
"content": "#!/usr/bin/env bash\njava -jar /usr/local/lib/BandWidthTester.jar \"$@\"\n"
},
{
"type": "TEXT",
"name": "install.sh",
"content": "#!/usr/bin/env bash\nARTIFACT=BandWidthTester\nVERSION=1.0-SNAPSHOT\nWITHDEP=all\nprintf \"[\\033[32;7mSTAGE 1\\033[0m] \\033[33m-------------------------------<\\033[0m \\033[32;7mBUILDING\\033[0m ... \\033[33m>-------------------------------\\033[0m\\n\"\n\ngradle clean shadowJar; RC=$?\nif [[ $RC -eq 0 ]]; then\n echo\n echo\n printf \"[\\033[32;7mSTAGE 2\\033[0m] \\033[33m----------------------- <\\033[0m \\033[32;7mInstalling\\033[0m: \\033[35m/usr/local/lib/${ARTIFACT}.jar \\033[0m \\033[33m>-----------------------\\033[0m\\n\"\n echo \"sudo cp -p build/${ARTIFACT}-${VERSION}-${WITHDEP}.jar /usr/local/lib/${ARTIFACT}.jar\"\n sudo cp -p build/libs/${ARTIFACT}-${VERSION}-${WITHDEP}.jar /usr/local/lib/${ARTIFACT}.jar; RC=$?\n if [[ $RC -eq 0 ]]; then\n \techo \"sudo cp -p newTestBandWidth.sh /usr/local/lib/\"\n \tsudo cp -p newTestBandWidth.sh /usr/local/bin/; RC=$?\n fi\t\n echo\n if [[ $RC -eq 0 ]]; then\n printf \"[\\033[32;7mCOMPLETE\\033[0m] \\033[32;1mSUCCESS\\033[0m\\n\"\n else\n printf \"[\\033[32;7mCOMPLETE\\033[0m] \\0033[31;1mFAILED\\033[0m\\n\"\n fi\nelse\n printf \"[\\033[31;7mCOMPLETE\\033[0m] \\033[31;1mFAILED\\033[0m\\n\"\nfi\necho\n"
}
],
"id": "c883d216-864a-475c-a7f3-fa302ac8dbcc",
"parent": "98877672-5b6a-4311-9cb5-d115cb9e53d1"
},
{
"convId": "8ed63031-5a89-4b18-b7a5-1b770b4349f3",
"type": "text",
"role": "assistant",
"content": "# Comprehensive Code Review – BandWidthTester \n*(project consisting of a Windows‑batch installer, several Bash helper scripts and a Java‑based command‑line wrapper around **iperf3**)* \n\n--- \n\n## 1. High‑level Architecture \n\n| Component | Purpose | Comments |\n|-----------|---------|----------|\n| **install.bat / install.sh / run.sh / newTestBandWidth.sh** | Simple build‑and‑install wrappers for Windows and *nix. | Mostly duplicated logic, uses hard‑coded paths, no error‑handling, and mixes ANSI escape sequences with plain `echo`. |\n| **BandWidthTester (Java)** | Parses CLI args, discovers the `iperf3` binary, spawns it, parses its output and presents a coloured, column‑aligned summary. | The code works but is a classic “single‑file monolith” with many responsibilities tangled together (argument parsing, terminal handling, OS‑specific quirks, conversion utilities, UI rendering). |\n| **Helper classes** (`Args`, `TerminalType`, `OS`, `AnsiCodes`, `Executor`, `Launcher`, `MonitorIPerf3Output`, `ConnectionDetails`, `ResultDetails`, `IPerf3Monitor`) | Split the monolith but still highly coupled; a lot of mutable state, many static fields, and a mix of UI and business logic. | The coupling makes unit‑testing difficult, and several classes expose internal state that is mutated from many places (e.g. `ConnectionDetails`). |\n\n---\n\n## 2. Build & Install Scripts \n\n### 2.1 `install.bat` \n\n| Issue | Details | Recommendation |\n|-------|---------|----------------|\n| **Hard‑coded paths** – `copy target\\%ARTIFACT%-%VERSION%-%WITHDEP%.jar %USERPROFILE%/bin/%ARTIFACT%.jar` | Works only on a Windows user with a `bin` folder under `%USERPROFILE%`. | Use `%APPDATA%` or let the user specify a destination via a command‑line argument. |\n| **ANSI escape handling** – uses `prompt $E` hack to obtain the ESC character. | Unreliable on older Windows versions (pre‑10) and on systems where `cmd.exe` is not the default shell. | Prefer PowerShell (`Write-Host`) or use a small Java installer that prints coloured output directly. |\n| **No error checking** after `copy`. | Failure to copy will silently leave the installer “successful”. | Check the return code (`IF %ERRORLEVEL% NEQ 0`) and abort with a clear message. |\n| **Mixed `@` and plain commands** – some lines are prefixed with `@`, others not. | Inconsistent output (some commands echo). | Either use `@echo off` at the top and prefix with `@` only when you really want to hide the line, or remove all `@` and let the script be explicit. |\n\n### 2.2 Bash scripts (`run.sh`, `install.sh`, `newTestBandWidth.sh`) \n\n| Issue | Details | Recommendation |\n|-------|---------|----------------|\n| **Duplicate logic** – `install.sh` and `run.sh` both rebuild the JAR and then run it. | Maintenance burden; a change to the Gradle command must be mirrored. | Create a single *build* script that accepts a flag (`--install` or `--run`). |\n| **Hard‑coded artifact name & version** – `ARTIFACT=BandWidthTester`, `VERSION=1.0-SNAPSHOT`. | Requires editing the script for every release. | Derive version from `gradle -q printVersion` or read from `gradle.properties`. |\n| **Copy with `sudo` without checking for success** – the script prints the `sudo cp` command *before* it runs it, then overwrites `$?` with the second copy result. | The user cannot know which step actually failed. | Capture each step’s exit code separately and print a concise summary at the end. |\n| **ANSI escape typo** – `\\0033[31;1mFAILED` (missing backslash) in `install.sh`. | Results in garbage characters on failure. | Fix to `\\033[31;1mFAILED`. |\n| **No `set -e`** – the script continues after a failure (e.g. Gradle error). | Leads to confusing “success” messages even when the build failed. | Add `set -euo pipefail` at the top, or manually check `$?` after each command. |\n| **Use of `printf` with hard‑coded escape sequences** – not portable to `sh` on macOS (which may use `dash`). | Some shells don’t interpret `\\033` inside `printf`. | Use `$'\\033'` syntax or rely on `tput` for colors. |\n\n---\n\n## 3. Java Source – General Observations \n\n| Category | Positive Points | Problems / Risks | Suggested Refactor |\n|----------|----------------|------------------|--------------------|\n| **Package Structure** | All classes reside under `org.jaa.bandwidthtester`. | No sub‑packages (e.g. `ui`, `model`, `util`) → everything is flat, making it hard to locate related code. | Introduce logical sub‑packages: `ui`, `model`, `service`, `util`. |\n| **Mutable Global State** | `static TerminalType termType`, `static Args myArgs`, `static List<ResultDetails> averageResults`. | Global mutable state makes the program non‑re‑entrant and difficult to test. | Pass needed objects as method parameters; keep `main` thin. |\n| **Argument Parsing** (`processArgs`) | Handles most common iperf3 switches, supports short combined forms (`-O2`). | • Manual string manipulation – error‑prone.<br>• No validation of unknown switches (they are silently added to `remainingArgs`).<br>• Uses `StringBuilder.split(\"\\\\s+\")` – may produce empty strings if there are multiple spaces.<br>• Does not support `--` separator, quoting, or long options (`--reverse`). | Use a mature library (Apache Commons CLI, JCommander, picocli). This gives automatic help/usage generation, validation, and cleaner code. |\n| **Error Handling** | Mostly prints to `System.out` or `System.err`. | • Swallows many `IOException`s (e.g. in `Executor.execCommand`).<br>• In `Launcher.run`, the thread silently continues after an `IOException` (only prints stack trace).<br>• In `OS.setWindowsConsoleMode`, catches `NoClassDefFoundError` to detect non‑Windows JNA availability – not a reliable way. | Propagate exceptions up to `main` and exit with a non‑zero code, or wrap them in a custom `BandwidthTesterException`. Log using `java.util.logging` or SLF4J. |\n| **Concurrency** | Uses two `Launcher` threads for stdout/stderr and a blocking queue to buffer lines. | • No back‑pressure handling – if the queue fills, `offer` may drop lines silently (`ArrayBlockingQueue.offer` returns false).<br>• The `Executor` never joins the `Launcher` threads if an exception occurs early, potentially leaving them hanging. | Use `LinkedBlockingQueue` (unbounded) or a proper producer/consumer pattern with `put`. Ensure threads are always `join`ed in a `finally` block. |\n| **Magic Numbers / Hard‑coded Constants** | `leftColumnMarker = 30`, `rightColumnMarker` derived later, `tick = {\"-\",\"/\",\"+\",\"\\\\\"}`. | No documentation of why those numbers were chosen; they break when terminal width changes. | Move UI constants to a dedicated `UiConstants` class and expose them for configuration (e.g. via CLI `--width`). |\n| **Terminal & ANSI handling** (`TerminalType`, `AnsiCodes`) | Attempts to detect UTF‑8 vs. DUMB terminals, and switches to plain ASCII on non‑UTF. | • The detection logic runs *once* at construction; if `TERM` changes later (rare) it won’t adapt.<br>• Uses JNA on Windows to force UTF‑8; this fails on JREs without JNA on the classpath (silently caught).<br>• `TerminalType` stores mutable public fields (`String VERTICAL_BAR = \"│\"` etc.) – they’re overwritten in the constructor. This violates encapsulation. | • Make the fields `final` and compute the “fallback” strings in a separate immutable `TerminalStyle` object.<br>• Decouple Windows console handling from `TerminalType` – put it into a dedicated `ConsoleConfigurator`. |\n| **Result aggregation** (`ResultDetails`, `ConnectionDetails`) | Provides min/max/avg fields, conversion utilities, and a human‑readable formatter. | • `ResultDetails` stores raw strings rather than numeric values – makes later calculations impossible.<br>• `ConnectionDetails` mixes UI state (`isColored`) with data (`minBitsPerSec`).<br>• Several public mutators (`setMinBitsBytesPerSec`) perform side‑effects (verbose printing) – violates Single Responsibility Principle. | • Create a pure data class `Result` with numeric fields and a separate `ResultFormatter`.<br>• Keep `ConnectionDetails` as a *model* (only data) and move UI rendering to `MonitorIPerf3Output`. |\n| **Logging / Verbosity** | Uses `if (args.verbose) System.out.printf(...)`. | Scattered `System.out` statements make it hard to control output format (e.g., redirect to a file). | Replace ad‑hoc prints with a logger (`java.util.logging` or SLF4J) and configure levels (`INFO`, `DEBUG`, `WARN`). |\n| **Testing** | None – there are no unit or integration tests. | Hard to guarantee correctness after refactoring; parsing of iperf3 output is fragile. | Add tests for: <br>• Argument parsing (valid/invalid combos).<br>• `TerminalType` detection logic (mock env vars).<br>• `convertToHumanReadable` edge cases (different units).<br>• `MonitorIPerf3Output.processLine` using sample iperf3 lines. |\n| **Java Version / Dependencies** | Uses only JDK standard libs **plus** JNA (for Windows console). | JNA is optional but not declared in `build.gradle`; the code catches `NoClassDefFoundError`. | Explicitly declare JNA as a compile‑time dependency, or isolate it behind a `WindowsConsole` service that is loaded only on Windows. |\n| **Resource Management** | `Launcher` closes the `BufferedReader` only when the thread ends; streams are never explicitly closed. | On abrupt termination (e.g., `System.exit`) the process may leak file descriptors. | Use try‑with‑resources in `Launcher.run` or close streams in a `finally` block. |\n| **String Concatenation in Loops** | Frequent use of `StringBuilder` for building command line, but also many `+` concatenations in `printf` statements. | Minor performance impact, but readability suffers. | Use `String.format` consistently, or keep the `StringBuilder` approach for building commands only. |\n| **Hard‑coded Paths to iperf3** (`iperf3Executables` array) | Good fallback list, but Windows entries contain spaces and no quoting. | When `Runtime.exec(String[])` receives a path with spaces, it works, but the path strings lack escaping for shells (if later switched to `exec(String)`). | Keep the array but also allow the user to override via env var `IPERF3_PATH` or CLI `--iperf3`. |\n| **Exit Codes** | Returns `rc` from `IPerf3Monitor.run`. | When an exception occurs the code falls back to `-1` but the `main` method may still exit with a previous `rc`. | Consolidate exit handling: always call `System.exit(exitCode)` once, after `displayResults`. |\n| **Formatting / Internationalisation** | Uses hard‑coded English messages and fixed width format strings (`%15.15s`). | Not i18n‑ready, and fixed widths break on wide Unicode characters (e.g., fancy arrows). | Externalise user‑visible strings to a `messages.properties` file and use `MessageFormat`. |\n| **Code Comments & Documentation** | Some classes have auto‑generated NetBeans headers, but most methods lack Javadoc. | New developers cannot quickly understand the intent. | Add Javadoc for public APIs and a high‑level design document (README) describing the flow: *args → executor → launcher → monitor → UI*. |\n\n---\n\n## 4. Specific Problem Areas & Suggested Fixes \n\nBelow are concrete patches (or pseudo‑code) for the most critical issues.\n\n### 4.1 Argument Parsing – Replace with **picocli**\n\n```java\n// Add dependency (Gradle)\nimplementation \"info.picocli:picocli:4.7.5\"\n\n@Command(name = \"BandWidthTester\",\n mixinStandardHelpOptions = true,\n description = \"Runs iperf3 and formats the output.\")\npublic class BandwidthTester implements Callable<Integer> {\n\n @Parameters(index = \"0\", description = \"iperf3 server host\")\n private String server;\n\n @Option(names = \"-O\", description = \"Omit first N seconds\", defaultValue = \"2\")\n private int omit;\n\n @Option(names = \"-P\", description = \"Parallel streams\", defaultValue = \"8\")\n private int parallel;\n\n @Option(names = \"-t\", description = \"Test duration (seconds)\", defaultValue = \"10\")\n private int duration;\n\n @Option(names = \"-R\", description = \"Reverse mode\")\n private boolean reverse;\n\n @Option(names = \"-l\", description = \"Repeat count\")\n private int repeat = 0;\n\n @Option(names = \"-v\", description = \"Verbose output\")\n private boolean verbose;\n\n @Option(names = \"-d\", description = \"Debug (implies verbose)\")\n private boolean debug;\n\n @Option(names = \"--no-buffer\", description = \"Do not force iperf3 output buffering\")\n private boolean noBuffer;\n\n @Parameters(arity = \"0..*\", description = \"Additional iperf3 arguments\")\n private List<String> extraArgs = Collections.emptyList();\n\n // inject the other services (Executor, OS, UI) via constructors or @Inject\n\n public static void main(String[] args) {\n int exitCode = new CommandLine(new BandwidthTester())\n .setCaseInsensitiveEnumValuesAllowed(true)\n .execute(args);\n System.exit(exitCode);\n }\n\n @Override\n public Integer call() throws Exception {\n // build args object, configure terminal, run monitor …\n return 0;\n }\n}\n```\n\n*Benefits*: automatic `--help`, validation, default values, no manual `String` slicing, and the code in `processArgs` can be removed entirely.\n\n### 4.2 Decouple UI Rendering \n\nCreate a `UiRenderer` interface:\n\n```java\npublic interface UiRenderer {\n void renderHeader(String stage, String message);\n void renderProgress(String line);\n void renderResult(ResultDetails result);\n void renderError(String message);\n}\n```\n\nImplement two versions:\n\n| Implementation | When used |\n|----------------|-----------|\n| `AnsiUiRenderer` – uses `AnsiCodes` and terminal‑size detection. | Default on ANSI terminals. |\n| `PlainUiRenderer` – prints plain text, no escape sequences. | When `TERM=dumb` or on Windows without JNA. |\n\nAll calls in `MonitorIPerf3Output`, `IPerf3Monitor`, and `BandWidthTester` go through the renderer, eliminating scattered `System.out.printf` statements.\n\n### 4.3 Refactor `ConnectionDetails` → Immutable Model + Builder \n\n```java\npublic final class ConnectionInfo {\n private final String localHost;\n private final String remoteHost;\n private final int localPort;\n private final int remotePort;\n private final boolean singleThread;\n // other immutable fields …\n\n private ConnectionInfo(Builder b) { … }\n\n public static class Builder {\n private String localHost = \"\";\n private String remoteHost = \"\";\n private int localPort = -1;\n private int remotePort = -1;\n private boolean singleThread = false;\n // setters returning Builder\n\n public ConnectionInfo build() { return new ConnectionInfo(this); }\n }\n}\n```\n\n`MonitorIPerf3Output` now receives a mutable “state” object (`ConnectionState`) that only holds UI‑related counters (`resultEntry`, `lastOmitted`, …). This separation makes the model testable and eliminates the need for a plethora of `setX` methods that also print debug messages.\n\n### 4.4 Safer Process Execution \n\n```java\nProcessBuilder pb = new ProcessBuilder(command);\npb.redirectErrorStream(true); // optional: merge stderr into stdout\npb.environment().putAll(customEnv); // if needed\nProcess proc = pb.start();\n```\n\n*Advantages*: \n\n* No need to manually manage `Runtime.exec`. \n* `ProcessBuilder` allows setting a working directory, redirecting streams, and more fine‑grained error handling. \n\n### 4.5 Queue Back‑pressure \n\nReplace `ArrayBlockingQueue.offer` with `put` (blocks until space is available) or use an **unbounded** `LinkedBlockingQueue`. \n\n```java\nwhile ((line = reader.readLine()) != null) {\n lines.put(line); // blocks if consumer is slower\n}\nlines.put(Launcher.EOF);\n```\n\nIn the consumer (`IPerf3Monitor`), handle `InterruptedException` properly and restore the thread’s interrupt status.\n\n### 4.6 Windows Console Configuration \n\nEncapsulate the JNA logic:\n\n```java\npublic final class WindowsConsole {\n private WindowsConsole() {}\n\n public static void enableVirtualTerminalProcessing() {\n // same JNA calls as before, but throw a checked exception on failure\n }\n}\n```\n\nCall it only when `OS.getMyOS() == OSTypes.WINDOWS && term.isAnsiTerm()`. If JNA is missing, catch `UnsatisfiedLinkError` and fallback gracefully.\n\n### 4.7 Result Formatting \n\nCreate a dedicated formatter:\n\n```java\npublic final class ResultFormatter {\n private static final double KB = 1024d;\n private static final double MB = KB * KB;\n // …\n\n public static String format(double value, boolean bits, boolean color, TerminalType term) {\n // same logic as convertToHumanReadable but without side‑effects\n }\n}\n```\n\n`ConnectionDetails` now only stores numeric min/max and passes them to the formatter when UI needs to display them.\n\n### 4.8 Logging \n\nAdd a simple logger wrapper:\n\n```java\npublic final class Log {\n private static final java.util.logging.Logger LOG =\n java.util.logging.Logger.getLogger(\"BandwidthTester\");\n\n public static void info(String fmt, Object... args) {\n LOG.info(String.format(fmt, args));\n }\n public static void debug(String fmt, Object... args) {\n if (ArgsHolder.get().isDebug()) {\n LOG.fine(String.format(fmt, args));\n }\n }\n // …\n}\n```\n\nReplace all `System.out.printf` used for *internal* diagnostics with `Log.debug`. Keep user‑facing output separate (via `UiRenderer`).\n\n### 4.9 Unit Tests (JUnit 5 example)\n\n```java\nclass TerminalTypeTest {\n\n @Test\n void detectsDumbTerminal() {\n try (MockedStatic<System> sys = mockStatic(System.class)) {\n sys.when(() -> System.getenv(\"TERM\")).thenReturn(\"dumb\");\n sys.when(() -> System.getenv(\"LANG\")).thenReturn(\"en_US.UTF-8\");\n TerminalType tt = new TerminalType();\n assertEquals(TerminalType.TERM.DUMB, tt.getTerm());\n assertTrue(tt.isUTF());\n }\n }\n\n @Test\n void convertsBitsToHumanReadable() {\n Args args = new Args(); // default (no debug)\n String out = ResultDetails.convertToHumanReadable(args, 1_500_000_000, true,\n \"%s\", \"%,.2f\", true);\n assertTrue(out.contains(\"1.40 GBits\"));\n }\n}\n```\n\nAdd similar tests for `ArgumentParser`, `ResultFormatter`, and the queue‑consumer logic.\n\n---\n\n## 5. Suggested Project Layout After Refactor \n\n```\nsrc/\n └─ main/\n └─ java/\n └─ org/\n └─ jaa/\n └─ bandwidthtester/\n ├─ cli/\n │ └─ BandwidthTester.java (picocli entry point)\n ├─ model/\n │ ├─ Args.java\n │ ├─ ConnectionInfo.java\n │ ├─ Result.java\n ├─ service/\n │ ├─ Executor.java\n │ ├─ Iperf3Runner.java\n │ ├─ WindowsConsole.java\n ├─ ui/\n │ ├─ UiRenderer.java\n │ ├─ AnsiUiRenderer.java\n │ ├─ PlainUiRenderer.java\n │ └─ Monitor.java\n ├─ util/\n │ ├─ AnsiCodes.java\n │ ├─ TerminalType.java\n │ └─ Log.java\n └─ Main.java (tiny wrapper that just calls the CLI)\n```\n\nThe `build.gradle` (or Maven POM) would declare:\n\n```gradle\ndependencies {\n implementation \"info.picocli:picocli:4.7.5\"\n implementation \"net.java.dev.jna:jna:5.13.0\" // optional, only on Windows\n testImplementation \"org.junit.jupiter:junit-jupiter:5.10.0\"\n}\n```\n\n---\n\n## 6. Security & Robustness \n\n| Issue | Impact | Fix |\n|-------|--------|-----|\n| **Unvalidated user input** – the server hostname is taken verbatim and passed to `iperf3`. | Could be abused to run arbitrary commands if the user supplies something like `\"; rm -rf /\"` on a shell‑based wrapper. | Since we now use `ProcessBuilder` with a *String[]* command, arguments are not interpreted by a shell, eliminating injection. |\n| **Running with `sudo` in install scripts** – `install.sh` copies files into `/usr/local/lib` without checking if the user has rights. | If the script is run unintentionally, it can overwrite system files. | Prompt for confirmation before `sudo cp`, or better, use a package manager (e.g., `brew` on macOS, `apt`/`yum` on Linux) to install the binary. |\n| **Hard‑coded temporary files** – none currently, but future extensions might use `/tmp`. | Potential race conditions. | Use `Files.createTempFile` and delete on exit. |\n| **JNA native calls** – may load native libraries from the system path. | If a malicious DLL is placed earlier on `PATH`, it could be loaded. | Load JNA with a specific library name (`kernel32`) and restrict the search path using `System.setProperty(\"jna.library.path\", ...)` if needed. |\n\n---\n\n## 7. Performance Considerations \n\n* **CPU** – The UI refresh logic prints many escape sequences (e.g., on each line of iperf3 output). On very high‑frequency tests (many parallel streams) this can become a bottleneck. \n *Solution*: Batch updates – accumulate a few lines and redraw once per 100 ms (already partially done via `pollInterval`), but also avoid `System.out.printf` inside tight loops. Use a `StringBuilder` and a single `System.out.print` per refresh. \n\n* **Memory** – `ArrayBlockingQueue` of size 1000 holds raw strings. If iperf3 outputs a huge burst (e.g., on a very fast network) the queue could fill and start dropping lines (`offer` returns false). \n *Solution*: Use an **unbounded** queue or increase the capacity; alternatively, process lines directly from the stream without intermediate buffering (e.g., `BufferedReader.lines().forEach(...)`). \n\n* **I/O** – The program writes the results file at the end with `PrintStream`. For many repetitions this is fine; for a long‑running daemon you would want a rolling log. \n\n---\n\n## 8. Documentation & README \n\n* Add a **project overview** section describing the flow (args → iperf3 → parser → UI). \n* Document **environment requirements** (Java 17+, iperf3 location, Windows console mode). \n* Provide a **quick‑start** guide: `./gradlew shadowJar && ./run.sh <host>` \n* Explain **how to override the iperf3 binary** (`export IPERF3_PATH=/opt/iperf3/iperf3`). \n* List **supported command‑line options** (generated automatically by picocli). \n\n---\n\n## 9. Summary of Action Items \n\n| # | Category | What to do |\n|---|----------|-------------|\n| 1 | Build scripts | Consolidate Bash scripts, add `set -e`, fix ANSI typo, make paths/versions configurable, add proper error handling. |\n| 2 | Windows installer | Replace the batch hack with a PowerShell script or a Java‑based installer; verify copy success. |\n| 3 | Argument parsing | Replace `processArgs` with picocli (or Commons CLI). |\n| 4 | Terminal handling | Refactor `TerminalType` into immutable style, separate Windows console configuration, expose a `UiRenderer` interface. |\n| 5 | Concurrency | Use `LinkedBlockingQueue` (or `put`) and ensure all threads are joined in a `finally`. |\n| 6 | Model / UI separation | Make `ConnectionInfo` immutable; move all UI rendering to `Monitor`/`UiRenderer`. |\n| 7 | Logging | Introduce a logger, replace ad‑hoc `System.out` debug prints. |\n| 8 | Error handling | Propagate exceptions up, exit with defined codes, avoid swallowing `IOException`. |\n| 9 | Testing | Add unit tests for argument parsing, terminal detection, unit conversion, and output parsing. |\n|10| Documentation | Write a proper README, generate help from picocli, document environment variables. |\n|11| Dependency management | Declare JNA explicitly, consider shading it only for Windows, or make it optional. |\n|12| Code style | Apply consistent formatting (Google Java Style), add Javadoc, remove dead imports, rename ambiguous fields (`leftColumnMarker` → `LEFT_COLUMN_POS`). |\n\nImplementing these changes will:\n\n* **Increase reliability** (proper error handling, safe process execution). \n* **Make the codebase maintainable** (clear separation of concerns, testable units). \n* **Improve user experience** (consistent colors, graceful fallback on dumb terminals, clearer install script messages). \n* **Future‑proof** the project (easier to add new iperf3 options, switch to a different measurement tool, or embed into a GUI). \n\n--- \n\nFeel free to ask for concrete code samples for any of the refactorings above, or for guidance on setting up the test suite and CI pipeline. Happy coding!",
"timestamp": 1769703693154,
"thinking": "We need to provide an updated comprehensive code review of the whole project. Should discuss code quality, design, bugs, improvements, style, security, performance, platform compatibility, etc. Also note the batch file, scripts, etc. Provide suggestions for refactoring, error handling, logging, unit tests, dependency management, etc. Provide specific line references. Provide updated code snippets where appropriate. Let's produce structured review: Overview, Build scripts, Java source, specific classes, arguments parsing, terminal handling, OS handling, concurrency, error handling, magic numbers, naming, documentation, testing, etc. Provide recommendations.",
"toolCalls": "",
"children": [],
"model": "ggml-org/gpt-oss-120b-GGUF",
"id": "cb10d7e6-615c-45b3-8162-c68292101c1e",
"parent": "c883d216-864a-475c-a7f3-fa302ac8dbcc",
"timings": {
"cache_n": 0,
"prompt_n": 16290,
"prompt_ms": 15257.07,
"prompt_per_token_ms": 0.9365911602209944,
"prompt_per_second": 1067.7017277891496,
"predicted_n": 5963,
"predicted_ms": 168994.368,
"predicted_per_token_ms": 28.34049438202247,
"predicted_per_second": 35.28519956357363
}
}
]
}