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;
  }
  private static void initialize() {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      return;
    }

    Ole32 ole32 = Ole32.INSTANCE;
    ole32.CoInitializeEx(Pointer.NULL, 0);

    Guid.GUID CLSID_TaskbarList =
        Ole32Util.getGUIDFromString("{56FDF344-FD6D-11d0-958A-006097C9A090}");
    Guid.GUID IID_ITaskbarList3 =
        Ole32Util.getGUIDFromString("{EA1AFB91-9E28-4B86-90E9-9E9F8A5EEFAF}");
    PointerByReference p = new PointerByReference();
    ole32.CoCreateInstance(
        CLSID_TaskbarList, Pointer.NULL, ObjBase.CLSCTX_ALL, IID_ITaskbarList3, p);

    myInterfacePointer = p.getValue();
    Pointer vTablePointer = myInterfacePointer.getPointer(0);
    Pointer[] vTable = new Pointer[TaskBarList_Methods];
    vTablePointer.read(0, vTable, 0, vTable.length);

    mySetProgressValue =
        Function.getFunction(vTable[TaskBarList_SetProgressValue], Function.ALT_CONVENTION);
    mySetProgressState =
        Function.getFunction(vTable[TaskBarList_SetProgressState], Function.ALT_CONVENTION);
    mySetOverlayIcon =
        Function.getFunction(vTable[TaskBarList_SetOverlayIcon], Function.ALT_CONVENTION);
  }
Esempio n. 3
0
 public void testSHGetDesktopFolder() {
   PointerByReference ppshf = new PointerByReference();
   WinNT.HRESULT hr = Shell32.INSTANCE.SHGetDesktopFolder(ppshf);
   assertTrue(W32Errors.SUCCEEDED(hr.intValue()));
   assertTrue(ppshf.getValue() != null);
   // should release the interface, but we need Com4JNA to do that.
 }
    @Override
    public HRESULT QueryInterface(REFIID.ByValue refid, PointerByReference ppvObject) {
      this.QueryInterface_called = true;
      if (null == ppvObject) {
        return new HRESULT(WinError.E_POINTER);
      }

      String s = refid.toGuidString();
      IID appEvnts4 = new IID("{00020A01-0000-0000-C000-000000000046}");
      REFIID.ByValue riid = new REFIID.ByValue(appEvnts4.getPointer());

      if (refid.equals(riid)) {
        return WinError.S_OK;
      }

      if (new Guid.IID(refid.getPointer()).equals(Unknown.IID_IUNKNOWN)) {
        ppvObject.setValue(this.getPointer());
        return WinError.S_OK;
      }

      if (new Guid.IID(refid.getPointer()).equals(Dispatch.IID_IDISPATCH)) {
        ppvObject.setValue(this.getPointer());
        return WinError.S_OK;
      }

      return new HRESULT(WinError.E_NOINTERFACE);
    }
Esempio n. 5
0
  /**
   * @return a list of PcapNetworkInterfaces.
   * @throws PcapNativeException
   */
  public static List<PcapNetworkInterface> findAllDevs() throws PcapNativeException {
    PointerByReference alldevsPP = new PointerByReference();
    PcapErrbuf errbuf = new PcapErrbuf();

    int rc = NativeMappings.pcap_findalldevs(alldevsPP, errbuf);
    if (rc != 0) {
      StringBuilder sb = new StringBuilder(50);
      sb.append("Return code: ").append(rc).append(", Message: ").append(errbuf);
      throw new PcapNativeException(sb.toString(), rc);
    }
    if (errbuf.length() != 0) {
      logger.warn("{}", errbuf);
    }

    Pointer alldevsp = alldevsPP.getValue();
    if (alldevsp == null) {
      logger.info("No NIF was found.");
      return Collections.<PcapNetworkInterface>emptyList();
    }

    pcap_if pcapIf = new pcap_if(alldevsp);

    List<PcapNetworkInterface> ifList = new ArrayList<PcapNetworkInterface>();
    for (pcap_if pif = pcapIf; pif != null; pif = pif.next) {
      ifList.add(PcapNetworkInterface.newInstance(pif, true));
    }

    NativeMappings.pcap_freealldevs(pcapIf.getPointer());

    logger.info("{} NIF(s) found.", ifList.size());
    return ifList;
  }
Esempio n. 6
0
  /** Test of TessBaseAPIInit4 method, of class TessAPI1. */
  @Test
  public void testTessBaseAPIInit4() {
    logger.info("TessBaseAPIInit4");
    int oem = TessOcrEngineMode.OEM_DEFAULT;
    PointerByReference configs = null;
    int configs_size = 0;
    // disable loading dictionaries
    String[] args = new String[] {"load_system_dawg", "load_freq_dawg"};
    StringArray sarray = new StringArray(args);
    PointerByReference vars_vec = new PointerByReference();
    vars_vec.setPointer(sarray);

    args = new String[] {"F", "F"};
    sarray = new StringArray(args);
    PointerByReference vars_values = new PointerByReference();
    vars_values.setPointer(sarray);

    NativeSize vars_vec_size = new NativeSize(args.length);

    int expResult = 0;
    int result =
        TessAPI1.TessBaseAPIInit4(
            handle,
            datapath,
            language,
            oem,
            configs,
            configs_size,
            vars_vec,
            vars_values,
            vars_vec_size,
            FALSE);
    assertEquals(expResult, result);
  }
Esempio n. 7
0
  protected void setBinaries(Map<CLDevice, byte[]> binaries) {
    if (this.devices == null) {
      this.devices = new CLDevice[binaries.size()];
      int iDevice = 0;
      for (CLDevice device : binaries.keySet()) this.devices[iDevice++] = device;
    }
    int nDevices = this.devices.length;
    NativeSize[] lengths = new NativeSize[nDevices];
    cl_device_id[] deviceIds = new cl_device_id[nDevices];
    Memory binariesArray = new Memory(Pointer.SIZE * nDevices);
    Memory[] binariesMems = new Memory[nDevices];

    for (int iDevice = 0; iDevice < nDevices; iDevice++) {
      CLDevice device = devices[iDevice];
      byte[] binary = binaries.get(device);

      Memory binaryMem = binariesMems[iDevice] = new Memory(binary.length);
      binaryMem.write(0, binary, 0, binary.length);
      binariesArray.setPointer(iDevice * Pointer.SIZE, binaryMem);

      lengths[iDevice] = toNS(binary.length);
      deviceIds[iDevice] = device.getEntity();
    }
    PointerByReference binariesPtr = new PointerByReference();
    binariesPtr.setPointer(binariesArray);

    IntBuffer errBuff = NIOUtils.directInts(1, ByteOrder.nativeOrder());
    int previousAttempts = 0;
    IntBuffer statuses = NIOUtils.directInts(nDevices, ByteOrder.nativeOrder());
    do {
      entity =
          CL.clCreateProgramWithBinary(
              context.getEntity(), nDevices, deviceIds, lengths, binariesPtr, statuses, errBuff);
    } while (failedForLackOfMemory(errBuff.get(0), previousAttempts++));
  }
  @Test
  public void Advise() {

    // query for ConnectionPointContainer
    Unknown unk = new Unknown(this.ppWordApp.getValue());
    PointerByReference ppCpc = new PointerByReference();
    IID cpcIID = new IID("{B196B284-BAB4-101A-B69C-00AA00341D07}");
    HRESULT hr = unk.QueryInterface(new REFIID.ByValue(cpcIID), ppCpc);
    COMUtils.checkRC(hr);
    ConnectionPointContainer cpc = new ConnectionPointContainer(ppCpc.getValue());

    // find connection point for Application_Events4
    IID appEvnts4 = new IID("{00020A01-0000-0000-C000-000000000046}");
    REFIID riid = new REFIID(appEvnts4.getPointer());
    PointerByReference ppCp = new PointerByReference();
    hr = cpc.FindConnectionPoint(riid, ppCp);
    COMUtils.checkRC(hr);
    ConnectionPoint cp = new ConnectionPoint(ppCp.getValue());
    IID cp_iid = new IID();
    hr = cp.GetConnectionInterface(cp_iid);
    COMUtils.checkRC(hr);

    Application_Events4 listener = new Application_Events4();

    DWORDByReference pdwCookie = new DWORDByReference();
    hr = cp.Advise(listener, pdwCookie);
    COMUtils.checkRC(hr);

    Assert.assertTrue(listener.QueryInterface_called);
  }
Esempio n. 9
0
  public List<WebElement> findElementsById(String using) {
    PointerByReference elements = new PointerByReference();
    int result = lib.wdFindElementsById(driver, element, new WString(using), elements);

    handleErrorCode("id", using, result);

    return new ElementCollection(lib, driver, elements.getValue()).toList();
  }
Esempio n. 10
0
  public WebElement findElementByLinkText(String using) {
    PointerByReference rawElement = new PointerByReference();
    int result = lib.wdFindElementByLinkText(driver, element, new WString(using), rawElement);

    handleErrorCode("link text", using, result);

    return new InternetExplorerElement(lib, driver, rawElement.getValue());
  }
 @Test
 public void queryInterface_ConnectionPointContainer() {
   Unknown unk = new Unknown(this.ppWordApp.getValue());
   PointerByReference ppCpc = new PointerByReference();
   IID cpcIID = new IID("{B196B284-BAB4-101A-B69C-00AA00341D07}");
   HRESULT hr = unk.QueryInterface(new REFIID.ByValue(cpcIID), ppCpc);
   COMUtils.checkRC(hr);
   ConnectionPointContainer cpc = new ConnectionPointContainer(ppCpc.getValue());
 }
Esempio n. 12
0
 public Pointer SendMessageTimeoutA(
     Pointer hWnd, Messages Msg, FType wParam, int lParam, int fuFlags, int uTimeout)
     throws Exception {
   PointerByReference lpdwResult = new PointerByReference();
   int ret =
       u32.SendMessageTimeoutA(
           hWnd, Msg.getValue(), wParam.getValue(), lParam, fuFlags, uTimeout, lpdwResult);
   if (ret == 0) {
     int err = Native.getLastError();
     throw new Exception("GetClassLong failed. Error: " + err);
   }
   return lpdwResult.getValue();
 }
Esempio n. 13
0
 /** Test of TessBaseAPIInit1 method, of class TessAPI1. */
 @Test
 public void testTessBaseAPIInit1() throws Exception {
   logger.info("TessBaseAPIInit1");
   int oem = TessOcrEngineMode.OEM_DEFAULT;
   String[] args = {"hocr"};
   StringArray sarray = new StringArray(args);
   PointerByReference configs = new PointerByReference();
   configs.setPointer(sarray);
   int configs_size = args.length;
   int expResult = 0;
   int result = TessAPI1.TessBaseAPIInit1(handle, datapath, language, oem, configs, configs_size);
   assertEquals(expResult, result);
 }
Esempio n. 14
0
  private void writeNative(byte[] bs) throws SerialPortException {
    Memory mem = new Memory(Byte.SIZE * bs.length + 1);
    mem.clear();

    PointerByReference inipar = new PointerByReference();
    inipar.setPointer(mem);
    for (int i = 0; i < bs.length; i++) {
      inipar.getPointer().setByte(i * Byte.SIZE / 8, bs[i]);
    }
    byte c = '\n';
    inipar.getPointer().setByte((bs.length + 1) * Byte.SIZE / 8, c);
    int rt = NativeLoader.getInstance().serialport_write(getFd(), inipar);
    if (rt != 0) {
      logger.error("Warning fail to write store " + bs.length);
      throw new SerialPortException("The serial port is closed " + getFd());
    }
  }
Esempio n. 15
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;
  }
  @Test
  public void FindConnectionPoint() {
    // query for ConnectionPointContainer
    Unknown unk = new Unknown(this.ppWordApp.getValue());
    PointerByReference ppCpc = new PointerByReference();
    IID cpcIID = new IID("{B196B284-BAB4-101A-B69C-00AA00341D07}");
    HRESULT hr = unk.QueryInterface(new REFIID.ByValue(cpcIID), ppCpc);
    COMUtils.checkRC(hr);
    ConnectionPointContainer cpc = new ConnectionPointContainer(ppCpc.getValue());

    // find connection point for Application_Events4
    IID appEvnts4 = new IID("{00020A01-0000-0000-C000-000000000046}");
    REFIID riid = new REFIID(appEvnts4.getPointer());
    PointerByReference ppCp = new PointerByReference();
    hr = cpc.FindConnectionPoint(riid, ppCp);
    COMUtils.checkRC(hr);
    ConnectionPoint cp = new ConnectionPoint(ppCp.getValue());
  }
Esempio n. 17
0
  /** try to install our custom rule profile into sandbox_init() to block execution */
  private static void macImpl(Path tmpFile) throws IOException {
    // first be defensive: we can give nice errors this way, at the very least.
    boolean supported = Constants.MAC_OS_X;
    if (supported == false) {
      throw new IllegalStateException(
          "bug: should not be trying to initialize seatbelt for an unsupported OS");
    }

    // we couldn't link methods, could be some really ancient OS X (< Leopard) or some bug
    if (libc_mac == null) {
      throw new UnsupportedOperationException(
          "seatbelt unavailable: could not link methods. requires Leopard or above.");
    }

    // write rules to a temporary file, which will be passed to sandbox_init()
    Path rules = Files.createTempFile(tmpFile, "es", "sb");
    Files.write(rules, Collections.singleton(SANDBOX_RULES));

    boolean success = false;
    try {
      PointerByReference errorRef = new PointerByReference();
      int ret = libc_mac.sandbox_init(rules.toAbsolutePath().toString(), SANDBOX_NAMED, errorRef);
      // if sandbox_init() fails, add the message from the OS (e.g. syntax error) and free the
      // buffer
      if (ret != 0) {
        Pointer errorBuf = errorRef.getValue();
        RuntimeException e =
            new UnsupportedOperationException("sandbox_init(): " + errorBuf.getString(0));
        libc_mac.sandbox_free_error(errorBuf);
        throw e;
      }
      logger.debug("OS X seatbelt initialization successful");
      success = true;
    } finally {
      if (success) {
        Files.delete(rules);
      } else {
        IOUtils.deleteFilesIgnoringExceptions(rules);
      }
    }
  }
Esempio n. 18
0
  /**
   * Test of TessBaseAPIGetUTF8Text method, of class TessAPI1.
   *
   * @throws java.lang.Exception
   */
  @Test
  public void testTessBaseAPIGetUTF8Text_Pix() throws Exception {
    logger.info("TessBaseAPIGetUTF8Text_Pix");
    String expResult = expOCRResult;
    File tiff = new File(this.testResourcesDataPath, "eurotext.tif");
    Leptonica leptInstance = Leptonica.INSTANCE;
    Pix pix = leptInstance.pixRead(tiff.getPath());
    TessAPI1.TessBaseAPIInit3(handle, datapath, language);
    TessAPI1.TessBaseAPISetImage2(handle, pix);
    Pointer utf8Text = TessAPI1.TessBaseAPIGetUTF8Text(handle);
    String result = utf8Text.getString(0);
    TessAPI1.TessDeleteText(utf8Text);
    logger.info(result);

    // release Pix resource
    PointerByReference pRef = new PointerByReference();
    pRef.setValue(pix.getPointer());
    leptInstance.pixDestroy(pRef);

    assertEquals(expResult, result.substring(0, expResult.length()));
  }
Esempio n. 19
0
  /**
   * Test of TessBaseAPIGetComponentImages method, of class TessAPI1.
   *
   * @throws java.lang.Exception
   */
  @Test
  public void testTessBaseAPIGetComponentImages() throws Exception {
    logger.info("TessBaseAPIGetComponentImages");
    File image = new File(this.testResourcesDataPath, "eurotext.png");
    int expResult = 12; // number of lines in the test image
    Pix pix = Leptonica1.pixRead(image.getPath());
    TessAPI1.TessBaseAPIInit3(handle, datapath, language);
    TessAPI1.TessBaseAPISetImage2(handle, pix);
    PointerByReference pixa = null;
    PointerByReference blockids = null;
    Boxa boxes =
        TessAPI1.TessBaseAPIGetComponentImages(
            handle, TessPageIteratorLevel.RIL_TEXTLINE, TRUE, pixa, blockids);
    //        boxes = TessAPI1.TessBaseAPIGetRegions(handle, pixa); // equivalent to
    // TessPageIteratorLevel.RIL_BLOCK
    int boxCount = Leptonica1.boxaGetCount(boxes);
    for (int i = 0; i < boxCount; i++) {
      Box box = Leptonica1.boxaGetBox(boxes, i, L_CLONE);
      if (box == null) {
        continue;
      }
      TessAPI1.TessBaseAPISetRectangle(handle, box.x, box.y, box.w, box.h);
      Pointer utf8Text = TessAPI1.TessBaseAPIGetUTF8Text(handle);
      String ocrResult = utf8Text.getString(0);
      TessAPI1.TessDeleteText(utf8Text);
      int conf = TessAPI1.TessBaseAPIMeanTextConf(handle);
      System.out.print(
          String.format(
              "Box[%d]: x=%d, y=%d, w=%d, h=%d, confidence: %d, text: %s",
              i, box.x, box.y, box.w, box.h, conf, ocrResult));
    }

    // release Pix resource
    PointerByReference pRef = new PointerByReference();
    pRef.setValue(pix.getPointer());
    Leptonica1.pixDestroy(pRef);

    assertEquals(expResult, boxCount);
  }
Esempio n. 20
0
  @Override
  public void visitSources(IElementVisitor visitor) {
    if (visitor == null) return;

    Pointer pIterator = gst_bin_iterate_sources(ptr);
    if (pIterator == null || pIterator == Pointer.NULL) return;

    boolean done = false;
    PointerByReference ref = new PointerByReference();
    while (!done) {
      // This will increase the ref counter -- so we need to create an object
      // that doesn't increase the ref counter when it's built so on dispose(),
      // the ref count will be zero.
      switch (IteratorResult.fromNative(gst_iterator_next(pIterator, ref))) {
        case OK:
          // Passing true here tells it to increase the ref count
          // when building a new element from the pointer.
          IElement element = Element.from(ref.getValue(), true);
          boolean ret = visitor.visit(this, element);
          element.unref();
          done = !ret;
          break;
        case Resync:
          gst_iterator_resync(pIterator);
          break;
        case Error:
        case Done:
        case Unknown:
          done = true;
          break;
        default:
          done = true;
          break;
      }
    }
    gst_iterator_free(pIterator);
  }
Esempio n. 21
0
  /**
   * Download a live view image from the camera and convert it directly into a bufferd image.
   *
   * @param camera
   * @return
   */
  public static BufferedImage getLiveViewImage(final EdsCameraRef camera) {
    EdsError err = EdsError.EDS_ERR_OK;

    final EdsBaseRef.ByReference[] references = CanonUtils.getLiveViewImageReference(camera);
    if (references != null) {
      final EdsStreamRef.ByReference streamRef = (EdsStreamRef.ByReference) references[1];
      final EdsEvfImageRef.ByReference imageRef = (EdsEvfImageRef.ByReference) references[0];

      //		// Get the incidental data of the image.
      //		NativeLongByReference zoom = new NativeLongByReference( new NativeLong( 0 ) );
      //		Pointer data = zoom.getPointer();
      //		err = getPropertyData( image.getValue(), EdSdkLibrary.kEdsPropID_Evf_ZoomPosition, 0,
      // NativeLong.SIZE, data );
      //		if( err != EdsError.EDS_ERR_OK ){
      //			System.err.println( "Failed to download live view image, zoom value wasn't read (error "+
      // err.value() + ": "+ err.name() + " - " + err.description() + ")" );
      //			return null;
      //		}
      //
      //		// Get the focus and zoom border position
      //		EdsPoint point = new EdsPoint();
      //		data = point.getPointer();
      //		err = getPropertyData( image.getValue(), EdSdkLibrary.kEdsPropID_Evf_ZoomPosition, 0 ,
      // sizeof( point ), data );
      //		if( err != EdsError.EDS_ERR_OK ){
      //			System.err.println( "Failed to download live view image, focus point wasn't read (error
      // "+ err.value() + ": "+ err.name() + " - " + err.description() + ")" );
      //			return null;
      //		}

      final NativeLongByReference length = new NativeLongByReference();
      err = CanonUtils.toEdsError(CanonCamera.EDSDK.EdsGetLength(streamRef.getValue(), length));
      if (err != EdsError.EDS_ERR_OK) {
        System.err.println(
            "Failed to download live view image, failed to read stream length (error "
                + err.value()
                + ": "
                + err.name()
                + " - "
                + err.description()
                + ")");
        CanonUtils.release(imageRef, streamRef);
        return null;
      }

      final PointerByReference ref = new PointerByReference();
      err = CanonUtils.toEdsError(CanonCamera.EDSDK.EdsGetPointer(streamRef.getValue(), ref));
      if (err != EdsError.EDS_ERR_OK) {
        System.err.println(
            "Failed to download live view image, failed to get reference to image in memory (error "
                + err.value()
                + ": "
                + err.name()
                + " - "
                + err.description()
                + ")");
        CanonUtils.release(imageRef, streamRef);
        return null;
      }

      final byte[] data = ref.getValue().getByteArray(0, length.getValue().intValue());
      try {
        final BufferedImage img = ImageIO.read(new ByteArrayInputStream(data));
        return img;
      } catch (final IOException e) {
        e.printStackTrace();
      } finally {
        CanonUtils.release(imageRef, streamRef);
      }
    }

    return null;
  }
Esempio n. 22
0
  /**
   * Test of ResultRenderer method, of class TessAPI1.
   *
   * @throws java.lang.Exception
   */
  @Test
  public void testResultRenderer() throws Exception {
    logger.info("TessResultRenderer");
    String image = String.format("%s/%s", this.testResourcesDataPath, "eurotext.tif");
    String output = "capi-test.txt";
    int set_only_init_params = TessAPI.FALSE;
    int oem = TessOcrEngineMode.OEM_DEFAULT;
    PointerByReference configs = null;
    int configs_size = 0;

    String[] params = {"load_system_dawg", "tessedit_char_whitelist"};
    String vals[] = {"F", ""}; // 0123456789-.IThisalotfpnex
    PointerByReference vars_vec = new PointerByReference();
    vars_vec.setPointer(new StringArray(params));
    PointerByReference vars_values = new PointerByReference();
    vars_values.setPointer(new StringArray(vals));
    NativeSize vars_vec_size = new NativeSize(params.length);

    TessAPI1.TessBaseAPISetOutputName(handle, output);

    int rc =
        TessAPI1.TessBaseAPIInit4(
            handle,
            datapath,
            language,
            oem,
            configs,
            configs_size,
            vars_vec,
            vars_values,
            vars_vec_size,
            set_only_init_params);

    if (rc != 0) {
      TessAPI1.TessBaseAPIDelete(handle);
      logger.error("Could not initialize tesseract.");
      return;
    }

    String outputbase = "target/test-classes/test-results/outputbase1";
    TessResultRenderer renderer = TessAPI1.TessHOcrRendererCreate(outputbase);
    TessAPI1.TessResultRendererInsert(renderer, TessAPI1.TessBoxTextRendererCreate(outputbase));
    TessAPI1.TessResultRendererInsert(renderer, TessAPI1.TessTextRendererCreate(outputbase));
    String dataPath = TessAPI1.TessBaseAPIGetDatapath(handle);
    TessAPI1.TessResultRendererInsert(
        renderer, TessAPI1.TessPDFRendererCreate(outputbase, dataPath));
    TessAPI1.TessResultRendererBeginDocument(renderer, image);
    int result = TessAPI1.TessBaseAPIProcessPages(handle, image, null, 0, renderer);
    TessAPI1.TessResultRendererEndDocument(renderer);

    //        if (result == FALSE) {
    //            logger.error("Error during processing.");
    //            return;
    //        }
    for (; renderer != null; renderer = TessAPI1.TessResultRendererNext(renderer)) {
      String ext = TessAPI1.TessResultRendererExtention(renderer).getString(0);
      logger.info(
          String.format(
              "TessResultRendererExtention: %s\nTessResultRendererTitle: %s\nTessResultRendererImageNum: %d",
              ext,
              TessAPI1.TessResultRendererTitle(renderer).getString(0),
              TessAPI1.TessResultRendererImageNum(renderer)));
    }

    TessAPI1.TessDeleteResultRenderer(renderer);
    assertTrue(new File(outputbase + ".pdf").exists());
  }
Esempio n. 23
0
 public final long getAddress() {
   PointerByReference ref = new PointerByReference(ptr);
   return ADDRESS_SIZE == 32
       ? (ref.getPointer().getInt(0) & 0xffffffffL)
       : ref.getPointer().getLong(0);
 }
Esempio n. 24
0
 public Collection<String> getLogFiles() {
   PointerByReference ptrRef = s_lib.CExternalEntry_getLogFilePaths();
   String[] strs = ptrRef.getPointer().getStringArray(0);
   return Arrays.asList(strs);
 }
Esempio n. 25
0
  private DomainControllerInfo getDcInfo(String domainName, boolean bForceRediscovery) {
    DomainControllerInfo domainInfo = null;

    int dwError = 0;
    WinDcInfoNative dcInfo = null;
    PointerByReference ppDcInfo = new PointerByReference(Pointer.NULL);
    Pointer pDcInfo = Pointer.NULL;

    WinDcInfoNative dcInfo_flat = null;
    PointerByReference ppDcInfo_flat = new PointerByReference(Pointer.NULL);
    Pointer pDcInfo_flat = Pointer.NULL;

    try {
      dwError =
          WinNetApi32.INSTANCE.DsGetDcName(
              null,
              domainName,
              null,
              null,
              bForceRediscovery
                  ? PlatformUtils.getFlagsForGetDcInfoWithRediscovery()
                  : PlatformUtils.getFlagsForGetDcInfo(),
              ppDcInfo);
      logAndThrow(
          String.format("Failed to get domain controller information for %s ", domainName),
          dwError);

      pDcInfo = ppDcInfo.getValue();
      if (pDcInfo == Pointer.NULL) {
        throw new DomainManagerException(
            String.format("Failed to get domain controller information for %s", domainName));
      }

      try {
        dcInfo = new WinDcInfoNative(pDcInfo);
      } catch (Exception e) {
        throw new DomainManagerException(
            String.format("Failed to get domain controller information for %s", domainName));
      }

      dwError =
          WinNetApi32.INSTANCE.DsGetDcName(
              null,
              domainName,
              null,
              null,
              PlatformUtils.getFlagsForGetFlatDcInfo(),
              ppDcInfo_flat);
      logAndThrow(
          String.format("Failed to get domain controller information for %s ", domainName),
          dwError);

      pDcInfo_flat = ppDcInfo_flat.getValue();
      if (pDcInfo_flat == Pointer.NULL) {
        throw new DomainManagerException(
            String.format("Failed to get domain controller information for %s", domainName));
      }

      try {
        dcInfo_flat = new WinDcInfoNative(pDcInfo_flat);
      } catch (Exception e) {
        throw new DomainManagerException(
            String.format("Failed to get domain controller information for %s", domainName));
      }

      if (dcInfo != null && dcInfo_flat != null) {
        domainInfo =
            new DomainControllerInfo(
                dcInfo.domainName,
                dcInfo_flat.domainName,
                dcInfo.domainControllerAddress,
                dcInfo.domainControllerName,
                dcInfo.dnsForestName);
      }

      return domainInfo;

    } catch (Win32Exception e) {
      String errMsg =
          String.format(
              "Failed to get domain controller information for %s",
              (domainName == null || domainName.length() == 0) ? "local host domain" : domainName);
      logger.error(errMsg);
      throw new DomainManagerException(errMsg + e.getMessage());
    } finally {
      if (pDcInfo != Pointer.NULL) {
        WinNetApi32.INSTANCE.NetApiBufferFree(pDcInfo);
      }
      if (pDcInfo_flat != Pointer.NULL) {
        WinNetApi32.INSTANCE.NetApiBufferFree(pDcInfo_flat);
      }
    }
  }