-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathPmemkvExample.java
More file actions
79 lines (67 loc) · 2.21 KB
/
PmemkvExample.java
File metadata and controls
79 lines (67 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import io.pmem.pmemkv.Converter;
import io.pmem.pmemkv.Database;
import io.pmem.pmemkv.NotFoundException;
import java.nio.ByteBuffer;
/*
* Implementation of Converter interface to allow
* storing in the Database keys and values as Strings.
*/
class StringConverter implements Converter<String> {
public ByteBuffer toByteBuffer(String entry) {
return ByteBuffer.wrap(entry.getBytes());
}
public String fromByteBuffer(ByteBuffer entry) {
byte[] bytes;
bytes = new byte[entry.capacity()];
entry.get(bytes);
return new String(bytes);
}
}
public class PmemkvExample {
/*
* this is the main program, used this way:
* java PmemkvExample pmemfile -- print all the keys and values in the pmemfile
* java PmemkvExample pmemfile key -- lookup key and print the value
* java PmemkvExample pmemfile key value -- add a key/value pair to the pmemfile
*
* the pmemfile is created automatically if it doesn't already exist.
*/
public static void main(String[] args) {
int SIZE = 10 * 1024 * 1024; // 10 MiB
String ENGINE = "cmap";
if (args.length < 1 || args.length > 3) {
System.err.println("Usage: java PmemkvExample kvfile [key [value]]");
System.exit(1);
}
/*
* Configure and open Database, using Builder.
* Part of the configuration is given (as an example) as JSON Object.
* Note, it is required to define key and value converter (to/from ByteBuffer).
*/
Database<String, String> db = new Database.Builder<String, String>(ENGINE)
.fromJson("{\"path\":\"" + args[0] + "\", \"create_if_missing\":1}")
.setSize(SIZE)
.setKeyConverter(new StringConverter())
.setValueConverter(new StringConverter())
.build();
if (args.length == 1) {
// iterate through the key-value store, printing them
db.getAll((String k, String v) -> {
System.out.println(k + "=\"" + v + "\"");
});
} else if (args.length == 2) {
// lookup the given key and print the value
try {
db.get(args[1], (String v) -> {
System.out.println(args[1] + "=\"" + v + "\"");
});
} catch (NotFoundException e) {
System.out.println("Key '" + args[1] + "' wasn't found in DB");
}
} else {
// add the given key-value pair
db.put(args[1], args[2]);
}
db.stop();
}
}