Java Code Examples for com.sun.jna.ptr.PointerByReference#getValue()

The following examples show how to use com.sun.jna.ptr.PointerByReference#getValue() . 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: KeychainCertificateStore.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public static X509Certificate toX509Certificate(final SecIdentityRef identityRef) {
    final PointerByReference reference = new PointerByReference();
    SecurityFunctions.library.SecIdentityCopyCertificate(identityRef, reference);
    final SecCertificateRef certificateRef = new SecCertificateRef(reference.getValue());
    try {
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
        final NSData dataRef = SecurityFunctions.library.SecCertificateCopyData(certificateRef);
        final X509Certificate selected = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(
            Base64.decodeBase64(dataRef.base64Encoding())));
        if(log.isDebugEnabled()) {
            log.info(String.format("Selected certificate %s", selected));
        }
        FoundationKitFunctions.library.CFRelease(certificateRef);
        return selected;
    }
    catch(CertificateException e) {
        log.error(String.format("Error %s creating certificate from reference", e));
        return null;
    }
}
 
Example 2
Source File: AbstractSocket.java    From jnanomsg with Apache License 2.0 6 votes vote down vote up
public synchronized byte[] recvBytes(final EnumSet<SocketFlag> flagSet)
  throws IOException {

  final PointerByReference ptrBuff = new PointerByReference();

  int flags = 0;
  if (flagSet.contains(SocketFlag.NN_DONTWAIT)){
    flags |= SocketFlag.NN_DONTWAIT.value();
  }

  final int rc = nn_recv(this.fd, ptrBuff, NN_MSG, flags);

  if (rc < 0) {
    Nanomsg.handleError(rc);
  }

  final Pointer result = ptrBuff.getValue();
  final byte[] bytesResult = result.getByteArray(0, rc);

  return bytesResult;
}
 
Example 3
Source File: CarbonProvider.java    From SikuliX1 with MIT License 6 votes vote down vote up
private void register(OSXHotKey hotKey) {
    KeyStroke keyCode = hotKey.keyStroke;
    EventHotKeyID.ByValue hotKeyReference = new EventHotKeyID.ByValue();
    int id = idSeq++;
    hotKeyReference.id = id;
    hotKeyReference.signature = OS_TYPE("hk" + String.format("%02d", id));
    PointerByReference gMyHotKeyRef = new PointerByReference();

    int status = Lib.RegisterEventHotKey(KeyMap.getKeyCode(keyCode), KeyMap.getModifier(keyCode), hotKeyReference, Lib.GetEventDispatcherTarget(), 0, gMyHotKeyRef);

    if (status != 0) {
        //LOGGER.warn("Could not register HotKey: " + keyCode + ". Error code: " + status);
        return;
    }

    if (gMyHotKeyRef.getValue() == null) {
        //LOGGER.warn("HotKey returned null handler reference");
        return;
    }
    hotKey.handler = gMyHotKeyRef;
    //LOGGER.info("Registered hotkey: " + keyCode);
    hotKeys.put(id, hotKey);
}
 
Example 4
Source File: JnaUtils.java    From djl with Apache License 2.0 6 votes vote down vote up
private static Set<String> getFeaturesInternal() {
    PointerByReference ref = new PointerByReference();
    NativeSizeByReference outSize = new NativeSizeByReference();
    checkCall(LIB.MXLibInfoFeatures(ref, outSize));

    int size = outSize.getValue().intValue();
    if (size == 0) {
        return Collections.emptySet();
    }

    LibFeature pointer = new LibFeature(ref.getValue());
    pointer.read();

    LibFeature[] features = (LibFeature[]) pointer.toArray(size);

    Set<String> set = new HashSet<>();
    for (LibFeature feature : features) {
        if (feature.getEnabled() == 1) {
            set.add(feature.getName());
        }
    }
    return set;
}
 
Example 5
Source File: MimeConversionControl.java    From domino-jna with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Conversions Controls context for the reading and writing of various conversion
 * configuration settings.<br>
 * The various settings are initialized to their default settings (the same as those set by {@link #setDefaults()}).
 */
public MimeConversionControl() {
	PointerByReference retConvControls = new PointerByReference();
	NotesNativeAPI.get().MMCreateConvControls(retConvControls);
	m_convControls = retConvControls.getValue();
	
	NotesGC.__objectCreated(MimeConversionControl.class, this);
}
 
Example 6
Source File: Seccomp.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/** 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), StandardCharsets.UTF_8);

    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);
        }
    }
}
 
Example 7
Source File: KeychainCertificateStore.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param certificates Chain of certificates
 * @return True if chain is trusted
 */
@Override
public boolean verify(final CertificateTrustCallback prompt, final String hostname, final List<X509Certificate> certificates) throws CertificateException {
    if(certificates.isEmpty()) {
        return false;
    }
    final SecPolicyRef policyRef = SecurityFunctions.library.SecPolicyCreateSSL(true, hostname);
    final PointerByReference reference = new PointerByReference();
    SecurityFunctions.library.SecTrustCreateWithCertificates(toDEREncodedCertificates(certificates), policyRef, reference);
    final SecTrustRef trustRef = new SecTrustRef(reference.getValue());
    final SecTrustResultType trustResultType = new SecTrustResultType();
    SecurityFunctions.library.SecTrustEvaluate(trustRef, trustResultType);
    FoundationKitFunctions.library.CFRelease(trustRef);
    FoundationKitFunctions.library.CFRelease(policyRef);
    switch(trustResultType.getValue()) {
        case SecTrustResultType.kSecTrustResultUnspecified:
            // Accepted by user keychain setting explicitly
        case SecTrustResultType.kSecTrustResultProceed:
            return true;
        default:
            if(log.isDebugEnabled()) {
                log.debug("Evaluated recoverable trust result failure " + trustResultType.getValue());
            }
            try {
                prompt.prompt(hostname, certificates);
                return true;
            }
            catch(ConnectionCanceledException e) {
                return false;
            }
    }
}
 
Example 8
Source File: STMobileFaceDetection.java    From Fatigue-Detection with MIT License 5 votes vote down vote up
public STMobileFaceDetection(Context context, int config) {
      PointerByReference handlerPointer = new PointerByReference();
mContext = context;
synchronized(this.getClass())
{
   copyModelIfNeed(DETECTION_MODEL_NAME);
}
String modulePath = getModelPath(DETECTION_MODEL_NAME);
  	int rst = STMobileApiBridge.FACESDK_INSTANCE.st_mobile_face_detection_create(modulePath, config, handlerPointer);
  	if(rst != ResultCode.ST_OK.getResultCode())
  	{
  		return;
  	}
  	detectHandle = handlerPointer.getValue();
  }
 
Example 9
Source File: Libimobiledevice.java    From blobsaver with GNU General Public License v3.0 5 votes vote down vote up
public static Pointer lockdowndClientFromConnectedDevice(boolean showErrorAlert) {
    PointerByReference device = new PointerByReference();
    throwIfNeeded(idevice_new(device, Pointer.NULL), showErrorAlert, ErrorCodeType.idevice_error_t);
    PointerByReference client = new PointerByReference();
    throwIfNeeded(lockdownd_client_new(device.getValue(), client, "blobsaver"), showErrorAlert, ErrorCodeType.lockdownd_error_t);
    if (lockdownd_pair(client.getValue(), Pointer.NULL) != 0) {
        // try again, and if it doesn't work, show an error to the user + throw an exception
        throwIfNeeded(lockdownd_pair(client.getValue(), Pointer.NULL), showErrorAlert, ErrorCodeType.lockdownd_error_t);
    }
    idevice_free(device.getValue());
    return client.getValue();
}
 
Example 10
Source File: PAM.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new authenticator.
 *
 * @param serviceName PAM service name. This corresponds to the service name that shows up
 *                    in the PAM configuration,
 */
public PAM(String serviceName) throws PAMException {
    pam_conv conv = new pam_conv(new PamCallback() {
        public int callback(int num_msg, Pointer msg, Pointer resp, Pointer _) {
            LOGGER.debug("pam_conv num_msg=" + num_msg);
            if (factors == null)
                return PAM_CONV_ERR;

            // allocates pam_response[num_msg]. the caller will free this
            Pointer m = libc.calloc(pam_response.SIZE, num_msg);
            resp.setPointer(0, m);

            for (int i = 0; i < factors.length; i++) {
                pam_message pm = new pam_message(msg.getPointer(POINTER_SIZE * i));
                LOGGER.debug(pm.msg_style + ":" + pm.msg);
                if (pm.msg_style == PAM_PROMPT_ECHO_OFF) {
                    pam_response r = new pam_response(m.share(pam_response.SIZE * i));
                    r.setResp(factors[i]);
                    r.write(); // write to (*resp)[i]
                }
            }

            return PAM_SUCCESS;
        }
    });

    PointerByReference phtr = new PointerByReference();
    check(libpam.pam_start(serviceName, null, conv, phtr), "pam_start failed");
    pht = new pam_handle_t(phtr.getValue());
}
 
Example 11
Source File: JnaUtils.java    From djl with Apache License 2.0 5 votes vote down vote up
public static Pointer createSparseNdArray(
        SparseFormat fmt,
        Device device,
        Shape shape,
        DataType dtype,
        DataType[] auxDTypes,
        Shape[] auxShapes,
        boolean delayedAlloc) {
    int[] shapeArray = Arrays.stream(shape.getShape()).mapToInt(Math::toIntExact).toArray();
    int deviceType = MxDeviceType.toDeviceType(device);
    int deviceId = (deviceType != 1) ? device.getDeviceId() : -1;
    int delay = delayedAlloc ? 1 : 0;
    PointerByReference ref = new PointerByReference();
    IntBuffer auxDTypesInt =
            IntBuffer.wrap(Arrays.stream(auxDTypes).mapToInt(DataType::ordinal).toArray());
    IntBuffer auxNDims =
            IntBuffer.wrap(Arrays.stream(auxShapes).mapToInt(Shape::dimension).toArray());
    int[] auxShapesInt = Arrays.stream(auxShapes).mapToInt(ele -> (int) ele.head()).toArray();
    checkCall(
            LIB.MXNDArrayCreateSparseEx(
                    fmt.getValue(),
                    shapeArray,
                    shapeArray.length,
                    deviceType,
                    deviceId,
                    delay,
                    dtype.ordinal(),
                    auxDTypes.length,
                    auxDTypesInt,
                    auxNDims,
                    auxShapesInt,
                    ref));
    return ref.getValue();
}
 
Example 12
Source File: JnaUtils.java    From djl with Apache License 2.0 5 votes vote down vote up
public static Pointer createNdArray(
        Device device, Shape shape, DataType dtype, int size, boolean delayedAlloc) {
    int deviceType = MxDeviceType.toDeviceType(device);
    int deviceId = (deviceType != 1) ? device.getDeviceId() : -1;
    int delay = delayedAlloc ? 1 : 0;

    PointerByReference ref = new PointerByReference();
    int[] shapeArray = Arrays.stream(shape.getShape()).mapToInt(Math::toIntExact).toArray();
    checkCall(
            LIB.MXNDArrayCreateEx(
                    shapeArray, size, deviceType, deviceId, delay, dtype.ordinal(), ref));

    return ref.getValue();
}
 
Example 13
Source File: JnaUtils.java    From djl with Apache License 2.0 4 votes vote down vote up
public static Pointer createSymbolFromFile(String path) {
    PointerByReference ref = new PointerByReference();
    checkCall(LIB.MXSymbolCreateFromFile(path, ref));
    return ref.getValue();
}
 
Example 14
Source File: JnaUtils.java    From djl with Apache License 2.0 4 votes vote down vote up
public static Pointer getSymbolInternals(Pointer symbol) {
    PointerByReference ref = new PointerByReference();
    checkCall(LIB.MXSymbolGetInternals(symbol, ref));
    return ref.getValue();
}
 
Example 15
Source File: JnaUtils.java    From djl with Apache License 2.0 4 votes vote down vote up
public static Pointer getSymbolOutput(Pointer symbol, int index) {
    PointerByReference ref = new PointerByReference();
    checkCall(LIB.MXSymbolGetOutput(symbol, index, ref));
    return ref.getValue();
}
 
Example 16
Source File: SecureStorageWindowsManager.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
public String getCredential(String host, String user)
{
  PointerByReference pCredential = new PointerByReference();
  String target = SecureStorageManager.convertTarget(host, user);

  try
  {
    boolean ret = false;
    synchronized (advapi32Lib)
    {
      ret =
          advapi32Lib.CredReadW(target, SecureStorageWindowsCredentialType.CRED_TYPE_GENERIC.getType(), 0, pCredential);
    }

    if (!ret)
    {
      logger.info(String.format("Failed to read target or could not find it in Windows Credential Manager. Error code = %d", Native.getLastError()));
      return null;
    }

    logger.debug("Found the token from Windows Credential Manager and now copying it");

    SecureStorageWindowsCredential cred = new SecureStorageWindowsCredential(pCredential.getValue());

    if (SecureStorageWindowsCredentialType.typeOf(cred.Type) != SecureStorageWindowsCredentialType.CRED_TYPE_GENERIC)
    {
      logger.info("Wrong type of credential. Expected: CRED_TYPE_GENERIC");
      return null;
    }

    if (cred.CredentialBlobSize == 0)
    {
      logger.info("Returned credential is empty");
      return null;
    }

    byte[] credBytes = cred.CredentialBlob.getByteArray(0, cred.CredentialBlobSize);
    String res = new String(credBytes, StandardCharsets.UTF_16LE);
    logger.debug("Successfully read the token. Will return it as String now");
    return res;
  }
  finally
  {
    if (pCredential.getValue() != null)
    {
      synchronized (advapi32Lib)
      {
        advapi32Lib.CredFree(pCredential.getValue());
      }
    }
  }
}
 
Example 17
Source File: UsbDevice.java    From Flashtool with GNU General Public License v3.0 4 votes vote down vote up
public void setConfiguration() throws Exception {
  PointerByReference configRef = new PointerByReference();
  int result = LibUsbLibrary.libUsb.libusb_get_config_descriptor(this.usb_device, 0, configRef);
  int retries=0;
 int maxretries=5;
 if (result <0) {
  while (retries<maxretries) {
	  try {
	  Thread.sleep(500);
	  } catch (Exception e) {};
	  result = LibUsbLibrary.libUsb.libusb_get_config_descriptor(this.usb_device, 0, configRef);
	  if (result==0) retries=maxretries;
	  retries++;
  }			  
 }
  UsbSystem.checkError("get_config", result);
  if (result<0) throw new Exception("setConfiguration error");
  libusb_config_descriptor cd = new libusb_config_descriptor(configRef.getValue());
  libusb_config_descriptor[] cdescs = cd.toArray(nbconfig);
  for (libusb_config_descriptor cdesc : cdescs) {
    this.confs.add(new UsbConfiguration(cdesc));
  }
  LibUsbLibrary.libUsb.libusb_free_config_descriptor(configRef.getValue());
  Iterator iconfs = getConfigurations().iterator();
  while (iconfs.hasNext()) {
	  UsbConfiguration c = (UsbConfiguration)iconfs.next();
	  Iterator ifaces = c.getInterfaces().iterator();
	  while (ifaces.hasNext()) {
		  UsbInterface iface = (UsbInterface)ifaces.next();
		  Iterator<UsbInterfaceDescriptor>ifdescs = iface.getInterfaceDescriptors().iterator();
		  while (ifdescs.hasNext()) {
			  UsbInterfaceDescriptor ifdesc = ifdescs.next();
			  Iterator endpoints = ifdesc.getEndpointDescriptors().iterator();
			  while (endpoints.hasNext()) {
				  UsbEndpointDescriptor endpoint = (UsbEndpointDescriptor)endpoints.next();
				  if (endpoint.isIn()) default_endpoint_in = endpoint.getEndpoint(); else
					  default_endpoint_out = endpoint.getEndpoint();
			  }
		  }
	  }
  }
}
 
Example 18
Source File: JnaUtils.java    From djl with Apache License 2.0 4 votes vote down vote up
public static Pointer getGradient(Pointer handle) {
    PointerByReference ref = new PointerByReference();
    checkNDArray(handle, "get the gradient for");
    checkCall(LIB.MXNDArrayGetGrad(handle, ref));
    return ref.getValue();
}
 
Example 19
Source File: ReedsSheppCarPlanner.java    From coordination_oru with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean doPlanning() {
	ArrayList<PoseSteering> finalPath = new ArrayList<PoseSteering>();  
	for (int i = 0; i < this.goal.length; i++) {
		Pose start_ = null;
		Pose goal_ = this.goal[i];
		if (i == 0) start_ = this.start;
		else start_ = this.goal[i-1];
		path = new PointerByReference();
		pathLength = new IntByReference();
		double[] xCoords = new double[collisionCircleCenters.length];
		double[] yCoords = new double[collisionCircleCenters.length];
		int numCoords = collisionCircleCenters.length;
		for (int j = 0; j < collisionCircleCenters.length; j++) {
			xCoords[j] = collisionCircleCenters[j].x;
			yCoords[j] = collisionCircleCenters[j].y;
		}
		metaCSPLogger.info("Path planning with " + collisionCircleCenters.length + " circle positions");
		if (this.om != null) {
			byte[] occ = om.asByteArray();
			int w = om.getPixelWidth();
			int h = om.getPixelHeight();
			double res = om.getResolution();				
			if (!INSTANCE.plan_multiple_circles(occ, w, h, res, robotRadius, xCoords, yCoords, numCoords, start_.getX(), start_.getY(), start_.getTheta(), goal_.getX(), goal_.getY(), goal_.getTheta(), path, pathLength, distanceBetweenPathPoints, turningRadius, planningTimeInSecs, algo.ordinal())) return false;
		}
		else {
			if (!INSTANCE.plan_multiple_circles_nomap(xCoords, yCoords, numCoords, start_.getX(), start_.getY(), start_.getTheta(), goal_.getX(), goal_.getY(), goal_.getTheta(), path, pathLength, distanceBetweenPathPoints, turningRadius, planningTimeInSecs, algo.ordinal())) return false;					
		}
		final Pointer pathVals = path.getValue();
		final PathPose valsRef = new PathPose(pathVals);
		valsRef.read();
		int numVals = pathLength.getValue();
		if (numVals == 0) return false;
		PathPose[] pathPoses = (PathPose[])valsRef.toArray(numVals);
		if (i == 0) finalPath.add(new PoseSteering(pathPoses[0].x, pathPoses[0].y, pathPoses[0].theta, 0.0));
		for (int j = 1; j < pathPoses.length; j++) finalPath.add(new PoseSteering(pathPoses[j].x, pathPoses[j].y, pathPoses[j].theta, 0.0));
		INSTANCE.cleanupPath(pathVals);
	}
	this.pathPS = finalPath.toArray(new PoseSteering[finalPath.size()]);
	return true;
}
 
Example 20
Source File: JnaUtils.java    From djl with Apache License 2.0 4 votes vote down vote up
public static Pointer autogradGetSymbol(NDArray array) {
    Pointer handle = ((MxNDArray) array).getHandle();
    PointerByReference out = new PointerByReference();
    checkCall(LIB.MXAutogradGetSymbol(handle, out));
    return out.getValue();
}