Java Code Examples for com.sun.jna.Native#toString()

The following examples show how to use com.sun.jna.Native#toString() . 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: FileLogicDefault.java    From canon-sdk-java with MIT License 6 votes vote down vote up
protected File getDestinationOfDownloadFile(final EdsDirectoryItemInfo dirItemInfo, @Nullable final File folderDestination, @Nullable final String filename) {
    final String itemFilename = Native.toString(dirItemInfo.szFileName, DEFAULT_CHARSET.name());
    final String itemFileExtension = Files.getFileExtension(itemFilename);

    final File saveFolder = folderDestination == null ? SYSTEM_TEMP_DIR : folderDestination;
    final String saveFilename;
    if (StringUtils.isBlank(filename)) {
        saveFilename = itemFilename;
    } else {
        final String fileExtension = Files.getFileExtension(filename);
        if (StringUtils.isBlank(fileExtension)) {
            saveFilename = filename + "." + itemFileExtension;
        } else {
            if (fileExtension.equalsIgnoreCase(itemFileExtension)) {
                saveFilename = filename;
            } else {
                saveFilename = filename + "." + itemFileExtension;
            }
        }
    }

    saveFolder.mkdirs();
    return new File(saveFolder, saveFilename);
}
 
Example 2
Source File: Processes.java    From Java-Memory-Manipulation with Apache License 2.0 6 votes vote down vote up
public static Process byName(String name) {
	if (Platform.isWindows()) {
		Tlhelp32.PROCESSENTRY32.ByReference entry = new Tlhelp32.PROCESSENTRY32.ByReference();
		Pointer snapshot = Kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPALL.intValue(), 0);
		try {
			while (Kernel32.Process32NextW(snapshot, entry)) {
				String processName = Native.toString(entry.szExeFile);
				if (name.equals(processName)) {
					return byId(entry.th32ProcessID.intValue());
				}
			}
		} finally {
			Kernel32.CloseHandle(snapshot);
		}
	} else if (Platform.isMac() || Platform.isLinux()) {
		return byId(Utils.exec("bash", "-c", "ps -A | grep -m1 \"" + name + "\" | awk '{print $1}'"));
	} else {
		throw new UnsupportedOperationException("Unknown operating system! (" + System.getProperty("os.name") + ")");
	}
	throw new IllegalStateException("Process '" + name + "' was not found. Are you sure its running?");
}
 
Example 3
Source File: Processes.java    From Java-Memory-Manipulation with Apache License 2.0 6 votes vote down vote up
public static Process byName(String name) {
	if (Platform.isWindows()) {
		Tlhelp32.PROCESSENTRY32.ByReference entry = new Tlhelp32.PROCESSENTRY32.ByReference();
		Pointer snapshot = Kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPALL.intValue(), 0);
		try {
			while (Kernel32.Process32NextW(snapshot, entry)) {
				String processName = Native.toString(entry.szExeFile);
				if (name.equals(processName)) {
					return byId(entry.th32ProcessID.intValue());
				}
			}
		} finally {
			Kernel32.CloseHandle(snapshot);
		}
	} else if (Platform.isMac() || Platform.isLinux()) {
		return byId(Utils.exec("bash", "-c", "ps -A | grep -m1 \"" + name + "\" | awk '{print $1}'"));
	} else {
		throw new UnsupportedOperationException("Unknown operating system! (" + System.getProperty("os.name") + ")");
	}
	throw new IllegalStateException("Process '" + name + "' was not found. Are you sure its running?");
}
 
Example 4
Source File: KunpengScan.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
private String checkPlugins(){
    JSONObject cfg = new JSONObject();
    cfg.put("timeout",Integer.parseInt(getParam().getOrDefault("timeout","15").toString()));
    cfg.put("aider","http://"+identifier);
    cfg.put("extra_plugin_path", new File(JSONPlugin.jsonPath).getAbsolutePath());
    Kunpeng.INSTANCE.SetConfig(cfg.toString());
    JSONObject jsonObject = new JSONObject();
    if (getParam().containsKey("netloc"))
        jsonObject.put("netloc",getParam().getOrDefault("netloc",""));
    if (getParam().containsKey("target"))
        jsonObject.put("target",getParam().getOrDefault("target","web"));
    if (getParam().containsKey("type"))
        jsonObject.put("type",getParam().getOrDefault("type","web"));
    String check_json = jsonObject.toString();
    String checkResult = Kunpeng.INSTANCE.Check(check_json);
    if (CheckUtils.isJson(checkResult)){
        return StrUtils.formatJson(checkResult);
    }else{
        String s = Native.toString(Native.toByteArray(checkResult), "UTF-8");
        return StrUtils.formatJson(s);
    }
}
 
Example 5
Source File: KunpengScan.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
private void loadPlugins() {
    String result = Kunpeng.INSTANCE.GetPlugins();
    result = Native.toString(Native.toByteArray(result), "UTF-8");
    targets.clear();
    plugins.clear();
    JSONArray arr = toJSON(result);
    if (arr!=null && !arr.isEmpty()){
        for (int i = 0; i < arr.size(); i++) {
            JSONObject obj = arr.getJSONObject(i);
            String name = obj.getString("name");
            String remarks = obj.getString("remarks");
            String target = obj.getString("target");
            String type = obj.getString("type");

            Plugin plugin = new Plugin();
            plugin.setName(name);
            plugin.setRemarks(remarks);
            plugin.setTarget(target);
            plugin.setType(type);

            targets.add(target);
            plugins.add(plugin);

        }
    }
}
 
Example 6
Source File: LibCBackedProcessEnvironment.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public File getProcessDir() {
    byte[] out = new byte[LOTS_OF_CHARS];
    try {
        libc.getcwd(out, LOTS_OF_CHARS);
    } catch (LastErrorException lastErrorException) {
        throw new NativeIntegrationException(String.format("Could not get process working directory. errno: %d", lastErrorException.getErrorCode()));
    }
    return new File(Native.toString(out));
}
 
Example 7
Source File: ShowFilePathAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static String shortPath(String path) {
  if (path.contains("  ")) {
    // On the way from Runtime.exec() to CreateProcess(), a command line goes through couple rounds of merging and splitting
    // which breaks paths containing a sequence of two or more spaces.
    // Conversion to a short format is an ugly hack allowing to open such paths in Explorer.
    char[] result = new char[WinDef.MAX_PATH];
    if (Kernel32.INSTANCE.GetShortPathName(path, result, result.length) <= result.length) {
      return Native.toString(result);
    }
  }

  return path;
}
 
Example 8
Source File: HostnameFetching.java    From buck with Apache License 2.0 5 votes vote down vote up
private static String getHostnamePosix() throws IOException {
  byte[] hostnameBuf = new byte[HOSTNAME_MAX_LEN];
  try {
    // Subtract 1 to ensure NUL termination.
    HostnameFetchingPosixLibrary.gethostname(hostnameBuf, hostnameBuf.length - 1);
    return Native.toString(hostnameBuf);
  } catch (LastErrorException e) {
    throw new IOException(e);
  }
}
 
Example 9
Source File: WindowsUtilities.java    From libreveris with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String getModuleFilename ()
{
    final int MAX_SIZE = 512;
    byte[] exePathname = new byte[MAX_SIZE];
    Pointer zero = new Pointer(0);
    int result = Kernel32.INSTANCE.GetModuleFileNameA(
            zero,
            exePathname,
            MAX_SIZE);

    return Native.toString(exePathname);
}
 
Example 10
Source File: JsetupAPi.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public static String getDevicePath(HDEVINFO hDevInfo, SP_DEVINFO_DATA DeviceInfoData) {
	String devpath = "";
       SP_DEVICE_INTERFACE_DATA DeviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();
       DeviceInterfaceData.cbSize = DeviceInterfaceData.size();
       /* Query the device using the index to get the interface data */
       int index=0;
       do {
       	int result = setupapi.SetupDiEnumDeviceInterfaces(hDevInfo, DeviceInfoData, USBGuid,index, DeviceInterfaceData);
       	if (result == 0) {
       		break;        		
       	}
   		/* A successful query was made, use it to get the detailed data of the device */
   	    IntByReference reqlength = new IntByReference();
   	    /* Obtain the length of the detailed data structure, and then allocate space and retrieve it */
   	    result = setupapi.SetupDiGetDeviceInterfaceDetail(hDevInfo, DeviceInterfaceData, null, 0, reqlength, null);
   	    // Create SP_DEVICE_INTERFACE_DETAIL_DATA structure and set appropriate length for device Path */
   	    SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData      = new SP_DEVICE_INTERFACE_DETAIL_DATA(reqlength.getValue());
   	    result = setupapi.SetupDiGetDeviceInterfaceDetail(hDevInfo, DeviceInterfaceData, DeviceInterfaceDetailData, reqlength.getValue(), reqlength, null);
   	    devpath = Native.toString(DeviceInterfaceDetailData.devicePath);
   	    if (devpath.length()==0) {
       	    SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailDataDummy      = new SP_DEVICE_INTERFACE_DETAIL_DATA();
       	    DeviceInterfaceDetailData.cbSize=DeviceInterfaceDetailDataDummy.size();
       	    result = setupapi.SetupDiGetDeviceInterfaceDetail(hDevInfo, DeviceInterfaceData, DeviceInterfaceDetailData, reqlength.getValue(), reqlength, null);
       	    devpath = Native.toString(DeviceInterfaceDetailData.devicePath);
   	    }
           index++;
       } while (true);
       return devpath;
}
 
Example 11
Source File: Advapi32Util.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get a registry REG_EXPAND_SZ value.
 *
 * @param root Root key.
 * @param key Registry path.
 * @param value Name of the value to retrieve.
 * @return String value.
 */
public static String registryGetExpandableStringValue(HKEY root, String key, String value) {
    HKEYByReference phkKey = new HKEYByReference();
    int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ | WinNT.KEY_WOW64_32KEY, phkKey);
    if (rc != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(rc);
    }
    try {
        IntByReference lpcbData = new IntByReference();
        IntByReference lpType = new IntByReference();
        rc = Advapi32.INSTANCE.RegQueryValueEx(
                phkKey.getValue(), value, 0, lpType, (char[]) null, lpcbData);
        if (rc != W32Errors.ERROR_SUCCESS && rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
            throw new Win32Exception(rc);
        }
        if (lpType.getValue() != WinNT.REG_EXPAND_SZ) {
            throw new RuntimeException("Unexpected registry type " + lpType.getValue() + ", expected REG_SZ");
        }
        char[] data = new char[lpcbData.getValue()];
        rc = Advapi32.INSTANCE.RegQueryValueEx(
                phkKey.getValue(), value, 0, lpType, data, lpcbData);
        if (rc != W32Errors.ERROR_SUCCESS && rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
            throw new Win32Exception(rc);
        }
        return Native.toString(data);
    } finally {
        rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
        if (rc != W32Errors.ERROR_SUCCESS) {
            throw new Win32Exception(rc);
        }
    }
}
 
Example 12
Source File: Advapi32Util.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get a registry REG_SZ value.
 *
 * @param root Root key.
 * @param key Registry path.
 * @param value Name of the value to retrieve.
 * @return String value.
 */
public static String registryGetStringValue(HKEY root, String key, String value) {
    HKEYByReference phkKey = new HKEYByReference();
    int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ | WinNT.KEY_WOW64_32KEY, phkKey);
    if (rc != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(rc);
    }
    try {
        IntByReference lpcbData = new IntByReference();
        IntByReference lpType = new IntByReference();
        rc = Advapi32.INSTANCE.RegQueryValueEx(
                phkKey.getValue(), value, 0, lpType, (char[]) null, lpcbData);
        if (rc != W32Errors.ERROR_SUCCESS && rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
            throw new Win32Exception(rc);
        }
        if (lpType.getValue() != WinNT.REG_SZ) {
            throw new RuntimeException("Unexpected registry type " + lpType.getValue() + ", expected REG_SZ");
        }
        char[] data = new char[lpcbData.getValue()];
        rc = Advapi32.INSTANCE.RegQueryValueEx(
                phkKey.getValue(), value, 0, lpType, data, lpcbData);
        if (rc != W32Errors.ERROR_SUCCESS && rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
            throw new Win32Exception(rc);
        }
        return Native.toString(data);
    } finally {
        rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
        if (rc != W32Errors.ERROR_SUCCESS) {
            throw new Win32Exception(rc);
        }
    }
}
 
Example 13
Source File: CFString.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public String getString() {
  int lengthInChars = CFLibrary.INSTANCE.CFStringGetLength(this).intValue();
  NativeLong potentialLengthInBytes = new NativeLong(4 * lengthInChars + 1); // UTF8 fully escaped 16 bit chars, plus nul
 
  ByteBuffer buffer = ByteBuffer.allocate(potentialLengthInBytes.intValue());
  boolean ok = CFLibrary.INSTANCE.CFStringGetCString(this, buffer, potentialLengthInBytes, CFLibrary.kCFStringEncodingUTF8);
  if (!(ok))
    throw new RuntimeException("Could not convert string");
  Charset charset = Charset.forName("UTF-8");
  CharBuffer cbf = charset.decode(buffer);
  return Native.toString(cbf.array());
}
 
Example 14
Source File: LibCBackedProcessEnvironment.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public File getProcessDir() {
    byte[] out = new byte[LOTS_OF_CHARS];
    try {
        libc.getcwd(out, LOTS_OF_CHARS);
    } catch (LastErrorException lastErrorException) {
        throw new NativeIntegrationException(String.format("Could not get process working directory. errno: %d", lastErrorException.getErrorCode()));
    }
    return new File(Native.toString(out));
}
 
Example 15
Source File: BaseArgon2.java    From argon2-jvm with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String hashBytes(int iterations, int memory, int parallelism, byte[] pwd, byte[] salt) {
    final JnaUint32 jnaIterations = new JnaUint32(iterations);
    final JnaUint32 jnaMemory = new JnaUint32(memory);
    final JnaUint32 jnaParallelism = new JnaUint32(parallelism);

    int len = Argon2Library.INSTANCE.argon2_encodedlen(jnaIterations, jnaMemory, jnaParallelism,
            new JnaUint32(salt.length), new JnaUint32(defaultHashLength), getType().getJnaType()).intValue();
    final byte[] encoded = new byte[len];

    int result = callLibraryHash(pwd, salt, jnaIterations, jnaMemory, jnaParallelism, encoded);
    checkResult(result);

    return Native.toString(encoded, ASCII);
}
 
Example 16
Source File: HostnameUtilsUnix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the result of {@code gethostname()} function 
 * from the standard Unix/Linux C Library.
 * 
 * @return host name 
 * @throws NativeException if there was an error executing the
 *    system call.
 */
public static String cLibGetHostname() throws NativeException {
    byte[] buf = new byte[MAXHOSTNAMELEN];
    int retCode = CLib.INSTANCE.gethostname(buf, buf.length);
    
    if (retCode == 0) {
        return Native.toString(buf);
    }
    throw new NativeException(retCode, "error calling 'gethostname()' function");
}
 
Example 17
Source File: Windows.java    From Simplified-JNA with MIT License 4 votes vote down vote up
/**
 * @param hWnd
 * @return Title of a given process HWND.
 */
public static String getWindowTitle(HWND hWnd) {
	char[] buffer = new char[MAX_TITLE_LENGTH * 2];
	User32.INSTANCE.GetWindowText(hWnd, buffer, MAX_TITLE_LENGTH);
	return Native.toString(buffer);
}
 
Example 18
Source File: Advapi32Util.java    From jpexs-decompiler with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get a table of registry values.
 *
 * @param hKey Registry key.
 * @return Table of values.
 */
public static TreeMap<String, Object> registryGetValues(HKEY hKey) {
    IntByReference lpcValues = new IntByReference();
    IntByReference lpcMaxValueNameLen = new IntByReference();
    IntByReference lpcMaxValueLen = new IntByReference();
    int rc = Advapi32.INSTANCE.RegQueryInfoKey(hKey, null, null, null, null,
            null, null, lpcValues, lpcMaxValueNameLen, lpcMaxValueLen, null, null);
    if (rc != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(rc);
    }
    TreeMap<String, Object> keyValues = new TreeMap<>();
    char[] name = new char[lpcMaxValueNameLen.getValue() + 1];
    byte[] data = new byte[lpcMaxValueLen.getValue()];
    for (int i = 0; i < lpcValues.getValue(); i++) {
        IntByReference lpcchValueName = new IntByReference(lpcMaxValueNameLen.getValue() + 1);
        IntByReference lpcbData = new IntByReference(lpcMaxValueLen.getValue());
        IntByReference lpType = new IntByReference();
        rc = Advapi32.INSTANCE.RegEnumValue(hKey, i, name, lpcchValueName, null,
                lpType, data, lpcbData);
        if (rc != W32Errors.ERROR_SUCCESS) {
            throw new Win32Exception(rc);
        }

        String nameString = Native.toString(name);

        Memory byteData = new Memory(lpcbData.getValue());
        byteData.write(0, data, 0, lpcbData.getValue());

        switch (lpType.getValue()) {
            case WinNT.REG_DWORD: {
                keyValues.put(nameString, byteData.getInt(0));
                break;
            }
            case WinNT.REG_SZ:
            case WinNT.REG_EXPAND_SZ: {
                keyValues.put(nameString, byteData.getString(0, true));
                break;
            }
            case WinNT.REG_BINARY: {
                keyValues.put(nameString, byteData.getByteArray(0, lpcbData.getValue()));
                break;
            }
            case WinNT.REG_MULTI_SZ: {
                Memory stringData = new Memory(lpcbData.getValue());
                stringData.write(0, data, 0, lpcbData.getValue());
                ArrayList<String> result = new ArrayList<>();
                int offset = 0;
                while (offset < stringData.size()) {
                    String s = stringData.getString(offset, true);
                    offset += s.length() * Native.WCHAR_SIZE;
                    offset += Native.WCHAR_SIZE;
                    result.add(s);
                }
                keyValues.put(nameString, result.toArray(new String[result.size()]));
                break;
            }
            default:
                throw new RuntimeException("Unsupported type: " + lpType.getValue());
        }
    }
    return keyValues;
}
 
Example 19
Source File: HostnameUtilsWin.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the local host name.
 * 
 * <p>
 * The underlying Windows function may return a simple host name (e.g.
 * {@code chicago}) or it may return a fully qualified host name (e.g.
 * {@code chicago.us.internal.net}). The {@code noQualify} parameter can
 * remove the domain part if it exists.
 *
 * <p>
 * Note that the underlying Windows function will do a name service lookup
 * and the method is therefore potentially blocking, although it is more
 * than likely that Windows has cached this result in the DNS Client Cache
 * and therefore the result will be returned very fast.
 *
 * <p>
 * Windows API equivalent: {@code gethostname()} function from 
 * {@code Ws2_32} library.
 * 
 * @param noQualify if {@code true} the result is never qualified with domain,
 *   if {@code false} the result is <i>potentially</i> a fully qualified
 *   host name.
 * 
 * @return host name
 * @throws NativeException if there was an error executing the
 *    system call.
 */
public static String getHostName(boolean noQualify) throws NativeException {
    
    byte[] buf = new byte[256];
    
    int returnCode = Winsock2Lib.INSTANCE.gethostname(buf, buf.length);
    if (returnCode == 0) {
        String result = Native.toString(buf);
        if (noQualify) {
            return IpAddressUtils.removeDomain(result);
        } else {
            return result;
        }
    } else {
        throw new NativeException(returnCode, "error calling 'gethostname()' function");
    }
}
 
Example 20
Source File: LinuxNotifier.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private String getString(int maxLen) {
    if (maxLen < 1) return null; // no name field
    byte[] temp = new byte[maxLen];
    buff.get(temp);
    return Native.toString(temp);
}