Java examples to match similarly named examples from C.

These allow a Java version of documentation to show real example fragments.
refs #1130.
This commit is contained in:
Don Anderson
2014-10-06 13:35:50 -04:00
parent 098d1452e1
commit b00bec1480
9 changed files with 2897 additions and 0 deletions

View File

@@ -32,24 +32,45 @@ import com.wiredtiger.db.*;
public class ex_access {
public static void main(String[] args) {
/*! [access example connection] */
Connection conn;
Session s;
Cursor c;
try {
conn = wiredtiger.open("WT_HOME", "create");
s = conn.open_session(null);
} catch (WiredTigerException wte) {
System.err.println("WiredTigerException: " + wte);
return;
}
/*! [access example connection] */
try {
/*! [access example table create] */
s.create("table:t", "key_format=S,value_format=u");
/*! [access example table create] */
/*! [access example cursor open] */
c = s.open_cursor("table:t", null, null);
/*! [access example cursor open] */
} catch (WiredTigerException wte) {
System.err.println("WiredTigerException: " + wte);
return;
}
System.out.println("Key format: " + c.getKeyFormat());
System.out.println("Value format: " + c.getValueFormat());
/*! [access example cursor insert] */
try {
c.putKeyString("foo");
c.putValueByteArray("bar".getBytes());
c.insert();
} catch (WiredTigerPackingException wtpe) {
System.err.println("WiredTigerPackingException: " + wtpe);
} catch (WiredTigerException wte) {
System.err.println("WiredTigerException: " + wte);
}
/*! [access example cursor insert] */
/*! [access example cursor list] */
try {
c.reset();
while (c.next() == 0) {
System.out.println("Got: " + c.getKeyString());
@@ -59,10 +80,14 @@ public class ex_access {
} catch (WiredTigerException wte) {
System.err.println("WiredTigerException: " + wte);
}
/*! [access example cursor list] */
/*! [access example close] */
try {
conn.close(null);
} catch (WiredTigerException wte) {
System.err.println("WiredTigerException: " + wte);
}
/*! [access example close] */
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,222 @@
/*-
* Public Domain 2008-2014 WiredTiger, Inc.
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* ex_async.java
* demonstrates how to use the asynchronous API.
*/
package com.wiredtiger.examples;
import com.wiredtiger.db.*;
import java.io.*;
import java.util.*;
/*! [async example callback implementation] */
class AsyncKeys implements AsyncCallback {
public int numKeys = 0;
public AsyncKeys() {}
public void notifyError(String desc) {
System.err.println("ERROR: notify: " + desc);
}
public int notify(AsyncOp op, int opReturn, int flags) {
/*
* Note: we are careful not to throw any errors here. Any
* exceptions would be swallowed by a native worker thread.
*/
int ret = 0;
try {
/*! [async get type] */
/* Retrieve the operation's type. */
AsyncOpType optype = op.getType();
/*! [async get type] */
/*! [async get identifier] */
/* Retrieve the operation's 64-bit identifier. */
long id = op.getId();
/*! [async get identifier] */
if (optype == AsyncOpType.WT_AOP_SEARCH) {
/*! [async get the operation's string key] */
String key = op.getKeyString();
/*! [async get the operation's string key] */
/*! [async get the operation's string value] */
String value = op.getValueString();
/*! [async get the operation's string value] */
synchronized (this) {
numKeys += 1;
}
System.out.println("Id " + id + " got record: " + key +
" : " + value);
}
else {
notifyError("unexpected optype");
ret = 1;
}
}
catch (Exception e) {
System.err.println("ERROR: exception in notify: " + e.toString() +
", opreturn=" + opReturn);
ret = 1;
}
return (ret);
}
}
/*! [async example callback implementation] */
public class ex_async {
public static String home;
public static final int MAX_KEYS = 15;
public static AsyncOp tryAsyncNewOp(Connection conn, String uri,
String config, AsyncCallback cb) throws WiredTigerException
{
WiredTigerException savedwte = null;
for (int tries = 0; tries < 10; tries++)
try {
return conn.async_new_op(uri, config, cb);
}
catch (WiredTigerException wte) {
/*
* If we used up all the handles, pause and retry to
* give the workers a chance to catch up.
*/
System.err.println(
"asynchronous operation handle not available: " + wte);
savedwte = wte;
try {
Thread.sleep(1);
} catch (InterruptedException ie) {
/* not a big problem, continue to retry */
}
}
throw savedwte;
}
public static int
asyncExample()
throws WiredTigerException
{
AsyncOp op;
Connection conn;
Session session;
int i, ret;
String k[] = new String[MAX_KEYS];
String v[] = new String[MAX_KEYS];
/*! [async example callback implementation part 2] */
AsyncKeys asynciface = new AsyncKeys();
/*! [async example callback implementation part 2] */
/*! [async example connection] */
conn = wiredtiger.open(home, "create,cache_size=100MB," +
"async=(enabled=true,ops_max=20,threads=2)");
/*! [async example connection] */
/*! [async example table create] */
session = conn.open_session(null);
ret = session.create("table:async", "key_format=S,value_format=S");
/*! [async example table create] */
/* Insert a set of keys asynchronously. */
for (i = 0; i < MAX_KEYS; i++) {
/*! [async handle allocation] */
op = tryAsyncNewOp(conn, "table:async", null, asynciface);
/*! [async handle allocation] */
/*! [async insert] */
/*
* Set the operation's string key and value, and then do
* an asynchronous insert.
*/
/*! [async set the operation's string key] */
k[i] = "key" + i;
op.putKeyString(k[i]);
/*! [async set the operation's string key] */
/*! [async set the operation's string value] */
v[i] = "value" + i;
op.putValueString(v[i]);
/*! [async set the operation's string value] */
ret = op.insert();
/*! [async insert] */
}
/*! [async flush] */
/* Wait for all outstanding operations to complete. */
ret = conn.async_flush();
/*! [async flush] */
/*! [async compaction] */
/*
* Compact a table asynchronously, limiting the run-time to 5 minutes.
*/
op = tryAsyncNewOp(conn, "table:async", "timeout=300", asynciface);
ret = op.compact();
/*! [async compaction] */
/* Search for the keys we just inserted, asynchronously. */
for (i = 0; i < MAX_KEYS; i++) {
op = tryAsyncNewOp(conn, "table:async", null, asynciface);
/*! [async search] */
/*
* Set the operation's string key and value, and then do
* an asynchronous search.
*/
k[i] = "key" + i;
op.putKeyString(k[i]);
ret = op.search();
/*! [async search] */
}
/*
* Connection close automatically does an async_flush so it will wait
* for all queued search operations to complete.
*/
ret = conn.close(null);
System.out.println("Searched for " + asynciface.numKeys + " keys");
return (ret);
}
public static int
main(String[] argv)
{
try {
return (asyncExample());
}
catch (WiredTigerException wte) {
System.err.println("Exception: " + wte);
return (-1);
}
}
}

View File

@@ -0,0 +1,299 @@
/*-
* Public Domain 2008-2014 WiredTiger, Inc.
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* ex_call_center.java
* This is an example application that demonstrates how to map a
* moderately complex SQL application into WiredTiger.
*/
package com.wiredtiger.examples;
import com.wiredtiger.db.*;
import java.io.*;
import java.util.*;
/*! [call-center decl] */
/*
* In SQL, the tables are described as follows:
*
* CREATE TABLE Customers(id INTEGER PRIMARY KEY,
* name VARCHAR(30), address VARCHAR(50), phone VARCHAR(15))
* CREATE INDEX CustomersPhone ON Customers(phone)
*
* CREATE TABLE Calls(id INTEGER PRIMARY KEY, call_date DATE,
* cust_id INTEGER, emp_id INTEGER, call_type VARCHAR(12),
* notes VARCHAR(25))
* CREATE INDEX CallsCustDate ON Calls(cust_id, call_date)
*
* In this example, both tables will use record numbers for their IDs, which
* will be the key. The C structs for the records are as follows.
*/
/* Customer records. */
class Customer {
public long id;
public String name;
public String address;
public String phone;
public Customer(long id, String name, String address, String phone) {
this.id = id;
this.name = name;
this.address = address;
this.phone = phone;
}
public Customer() {}
}
/* Call records. */
class Call {
public long id;
public long call_date;
public long cust_id;
public long emp_id;
public String call_type;
public String notes;
public Call(long id, long call_date, long cust_id, long emp_id,
String call_type, String notes) {
this.id = id;
this.call_date = call_date;
this.cust_id = cust_id;
this.emp_id = emp_id;
this.call_type = call_type;
this.notes = notes;
}
public Call() {}
}
/*! [call-center decl] */
public class ex_call_center {
public static String home;
public static int
callCenterExample()
throws WiredTigerException
{
Connection conn;
Cursor cursor;
Session session;
int count, ret;
SearchStatus nearstatus;
List<Customer> custSample = new ArrayList<Customer>();
List<Call> callSample = new ArrayList<Call>();
custSample.add(new Customer(0, "Professor Oak",
"LeafGreen Avenue", "123-456-7890"));
custSample.add(new Customer(0, "Lorelei",
"Sevii Islands", "098-765-4321"));
callSample.add(new Call(0, 32, 1, 2, "billing", "unavailable"));
callSample.add(new Call(0, 33, 1, 2, "billing", "available"));
callSample.add(new Call(0, 34, 1, 2, "reminder", "unavailable"));
callSample.add(new Call(0, 35, 1, 2, "reminder", "available"));
/*
* Create a clean test directory for this run of the test program if the
* environment variable isn't already set (as is done by make check).
*/
if (System.getenv("WIREDTIGER_HOME") == null) {
home = "WT_HOME";
try {
Process proc = Runtime.getRuntime().exec("/bin/rm -rf WT_HOME");
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while(br.ready())
System.out.println(br.readLine());
br.close();
new File("WT_HOME").mkdir();
} catch (IOException ioe) {
System.err.println("IOException: WT_HOME: " + ioe);
return(1);
}
} else
home = null;
try {
conn = wiredtiger.open(home, "create");
session = conn.open_session(null);
} catch (WiredTigerException wte) {
System.err.println("WiredTigerException: " + wte);
return(1);
}
/* Note: further error checking omitted for clarity. */
/*! [call-center work] */
/*
* Create the customers table, give names and types to the columns.
* The columns will be stored in two groups: "main" and "address",
* created below.
*/
ret = session.create("table:customers",
"key_format=r," +
"value_format=SSS," +
"columns=(id,name,address,phone)," +
"colgroups=(main,address)");
/* Create the main column group with value columns except address. */
ret = session.create(
"colgroup:customers:main", "columns=(name,phone)");
/* Create the address column group with just the address. */
ret = session.create(
"colgroup:customers:address", "columns=(address)");
/* Create an index on the customer table by phone number. */
ret = session.create(
"index:customers:phone", "columns=(phone)");
/* Populate the customers table with some data. */
cursor = session.open_cursor("table:customers", null, "append");
for (Customer cust : custSample) {
cursor.putValueString(cust.name);
cursor.putValueString(cust.address);
cursor.putValueString(cust.phone);
ret = cursor.insert();
}
ret = cursor.close();
/*
* Create the calls table, give names and types to the columns. All the
* columns will be stored together, so no column groups are declared.
*/
ret = session.create("table:calls",
"key_format=r," +
"value_format=qrrSS," +
"columns=(id,call_date,cust_id,emp_id,call_type,notes)");
/*
* Create an index on the calls table with a composite key of cust_id
* and call_date.
*/
ret = session.create("index:calls:cust_date",
"columns=(cust_id,call_date)");
/* Populate the calls table with some data. */
cursor = session.open_cursor("table:calls", null, "append");
for (Call call : callSample) {
cursor.putValueLong(call.call_date);
cursor.putValueLong(call.cust_id);
cursor.putValueLong(call.emp_id);
cursor.putValueString(call.call_type);
cursor.putValueString(call.notes);
ret = cursor.insert();
}
ret = cursor.close();
/*
* First query: a call arrives. In SQL:
*
* SELECT id, name FROM Customers WHERE phone=?
*
* Use the cust_phone index, lookup by phone number to fill the
* customer record. The cursor will have a key format of "S" for a
* string because the cust_phone index has a single column ("phone"),
* which is of type "S".
*
* Specify the columns we want: the customer ID and the name. This
* means the cursor's value format will be "rS".
*/
cursor = session.open_cursor(
"index:customers:phone(id,name)", null, null);
cursor.putKeyString("123-456-7890");
ret = cursor.search();
if (ret == 0) {
Customer cust = new Customer();
cust.id = cursor.getValueLong();
cust.name = cursor.getValueString();
System.out.println("Read customer record for " + cust.name +
" (ID " + cust.id + ")");
}
ret = cursor.close();
/*
* Next query: get the recent order history. In SQL:
*
* SELECT * FROM Calls WHERE cust_id=? ORDER BY call_date DESC LIMIT 3
*
* Use the call_cust_date index to find the matching calls. Since it is
* is in increasing order by date for a given customer, we want to start
* with the last record for the customer and work backwards.
*
* Specify a subset of columns to be returned. (Note that if these were
* all covered by the index, the primary would not have to be accessed.)
* Stop after getting 3 records.
*/
cursor = session.open_cursor(
"index:calls:cust_date(cust_id,call_type,notes)",
null, null);
/*
* The keys in the index are (cust_id,call_date) -- we want the largest
* call date for a given cust_id. Search for (cust_id+1,0), then work
* backwards.
*/
long custid = 1;
cursor.putKeyLong(custid + 1);
cursor.putKeyLong(0);
nearstatus = cursor.search_near();
/*
* If the table is empty, search_near will return WT_NOTFOUND, else the
* cursor will be positioned on a matching key if one exists, or an
* adjacent key if one does not. If the positioned key is equal to or
* larger than the search key, go back one.
*/
if (ret == 0 && (nearstatus == SearchStatus.LARGER ||
nearstatus == SearchStatus.FOUND))
ret = cursor.prev();
for (count = 0; ret == 0 && count < 3; ++count) {
Call call = new Call();
call.cust_id = cursor.getValueLong();
call.call_type = cursor.getValueString();
call.notes = cursor.getValueString();
if (call.cust_id != custid)
break;
System.out.println("Call record: customer " + call.cust_id +
" (" + call.call_type +
": " + call.notes + ")");
ret = cursor.prev();
}
/*! [call-center work] */
ret = conn.close(null);
return (ret);
}
public static int
main(String[] argv)
{
try {
return (callCenterExample());
}
catch (WiredTigerException wte) {
System.err.println("Exception: " + wte);
return (-1);
}
}
}

View File

@@ -0,0 +1,239 @@
/*-
* Public Domain 2008-2014 WiredTiger, Inc.
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* ex_cursor.java
* This is an example demonstrating some cursor types and operations.
*/
package com.wiredtiger.examples;
import com.wiredtiger.db.*;
import java.io.*;
import java.util.*;
public class ex_cursor {
public static String home;
/*! [cursor next] */
public static int
cursor_forward_scan(Cursor cursor)
throws WiredTigerException
{
String key, value;
int ret;
while ((ret = cursor.next()) == 0) {
key = cursor.getKeyString();
value = cursor.getValueString();
}
return (ret);
}
/*! [cursor next] */
/*! [cursor prev] */
public static int
cursor_reverse_scan(Cursor cursor)
throws WiredTigerException
{
String key, value;
int ret;
while ((ret = cursor.prev()) == 0) {
key = cursor.getKeyString();
value = cursor.getValueString();
}
return (ret);
}
/*! [cursor prev] */
/*! [cursor reset] */
public static int
cursor_reset(Cursor cursor)
throws WiredTigerException
{
return (cursor.reset());
}
/*! [cursor reset] */
/*! [cursor search] */
public static int
cursor_search(Cursor cursor)
throws WiredTigerException
{
String value;
int ret;
cursor.putKeyString("foo");
if ((ret = cursor.search()) != 0)
value = cursor.getValueString();
return (ret);
}
/*! [cursor search] */
/*! [cursor search near] */
public static int
cursor_search_near(Cursor cursor)
throws WiredTigerException
{
String key, value;
SearchStatus exact;
key = "foo";
cursor.putKeyString(key);
exact = cursor.search_near();
if (exact == SearchStatus.SMALLER)
/* Returned key smaller than search key */
key = cursor.getKeyString();
else if (exact == SearchStatus.LARGER)
/* Returned key larger than search key */
key = cursor.getKeyString();
/* Else exact match found, and key already set */
value = cursor.getValueString();
return (0);
}
/*! [cursor search near] */
/*! [cursor insert] */
public static int
cursor_insert(Cursor cursor)
throws WiredTigerException
{
cursor.putKeyString("foo");
cursor.putValueString("bar");
return (cursor.insert());
}
/*! [cursor insert] */
/*! [cursor update] */
public static int
cursor_update(Cursor cursor)
throws WiredTigerException
{
cursor.putKeyString("foo");
cursor.putValueString("newbar");
return (cursor.update());
}
/*! [cursor update] */
/*! [cursor remove] */
public static int
cursor_remove(Cursor cursor)
throws WiredTigerException
{
cursor.putKeyString("foo");
return (cursor.remove());
}
/*! [cursor remove] */
public static int
cursorExample()
throws WiredTigerException
{
Connection conn;
Cursor cursor;
Session session;
int ret;
/*
* Create a clean test directory for this run of the test program if the
* environment variable isn't already set (as is done by make check).
*/
if (System.getenv("WIREDTIGER_HOME") == null) {
home = "WT_HOME";
try {
Process proc = Runtime.getRuntime().exec("/bin/rm -rf WT_HOME");
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while(br.ready())
System.out.println(br.readLine());
br.close();
new File("WT_HOME").mkdir();
} catch (IOException ioe) {
System.err.println("IOException: WT_HOME: " + ioe);
return(1);
}
} else
home = null;
conn = wiredtiger.open(home, "create,statistics=(fast)");
session = conn.open_session(null);
ret = session.create("table:world",
"key_format=r,value_format=5sii," +
"columns=(id,country,population,area)");
/*! [open cursor #1] */
cursor = session.open_cursor("table:world", null, null);
/*! [open cursor #1] */
/*! [open cursor #2] */
cursor = session.open_cursor("table:world(country,population)", null, null);
/*! [open cursor #2] */
/*! [open cursor #3] */
cursor = session.open_cursor("statistics:", null, null);
/*! [open cursor #3] */
/* Create a simple string table to illustrate basic operations. */
ret = session.create("table:map", "key_format=S,value_format=S");
cursor = session.open_cursor("table:map", null, null);
ret = cursor_insert(cursor);
ret = cursor_reset(cursor);
ret = cursor_forward_scan(cursor);
ret = cursor_reset(cursor);
ret = cursor_reverse_scan(cursor);
ret = cursor_search_near(cursor);
ret = cursor_update(cursor);
ret = cursor_remove(cursor);
ret = cursor.close();
/* Note: closing the connection implicitly closes open session(s). */
if ((ret = conn.close(null)) != 0)
System.err.println("Error connecting to " + home + ": " +
wiredtiger.wiredtiger_strerror(ret));
return (ret);
}
public static int
main(String[] argv)
{
try {
return (cursorExample());
}
catch (WiredTigerException wte) {
System.err.println("Exception: " + wte);
return (-1);
}
}
}

View File

@@ -0,0 +1,376 @@
/*-
* Public Domain 2008-2014 WiredTiger, Inc.
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* ex_log.java
* demonstrates how to logging and log cursors.
*/
package com.wiredtiger.examples;
import com.wiredtiger.db.*;
import java.io.*;
import java.util.*;
class Lsn {
int file;
long offset;
}
public class ex_log {
public static String home1 = "WT_HOME_LOG_1";
public static String home2 = "WT_HOME_LOG_2";
public static String uri = "table:logtest";
public static final String CONN_CONFIG =
"create,cache_size=100MB,log=(archive=false,enabled=true)";
public static final int MAX_KEYS = 10;
static Session
setup_copy()
throws WiredTigerException
{
int ret = 0;
Connection conn;
conn = wiredtiger.open(home2, CONN_CONFIG);
Session session = conn.open_session(null);
session.create(uri, "key_format=S,value_format=S");
return (session);
}
static int
compare_tables(Session session, Session sess_copy)
throws WiredTigerException
{
int ret;
Cursor cursor = session.open_cursor(uri, null, null);
Cursor curs_copy = sess_copy.open_cursor(uri, null, null);
while ((ret = cursor.next()) == 0) {
ret = curs_copy.next();
String key = cursor.getKeyString();
String value = cursor.getValueString();
String key_copy = curs_copy.getKeyString();
String value_copy = curs_copy.getValueString();
if (!key.equals(key_copy) || !value.equals(value_copy)) {
System.err.println(
"Mismatched: key " + key +
", key_copy " + key_copy +
" value " + value +
" value_copy " + value_copy);
return (1);
}
}
if (ret != wiredtiger.WT_NOTFOUND)
System.err.println("WT_CURSOR.next: " +
wiredtiger.wiredtiger_strerror(ret));
ret = cursor.close();
ret = curs_copy.next();
if (ret != wiredtiger.WT_NOTFOUND)
System.err.println("WT_CURSOR.next: " +
wiredtiger.wiredtiger_strerror(ret));
ret = curs_copy.close();
return (ret);
}
/*! [log cursor walk] */
static void
print_record(Lsn lsn, int opcount,
int rectype, int optype, long txnid, int fileid,
byte[] key, byte[] value)
{
System.out.print(
"LSN [" + lsn.file + "][" + lsn.offset + "]." + opcount +
": record type " + rectype + " optype " + optype +
" txnid " + txnid + " fileid " + fileid);
System.out.println(" key size " + key.length +
"value size " + value.length);
if (rectype == wiredtiger.WT_LOGREC_MESSAGE)
System.out.println("Application Record: " + new String(value));
}
/*
* simple_walk_log --
* A simple walk of the log.
*/
static int
simple_walk_log(Session session)
throws WiredTigerException
{
Cursor cursor;
Lsn lsn = new Lsn();
byte[] logrec_key, logrec_value;
long txnid;
int fileid, opcount, optype, rectype;
int ret;
/*! [log cursor open] */
cursor = session.open_cursor("log:", null, null);
/*! [log cursor open] */
while ((ret = cursor.next()) == 0) {
/*! [log cursor get_key] */
lsn.file = cursor.getKeyInt();
lsn.offset = cursor.getKeyLong();
opcount = cursor.getKeyInt();
/*! [log cursor get_key] */
/*! [log cursor get_value] */
txnid = cursor.getValueLong();
rectype = cursor.getValueInt();
optype = cursor.getValueInt();
fileid = cursor.getValueInt();
logrec_key = cursor.getValueByteArray();
logrec_value = cursor.getValueByteArray();
/*! [log cursor get_value] */
print_record(lsn, opcount,
rectype, optype, txnid, fileid, logrec_key, logrec_value);
}
if (ret == wiredtiger.WT_NOTFOUND)
ret = 0;
ret = cursor.close();
return (ret);
}
/*! [log cursor walk] */
static int
walk_log(Session session)
throws WiredTigerException
{
Connection wt_conn2;
Cursor cursor, cursor2;
Lsn lsn, lsnsave;
byte[] logrec_key, logrec_value;
Session session2;
long txnid;
int fileid, opcount, optype, rectype;
int i, ret;
boolean in_txn, first;
session2 = setup_copy();
wt_conn2 = session2.getConnection();
cursor = session.open_cursor("log:", null, null);
cursor2 = session2.open_cursor(uri, null, "raw=true");
i = 0;
in_txn = false;
txnid = 0;
lsn = new Lsn();
lsnsave = new Lsn();
while ((ret = cursor.next()) == 0) {
lsn.file = cursor.getKeyInt();
lsn.offset = cursor.getKeyLong();
opcount = cursor.getKeyInt();
/*
* Save one of the LSNs we get back to search for it
* later. Pick a later one because we want to walk from
* that LSN to the end (where the multi-step transaction
* was performed). Just choose the record that is MAX_KEYS.
*/
if (++i == MAX_KEYS)
lsnsave = lsn;
txnid = cursor.getValueLong();
rectype = cursor.getValueInt();
optype = cursor.getValueInt();
fileid = cursor.getValueInt();
logrec_key = cursor.getValueByteArray();
logrec_value = cursor.getValueByteArray();
print_record(lsn, opcount,
rectype, optype, txnid, fileid, logrec_key, logrec_value);
/*
* If we are in a transaction and this is a new one, end
* the previous one.
*/
if (in_txn && opcount == 0) {
ret = session2.commit_transaction(null);
in_txn = false;
}
/*
* If the operation is a put, replay it here on the backup
* connection. Note, we cheat by looking only for fileid 1
* in this example. The metadata is fileid 0.
*/
if (fileid == 1 && rectype == wiredtiger.WT_LOGREC_COMMIT &&
optype == wiredtiger.WT_LOGOP_ROW_PUT) {
if (!in_txn) {
ret = session2.begin_transaction(null);
in_txn = true;
}
cursor2.putKeyByteArray(logrec_key);
cursor2.putValueByteArray(logrec_value);
ret = cursor2.insert();
}
}
if (in_txn)
ret = session2.commit_transaction(null);
ret = cursor2.close();
/*
* Compare the tables after replay. They should be identical.
*/
if (compare_tables(session, session2) != 0)
System.out.println("compare failed");
ret = session2.close(null);
ret = wt_conn2.close(null);
ret = cursor.reset();
/*! [log cursor set_key] */
cursor.putKeyInt(lsnsave.file);
cursor.putKeyLong(lsnsave.offset);
/*! [log cursor set_key] */
/*! [log cursor search] */
ret = cursor.search();
/*! [log cursor search] */
System.out.println("Reset to saved...");
/*
* Walk all records starting with this key.
*/
first = true;
while (ret == 0) { /*TODO: not quite right*/
lsn.file = cursor.getKeyInt();
lsn.offset = cursor.getKeyLong();
opcount = cursor.getKeyInt();
if (first) {
first = false;
if (lsnsave.file != lsn.file ||
lsnsave.offset != lsn.offset) {
System.err.println("search returned the wrong LSN");
System.exit(1);
}
}
txnid = cursor.getValueLong();
rectype = cursor.getValueInt();
optype = cursor.getValueInt();
fileid = cursor.getValueInt();
logrec_key = cursor.getValueByteArray();
logrec_value = cursor.getValueByteArray();
print_record(lsn, opcount, rectype, optype, txnid,
fileid, logrec_key, logrec_value);
ret = cursor.next();
if (ret != 0)
break;
}
ret = cursor.close();
return (ret);
}
public static int
logExample()
throws WiredTigerException
{
Connection wt_conn;
Cursor cursor;
Session session;
int i, record_count, ret;
try {
String command = "/bin/rm -rf " + home1 + " " + home2;
Process proc = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while(br.ready())
System.out.println(br.readLine());
br.close();
new File(home1).mkdir();
new File(home2).mkdir();
} catch (IOException ioe) {
System.err.println("IOException: " + ioe);
return (1);
}
if ((wt_conn = wiredtiger.open(home1, CONN_CONFIG)) == null) {
System.err.println("Error connecting to " + home1);
return (1);
}
session = wt_conn.open_session(null);
ret = session.create(uri, "key_format=S,value_format=S");
cursor = session.open_cursor(uri, null, null);
/*
* Perform some operations with individual auto-commit transactions.
*/
for (record_count = 0, i = 0; i < MAX_KEYS; i++, record_count++) {
String k = "key" + i;
String v = "value" + i;
cursor.putKeyString(k);
cursor.putValueString(v);
ret = cursor.insert();
}
ret = session.begin_transaction(null);
/*
* Perform some operations within a single transaction.
*/
for (i = MAX_KEYS; i < MAX_KEYS+5; i++, record_count++) {
String k = "key" + i;
String v = "value" + i;
cursor.putKeyString(k);
cursor.putValueString(v);
ret = cursor.insert();
}
ret = session.commit_transaction(null);
ret = cursor.close();
/*! [log cursor printf] */
ret = session.log_printf("Wrote " + record_count + " records");
/*! [log cursor printf] */
/*
* Close and reopen the connection so that the log ends up with
* a variety of records such as file sync and checkpoint. We
* have archiving turned off.
*/
ret = wt_conn.close(null);
if ((wt_conn = wiredtiger.open(home1, CONN_CONFIG)) == null) {
System.err.println("Error connecting to " + home1);
return (ret);
}
session = wt_conn.open_session(null);
ret = simple_walk_log(session);
ret = walk_log(session);
ret = wt_conn.close(null);
return (ret);
}
public static int
main()
{
try {
return (logExample());
}
catch (WiredTigerException wte) {
System.err.println("Exception: " + wte);
return (-1);
}
}
}

View File

@@ -0,0 +1,333 @@
/*-
* Public Domain 2008-2014 WiredTiger, Inc.
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* ex_schema.java
* This is an example application demonstrating how to create and access
* tables using a schema.
*/
package com.wiredtiger.examples;
import com.wiredtiger.db.*;
import java.io.*;
import java.util.*;
public class ex_schema {
public static String home;
/*! [schema declaration] */
/* The class for the data we are storing in a WiredTiger table. */
static class PopRecord {
public String country; // Stored in database as fixed size char[5];
public short year;
public long population;
public PopRecord(String country, short year, long population) {
this.country = country;
this.year = year;
this.population = population;
}
}
static List<PopRecord> popData;
static {
popData = new ArrayList<PopRecord>();
popData.add(new PopRecord("AU", (short)1900, 4000000 ));
popData.add(new PopRecord("AU", (short)2000, 19053186 ));
popData.add(new PopRecord("CAN", (short)1900, 5500000 ));
popData.add(new PopRecord("CAN", (short)2000, 31099561 ));
popData.add(new PopRecord("UK", (short)1900, 369000000 ));
popData.add(new PopRecord("UK", (short)2000, 59522468 ));
popData.add(new PopRecord("USA", (short)1900, 76212168 ));
popData.add(new PopRecord("USA", (short)2000, 301279593 ));
};
/*! [schema declaration] */
public static int
schemaExample()
throws WiredTigerException
{
Connection conn;
Cursor cursor;
Session session;
String country;
long recno, population;
short year;
int ret;
/*
* Create a clean test directory for this run of the test program if the
* environment variable isn't already set (as is done by make check).
*/
if (System.getenv("WIREDTIGER_HOME") == null) {
home = "WT_HOME";
try {
Process proc = Runtime.getRuntime().exec("/bin/rm -rf WT_HOME");
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while(br.ready())
System.out.println(br.readLine());
br.close();
new File("WT_HOME").mkdir();
} catch (IOException ioe) {
System.err.println("IOException: WT_HOME: " + ioe);
return(1);
}
} else
home = null;
try {
conn = wiredtiger.open(home, "create");
session = conn.open_session(null);
} catch (WiredTigerException wte) {
System.err.println("WiredTigerException: " + wte);
return(1);
}
/*! [Create a table with column groups] */
/*
* Create the population table.
* Keys are record numbers, the format for values is (5-byte string,
* long, long).
* See ::wiredtiger_struct_pack for details of the format strings.
*/
ret = session.create("table:poptable",
"key_format=r,value_format=5sHQ," +
"columns=(id,country,year,population),colgroups=(main,population)");
/*
* Create two column groups: a primary column group with the country
* code, year and population (named "main"), and a population column
* group with the population by itself (named "population").
*/
ret = session.create("colgroup:poptable:main",
"columns=(country,year,population)");
ret = session.create("colgroup:poptable:population",
"columns=(population)");
/*! [Create a table with column groups] */
/*! [Create an index] */
/* Create an index with a simple key. */
ret = session.create("index:poptable:country",
"columns=(country)");
/*! [Create an index] */
/*! [Create an index with a composite key] */
/* Create an index with a composite key (country,year). */
ret = session.create("index:poptable:country_plus_year",
"columns=(country,year)");
/*! [Create an index with a composite key] */
/*! [Insert and list records] */
/* Insert the records into the table. */
cursor = session.open_cursor("table:poptable", null, "append");
for (PopRecord p : popData) {
cursor.putValueString(p.country);
cursor.putValueShort(p.year);
cursor.putValueLong(p.population);
ret = cursor.insert();
}
ret = cursor.close();
/* List the records in the table. */
cursor = session.open_cursor("table:poptable", null, null);
while ((ret = cursor.next()) == 0) {
recno = cursor.getKeyLong();
country = cursor.getValueString();
year = cursor.getValueShort();
population = cursor.getValueLong();
System.out.print("ID " + recno);
System.out.println(": country " + country + ", year " + year +
", population " + population);
}
ret = cursor.close();
/*! [Insert and list records] */
/*! [List the records in the table using raw mode.] */
cursor = session.open_cursor("table:poptable", null, "raw");
while ((ret = cursor.next()) == 0) {
byte[] key, value;
key = cursor.getKeyByteArray();
System.out.println(Arrays.toString(key));
value = cursor.getValueByteArray();
System.out.println("raw key: " + Arrays.toString(key) +
", raw value: " + Arrays.toString(value));
}
/*! [List the records in the table using raw mode.] */
/*! [Read population from the primary column group] */
/*
* Open a cursor on the main column group, and return the information
* for a particular country.
*/
cursor = session.open_cursor("colgroup:poptable:main", null, null);
cursor.putKeyLong(2);
if ((ret = cursor.search()) == 0) {
country = cursor.getValueString();
year = cursor.getValueShort();
population = cursor.getValueLong();
System.out.println("ID 2: country " + country +
", year " + year + ", population " + population);
}
/*! [Read population from the primary column group] */
ret = cursor.close();
/*! [Read population from the standalone column group] */
/*
* Open a cursor on the population column group, and return the
* population of a particular country.
*/
cursor = session.open_cursor("colgroup:poptable:population", null, null);
cursor.putKeyLong(2);
if ((ret = cursor.search()) == 0) {
population = cursor.getValueLong();
System.out.println("ID 2: population " + population);
}
/*! [Read population from the standalone column group] */
ret = cursor.close();
/*! [Search in a simple index] */
/* Search in a simple index. */
cursor = session.open_cursor("index:poptable:country", null, null);
cursor.putKeyString("AU");
ret = cursor.search();
country = cursor.getValueString();
year = cursor.getValueShort();
population = cursor.getValueLong();
System.out.println("AU: country " + country + ", year " + year +
", population " + population);
/*! [Search in a simple index] */
ret = cursor.close();
/*! [Search in a composite index] */
/* Search in a composite index. */
cursor = session.open_cursor(
"index:poptable:country_plus_year", null, null);
cursor.putKeyString("USA");
cursor.putKeyShort((short)1900);
ret = cursor.search();
country = cursor.getValueString();
year = cursor.getValueShort();
population = cursor.getValueLong();
System.out.println("US 1900: country " + country +
", year " + year + ", population " + population);
/*! [Search in a composite index] */
ret = cursor.close();
/*! [Return a subset of values from the table] */
/*
* Use a projection to return just the table's country and year
* columns.
*/
cursor = session.open_cursor("table:poptable(country,year)", null, null);
while ((ret = cursor.next()) == 0) {
country = cursor.getValueString();
year = cursor.getValueShort();
System.out.println("country " + country + ", year " + year);
}
/*! [Return a subset of values from the table] */
ret = cursor.close();
/*! [Return a subset of values from the table using raw mode] */
/*
* Use a projection to return just the table's country and year
* columns.
*/
cursor = session.open_cursor("table:poptable(country,year)", null, null);
while ((ret = cursor.next()) == 0) {
country = cursor.getValueString();
year = cursor.getValueShort();
System.out.println("country " + country + ", year " + year);
}
/*! [Return a subset of values from the table using raw mode] */
ret = cursor.close();
/*! [Return the table's record number key using an index] */
/*
* Use a projection to return just the table's record number key
* from an index.
*/
cursor = session.open_cursor("index:poptable:country_plus_year(id)", null, null);
while ((ret = cursor.next()) == 0) {
country = cursor.getKeyString();
year = cursor.getKeyShort();
recno = cursor.getValueLong();
System.out.println("row ID " + recno + ": country " + country +
", year " + year);
}
/*! [Return the table's record number key using an index] */
ret = cursor.close();
/*! [Return a subset of the value columns from an index] */
/*
* Use a projection to return just the population column from an
* index.
*/
cursor = session.open_cursor(
"index:poptable:country_plus_year(population)", null, null);
while ((ret = cursor.next()) == 0) {
country = cursor.getKeyString();
year = cursor.getKeyShort();
population = cursor.getValueLong();
System.out.println("population " + population +
": country " + country + ", year " + year);
}
/*! [Return a subset of the value columns from an index] */
ret = cursor.close();
/*! [Access only the index] */
/*
* Use a projection to avoid accessing any other column groups when
* using an index: supply an empty list of value columns.
*/
cursor = session.open_cursor(
"index:poptable:country_plus_year()", null, null);
while ((ret = cursor.next()) == 0) {
country = cursor.getKeyString();
year = cursor.getKeyShort();
System.out.println("country " + country + ", year " + year);
}
/*! [Access only the index] */
ret = cursor.close();
ret = conn.close(null);
return (ret);
}
public static int
main(String[] argv)
{
try {
return (schemaExample());
}
catch (WiredTigerException wte) {
System.err.println("Exception: " + wte);
return (-1);
}
}
}

View File

@@ -0,0 +1,252 @@
/*-
* Public Domain 2008-2014 WiredTiger, Inc.
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* ex_stat.java
* This is an example demonstrating how to query database statistics.
*/
package com.wiredtiger.examples;
import com.wiredtiger.db.*;
import java.io.*;
import java.util.*;
public class ex_stat {
public static String home;
/*! [statistics display function] */
int
print_cursor(Cursor cursor)
throws WiredTigerException
{
String desc, pvalue;
long value;
int ret;
while ((ret = cursor.next()) == 0) {
desc = cursor.getValueString();
pvalue = cursor.getValueString();
value = cursor.getValueLong();
if (value != 0)
System.out.println(desc + "=" + pvalue);
}
return (ret == wiredtiger.WT_NOTFOUND ? 0 : ret);
}
/*! [statistics display function] */
int
print_database_stats(Session session)
throws WiredTigerException
{
Cursor cursor;
int ret;
/*! [statistics database function] */
cursor = session.open_cursor("statistics:", null, null);
ret = print_cursor(cursor);
ret = cursor.close();
/*! [statistics database function] */
return (ret);
}
int
print_file_stats(Session session)
throws WiredTigerException
{
Cursor cursor;
int ret;
/*! [statistics table function] */
cursor = session.open_cursor("statistics:table:access", null, null);
ret = print_cursor(cursor);
ret = cursor.close();
/*! [statistics table function] */
return (ret);
}
int
print_overflow_pages(Session session)
throws WiredTigerException
{
/*! [statistics retrieve by key] */
Cursor cursor;
String desc, pvalue;
long value;
int ret;
cursor = session.open_cursor("statistics:table:access", null, null);
cursor.putKeyInt(wiredtiger.WT_STAT_DSRC_BTREE_OVERFLOW);
ret = cursor.search();
desc = cursor.getValueString();
pvalue = cursor.getValueString();
value = cursor.getValueLong();
System.out.println(desc + "=" + pvalue);
ret = cursor.close();
/*! [statistics retrieve by key] */
return (ret);
}
/*! [statistics calculation helper function] */
long
get_stat(Cursor cursor, int stat_field)
throws WiredTigerException
{
long value;
int ret;
cursor.putKeyInt(stat_field);
if ((ret = cursor.search()) != 0) {
System.err.println("stat_field: " + stat_field + " not found");
value = 0;
}
else {
String desc = cursor.getValueString();
String pvalue = cursor.getValueString();
value = cursor.getValueLong();
}
return (value);
}
/*! [statistics calculation helper function] */
int
print_derived_stats(Session session)
throws WiredTigerException
{
Cursor cursor;
int ret;
/*! [statistics calculate open table stats] */
cursor = session.open_cursor("statistics:table:access", null, null);
/*! [statistics calculate open table stats] */
{
/*! [statistics calculate table fragmentation] */
long ckpt_size = get_stat(cursor,
wiredtiger.WT_STAT_DSRC_BLOCK_CHECKPOINT_SIZE);
long file_size = get_stat(cursor,
wiredtiger.WT_STAT_DSRC_BLOCK_SIZE);
System.out.println("File is " +
(int)(100 * (file_size - ckpt_size) / file_size) +
"% fragmented\n");
/*! [statistics calculate table fragmentation] */
}
{
/*! [statistics calculate write amplification] */
long app_insert = get_stat(cursor,
wiredtiger.WT_STAT_DSRC_CURSOR_INSERT_BYTES);
long app_remove = get_stat(cursor,
wiredtiger.WT_STAT_DSRC_CURSOR_REMOVE_BYTES);
long app_update = get_stat(cursor,
wiredtiger.WT_STAT_DSRC_CURSOR_UPDATE_BYTES);
long fs_writes = get_stat(cursor,
wiredtiger.WT_STAT_DSRC_CACHE_BYTES_WRITE);
if (app_insert + app_remove + app_update != 0)
System.out.println("Write amplification is " +
(double)fs_writes / (app_insert + app_remove + app_update));
/*! [statistics calculate write amplification] */
}
ret = cursor.close();
return (ret);
}
public int
statExample()
throws WiredTigerException
{
Connection conn;
Cursor cursor;
Session session;
int ret;
/*
* Create a clean test directory for this run of the test program if the
* environment variable isn't already set (as is done by make check).
*/
if (System.getenv("WIREDTIGER_HOME") == null) {
home = "WT_HOME";
try {
Process proc = Runtime.getRuntime().exec("/bin/rm -rf WT_HOME");
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while(br.ready())
System.out.println(br.readLine());
br.close();
new File("WT_HOME").mkdir();
} catch (IOException ioe) {
System.err.println("IOException: WT_HOME: " + ioe);
return(1);
}
} else
home = null;
conn = wiredtiger.open(home, "create,statistics=(all)");
session = conn.open_session(null);
ret = session.create("table:access", "key_format=S,value_format=S");
cursor = session.open_cursor("table:access", null, null);
cursor.putKeyString("key");
cursor.putValueString("value");
ret = cursor.insert();
ret = cursor.close();
ret = session.checkpoint(null);
ret = print_database_stats(session);
ret = print_file_stats(session);
ret = print_overflow_pages(session);
ret = print_derived_stats(session);
return (conn.close(null) == 0 ? ret : -1);
}
public static int
main(String[] argv)
{
try {
return ((new ex_stat()).statExample());
}
catch (WiredTigerException wte) {
System.err.println("Exception: " + wte);
return (-1);
}
}
}

View File

@@ -0,0 +1,142 @@
/*-
* Public Domain 2008-2014 WiredTiger, Inc.
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* ex_thread.java
* This is an example demonstrating how to create and access a simple
* table from multiple threads.
*/
package com.wiredtiger.examples;
import com.wiredtiger.db.*;
import java.io.*;
import java.util.*;
/*! [thread scan] */
class ScanThread extends Thread {
private Connection conn;
public ScanThread(Connection conn) {
this.conn = conn;
}
public void run()
{
try {
int ret;
Session session = conn.open_session(null);
Cursor cursor = session.open_cursor("table:access", null, null);
/* Show all records. */
while ((ret = cursor.next()) == 0) {
String key = cursor.getKeyString();
String value = cursor.getValueString();
System.out.println("Got record: " + key + " : " + value);
}
if (ret != wiredtiger.WT_NOTFOUND)
System.err.println("Cursor.next: " +
wiredtiger.wiredtiger_strerror(ret));
} catch (WiredTigerException wte) {
System.err.println("Exception " + wte);
}
}
}
/*! [thread scan] */
public class ex_thread {
public static String home;
public static final int NUM_THREADS = 10;
/*! [thread main] */
static int main(String[] argv)
{
try {
Thread[] threads = new Thread[NUM_THREADS];
int i, ret;
Connection conn;
/*
* Create a clean test directory for this run of the test program if the
* environment variable isn't already set (as is done by make check).
*/
if (System.getenv("WIREDTIGER_HOME") == null) {
home = "WT_HOME";
try {
Process proc = Runtime.getRuntime().exec("/bin/rm -rf " + home);
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while(br.ready())
System.out.println(br.readLine());
br.close();
new File(home).mkdir();
} catch (IOException ioe) {
System.err.println("IOException: " + home + ": " + ioe);
return(1);
}
} else
home = null;
if ((conn = wiredtiger.open(home, "create")) == null) {
System.err.println("Error connecting to " + home);
return(1);
}
/* Note: further error checking omitted for clarity. */
Session session = conn.open_session(null);
ret = session.create("table:access", "key_format=S,value_format=S");
Cursor cursor = session.open_cursor("table:access", null, "overwrite");
cursor.putKeyString("key1");
cursor.putValueString("value1");
ret = cursor.insert();
ret = session.close(null);
for (i = 0; i < NUM_THREADS; i++) {
threads[i] = new ScanThread(conn);
threads[i].start();
}
for (i = 0; i < NUM_THREADS; i++)
try {
threads[i].join();
ret = -1;
}
catch (InterruptedException ie) {
}
ret = conn.close(null);
return (ret);
}
catch (WiredTigerException wte) {
System.err.println("Exception: " + wte);
return (-1);
}
}
/*! [thread main] */
}