package ca.carleton.gcrc.couch.app;
import java.io.File;
import java.io.StringWriter;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONTokener;
import org.apache.log4j.Logger;
import ca.carleton.gcrc.couch.client.CouchDb;
public class DocumentInitialize {
final protected Logger logger = Logger.getLogger(this.getClass());
private CouchDb couchDb;
private JSONLoader jsonLoader;
public DocumentInitialize() {
}
public DocumentInitialize(
CouchDb couchDb
,File file
) throws Exception {
this.couchDb = couchDb;
this.jsonLoader = new JSONFileLoader(file);
}
public DocumentInitialize(
CouchDb couchDb
,JSONLoader jsonLoader
) {
this.couchDb = couchDb;
this.jsonLoader = jsonLoader;
}
public CouchDb getCouchDb() {
return couchDb;
}
public void setCouchDb(CouchDb couchDb) {
this.couchDb = couchDb;
}
public JSONLoader getJsonLoader() {
return jsonLoader;
}
public void setJsonLoader(JSONLoader jsonLoader) {
this.jsonLoader = jsonLoader;
}
public void upload() throws Exception {
String docId = null;
// Load document
StringWriter docWriter = new StringWriter();
JSONObject doc = new JSONObject();
try {
jsonLoader.write(docWriter);
JSONTokener jsonTokener = new JSONTokener(docWriter.toString());
Object obj = jsonTokener.nextValue();
if( obj instanceof JSONObject ) {
doc = (JSONObject)obj;
} else {
throw new Exception("Unexpected returned object type: "+obj.getClass().getSimpleName());
}
docId = doc.getString("_id");
} catch(Exception e) {
throw new Exception("Unable to load document", e);
}
// Check if doc exists
boolean creationRequired = false;
try {
if( false == couchDb.documentExists(docId) ) {
creationRequired = true;
}
} catch(Exception e) {
throw new Exception("Unable to access current document", e);
}
// Upload, if required
if( creationRequired ) {
logger.info("Creating document: "+docId);
try {
couchDb.createDocument(doc);
} catch (Exception e) {
throw new Exception("Unable to create document", e);
}
}
}
}