Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preview of contribution / More .ini APIs (nearly completes set of PrivateProfile API) #250

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
Next Release (4.0.1)
====================

Features
--------
* More win32 initialization file APIs - [@quipsy](https://github.com/quipsy).

Release 4.0
===========

Expand Down
61 changes: 61 additions & 0 deletions contrib/platform/src/com/sun/jna/platform/win32/Kernel32.java
Original file line number Diff line number Diff line change
Expand Up @@ -1940,4 +1940,65 @@ boolean Process32Next(HANDLE hSnapshot,
* </p>
*/
boolean WritePrivateProfileString(String lpAppName, String lpKeyName, String lpString, String lpFileName);

/**
* Retrieves all the keys and values for the specified section of an initialization file.
*
* <p>
* Each string has the following format: {@code key=string}.
* </p>
* <p>
* This operation is atomic; no updates to the specified initialization file are allowed while the key name and value pairs for the section are being copied
* to the buffer pointed to by the {@code lpReturnedString} parameter.
* </p>
*
* @param lpAppName
* The name of the section in the initialization file.
* @param lpReturnedString
* A buffer that receives the key name and value pairs associated with the named section. The buffer is filled with one or more {@code null}
* -terminated strings; the last string is followed by a second {@code null} character.
* @param nSize
* The size of the buffer pointed to by the {@code lpReturnedString} parameter, in characters. The maximum profile section size is 32,767
* characters.
* @param lpFileName
* The name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the
* Windows directory.
* @return The number of characters copied to the buffer, not including the terminating null character. If the buffer is not large enough to contain all the
* key name and value pairs associated with the named section, the return value is equal to {@code nSize} minus two.
*/
DWORD GetPrivateProfileSection(String lpAppName, char[] lpReturnedString, DWORD nSize, String lpFileName);

/**
* Retrieves the names of all sections in an initialization file.
* <p>
* This operation is atomic; no updates to the initialization file are allowed while the section names are being copied to the buffer.
* </p>
*
* @param lpszReturnBuffer
* A pointer to a buffer that receives the section names associated with the named file. The buffer is filled with one or more {@code null}
* -terminated strings; the last string is followed by a second {@code null} character.
* @param nSize
* size of the buffer pointed to by the {@code lpszReturnBuffer} parameter, in characters.
* @param lpFileName
* The name of the initialization file. If this parameter is {@code NULL}, the function searches the Win.ini file. If this parameter does not
* contain a full path to the file, the system searches for the file in the Windows directory.
* @return The return value specifies the number of characters copied to the specified buffer, not including the terminating {@code null} character. If the
* buffer is not large enough to contain all the section names associated with the specified initialization file, the return value is equal to the
* size specified by {@code nSize} minus two.
*/
DWORD GetPrivateProfileSectionNames(char[] lpszReturnBuffer, DWORD nSize, String lpFileName);

/**
* @param lpAppName
* The name of the section in which data is written. This section name is typically the name of the calling application.
* @param lpString
* The new key names and associated values that are to be written to the named section. This string is limited to 65,535 bytes. Must be filled
* with zero or many {@code null}-terminated strings of the form {@code key=value}, appended by an additional {@code null} byte to terminate the
* list.
* @param lpFileName
* The name of the initialization file. If this parameter does not contain a full path for the file, the function searches the Windows directory
* for the file. If the file does not exist and lpFileName does not contain a full path, the function creates the file in the Windows directory.
* @return If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.
*/
boolean WritePrivateProfileSection(String lpAppName, String lpString, String lpFileName);
}
62 changes: 62 additions & 0 deletions contrib/platform/src/com/sun/jna/platform/win32/Kernel32Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
*/
package com.sun.jna.platform.win32;

import static java.util.Arrays.asList;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
Expand Down Expand Up @@ -307,6 +309,66 @@ public static final void writePrivateProfileString(final String appName, final S
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}

/**
* Retrieves all the keys and values for the specified section of an initialization file.
*
* <p>
* Each string has the following format: {@code key=string}.
* </p>
* <p>
* This operation is atomic; no updates to the specified initialization file are allowed while this method is executed.
* </p>
*
* @param appName
* The name of the section in the initialization file.
* @param fileName
* The name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the
* Windows directory.
* @return The key name and value pairs associated with the named section.
*/
public static final List<String> getPrivateProfileSection(final String appName, final String fileName) {
final char buffer[] = new char[32768]; // Maximum section size according to MSDN (http://msdn.microsoft.com/en-us/library/windows/desktop/ms724348(v=vs.85).aspx)
if (Kernel32.INSTANCE.GetPrivateProfileSection(appName, buffer, new DWORD(buffer.length), fileName).intValue() == 0)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should rewrite this by making two calls, otherwise this has a hidden limitation of an upper 32K bound. Call it once to get the size, allocate the string and call it again.

MSDN says: the return value specifies the number of characters copied to the buffer, not including the terminating null character. If the buffer is not large enough to contain all the key name and value pairs associated with the named section, the return value is equal to nSize minus two.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no 'hidden' limitation. Actually the limitation is documented in MSDN (http://msdn.microsoft.com/en-us/library/windows/desktop/ms724348(v=vs.85).aspx): ...nSize [in]
The size of the buffer pointed to by the lpReturnedString parameter, in characters. The maximum profile section size is 32,767 characters...

Hence, the above function is perfectly well and nothing is "hidden". :-)

throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
return asList(Native.toStrings(buffer));
}

/**
* Retrieves the names of all sections in an initialization file.
* <p>
* This operation is atomic; no updates to the initialization file are allowed while this method is executed.
* </p>
*
* @param fileName
* The name of the initialization file. If this parameter is {@code NULL}, the function searches the Win.ini file. If this parameter does not
* contain a full path to the file, the system searches for the file in the Windows directory.
* @return the section names associated with the named file.
*/
public static final List<String> getPrivateProfileSectionNames(final String fileName) {
final char buffer[] = new char[65536]; // Maximum INI file size according to MSDN (http://support.microsoft.com/kb/78346)
if (Kernel32.INSTANCE.GetPrivateProfileSectionNames(buffer, new DWORD(buffer.length), fileName).intValue() == 0)
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
return asList(Native.toStrings(buffer));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As said above, your concerns are not correct. It is documented in MSDN that GetPrivateProfileSectionNames will never return more than 32767 bytes + NUL, so my code does not imply any other limitation than the operating system itself already has.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

EDIT: Actually it is not documented in MSDN but in the Microsoft Knowledge Base (http://support.microsoft.com/kb/78346/en). While that article says that even some Microsoft tools cannot handle files larger than 32K, I just expanded the buffer to 64K in my latest COMMIT to reflect the official size limit documented in that article. So JNA now can handle larger files than Windows itself! ;-) Also I added code comments so other authors can see where the numbers are taken from. :-)

}

/**
* @param appName
* The name of the section in which data is written. This section name is typically the name of the calling application.
* @param strings
* The new key names and associated values that are to be written to the named section. Each entry must be of the form {@code key=value}.
* @param fileName
* The name of the initialization file. If this parameter does not contain a full path for the file, the function searches the Windows directory
* for the file. If the file does not exist and lpFileName does not contain a full path, the function creates the file in the Windows directory.
*/
public static final void writePrivateProfileSection(final String appName, final List<String> strings, final String fileName) {
final StringBuilder buffer = new StringBuilder();
for (final String string : strings)
buffer.append(string).append('\0');
buffer.append('\0');
if (!(Kernel32.INSTANCE.WritePrivateProfileSection(appName, buffer.toString(), fileName)))
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}

/**
* Convenience method to get the processor information. Takes care of auto-growing the array.
*
Expand Down
102 changes: 102 additions & 0 deletions contrib/platform/test/com/sun/jna/platform/win32/Kernel32Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@
*/
package com.sun.jna.platform.win32;

import static com.sun.jna.platform.win32.RegexMatcher.matches;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
Expand All @@ -22,12 +29,15 @@
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.TimeZone;

import junit.framework.TestCase;

import org.junit.Test;

import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.NativeMappedConverter;
Expand Down Expand Up @@ -606,4 +616,96 @@ public final void testWritePrivateProfileString() throws IOException {
tmp.delete();
}
}

@Test
public final void testGetPrivateProfileSection() throws IOException {
// given
final File tmp = File.createTempFile(getName(), "ini");
tmp.deleteOnExit();
try {
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();
}

// when
final char[] buffer = new char[9];
final DWORD len = Kernel32.INSTANCE.GetPrivateProfileSection("X", buffer, new DWORD(buffer.length), tmp.getCanonicalPath());

// then
assertThat("Wrong length", len, is(new DWORD(7)));
assertThat("Wrong content", buffer, is(anyOf(equalTo("A=1\0B=X\0\0".toCharArray()), equalTo("B=X\0A=1\0\0".toCharArray()))));
} finally {
tmp.delete();
}
}

@Test
public final void testGetPrivateProfileSectionNames() throws IOException {
// given
final File tmp = File.createTempFile(getName(), "ini");
tmp.deleteOnExit();
try {
final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(tmp)));
try {
writer.println("[S1]");
writer.println("[S2]");
} finally {
writer.close();
}

// when
final char[] buffer = new char[7];
final DWORD len = Kernel32.INSTANCE.GetPrivateProfileSectionNames(buffer, new DWORD(buffer.length), tmp.getCanonicalPath());

// then
assertThat("Wrong length", len, is(new DWORD(5)));
assertThat("Wrong content", buffer, is(anyOf(equalTo("S1\0S2\0\0".toCharArray()), equalTo("S2\0S1\0\0".toCharArray()))));
} finally {
tmp.delete();
}
}

@SuppressWarnings("unchecked")
@Test
public final void testWritePrivateProfileSection() throws IOException {
// given
final File tmp = File.createTempFile(getName(), "ini");
tmp.deleteOnExit();
try {
final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(tmp)));
try {
writer.println("[S1]");
writer.println("A=1");
writer.println("B=X");
} finally {
writer.close();
}

// when
final boolean result = Kernel32.INSTANCE.WritePrivateProfileSection("S1", "A=3\0E=Z\0\0", tmp.getCanonicalPath());

// then
assertThat("Wrong result", result, is(true));
assertThat(readAllLines(tmp), hasItems(is("[S1]"), matches("A\\s*=\\s*3"), matches("E\\s*=\\s*Z")));
} finally {
tmp.delete();
}
}

private static final List<String> readAllLines(final File file) throws IOException {
final List<String> lines = new LinkedList<String>();
final BufferedReader reader = new BufferedReader(new FileReader(file));
try {
for (String line = reader.readLine(); line != null; line = reader.readLine())
lines.add(line);
} finally {
reader.close();
}
return lines;
}
}
Loading