--- /dev/null
+package org.simantics.modeling.tests.commands;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.management.ManagementFactory;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import org.simantics.db.testing.common.CommandSequenceEnvironment;
+import org.simantics.db.testing.common.WriteCommand;
+
+public class WriteHeapDump extends WriteCommand<CommandSequenceEnvironment> {
+
+ private String fileName;
+
+ public WriteHeapDump(String fileName) {
+ this.fileName = fileName;
+ }
+
+ @Override
+ public void run(CommandSequenceEnvironment environment) throws Exception {
+
+ final File dumpFile = new File(fileName);
+ if (dumpFile.exists() && !dumpFile.delete()) {
+ return;
+ }
+ try {
+ Object bean = getBean();
+ if (bean == null)
+ return;
+
+ Method m = bean.getClass().getMethod("dumpHeap", String.class, boolean.class);
+ m.invoke(bean, dumpFile.getAbsolutePath(), true);
+ } catch (IllegalArgumentException e) {
+ throw new InvocationTargetException(e);
+ } catch (IllegalAccessException e) {
+ throw new InvocationTargetException(e);
+ } catch (SecurityException e) {
+ throw new InvocationTargetException(e);
+ } catch (NoSuchMethodException e) {
+ throw new InvocationTargetException(e);
+ }
+
+ }
+
+ private static Object getBean() {
+ Class<?> beanClass = getBeanClass();
+ if (beanClass == null)
+ return null;
+ try {
+ Object bean = ManagementFactory.newPlatformMXBeanProxy(
+ ManagementFactory.getPlatformMBeanServer(),
+ "com.sun.management:type=HotSpotDiagnostic",
+ beanClass);
+ return bean;
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ private static Class<?> getBeanClass() {
+ try {
+ Class<?> clazz = Class.forName("com.sun.management.HotSpotDiagnosticMXBean");
+ return clazz;
+ } catch (ClassNotFoundException e) {
+ return null;
+ }
+ }
+}
\ No newline at end of file