Java Code Examples for java.lang.reflect.Field#getLong()

The following examples show how to use java.lang.reflect.Field#getLong() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CustomMySQLHa.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: TestJvmProcess.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example 3
Source File: ProcessHelper.java    From buck with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 4
Source File: OSUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example 5
Source File: SpringBootManagedContainer.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 6
Source File: JobProcessManagerImpl.java    From genie with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 7
Source File: GatherProcessInfoTimeoutHandler.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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;
}
 
Example 8
Source File: FpsCalculator.java    From StaticLayoutView with MIT License 5 votes vote down vote up
@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);

}
 
Example 9
Source File: JavaSerializer.java    From sofa-hessian with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 10
Source File: ProducerManagerTest.java    From rocketmq-read with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 11
Source File: JavaSerializer.java    From jvm-sandbox-repeater with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 12
Source File: JavaSerializer.java    From dubbo-hessian-lite with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 13
Source File: ProducerManagerTest.java    From rocketmq-4.3.0 with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 14
Source File: DBObject.java    From GLEXP-Team-onebillion with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 15
Source File: Utils.java    From mnemonic with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 16
Source File: StorageUtils.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 17
Source File: DisplayChangedTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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();

}
 
Example 18
Source File: FpsCalculator.java    From FastTextView with Apache License 2.0 5 votes vote down vote up
@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);

}
 
Example 19
Source File: FieldTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 20
Source File: LocalNativeProcess.java    From netbeans with Apache License 2.0 4 votes vote down vote up
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);
}