├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle ├── src ├── main │ ├── java │ │ └── io │ │ │ └── twasyl │ │ │ └── jstackfx │ │ │ ├── JStackFX.java │ │ │ ├── beans │ │ │ ├── Dump.java │ │ │ ├── DumpTimeline.java │ │ │ ├── FileDump.java │ │ │ ├── InMemoryDump.java │ │ │ ├── Pair.java │ │ │ ├── ThreadElement.java │ │ │ └── ThreadReference.java │ │ │ ├── controllers │ │ │ └── JStackFXController.java │ │ │ ├── exceptions │ │ │ └── DumpException.java │ │ │ ├── factory │ │ │ ├── DumpFactory.java │ │ │ └── ThreadElementFactory.java │ │ │ ├── search │ │ │ ├── Comparator.java │ │ │ ├── FieldExpression.java │ │ │ ├── FieldExpressionQueue.java │ │ │ ├── Operand.java │ │ │ ├── Query.java │ │ │ └── exceptions │ │ │ │ ├── ConversionException.java │ │ │ │ ├── EvaluateException.java │ │ │ │ └── UnparsableQueryException.java │ │ │ └── ui │ │ │ ├── SearchField.java │ │ │ ├── TooltipUtils.java │ │ │ ├── cells │ │ │ ├── StateCell.java │ │ │ ├── StateCellFactory.java │ │ │ ├── ThreadElementRow.java │ │ │ ├── ThreadElementRowFactory.java │ │ │ └── ThreadListCellFactory.java │ │ │ └── charts │ │ │ ├── LocalDateTimeAxis.java │ │ │ ├── LockedSynchronizersRepartitionChart.java │ │ │ ├── StateRepartitionChart.java │ │ │ └── StateRepartitionTimelineChart.java │ └── resources │ │ └── io │ │ └── twasyl │ │ └── jstackfx │ │ ├── css │ │ └── default.css │ │ └── fxml │ │ └── jstackfx.fxml ├── site │ └── screenshots │ │ ├── JStackFX_01.png │ │ ├── JStackFX_02.png │ │ ├── JStackFX_03.png │ │ └── JStackFX_04.png └── test │ ├── java │ └── io │ │ └── twasyl │ │ └── jstackfx │ │ ├── factory │ │ ├── DumpFactoryTests.java │ │ └── ThreadElementFactoryTest.java │ │ ├── search │ │ ├── ComparatorTest.java │ │ ├── FieldExpressionQueueTest.java │ │ ├── FieldExpressionTest.java │ │ └── QueryTest.java │ │ └── ui │ │ └── charts │ │ ├── LockedSynchronizersRepartitionChartTest.java │ │ ├── StateRepartitionChartTest.java │ │ └── StateRepartitionTimelineChartTest.java │ └── resources │ ├── blocked.txt │ ├── intellij.txt │ ├── timeline_01.txt │ └── timeline_02.txt └── ui └── charts ├── LockedSynchronizersRepartitionChartTest.java ├── StateRepartitionChartTest.java └── StateRepartitionTimelineChartTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # IntelliJ IDEA files 2 | out 3 | .idea 4 | *.iml 5 | **/*.iml 6 | 7 | # gradle files 8 | .gradle/ 9 | gradle.properties 10 | **/gradle.properties 11 | build 12 | **/build/ 13 | 14 | # Error files generated when JavaFX crashes 15 | hs_err_* 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | sudo: true 4 | 5 | jdk: 6 | - oraclejdk8 7 | 8 | os: 9 | - linux 10 | 11 | git: 12 | depth: 5 13 | 14 | branches: 15 | only: 16 | - master 17 | 18 | script: 19 | - chmod +x ./gradlew 20 | - ./gradlew build 21 | - ./gradlew --stop 22 | 23 | cache: 24 | directories: 25 | - $HOME/.gradle/caches/ 26 | - $HOME/.gradle/wrapper/ 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Thierry Wasylczenko 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/twasyl/jstackfx.svg?branch=master)](https://travis-ci.org/twasyl/jstackfx) 2 | 3 | # Context 4 | 5 | It is not an easy task to analyse thread dumps as files generated by the `jstack` tool provides raw _text files_. 6 | This is why I'm developing **JStackFX**. 7 | 8 | # Requirements 9 | 10 | JStackFX requires the latest JDK 8 available on your system. 11 | 12 | # Build 13 | 14 | As JStackFX is currently under development, you can build it manually in order to have the latest version. In order to build it, ensure the JDK 8 is available and execute the following command: 15 | 16 | ```shell 17 | gradlew clean assemble 18 | ``` 19 | 20 | # Execution 21 | 22 | In order to start JStackFX, unzip the `build/distributions/JStackFX-.zip` archive and start a command line within the unzipped folder. Execute the following command: 23 | 24 | ```shell 25 | java -jar jstackfx-.jar 26 | ``` 27 | 28 | In order to start JStackFX and open directly a dumpTimeline file you can use the following command: 29 | 30 | ```shell 31 | java -jar jstackfx-.jar --file=/path/to/dumpTimeline.txt 32 | ``` 33 | 34 | In order to start JStackFX and make a thread dumpTimeline of a given process you can use the following command: 35 | 36 | ```shell 37 | java -jar jstackfx-.jar --pid= 38 | ``` 39 | 40 | **Warning:** if both `--pid` and `--file` parameters are used, `--file` is ignored. 41 | 42 | # Screenshot```` 43 | 44 | ![Screenshot of JStackFX](src/site/screenshots/JStackFX_01.png) 45 | ![Screenshot of JStackFX](src/site/screenshots/JStackFX_02.png) 46 | ![Screenshot of JStackFX](src/site/screenshots/JStackFX_03.png) 47 | ![Screenshot of JStackFX](src/site/screenshots/JStackFX_04.png) 48 | 49 | # Usage 50 | 51 | ## SearchingF 52 | 53 | Use the search bar in JStackFX to filter results. A query must have the following syntax: 54 | 55 | ```shell 56 | fieldName comparator value operand fieldName comparator value ... 57 | ``` 58 | 59 | * _fieldName_ can be: **state**, **number**, **threadId**, **priority** or **osPriority** 60 | * _comparator_ can be: **=**, **!=**, **<=**, **<**, **>=** or **>** 61 | * _operand_ can be: **and** or **or** 62 | 63 | Examples: 64 | 65 | * List all RUNNABLE threads:`state = runnable` 66 | * Display threads having number 10 or 20: `number = 10 or number = 20` 67 | * Display threads having number 10 or thread having number 20 and is in state BLOCKED: `number = 10 or number = 20 and state = blocked` 68 | 69 | # Release notes 70 | 71 | ## Version 1.3 72 | 73 | **New and noteworthy:** 74 | 75 | * Support for operators `<=`, `<`, `>=` and `>` 76 | * UI improvements 77 | 78 | ## Version 1.2 79 | 80 | **New and noteworthy:** 81 | 82 | * Display the number of results in the search bar 83 | * Allow to display thread elements' source from the dumpTimeline file 84 | * UX improvements 85 | 86 | ## Version 1.1 87 | 88 | **New and noteworthy:** 89 | 90 | * Adding a search bar for filtering results 91 | * Change the cursor when over a blocked or blocking thread in the table 92 | * Make some information of the thread copyable -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | group 'io.twasyl' 2 | version '@@NEXT-VERSION@@' 3 | 4 | apply plugin: 'java' 5 | apply plugin: 'distribution' 6 | 7 | sourceCompatibility = 1.8 8 | targetCompatibility = 1.8 9 | 10 | repositories { 11 | jcenter() 12 | } 13 | 14 | dependencies { 15 | compile 'de.jensd:fontawesomefx-octicons:4.3.0-1' 16 | testCompile 'junit:junit:4.12' 17 | } 18 | 19 | wrapper { 20 | gradleVersion = '3.2.1' 21 | } 22 | 23 | jar { 24 | manifest { 25 | attributes("Implementation-Title": "JStackFX", 26 | "Implementation-Version": version, 27 | "Implementation-Vendor": "Thierry Wasylczenko", 28 | "Main-Class": "io.twasyl.jstackfx.JStackFX", 29 | "JavaFX-Version": "8.0+", 30 | "Class-Path": configurations.compile.collect { it.getName() }.join(' ')) 31 | } 32 | } 33 | 34 | distributions { 35 | main { 36 | baseName = "JStackFX" 37 | contents { 38 | into('/') { 39 | from jar 40 | from project.configurations.compile 41 | } 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twasyl/jstackfx/10f98d24ec7a7f390fedb4cac1151f4a6e76bbc8/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.2.1-bin.zip 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStorePath=wrapper/dists 5 | zipStoreBase=GRADLE_USER_HOME 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | for s in "${@}" ; do 159 | s=\"$s\" 160 | APP_ARGS=$APP_ARGS" "$s 161 | done 162 | 163 | # Collect all arguments for the java command, following the shell quoting and substitution rules 164 | eval set -- "$DEFAULT_JVM_OPTS" "$JAVA_OPTS" "$GRADLE_OPTS" "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 165 | 166 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 167 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 168 | cd "$(dirname "$0")" 169 | fi 170 | 171 | exec "$JAVACMD" "$@" 172 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'jstackfx' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/JStackFX.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx; 2 | 3 | import io.twasyl.jstackfx.controllers.JStackFXController; 4 | import javafx.application.Application; 5 | import javafx.fxml.FXMLLoader; 6 | import javafx.scene.Parent; 7 | import javafx.scene.Scene; 8 | import javafx.scene.control.Alert; 9 | import javafx.scene.control.ButtonType; 10 | import javafx.stage.Stage; 11 | 12 | import java.io.File; 13 | import java.util.Map; 14 | 15 | /** 16 | * Application class of JStackFX. 17 | * 18 | * @author Thierry Wasylczenko 19 | * @since JStackFX 1.0 20 | */ 21 | public class JStackFX extends Application { 22 | protected static final String FILE_PARAMETER = "file"; 23 | protected static final String PID_PARAMETER = "pid"; 24 | 25 | private File fileToOpenAtStartup = null; 26 | private String pidToDumpAtStartup = null; 27 | 28 | @Override 29 | public void init() throws Exception { 30 | final Map parameters = getParameters().getNamed(); 31 | 32 | if (parameters.containsKey(PID_PARAMETER)) { 33 | this.pidToDumpAtStartup = parameters.get(PID_PARAMETER); 34 | } else if (parameters.containsKey(FILE_PARAMETER)) { 35 | this.fileToOpenAtStartup = new File(parameters.get(FILE_PARAMETER)); 36 | } 37 | } 38 | 39 | @Override 40 | public void start(Stage stage) throws Exception { 41 | final FXMLLoader loader = new FXMLLoader(JStackFX.class.getResource("/io/twasyl/jstackfx/fxml/jstackfx.fxml")); 42 | final Parent root = loader.load(); 43 | 44 | if (this.pidToDumpAtStartup != null) { 45 | final JStackFXController controller = loader.getController(); 46 | try { 47 | final long pid = Long.parseLong(this.pidToDumpAtStartup); 48 | controller.dumpPID(pid); 49 | } catch (Exception e) { 50 | final Alert errorDialog = new Alert(Alert.AlertType.ERROR, e.getMessage(), ButtonType.OK); 51 | errorDialog.setTitle("Can create thread dump for process " + this.pidToDumpAtStartup); 52 | errorDialog.showAndWait(); 53 | } 54 | } else if (this.fileToOpenAtStartup != null) { 55 | final JStackFXController controller = loader.getController(); 56 | try { 57 | controller.loadDumpFile(this.fileToOpenAtStartup); 58 | } catch (Exception e) { 59 | final Alert errorDialog = new Alert(Alert.AlertType.ERROR, e.getMessage(), ButtonType.OK); 60 | errorDialog.setTitle("Can not open dump file"); 61 | errorDialog.showAndWait(); 62 | } 63 | } 64 | 65 | final Scene scene = new Scene(root); 66 | 67 | stage.setScene(scene); 68 | stage.setTitle("JStackFX"); 69 | // stage.setMaximized(true); 70 | stage.show(); 71 | } 72 | 73 | public static void main(String[] args) { 74 | launch(args); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/beans/Dump.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.beans; 2 | 3 | import javafx.beans.property.*; 4 | import javafx.collections.FXCollections; 5 | import javafx.collections.ObservableList; 6 | import javafx.scene.text.Font; 7 | import javafx.scene.text.FontWeight; 8 | import javafx.scene.text.Text; 9 | 10 | import java.time.LocalDateTime; 11 | import java.time.format.DateTimeFormatter; 12 | import java.util.ArrayList; 13 | import java.util.HashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | import java.util.stream.Collectors; 17 | 18 | /** 19 | * Class representing a thread dump realized with the {@code jstack} tool. 20 | * 21 | * @author Thierry Wasylczenko 22 | * @since JStackFX 1.0 23 | */ 24 | public abstract class Dump { 25 | public static final DateTimeFormatter DATE_TIME_FORMATTER_OUTPUT = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"); 26 | 27 | protected final ObjectProperty generationDateTime = new SimpleObjectProperty<>(); 28 | protected final StringProperty description = new SimpleStringProperty(); 29 | protected final ListProperty elements = new SimpleListProperty<>(FXCollections.observableArrayList()); 30 | protected final IntegerProperty numberOfJNIRefs = new SimpleIntegerProperty(0); 31 | 32 | public ObjectProperty generationDateTimeProperty() { return generationDateTime; } 33 | public LocalDateTime getGenerationDateTime() { return generationDateTime.get(); } 34 | public void setGenerationDateTime(LocalDateTime generationDateTime) { this.generationDateTime.set(generationDateTime); } 35 | 36 | public StringProperty descriptionProperty() { return description; } 37 | public String getDescription() { return description.get(); } 38 | public void setDescription(String description) { this.description.set(description); } 39 | 40 | public ListProperty elementsProperty() { return elements; } 41 | public ObservableList getElements() { return elements.get(); } 42 | public void setElements(ObservableList elements) { this.elements.set(elements); } 43 | 44 | public IntegerProperty numberOfJNIRefsProperty() { return numberOfJNIRefs; } 45 | public int getNumberOfJNIRefs() { return numberOfJNIRefs.get(); } 46 | public void setNumberOfJNIRefs(int numberOfJNIRefs) { this.numberOfJNIRefs.set(numberOfJNIRefs); } 47 | 48 | /** 49 | * Count the number of threads that haven't a stack. 50 | * @return The number of threads without a stack. 51 | */ 52 | public long countThreadsWithoutStack() { 53 | return this.getElements().stream().filter(thread -> { 54 | final String callingStack = thread.getCallingStack(); 55 | return callingStack == null || callingStack.isEmpty(); 56 | }).count(); 57 | } 58 | 59 | /** 60 | * Counts the number of threads this dump contains which are in the given state. 61 | * @param state The state to match. 62 | * @return The number of threads in the provided state this dump contains. 63 | */ 64 | public long countNumberOfThreads(final Thread.State state) { 65 | return this.getElements().stream() 66 | .filter(thread -> thread.getState() == state) 67 | .count(); 68 | } 69 | 70 | /** 71 | * Get the number of thread by state. 72 | * @return A map containing for each state, the number of threads in this state. 73 | */ 74 | public Map countNumberOfThreadsByState() { 75 | 76 | return this.getElements().stream() 77 | .collect( 78 | Collectors.groupingBy( 79 | ThreadElement::getState, 80 | Collectors.counting())); 81 | } 82 | 83 | public List asText() { 84 | final List texts = new ArrayList<>(); 85 | 86 | final Font bold = Font.font("Helvetica", FontWeight.BOLD, 12); 87 | final Font normal = Font.font("Helvetica", FontWeight.NORMAL, 12); 88 | final Font code = Font.font("Courier New", FontWeight.NORMAL, 12); 89 | 90 | Text text = new Text("Generated at " + DATE_TIME_FORMATTER_OUTPUT.format(this.getGenerationDateTime())); 91 | text.setFont(bold); 92 | texts.add(text); 93 | 94 | text = new Text("\n" + this.getDescription() + "\n\n"); 95 | text.setFont(normal); 96 | texts.add(text); 97 | 98 | text = new Text("# of threads:"); 99 | text.setFont(bold); 100 | texts.add(text); 101 | 102 | text = new Text(" " + this.getElements().size() + "\n"); 103 | text.setFont(normal); 104 | texts.add(text); 105 | 106 | text = new Text("# of threads w/o stack:"); 107 | text.setFont(bold); 108 | texts.add(text); 109 | 110 | text = new Text(" " + this.countThreadsWithoutStack() + "\n"); 111 | text.setFont(normal); 112 | texts.add(text); 113 | 114 | text = new Text("# of JNI references:"); 115 | text.setFont(bold); 116 | texts.add(text); 117 | 118 | text = new Text(" " + this.getNumberOfJNIRefs() + "\n"); 119 | text.setFont(normal); 120 | texts.add(text); 121 | 122 | return texts; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/beans/DumpTimeline.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.beans; 2 | 3 | import javafx.beans.property.ListProperty; 4 | import javafx.beans.property.SimpleListProperty; 5 | import javafx.collections.FXCollections; 6 | import javafx.collections.ObservableList; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | /** 12 | * @author Thierry Wasylczenko 13 | * @since JStackFX @@NEXT-VERSION@@ 14 | */ 15 | public class DumpTimeline { 16 | 17 | private final ListProperty dumps = new SimpleListProperty<>(FXCollections.observableArrayList()); 18 | 19 | public ObservableList getDumps() { 20 | return dumps.get(); 21 | } 22 | 23 | public ListProperty dumpsProperty() { 24 | return dumps; 25 | } 26 | 27 | public void setDumps(ObservableList dumps) { 28 | this.dumps.set(dumps); 29 | } 30 | 31 | public List findThreads(final String threadId) { 32 | final List threads = new ArrayList<>(); 33 | 34 | this.dumps.forEach(dump -> { 35 | dump.getElements().forEach(element -> { 36 | if (threadId.equals(element.getThreadId())) { 37 | threads.add(element); 38 | } 39 | }); 40 | }); 41 | 42 | return threads; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/beans/FileDump.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.beans; 2 | 3 | import javafx.beans.property.ObjectProperty; 4 | import javafx.beans.property.SimpleObjectProperty; 5 | 6 | import java.io.File; 7 | 8 | /** 9 | * An implementation of {@link Dump} for thread dumps stored within files. 10 | * 11 | * @author Thierry Wasylczenko 12 | * @since JStackFX 1.0 13 | */ 14 | public class FileDump extends Dump { 15 | private ObjectProperty file = new SimpleObjectProperty<>(); 16 | 17 | public ObjectProperty fileProperty() { return file; } 18 | public File getFile() { return file.get(); } 19 | public void setFile(File file) { this.file.set(file); } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/beans/InMemoryDump.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.beans; 2 | 3 | import javafx.beans.property.ListProperty; 4 | import javafx.beans.property.SimpleListProperty; 5 | import javafx.collections.FXCollections; 6 | import javafx.collections.ObservableList; 7 | 8 | /** 9 | * An implementation of {@link Dump} for thread dumps realized in memory and which results haven't been stored within 10 | * a file. 11 | * 12 | * @author Thierry Wasylczenko 13 | * @since JStackFX 1.0 14 | */ 15 | public class InMemoryDump extends Dump { 16 | private final ListProperty lines = new SimpleListProperty<>(FXCollections.observableArrayList()); 17 | 18 | public ListProperty linesProperty() { return lines; } 19 | public ObservableList getLines() { return lines.get(); } 20 | public void setLines(ObservableList lines) { this.lines.set(lines); } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/beans/Pair.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.beans; 2 | 3 | /** 4 | * Simple class for associating two objects. 5 | * 6 | * @author Thierry Wasylczenko 7 | * @since JStackFX 1.0 8 | */ 9 | public class Pair { 10 | protected K value1; 11 | protected V value2; 12 | 13 | public Pair() { 14 | } 15 | 16 | public Pair(K value1, V value2) { 17 | this.value1 = value1; 18 | this.value2 = value2; 19 | } 20 | 21 | public K getValue1() { 22 | return value1; 23 | } 24 | 25 | public void setValue1(K value1) { 26 | this.value1 = value1; 27 | } 28 | 29 | public V getValue2() { 30 | return value2; 31 | } 32 | 33 | public void setValue2(V value2) { 34 | this.value2 = value2; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/beans/ThreadElement.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.beans; 2 | 3 | import javafx.beans.property.*; 4 | import javafx.collections.FXCollections; 5 | import javafx.collections.ObservableSet; 6 | import javafx.scene.control.ContextMenu; 7 | import javafx.scene.control.MenuItem; 8 | import javafx.scene.input.Clipboard; 9 | import javafx.scene.input.DataFormat; 10 | import javafx.scene.text.Font; 11 | import javafx.scene.text.FontWeight; 12 | import javafx.scene.text.Text; 13 | 14 | import java.util.*; 15 | 16 | /** 17 | * A thread element is a part in the thread dump that gives information about a thread. It typically has a number, 18 | * various IDs and priorities, a name, a state among others. 19 | * 20 | * @author Thierry Wasylczenko 21 | * @since JStackFX 1.0 22 | */ 23 | public class ThreadElement { 24 | final static Font bold = Font.font("Helvetica", FontWeight.BOLD, 12); 25 | final static Font normal = Font.font("Helvetica", FontWeight.NORMAL, 12); 26 | final static Font code = Font.font("Courier New", FontWeight.NORMAL, 12); 27 | 28 | protected final ObjectProperty dump = new SimpleObjectProperty<>(); 29 | protected final StringProperty name = new SimpleStringProperty(); 30 | protected final LongProperty number = new SimpleLongProperty(); 31 | protected final ObjectProperty state = new SimpleObjectProperty<>(); 32 | protected final StringProperty callingStack = new SimpleStringProperty(); 33 | protected final IntegerProperty priority = new SimpleIntegerProperty(); 34 | protected final IntegerProperty osPriority = new SimpleIntegerProperty(); 35 | protected final StringProperty threadId = new SimpleStringProperty(); 36 | protected final SetProperty lockedSynchronizers = new SimpleSetProperty<>(FXCollections.observableSet()); 37 | protected final SetProperty holdingLocks = new SimpleSetProperty<>(FXCollections.observableSet()); 38 | protected final SetProperty waitingToLock = new SimpleSetProperty<>(FXCollections.observableSet()); 39 | protected final SetProperty parkingReasons = new SimpleSetProperty<>(FXCollections.observableSet()); 40 | protected final StringProperty source = new SimpleStringProperty(); 41 | 42 | public ObjectProperty dumpProperty() { 43 | return dump; 44 | } 45 | 46 | public Dump getDump() { 47 | return dump.get(); 48 | } 49 | 50 | public void setDump(Dump dump) { 51 | this.dump.set(dump); 52 | } 53 | 54 | public StringProperty nameProperty() { 55 | return name; 56 | } 57 | 58 | public String getName() { 59 | return name.get(); 60 | } 61 | 62 | public void setName(String name) { 63 | this.name.set(name); 64 | } 65 | 66 | public LongProperty numberProperty() { 67 | return number; 68 | } 69 | 70 | public long getNumber() { 71 | return number.get(); 72 | } 73 | 74 | public void setNumber(long number) { 75 | this.number.set(number); 76 | } 77 | 78 | public ObjectProperty stateProperty() { 79 | return state; 80 | } 81 | 82 | public Thread.State getState() { 83 | return state.get(); 84 | } 85 | 86 | public void setState(Thread.State state) { 87 | this.state.set(state); 88 | } 89 | 90 | public StringProperty callingStackProperty() { 91 | return callingStack; 92 | } 93 | 94 | public String getCallingStack() { 95 | return callingStack.get(); 96 | } 97 | 98 | public void setCallingStack(String callingStack) { 99 | this.callingStack.set(callingStack); 100 | } 101 | 102 | public IntegerProperty priorityProperty() { 103 | return priority; 104 | } 105 | 106 | public int getPriority() { 107 | return priority.get(); 108 | } 109 | 110 | public void setPriority(int priority) { 111 | this.priority.set(priority); 112 | } 113 | 114 | public IntegerProperty osPriorityProperty() { 115 | return osPriority; 116 | } 117 | 118 | public int getOsPriority() { 119 | return osPriority.get(); 120 | } 121 | 122 | public void setOsPriority(int osPriority) { 123 | this.osPriority.set(osPriority); 124 | } 125 | 126 | public StringProperty threadIdProperty() { 127 | return threadId; 128 | } 129 | 130 | public String getThreadId() { 131 | return threadId.get(); 132 | } 133 | 134 | public void setThreadId(String threadId) { 135 | this.threadId.set(threadId); 136 | } 137 | 138 | public SetProperty lockedSynchronizersProperty() { 139 | return lockedSynchronizers; 140 | } 141 | 142 | public ObservableSet getLockedSynchronizers() { 143 | return lockedSynchronizers.get(); 144 | } 145 | 146 | public void setLockedSynchronizers(ObservableSet lockedSynchronizers) { 147 | this.lockedSynchronizers.set(lockedSynchronizers); 148 | } 149 | 150 | public SetProperty holdingLocksProperty() { 151 | return holdingLocks; 152 | } 153 | 154 | public ObservableSet getHoldingLocks() { 155 | return holdingLocks.get(); 156 | } 157 | 158 | public void setHoldingLocks(ObservableSet holdingLocks) { 159 | this.holdingLocks.set(holdingLocks); 160 | } 161 | 162 | public SetProperty waitingToLockProperty() { 163 | return waitingToLock; 164 | } 165 | 166 | public ObservableSet getWaitingToLock() { 167 | return waitingToLock.get(); 168 | } 169 | 170 | public void setWaitingToLock(ObservableSet waitingToLock) { 171 | this.waitingToLock.set(waitingToLock); 172 | } 173 | 174 | public SetProperty parkingReasonsProperty() { 175 | return parkingReasons; 176 | } 177 | 178 | public ObservableSet getParkingReasons() { 179 | return parkingReasons.get(); 180 | } 181 | 182 | public void setParkingReasons(ObservableSet parkingReasons) { 183 | this.parkingReasons.set(parkingReasons); 184 | } 185 | 186 | public String getSource() { 187 | return source.get(); 188 | } 189 | 190 | public StringProperty sourceProperty() { 191 | return source; 192 | } 193 | 194 | public void setSource(String source) { 195 | this.source.set(source); 196 | } 197 | 198 | /** 199 | * Get threads in the given {@link Dump dump} that are blocking this thread. 200 | * 201 | * @return A never {@code null} collection of threads blocking this instance. 202 | */ 203 | public Set getBlockingThreads() { 204 | final Set blockingThreads = new HashSet<>(); 205 | 206 | if (!getDump().getElements().isEmpty()) { 207 | for (final ThreadElement thread : getDump().getElements()) { 208 | if (!Objects.equals(thread, this)) { 209 | final long numberOfLocks = thread.getHoldingLocks() 210 | .stream() 211 | .filter(this.getWaitingToLock()::contains) 212 | .count(); 213 | 214 | if (numberOfLocks > 0) { 215 | blockingThreads.add(thread); 216 | } 217 | } 218 | } 219 | } 220 | 221 | return blockingThreads; 222 | } 223 | 224 | /** 225 | * Get threads in the given {@link Dump dump} that are blocked by this thread. 226 | * 227 | * @return A never {@code null} collection of threads blocked by this instance. 228 | */ 229 | public Set getBlockedThreads() { 230 | final Set blockedThreads = new HashSet<>(); 231 | 232 | if (!getDump().getElements().isEmpty()) { 233 | for (final ThreadElement thread : getDump().getElements()) { 234 | if (!Objects.equals(thread, this)) { 235 | final long numberOfLocks = thread.getWaitingToLock() 236 | .stream() 237 | .filter(this.getHoldingLocks()::contains) 238 | .count(); 239 | 240 | if (numberOfLocks > 0) { 241 | blockedThreads.add(thread); 242 | } 243 | } 244 | } 245 | } 246 | 247 | return blockedThreads; 248 | } 249 | 250 | public List asText() { 251 | final List texts = new ArrayList<>(); 252 | 253 | appendThreadNumberText(texts); 254 | appendThreadName(texts); 255 | appendThreadId(texts); 256 | 257 | Text text; 258 | 259 | text = new Text("Priority:"); 260 | text.setFont(bold); 261 | texts.add(text); 262 | 263 | text = new Text(" " + this.getPriority() + " "); 264 | text.setFont(normal); 265 | texts.add(text); 266 | 267 | text = new Text("OS priority:"); 268 | text.setFont(bold); 269 | texts.add(text); 270 | 271 | text = new Text(" " + this.getOsPriority() + "\n\n"); 272 | text.setFont(normal); 273 | texts.add(text); 274 | 275 | this.appendThreadReferences(texts, "Parking to wait for:", this.parkingReasons); 276 | this.appendThreadReferences(texts, "Locked synchronizers:", this.lockedSynchronizers); 277 | this.appendThreadReferences(texts, "Wait to acquire locks:", this.waitingToLock); 278 | this.appendThreadReferences(texts, "Holding locks on:", this.holdingLocks); 279 | 280 | if (this.callingStack.isNotNull().and(this.callingStack.isNotEmpty()).get()) { 281 | text = new Text("Calling stack:\n\n"); 282 | text.setFont(bold); 283 | texts.add(text); 284 | 285 | text = new Text(this.getCallingStack()); 286 | text.setFont(code); 287 | defineContextMenu(text); 288 | texts.add(text); 289 | } 290 | return texts; 291 | } 292 | 293 | protected void appendThreadNumberText(List texts) { 294 | Text text = new Text("#"); 295 | text.setFont(bold); 296 | texts.add(text); 297 | 298 | text = new Text("" + this.getNumber()); 299 | text.setFont(bold); 300 | defineContextMenu(text); 301 | texts.add(text); 302 | } 303 | 304 | protected void appendThreadName(List texts) { 305 | Text text = new Text(" "); 306 | text.setFont(normal); 307 | texts.add(text); 308 | 309 | text = new Text(this.getName()); 310 | text.setFont(normal); 311 | defineContextMenu(text); 312 | texts.add(text); 313 | 314 | text = new Text(" "); 315 | text.setFont(normal); 316 | texts.add(text); 317 | } 318 | 319 | protected void appendThreadId(List texts) { 320 | Text text = new Text("("); 321 | text.setFont(normal); 322 | texts.add(text); 323 | 324 | text = new Text(this.getThreadId()); 325 | text.setFont(normal); 326 | defineContextMenu(text); 327 | texts.add(text); 328 | 329 | text = new Text(")\n\n"); 330 | text.setFont(normal); 331 | texts.add(text); 332 | } 333 | 334 | protected void appendThreadReferences(final List texts, final String label, final Collection references) { 335 | if (!references.isEmpty()) { 336 | Text text = new Text(label + "\n\n"); 337 | text.setFont(bold); 338 | texts.add(text); 339 | 340 | for (final ThreadReference reference : references) { 341 | text = new Text(reference.getThreadId()); 342 | text.setFont(normal); 343 | defineContextMenu(text); 344 | texts.add(text); 345 | 346 | text = new Text(" ("); 347 | text.setFont(normal); 348 | texts.add(text); 349 | 350 | text = new Text(reference.getClassName()); 351 | text.setFont(code); 352 | defineContextMenu(text); 353 | texts.add(text); 354 | 355 | text = new Text(")\n"); 356 | text.setFont(normal); 357 | texts.add(text); 358 | } 359 | 360 | text = new Text("\n"); 361 | text.setFont(normal); 362 | texts.add(text); 363 | } 364 | } 365 | 366 | protected void defineContextMenu(final Text text) { 367 | final MenuItem copy = new MenuItem("Copy"); 368 | copy.setOnAction(event -> { 369 | Clipboard.getSystemClipboard().setContent(Collections.singletonMap(DataFormat.PLAIN_TEXT, text.getText())); 370 | }); 371 | final ContextMenu menu = new ContextMenu(copy); 372 | 373 | text.setOnContextMenuRequested(event -> { 374 | menu.show(text, event.getScreenX(), event.getScreenY()); 375 | }); 376 | } 377 | } 378 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/beans/ThreadReference.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.beans; 2 | 3 | import javafx.beans.property.SimpleStringProperty; 4 | import javafx.beans.property.StringProperty; 5 | 6 | /** 7 | * Represents a thread reference present in a thread dump. A reference is known as a thread ID and a class name. 8 | * It typically appears as locked synchronizers, locks and so on in a thread dump. 9 | * 10 | * @author Thierry Wasylczenko 11 | * @since JStackFX 1.0 12 | */ 13 | public class ThreadReference { 14 | protected final StringProperty threadId = new SimpleStringProperty(); 15 | protected final StringProperty className = new SimpleStringProperty(); 16 | 17 | public StringProperty threadIdProperty() { return threadId; } 18 | public String getThreadId() { return threadId.get(); } 19 | public void setThreadId(String threadId) { this.threadId.set(threadId); } 20 | 21 | public StringProperty classNameProperty() { return className; } 22 | public String getClassName() { return className.get(); } 23 | public void setClassName(String className) { this.className.set(className); } 24 | 25 | @Override 26 | public boolean equals(Object o) { 27 | if (this == o) return true; 28 | if (o == null || getClass() != o.getClass()) return false; 29 | 30 | ThreadReference that = (ThreadReference) o; 31 | 32 | return getThreadId() != null ? getThreadId().equals(that.getThreadId()) : that.getThreadId() == null; 33 | } 34 | 35 | @Override 36 | public int hashCode() { 37 | return getThreadId() != null ? getThreadId().hashCode() : 0; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/controllers/JStackFXController.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.controllers; 2 | 3 | import io.twasyl.jstackfx.beans.Dump; 4 | import io.twasyl.jstackfx.beans.InMemoryDump; 5 | import io.twasyl.jstackfx.beans.ThreadElement; 6 | import io.twasyl.jstackfx.exceptions.DumpException; 7 | import io.twasyl.jstackfx.factory.DumpFactory; 8 | import io.twasyl.jstackfx.ui.SearchField; 9 | import io.twasyl.jstackfx.ui.charts.LockedSynchronizersRepartitionChart; 10 | import io.twasyl.jstackfx.ui.charts.StateRepartitionChart; 11 | import javafx.beans.property.ObjectProperty; 12 | import javafx.beans.property.SimpleObjectProperty; 13 | import javafx.event.ActionEvent; 14 | import javafx.fxml.FXML; 15 | import javafx.fxml.Initializable; 16 | import javafx.scene.control.*; 17 | import javafx.scene.text.TextFlow; 18 | import javafx.stage.FileChooser; 19 | 20 | import java.io.File; 21 | import java.io.FileNotFoundException; 22 | import java.io.IOException; 23 | import java.io.PrintWriter; 24 | import java.net.URL; 25 | import java.util.ResourceBundle; 26 | import java.util.logging.Logger; 27 | 28 | /** 29 | * Controller of the {@code jstack.fxml} file. 30 | * 31 | * @author Thierry Wasylczenko 32 | * @since JStackFX 1.0 33 | */ 34 | public class JStackFXController implements Initializable { 35 | 36 | private static Logger LOGGER = Logger.getLogger(JStackFXController.class.getName()); 37 | 38 | @FXML 39 | private TableView threadElements; 40 | @FXML 41 | private TextFlow dumpInformations; 42 | @FXML 43 | private TextFlow threadElementDetails; 44 | @FXML 45 | private TextArea threadElementSource; 46 | @FXML 47 | private StateRepartitionChart threadsRepartition; 48 | @FXML 49 | private LockedSynchronizersRepartitionChart mostLockedSynchronizers; 50 | @FXML 51 | private Button saveDumpButton; 52 | @FXML 53 | private SearchField searchField; 54 | 55 | private final ObjectProperty dump = new SimpleObjectProperty<>(null); 56 | 57 | @FXML 58 | private void chooseDumpToOpen(final ActionEvent event) { 59 | try { 60 | this.chooseDumpToOpen(); 61 | } catch (Exception e) { 62 | showError(e); 63 | } 64 | } 65 | 66 | @FXML 67 | private void saveThreadDump(final ActionEvent event) { 68 | final FileChooser fileSaver = new FileChooser(); 69 | fileSaver.setTitle("Save thread dump"); 70 | final File dumpFile = fileSaver.showSaveDialog(null); 71 | 72 | if (dumpFile != null) { 73 | try { 74 | this.writeToDumpFile(dumpFile, this.dump.get()); 75 | this.loadDumpFile(dumpFile); 76 | } catch (Exception e) { 77 | showError(e); 78 | } 79 | } 80 | } 81 | 82 | @FXML 83 | private void makeThreadDump(final ActionEvent event) { 84 | final TextInputDialog dialog = new TextInputDialog(); 85 | dialog.setHeaderText("Enter the process ID to make the thread dump for:"); 86 | final String userAnswer = dialog.showAndWait().orElse(null); 87 | 88 | if (userAnswer != null && !userAnswer.isEmpty()) { 89 | final long pid = Long.parseLong(userAnswer); 90 | try { 91 | this.dumpPID(pid); 92 | } catch (DumpException e) { 93 | showError(e); 94 | } 95 | } 96 | } 97 | 98 | /** 99 | * Opens a file chooser and open the dump file in the UI. 100 | */ 101 | protected void chooseDumpToOpen() throws IOException, InstantiationException, IllegalAccessException { 102 | final FileChooser chooser = new FileChooser(); 103 | chooser.setTitle("Open dump file"); 104 | final File fileToOpen = chooser.showOpenDialog(null); 105 | 106 | if (fileToOpen != null) { 107 | this.loadDumpFile(fileToOpen); 108 | } 109 | } 110 | 111 | /** 112 | * Loads the dump file and update the UI. 113 | * 114 | * @param file The dump file to open. 115 | */ 116 | public void loadDumpFile(final File file) throws IOException, IllegalAccessException, InstantiationException { 117 | if (file == null) throw new NullPointerException("The file to open is null"); 118 | if (!file.exists()) throw new FileNotFoundException("The file doesn't exist"); 119 | 120 | final Dump dump = DumpFactory.read(file); 121 | 122 | this.updateUI(dump); 123 | this.dump.set(dump); 124 | } 125 | 126 | /** 127 | * Create a thread dump for the given PID. 128 | * 129 | * @param pid The PID of the process to dump. 130 | * @throws DumpException 131 | */ 132 | public void dumpPID(final long pid) throws DumpException { 133 | final Dump dump = DumpFactory.make(pid); 134 | this.updateUI(dump); 135 | this.dump.set(dump); 136 | } 137 | 138 | public void updateUI(final Dump dump) { 139 | if (dump != null) { 140 | this.clearUI(); 141 | this.updateSearchField(dump); 142 | this.updateThreadInformationsTable(dump); 143 | this.updateDumpInformations(dump); 144 | this.threadsRepartition.setDump(dump); 145 | this.mostLockedSynchronizers.setDump(dump); 146 | } 147 | } 148 | 149 | protected void writeToDumpFile(final File dumpFile, final Dump dump) throws IOException { 150 | if (dumpFile == null) throw new NullPointerException("The dump file can not be null"); 151 | if (dump == null) throw new NullPointerException("The dump to save can not be null"); 152 | if (!(dump instanceof InMemoryDump)) throw new IllegalArgumentException("The dump is not an in-memory dump"); 153 | 154 | try (final PrintWriter output = new PrintWriter(dumpFile)) { 155 | ((InMemoryDump) dump).getLines().forEach(output::println); 156 | output.flush(); 157 | } 158 | } 159 | 160 | protected void clearUI() { 161 | this.searchField.clear(); 162 | this.threadElementDetails.getChildren().clear(); 163 | this.threadElementSource.setText(""); 164 | } 165 | 166 | protected void updateSearchField(final Dump dump) { 167 | this.searchField.setDataSet(dump.getElements()); 168 | } 169 | 170 | protected void updateThreadInformationsTable(final Dump dump) { 171 | this.threadElements.getSelectionModel().clearSelection(); 172 | } 173 | 174 | protected void updateDumpInformations(final Dump dump) { 175 | this.dumpInformations.getChildren().clear(); 176 | this.dumpInformations.getChildren().addAll(dump.asText()); 177 | } 178 | 179 | /** 180 | * Show an error dialog to the end user for the provided exception. 181 | * 182 | * @param exception The exception that was thrown. 183 | */ 184 | protected void showError(Exception exception) { 185 | final Alert error = new Alert(Alert.AlertType.ERROR, exception.getMessage(), ButtonType.OK); 186 | error.show(); 187 | } 188 | 189 | @Override 190 | public void initialize(URL location, ResourceBundle resources) { 191 | this.threadElements.getSelectionModel().selectedItemProperty().addListener((value, oldItem, newItem) -> { 192 | this.threadElementDetails.getChildren().clear(); 193 | if (newItem != null) { 194 | this.threadElementDetails.getChildren().addAll(newItem.asText()); 195 | this.threadElementSource.setText(newItem.getSource()); 196 | } 197 | }); 198 | 199 | this.threadElements.itemsProperty().bind(this.searchField.resultsProperty()); 200 | 201 | this.dump.addListener((value, oldDump, newDump) -> { 202 | this.saveDumpButton.setDisable(newDump == null || !(newDump instanceof InMemoryDump)); 203 | }); 204 | } 205 | } 206 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/exceptions/DumpException.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.exceptions; 2 | 3 | /** 4 | * Main exception when working with {@link io.twasyl.jstackfx.beans.Dump}. 5 | * 6 | * @author Thierry Wasylczenko 7 | * @since JStackFX 1.0 8 | */ 9 | public class DumpException extends Exception { 10 | 11 | public DumpException() { 12 | } 13 | 14 | public DumpException(String message) { 15 | super(message); 16 | } 17 | 18 | public DumpException(String message, Throwable cause) { 19 | super(message, cause); 20 | } 21 | 22 | public DumpException(Throwable cause) { 23 | super(cause); 24 | } 25 | 26 | public DumpException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 27 | super(message, cause, enableSuppression, writableStackTrace); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/factory/DumpFactory.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.factory; 2 | 3 | import io.twasyl.jstackfx.beans.Dump; 4 | import io.twasyl.jstackfx.beans.FileDump; 5 | import io.twasyl.jstackfx.beans.InMemoryDump; 6 | import io.twasyl.jstackfx.beans.ThreadElement; 7 | import io.twasyl.jstackfx.exceptions.DumpException; 8 | 9 | import java.io.*; 10 | import java.nio.file.Files; 11 | import java.time.LocalDateTime; 12 | import java.time.format.DateTimeFormatter; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | import java.util.StringJoiner; 16 | import java.util.regex.Matcher; 17 | import java.util.regex.Pattern; 18 | import java.util.stream.Collectors; 19 | 20 | import static io.twasyl.jstackfx.beans.Dump.DATE_TIME_FORMATTER_OUTPUT; 21 | 22 | /** 23 | * This class is responsible for creating correctly {@link Dump dumps} instances. {@link Dump Dumps} can be instantiated 24 | * from a files or from a collections of lines representing the thread dump. 25 | * 26 | * @author Thierry Wasylczenko 27 | * @since JStackFX 1.0 28 | */ 29 | public class DumpFactory { 30 | 31 | protected static final String BEGINNING_OF_THREAD = "\""; 32 | protected static final Pattern VM_THREAD_PATTERN = Pattern.compile("^\\\"VM Thread\\\".+$"); 33 | protected static final Pattern GC_TASK_THREAD_PATTERN = Pattern.compile("\\\"GC task thread#.+"); 34 | protected static final Pattern VM_PERIODIC_TASK_THREAD_PATTERN = Pattern.compile("\\\"VM Periodic Task Thread\\\".+"); 35 | protected static final Pattern JNI_REFERENCES_PATTERN = Pattern.compile("^JNI global references: ([0-9]*)$"); 36 | 37 | /** 38 | * Reads a given jstack file and create the associated {@link Dump} object. 39 | * 40 | * @param file The thread dump file to read. 41 | * @return A dump object. 42 | */ 43 | public static Dump read(final File file) throws IOException, InstantiationException, IllegalAccessException { 44 | if (file == null) throw new NullPointerException("The file can not be null"); 45 | if (!file.exists()) throw new FileNotFoundException("The file doesn't exist"); 46 | 47 | final List lines = Files.lines(file.toPath()).collect(Collectors.toList()); 48 | final FileDump dump = createDumpInstance(FileDump.class, lines); 49 | dump.setFile(file); 50 | 51 | return dump; 52 | } 53 | 54 | /** 55 | * Reads a given collections of lines coming from a thread dump and create the associated {@link Dump} object. 56 | * 57 | * @param lines The lines of the thread dump. 58 | * @return A dump object. 59 | */ 60 | public static Dump read(final List lines) throws IOException, InstantiationException, IllegalAccessException { 61 | final InMemoryDump dump = createDumpInstance(InMemoryDump.class, lines); 62 | dump.getLines().addAll(lines); 63 | 64 | return dump; 65 | } 66 | 67 | private static D createDumpInstance(Class dumpClass, final List lines) throws IllegalAccessException, InstantiationException { 68 | final D dump; 69 | 70 | if (!lines.isEmpty()) { 71 | dump = dumpClass.newInstance(); 72 | 73 | dump.setGenerationDateTime(LocalDateTime.parse(lines.get(0), DATE_TIME_FORMATTER_OUTPUT)); 74 | dump.setDescription(lines.get(1)); 75 | 76 | int beginningOfThreadIndex = 3; 77 | int endOfThreadIndex = 0; 78 | boolean beginningOfThreadFound = false; 79 | boolean endOfThreadFound = false; 80 | boolean jniReferencesFound = false; 81 | 82 | for (int index = beginningOfThreadIndex; index < lines.size(); index++) { 83 | final String line = lines.get(index); 84 | 85 | if (line.startsWith(BEGINNING_OF_THREAD)) { 86 | if (!beginningOfThreadFound) { 87 | beginningOfThreadFound = true; 88 | beginningOfThreadIndex = index; 89 | } else if (!endOfThreadFound) { 90 | endOfThreadFound = true; 91 | endOfThreadIndex = index - 1; 92 | } 93 | } else if (JNI_REFERENCES_PATTERN.matcher(line).matches()) { 94 | endOfThreadFound = true; 95 | jniReferencesFound = true; 96 | endOfThreadIndex = index - 1; 97 | } 98 | 99 | if (beginningOfThreadFound && endOfThreadFound) { 100 | if (isSingleLine(beginningOfThreadIndex, endOfThreadIndex)) { 101 | if (jniReferencesFound) { 102 | final Matcher result = JNI_REFERENCES_PATTERN.matcher(line); 103 | if (result.matches()) { 104 | dump.setNumberOfJNIRefs(Integer.parseInt(result.group(1))); 105 | } 106 | } 107 | } else { 108 | final ThreadElement thread = ThreadElementFactory.build(lines.subList(beginningOfThreadIndex, endOfThreadIndex)); 109 | thread.setDump(dump); 110 | dump.getElements().add(thread); 111 | } 112 | 113 | beginningOfThreadFound = true; 114 | endOfThreadFound = false; 115 | beginningOfThreadIndex = index; 116 | } 117 | } 118 | } else { 119 | dump = null; 120 | } 121 | 122 | return dump; 123 | } 124 | 125 | /** 126 | * Take a thread dump for a given process. The {@code jstack} tool should be in the {@code PATH} in order to be 127 | * launched by the application. 128 | * 129 | * @param processId The ID of the process to make a thread dump for. 130 | * @return The thread dump. 131 | */ 132 | public static Dump make(final long processId) throws DumpException { 133 | final Process jstack; 134 | try { 135 | jstack = new ProcessBuilder("jstack", String.valueOf(processId)) 136 | .redirectErrorStream(true) 137 | .start(); 138 | 139 | final List lines = getLinesFrom(jstack); 140 | 141 | if (jstack.waitFor() == 0) { 142 | return read(lines); 143 | } else { 144 | final StringJoiner error = new StringJoiner("\n"); 145 | lines.forEach(error::add); 146 | throw new DumpException(error.toString()); 147 | } 148 | } catch (IOException | InterruptedException | IllegalAccessException | InstantiationException e) { 149 | throw new DumpException(e); 150 | } 151 | } 152 | 153 | /** 154 | * Reads a {@link Process} input and create a collection of lines from it. 155 | * 156 | * @param process The process to capture the input. 157 | * @return A collection of lines corresponding to the process' output. 158 | * @throws DumpException If something went wrong. 159 | */ 160 | protected static List getLinesFrom(final Process process) throws DumpException { 161 | final List lines = new ArrayList<>(); 162 | 163 | try (final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { 164 | String line; 165 | 166 | while ((line = reader.readLine()) != null) { 167 | lines.add(line); 168 | } 169 | } catch (IOException e) { 170 | throw new DumpException(e); 171 | } 172 | 173 | return lines; 174 | } 175 | 176 | protected static boolean isSingleLine(int firstLine, int secondLine) { 177 | return secondLine - firstLine == 1; 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/factory/ThreadElementFactory.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.factory; 2 | 3 | import io.twasyl.jstackfx.beans.ThreadElement; 4 | import io.twasyl.jstackfx.beans.ThreadReference; 5 | 6 | import java.util.*; 7 | import java.util.regex.Matcher; 8 | import java.util.regex.Pattern; 9 | 10 | /** 11 | * This class is responsible for creating {@link ThreadElement thread elements} properly. 12 | * 13 | * @author Thierry Wasylczenko 14 | * @since JStackFX 1.0 15 | */ 16 | public class ThreadElementFactory { 17 | protected static final Pattern LINE_STARTING_WITH_DASH = Pattern.compile("^\\s+-.+$"); 18 | protected static final Pattern THREAD_NAME_PATTERN = Pattern.compile("^\\\"([^\\\"]+)\\\".+"); 19 | protected static final Pattern THREAD_STATE_PATTERN = Pattern.compile("^\\s+java\\.lang\\.Thread\\.State: ([^ ]+).*$"); 20 | protected static final Pattern THREAD_NUMBER_PATTERN = Pattern.compile("^[^#]+#([0-9]+).+"); 21 | protected static final Pattern THREAD_PRIORITY_PATTERN = Pattern.compile("(\\sprio=([0-9]+))"); 22 | protected static final Pattern THREAD_OS_PRIORITY_PATTERN = Pattern.compile("(os_prio=([0-9]+))"); 23 | protected static final Pattern THREAD_ID_PATTERN = Pattern.compile("(tid=(0x[0-9a-f]+))"); 24 | protected static final Pattern CALLING_STACK_LINE_MATCHER = Pattern.compile("^\\sat ([a-zA-Z\\.\\$]+)\\([a-zA-Z0-9 \\.:\\$]+\\)"); 25 | protected static final Pattern LOCKED_OWNALBLE_SYNCHRONIZERS_START = Pattern.compile("^\\s+Locked ownable synchronizers:"); 26 | protected static final Pattern LOCKED_SYNCHRONIZER_PATTERN = Pattern.compile("^\\s+-\\s<(0x[0-9a-f]+)>\\s\\(a ([a-zA-Z\\.\\$]+)\\)$"); 27 | protected static final Pattern HOLDING_LOCKS_PATTERN = Pattern.compile("^\\s+- locked <(0x[0-9a-f]+)>\\s\\(a ([a-zA-Z\\.\\$]+)\\)$"); 28 | protected static final Pattern WAITING_TO_LOCK_PATTERN = Pattern.compile("^\\s+- waiting to lock <(0x[0-9a-f]+)>\\s\\(a ([a-zA-Z\\.\\$]+)\\)$"); 29 | protected static final Pattern PARKING_TO_WAIT_FOR_PATTERN = Pattern.compile("^\\s+- parking to wait for\\s+<(0x[0-9a-f]+)>\\s\\(a ([a-zA-Z\\.\\$]+)\\)$"); 30 | 31 | public static ThreadElement build(final List lines) { 32 | final ThreadElement element = new ThreadElement(); 33 | 34 | element.setSource(buildSource(lines)); 35 | 36 | String line = lines.get(0); 37 | element.setName(extractNameFrom(line)); 38 | element.setNumber(extractThreadNumberFrom(line)); 39 | element.setPriority(extractPriorityFrom(line)); 40 | element.setOsPriority(extractOsPriorityFrom(line)); 41 | element.setThreadId(extractThreadIdFrom(line)); 42 | 43 | if(lines.size() > 1) { 44 | line = lines.get(1); 45 | element.setState(extractStateFrom(line)); 46 | } 47 | 48 | element.setCallingStack(extractCallingStack(lines)); 49 | element.getLockedSynchronizers().addAll(extractLockedSynchronizersFrom(lines)); 50 | element.getHoldingLocks().addAll(extractHoldingLocks(lines)); 51 | element.getWaitingToLock().addAll(extractWaitingToLock(lines)); 52 | element.getParkingReasons().addAll(extractParkingToWaitFor(lines)); 53 | 54 | return element; 55 | } 56 | 57 | protected static String buildSource(final List lines) { 58 | final StringJoiner source = new StringJoiner("\n"); 59 | lines.forEach(source::add); 60 | return source.toString(); 61 | } 62 | 63 | protected static String extractNameFrom(final String line) { 64 | final Matcher matcher = THREAD_NAME_PATTERN.matcher(line); 65 | 66 | if (matcher.find()) { 67 | return matcher.group(1); 68 | } 69 | 70 | return null; 71 | } 72 | 73 | protected static Thread.State extractStateFrom(final String line) { 74 | final Matcher matcher = THREAD_STATE_PATTERN.matcher(line); 75 | 76 | if (matcher.find()) { 77 | return Thread.State.valueOf(matcher.group(1)); 78 | } 79 | 80 | return null; 81 | } 82 | 83 | protected static long extractThreadNumberFrom(final String line) { 84 | final Matcher matcher = THREAD_NUMBER_PATTERN.matcher(line); 85 | 86 | if (matcher.find()) { 87 | return Long.parseLong(matcher.group(1)); 88 | } 89 | 90 | return -1; 91 | } 92 | 93 | protected static String extractCallingStack(final List lines) { 94 | final StringJoiner callingStack = new StringJoiner("\n"); 95 | 96 | for(final String line : lines) { 97 | final Matcher lineMatcher = CALLING_STACK_LINE_MATCHER.matcher(line); 98 | 99 | if(lineMatcher.matches()) { 100 | callingStack.add(line.trim()); 101 | } 102 | } 103 | 104 | return callingStack.toString(); 105 | } 106 | 107 | protected static int extractPriorityFrom(final String line) { 108 | final Matcher matcher = THREAD_PRIORITY_PATTERN.matcher(line); 109 | 110 | if (matcher.find()) { 111 | return Integer.parseInt(matcher.group(2)); 112 | } 113 | 114 | return -1; 115 | } 116 | 117 | protected static int extractOsPriorityFrom(final String line) { 118 | final Matcher matcher = THREAD_OS_PRIORITY_PATTERN.matcher(line); 119 | 120 | if (matcher.find()) { 121 | return Integer.parseInt(matcher.group(2)); 122 | } 123 | 124 | return -1; 125 | } 126 | 127 | protected static String extractThreadIdFrom(final String line) { 128 | final Matcher matcher = THREAD_ID_PATTERN.matcher(line); 129 | 130 | if (matcher.find()) { 131 | return matcher.group(2); 132 | } 133 | 134 | return null; 135 | } 136 | 137 | protected static Set extractLockedSynchronizersFrom(final List lines) { 138 | final Set synchronizers = new HashSet<>(); 139 | 140 | boolean foundLockedOwnableSynchronizersLine = false; 141 | int index = 0; 142 | 143 | while (!foundLockedOwnableSynchronizersLine && index < lines.size()) { 144 | final String line = lines.get(index); 145 | foundLockedOwnableSynchronizersLine = LOCKED_OWNALBLE_SYNCHRONIZERS_START.matcher(line).matches(); 146 | index++; 147 | } 148 | 149 | if (foundLockedOwnableSynchronizersLine) { 150 | boolean lineIsStartingWithDash = true; 151 | 152 | while (lineIsStartingWithDash && index < lines.size()) { 153 | final String line = lines.get(index); 154 | lineIsStartingWithDash = LINE_STARTING_WITH_DASH.matcher(line).matches(); 155 | 156 | if (lineIsStartingWithDash) { 157 | final Matcher synchronizerMatcher = LOCKED_SYNCHRONIZER_PATTERN.matcher(line); 158 | 159 | if (synchronizerMatcher.matches()) { 160 | final ThreadReference synchronizer = new ThreadReference(); 161 | synchronizer.setThreadId(synchronizerMatcher.group(1)); 162 | synchronizer.setClassName(synchronizerMatcher.group(2)); 163 | synchronizers.add(synchronizer); 164 | } 165 | } 166 | 167 | index++; 168 | } 169 | } 170 | 171 | return synchronizers; 172 | } 173 | 174 | protected static Set extractWaitingToLock(final List lines) { 175 | final Set waitingToLock = new LinkedHashSet<>(); 176 | 177 | for (final String line : lines) { 178 | final Matcher waitingToLockMatcher = WAITING_TO_LOCK_PATTERN.matcher(line); 179 | 180 | if(waitingToLockMatcher.matches()) { 181 | final ThreadReference synchronizer = new ThreadReference(); 182 | synchronizer.setThreadId(waitingToLockMatcher.group(1)); 183 | synchronizer.setClassName(waitingToLockMatcher.group(2)); 184 | waitingToLock.add(synchronizer); 185 | } 186 | } 187 | 188 | return waitingToLock; 189 | } 190 | 191 | protected static Set extractHoldingLocks(final List lines) { 192 | final Set holdingLocks = new LinkedHashSet<>(); 193 | 194 | for (final String line : lines) { 195 | final Matcher holdingLocksMatcher = HOLDING_LOCKS_PATTERN.matcher(line); 196 | 197 | if(holdingLocksMatcher.matches()) { 198 | final ThreadReference synchronizer = new ThreadReference(); 199 | synchronizer.setThreadId(holdingLocksMatcher.group(1)); 200 | synchronizer.setClassName(holdingLocksMatcher.group(2)); 201 | holdingLocks.add(synchronizer); 202 | } 203 | } 204 | 205 | return holdingLocks; 206 | } 207 | 208 | protected static Set extractParkingToWaitFor(final List lines) { 209 | final Set parkingReasons = new LinkedHashSet<>(); 210 | 211 | for (final String line : lines) { 212 | final Matcher parkingMatcher = PARKING_TO_WAIT_FOR_PATTERN.matcher(line); 213 | 214 | if(parkingMatcher.matches()) { 215 | final ThreadReference synchronizer = new ThreadReference(); 216 | synchronizer.setThreadId(parkingMatcher.group(1)); 217 | synchronizer.setClassName(parkingMatcher.group(2)); 218 | parkingReasons.add(synchronizer); 219 | } 220 | } 221 | 222 | return parkingReasons; 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/search/Comparator.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.search; 2 | 3 | /** 4 | * Enumeration defining which comparators are allowed in a {@link Query}. 5 | * 6 | * @author Thierry Wasylczenko 7 | * @since JStackFX 1.1 8 | */ 9 | public enum Comparator { 10 | EQUAL("="), 11 | DIFFERENT("!="), 12 | LESS_OR_EQUAL("<="), 13 | LESS("<"), 14 | GREATER_OR_EQUAL(">="), 15 | GREATER(">"); 16 | 17 | private final String regexExpression; 18 | 19 | Comparator(final String regexExpression) { 20 | this.regexExpression = regexExpression; 21 | } 22 | 23 | public String getRegexExpression() { 24 | return regexExpression; 25 | } 26 | 27 | public static Comparator fromRegex(final String regex) { 28 | for (final Comparator comparator : values()) { 29 | if (comparator.regexExpression.equals(regex)) { 30 | return comparator; 31 | } 32 | } 33 | return null; 34 | } 35 | 36 | public boolean evaluate(final Comparable obj1, final Comparable obj2) { 37 | if (obj1 == null && obj2 == null) { 38 | return this == EQUAL; 39 | } else if ((obj1 != null && obj2 == null) || (obj1 == null && obj2 != null)) { 40 | return this == DIFFERENT; 41 | } else { 42 | final int compareTo = obj1.compareTo(obj2); 43 | 44 | if (this == EQUAL) { 45 | return compareTo == 0; 46 | } else if (this == DIFFERENT) { 47 | return compareTo != 0; 48 | } else if (this == LESS) { 49 | return compareTo < 0; 50 | } else if (this == LESS_OR_EQUAL) { 51 | return compareTo <= 0; 52 | } else if (this == GREATER) { 53 | return compareTo > 0; 54 | } else if (this == GREATER_OR_EQUAL) { 55 | return compareTo >= 0; 56 | } else { 57 | return true; 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/search/FieldExpression.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.search; 2 | 3 | import io.twasyl.jstackfx.search.exceptions.EvaluateException; 4 | 5 | import java.beans.BeanInfo; 6 | import java.beans.IntrospectionException; 7 | import java.beans.Introspector; 8 | import java.beans.PropertyDescriptor; 9 | import java.lang.reflect.InvocationTargetException; 10 | import java.lang.reflect.Method; 11 | 12 | /** 13 | * @author Thierry Wasylczenko 14 | * @since JStackFX 1.1 15 | */ 16 | public class FieldExpression { 17 | 18 | public static class Builder { 19 | private final FieldExpression fieldExpression = new FieldExpression<>(); 20 | 21 | private Builder() { 22 | } 23 | 24 | public static Builder create(Class clazz) { 25 | if (clazz == null) throw new NullPointerException("The class can not be null"); 26 | 27 | final Builder builder = new Builder(); 28 | builder.fieldExpression.clazz = clazz; 29 | return builder; 30 | } 31 | 32 | public FieldExpression build() { 33 | try { 34 | final BeanInfo bean = Introspector.getBeanInfo(this.fieldExpression.clazz); 35 | final PropertyDescriptor[] descriptors = bean.getPropertyDescriptors(); 36 | boolean found = false; 37 | int index = 0; 38 | 39 | while (!found && index < descriptors.length) { 40 | final PropertyDescriptor descriptor = descriptors[index]; 41 | 42 | if (this.fieldExpression.fieldName.equals(descriptor.getName())) { 43 | found = true; 44 | this.fieldExpression.fieldReadMethod = descriptor.getReadMethod(); 45 | } 46 | 47 | index++; 48 | } 49 | 50 | if (this.fieldExpression.fieldReadMethod == null) { 51 | throw new NullPointerException("Getter for the field " + this.fieldExpression.fieldName + " in given class " + this.fieldExpression.clazz.getName()); 52 | } 53 | } catch (IntrospectionException e) { 54 | throw new IllegalArgumentException("Can not determine BeanInfo for instance object", e); 55 | } 56 | 57 | return this.fieldExpression; 58 | } 59 | 60 | public Builder onField(final String field) { 61 | if (field == null) throw new NullPointerException("The field can not be null"); 62 | if (field.trim().isEmpty()) throw new IllegalArgumentException("The field can not be empty"); 63 | 64 | this.fieldExpression.fieldName = field.trim(); 65 | return this; 66 | } 67 | 68 | public Builder withWalue(final Comparable value) { 69 | this.fieldExpression.value = value; 70 | return this; 71 | } 72 | 73 | public Builder using(final Comparator comparator) { 74 | if (comparator == null) throw new NullPointerException("The comparator can not be null"); 75 | 76 | this.fieldExpression.comparator = comparator; 77 | return this; 78 | } 79 | } 80 | 81 | protected Class clazz = null; 82 | protected Method fieldReadMethod = null; 83 | protected Comparator comparator = null; 84 | protected String fieldName = null; 85 | protected Comparable value = null; 86 | 87 | private FieldExpression() { 88 | } 89 | 90 | public boolean match(final T instance) throws EvaluateException { 91 | try { 92 | final Comparable instanceValue = Comparable.class.cast(fieldReadMethod.invoke(instance)); 93 | final boolean evaluation = this.comparator.evaluate(instanceValue, this.value); 94 | return evaluation; 95 | } catch (IllegalAccessException | InvocationTargetException e) { 96 | throw new EvaluateException("Can not determine value for field " + this.fieldName + " for given instance", e); 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/search/FieldExpressionQueue.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.search; 2 | 3 | import io.twasyl.jstackfx.beans.Pair; 4 | import io.twasyl.jstackfx.search.exceptions.EvaluateException; 5 | 6 | import javax.script.ScriptEngine; 7 | import javax.script.ScriptEngineManager; 8 | import javax.script.ScriptException; 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | import java.util.Objects; 12 | import java.util.logging.Level; 13 | import java.util.logging.Logger; 14 | 15 | /** 16 | * @author Thierry Wasylczenko 17 | * @since JStackFX 1.1 18 | */ 19 | public class FieldExpressionQueue { 20 | private static Logger LOGGER = Logger.getLogger(FieldExpressionQueue.class.getName()); 21 | 22 | protected ScriptEngine engine; 23 | protected List, Operand>> expressions = new ArrayList<>(); 24 | 25 | public FieldExpressionQueue() { 26 | final ScriptEngineManager manager = new ScriptEngineManager(); 27 | this.engine = manager.getEngineByName("nashorn"); 28 | } 29 | 30 | public FieldExpressionQueue put(final FieldExpression expression) { 31 | this.expressions.add(new Pair<>(expression, null)); 32 | return this; 33 | } 34 | 35 | public FieldExpressionQueue and() { 36 | this.setOperandToLastElement(Operand.AND); 37 | return this; 38 | } 39 | 40 | public FieldExpressionQueue or() { 41 | this.setOperandToLastElement(Operand.OR); 42 | return this; 43 | } 44 | 45 | public FieldExpressionQueue clear() { 46 | this.expressions.clear(); 47 | return this; 48 | } 49 | 50 | public boolean match(final T instance) { 51 | if (expressions.isEmpty()) { 52 | return false; 53 | } else { 54 | try { 55 | final Object result = this.engine.eval(this.buildScriptExpression(instance)); 56 | return result != null && Objects.equals(true, result); 57 | } catch (ScriptException | EvaluateException e) { 58 | if(LOGGER.isLoggable(Level.FINE)){ 59 | LOGGER.log(Level.WARNING, "Can not evaluate matching", e); 60 | } 61 | return false; 62 | } 63 | } 64 | } 65 | 66 | protected String buildScriptExpression(final T instance) throws EvaluateException { 67 | final StringBuilder scriptExpression = new StringBuilder(""); 68 | boolean continueBuilding = true; 69 | int index = 0; 70 | 71 | while (continueBuilding && index < this.expressions.size()) { 72 | final Pair, Operand> pair = this.expressions.get(index); 73 | scriptExpression.append(pair.getValue1().match(instance)); 74 | 75 | if (pair.getValue2() != null) { 76 | boolean hasMorePair = (index + 1) < this.expressions.size(); 77 | final Pair, Operand> nextPair; 78 | 79 | if (hasMorePair) { 80 | nextPair = this.expressions.get(index + 1); 81 | } else { 82 | nextPair = null; 83 | } 84 | 85 | continueBuilding = nextPair != null && nextPair.getValue1() != null; 86 | } else { 87 | continueBuilding = false; 88 | } 89 | 90 | index++; 91 | 92 | if(continueBuilding) { 93 | scriptExpression.append(" ").append(pair.getValue2().getProgrammingOperator()).append(" "); 94 | } 95 | } 96 | 97 | return scriptExpression.toString(); 98 | } 99 | 100 | protected void setOperandToLastElement(final Operand operand) { 101 | final Pair, Operand> last = getLast(); 102 | if (last != null) { 103 | last.setValue2(operand); 104 | } 105 | } 106 | 107 | protected Pair, Operand> getLast() { 108 | if (this.expressions.isEmpty()) return null; 109 | else return this.expressions.get(this.expressions.size() - 1); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/search/Operand.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.search; 2 | 3 | /** 4 | * @author Thierry Wasylczenko 5 | * @since JStackFX 1.1 6 | */ 7 | public enum Operand { 8 | AND("and", "&&"), 9 | OR("or", "||"); 10 | 11 | private final String regexExpression; 12 | private final String programmingOperator; 13 | 14 | Operand(final String regexExpression, final String programmingOperator) { 15 | this.regexExpression = regexExpression; 16 | this.programmingOperator = programmingOperator; 17 | } 18 | 19 | public String getRegexExpression() { 20 | return regexExpression; 21 | } 22 | 23 | public String getProgrammingOperator() { 24 | return programmingOperator; 25 | } 26 | 27 | public static Operand fromRegex(final String regex) { 28 | for (final Operand operand : values()) { 29 | if (operand.regexExpression.equals(regex)) { 30 | return operand; 31 | } 32 | } 33 | return null; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/search/Query.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.search; 2 | 3 | import io.twasyl.jstackfx.search.exceptions.ConversionException; 4 | import io.twasyl.jstackfx.search.exceptions.UnparsableQueryException; 5 | 6 | import java.beans.BeanInfo; 7 | import java.beans.IntrospectionException; 8 | import java.beans.Introspector; 9 | import java.beans.PropertyDescriptor; 10 | import java.util.Arrays; 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | import java.util.StringJoiner; 14 | import java.util.logging.Level; 15 | import java.util.logging.Logger; 16 | import java.util.regex.Matcher; 17 | import java.util.regex.Pattern; 18 | import java.util.stream.Collectors; 19 | 20 | /** 21 | * Class defining a query that can be made using the search bar. 22 | * 23 | * @author Thierry Wasylczenko 24 | * @since JStackFX 1.1 25 | */ 26 | public class Query { 27 | 28 | private static Logger LOGGER = Logger.getLogger(Query.class.getName()); 29 | 30 | protected static Pattern EXPRESSION_PATTERN; 31 | protected static String FIELD_NAME_GROUP = "fieldName"; 32 | protected static String FIELD_VALUE_GROUP = "fieldValue"; 33 | protected static String COMPARATOR_GROUP = "comparator"; 34 | protected static String OPERAND_GROUP = "operand"; 35 | 36 | protected static Map FIELD_TYPE_CACHE = new HashMap<>(); 37 | 38 | static { 39 | final String comparators = Arrays.stream(Comparator.values()) 40 | .map(Comparator::getRegexExpression) 41 | .collect(Collectors.joining("|", "(?<" + COMPARATOR_GROUP + ">", ")")); 42 | 43 | final String operands = Arrays.stream(Operand.values()) 44 | .map(Operand::getRegexExpression) 45 | .collect(Collectors.joining("|", "(?<" + OPERAND_GROUP + ">", ")")); 46 | 47 | final StringBuilder expression = new StringBuilder("(?<").append(FIELD_NAME_GROUP).append(">[^\\s]+)") 48 | .append("\\s*").append(comparators) 49 | .append("\\s*(?<").append(FIELD_VALUE_GROUP).append(">[^\\s]+)") 50 | .append("\\s*").append(operands).append("?"); 51 | 52 | EXPRESSION_PATTERN = Pattern.compile(expression.toString()); 53 | } 54 | 55 | protected Class clazz; 56 | protected FieldExpressionQueue expressions; 57 | protected String rawQuery; 58 | 59 | private Query(final Class clazz) { 60 | this.clazz = clazz; 61 | this.expressions = new FieldExpressionQueue<>(); 62 | } 63 | 64 | public static Query create(final Class clazz) { 65 | if (clazz == null) throw new NullPointerException("The class can not be null"); 66 | final Query query = new Query(clazz); 67 | return query; 68 | } 69 | 70 | public String getRawQuery() { 71 | return rawQuery; 72 | } 73 | 74 | public boolean parse(final String query) throws UnparsableQueryException { 75 | this.rawQuery = query; 76 | final Matcher matcher = EXPRESSION_PATTERN.matcher(query); 77 | this.expressions.clear(); 78 | 79 | boolean parsingSuccessful = true; 80 | 81 | while (matcher.find() && parsingSuccessful) { 82 | final String field = matcher.group(FIELD_NAME_GROUP); 83 | final Comparator comparator = Comparator.fromRegex(matcher.group(COMPARATOR_GROUP)); 84 | final Comparable value; 85 | 86 | try { 87 | value = convertFieldValue(field, matcher.group(FIELD_VALUE_GROUP)); 88 | this.expressions.put(FieldExpression.Builder.create(this.clazz) 89 | .onField(field) 90 | .using(comparator) 91 | .withWalue(value) 92 | .build()); 93 | 94 | final String operandString = matcher.group(OPERAND_GROUP); 95 | if (operandString != null) { 96 | final Operand operand = Operand.fromRegex(operandString); 97 | if (operand == Operand.AND) { 98 | this.expressions.and(); 99 | } else if (operand == Operand.OR) { 100 | this.expressions.or(); 101 | } 102 | } 103 | } catch (ConversionException e) { 104 | if (LOGGER.isLoggable(Level.FINE)) { 105 | LOGGER.log(Level.WARNING, "Error parsing the query", e); 106 | } 107 | parsingSuccessful = false; 108 | } 109 | } 110 | return parsingSuccessful; 111 | } 112 | 113 | public boolean match(final T object) { 114 | return this.expressions.match(object); 115 | } 116 | 117 | protected Comparable convertFieldValue(final String fieldName, final String fieldValue) throws ConversionException { 118 | if (!FIELD_TYPE_CACHE.containsKey(fieldName)) { 119 | FIELD_TYPE_CACHE.put(fieldName, determineFieldClass(fieldName)); 120 | } 121 | 122 | final Class aClass = FIELD_TYPE_CACHE.get(fieldName); 123 | 124 | try { 125 | if (aClass.isEnum()) { 126 | return Enum.valueOf(aClass, fieldValue.toUpperCase()); 127 | } else if (aClass.equals(byte.class) || aClass.equals(Byte.class)) { 128 | return Byte.parseByte(fieldValue); 129 | } else if (aClass.equals(int.class) || aClass.equals(Integer.class)) { 130 | return Integer.parseInt(fieldValue); 131 | } else if (aClass.equals(long.class) || aClass.equals(Long.class)) { 132 | return Long.parseLong(fieldValue); 133 | } else if (aClass.equals(short.class) || aClass.equals(Short.class)) { 134 | return Short.parseShort(fieldValue); 135 | } else if (aClass.equals(float.class) || aClass.equals(Float.class)) { 136 | return Float.parseFloat(fieldValue); 137 | } else if (aClass.equals(double.class) || aClass.equals(Double.class)) { 138 | return Double.parseDouble(fieldValue); 139 | } else if (aClass.equals(boolean.class) || aClass.equals(Boolean.class)) { 140 | return Boolean.parseBoolean(fieldValue); 141 | } else if (aClass.equals(char.class) || aClass.equals(Character.class)) { 142 | if (fieldValue.length() == 1) { 143 | return fieldValue.charAt(0); 144 | } else { 145 | throw new ConversionException("Field value [" + fieldValue + "] is not a character"); 146 | } 147 | } else if (aClass.equals(String.class)) { 148 | return fieldValue; 149 | } else { 150 | throw new ConversionException("Type [" + aClass.getName() + "] is not supported in search"); 151 | } 152 | } catch (ConversionException e) { 153 | throw e; 154 | } catch (Exception e) { 155 | throw new ConversionException("Can not convert value [" + fieldValue + "] to class [" + aClass.getName() + "]", e); 156 | } 157 | } 158 | 159 | protected Class determineFieldClass(final String fieldName) { 160 | try { 161 | final BeanInfo beanInfo = Introspector.getBeanInfo(this.clazz); 162 | final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); 163 | final PropertyDescriptor fieldDescriptor = Arrays.stream(descriptors).filter(descriptor -> descriptor.getName().equals(fieldName)).findFirst().orElse(null); 164 | 165 | return fieldDescriptor.getReadMethod().getReturnType(); 166 | 167 | } catch (IntrospectionException e) { 168 | if (LOGGER.isLoggable(Level.FINE)) { 169 | LOGGER.log(Level.WARNING, "Error determining the field [" + fieldName + "] class", e); 170 | } 171 | return null; 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/search/exceptions/ConversionException.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.search.exceptions; 2 | 3 | /** 4 | * @author Thierry Wasylczenko 5 | * @since JStackFX 1.1 6 | */ 7 | public class ConversionException extends Exception { 8 | public ConversionException() { 9 | } 10 | 11 | public ConversionException(String message) { 12 | super(message); 13 | } 14 | 15 | public ConversionException(String message, Throwable cause) { 16 | super(message, cause); 17 | } 18 | 19 | public ConversionException(Throwable cause) { 20 | super(cause); 21 | } 22 | 23 | public ConversionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 24 | super(message, cause, enableSuppression, writableStackTrace); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/search/exceptions/EvaluateException.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.search.exceptions; 2 | 3 | /** 4 | * @author Thierry Wasylczenko 5 | * @since JStackFX 1.1 6 | */ 7 | public class EvaluateException extends Exception { 8 | public EvaluateException() { 9 | } 10 | 11 | public EvaluateException(String message) { 12 | super(message); 13 | } 14 | 15 | public EvaluateException(String message, Throwable cause) { 16 | super(message, cause); 17 | } 18 | 19 | public EvaluateException(Throwable cause) { 20 | super(cause); 21 | } 22 | 23 | public EvaluateException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 24 | super(message, cause, enableSuppression, writableStackTrace); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/search/exceptions/UnparsableQueryException.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.search.exceptions; 2 | 3 | /** 4 | * @author Thierry Wasylczenko 5 | * @since JStackFX 1.1 6 | */ 7 | public class UnparsableQueryException extends Exception { 8 | public UnparsableQueryException() { 9 | } 10 | 11 | public UnparsableQueryException(String message) { 12 | super(message); 13 | } 14 | 15 | public UnparsableQueryException(String message, Throwable cause) { 16 | super(message, cause); 17 | } 18 | 19 | public UnparsableQueryException(Throwable cause) { 20 | super(cause); 21 | } 22 | 23 | public UnparsableQueryException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 24 | super(message, cause, enableSuppression, writableStackTrace); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/ui/SearchField.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.ui; 2 | 3 | 4 | import de.jensd.fx.glyphs.octicons.OctIcon; 5 | import de.jensd.fx.glyphs.octicons.OctIconView; 6 | import io.twasyl.jstackfx.search.Query; 7 | import io.twasyl.jstackfx.search.exceptions.UnparsableQueryException; 8 | import javafx.beans.property.*; 9 | import javafx.collections.FXCollections; 10 | import javafx.collections.ObservableList; 11 | import javafx.scene.control.TextField; 12 | import javafx.scene.layout.StackPane; 13 | import javafx.scene.text.Text; 14 | import javafx.scene.text.TextAlignment; 15 | 16 | import java.util.Collection; 17 | import java.util.Objects; 18 | import java.util.logging.Level; 19 | import java.util.logging.Logger; 20 | 21 | /** 22 | * Control allowing to perform a search inside a set of data. The search is performed each time a key is released. 23 | * The control exposes two main properties to be used: 24 | *
    25 | *
  • {@link #dataSetProperty()} which is the data within which the search will be performed;
  • 26 | *
  • {@link #resultsProperty()} which represents the results of the search.
  • 27 | *
28 | *

29 | * The {@link #resultsProperty()} will always be a subset of {@link #dataSetProperty()}. 30 | * 31 | * @author Thierry Wasylczenko 32 | * @since JStackFX 1.1 33 | */ 34 | public class SearchField extends StackPane { 35 | private static final Logger LOGGER = Logger.getLogger(SearchField.class.getName()); 36 | 37 | protected TextField textField = new TextField(); 38 | protected OctIconView icon = new OctIconView(OctIcon.SEARCH); 39 | protected Text numberOfResults = new Text(); 40 | 41 | protected Query query; 42 | protected final DoubleProperty prefColumnCount = new SimpleDoubleProperty(); 43 | protected final ObjectProperty> searchingClass = new SimpleObjectProperty<>(); 44 | protected final ListProperty dataSet = new SimpleListProperty<>(FXCollections.observableArrayList()); 45 | protected final ReadOnlyListProperty results = new SimpleListProperty<>(FXCollections.observableArrayList()); 46 | 47 | public SearchField() { 48 | this.getStyleClass().add("search-field"); 49 | this.icon.getStyleClass().add("search"); 50 | 51 | this.prefColumnCount.bindBidirectional(this.textField.prefColumnCountProperty()); 52 | 53 | this.getChildren().addAll(this.textField, this.icon, this.numberOfResults); 54 | 55 | this.initializeKeyPressed(); 56 | this.initializeNumberOfResults(); 57 | } 58 | 59 | protected void initializeKeyPressed() { 60 | this.textField.setOnKeyReleased(event -> { 61 | if (LOGGER.isLoggable(Level.FINE)) { 62 | LOGGER.log(Level.FINE, this.textField.getText()); 63 | } 64 | 65 | final String cleanedText = this.getCleanedText(); 66 | 67 | if (cleanedText.isEmpty()) { 68 | this.clearResults(); 69 | this.addResults(this.dataSet); 70 | } else { 71 | if (this.query != null && !Objects.equals(query.getRawQuery(), cleanedText)) { 72 | try { 73 | if (query.parse(cleanedText)) { 74 | this.clearResults(); 75 | 76 | this.dataSet.forEach(data -> { 77 | if (query.match(data)) { 78 | this.addResult(data); 79 | } 80 | }); 81 | } 82 | } catch (UnparsableQueryException e) { 83 | if (LOGGER.isLoggable(Level.FINE)) { 84 | LOGGER.log(Level.WARNING, "Can not parse query", e); 85 | } 86 | } 87 | } 88 | } 89 | }); 90 | } 91 | 92 | protected void initializeNumberOfResults() { 93 | this.numberOfResults.getStyleClass().add("number"); 94 | this.numberOfResults.setWrappingWidth(50); 95 | this.numberOfResults.setTextAlignment(TextAlignment.RIGHT); 96 | this.numberOfResults.translateXProperty().bind(this.textField.widthProperty().subtract(this.numberOfResults.wrappingWidthProperty()).subtract(5)); 97 | this.numberOfResults.textProperty().bind(this.resultsProperty().sizeProperty().asString().concat("/").concat(this.dataSetProperty().sizeProperty().asString())); 98 | } 99 | 100 | /** 101 | * Clear the content of the search field. 102 | */ 103 | public void clear() { 104 | this.textField.clear(); 105 | } 106 | 107 | public DoubleProperty prefColumnCountProperty() { 108 | return prefColumnCount; 109 | } 110 | 111 | public double getPrefColumnCount() { 112 | return prefColumnCount.get(); 113 | } 114 | 115 | public void setPrefColumnCount(double prefColumnCount) { 116 | this.prefColumnCount.set(prefColumnCount); 117 | } 118 | 119 | protected String getCleanedText() { 120 | return this.textField.getText().trim(); 121 | } 122 | 123 | protected void clearResults() { 124 | ((SimpleListProperty) results).clear(); 125 | } 126 | 127 | protected void addResult(final T result) { 128 | ((SimpleListProperty) this.results).add(result); 129 | } 130 | 131 | protected void addResults(final Collection results) { 132 | ((SimpleListProperty) this.results).addAll(results); 133 | } 134 | 135 | public ObjectProperty> searchingClassProperty() { 136 | return searchingClass; 137 | } 138 | 139 | public Class getSearchingClass() { 140 | return searchingClass.get(); 141 | } 142 | 143 | public void setSearchingClass(Class searchingClass) { 144 | this.searchingClass.set(searchingClass); 145 | this.query = Query.create(searchingClass); 146 | } 147 | 148 | public ListProperty dataSetProperty() { 149 | return dataSet; 150 | } 151 | 152 | public ObservableList getDataSet() { 153 | return dataSet.get(); 154 | } 155 | 156 | public void setDataSet(ObservableList dataSet) { 157 | this.dataSet.set(dataSet); 158 | this.clearResults(); 159 | this.addResults(this.dataSet); 160 | } 161 | 162 | public ReadOnlyListProperty resultsProperty() { 163 | return results; 164 | } 165 | 166 | public ObservableList getResults() { 167 | return results.get(); 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/ui/TooltipUtils.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.ui; 2 | 3 | import javafx.beans.binding.StringExpression; 4 | import javafx.beans.property.DoubleProperty; 5 | import javafx.beans.property.SimpleStringProperty; 6 | import javafx.beans.property.StringProperty; 7 | import javafx.scene.chart.PieChart; 8 | import javafx.scene.control.Tooltip; 9 | 10 | /** 11 | * Utility class providing methods for working with {@link Tooltip}. 12 | * 13 | * @author Thierry Wasylczenko 14 | * @since JStackFX @@NEXT-VERSION@@ 15 | */ 16 | public class TooltipUtils { 17 | 18 | public static void addTooltipToData(final PieChart.Data blockedThreads, final String label) { 19 | addTooltipToData(blockedThreads, new SimpleStringProperty(label)); 20 | } 21 | 22 | public static void addTooltipToData(final PieChart.Data data, final StringProperty label) { 23 | data.nodeProperty().addListener((value, oldNode, newNode) -> { 24 | if (newNode != null) { 25 | Tooltip.install(newNode, createNumberedTooltip(label, data.pieValueProperty())); 26 | } 27 | }); 28 | } 29 | 30 | public static Tooltip createNumberedTooltip(final StringProperty label, final DoubleProperty value) { 31 | final StringExpression text = label.concat(": ").concat(value.asString("%.0f")); 32 | final Tooltip tooltip = new Tooltip(); 33 | tooltip.textProperty().bind(text); 34 | return tooltip; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/ui/cells/StateCell.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.ui.cells; 2 | 3 | import de.jensd.fx.glyphs.octicons.OctIcon; 4 | import de.jensd.fx.glyphs.octicons.OctIconView; 5 | import io.twasyl.jstackfx.beans.ThreadElement; 6 | import javafx.scene.control.TableCell; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | /** 12 | * Cell displaying an {@link OctIcon} according a {@link Thread.State}. 13 | * 14 | * @author Thierry Wasylczenko 15 | * @since JStackFX 1.0 16 | */ 17 | public class StateCell extends TableCell { 18 | 19 | private static final Map ICONS = new HashMap<>(); 20 | 21 | static { 22 | ICONS.put(Thread.State.NEW, OctIcon.PLUS); 23 | ICONS.put(Thread.State.RUNNABLE, OctIcon.SYNC); 24 | ICONS.put(Thread.State.WAITING, OctIcon.CLOCK); 25 | ICONS.put(Thread.State.TIMED_WAITING, OctIcon.CLOCK); 26 | ICONS.put(Thread.State.BLOCKED, OctIcon.STOP); 27 | ICONS.put(Thread.State.TERMINATED, OctIcon.CHECK); 28 | } 29 | 30 | public StateCell() { 31 | this.getStyleClass().add("state-cell"); 32 | } 33 | 34 | @Override 35 | protected void updateItem(Thread.State item, boolean empty) { 36 | super.updateItem(item, empty); 37 | if (!empty && item != null) { 38 | final OctIcon icon = ICONS.get(item); 39 | 40 | if (icon != null) { 41 | final OctIconView displayedIcon = new OctIconView(icon); 42 | displayedIcon.setGlyphSize(18); 43 | this.setGraphic(displayedIcon); 44 | } else { 45 | this.setGraphic(null); 46 | } 47 | } else { 48 | setGraphic(null); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/ui/cells/StateCellFactory.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.ui.cells; 2 | 3 | import io.twasyl.jstackfx.beans.ThreadElement; 4 | import javafx.scene.control.TableCell; 5 | import javafx.scene.control.TableColumn; 6 | import javafx.util.Callback; 7 | 8 | /** 9 | * Factory used to create {@link StateCell}. 10 | * 11 | * @author Thierry Wasylczenko 12 | * @since JStackFX 1.0 13 | */ 14 | public class StateCellFactory implements Callback, TableCell> { 15 | 16 | @Override 17 | public TableCell call(TableColumn column) { 18 | final StateCell cell = new StateCell(); 19 | 20 | return cell; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/ui/cells/ThreadElementRow.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.ui.cells; 2 | 3 | import com.sun.javafx.css.PseudoClassState; 4 | import io.twasyl.jstackfx.beans.ThreadElement; 5 | import javafx.css.PseudoClass; 6 | import javafx.scene.control.TableRow; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | /** 12 | * Class representing a {@link ThreadElement} within a {@link javafx.scene.control.TableView} of elements. 13 | * 14 | * @author Thierry Wasylczenko 15 | * @since JStackFX 1.0 16 | */ 17 | public class ThreadElementRow extends TableRow { 18 | 19 | private static final Map PSEUDO_CLASS_STATES = new HashMap<>(); 20 | 21 | static { 22 | PSEUDO_CLASS_STATES.put(Thread.State.NEW, PseudoClassState.getPseudoClass("new")); 23 | PSEUDO_CLASS_STATES.put(Thread.State.RUNNABLE, PseudoClassState.getPseudoClass("runnable")); 24 | PSEUDO_CLASS_STATES.put(Thread.State.WAITING, PseudoClassState.getPseudoClass("waiting")); 25 | PSEUDO_CLASS_STATES.put(Thread.State.TIMED_WAITING, PseudoClassState.getPseudoClass("timed-waiting")); 26 | PSEUDO_CLASS_STATES.put(Thread.State.BLOCKED, PseudoClassState.getPseudoClass("blocked")); 27 | PSEUDO_CLASS_STATES.put(Thread.State.TERMINATED, PseudoClassState.getPseudoClass("terminated")); 28 | } 29 | 30 | @Override 31 | protected void updateItem(ThreadElement item, boolean empty) { 32 | super.updateItem(item, empty); 33 | 34 | PSEUDO_CLASS_STATES.forEach((sate, pseudoClass) -> { 35 | this.pseudoClassStateChanged(pseudoClass, false); 36 | }); 37 | 38 | if(!empty && item != null) { 39 | this.pseudoClassStateChanged(PSEUDO_CLASS_STATES.get(item.getState()), true); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/ui/cells/ThreadElementRowFactory.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.ui.cells; 2 | 3 | import io.twasyl.jstackfx.beans.ThreadElement; 4 | import javafx.scene.control.TableRow; 5 | import javafx.scene.control.TableView; 6 | import javafx.util.Callback; 7 | 8 | /** 9 | * @author Thierry Wasylczenko 10 | * @since JStackFX 1.0 11 | */ 12 | public class ThreadElementRowFactory implements Callback, TableRow> { 13 | 14 | @Override 15 | public TableRow call(TableView param) { 16 | final ThreadElementRow row = new ThreadElementRow(); 17 | 18 | return row; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/ui/cells/ThreadListCellFactory.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.ui.cells; 2 | 3 | import io.twasyl.jstackfx.beans.ThreadElement; 4 | import javafx.event.EventHandler; 5 | import javafx.scene.Cursor; 6 | import javafx.scene.control.TableCell; 7 | import javafx.scene.control.TableColumn; 8 | import javafx.scene.input.MouseButton; 9 | import javafx.scene.input.MouseEvent; 10 | import javafx.scene.text.Text; 11 | import javafx.scene.text.TextFlow; 12 | import javafx.util.Callback; 13 | 14 | import java.util.Iterator; 15 | import java.util.Set; 16 | 17 | /** 18 | * Class responsible of creating cells that lists a collection of {@link ThreadElement}. 19 | * 20 | * @author Thierry Wasylczenko 21 | * @since JStackFX 1.0 22 | */ 23 | public class ThreadListCellFactory implements Callback>, TableCell>> { 24 | @Override 25 | public TableCell> call(TableColumn> param) { 26 | final TableCell> cell = new TableCell>() { 27 | @Override 28 | protected void updateItem(Set item, boolean empty) { 29 | super.updateItem(item, empty); 30 | 31 | if (item != null && !item.isEmpty() && !empty) { 32 | final TextFlow threadList = buildThreadListGraphic(this, item); 33 | 34 | if (this.prefHeightProperty().isBound()) { 35 | this.prefHeightProperty().unbind(); 36 | } 37 | 38 | this.prefHeightProperty().bind(threadList.heightProperty()); 39 | threadList.prefWidthProperty().bind(this.widthProperty().subtract(-5)); 40 | 41 | this.setGraphic(threadList); 42 | this.layout(); 43 | } else { 44 | this.setGraphic(null); 45 | } 46 | } 47 | }; 48 | 49 | return cell; 50 | } 51 | 52 | protected TextFlow buildThreadListGraphic(final TableCell> cell, final Set threads) { 53 | final TextFlow threadsGraphic = new TextFlow(); 54 | threadsGraphic.setPrefHeight(20); 55 | 56 | final Iterator threadIterator = threads.iterator(); 57 | while (threadIterator.hasNext()) { 58 | final ThreadElement thread = threadIterator.next(); 59 | 60 | threadsGraphic.getChildren().add(buildThreadLink(cell, thread)); 61 | 62 | if (threadIterator.hasNext()) { 63 | threadsGraphic.getChildren().add(buildThreadSeparator()); 64 | } 65 | } 66 | return threadsGraphic; 67 | } 68 | 69 | protected Text buildThreadLink(final TableCell> cell, final ThreadElement thread) { 70 | final Text threadText = new Text(thread.getName()); 71 | threadText.getStyleClass().add("text"); 72 | 73 | threadText.setOnMouseClicked(ThreadListCellFactory.this.buildMouseClickedEventHandler(cell, thread)); 74 | threadText.setOnMouseEntered(event -> threadText.setCursor(Cursor.HAND)); 75 | 76 | return threadText; 77 | } 78 | 79 | protected Text buildThreadSeparator() { 80 | final Text separator = new Text(", "); 81 | separator.getStyleClass().add("text"); 82 | return separator; 83 | } 84 | 85 | protected EventHandler buildMouseClickedEventHandler(final TableCell> cell, final ThreadElement thread) { 86 | final EventHandler handler = event -> { 87 | if (event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 1) { 88 | cell.getTableView().getSelectionModel().select(thread); 89 | } 90 | }; 91 | 92 | return handler; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/ui/charts/LocalDateTimeAxis.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.ui.charts; 2 | 3 | import javafx.beans.property.LongProperty; 4 | import javafx.beans.property.SimpleLongProperty; 5 | import javafx.scene.chart.Axis; 6 | import javafx.scene.chart.NumberAxis; 7 | import javafx.scene.chart.ValueAxis; 8 | 9 | import java.time.Instant; 10 | import java.time.LocalDateTime; 11 | import java.time.ZoneId; 12 | import java.time.ZoneOffset; 13 | import java.time.temporal.ChronoField; 14 | import java.util.List; 15 | 16 | /** 17 | * @author Thierry Wasylczenko 18 | * @since JStackFX @@NEXT-VERSION@@ 19 | */ 20 | public class LocalDateTimeAxis extends Axis { 21 | 22 | protected final LongProperty lowerBound = new SimpleLongProperty(); 23 | protected final LongProperty upperBound = new SimpleLongProperty(); 24 | 25 | protected LocalDateTime minDate; 26 | protected LocalDateTime maxDate; 27 | 28 | @Override 29 | protected Object autoRange(double length) { 30 | if(isAutoRanging()) { 31 | return new LocalDateTime[] { minDate, maxDate }; 32 | } else { 33 | return getRange(); 34 | } 35 | } 36 | 37 | @Override 38 | protected void setRange(Object range, boolean animate) { 39 | LocalDateTime[] dateTimesRange = (LocalDateTime[]) range; 40 | 41 | this.minDate = dateTimesRange[0]; 42 | this.maxDate = dateTimesRange[1]; 43 | } 44 | 45 | @Override 46 | protected Object getRange() { 47 | return new LocalDateTime[] { minDate, maxDate }; 48 | } 49 | 50 | @Override 51 | public double getZeroPosition() { 52 | return 0; 53 | } 54 | 55 | @Override 56 | public double getDisplayPosition(LocalDateTime value) { 57 | final double axisLength = getSide().isHorizontal() ? getWidth() : getHeight(); 58 | final double datesDiff = toNumericValue(this.maxDate) - toNumericValue(this.minDate); 59 | 60 | return 0; 61 | } 62 | 63 | @Override 64 | public LocalDateTime getValueForDisplay(double displayPosition) { 65 | 66 | return null; 67 | } 68 | 69 | @Override 70 | public boolean isValueOnAxis(LocalDateTime value) { 71 | if(value == null) return false; 72 | else { 73 | final double valueX = toNumericValue(value); 74 | final double minX = toNumericValue(this.minDate); 75 | final double maxX = toNumericValue(this.maxDate); 76 | 77 | return valueX >= minX && valueX < maxX; 78 | } 79 | } 80 | 81 | @Override 82 | public double toNumericValue(LocalDateTime value) { 83 | return value.toInstant(ZoneOffset.ofTotalSeconds(0)).toEpochMilli(); 84 | } 85 | 86 | @Override 87 | public LocalDateTime toRealValue(double value) { 88 | final long timestamp = new Double(value).longValue(); 89 | return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()); 90 | } 91 | 92 | @Override 93 | protected List calculateTickValues(double length, Object range) { 94 | return null; 95 | } 96 | 97 | @Override 98 | protected String getTickMarkLabel(LocalDateTime value) { 99 | return null; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/ui/charts/LockedSynchronizersRepartitionChart.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.ui.charts; 2 | 3 | import io.twasyl.jstackfx.beans.Dump; 4 | import io.twasyl.jstackfx.beans.ThreadElement; 5 | import io.twasyl.jstackfx.beans.ThreadReference; 6 | import io.twasyl.jstackfx.ui.TooltipUtils; 7 | import javafx.beans.property.ObjectProperty; 8 | import javafx.beans.property.SimpleObjectProperty; 9 | import javafx.scene.chart.PieChart; 10 | 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | 14 | /** 15 | * An implementation of {@link PieChart} showing the most locked synchronizers in a {@link Dump}. 16 | * 17 | * @author Thierry Wasylczenko 18 | * @since JStackFX @@NEXT-VERSION@@ 19 | */ 20 | public class LockedSynchronizersRepartitionChart extends PieChart { 21 | private final ObjectProperty dump = new SimpleObjectProperty<>(null); 22 | 23 | public LockedSynchronizersRepartitionChart() { 24 | this.initializeDumpProperty(); 25 | this.setTitle("Locked synchronizers repartition"); 26 | this.setLabelsVisible(false); 27 | } 28 | 29 | /** 30 | * Initialize the {@link #dumpProperty()} to react to changes. 31 | */ 32 | private void initializeDumpProperty() { 33 | this.dump.addListener((value, oldDump, newDump) -> { 34 | this.clearSeries(); 35 | 36 | if (newDump != null) { 37 | this.populateChart(newDump); 38 | } 39 | }); 40 | } 41 | 42 | private void populateChart(final Dump dump) { 43 | final Map data = new HashMap<>(); 44 | 45 | for (final ThreadElement thread : dump.getElements()) { 46 | for (final ThreadReference synchronizer : thread.getLockedSynchronizers()) { 47 | if (!data.containsKey(synchronizer.getClassName())) { 48 | final Data synchronizerData = new PieChart.Data(synchronizer.getClassName(), 0); 49 | TooltipUtils.addTooltipToData(synchronizerData, synchronizerData.nameProperty()); 50 | data.put(synchronizer.getClassName(), synchronizerData); 51 | } 52 | 53 | final PieChart.Data synchronizerData = data.get(synchronizer.getClassName()); 54 | synchronizerData.setPieValue(synchronizerData.getPieValue() + 1); 55 | } 56 | } 57 | this.getData().clear(); 58 | this.getData().addAll(data.values()); 59 | } 60 | 61 | /** 62 | * Removes all series of the chart. 63 | */ 64 | private void clearSeries() { 65 | this.getData().clear(); 66 | } 67 | 68 | public ObjectProperty dumpProperty() { return this.dump; } 69 | public Dump getDump() { return dump.get(); } 70 | public void setDump(Dump dump) { this.dump.set(dump); } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/ui/charts/StateRepartitionChart.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.ui.charts; 2 | 3 | import io.twasyl.jstackfx.beans.Dump; 4 | import io.twasyl.jstackfx.ui.TooltipUtils; 5 | import javafx.beans.property.ObjectProperty; 6 | import javafx.beans.property.SimpleObjectProperty; 7 | import javafx.collections.FXCollections; 8 | import javafx.scene.chart.PieChart; 9 | 10 | import java.util.Map; 11 | 12 | /** 13 | * An implementation of {@link PieChart} that shows the by state of all {@link Dump#getElements() elements} of a 14 | * {@link Dump dump}. 15 | * 16 | * @author Thierry Wasylczenko 17 | * @since JStackFX @@NEXT-VERSION@@ 18 | */ 19 | public class StateRepartitionChart extends PieChart { 20 | private final ObjectProperty dump = new SimpleObjectProperty<>(null); 21 | 22 | private final Data newThreads = new Data(Thread.State.NEW.name(), 0); 23 | private final Data runnableThreads = new Data(Thread.State.RUNNABLE.name(), 0); 24 | private final Data waitingThreads = new Data(Thread.State.WAITING.name() + "/" + Thread.State.TIMED_WAITING.name(), 0); 25 | private final Data blockedThreads = new Data(Thread.State.BLOCKED.name(), 0); 26 | private final Data terminatedThreads = new Data(Thread.State.TERMINATED.name(), 0); 27 | 28 | public StateRepartitionChart() { 29 | this.initializeSeries(); 30 | this.initializeDumpProperty(); 31 | this.setTitle("Thread repartition by state"); 32 | this.setLabelsVisible(false); 33 | } 34 | 35 | /** 36 | * Initialize the series used in the chart. 37 | */ 38 | private void initializeSeries() { 39 | TooltipUtils.addTooltipToData(newThreads, "New threads"); 40 | TooltipUtils.addTooltipToData(runnableThreads, "Runnable threads"); 41 | TooltipUtils.addTooltipToData(waitingThreads, "Waiting threads"); 42 | TooltipUtils.addTooltipToData(blockedThreads, "Blocked threads"); 43 | TooltipUtils.addTooltipToData(terminatedThreads, "Terminated threads"); 44 | 45 | this.setData(FXCollections.observableArrayList(newThreads, runnableThreads, waitingThreads, blockedThreads, terminatedThreads)); 46 | } 47 | 48 | /** 49 | * Initialize the {@link #dumpProperty()} to react to changes. 50 | */ 51 | private void initializeDumpProperty() { 52 | this.dump.addListener((value, oldDump, newDump) -> { 53 | this.clearSeries(); 54 | 55 | if (newDump != null) { 56 | this.populateSeries(newDump); 57 | } 58 | }); 59 | } 60 | 61 | /** 62 | * Set the value of all series to 0. 63 | */ 64 | private void clearSeries() { 65 | this.newThreads.setPieValue(0); 66 | this.runnableThreads.setPieValue(0); 67 | this.waitingThreads.setPieValue(0); 68 | this.blockedThreads.setPieValue(0); 69 | this.terminatedThreads.setPieValue(0); 70 | } 71 | 72 | /** 73 | * Set the value of each serie of the chart according the given {@link Dump} 74 | * 75 | * @param dump The dump used to populate the series. 76 | */ 77 | private void populateSeries(final Dump dump) { 78 | final Map statesCounter = dump.countNumberOfThreadsByState(); 79 | if (statesCounter.containsKey(Thread.State.NEW)) { 80 | newThreads.setPieValue(statesCounter.get(Thread.State.NEW)); 81 | } 82 | 83 | if (statesCounter.containsKey(Thread.State.RUNNABLE)) { 84 | runnableThreads.setPieValue(statesCounter.get(Thread.State.RUNNABLE)); 85 | } 86 | 87 | if (statesCounter.containsKey(Thread.State.TIMED_WAITING)) { 88 | waitingThreads.setPieValue(statesCounter.get(Thread.State.TIMED_WAITING)); 89 | } 90 | 91 | if (statesCounter.containsKey(Thread.State.WAITING)) { 92 | waitingThreads.setPieValue(waitingThreads.getPieValue() + statesCounter.get(Thread.State.WAITING)); 93 | } 94 | 95 | if (statesCounter.containsKey(Thread.State.BLOCKED)) { 96 | blockedThreads.setPieValue(statesCounter.get(Thread.State.BLOCKED)); 97 | } 98 | 99 | if (statesCounter.containsKey(Thread.State.TERMINATED)) { 100 | terminatedThreads.setPieValue(statesCounter.get(Thread.State.TERMINATED)); 101 | } 102 | } 103 | 104 | public ObjectProperty dumpProperty() { return this.dump; } 105 | public Dump getDump() { return dump.get(); } 106 | public void setDump(Dump dump) { this.dump.set(dump); } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/io/twasyl/jstackfx/ui/charts/StateRepartitionTimelineChart.java: -------------------------------------------------------------------------------- 1 | package io.twasyl.jstackfx.ui.charts; 2 | 3 | import io.twasyl.jstackfx.beans.Dump; 4 | import io.twasyl.jstackfx.beans.DumpTimeline; 5 | import javafx.beans.property.ObjectProperty; 6 | import javafx.beans.property.SimpleObjectProperty; 7 | import javafx.collections.FXCollections; 8 | import javafx.scene.chart.*; 9 | import javafx.util.StringConverter; 10 | 11 | import java.time.Instant; 12 | import java.time.LocalDateTime; 13 | import java.time.ZoneId; 14 | import java.time.ZoneOffset; 15 | import java.time.format.DateTimeFormatter; 16 | import java.util.Comparator; 17 | import java.util.List; 18 | import java.util.Map; 19 | import java.util.stream.Collectors; 20 | 21 | /** 22 | * @author Thierry Wasylczenko 23 | * @since JStackFX @@NEXT-VERSION@@ 24 | */ 25 | public class StateRepartitionTimelineChart extends LineChart { 26 | protected static final DateTimeFormatter DATE_TIME_FORMATTER_OUTPUT = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"); 27 | 28 | private final ObjectProperty dumpTimeline = new SimpleObjectProperty<>(null); 29 | 30 | private final Series newThreads = new Series(); 31 | private final Series runnableThreads = new Series(); 32 | private final Series waitingThreads = new Series(); 33 | private final Series blockedThreads = new Series(); 34 | private final Series terminatedThreads = new Series(); 35 | 36 | private final NumberAxis xAxis; 37 | private final NumberAxis yAxis; 38 | 39 | public StateRepartitionTimelineChart() { 40 | super(new NumberAxis(), new NumberAxis()); 41 | 42 | this.xAxis = (NumberAxis) getXAxis(); 43 | this.yAxis = (NumberAxis) getYAxis(); 44 | 45 | this.xAxis.setTickLabelFormatter(new StringConverter() { 46 | @Override 47 | public String toString(Number object) { 48 | if(object == null) return null; 49 | else { 50 | return DATE_TIME_FORMATTER_OUTPUT.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(object.longValue()), ZoneId.systemDefault())); 51 | } 52 | } 53 | 54 | @Override 55 | public Number fromString(String string) { 56 | if(string == null || string.isEmpty()) return null; 57 | else { 58 | return LocalDateTime.parse(string, DATE_TIME_FORMATTER_OUTPUT).toInstant(ZoneOffset.ofTotalSeconds(0)).toEpochMilli(); 59 | } 60 | } 61 | }); 62 | 63 | this.initializeDumpTimelineProperty(); 64 | this.initializeSeries(); 65 | } 66 | 67 | /** 68 | * Initialize the series used in the chart. 69 | */ 70 | private void initializeSeries() { 71 | newThreads.setName("New threads"); 72 | runnableThreads.setName("Runnable threads"); 73 | waitingThreads.setName("Waiting threads"); 74 | blockedThreads.setName("Blocked threads"); 75 | terminatedThreads.setName("Terminated threads"); 76 | 77 | this.setData(FXCollections.observableArrayList(newThreads, runnableThreads, waitingThreads, blockedThreads, terminatedThreads)); 78 | } 79 | 80 | /** 81 | * Initialize the {@link #dumpTimelineProperty()} to react to changes. 82 | */ 83 | private void initializeDumpTimelineProperty() { 84 | this.dumpTimeline.addListener((value, oldTimeline, newTimeline) -> { 85 | this.clearSeries(); 86 | 87 | if (newTimeline != null) { 88 | this.populateSeries(newTimeline); 89 | } 90 | }); 91 | } 92 | 93 | /** 94 | * Set the value of all series to 0. 95 | */ 96 | private void clearSeries() { 97 | this.newThreads.getData().clear(); 98 | this.runnableThreads.getData().clear(); 99 | this.waitingThreads.getData().clear(); 100 | this.blockedThreads.getData().clear(); 101 | this.terminatedThreads.getData().clear(); 102 | } 103 | 104 | /** 105 | * Set the value of each serie of the chart according the given {@link Dump} 106 | * 107 | * @param dumpTimeline The timeline used to populate the series. 108 | */ 109 | private void populateSeries(final DumpTimeline dumpTimeline) { 110 | dumpTimeline.getDumps().forEach(dump -> { 111 | final Map counters = dump.countNumberOfThreadsByState(); 112 | final ZoneOffset zoneOffset = ZoneId.systemDefault().getRules().getOffset(dump.getGenerationDateTime()); 113 | final long generationTimestamp = dump.getGenerationDateTime().toInstant(zoneOffset).toEpochMilli(); 114 | 115 | if(counters.containsKey(Thread.State.NEW)) { 116 | this.newThreads.getData().add(new Data<>(generationTimestamp, counters.get(Thread.State.NEW))); 117 | } 118 | 119 | if(counters.containsKey(Thread.State.RUNNABLE)) { 120 | this.runnableThreads.getData().add(new Data<>(generationTimestamp, counters.get(Thread.State.RUNNABLE))); 121 | } 122 | 123 | Data waitingData = new Data<>(generationTimestamp, 0l); 124 | 125 | if(counters.containsKey(Thread.State.WAITING)) { 126 | waitingData.setYValue(counters.get(Thread.State.WAITING)); 127 | } 128 | 129 | if(counters.containsKey(Thread.State.TIMED_WAITING)) { 130 | waitingData.setYValue(waitingData.getYValue().longValue() + counters.get(Thread.State.TIMED_WAITING)); 131 | } 132 | 133 | if(waitingData.getXValue().longValue() > 0) { 134 | this.waitingThreads.getData().add(waitingData); 135 | } 136 | 137 | if(counters.containsKey(Thread.State.BLOCKED)) { 138 | this.blockedThreads.getData().add(new Data<>(generationTimestamp, counters.get(Thread.State.BLOCKED))); 139 | } 140 | 141 | if(counters.containsKey(Thread.State.TERMINATED)) { 142 | this.terminatedThreads.getData().add(new Data<>(generationTimestamp, counters.get(Thread.State.TERMINATED))); 143 | } 144 | }); 145 | } 146 | 147 | public ObjectProperty dumpTimelineProperty() { return this.dumpTimeline; } 148 | public DumpTimeline getDumpTimeline() { return dumpTimeline.get(); } 149 | public void setDumpTimeline(DumpTimeline dumpTimeline) { this.dumpTimeline.set(dumpTimeline); } 150 | } 151 | -------------------------------------------------------------------------------- /src/main/resources/io/twasyl/jstackfx/css/default.css: -------------------------------------------------------------------------------- 1 | .root { 2 | -fx-thread-new: #337ab7; 3 | -fx-thread-runnable: #5cb85c; 4 | -fx-thread-waiting: #f0ad4e; 5 | -fx-thread-blocked: #d9534f; 6 | -fx-thread-terminated: #5bc0de; 7 | } 8 | 9 | .tool-bar { 10 | -fx-alignment: BASELINE_LEFT; 11 | } 12 | 13 | /** Table Cells */ 14 | .table-view *.glyph-icon { -fx-fill: white; } 15 | 16 | .cell { 17 | -fx-border-width: 0; 18 | -fx-text-fill: white; 19 | } 20 | 21 | .cell *.text { -fx-text-fill: white; -fx-fill: white; } 22 | 23 | .table-row-cell *.centered-cell { -fx-alignment: center; } 24 | 25 | .state-cell { -fx-alignment: baseline-center; } 26 | 27 | .cell:new { -fx-background-color: -fx-thread-new; } 28 | .cell:new:focused { -fx-background-color: derive(-fx-thread-new, -20%); } 29 | 30 | .cell:runnable { -fx-background-color: -fx-thread-runnable; } 31 | .cell:runnable:focused { -fx-background-color: derive(-fx-thread-runnable, -20%); } 32 | 33 | .cell:waiting, .cell:timed-waiting { -fx-background-color: -fx-thread-waiting; } 34 | .cell:waiting:focused, .cell:timed-waiting:focused { -fx-background-color: derive(-fx-thread-waiting, -20%); } 35 | .cell:waiting .label, .cell:timed-waiting .label { -fx-fill: white; } 36 | 37 | .cell:blocked { -fx-background-color: -fx-thread-blocked; } 38 | .cell:blocked:focused { -fx-background-color: derive(-fx-thread-blocked, -20%); } 39 | 40 | .cell:terminated { -fx-background-color: -fx-thread-terminated; } 41 | .cell:terminated:focused { -fx-background-color: derive(-fx-thread-terminated, -20%); } 42 | 43 | /** Pie Chart customization */ 44 | .data0.chart-pie { -fx-pie-color: -fx-thread-new; } 45 | .data1.chart-pie { -fx-pie-color: -fx-thread-runnable; } 46 | .data2.chart-pie { -fx-pie-color: -fx-thread-waiting; } 47 | .data3.chart-pie { -fx-pie-color: -fx-thread-blocked; } 48 | .data4.chart-pie { -fx-pie-color: -fx-thread-terminated; } 49 | 50 | /** Search field */ 51 | .search-field { -fx-alignment: BASELINE_LEFT; } 52 | .search-field .text-field { -fx-padding: 6px 60px 6px 30px; } 53 | .search-field .search { -fx-translate-x: 10px; } 54 | .search-field .number { -fx-fill: lightgray; } 55 | 56 | /** Thread element nodes */ 57 | #threadElementDetails { -fx-padding: 5px ; } 58 | 59 | #threadElementSource { -fx-font-family: 'Courier New'; -fx-padding: 5px; } 60 | #threadElementSource, 61 | #threadElementSource .content, 62 | #threadElementSource .scroll-pane { -fx-background-color: transparent; } -------------------------------------------------------------------------------- /src/main/resources/io/twasyl/jstackfx/fxml/jstackfx.fxml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 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 | 52 | 60 | 61 | 69 | 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 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 |