Search in sources :

Example 16 with DWORD

use of com.sun.jna.platform.win32.WinDef.DWORD in project jna by java-native-access.

the class Advapi32Util method backupEncryptedFile.

/**
     * Backup an encrypted file or folder without decrypting it. A file named
     * "bar/sample.text" will be backed-up to "destDir/sample.text". A directory
     * named "bar" will be backed-up to "destDir/bar". This method is NOT
     * recursive. If you have an encrypted directory with encrypted files, this
     * method must be called once for the directory, and once for each encrypted
     * file to be backed-up.
     *
     * @param src
     *         The encrypted file or directory to backup.
     * @param destDir
     *         The directory where the backup will be saved.
     */
public static void backupEncryptedFile(File src, File destDir) {
    if (!destDir.isDirectory()) {
        throw new IllegalArgumentException("destDir must be a directory.");
    }
    // Open the file for export (backup)
    ULONG readFlag = new ULONG(0);
    // Import (restore) file
    ULONG writeFlag = new ULONG(CREATE_FOR_IMPORT);
    if (src.isDirectory()) {
        writeFlag.setValue(CREATE_FOR_IMPORT | CREATE_FOR_DIR);
    }
    // open encrypted file for export
    String srcFileName = src.getAbsolutePath();
    PointerByReference pvContext = new PointerByReference();
    if (Advapi32.INSTANCE.OpenEncryptedFileRaw(srcFileName, readFlag, pvContext) != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    // read encrypted file
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    FE_EXPORT_FUNC pfExportCallback = new FE_EXPORT_FUNC() {

        @Override
        public DWORD callback(Pointer pbData, Pointer pvCallbackContext, ULONG ulLength) {
            byte[] arr = pbData.getByteArray(0, ulLength.intValue());
            try {
                outputStream.write(arr);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return new DWORD(W32Errors.ERROR_SUCCESS);
        }
    };
    if (Advapi32.INSTANCE.ReadEncryptedFileRaw(pfExportCallback, null, pvContext.getValue()) != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    // close
    try {
        outputStream.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Advapi32.INSTANCE.CloseEncryptedFileRaw(pvContext.getValue());
    // open file for import
    String destFileName = destDir.getAbsolutePath() + File.separator + src.getName();
    pvContext = new PointerByReference();
    if (Advapi32.INSTANCE.OpenEncryptedFileRaw(destFileName, writeFlag, pvContext) != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    // write encrypted file
    final IntByReference elementsReadWrapper = new IntByReference(0);
    FE_IMPORT_FUNC pfImportCallback = new FE_IMPORT_FUNC() {

        @Override
        public DWORD callback(Pointer pbData, Pointer pvCallbackContext, ULONGByReference ulLength) {
            int elementsRead = elementsReadWrapper.getValue();
            int remainingElements = outputStream.size() - elementsRead;
            int length = Math.min(remainingElements, ulLength.getValue().intValue());
            pbData.write(0, outputStream.toByteArray(), elementsRead, length);
            elementsReadWrapper.setValue(elementsRead + length);
            ulLength.setValue(new ULONG(length));
            return new DWORD(W32Errors.ERROR_SUCCESS);
        }
    };
    if (Advapi32.INSTANCE.WriteEncryptedFileRaw(pfImportCallback, null, pvContext.getValue()) != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    // close
    Advapi32.INSTANCE.CloseEncryptedFileRaw(pvContext.getValue());
}
Also used : ULONG(com.sun.jna.platform.win32.WinDef.ULONG) IntByReference(com.sun.jna.ptr.IntByReference) DWORD(com.sun.jna.platform.win32.WinDef.DWORD) Pointer(com.sun.jna.Pointer) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ULONGByReference(com.sun.jna.platform.win32.WinDef.ULONGByReference) PointerByReference(com.sun.jna.ptr.PointerByReference) FE_EXPORT_FUNC(com.sun.jna.platform.win32.WinBase.FE_EXPORT_FUNC) FE_IMPORT_FUNC(com.sun.jna.platform.win32.WinBase.FE_IMPORT_FUNC)

Example 17 with DWORD

use of com.sun.jna.platform.win32.WinDef.DWORD in project jna by java-native-access.

the class Kernel32Test method testGetPrivateProfileSection.

public final void testGetPrivateProfileSection() throws IOException {
    final File tmp = File.createTempFile("testGetPrivateProfileSection", ".ini");
    tmp.deleteOnExit();
    final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(tmp)));
    try {
        writer.println("[X]");
        writer.println("A=1");
        writer.println("B=X");
    } finally {
        writer.close();
    }
    final char[] buffer = new char[9];
    final DWORD len = Kernel32.INSTANCE.GetPrivateProfileSection("X", buffer, new DWORD(buffer.length), tmp.getCanonicalPath());
    assertEquals(len.intValue(), 7);
    assertEquals(new String(buffer), "A=1\0B=X\0\0");
}
Also used : FileWriter(java.io.FileWriter) DWORD(com.sun.jna.platform.win32.WinDef.DWORD) File(java.io.File) PrintWriter(java.io.PrintWriter) BufferedWriter(java.io.BufferedWriter)

Example 18 with DWORD

use of com.sun.jna.platform.win32.WinDef.DWORD in project jna by java-native-access.

the class Kernel32Test method testFileTimeFromLargeInteger.

/**
     * Test FILETIME's LARGE_INTEGER constructor
     * @throws IOException
     */
public final void testFileTimeFromLargeInteger() throws IOException {
    File tmp = File.createTempFile("testGetFileInformationByHandleEx", "jna");
    tmp.deleteOnExit();
    HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_WRITE, WinNT.FILE_SHARE_WRITE, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null);
    assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile));
    try {
        Memory p = new Memory(FILE_BASIC_INFO.sizeOf());
        if (false == Kernel32.INSTANCE.GetFileInformationByHandleEx(hFile, WinBase.FileBasicInfo, p, new DWORD(p.size()))) {
            fail("GetFileInformationByHandleEx failed with " + Kernel32.INSTANCE.GetLastError());
        }
        FILE_BASIC_INFO fbi = new FILE_BASIC_INFO(p);
        FILETIME ft = new FILETIME(fbi.LastWriteTime);
        SYSTEMTIME stUTC = new SYSTEMTIME();
        SYSTEMTIME stLocal = new SYSTEMTIME();
        Kernel32.INSTANCE.FileTimeToSystemTime(ft, stUTC);
        // Covert to local
        Kernel32.INSTANCE.SystemTimeToTzSpecificLocalTime(null, stUTC, stLocal);
        FileTime calculatedCreateTime = FileTime.fromMillis(stLocal.toCalendar().getTimeInMillis());
        // Actual file's createTime
        FileTime createTime = Files.getLastModifiedTime(Paths.get(tmp.getAbsolutePath()));
        assertEquals(createTime.toMillis(), calculatedCreateTime.toMillis());
    } finally {
        Kernel32.INSTANCE.CloseHandle(hFile);
    }
}
Also used : FILETIME(com.sun.jna.platform.win32.WinBase.FILETIME) Memory(com.sun.jna.Memory) SYSTEMTIME(com.sun.jna.platform.win32.WinBase.SYSTEMTIME) DWORD(com.sun.jna.platform.win32.WinDef.DWORD) FileTime(java.nio.file.attribute.FileTime) File(java.io.File) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE) FILE_BASIC_INFO(com.sun.jna.platform.win32.WinBase.FILE_BASIC_INFO)

Example 19 with DWORD

use of com.sun.jna.platform.win32.WinDef.DWORD in project jna by java-native-access.

the class Kernel32Test method testSetCommTimeouts.

public void testSetCommTimeouts() {
    WinBase.COMMTIMEOUTS lpCommTimeouts = new WinBase.COMMTIMEOUTS();
    // Here we test a com port that definitely does not exist!
    HANDLE handleSerialPort = Kernel32.INSTANCE.CreateFile("\\\\.\\comDummy", WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, 0, null, WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null);
    int lastError = Kernel32.INSTANCE.GetLastError();
    assertEquals(lastError, WinNT.ERROR_FILE_NOT_FOUND);
    // try to store the com port timeouts using the invalid handle
    assertFalse(Kernel32.INSTANCE.SetCommTimeouts(handleSerialPort, lpCommTimeouts));
    // Check if we can open a connection to com port1
    // If yes, we try to store the com timeouts
    // If no com port exists we have to skip this test
    handleSerialPort = Kernel32.INSTANCE.CreateFile("\\\\.\\com1", WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, 0, null, WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null);
    lastError = Kernel32.INSTANCE.GetLastError();
    if (WinNT.NO_ERROR == lastError) {
        assertFalse(WinNT.INVALID_HANDLE_VALUE.equals(handleSerialPort));
        try {
            lpCommTimeouts = new WinBase.COMMTIMEOUTS();
            assertTrue(Kernel32.INSTANCE.GetCommTimeouts(handleSerialPort, lpCommTimeouts));
            DWORD oldReadIntervalTimeout = new DWORD(lpCommTimeouts.ReadIntervalTimeout.longValue());
            lpCommTimeouts.ReadIntervalTimeout = new DWORD(20);
            assertTrue(Kernel32.INSTANCE.SetCommTimeouts(handleSerialPort, lpCommTimeouts));
            WinBase.COMMTIMEOUTS lpNewCommTimeouts = new WinBase.COMMTIMEOUTS();
            assertTrue(Kernel32.INSTANCE.GetCommTimeouts(handleSerialPort, lpNewCommTimeouts));
            assertEquals(20, lpNewCommTimeouts.ReadIntervalTimeout.intValue());
            lpCommTimeouts.ReadIntervalTimeout = oldReadIntervalTimeout;
            assertTrue(Kernel32.INSTANCE.SetCommTimeouts(handleSerialPort, lpCommTimeouts));
        } finally {
            Kernel32Util.closeHandle(handleSerialPort);
        }
    }
}
Also used : DWORD(com.sun.jna.platform.win32.WinDef.DWORD) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE)

Example 20 with DWORD

use of com.sun.jna.platform.win32.WinDef.DWORD in project jna by java-native-access.

the class Kernel32Test method testSetFileAttributes.

public void testSetFileAttributes() throws IOException {
    File tmp = File.createTempFile("testSetFileAttributes", "jna");
    tmp.deleteOnExit();
    Kernel32.INSTANCE.SetFileAttributes(tmp.getCanonicalPath(), new DWORD(WinNT.FILE_ATTRIBUTE_HIDDEN));
    int attributes = Kernel32.INSTANCE.GetFileAttributes(tmp.getCanonicalPath());
    assertTrue((attributes & WinNT.FILE_ATTRIBUTE_HIDDEN) != 0);
}
Also used : DWORD(com.sun.jna.platform.win32.WinDef.DWORD) File(java.io.File)

Aggregations

DWORD (com.sun.jna.platform.win32.WinDef.DWORD)56 PointerByReference (com.sun.jna.ptr.PointerByReference)23 HANDLE (com.sun.jna.platform.win32.WinNT.HANDLE)17 File (java.io.File)17 HRESULT (com.sun.jna.platform.win32.WinNT.HRESULT)16 Test (org.junit.Test)15 DWORDByReference (com.sun.jna.platform.win32.WinDef.DWORDByReference)11 Memory (com.sun.jna.Memory)9 ULONG (com.sun.jna.platform.win32.WinDef.ULONG)9 ULONGByReference (com.sun.jna.platform.win32.WinDef.ULONGByReference)7 HANDLEByReference (com.sun.jna.platform.win32.WinNT.HANDLEByReference)7 GENERIC_MAPPING (com.sun.jna.platform.win32.WinNT.GENERIC_MAPPING)6 UINT_PTR (com.sun.jna.platform.win32.WinDef.UINT_PTR)5 TOKEN_PRIVILEGES (com.sun.jna.platform.win32.WinNT.TOKEN_PRIVILEGES)5 IntByReference (com.sun.jna.ptr.IntByReference)5 APPBARDATA (com.sun.jna.platform.win32.ShellAPI.APPBARDATA)4 WinNT (com.sun.jna.platform.win32.WinNT)4 Pointer (com.sun.jna.Pointer)3 SC_HANDLE (com.sun.jna.platform.win32.Winsvc.SC_HANDLE)3 BufferedWriter (java.io.BufferedWriter)3