下面列出了java.lang.reflect.Field#getLong ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private long getPidOfLinux(boolean byHook) {
long pid = -1;
try {
if (process.getClass().getName().equals("java.lang.UNIXProcess")) {
Field f = process.getClass().getDeclaredField("pid");
f.setAccessible(true);
pid = f.getLong(process);
f.setAccessible(false);
}
} catch (Exception e) {
if (byHook) {
System.out.println("getPidOfLinux failed:" + e);
} else {
LOGGER.warn("getPidOfLinux failed:", e);
}
pid = -1;
}
if (byHook) {
System.out.println("python pid is " + pid);
} else if (LOGGER.isDebugEnabled()) {
LOGGER.debug("python pid is " + pid);
}
return pid;
}
@Override
protected long getProcessId(Process process) {
long result = super.getProcessId(process);
if (result == 0L) {
/* jtreg didn't find pid, most probably we are on JDK < 9
there is no Process::getPid */
if (HAS_NATIVE_LIBRARY && "windows".equals(OS.current().family)) {
try {
Field field = process.getClass().getDeclaredField("handle");
boolean old = field.isAccessible();
try {
field.setAccessible(true);
long handle = field.getLong(process);
result = getWin32Pid(handle);
} finally {
field.setAccessible(old);
}
} catch (ReflectiveOperationException e) {
e.printStackTrace(log);
}
}
}
return result;
}
private long getPid(final Process process) {
long pid = -1;
final String processClassName = process.getClass().getCanonicalName();
try {
if ("java.lang.UNIXProcess".equals(processClassName)) {
final Field pidMemberField = process.getClass().getDeclaredField("pid");
final boolean resetAccessible = pidMemberField.isAccessible();
pidMemberField.setAccessible(true);
pid = pidMemberField.getLong(process);
pidMemberField.setAccessible(resetAccessible);
} else {
log.debug("Don't know how to access PID for class {}", processClassName);
}
} catch (final Throwable t) {
log.warn("Failed to determine job process PID");
}
return pid;
}
protected static Integer windowsProcessId(Process process) {
if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) {
/* determine the pid on windows plattforms */
try {
Field f = process.getClass().getDeclaredField("handle");
f.setAccessible(true);
long handl = f.getLong(process);
Kernel32 kernel = Kernel32.INSTANCE;
WinNT.HANDLE handle = new WinNT.HANDLE();
handle.setPointer(Pointer.createConstant(handl));
int ret = kernel.GetProcessId(handle);
log.debug("Detected pid: {}", ret);
return ret;
} catch (Throwable ex) {
throw new RuntimeException("Cannot fetch windows pid!", ex);
}
}
return null;
}
/**
* @param process NiFi Process Reference
* @param logger Logger Reference for Debug
* @return Returns pid or null in-case pid could not be determined
* This method takes {@link Process} and {@link Logger} and returns
* the platform specific Handle for Win32 Systems, a.k.a <b>pid</b>
* In-case it fails to determine the pid, it will return Null.
* Purpose for the Logger is to log any interaction for debugging.
*/
private static Long getWindowsProcessId(final Process process, final Logger logger) {
/* determine the pid on windows plattforms */
try {
Field f = process.getClass().getDeclaredField("handle");
f.setAccessible(true);
long handl = f.getLong(process);
Kernel32 kernel = Kernel32.INSTANCE;
WinNT.HANDLE handle = new WinNT.HANDLE();
handle.setPointer(Pointer.createConstant(handl));
int ret = kernel.GetProcessId(handle);
logger.debug("Detected pid: {}", ret);
return Long.valueOf(ret);
} catch (final IllegalAccessException | NoSuchFieldException nsfe) {
logger.debug("Could not find PID for child process due to {}", nsfe);
}
return null;
}
@Nullable
private Long windowsProcessId(Object process) {
Class<?> clazz = process.getClass();
if (clazz.getName().equals("java.lang.Win32Process")
|| clazz.getName().equals("java.lang.ProcessImpl")) {
try {
Field f = clazz.getDeclaredField("handle");
f.setAccessible(true);
long peer = f.getLong(process);
Pointer pointer = Pointer.createConstant(peer);
WinNT.HANDLE handle = new WinNT.HANDLE(pointer);
return (long) Kernel32.INSTANCE.GetProcessId(handle);
} catch (Exception e) {
LOG.warn(e, "Cannot get process id!");
}
}
return null;
}
/**
* Gets the process ID, if possible. This method currently only work on UNIX-based
* operating systems. On others, it returns {@code -1}.
*
* @return The process ID, or -1, if the ID cannot be determined.
*/
public long getProcessId() {
checkState(process != null, "process not started");
try {
Class<? extends Process> clazz = process.getClass();
if (clazz.getName().equals("java.lang.UNIXProcess")) {
Field pidField = clazz.getDeclaredField("pid");
pidField.setAccessible(true);
return pidField.getLong(process);
} else if (clazz.getName().equals("java.lang.ProcessImpl")) {
Method pid = clazz.getDeclaredMethod("pid");
pid.setAccessible(true);
return (long) pid.invoke(process);
} else {
return -1;
}
}
catch (Throwable ignored) {
return -1;
}
}
/**
* Test fails if it throws any exception.
*
* @throws Exception
*/
private void init() throws Exception {
if (!System.getProperty("os.name").startsWith("Windows")) {
System.out.println("This is Windows only test.");
return;
}
Frame frame = new Frame("AWT Frame");
frame.pack();
FramePeer frame_peer = AWTAccessor.getComponentAccessor()
.getPeer(frame);
Class comp_peer_class = Class.forName("sun.awt.windows.WComponentPeer");
Field hwnd_field = comp_peer_class.getDeclaredField("hwnd");
hwnd_field.setAccessible(true);
long hwnd = hwnd_field.getLong(frame_peer);
Class clazz = Class.forName("sun.awt.windows.WEmbeddedFrame");
Constructor constructor = clazz
.getConstructor(new Class[]{long.class});
Frame embedded_frame = (Frame) constructor
.newInstance(new Object[]{new Long(hwnd)});
frame.setVisible(true);
ComponentPeer peer = AWTAccessor.getComponentAccessor().getPeer(
embedded_frame);
Class peerClass = peer.getClass();
Method displayChangedM = peerClass.getMethod("displayChanged",
new Class[0]);
displayChangedM.invoke(peer, null);
embedded_frame.dispose();
frame.dispose();
}
/**
* Gets the address value for the memory that backs a direct byte buffer.
*
* @param buffer
* A buffer to retrieve its address
*
* @return
* The system address for the buffers
*/
public static long getAddressFromDirectByteBuffer(ByteBuffer buffer) {
try {
Field addressField = Buffer.class.getDeclaredField("address");
addressField.setAccessible(true);
return addressField.getLong(buffer);
} catch (Exception e) {
throw new RuntimeException("Unable to address field from ByteBuffer", e);
}
}
@Test
public void scanNotActiveChannel() throws Exception {
producerManager.registerProducer(group, clientInfo);
assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNotNull();
Field field = ProducerManager.class.getDeclaredField("CHANNEL_EXPIRED_TIMEOUT");
field.setAccessible(true);
long CHANNEL_EXPIRED_TIMEOUT = field.getLong(producerManager);
clientInfo.setLastUpdateTimestamp(System.currentTimeMillis() - CHANNEL_EXPIRED_TIMEOUT - 10);
when(channel.close()).thenReturn(mock(ChannelFuture.class));
producerManager.scanNotActiveChannel();
assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNull();
}
void serialize(AbstractHessianOutput out, Object obj, Field field)
throws IOException
{
long value = 0;
try {
value = field.getLong(obj);
} catch (IllegalAccessException e) {
log.log(Level.FINE, e.toString(), e);
}
out.writeLong(value);
}
@Test
public void scanNotActiveChannel() throws Exception {
producerManager.registerProducer(group, clientInfo);
assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNotNull();
Field field = ProducerManager.class.getDeclaredField("CHANNEL_EXPIRED_TIMEOUT");
field.setAccessible(true);
long CHANNEL_EXPIRED_TIMEOUT = field.getLong(producerManager);
clientInfo.setLastUpdateTimestamp(System.currentTimeMillis() - CHANNEL_EXPIRED_TIMEOUT - 10);
when(channel.close()).thenReturn(mock(ChannelFuture.class));
producerManager.scanNotActiveChannel();
assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNull();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void start() {
Log.d(TAG, "start vsync detect");
if (mRunning) {
return;
}
mRunning = true;
syncCheckThread = new Thread(new Runnable() {
@Override
public void run() {
for (;;) {
if (!mRunning) {
break;
}
syncCheckThread();
}
}
});
syncCheckThread.start();
Choreographer chor = Choreographer.getInstance();
Field field;
try {
field = chor.getClass().getDeclaredField("mFrameIntervalNanos");
field.setAccessible(true);
mFrameIntervalNanos = field.getLong(chor);
Log.d(TAG, "mFrameIntervalNanos " + mFrameIntervalNanos);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage());
}
chor.postFrameCallback(frameCallback);
}
void serialize(AbstractHessianOutput out, Object obj, Field field)
throws IOException
{
long value = 0;
try {
value = field.getLong(obj);
} catch (IllegalAccessException e) {
log.log(Level.FINE, e.toString(), e);
}
out.writeLong(value);
}
@Override
void serialize(AbstractHessianOutput out, Object obj, Field field)
throws IOException {
long value = 0;
try {
value = field.getLong(obj);
} catch (IllegalAccessException e) {
log.log(Level.FINE, e.toString(), e);
}
out.writeLong(value);
}
private long getLongValue(String name)
{
long result = 0;
try {
Field field = this.getClass().getDeclaredField(name);
result = field.getLong(this);
} catch (Exception e) {
throw new IllegalStateException(e);
}
return result;
}
private long getLong(Object object, String id) {
long value = 0l;
try {
Field field = object.getClass().getDeclaredField(id);
field.setAccessible(true);
value = field.getLong(object);
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void start() {
Log.d(TAG, "start vsync detect");
if (mRunning) {
return;
}
mRunning = true;
syncCheckThread = new Thread(new Runnable() {
@Override
public void run() {
for (;;) {
if (!mRunning) {
break;
}
syncCheckThread();
}
}
});
syncCheckThread.start();
Choreographer chor = Choreographer.getInstance();
Field field;
try {
field = chor.getClass().getDeclaredField("mFrameIntervalNanos");
field.setAccessible(true);
mFrameIntervalNanos = field.getLong(chor);
Log.d(TAG, "mFrameIntervalNanos " + mFrameIntervalNanos);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage());
}
chor.postFrameCallback(frameCallback);
}
Object getField(char primitiveType, Object o, Field f,
Class expected) {
Object res = null;
try {
primitiveType = Character.toUpperCase(primitiveType);
switch (primitiveType) {
case 'I': // int
res = new Integer(f.getInt(o));
break;
case 'J': // long
res = new Long(f.getLong(o));
break;
case 'Z': // boolean
res = new Boolean(f.getBoolean(o));
break;
case 'S': // short
res = new Short(f.getShort(o));
break;
case 'B': // byte
res = new Byte(f.getByte(o));
break;
case 'C': // char
res = new Character(f.getChar(o));
break;
case 'D': // double
res = new Double(f.getDouble(o));
break;
case 'F': // float
res = new Float(f.getFloat(o));
break;
default:
res = f.get(o);
}
// Since 2011, members are always accessible and throwing is optional
assertTrue("expected " + expected + " for " + f.getName(),
expected == null || expected == IllegalAccessException.class);
} catch (Exception e) {
if (expected == null) {
fail("unexpected exception " + e);
} else {
assertTrue("expected exception "
+ expected.getName() + " and got " + e, e
.getClass().equals(expected));
}
}
return res;
}
private void createWin() throws IOException, InterruptedException {
// Don't use shell wrapping on Windows...
// Mostly this is because exec works not as expected and we cannot
// control processes started with exec method....
// Suspend is not supported on Windows.
final ProcessBuilder pb = new ProcessBuilder(); // NOI18N
final MacroMap jointEnv = MacroMap.forExecEnv(ExecutionEnvironmentFactory.getLocal());
jointEnv.putAll(info.getEnvironment());
if (isInterrupted()) {
throw new InterruptedException();
}
if (info.isUnbuffer()) {
UnbufferSupport.initUnbuffer(info.getExecutionEnvironment(), jointEnv);
}
pb.environment().clear();
for (Entry<String, String> envEntry : jointEnv.entrySet()) {
pb.environment().put(envEntry.getKey(), envEntry.getValue());
}
pb.redirectErrorStream(info.isRedirectError());
pb.command(info.getCommand());
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest(String.format("Command: %s", info.getCommand())); // NOI18N
}
String wdir = info.getWorkingDirectory(true);
if (wdir != null) {
File wd = new File(wdir);
if (!wd.exists()) {
throw new FileNotFoundException(loc("NativeProcess.noSuchDirectoryError.text", wd.getAbsolutePath())); // NOI18N
}
pb.directory(wd);
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest(String.format("Working directory: %s", wdir)); // NOI18N
}
}
process = pb.start();
creation_ts = System.nanoTime();
errorPipedOutputStream = new PipedOutputStream();
errorPipedInputStream = new PipedInputStream(errorPipedOutputStream);
setErrorStream(new SequenceInputStream(process.getErrorStream(), errorPipedInputStream));
setInputStream(process.getInputStream());
setOutputStream(process.getOutputStream());
int newPid = 12345;
try {
String className = process.getClass().getName();
if ("java.lang.Win32Process".equals(className) || "java.lang.ProcessImpl".equals(className)) { // NOI18N
Field f = process.getClass().getDeclaredField("handle"); // NOI18N
f.setAccessible(true);
long phandle = f.getLong(process);
Win32APISupport kernel = Win32APISupport.INSTANCE;
Win32APISupport.HANDLE handle = new Win32APISupport.HANDLE();
handle.setPointer(Pointer.createConstant(phandle));
newPid = kernel.GetProcessId(handle);
}
} catch (Throwable e) {
}
ByteArrayInputStream bis = new ByteArrayInputStream(("" + newPid).getBytes()); // NOI18N
readPID(bis);
}