UnixUtils { public static Subject getCurrentUser() { try { Class<?> unixSystemClass = Class.forName("com.sun.security.auth.module.UnixSystem"); Object unixSystemInstance = unixSystemClass.getDeclaredConstructor().newInstance(); Method getUidMethod = unixSystemClass.getDeclaredMethod("getUid"); Method getGidMethod = unixSystemClass.getDeclaredMethod("getGid"); Method getGroupsMethod = unixSystemClass.getDeclaredMethod("getGroups"); Subject subject = new Subject(); subject.getPrincipals().add(new UidPrincipal((Long) getUidMethod.invoke(unixSystemInstance)) ); subject.getPrincipals().add(new GidPrincipal((Long) getGidMethod.invoke(unixSystemInstance), true)); long[] groups = (long[]) getGroupsMethod.invoke(unixSystemInstance); for (long gid: groups) { subject.getPrincipals().add(new GidPrincipal(gid, false)); } return subject; } catch (IllegalAccessException | ClassNotFoundException | InvocationTargetException | NoSuchMethodException | InstantiationException e) { _log.debug("couldn't get current unix user",e); return null; } }  static Subject getCurrentUser(); static int[] toIntArray(long[] longArray);  }
@Test public void testGetCurrentUser() { String osName = System.getProperty("os.name"); boolean isWindows = osName.toLowerCase(Locale.ROOT).contains("windows"); Subject currentUser = UnixUtils.getCurrentUser(); if (isWindows) { Assert.assertNull(currentUser); } else { Assert.assertNotNull(currentUser); } }