// Get "valueType" row for update.
logger.info("Checking valueType row in :" + kind);
RecordQuery query = new RecordQuery(recordFeedUrl);
query.setSpreadsheetQuery(Entity.KEY_RESERVED_PROPERTY + "=" + VALUE_TYPE);
RecordEntry valueTypeRow = ss.query(query, RecordFeed.class).getEntries().get(0);
Map<String, Field> valueTypeRowMap = new HashMap<String, Field>();
boolean valueTypeNotSet = false;
for (Field field : valueTypeRow.getFields()) {
valueTypeRowMap.put(field.getName(), field);
if (field.getValue().equals(VALUE_TYPE_NOT_SET)) {
valueTypeNotSet = true;
}
}
// When retrying, Check if already exists
List<String> duplicateCheckList = new ArrayList<String>();
if (retry) {
/*
* If you use query like setSpreadsheetQuery("__key__=Kind(1)"),
* '()' in __key__ conflicts with '()' as parameter...
*/
RecordQuery query2 = new RecordQuery(recordFeedUrl);
query2.setMaxResults(list.size());
query2.setReverse(true);
final List<RecordEntry> entries = ss.query(query2, RecordFeed.class).getEntries();
for (RecordEntry entry : entries) {
for (Field field : entry.getFields()) {
if (field.getName().equals(Entity.KEY_RESERVED_PROPERTY)) {
duplicateCheckList.add(field.getValue());
break;
}
}
}
logger.info("duplicateCheckList :" + duplicateCheckList);
}
// Add new rows to table
logger.info("Start writing dump data to :" + kind);
List<RecordEntry> newRecordList = new ArrayList<RecordEntry>();
try {
for (GbEntity gbEntity : list) {
logger.info(gbEntity.toString());
RecordEntry newEntry = new RecordEntry();
final String key = gbEntity.getKey().toString();
if (duplicateCheckList.contains(key)) {
logger.info(key + " is duplicate");
continue;
}
newEntry.addField(new Field(null, Entity.KEY_RESERVED_PROPERTY, key));
for (GbProperty gbProperty : gbEntity.getProperties()) {
final String value = gbProperty.asSpreadsheetValue();
if (value == null) {
continue;
}
final String columnName = gbProperty.getName();
if (valueTypeRowMap.containsKey(columnName) == false) {
continue; // when the colum name is undefined.
}
newEntry.addField(new Field(null, columnName, "'" + value));
// Update valueType Cell
if (valueTypeNotSet) {
Field valueTypeCell = valueTypeRowMap.get(columnName);
// Avoid when statistics is not updated.
if (valueTypeCell != null) {
valueTypeCell.setValue(gbProperty.asSpreadsheetValueType());
}
}
}
RecordEntry inserted = ss.insert(recordFeedUrl, newEntry);
newRecordList.add(inserted);
}
logger.info("Finish writing dump data to :" + kind);
// Update valueType row.
if (valueTypeNotSet) {
valueTypeRow.update();
logger.info("Updated TypeValue row in :" + kind);
}
} catch (Exception e) {
for (RecordEntry inserted : newRecordList) {
try {
inserted.delete();
} catch (Exception e2) {
e2.printStackTrace();
}
}
throw e;