UpdateJSON.loadTable()
UpdateJSON.loadTable()
メソッドは、サンプル日付をOracle NoSQL Databaseストアにロードします。
サンプル・データに示されているように、表のすべての行は、単一のテキスト・ファイルでJSONデータとして表されます。各行は、ファイル内の単一のJSONオブジェクトです。通常、JSONファイルには1つのJSONオブジェクトのみが含まれます。ストリーム内で検出された複数のJSONオブジェクトを反復処理するサード・パーティ・ライブラリはありますが、この例ではそれらに依存しません。(わかりやすくするため、サード・パーティ依存性を追加しないようにします。)その結果、このメソッドは、サンプル・データをストアにロードするためのプリミティブ・カスタム・パーサーを提供します。
// Loads the contents of the sample data file into
// the personContacts table. The defineTable() method
// must have been run at least once (either in this
// runtime, or in one before it) before this method
// is run.
//
// JSON parsers ordinarily expect one JSON Object per file.
// Our sample data contains multiple JSON Objects, each of
// which represents a single table row. So this method
// implements a simple, custom, not particularly robust
// parser to read the input file, collect JSON Objects,
// and load them into the table.
private void loadTable(KVStore kvstore, String file2load) {
TableAPI tableH = kvstore.getTableAPI();
Table myTable = tableH.getTable("personContacts");
BufferedReader br = null;
FileReader fr = null;
try {
String jObj = "";
String currLine;
int pCount = 0;
boolean buildObj = false;
boolean beganParsing = false;
fr = new FileReader(file2load);
br = new BufferedReader(fr);
// Parse the example data file, loading each JSON object
// found there into the table.
while ((currLine = br.readLine()) != null) {
pCount += countParens(currLine, '{');
// Empty line in the data file
if (currLine.length() == 0)
continue;
// Comments must start at column 0 in the
// data file.
if (currLine.charAt(0) == '#')
continue;
// If we've found at least one open paren, it's time to
// start collecting data
if (pCount > 0) {
buildObj = true;
beganParsing = true;
}
if (buildObj) {
jObj += currLine;
}
// If our open and closing parens balance (the count
// is zero) then we've collected an entire object
pCount -= countParens(currLine, '}');
if (pCount < 1)
buildObj = false;
// If we started parsing data, but buildObj is false
// then that means we've reached the end of a JSON
// object in the input file. So write the object
// to the table, which means it is written to the
// store.
if (beganParsing && !buildObj) {
Row row = myTable.createRowFromJson(jObj, false);
tableH.put(row, null, null);
jObj = "";
}
}
System.out.println("Loaded sample data " + file2load);
} catch (FileNotFoundException fnfe) {
System.out.println("File not found: " + fnfe);
System.exit(-1);
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
System.exit(-1);
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException iox) {
System.out.println("IOException on close: " + iox);
}
}
}
// Used by loadTable() to know when a JSON object
// begins and ends in the input data file.
private int countParens(String line, char p) {
int c = 0;
for( int i=0; i < line.length(); i++ ) {
if( line.charAt(i) == p ) {
c++;
}
}
return c;
}