LegacyJavaRuntime extends AbstractJavaRuntime { @Override public long getProcessId() { String name = ManagementFactory.getRuntimeMXBean().getName(); try { return Long.parseLong(name.substring(0, name.indexOf('@'))); } catch (NumberFormatException ex) { InternalLogger.log(Level.ERROR, "Illegal process ID: " + name.substring(0, name.indexOf('@'))); return -1; } catch (IndexOutOfBoundsException ex) { InternalLogger.log(Level.ERROR, "Name of virtual machine does not contain a process ID: " + name); return -1; } } LegacyJavaRuntime(); @Override boolean isAndroid(); @Override long getProcessId(); @Override Timestamp getStartTime(); @Override @SuppressWarnings("removal") @IgnoreJRERequirement String getCallerClassName(final int depth); @Override String getCallerClassName(final String loggerClassName); @Override StackTraceElement getCallerStackTraceElement(final int depth); @Override StackTraceElement getCallerStackTraceElement(final String loggerClassName); @Override Timestamp createTimestamp(); @Override TimestampFormatter createTimestampFormatter(final String pattern, final Locale locale);  }
@Test public void processId() { assertThat(new LegacyJavaRuntime().getProcessId()).isEqualTo(ProcessHandle.current().pid()); }
@Test @PrepareForTest(LegacyJavaRuntime.class) public void invalidProcessId() { RuntimeMXBean bean = mock(RuntimeMXBean.class); when(bean.getName()).thenReturn("abc@test"); mockStatic(ManagementFactory.class); when(ManagementFactory.getRuntimeMXBean()).thenReturn(bean); assertThat(new LegacyJavaRuntime().getProcessId()).isEqualTo(-1); assertThat(systemStream.consumeErrorOutput()).containsOnlyOnce("ERROR").containsOnlyOnce("abc"); }
@Test @PrepareForTest(LegacyJavaRuntime.class) public void invalidJvmName() { RuntimeMXBean bean = mock(RuntimeMXBean.class); when(bean.getName()).thenReturn("test"); mockStatic(ManagementFactory.class); when(ManagementFactory.getRuntimeMXBean()).thenReturn(bean); assertThat(new LegacyJavaRuntime().getProcessId()).isEqualTo(-1); assertThat(systemStream.consumeErrorOutput()).containsOnlyOnce("ERROR").containsOnlyOnce("test"); }