Package ca.carleton.gcrc.couch.app

Source Code of ca.carleton.gcrc.couch.app.DocumentInitialize

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 File file;
 
  public DocumentInitialize() {
   
  }

  public DocumentInitialize(
    CouchDb couchDb
    ,File file
    ) {
    this.couchDb = couchDb;
    this.file = file;
  }
 
  public CouchDb getCouchDb() {
    return couchDb;
  }

  public void setCouchDb(CouchDb couchDb) {
    this.couchDb = couchDb;
  }

  public File getFile() {
    return file;
  }

  public void setFile(File file) {
    this.file = file;
  }

  public void upload() throws Exception {
    String docId = null;
   
    // Load document
    StringWriter docWriter = new StringWriter();
    JSONObject doc = new JSONObject();
    try {
      JSONFileLoader builder = new JSONFileLoader(file);
      builder.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);
      }
    }
  }
}
TOP

Related Classes of ca.carleton.gcrc.couch.app.DocumentInitialize

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.