From 0347064423d8594c7f54eb86956f806716fcbafe Mon Sep 17 00:00:00 2001 From: Alex Cheung Date: Sat, 28 Jun 2025 00:44:19 +0800 Subject: [PATCH] add get jvm info --- src/pages/JVM/index.js | 283 +++++++++++--------------------------- src/utils/ApiPathConst.js | 3 + 2 files changed, 87 insertions(+), 199 deletions(-) diff --git a/src/pages/JVM/index.js b/src/pages/JVM/index.js index 561b6d8..a719cad 100644 --- a/src/pages/JVM/index.js +++ b/src/pages/JVM/index.js @@ -4,233 +4,118 @@ import { Grid, Typography, - Stack + Stack, + Paper, + Box, + CircularProgress, + Button } from '@mui/material'; import * as React from "react"; +import { GET_JVM_INFO } from "utils/ApiPathConst"; +import axios from "axios"; import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png' -// ==============================|| DASHBOARD - DEFAULT ||============================== // const JVMDefault = () => { - // const userData = JSON.parse(localStorage.getItem("userData")); + const [jvmInfo, setJvmInfo] = React.useState(null); + const [loading, setLoading] = React.useState(true); + const [error, setError] = React.useState(null); + const fetchJvmInfo = () => { + setLoading(true); + setError(null); + axios.get(`${GET_JVM_INFO}`) + .then((response) => { + if (response.status === 200) { + console.log(response) + setJvmInfo(response.data); + } + }) + .catch(error => { + setError(error); + setLoading(false); + }); + }; + + React.useEffect(() => { + localStorage.setItem('searchCriteria', ""); + setLoading(false); + }, []); + React.useEffect(() => { - localStorage.setItem('searchCriteria',"") - }, []) + if(jvmInfo != null) { + if (Object.keys(jvmInfo).length > 0 && jvmInfo !== undefined) { + setLoading(false); + } + } + }, [jvmInfo]); const BackgroundHead = { backgroundImage: `url(${titleBackgroundImg})`, width: '100%', height: '100%', - backgroundSize:'contain', + backgroundSize: 'contain', backgroundRepeat: 'no-repeat', backgroundColor: '#0C489E', backgroundPosition: 'right' - } - - const htmlContent = ` - -
-

Certainly! Here's the complete implementation, showing both the updated Java controller to provide JVM - information in MB, and the corresponding UI code that will display the information. -

-

Step 1: Java Code (Controller)

-

This Spring Boot controller exposes the JVM information (including heap memory usage, operating system - details, and uptime) in MB, and it provides it via a REST API (/jvm-info). -

-

-        import org.springframework.web.bind.annotation.GetMapping;
-        import org.springframework.web.bind.annotation.RestController;
-
-        import java.lang.management.ManagementFactory;
-        import java.lang.management.MemoryMXBean;
-        import java.lang.management.MemoryUsage;
-        import java.lang.management.OperatingSystemMXBean;
-        import java.util.HashMap;
-        import java.util.Map;
-
-        @RestController
-        public class JvmInfoController {
-
-            @GetMapping("/jvm-info")
-            public Map getJvmInfo() {
-                Map jvmInfo = new HashMap<>();
-
-                // Get the Operating System MXBean for system-related info
-                OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
-                jvmInfo.put("osName", osBean.getName());
-                jvmInfo.put("osVersion", osBean.getVersion());
-                jvmInfo.put("osArch", osBean.getArch());
-
-                // Get memory info and convert bytes to MB
-                MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
-                MemoryUsage heapMemoryUsage = memoryBean.getHeapMemoryUsage();
-                jvmInfo.put("heapMemoryInitMB", bytesToMB(heapMemoryUsage.getInit()));
-                jvmInfo.put("heapMemoryUsedMB", bytesToMB(heapMemoryUsage.getUsed()));
-                jvmInfo.put("heapMemoryMaxMB", bytesToMB(heapMemoryUsage.getMax()));
-                jvmInfo.put("heapMemoryCommittedMB", bytesToMB(heapMemoryUsage.getCommitted()));
-
-                // Get JVM uptime and other stats
-                long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
-                jvmInfo.put("jvmUptimeMillis", uptime);
-
-                return jvmInfo;
-            }
-
-            // Helper function to convert bytes to MB
-            private long bytesToMB(long bytes) {
-                return bytes / (1024 * 1024);
-            }
-        }
-      
- -

Step 2: Frontend UI (HTML + JavaScript)

-

Here’s the frontend HTML page that will display the JVM information in a clean and readable format. It - uses JavaScript (fetch API) to get data from the /jvm-info endpoint and display it in a pre block -

-
-        <!DOCTYPE html>
-        <html lang="en">
-        <head>
-            <meta charset="UTF-8">
-            <meta name="viewport" content="width=device-width, initial-scale=1.0">
-            <title>JVM Information</title>
-            <style>
-                body {
-                    font-family: Arial, sans-serif;
-                    margin: 20px;
-                }
-                h1 {
-                    color: #333;
-                }
-                pre {
-                    background-color: #f4f4f4;
-                    padding: 10px;
-                    border-radius: 5px;
-                    font-size: 14px;
-                    line-height: 1.6;
-                    color: #333;
-                    max-height: 400px;
-                    overflow-y: scroll;
-                }
-                .container {
-                    max-width: 800px;
-                    margin: 0 auto;
-                }
-            </style>
-            <script>
-                function fetchJvmInfo() {
-                    fetch('/jvm-info')
-                        .then(response => response.json())
-                        .then(data => {
-                            document.getElementById("jvmInfo").innerHTML = JSON.stringify(data, null, 2);
-                        })
-                        .catch(error => console.error('Error fetching JVM info:', error));
-                }
-
-                window.onload = fetchJvmInfo;
-            </script>
-        </head>
-        <body>
-            <div class="container">
-                <h1>JVM Information</h1>
-                <pre id="jvmInfo">Loading...</pre>
-            </div>
-        </body>
-        </html>
-      
- -

Breakdown of the Information Displayed

-

1. Operating System Info:

- - -

2. Memory Usage Info:

- - -

3. JVM Uptime:

- - -

Example JSON Output (after fetching data):

-

If the /jvm-info API returns the following JSON, it will be displayed on the UI:

-
-        {
-          "osName": "Windows 10",
-          "osVersion": "10.0",
-          "osArch": "amd64",
-          "heapMemoryInitMB": 128,
-          "heapMemoryUsedMB": 50,
-          "heapMemoryMaxMB": 1024,
-          "heapMemoryCommittedMB": 512,
-          "jvmUptimeMillis": 123456789
-        }
-      
- -

UI Display Example

-

On the webpage, this information will be displayed as follows in a neatly formatted block:

-
-        JVM Information
-        {
-          "osName": "Windows 10",
-          "osVersion": "10.0",
-          "osArch": "amd64",
-          "heapMemoryInitMB": 128,
-          "heapMemoryUsedMB": 50,
-          "heapMemoryMaxMB": 1024,
-          "heapMemoryCommittedMB": 512,
-          "jvmUptimeMillis": 123456789
-        }
-      
-

Styling and Functionality:

-
    -
  1. Styling:The page has simple, clean styling with a scrollable pre block to display the JSON output in an organized manner. You can easily tweak the look and feel using CSS.
  2. -
  3. Dynamic Fetching:When the page loads, it automatically fetches the JVM information from the backend and updates the UI.
  4. -
- -

Optional Enhancements

-
    -
  1. Graphical Visualization: You could use a library like Chart.js to visualize memory usage in graphs (e.g., pie charts for heap memory)
  2. -
  3. Auto-Refresh: You can add a refresh button or periodically fetch the data at a set interval (e.g., every 30 seconds) using setInterval() in JavaScript
  4. -
-

Let me know if you need further help with customization or any other features!

-
- `; + }; return ( - +
- + JVM Information
- -
+ + + + + + {loading ? ( + + + + ) : error ? ( + Error: {error.message} + ) : jvmInfo ? ( + + {JSON.stringify(jvmInfo, null, 2)} + + ) : ( + No data available + )} + ); }; -export default JVMDefault; +export default JVMDefault; \ No newline at end of file diff --git a/src/utils/ApiPathConst.js b/src/utils/ApiPathConst.js index 8879c99..c9d6c7b 100644 --- a/src/utils/ApiPathConst.js +++ b/src/utils/ApiPathConst.js @@ -237,3 +237,6 @@ export const GET_HOLIDAY = apiPath+'/holiday/list'; //GET export const POST_HOLIDAY = apiPath+'/holiday/import'; //POST export const GET_HOLIDAY_COMBO = apiPath+'/holiday/combo'; //GET export const GET_HOLIDAY_TEMPLATE = apiPath+'/holiday/export'; //GET + + +export const GET_JVM_INFO = apiPath+'/jvm-info'; //GET