Преглед изворни кода

add get jvm info

New_Enhancement
Alex Cheung пре 2 месеци
родитељ
комит
0347064423
2 измењених фајлова са 87 додато и 199 уклоњено
  1. +84
    -199
      src/pages/JVM/index.js
  2. +3
    -0
      src/utils/ApiPathConst.js

+ 84
- 199
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 = `
<style>
pre {
background-color: #333333; /* Dark gray background */
color: white; /* White text */
padding: 15px; /* Add some padding */
border-radius: 5px; /* Rounded corners */
overflow-x: auto; /* Add horizontal scroll if needed */
width: 90%; /* 90% width */
}
</style>
<div>
<p>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.
</p>
<h2>Step 1: Java Code (Controller)</h2>
<p>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).
<p>
<pre>
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<String, Object> getJvmInfo() {
Map<String, Object> 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);
}
}
</pre>

<h2>Step 2: Frontend UI (HTML + JavaScript)</h2>
<p>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
</p>
<pre>
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="UTF-8"&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
&lt;title&gt;JVM Information&lt;/title&gt;
&lt;style&gt;
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;
}
&lt;/style&gt;
&lt;script&gt;
function fetchJvmInfo() {
fetch('/jvm-info')
.then(response =&gt; response.json())
.then(data =&gt; {
document.getElementById("jvmInfo").innerHTML = JSON.stringify(data, null, 2);
})
.catch(error =&gt; console.error('Error fetching JVM info:', error));
}

window.onload = fetchJvmInfo;
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div class="container"&gt;
&lt;h1&gt;JVM Information&lt;/h1&gt;
&lt;pre id="jvmInfo"&gt;Loading...&lt;/pre&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>

<h2>Breakdown of the Information Displayed</h2>
<h3>1. Operating System Info:</h3>
<ul>
<li><strong>osName:</strong> The name of the operating system (e.g., Windows, Linux)</li>
<li><strong>osVersion:</strong> The version of the operating system</li>
<li><strong>osArch:</strong> The architecture of the operating system (e.g., x86_64)</li>
</ul>

<h3>2. Memory Usage Info:</h3>
<ul>
<li><strong>heapMemoryInitMB:</strong> The initial heap memory available to the JVM (in MB)</li>
<li><strong>heapMemoryUsedMB:</strong> The current memory being used by the JVM (in MB)</li>
<li><strong>heapMemoryMaxMB:</strong> The maximum heap memory that the JVM can use (in MB)</li>
<li><strong>heapMemoryCommittedMB:</strong> The amount of memory committed by the JVM (in MB)</li>
</ul>

<h3>3. JVM Uptime:</h3>
<ul>
<li><strong>jvmUptimeMillis:</strong> The time the JVM has been running (in milliseconds)</li>
</ul>

<h2>Example JSON Output (after fetching data):</h2>
<p>If the /jvm-info API returns the following JSON, it will be displayed on the UI:</p>
<pre>
{
"osName": "Windows 10",
"osVersion": "10.0",
"osArch": "amd64",
"heapMemoryInitMB": 128,
"heapMemoryUsedMB": 50,
"heapMemoryMaxMB": 1024,
"heapMemoryCommittedMB": 512,
"jvmUptimeMillis": 123456789
}
</pre>

<h2>UI Display Example</h2>
<p>On the webpage, this information will be displayed as follows in a neatly formatted block:</p>
<pre>
JVM Information
{
"osName": "Windows 10",
"osVersion": "10.0",
"osArch": "amd64",
"heapMemoryInitMB": 128,
"heapMemoryUsedMB": 50,
"heapMemoryMaxMB": 1024,
"heapMemoryCommittedMB": 512,
"jvmUptimeMillis": 123456789
}
</pre>
<h2>Styling and Functionality:</h2>
<ol>
<li><strong>Styling:</strong>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.</li>
<li><strong>Dynamic Fetching:</strong>When the page loads, it automatically fetches the JVM information from the backend and updates the UI.</li>
</ol>

<h2>Optional Enhancements</h2>
<ol>
<li><strong>Graphical Visualization:</strong> You could use a library like Chart.js to visualize memory usage in graphs (e.g., pie charts for heap memory)</li>
<li><strong>Auto-Refresh:</strong> You can add a refresh button or periodically fetch the data at a set interval (e.g., every 30 seconds) using setInterval() in JavaScript</li>
</ol>
<p>Let me know if you need further help with customization or any other features!</p>
</div>
`;
};

return (
<Grid container sx={{minHeight: '87vh', backgroundColor: "backgroundColor.default"}} direction="column">
<Grid container sx={{ minHeight: '87vh', backgroundColor: "backgroundColor.default" }} direction="column">
<Grid item xs={12}>
<div style={BackgroundHead}>
<Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
<Stack direction="row" height='70px' justifyContent="space-between" alignItems="center">
<Typography ml={15} color='#FFF' variant="h4" sx={{ "textShadow": "0px 0px 25px #0C489E" }}>
JVM Information
</Typography>
</Stack>
</div>
</Grid>
<Grid item xs={12} ml={15} mb={2}>
<div dangerouslySetInnerHTML={{ __html: htmlContent }} />
<Grid item xs={12} ml={15} mb={2} mt={2}>
<Button
size="large"
variant="contained"
type="submit"
sx={{
textTransform: 'capitalize',
alignItems: 'end'
}}
onClick={fetchJvmInfo}
disabled={loading}
>
<Typography variant="h5">JVM Info</Typography>
</Button>
</Grid>
<Grid item xs={12} ml={15} mb={2} mt={2}>
<Paper elevation={3} sx={{ p: 2, bgcolor: 'background.paper' }}>
{loading ? (
<Box display="flex" justifyContent="center" alignItems="center" minHeight={200}>
<CircularProgress />
</Box>
) : error ? (
<Typography color="error">Error: {error.message}</Typography>
) : jvmInfo ? (
<Box
component="pre"
sx={{
p: 2,
borderRadius: 1,
bgcolor: 'grey.100',
overflow: 'auto',
maxHeight: 400,
fontSize: '0.875rem',
lineHeight: 1.6
}}
>
{JSON.stringify(jvmInfo, null, 2)}
</Box>
) : (
<Typography>No data available</Typography>
)}
</Paper>
</Grid>
</Grid>
);
};

export default JVMDefault;
export default JVMDefault;

+ 3
- 0
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

Loading…
Откажи
Сачувај