Java 类com.sun.jna.platform.win32.Kernel32Util 实例源码

项目:IO    文件:DeviceManager.java   
private long getDiskSize(Disk disk) {
    long result = -1l;
    Kernel32 kernel32 = Kernel32.INSTANCE;
    HANDLE diskHandle = kernel32.CreateFile(disk.path, WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, null,
            WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null);
    if (WinBase.INVALID_HANDLE_VALUE.equals(diskHandle)) {
        return result;
    }
    try {
        Memory output = new Memory(Native.getNativeSize(LARGE_INTEGER.class));
        IntByReference lpBytes = new IntByReference();
        boolean success = kernel32.DeviceIoControl(diskHandle,
                WinioctlUtil.CTL_CODE(Winioctl.FILE_DEVICE_DISK, 0x17, Winioctl.METHOD_BUFFERED,
                        Winioctl.FILE_READ_ACCESS),
                null, 0, output, Native.getNativeSize(LARGE_INTEGER.class), lpBytes, null);
        // TODO: Check success?
        result = output.getLong(0);
    }
    finally {
        Kernel32Util.closeHandle(diskHandle);
    }
    return result;
}
项目:gethostname4j    文件:Hostname.java   
/**
 * @return the hostname the of the current machine
 */
public static String getHostname() {
    if (Platform.isWindows()) {
        return Kernel32Util.getComputerName();
    } else {
        // For now, we'll consider anyhting other than Windows to be unix-ish enough to have gethostname
        // TODO - Consider http://stackoverflow.com/a/10543006 as a possibly better MacOS option

        byte[] hostnameBuffer = new byte[4097];
        // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html suggests
        // the actual limit would be 255.

        int result = UnixCLibrary.INSTANCE.gethostname(hostnameBuffer, hostnameBuffer.length);
        if (result != 0) {
            throw new RuntimeException("gethostname call failed");
        }

        return Native.toString(hostnameBuffer);
    }
}
项目:Clipcon-Client    文件:Elevator.java   
public static void executeAsAdmin(String command, String args) {
    SHELLEXECUTEINFO execInfo = new SHELLEXECUTEINFO();
    execInfo.lpFile = new WString(command);
    if (args != null) {
        execInfo.lpParameters = new WString(args);
    }
    execInfo.nShow = Shell32X.SW_SHOWDEFAULT;
    execInfo.fMask = Shell32X.SEE_MASK_NOCLOSEPROCESS;
    execInfo.lpVerb = new WString("runas");
    boolean result = Shell32X.INSTANCE.ShellExecuteEx(execInfo);

    if (!result) {
        int lastError = Kernel32.INSTANCE.GetLastError();
        String errorMessage = Kernel32Util.formatMessageFromLastErrorCode(lastError);
        throw new RuntimeException("Error performing elevation: " + lastError + ": " + errorMessage + " (apperror=" + execInfo.hInstApp + ")");
    }
}
项目:yajsw    文件:FileUtils.java   
public static long freeSpace(File file)
{
    if (!file.isDirectory() || !file.exists())
        return -2;

    WinNT.LARGE_INTEGER.ByReference lpTotalNumberOfFreeBytes = new WinNT.LARGE_INTEGER.ByReference();
    lpTotalNumberOfFreeBytes.clear();

    boolean ret = Kernel32.INSTANCE.GetDiskFreeSpaceEx(file.getPath(),
            null, null, lpTotalNumberOfFreeBytes);
    if (ret)
        return lpTotalNumberOfFreeBytes.getValue();
    else
    {
        String s = Kernel32Util
                .formatMessageFromLastErrorCode(Kernel32.INSTANCE
                        .GetLastError());
        log.severe("error in File.freeSpace getting for \""
                + file.getPath() + "\" " + s);
    }

    return -1;
}
项目:yajsw    文件:FileUtils.java   
public static long totalSpace(File file)
{
    if (!file.isDirectory() || !file.exists())
        return -2;

    WinNT.LARGE_INTEGER.ByReference lpTotalNumberOfBytes = new WinNT.LARGE_INTEGER.ByReference();
    lpTotalNumberOfBytes.clear();

    boolean ret = Kernel32.INSTANCE.GetDiskFreeSpaceEx(file.getPath(),
            null, lpTotalNumberOfBytes, null);
    if (ret)
        return lpTotalNumberOfBytes.getValue();
    else
    {
        String s = Kernel32Util
                .formatMessageFromLastErrorCode(Kernel32.INSTANCE
                        .GetLastError());
        log.severe("error in File.totalSpace getting for \""
                + file.getPath() + "\" " + s);
    }

    return -1;

}
项目:yajsw    文件:Win32Service.java   
/**
 * Initialize the service, connect to the ServiceControlManager.
 */
public void init()
{
    Advapi32 advapi32;
    // Advapi32.SERVICE_TABLE_ENTRY[] entries = new
    // Advapi32.SERVICE_TABLE_ENTRY[2];
    Advapi32.SERVICE_TABLE_ENTRY entry;

    serviceMain = new ServiceMain();
    advapi32 = Advapi32.INSTANCE;
    entry = new Advapi32.SERVICE_TABLE_ENTRY();
    entry.size();
    entry.lpServiceName = serviceName;
    entry.lpServiceProc = serviceMain;
    entry.write();

    if (!advapi32.StartServiceCtrlDispatcher(entry.toArray(2)))
    {
        log("error in StartServiceCtrlDispatcher", 0);
        int err = Native.getLastError();
        lastWinError = err;
        log(err + ":" + Kernel32Util.formatMessageFromLastErrorCode(err), 0);
    }
}
项目:Chronicle-Map    文件:WindowsMsync.java   
public static void msync(RandomAccessFile raf, long addr, long length)
        throws IOException {
    int retry = 0;
    boolean success;
    int lastError = 0;
    // FlushViewOfFile can fail with ERROR_LOCK_VIOLATION if the memory system is writing dirty
    // pages to disk. As there is no way to synchronize the flushing then we retry a limited
    // number of times.
    do {
        success = KERNEL_32.FlushViewOfFile(new Pointer(addr), new SIZE_T(length));
        if (success || (lastError = KERNEL_32.GetLastError()) != ERROR_LOCK_VIOLATION)
            break;
        retry++;
    } while (retry < 3);

    if (success) {
        // Finally calls FlushFileBuffers
        raf.getChannel().force(false);
    } else {
        throw new IOException(Kernel32Util.formatMessageFromLastErrorCode(lastError));
    }
}
项目:BEAST    文件:Win32Process.java   
/**
 * creates a new Win32 Process given a process id
 * @param pid the process id that describes this process
 * @throws IOException if something goes wrong with creating the process reference
 */
public Win32Process(int pid) throws IOException
{
    handle = Kernel32.INSTANCE.OpenProcess(
            0x0400 | /* PROCESS_QUERY_INFORMATION */
            0x0800 | /* PROCESS_SUSPEND_RESUME */
            0x0001 | /* PROCESS_TERMINATE */
            0x00100000 /* SYNCHRONIZE */,
            false,
            pid);
    if (handle == null) 
        throw new IOException("OpenProcess failed: " 
    + Kernel32Util.formatMessageFromLastErrorCode(Kernel32.INSTANCE.GetLastError()));
    this.pid = pid;
}
项目:yajsw    文件:WindowsXPProcess.java   
public boolean startElevated()
{

    String file = getCmdFile();
    if (file == null)
    {
        log("startElevated: Error: error in command");
        return false;
    }
    String parameters = getCmdParameters();
    if (_debug)
        log("elevated exec: " + file + " " + parameters);

    SHELLEXECUTEINFO lpExecInfo = new SHELLEXECUTEINFO();
    lpExecInfo.fMask = Shell32.SEE_MASK_NOCLOSEPROCESS;
    lpExecInfo.hwnd = null;
    lpExecInfo.lpFile = file;
    lpExecInfo.lpVerb = Shell32.VERB_RUNAS;
    lpExecInfo.nShow = Shell32.SW_SHOWMAXIMIZED;
    lpExecInfo.lpParameters = parameters;
    lpExecInfo.cbSize = lpExecInfo.size();

    boolean result = Shell32.INSTANCE.ShellExecuteEx(lpExecInfo);
    if (!result)
    {
        int err = Native.getLastError();
        System.out.println("Error: " + err + " "
                + Kernel32Util.formatMessageFromLastErrorCode(err));
    }
    else
    {
        _pid = MyKernel32.INSTANCE.GetProcessId(lpExecInfo.hProcess);
        _processInformation = new PROCESS_INFORMATION();
        _processInformation.dwProcessId = _pid;
        _processInformation.hProcess = lpExecInfo.hProcess;

    }
    return result;
}
项目:yajsw    文件:WindowsXPProcess.java   
public void reboot()
{
    setShutdownPrivileges();
    if (!MyUser32.INSTANCE.ExitWindowsEx(new UINT(MyUser32.INSTANCE.EWX_REBOOT + MyUser32.INSTANCE.EWX_FORCE), new DWORD(MyUser32.INSTANCE.SHTDN_REASON_FLAG_PLANNED)).booleanValue())
    {
        int err = MyKernel32.INSTANCE.GetLastError();
        System.out.println("error executing reboot "+err+ " "+Kernel32Util.formatMessageFromLastErrorCode(err));
    }
}
项目:winthing    文件:SystemService.java   
public void shutdown() throws SystemException {
    final boolean success = advapi32.InitiateSystemShutdown(
        null,
        null,
        new WinDef.DWORD(0),
        true,
        false
    );
    if (!success) {
        throw new SystemException(Kernel32Util.formatMessage(kernel32.GetLastError()));
    }
}
项目:winthing    文件:SystemService.java   
public void reboot() throws SystemException {
    final boolean success = advapi32.InitiateSystemShutdown(
        null,
        null,
        new WinDef.DWORD(0),
        true,
        true
    );
    if (!success) {
        throw new SystemException(Kernel32Util.formatMessage(kernel32.GetLastError()));
    }
}
项目:winthing    文件:SystemService.java   
public void suspend() throws SystemException {
    final boolean success = kernel32.SetSystemPowerState(
        true,
        false
    );
    if (!success) {
        throw new SystemException(Kernel32Util.formatMessage(kernel32.GetLastError()));
    }
}
项目:winthing    文件:SystemService.java   
public void hibernate() throws SystemException {
    final boolean success = kernel32.SetSystemPowerState(
            false,
            false
        );
    if (!success) {
        throw new SystemException(Kernel32Util.formatMessage(kernel32.GetLastError()));
    }
}
项目:sheepit-client    文件:WinProcess.java   
public WinProcess(int pid_) throws IOException {
    this();
    this.handle = Kernel32.INSTANCE.OpenProcess(0x0400 | // PROCESS_QUERY_INFORMATION
            0x0800 | // PROCESS_SUSPEND_RESUME
            0x0001 | // PROCESS_TERMINATE
            0x0200 | // PROCESS_SET_INFORMATION
            0x00100000, // SYNCHRONIZE
            false, pid_);
    if (this.handle == null) {
        throw new IOException("OpenProcess failed: " + Kernel32Util.formatMessageFromLastErrorCode(Kernel32.INSTANCE.GetLastError()) + " (pid: " + pid_ + ")");
    }
    this.pid = pid_;
}
项目:yajsw    文件:WindowsXPProcess.java   
public void waitFor(long timeout)
{
    if (_debug)
        log("waitFor " + timeout);
    try
    {
        if (!isRunning())
            return;
        if (_debug)
            log("1waitFor ");
        if (timeout > Integer.MAX_VALUE)
            timeout = Integer.MAX_VALUE;
        if (_processInformation == null)
            return;
        long start = System.currentTimeMillis();
        if (_debug)
            log("2waitFor ");
        while (_processInformation != null
                && (timeout == -1 || (start + timeout) > System
                        .currentTimeMillis()) && isRunning())
        {
            if (_debug)
                log("WaitForSingleObject +");
            int result = MyKernel32.INSTANCE.WaitForSingleObject(
                    _processInformation.hProcess, (int) timeout);
            if (_debug)
                log("WaitForSingleObject -");
            if (_debug)
                log("WaitForSingleObject terminated PID: " + getPid());
            if (result == MyKernel32.WAIT_FAILED)
            {
                int errNr = MyKernel32.INSTANCE.GetLastError();
                log("Error in Process.waitFor OS Error #"
                        + errNr
                        + " "
                        + Kernel32Util
                                .formatMessageFromLastErrorCode(errNr));
            }
            else if (result != MyKernel32.WAIT_OBJECT_0)
            {
                log("Error in Process.waitFor OS result #"
                        + result
                        + " "
                        + Kernel32Util
                                .formatMessageFromLastErrorCode(result));
            }
        }
    }
    catch (Throwable ex)
    {
        log("Exception in Process.waitFor: " + ex);
    }

}
项目:jdivert    文件:WinDivertException.java   
public WinDivertException(int code) {
    this(code, Kernel32Util.formatMessage(code));
}
项目:Flashtool    文件:JKernel32.java   
public static String getLastError() {
    return Kernel32Util.getLastErrorMessage();
}
项目:proactive-component-monitoring    文件:WindowsProcess.java   
/**
 * returns an IOException exception  with a Java-style error report from native implementation.
 * 
 * @param functionName The name of the native function the call has failed.
 */
private static IOException win32ErrorIOException(final String functionName) {
    final int err = Kernel32.INSTANCE.GetLastError();
    final String mess = Kernel32Util.formatMessageFromLastErrorCode(err);
    return new IOException(functionName + " error=" + err + ", " + mess);
}
项目:incubator-netbeans    文件:HostnameUtilsWin.java   
/**
 * Gets the computer name.
 * 
 * <p>This is the also known as the NetBIOS name, although NetBIOS is 
 * hardly used anymore. It is the same value as can be seen from the
 * {@code COMPUTERNAME} environment variable.
 * 
 * <p>
 * Windows API equivalent: {@code GetComputerName()} function from 
 * {@code Kernel32} library.
 * 
 * @return computer name
 * @throws NativeException if there was an error executing the
 *    system call.
 */
public static String getComputerName() throws NativeException {
    try {
        return Kernel32Util.getComputerName();
    } catch (Win32Exception ex) {
        LOGGER.log(Level.FINE, "Kernel32.GetComputerName error : {0}", ex.getHR().intValue());
        String env = System.getenv("COMPUTERNAME");
        if (env != null) {
            return env;
        }
        throw new NativeException(ex.getHR().intValue(), "error calling 'GetComputerName()' function");
    }
}