Ejemplo 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;
  }
Ejemplo n.º 2
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);
  }
Ejemplo n.º 3
0
 private String translateString(final String trantab, String inbuf) {
   try {
     if (inbuf.length() == 0) {
       return "";
     }
     HyphenatedString hyphenatedInbuf = null;
     boolean preHyphenated =
         inbuf.contains(String.valueOf(TXT_SOFT_HYPHEN)) || inbuf.contains(String.valueOf('-'));
     if (preHyphenated) {
       hyphenatedInbuf = new HyphenatedString(inbuf, TXT_SOFT_HYPHEN);
       inbuf = hyphenatedInbuf.getUnhyphenatedString();
     }
     final int inlen = inbuf.length();
     final int maxOutlen = OUT_IN_RATIO * inlen;
     final byte[] inbufArray = inbuf.getBytes(encoding);
     final byte[] outbufArray = new byte[charSize * maxOutlen];
     final IntByReference pInlen = new IntByReference(inlen);
     final IntByReference pOutlen = new IntByReference(maxOutlen);
     int[] outputPosArray = null;
     if (preHyphenated) {
       outputPosArray = new int[maxOutlen];
     }
     if (INSTANCE.lou_translate(
             trantab,
             inbufArray,
             pInlen,
             outbufArray,
             pOutlen,
             null,
             null,
             null,
             outputPosArray,
             null,
             0)
         == 0) {
       throw new RuntimeException("Unable to complete translation");
     }
     int outlen = pOutlen.getValue();
     String outbuf = new String(outbufArray, 0, outlen * charSize, encoding);
     if (preHyphenated) {
       try {
         outputPosArray = Arrays.copyOf(outputPosArray, outlen);
         boolean[] inHyphenPos = hyphenatedInbuf.getHyphenPoints();
         boolean[] outHyphenPos = convertHyphenPos(inHyphenPos, outputPosArray);
         HyphenatedString hyphenatedOutbuf = new HyphenatedString(outbuf, outHyphenPos);
         outbuf = hyphenatedOutbuf.getFullyHyphenatedString(BRL_SOFT_HYPHEN);
         // Replace 't' hyphen points after a hard hyphen (not a non-breaking hyphen) by 'm'
         outbuf = outbuf.replaceAll("-" + BRL_SOFT_HYPHEN, BRL_HARD_HYPHEN);
       } catch (RuntimeException e) {
         // Don't hyphenate the text when an exception occurs.
       }
     }
     // Replace non-breaking hyphens with a normal hyphen
     outbuf = outbuf.replaceAll("\u2011", "-");
     return outbuf;
   } catch (UnsupportedEncodingException e) {
     throw new RuntimeException("Encoding not supported by JVM:" + encoding);
   }
 }
Ejemplo n.º 4
0
 /** Return true if the window message queue is idle, false if timeout */
 public boolean waitForInputIdle(int timeout_ms) {
   IntByReference lpdwProcessId = new IntByReference();
   User32.INSTANCE.GetWindowThreadProcessId(hWnd, lpdwProcessId);
   return User32.INSTANCE
           .WaitForInputIdle(new HANDLE(lpdwProcessId.getPointer()), new DWORD(timeout_ms))
           .intValue()
       == 0;
 }
  public String executeRequest(String command, boolean doCloseConnection) {
    try {
      // System.out.println("Соединяемся");
      if (ensureConnected()) {
        // String command = "stm";//"isc";//"staEQBREMU:SBER03";
        WinBase.OVERLAPPED overlapped = new WinBase.OVERLAPPED();
        ByteBuffer commandBytes = ByteBuffer.allocate(command.length() + 1);
        commandBytes.put(command.getBytes()).put((byte) 0);
        kernel32.WriteFile(
            pipeHandle,
            commandBytes.array(),
            commandBytes.capacity(),
            new IntByReference(),
            overlapped);
        // System.out.println(kernel32.GetLastError());
        kernel32.FlushFileBuffers(pipeHandle);
        // System.out.println(kernel32.GetLastError());
        while (overlapped.Internal.intValue() == WinNT.ERROR_IO_PENDING) ;

        // System.out.println("Записали");
        ByteBuffer buffer = ByteBuffer.allocate(4 * 1024);
        IntByReference bytesRead = new IntByReference(buffer.capacity());
        int lastError = 0;
        // System.out.println("Начали читать..");

        // проверим, чтобы не зависнуть
        if (kernel32.PeekNamedPipe(pipeHandle, buffer, buffer.capacity(), bytesRead, null, null))
          while (!(kernel32.ReadFile(pipeHandle, buffer, buffer.capacity(), bytesRead, overlapped))
              || (lastError = kernel32.GetLastError()) == Kernel32.ERROR_MORE_DATA) {
            // читаем и читаем
            if (lastError == Kernel32.ERROR_PIPE_NOT_CONNECTED
                || overlapped.Internal.intValue() != WinNT.ERROR_IO_PENDING) break;
          }

        // System.out.println("Считали: " + bytesRead.getValue() + " байт");
        if (doCloseConnection) {
          forceDisconnect();
        }
        String result = new String(buffer.array(), 0, bytesRead.getValue());
        // System.out.println("Quik pipe -> : " + result);

        if ("not connected".equals(result)) return null;
        return result;
      } else {
        // System.out.println("Quik Pipe cоединение не может быть установлено. Вероятно сервер
        // выключен");
        return null;
      }
    } finally {
      if (doCloseConnection) {
        forceDisconnect();
      }
    }
  }
Ejemplo n.º 6
0
 public DirectMemoryIO wrapDirectMemory(long address) {
   com.sun.jna.Pointer ptr;
   if (Platform.getPlatform().addressSize() == 32) {
     IntByReference ref = new IntByReference((int) address);
     ptr = ref.getPointer().getPointer(0);
   } else {
     LongByReference ref = new LongByReference(address);
     ptr = ref.getPointer().getPointer(0);
   }
   return ptr != null ? new NativeMemoryIO(ptr) : null;
 }
Ejemplo n.º 7
0
  /**
   * Private helper to make sure that the data created by the simulation was set as expected.
   * Assumes that we used the "layoutarea" module
   */
  private static void checkSimulationData(Ssc ssclib, Pointer data) {
    FloatByReference val = new FloatByReference();
    boolean status = ssclib.ssc_data_get_number(data, "area", val);
    assertThat(status).isTrue();
    assertThat(val.getValue()).isAtLeast(0f);

    IntByReference rows = new IntByReference();
    IntByReference cols = new IntByReference();
    Pointer mtx = ssclib.ssc_data_get_matrix(data, "convex_hull", rows, cols);
    assertThat(mtx).isNotNull();
    assertThat(rows.getValue()).isGreaterThan(0);
    assertThat(cols.getValue()).isGreaterThan(0);
  }
Ejemplo n.º 8
0
 /** {@inheritDoc} */
 @Override
 public boolean isCpu64bit() {
   if (this.cpu64 == null) {
     IntByReference size = new IntByReference(SystemB.INT_SIZE);
     Pointer p = new Memory(size.getValue());
     if (0 != SystemB.INSTANCE.sysctlbyname("hw.cpu64bit_capable", p, size, null, 0)) {
       LOG.error("Failed to get 64Bit_capable. Error code: " + Native.getLastError());
       return false;
     }
     this.cpu64 = p.getInt(0) != 0;
   }
   return this.cpu64.booleanValue();
 }
Ejemplo n.º 9
0
 /** {@inheritDoc} */
 @Override
 public String getFamily() {
   if (this.cpuFamily == null) {
     IntByReference size = new IntByReference(SystemB.INT_SIZE);
     Pointer p = new Memory(size.getValue());
     if (0 != SystemB.INSTANCE.sysctlbyname("machdep.cpu.family", p, size, null, 0)) {
       LOG.error("Failed to get Family. Error code: " + Native.getLastError());
       return "";
     }
     this.cpuFamily = Integer.toString(p.getInt(0));
   }
   return this.cpuFamily;
 }
Ejemplo n.º 10
0
  public void testMsiLocateComponentW() {
    char[] componentBuffer = new char[40];
    assertTrue(
        W32Errors.ERROR_SUCCESS
            == Msi.INSTANCE.MsiEnumComponents(new WinDef.DWORD(0), componentBuffer));
    String component = new String(componentBuffer).trim();

    char[] pathBuffer = new char[WinDef.MAX_PATH];
    IntByReference pathBufferSize = new IntByReference(pathBuffer.length);
    Msi.INSTANCE.MsiLocateComponentW(new WString(component), pathBuffer, pathBufferSize);

    String path = new String(pathBuffer, 0, pathBufferSize.getValue()).trim();
    assertTrue(path.length() > 0);
  }
Ejemplo n.º 11
0
  /** Given the process handle, waits for its completion and returns the exit code. */
  public static int waitForExitProcess(Pointer hProcess) throws InterruptedException {
    while (true) {
      if (Thread.interrupted()) throw new InterruptedException();

      Kernel32.INSTANCE.WaitForSingleObject(hProcess, 1000);
      IntByReference exitCode = new IntByReference();
      exitCode.setValue(-1);
      Kernel32.INSTANCE.GetExitCodeProcess(hProcess, exitCode);

      int v = exitCode.getValue();
      if (v != Kernel32.STILL_ACTIVE) {
        return v;
      }
    }
  }
Ejemplo n.º 12
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);
  }
Ejemplo n.º 13
0
  @Test
  public void setArray() {
    float value = 0.5f;
    float[] array = {value, value, value, value};
    String name = "test";

    ssclib.ssc_data_set_array(data, name, array, array.length);
    IntByReference length = new IntByReference();
    Pointer result = ssclib.ssc_data_get_array(data, name, length);

    assertThat(length.getValue()).isEqualTo(array.length);
    for (int i = 0; i < length.getValue(); i++) {
      // Offset is by byte (float = 4 bytes)
      assertThat(result.getFloat(i * 4)).isWithin(EPSILON).of(value);
    }
  }
Ejemplo n.º 14
0
  public List<Pointer> EnumProcessModules(Pointer hProcess) throws Exception {
    List<Pointer> list = new LinkedList<Pointer>();

    Pointer[] lphModule = new Pointer[100 * 4];
    IntByReference lpcbNeededs = new IntByReference();
    boolean success = psapi.EnumProcessModules(hProcess, lphModule, lphModule.length, lpcbNeededs);
    if (!success) {
      int err = Native.getLastError();
      throw new Exception("EnumProcessModules failed. Error: " + err);
    }
    for (int i = 0; i < lpcbNeededs.getValue() / 4; i++) {
      list.add(lphModule[i]);
    }

    return list;
  }
Ejemplo n.º 15
0
  public List<Integer> enumProcesses() throws Exception {
    List<Integer> list = new LinkedList<Integer>();

    int[] pProcessIds = new int[256];
    IntByReference pBytesReturned = new IntByReference();
    boolean success =
        psapi.EnumProcesses(pProcessIds, pProcessIds.length * Integer.SIZE / 8, pBytesReturned);
    if (!success) {
      int err = Native.getLastError();
      throw new Exception("EnumProcesses failed. Error: " + err);
    }

    int size = (pBytesReturned.getValue() / (Integer.SIZE / 8));
    for (int i = 0; i < size; i++) list.add(pProcessIds[i]);

    return list;
  }
Ejemplo n.º 16
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;
 }
Ejemplo n.º 17
0
  private ArrayList<WinDomainTrustInfoNative> dsEnumerateDomainTrusts(
      String domainName, int trustFlags) {
    PointerByReference ppTrustsInfo = new PointerByReference(Pointer.NULL);
    Pointer pTrustsInfo = Pointer.NULL;
    WinDomainTrustInfoNative[] trustsArray = null;
    ArrayList<WinDomainTrustInfoNative> trusts = new ArrayList<WinDomainTrustInfoNative>();
    int numTrusts = 0;
    IntByReference pNumTrusts = new IntByReference();

    DomainControllerInfo dcInfo = null;
    try {
      dcInfo = this.getDcInfo(domainName);
    } catch (DomainManagerException ex) {
      logger.error(
          String.format(
              "Before enumerating trust for domain [%s], getDcInfo failed. ", domainName));
    }

    try {
      String serverName = dcInfo == null ? domainName : dcInfo.domainFQDN;
      int dwError =
          WinNetApi32.INSTANCE.DsEnumerateDomainTrusts(
              serverName, trustFlags, ppTrustsInfo, pNumTrusts);
      logAndThrow(String.format("Failed to enumerate domain trusts for %s ", serverName), dwError);

      numTrusts = pNumTrusts.getValue();
      pTrustsInfo = ppTrustsInfo.getValue();

      if ((numTrusts > 0) && (pTrustsInfo != null) && (pTrustsInfo != Pointer.NULL)) {
        WinDomainTrustInfoNative trustsInfo = new WinDomainTrustInfoNative(pTrustsInfo);
        trustsArray = (WinDomainTrustInfoNative[]) trustsInfo.toArray(numTrusts);
      }

      for (int i = 0; i < numTrusts; i++) {
        if (isEmptyOrNullTrust(trustsArray[i])) continue;
        trusts.add(trustsArray[i]);
      }
    } finally {
      if (pTrustsInfo != Pointer.NULL) {
        WinNetApi32.INSTANCE.NetApiBufferFree(pTrustsInfo);
      }
    }

    return trusts;
  }
Ejemplo n.º 18
0
  /**
   * Gets Display Information
   *
   * @return An array of Display objects representing monitors, etc.
   */
  public static Display[] getDisplays() {
    List<Display> displays = new ArrayList<>();

    Guid.GUID monitorGuid = new Guid.GUID("E6F07B5F-EE97-4a90-B076-33F57BF4EAA7");
    WinNT.HANDLE hDevInfo =
        SetupApi.INSTANCE.SetupDiGetClassDevs(
            monitorGuid, null, null, SetupApi.DIGCF_PRESENT | SetupApi.DIGCF_DEVICEINTERFACE);
    if (!hDevInfo.equals(WinNT.INVALID_HANDLE_VALUE)) {
      SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new SetupApi.SP_DEVICE_INTERFACE_DATA();
      deviceInterfaceData.cbSize = deviceInterfaceData.size();

      // build a DevInfo Data structure
      SP_DEVINFO_DATA info = new SetupApi.SP_DEVINFO_DATA();

      for (int memberIndex = 0;
          SetupApi.INSTANCE.SetupDiEnumDeviceInfo(hDevInfo, memberIndex, info);
          memberIndex++) {
        HKEY key =
            SetupApi.INSTANCE.SetupDiOpenDevRegKey(
                hDevInfo,
                info,
                SetupApi.DICS_FLAG_GLOBAL,
                0,
                SetupApi.DIREG_DEV,
                WinNT.KEY_QUERY_VALUE);

        byte[] edid = new byte[1];
        Advapi32 advapi32 = Advapi32.INSTANCE;
        IntByReference pType = new IntByReference();
        IntByReference lpcbData = new IntByReference();

        if (advapi32.RegQueryValueEx(key, "EDID", 0, pType, edid, lpcbData)
            == WinError.ERROR_MORE_DATA) {
          edid = new byte[lpcbData.getValue()];
          if (advapi32.RegQueryValueEx(key, "EDID", 0, pType, edid, lpcbData)
              == WinError.ERROR_SUCCESS) {
            Display display = new WindowsDisplay(edid);
            displays.add(display);
          }
        }
        Advapi32.INSTANCE.RegCloseKey(key);
      }
    }
    return displays.toArray(new Display[displays.size()]);
  }
Ejemplo n.º 19
0
 /** {@inheritDoc} */
 @Override
 public long getSystemUptime() {
   IntByReference size = new IntByReference();
   if (0 != SystemB.INSTANCE.sysctlbyname("kern.boottime", null, size, null, 0)) {
     LOG.error("Failed to get Boot Time. Error code: " + Native.getLastError());
     return 0L;
   }
   // This should point to a 16-byte structure. If not, this code is valid
   if (size.getValue() != 16)
     throw new UnsupportedOperationException("sysctl kern.boottime should be 16 bytes but isn't.");
   Pointer p = new Memory(size.getValue() + 1);
   if (0 != SystemB.INSTANCE.sysctlbyname("kern.boottime", p, size, null, 0)) {
     LOG.error("Failed to get Boot Time. Error code: " + Native.getLastError());
     return 0L;
   }
   // p now points to a 16-bit timeval structure for boot time.
   // First 8 bytes are seconds, second 8 bytes are microseconds (ignore)
   return System.currentTimeMillis() / 1000 - p.getLong(0);
 }
  @Ignore
  public void testAviTools() {
    //		VideoCapturerFactory factory = VideoCapturerFactory.getInstance();
    //		List<String> capturerNames = factory.getCapturerNames();
    //		String last = Iterables.getLast(capturerNames);
    //
    //		DSJCapturer dsjCapturer = new DSJCapturer(last) {
    //
    //		};
    //
    //		dsjCapturer.startRunning();

    IntByReference cameraId = new IntByReference(1);

    int is_InitCamera = UEyeLibrary.is_InitCamera(cameraId, Pointer.NULL);
    System.out.println("initCamera result: " + is_InitCamera);
    System.out.println("Camera handle returned: " + cameraId);
    IntByReference memoryId = new IntByReference(0);
    int width = 640, height = 480, bitspixel = 8, adjust = 0;
    int bufferSize = (width * ((bitspixel + 1) / 8) + adjust) * height;
    // ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);
    PointerByReference buffer = new PointerByReference();
    //	int is_GetActiveImageMem = NativeIdsCapturerLibrary.is_GetActiveImageMem
    // (cameraId.getValue(), buffer, memoryId);
    //	System.out.println("Result activeImageMem: " + is_GetActiveImageMem);
    int allocateMemory =
        UEyeLibrary.is_AllocImageMem(cameraId.getValue(), 640, 480, 8, buffer, memoryId);
    //		System.out.println("allocateMemory result: " + allocateMemory);
    System.out.println("Memory handle returned: " + buffer);
    // int loadParameters = NativeIdsCapturerLibrary.is_LoadParameters(phf, fileName);
    IntByReference aviPointer = new IntByReference(0);
    int initAvi = UEyeAviLibrary.isavi_InitAVI(aviPointer, cameraId.getValue());
    System.out.println("initAvi result: " + initAvi);
    System.out.println("Avi handle returned: " + aviPointer.getValue());
    int imageSize =
        UEyeAviLibrary.isavi_SetImageSize(
            aviPointer.getValue(), UEyeAviLibrary.IS_AVI_CM_RGB24, width, height, 0, 0, 0);
    System.out.println("imageSize result: " + imageSize);
    int openAvi = UEyeAviLibrary.isavi_OpenAVI(aviPointer.getValue(), "C:/dump.avi");
    System.out.println("openAvi result: " + openAvi);
    int frameRate = UEyeAviLibrary.isavi_SetFrameRate(aviPointer.getValue(), 25);
    System.out.println("frameRate result: " + frameRate);
    int startAvi = UEyeAviLibrary.isavi_StartAVI(aviPointer.getValue());
    System.out.println("startAvi result: " + startAvi);

    // int closeAvi = AviToolsLibrary.isavi_ExitAVI(initAvi);
    // System.out.println("closeAvi result: "+ closeAvi);
  }
Ejemplo n.º 21
0
  @Test
  public void testModuleLog() {
    Pointer module = ssclib.ssc_module_create("layoutarea");
    boolean result = ssclib.ssc_module_exec(module, data);

    assertThat(result).isFalse();

    int i = 0;
    IntByReference itemType = new IntByReference();
    FloatByReference time = new FloatByReference();
    String logMsg = ssclib.ssc_module_log(module, i, itemType, time);
    do {
      assertThat(logMsg).isNotNull();

      assertThat(itemType.getValue()).isGreaterThan(0);
      assertThat(time.getValue()).isNotWithin(EPSILON).of(0f);

      i++;
      logMsg = ssclib.ssc_module_log(module, i, itemType, time);
    } while (logMsg != null);
  }
Ejemplo n.º 22
0
  public WindowsOSSystemInfo() {

    SYSTEM_INFO si = new SYSTEM_INFO();
    Kernel32.INSTANCE.GetSystemInfo(si);

    try {
      IntByReference isWow64 = new IntByReference();
      HANDLE hProcess = Kernel32.INSTANCE.GetCurrentProcess();
      if (Kernel32.INSTANCE.IsWow64Process(hProcess, isWow64)) {
        if (isWow64.getValue() > 0) {
          Kernel32.INSTANCE.GetNativeSystemInfo(si);
        }
      }
    } catch (UnsatisfiedLinkError e) {
      // no WOW64 support
      LOG.trace("", e);
    }

    this._si = si;
    LOG.debug("Initialized OSNativeSystemInfo");
  }
Ejemplo n.º 23
0
  /** Return all the kernels found in the program. */
  public CLKernel[] createKernels() throws CLBuildException {
    synchronized (this) {
      if (!built) build();
    }
    IntByReference pCount = new IntByReference();
    int previousAttempts = 0;
    while (failedForLackOfMemory(
        CL.clCreateKernelsInProgram(getEntity(), 0, (cl_kernel[]) null, pCount),
        previousAttempts++)) {}

    int count = pCount.getValue();
    cl_kernel[] kerns = new cl_kernel[count];
    previousAttempts = 0;
    while (failedForLackOfMemory(
        CL.clCreateKernelsInProgram(getEntity(), count, kerns, pCount), previousAttempts++)) {}

    CLKernel[] kernels = new CLKernel[count];
    for (int i = 0; i < count; i++) kernels[i] = new CLKernel(this, null, kerns[i]);

    return kernels;
  }
Ejemplo n.º 24
0
  /**
   * @param devName
   * @return an {@link org.pcap4j.util.Inet4NetworkAddress Inet4NetworkAddress} object.
   * @throws PcapNativeException
   */
  public static Inet4NetworkAddress lookupNet(String devName) throws PcapNativeException {
    if (devName == null) {
      StringBuilder sb = new StringBuilder();
      sb.append("devName: ").append(devName);
      throw new NullPointerException(sb.toString());
    }

    PcapErrbuf errbuf = new PcapErrbuf();
    IntByReference netp = new IntByReference();
    IntByReference maskp = new IntByReference();
    int rc = NativeMappings.pcap_lookupnet(devName, netp, maskp, errbuf);

    if (rc < 0) {
      throw new PcapNativeException(errbuf.toString(), rc);
    }

    int net = netp.getValue();
    int mask = maskp.getValue();

    return new Inet4NetworkAddress(Inets.itoInetAddress(net), Inets.itoInetAddress(mask));
  }
Ejemplo n.º 25
0
  public static int sched_getcpu() {
    final CLibrary lib = CLibrary.INSTANCE;
    try {
      final int ret = lib.sched_getcpu();
      if (ret < 0) {
        throw new IllegalStateException("sched_getcpu() failed; errno=" + Native.getLastError());
      }
      return ret;
    } catch (LastErrorException e) {
      throw new IllegalStateException("sched_getcpu() failed; errno=" + e.getErrorCode(), e);
    } catch (UnsatisfiedLinkError ule) {
      try {
        final IntByReference cpu = new IntByReference();
        final IntByReference node = new IntByReference();
        final int ret = lib.syscall(318, cpu, node, null);
        if (ret != 0) {
          throw new IllegalStateException("getcpu() failed; errno=" + Native.getLastError());
        }
        return cpu.getValue();
      } catch (LastErrorException lee) {
        if (lee.getErrorCode() == 38 && Platform.is64Bit()) { // unknown call
          final Pointer getcpuAddr = new Pointer((-10L << 20) + 1024L * 2L);
          final Function getcpu = Function.getFunction(getcpuAddr, Function.C_CONVENTION);
          final IntByReference cpu = new IntByReference();
          if (getcpu.invokeInt(new Object[] {cpu, null, null}) < 0) {
            throw new IllegalStateException("getcpu() failed; errno=" + Native.getLastError());

          } else {
            return cpu.getValue();
          }
        } else {
          throw new IllegalStateException("getcpu() failed; errno=" + lee.getErrorCode(), lee);
        }
      }
    }
  }
Ejemplo n.º 26
0
  public XTestDemo() throws InterruptedException {
    IntByReference event_basep = new IntByReference();
    IntByReference error_basep = new IntByReference();
    IntByReference majorp = new IntByReference();
    IntByReference minorp = new IntByReference();

    if (X11.XTest.INSTANCE.XTestQueryExtension(
        display.getX11Display(), event_basep, error_basep, majorp, minorp)) {

      System.out.println("event_basep.getValue() = " + event_basep.getValue());
      System.out.println("error_basep.getValue() = " + error_basep.getValue());
      System.out.println("majorp.getValue() = " + majorp.getValue());
      System.out.println("minorp.getValue() = " + minorp.getValue());
    }

    Thread.sleep(1000);

    type("hello world");
    //        typeKey("Return");
    //        type("it works!");

    Thread.sleep(1000);
  }
Ejemplo n.º 27
0
  @Test
  public void setMatrix() {
    float value = 0.5f;
    int n = 2;
    float[] array = {value, value, value, value};
    String name = "test";

    ssclib.ssc_data_set_matrix(data, name, array, n, n);
    IntByReference rows = new IntByReference();
    IntByReference cols = new IntByReference();
    Pointer result = ssclib.ssc_data_get_matrix(data, name, rows, cols);

    assertThat(rows.getValue()).isEqualTo(n);
    assertThat(cols.getValue()).isEqualTo(n);
    for (int i = 0; i < rows.getValue(); i++) {
      for (int j = 0; j < cols.getValue(); j++) {
        // Offset is by byte (float = 4 bytes)
        assertThat(result.getFloat((i * j + j) * 4)).isWithin(EPSILON).of(value);
      }
    }
  }
  public StationTimeSeriesNetCDFFile(
      File file,
      RecordType rt,
      Map<String, String> globalAttrs,
      boolean doChunking,
      Station... stations) {
    this.record = rt;
    this.record_index = 0;
    this.name = file.getName();

    this.createFlags = NC_NETCDF4;

    // this.convention = convention;

    int ncStatus;
    IntByReference iRef = new IntByReference();

    ncStatus = nc_create(file.getAbsolutePath(), createFlags, iRef);
    status(ncStatus);
    ncId = iRef.getValue();

    // DIMENSIONS:
    ncStatus = nc_def_dim(ncId, STATION_DIM_NAME, new NativeLong(stations.length), iRef);
    status(ncStatus);
    ncDimId_station = iRef.getValue();

    int max_length = Station.findMaxStationLength(stations);
    ncStatus = nc_def_dim(ncId, STATION_ID_LEN_NAME, new NativeLong(max_length), iRef);
    status(ncStatus);
    ncDimId_station_id_len = iRef.getValue();

    ncStatus = nc_def_dim(ncId, OBSERVATION_DIM_NAME, new NativeLong(NC_UNLIMITED), iRef);
    status(ncStatus);
    ncDimId_observation = iRef.getValue();

    //// VARIABLES
    // STATION
    int ncTypeId_record_type = this.record.writeRecordCompound(ncId);
    Map<String, Variable> stVars =
        this.record.writeStationVariables(ncId, ncDimId_station, ncDimId_station_id_len);
    this.record.writeObservationVariables(
        ncId, new int[] {ncDimId_observation}, ncTypeId_record_type, doChunking);

    // Global Attributes
    writeGlobalAttributes(globalAttrs);

    ncStatus = nc_enddef(ncId);
    status(ncStatus);

    // Now lets fill in the Station data from vararg stations
    // Then we're set up to start putting observations
    NativeLong station_indexp = new NativeLong(0);
    NativeLong stationid_len_indexp = new NativeLong(0);
    for (Station station : stations) {
      ncStatus =
          nc_put_var1_float(ncId, stVars.get("lon").ncVarId, station.longitude, station_indexp);
      status(ncStatus);
      ncStatus =
          nc_put_var1_float(ncId, stVars.get("lat").ncVarId, station.latitude, station_indexp);
      status(ncStatus);
      ncStatus =
          nc_put_vara_text(
              ncId,
              stVars.get("station_id").ncVarId,
              station.station_id,
              station_indexp,
              stationid_len_indexp);
      status(ncStatus);
      station_indexp.setValue(station_indexp.longValue() + 1);
    }
  }
Ejemplo n.º 29
0
 @Override
 public int getHandle() {
   return handle.getValue();
 }
Ejemplo n.º 30
0
  @Override
  protected void doTask() {

    NotesNativeLibrary notes = NotesNativeLibrary.SYNC_INSTANCE;

    IntByReference dbHandle = new IntByReference();
    NativeLongByReference note_handle = new NativeLongByReference();

    // Note Item field
    String FIELD_SCXD = "$XpageSharedDesign";
    // StringByReference scxdFlagField = new StringByReference(FIELD_SCXD);
    // short flag_field_length = (short) FIELD_SCXD.length();

    String flagSetting = (flag) ? "1" : "0";

    StringByReference flagSettingRef = new StringByReference(flagSetting);

    String FIELD_SCXDPATH = "$XpageSharedDesignTemplate";
    // StringByReference scxdPathField = new StringByReference(FIELD_SCXDPATH);
    // short path_field_length = (short) FIELD_SCXDPATH.length();
    StringByReference scxdFilePath = new StringByReference(this.scxdPath);

    short open_flags = 0;
    int note_id = (NOTE_ID_SPECIAL | NOTE_CLASS_ICON);

    short errorint = 0;
    boolean dbOpen = false;
    boolean noteOpen = false;

    try {

      String pathnet = pathNetConstruct(server, database);
      errorint = notes.NSFDbOpen(pathnet, dbHandle);

      checkError(errorint);
      dbOpen = true;

      // Update the Note With SCXD details
      errorint = notes.NSFNoteOpen(dbHandle.getValue(), note_id, open_flags, note_handle);
      checkError(errorint);
      noteOpen = true;

      // errorint = notes.NSFItemInfo(note_handle.getValue(),
      // scxdFlagField, flag_field_length, Pointer.NULL, Pointer.NULL,
      // Pointer.NULL, Pointer.NULL);
      // checkError(errorint);

      // Check the Existing setting for the Flag
      StringByReference existFlag = new StringByReference(128);
      short retLengthFlag =
          notes.NSFItemGetText(note_handle.getValue(), FIELD_SCXD, existFlag, (short) 128);
      checkError(errorint);
      System.out.println("Prev scxdflag: " + existFlag.getValue().substring(0, retLengthFlag));

      short flagLength = (short) flagSettingRef.getValue().length();
      errorint =
          notes.NSFItemSetText(
              note_handle.getValue(), FIELD_SCXD, flagSettingRef.getValue(), flagLength);
      checkError(errorint);
      System.out.println("New scxdflag: " + flagSettingRef.getValue());

      // Update Path
      // errorint = notes.NSFItemInfo(note_handle.getValue(),
      // scxdPathField, path_field_length, Pointer.NULL, Pointer.NULL,
      // Pointer.NULL, Pointer.NULL);
      // checkError(errorint);

      StringByReference me = new StringByReference(128);
      short retLength =
          notes.NSFItemGetText(note_handle.getValue(), FIELD_SCXDPATH, me, (short) 128);
      checkError(errorint);
      System.out.println("Previous scxdpath: " + me.getValue().substring(0, retLength));

      short pathLength = (short) scxdFilePath.getValue().length();
      errorint =
          notes.NSFItemSetText(
              note_handle.getValue(), FIELD_SCXDPATH, scxdFilePath.getValue(), pathLength);
      checkError(errorint);
      System.out.println("New scxdpath: " + scxdFilePath.getValue());

      errorint = notes.NSFNoteUpdate(note_handle.getValue(), (short) 0);
      checkError(errorint);
      System.out.println("Update complete");

    } finally {

      if (noteOpen) {
        errorint = notes.NSFNoteClose(note_handle.getValue());
        checkError(errorint);
        noteOpen = false;
      }

      if (dbOpen) {
        errorint = notes.NSFDbClose(dbHandle.getValue());
        checkError(errorint);
        dbOpen = false;
      }
    }
  }