Esempio n. 1
1
  /** {@inheritDoc} */
  @Override
  public long[][] getProcessorCpuLoadTicks() {
    long[][] ticks = new long[logicalProcessorCount][4];

    int machPort = SystemB.INSTANCE.mach_host_self();

    IntByReference procCount = new IntByReference();
    PointerByReference procCpuLoadInfo = new PointerByReference();
    IntByReference procInfoCount = new IntByReference();
    if (0
        != SystemB.INSTANCE.host_processor_info(
            machPort, SystemB.PROCESSOR_CPU_LOAD_INFO, procCount, procCpuLoadInfo, procInfoCount)) {
      LOG.error("Failed to update CPU Load. Error code: " + Native.getLastError());
      return ticks;
    }

    int[] cpuTicks = procCpuLoadInfo.getValue().getIntArray(0, procInfoCount.getValue());
    for (int cpu = 0; cpu < procCount.getValue(); cpu++) {
      for (int j = 0; j < 4; j++) {
        int offset = cpu * SystemB.CPU_STATE_MAX;
        ticks[cpu][0] = FormatUtil.getUnsignedInt(cpuTicks[offset + SystemB.CPU_STATE_USER]);
        ticks[cpu][1] = FormatUtil.getUnsignedInt(cpuTicks[offset + SystemB.CPU_STATE_NICE]);
        ticks[cpu][2] = FormatUtil.getUnsignedInt(cpuTicks[offset + SystemB.CPU_STATE_SYSTEM]);
        ticks[cpu][3] = FormatUtil.getUnsignedInt(cpuTicks[offset + SystemB.CPU_STATE_IDLE]);
      }
    }
    return ticks;
  }
Esempio n. 2
0
 private FileSystemWatcher() {
   cf = (CoreFoundation) Native.loadLibrary("CoreFoundation", CoreFoundation.class); // NOI18N
   cs = (CoreServices) Native.loadLibrary("CoreServices", CoreServices.class); // NOI18N
   callback = new EventCallbackImpl();
   events = new LinkedBlockingQueue<Event>();
   listensOn = new ConcurrentHashMap<String, Key>();
 }
Esempio n. 3
0
  /**
   * Uses JNA to retrieve the module file name of a program and parses it as a string which is then
   * passed to the InterruptionLogic class.
   */
  private void getProgramIdentifier() {

    PSAPI psapi = (PSAPI) Native.loadLibrary("psapi", PSAPI.class);

    HWND focusedWindow = User32.INSTANCE.GetForegroundWindow();
    byte[] name = new byte[1024];

    IntByReference pid = new IntByReference();
    User32.INSTANCE.GetWindowThreadProcessId(focusedWindow, pid);

    System.out.println("pid = " + pid.getValue());

    HANDLE process = Kernel32.INSTANCE.OpenProcess(0x0400 | 0x0010, false, pid.getValue());

    // Initally I was using the 'GetWindowModuleFileName' which provided
    // erronous behaviour. 'technomage' on Stackoverflow pointed out that
    // the method that should be used is 'GetModuleFileNameEx' -
    // http://stackoverflow.com/questions/15693210/getmodulefilename-for-window-in-focus-jna-windows-os

    psapi.GetModuleFileNameExA(process, null, name, 1024);
    String nameString = Native.toString(name);

    System.out.println(nameString);

    interruptDec.interruptNow(nameString);
  }
  public interface User32 extends W32APIOptions {
    public static final String SHELL_TRAY_WND = "Shell_TrayWnd";
    public static final int WM_COMMAND = 0x111;
    public static final int MIN_ALL = 0x1a3;
    public static final int MIN_ALL_UNDO = 0x1a0;
    User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);

    HWND GetForegroundWindow(); // add this

    int GetWindowTextA(PointerType hWnd, byte[] lpString, int nMaxCount);

    User32 instance = (User32) Native.loadLibrary("user32", User32.class, DEFAULT_OPTIONS);

    HWND FindWindow(String winClass, String title);

    long SendMessageA(HWND hWnd, int msg, int num1, int num2);

    boolean IsWindowVisible(int hWnd);

    int GetWindowRect(int hWnd, RECT r);

    void GetWindowTextA(int hWnd, byte[] buffer, int buflen);

    int GetTopWindow(int hWnd);

    int GetWindow(int hWnd, int flag);

    final int GW_HWNDNEXT = 2;
  }
Esempio n. 5
0
 static {
   if (SystemUtils.IS_OS_LINUX) {
     try {
       libappindicator = (AppIndicator) Native.loadLibrary("appindicator", AppIndicator.class);
       libgtk = (Gtk) Native.loadLibrary("gtk-x11-2.0", Gtk.class);
       libgobject = (Gobject) Native.loadLibrary("gobject-2.0", Gobject.class);
       libglib = (Glib) Native.loadLibrary("glib-2.0", Glib.class);
       // libunique = (Unique) Native.loadLibrary("unique-3.0", Unique.class);
     } catch (final Throwable ex) {
       LOG.warn("no supported version of appindicator libs found", ex);
     }
   }
 }
Esempio n. 6
0
 /**
  * Retrieve the PassThru device firmware version, DLL version, and the J2534 implementation
  * version.
  *
  * @param deviceId - of PassThru device
  * @return an instance of <b>Version</b>
  * @see Version
  */
 public Version readVersion(int deviceId) {
   ByteBuffer pFirmwareVersion = ByteBuffer.allocate(80);
   ByteBuffer pDllVersion = ByteBuffer.allocate(80);
   ByteBuffer pApiVersion = ByteBuffer.allocate(80);
   NativeLong ret =
       lib.PassThruReadVersion(
           new NativeLong(deviceId), pFirmwareVersion, pDllVersion, pApiVersion);
   if (ret.intValue() != Status.NOERROR.getValue())
     handleError("PassThruReadVersion", ret.intValue());
   return new Version(
       Native.toString(pFirmwareVersion.array()),
       Native.toString(pDllVersion.array()),
       Native.toString(pApiVersion.array()));
 }
Esempio n. 7
0
    public WindowInfo(HWND hWnd, boolean isChild) {
      byte[] buffer = new byte[1024];
      User32.instance.GetWindowTextA(hWnd, buffer, buffer.length);
      title = Native.toString(buffer);

      char[] buffer2 = new char[1026];
      User32.instance.GetClassName(hWnd, buffer2, 1026);
      className = Native.toString(buffer2);

      rect = new RECT();
      User32.instance.GetWindowRect(hWnd, rect);

      this.isChild = isChild;
    }
  // deve saber se win ou linux
  public static IComunicacaoSensores getConector() {
    IComunicacaoSensores conector = null;

    if (Platform.isWindows()) {
      conector =
          (IComunicacaoSensores)
              Native.loadLibrary("comunicacaosensores.dll", IComunicacaoSensores.class);

    } else if (Platform.isLinux()) {
      conector =
          (IComunicacaoSensores)
              Native.loadLibrary("comunicacaosensores.so", IComunicacaoSensores.class);
    }
    return conector;
  }
Esempio n. 9
0
  // 定义接口CLibrary,继承自com.sun.jna.Library
  public interface CLibrary extends Library {
    // 定义并初始化接口的静态变量 这一个语句是来加载 dll 的, 注意 dll 文件的路径
    // 可以是绝对路径也可以是相对路径,只需要填写 dll 的文件名,不能加后缀
    CLibrary Instance =
        (CLibrary)
            Native.loadLibrary(System.getProperty("user.dir") + "\\source\\NLPIR", CLibrary.class);
    // 初始化函数声明
    public int NLPIR_Init(String sDataPath, int encoding, String sLicenceCode);
    // 执行分词函数声明
    public String NLPIR_ParagraphProcess(String sSrc, int bPOSTagged);
    // 提取关键词函数声明
    public String NLPIR_GetKeyWords(String sLine, int nMaxKeyLimit, boolean bWeightOut);

    public String NLPIR_GetFileKeyWords(String sLine, int nMaxKeyLimit, boolean bWeightOut);
    // 添加用户词典声明
    public int NLPIR_AddUserWord(String sWord); // add by qp 2008.11.10
    // 删除用户词典声明
    public int NLPIR_DelUsrWord(String sWord); // add by qp 2008.11.10

    public String NLPIR_GetLastErrorMsg();
    // 退出函数声明
    public void NLPIR_Exit();
    // 文件分词声明
    public void NLPIR_FileProcess(String utf8File, String utf8FileResult, int i);
  }
Esempio n. 10
0
  public interface User32 extends W32APIOptions {
    User32 instance = (User32) Native.loadLibrary("user32", User32.class, DEFAULT_OPTIONS);

    boolean ShowWindow(HWND hWnd, int nCmdShow);

    boolean SetForegroundWindow(HWND hWnd);

    HWND FindWindow(String winClass, String title);

    LRESULT SendMessage(HWND hWnd, int Msg, WPARAM wParam, LPARAM lParam);

    boolean EnumWindows(WNDENUMPROC wndenumproc, int lParam);

    boolean EnumChildWindows(HWND hWnd, WNDENUMPROC lpEnumFunc, Pointer data);

    HWND GetParent(HWND hWnd);

    boolean IsWindowVisible(HWND hWnd);

    int GetWindowRect(HWND hWnd, RECT r);

    void GetWindowTextA(HWND hWnd, byte[] buffer, int buflen);

    int GetTopWindow(HWND hWnd);

    int GetWindow(HWND hWnd, int flag);

    final int GW_HWNDNEXT = 2;

    int GetClassName(HWND hWnd, char[] buffer2, int i);
  }
 public static void sched_setaffinity(final BitSet affinity) {
   final CLibrary lib = CLibrary.INSTANCE;
   final cpu_set_t cpuset = new cpu_set_t();
   final int size =
       version.isSameOrNewer(VERSION_2_6) ? cpu_set_t.SIZE_OF_CPU_SET_T : NativeLong.SIZE;
   final long[] bits = affinity.toLongArray();
   for (int i = 0; i < bits.length; i++) {
     if (Platform.is64Bit()) {
       cpuset.__bits[i].setValue(bits[i]);
     } else {
       cpuset.__bits[i * 2].setValue(bits[i] & 0xFFFFFFFFL);
       cpuset.__bits[i * 2 + 1].setValue((bits[i] >>> 32) & 0xFFFFFFFFL);
     }
   }
   try {
     if (lib.sched_setaffinity(0, size, cpuset) != 0) {
       throw new IllegalStateException(
           "sched_setaffinity(0, "
               + size
               + ", 0x"
               + Utilities.toHexString(affinity)
               + ") failed; errno="
               + Native.getLastError());
     }
   } catch (LastErrorException e) {
     throw new IllegalStateException(
         "sched_setaffinity(0, "
             + size
             + ", 0x"
             + Utilities.toHexString(affinity)
             + ") failed; errno="
             + e.getErrorCode(),
         e);
   }
 }
Esempio n. 12
0
/**
 * Provides access to ioctl calls for register access.
 *
 * @author jnaous
 */
public interface NFRegAccess extends Library {

  /* create an instance of this interface to load the library */
  NFRegAccess INSTANCE = (NFRegAccess) Native.loadLibrary("nf10", NFRegAccess.class);

  public static class NF2 extends Structure {
    public String device_name;
    public int fd;
    public int net_iface;

    @Override
    protected List getFieldOrder() {
      return Arrays.asList("device_name", "fd", "net_iface");
    };
  }

  public int readReg(int fd, int reg, IntByReference val);

  public int writeReg(int fd, int reg, int val);

  public int check_iface(NF2 nf2);

  public int openDescriptor(NF2 nf2);

  public int closeDescriptor(NF2 nf2);

  public void read_info(NF2 nf2);

  public void printHello(NF2 nf2, IntByReference val);
}
Esempio n. 13
0
  public static void tryMlockall() {
    int errno = Integer.MIN_VALUE;
    try {
      int result = CLibrary.mlockall(CLibrary.MCL_CURRENT);
      if (result != 0) {
        errno = Native.getLastError();
      } else {
        LOCAL_MLOCKALL = true;
      }
    } catch (UnsatisfiedLinkError e) {
      // this will have already been logged by CLibrary, no need to repeat it
      return;
    }

    if (errno != Integer.MIN_VALUE) {
      if (errno == CLibrary.ENOMEM
          && System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("linux")) {
        logger.warn(
            "Unable to lock JVM memory (ENOMEM)."
                + " This can result in part of the JVM being swapped out."
                + " Increase RLIMIT_MEMLOCK (ulimit).");
      } else if (!System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("mac")) {
        // OS X allows mlockall to be called, but always returns an error
        logger.warn("Unknown mlockall error " + errno);
      }
    }
  }
Esempio n. 14
0
  /** Updates logical and physical processor counts from sysctl calls */
  private void calculateProcessorCounts() {
    IntByReference size = new IntByReference(SystemB.INT_SIZE);
    Pointer p = new Memory(size.getValue());

    // Get number of logical processors
    if (0 != SystemB.INSTANCE.sysctlbyname("hw.logicalcpu", p, size, null, 0)) {
      LOG.error("Failed to get number of logical CPUs. Error code: " + Native.getLastError());
      this.logicalProcessorCount = 1;
    } else this.logicalProcessorCount = p.getInt(0);

    // Get number of physical processors
    if (0 != SystemB.INSTANCE.sysctlbyname("hw.physicalcpu", p, size, null, 0)) {
      LOG.error("Failed to get number of physical CPUs. Error code: " + Native.getLastError());
      this.physicalProcessorCount = 1;
    } else this.physicalProcessorCount = p.getInt(0);
  }
Esempio n. 15
0
 public static final Object getLibrary(String name, String path, final Class<?> libraryClass) {
   Object original =
       com.sun.jna.Native.loadLibrary(path, libraryClass, MangledFunctionMapper.DEFAULT_OPTIONS);
   return shouldTraceCalls(name)
       ? LibraryExtractor.getTracingLibrary(original, libraryClass)
       : original;
 }
  public static void main(String[] args) {
    // get the taskbar's window handle
    HWND shellTrayHwnd = User32.instance.FindWindow(User32.SHELL_TRAY_WND, null);

    // use it to minimize all windows
    User32.instance.SendMessageA(shellTrayHwnd, User32.WM_COMMAND, User32.MIN_ALL, 0);

    // Test
    // System.out.println(shellTrayHwnd);
    // System.out.println(User32.WM_COMMAND);

    // sleep for 3 seconds
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
    }

    // then restore previously minimized windows
    User32.instance.SendMessageA(shellTrayHwnd, User32.WM_COMMAND, User32.MIN_ALL_UNDO, 0);
    byte[] windowText = new byte[512];
    PointerType hwnd = User32.INSTANCE.GetForegroundWindow();
    // then you can call it!
    User32.INSTANCE.GetWindowTextA(hwnd, windowText, 512);
    System.out.println(Native.toString(windowText));
    // System.out.println(User32.INSTANCE.GetForegroundWindow());

  }
Esempio n. 17
0
/** Simple example of native library declaration and usage. */
public interface User32 extends Library {
  User32 INSTANCE = (User32) Native.loadLibrary(null, User32.class);

  void system(String command);

  void printf(String text, Object... obj);

  void WriteConsoleOutputCharacterA(int hwnd, String content, int size, int coord, Object bytes);

  int GetStdHandle(int ok);

  int CreateConsoleScreenBuffer(int access, int shareMode, Object security, int flags, Object data);

  int SetConsoleActiveScreenBuffer(int hwnd);

  int SetConsoleCursorInfo(int hwnd); // int cursorInfo);

  int GetConsoleCursorInfo(int hwnd);

  int SetConsoleScreenBufferSize(int hwnd, int size);

  int WriteConsoleA(int hwnd, String text, int size, int lpNumberOfCharsWritten, Object flags);

  int ReadConsoleA(int hwnd, String text, int size, String out, Object smg);

  int FlushConsoleInputBuffer(int hwnd);

  int ReadConsoleOutputCharacterA(int hwnd, String text, int size, int coord, Object smg);

  int SetConsoleTitleA(String title);
}
Esempio n. 18
0
 public int GetClassLong(Pointer hWnd, GCFlags nIndex) throws Exception {
   int ret = u32.GetClassLongA(hWnd, nIndex.getValue());
   if (ret == 0) {
     int err = Native.getLastError();
     throw new Exception("GetClassLong failed. Error: " + err);
   }
   return ret;
 }
Esempio n. 19
0
 /*package*/ static Kernel32 load() {
   try {
     return (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
   } catch (Throwable e) {
     LOGGER.log(Level.SEVERE, "Failed to load Kernel32", e);
     return InitializationErrorInvocationHandler.create(Kernel32.class, e);
   }
 }
Esempio n. 20
0
 public void testSHGetFolderPath() {
   char[] pszPath = new char[WinDef.MAX_PATH];
   assertEquals(
       W32Errors.S_OK,
       Shell32.INSTANCE.SHGetFolderPath(
           null, ShlObj.CSIDL_PROGRAM_FILES, null, ShlObj.SHGFP_TYPE_CURRENT, pszPath));
   assertTrue(Native.toString(pszPath).length() > 0);
 }
Esempio n. 21
0
 /** {@inheritDoc} */
 @Override
 public String getName() {
   if (this.cpuName == null) {
     IntByReference size = new IntByReference();
     if (0 != SystemB.INSTANCE.sysctlbyname("machdep.cpu.brand_string", null, size, null, 0)) {
       LOG.error("Failed to get Name. Error code: " + Native.getLastError());
       return "";
     }
     Pointer p = new Memory(size.getValue() + 1);
     if (0 != SystemB.INSTANCE.sysctlbyname("machdep.cpu.brand_string", p, size, null, 0)) {
       LOG.error("Failed to get Name. Error code: " + Native.getLastError());
       return "";
     }
     this.cpuName = p.getString(0);
   }
   return this.cpuName;
 }
Esempio n. 22
0
  private Memory toPointer(String input) {
    byte[] data = Native.toByteArray(input);
    Memory pointer = new Memory(data.length + 1);
    pointer.write(0, data, 0, data.length);
    pointer.setByte(data.length, (byte) 0);

    return pointer;
  }
Esempio n. 23
0
  static void windowsImpl() {
    if (!Constants.WINDOWS) {
      throw new IllegalStateException(
          "bug: should not be trying to initialize ActiveProcessLimit for an unsupported OS");
    }

    JNAKernel32Library lib = JNAKernel32Library.getInstance();

    // create a new Job
    Pointer job = lib.CreateJobObjectW(null, null);
    if (job == null) {
      throw new UnsupportedOperationException("CreateJobObject: " + Native.getLastError());
    }

    try {
      // retrieve the current basic limits of the job
      int clazz = JNAKernel32Library.JOBOBJECT_BASIC_LIMIT_INFORMATION_CLASS;
      JNAKernel32Library.JOBOBJECT_BASIC_LIMIT_INFORMATION limits =
          new JNAKernel32Library.JOBOBJECT_BASIC_LIMIT_INFORMATION();
      limits.write();
      if (!lib.QueryInformationJobObject(job, clazz, limits.getPointer(), limits.size(), null)) {
        throw new UnsupportedOperationException(
            "QueryInformationJobObject: " + Native.getLastError());
      }
      limits.read();
      // modify the number of active processes to be 1 (exactly the one process we will add to the
      // job).
      limits.ActiveProcessLimit = 1;
      limits.LimitFlags = JNAKernel32Library.JOB_OBJECT_LIMIT_ACTIVE_PROCESS;
      limits.write();
      if (!lib.SetInformationJobObject(job, clazz, limits.getPointer(), limits.size())) {
        throw new UnsupportedOperationException(
            "SetInformationJobObject: " + Native.getLastError());
      }
      // assign ourselves to the job
      if (!lib.AssignProcessToJobObject(job, lib.GetCurrentProcess())) {
        throw new UnsupportedOperationException(
            "AssignProcessToJobObject: " + Native.getLastError());
      }
    } finally {
      lib.CloseHandle(job);
    }

    logger.debug("Windows ActiveProcessLimit initialization successful");
  }
Esempio n. 24
0
  public interface Kernel32 extends W32APIOptions {
    Kernel32 instance = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class, DEFAULT_OPTIONS);

    boolean GetDiskFreeSpaceEx(
        String lpDirectoryName,
        LARGE_INTEGER.ByReference lpFreeBytesAvailable,
        LARGE_INTEGER.ByReference lpTotalNumberOfBytes,
        LARGE_INTEGER.ByReference lpTotalNumberOfFreeBytes);
  }
Esempio n. 25
0
 @Override
 public <T> T loadLibrary(String libraryName, Class<T> libraryClass) {
   try {
     return libraryClass.cast(Native.loadLibrary(libraryName, libraryClass));
   } catch (Exception ex) {
     ex.printStackTrace();
     return null;
   }
 }
Esempio n. 26
0
 static {
   try {
     Native.register("c");
   } catch (NoClassDefFoundError e) {
     logger.warn("JNA not found. native methods (mlockall) will be disabled.");
   } catch (UnsatisfiedLinkError e) {
     logger.warn("unable to link C library. native methods (mlockall) will be disabled.");
   }
 }
Esempio n. 27
0
 /**
  * Retrieve the text description for the most recent non-zero error and throw an exception.
  *
  * @param operation - string containing the name of the method for which the error occurred
  * @param status - the method's numeric error value
  * @exception J2534Exception on various non-zero return status
  * @see J2534_v0404
  */
 private static void handleError(String operation, int status) {
   ByteBuffer error = ByteBuffer.allocate(255);
   lib.PassThruGetLastError(error);
   String errString =
       String.format(
           "%s error [%d:%s], %s",
           operation, status, Status.get(status), Native.toString(error.array()));
   throw new J2534Exception(errString);
 }
Esempio n. 28
0
 public PPROCESS_MEMORY_COUNTERS GetProcessMemoryInfo(Pointer Process) throws Exception {
   PPROCESS_MEMORY_COUNTERS ppsmemCounters = new PPROCESS_MEMORY_COUNTERS();
   boolean success = psapi.GetProcessMemoryInfo(Process, ppsmemCounters, ppsmemCounters.size());
   if (!success) {
     int err = Native.getLastError();
     throw new Exception("GetProcessMemoryInfo failed. Error: " + err);
   }
   return ppsmemCounters;
 }
 static {
   if (Platform.isSolaris()) {
     System.loadLibrary("nsl");
     System.loadLibrary("socket");
   }
   if (!Platform.isWindows() && !Platform.isWindowsCE()) {
     Native.register("c");
   }
 }
Esempio n. 30
0
  /* package */ HidDevice(String path, Frontend frontend) throws IOException {
    m_Frontend = frontend;
    udev udev = udev_new();
    udev_device raw_dev = udev_device_new_from_syspath(udev, path);
    String dev_path = udev_device_get_devnode(raw_dev);
    udev_unref(udev);

    m_HidDeviceInfo = new HidDeviceInfo(path);
    // OPEN HERE //
    m_DeviceHandle = open(dev_path, O_RDWR);

    // If we have a good handle, return it.
    if (m_DeviceHandle <= 0) throw new IOException("open() failed, errno " + Native.getLastError());

    // Get the report descriptor
    int[] desc_size = {0};
    int res;
    hidraw_report_descriptor rpt_desc = new hidraw_report_descriptor();
    // Get Report Descriptor Size

    res = ioctl(m_DeviceHandle, HIDIOCGRDESCSIZE, desc_size);
    if (res < 0) // FIXME ERROR HANDLING
    throw new IOException("ioctl(...HIDIOCGRDESCSIZE..) failed"); // perror("HIDIOCGRDESCSIZE");

    // Get Report Descriptor
    rpt_desc.size = desc_size[0];
    res = ioctl(m_DeviceHandle, HIDIOCGRDESC, rpt_desc);
    if (res < 0) throw new IOException("ioctl(...HIDIOCGRDESC..) failed");
    // Determine if this device uses numbered reports.
    m_UsesNumberedReports = uses_numbered_reports(rpt_desc.value, rpt_desc.size);

    // ---------------

    // Magic here, assume that no HID device ever uses reports longer than 4kB
    m_InputReportBytes = new byte[4096 + 1];
    m_OutputReportBytes = new byte[4096 + 1];

    m_SyncStart = new SyncPoint(2);
    m_SyncShutdown = new SyncPoint(2);

    m_Thread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  runReadOnBackground();
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            },
            m_HidDeviceInfo.getPath());
    m_Thread.start();
    m_SyncStart.waitAndSync();
  }