it("ui__list$", function(d) {
    var ui_list_value = [ 
      { id: 'ui_001',
        name: 'myui001',
        app: 'app1',
        path: B.path.join(appbundle_path, '/app1/uis/ui_001.json') 
      },
      { id: 'ui_002',
        name: 'myui002',
        app: 'app1',
        path: B.path.join(appbundle_path, '/app1/uis/ui_002.json') 
      },
      { id: 'ui_003',
        name: 'myui003',
        app: 'app2',
        path: B.path.join(appbundle_path, '/app2/uis/ui_003.json') 
      },
      { id: 'ui_004',
        name: 'myui004',
        app: 'app2',
        path: B.path.join(appbundle_path, '/app2/uis/ui_004.json') 
      }];

      var max_length = 2;
      if (max_length > ui_list_value.length) {
        max_length = ui_list_value.length;
      }
      em.ui__list$(max_length).then(function(v) {
        assert.equal(_.isEqual(v, ui_list_value.slice(0, max_length)), true);
        d();
    }).done();
  });
  it("graph__list$", function(d) {
    var graph_list_value = [ 
      { id: 'graph_001',
        name: 'mygraph001',
        app: 'app1',
        path: B.path.join(appbundle_path, '/app1/graphs/graph_001.json') 
      },
      { id: 'graph_002',
        name: 'mygraph002',
        app: 'app1',
        path: B.path.join(appbundle_path, '/app1/graphs/graph_002.json') 
      },
      { id: 'graph_003',
        name: 'mygraph003',
        app: 'app2',
        path: B.path.join(appbundle_path, '/app2/graphs/graph_003.json') 
      },
      { id: 'graph_004',
        name: 'mygraph004',
        app: 'app2',
        path: B.path.join(appbundle_path, '/app2/graphs/graph_004.json') 
      }];

      var max_length = 2;
      if (max_length > graph_list_value.length) {
        max_length = graph_list_value.length;
      }
      em.graph__list$(max_length).then(function(v) {
        assert.equal(_.isEqual(v, graph_list_value.slice(0, max_length)), true);
        d();
    }).done();
  });
  .then(function() {
    var tasks = [];
    var spec_bundle = {
      id: "SpecBundle" + self.id,
      name: "default_bundle"
    };
    //for hope-service
    if (self.config.thingbundle_path) {
      var thingbundle_path = B.path.abs(self.config.thingbundle_path, self.config_path);
      tasks.push(self.em.thing__load_from_bundle$(thingbundle_path, spec_bundle, self.id));
    }
    
    if (self.config.specbundle_path) {
      var specbundle_path = B.path.abs(self.config.specbundle_path, self.config_path);
      tasks.push(self.em.spec__load_from_localbundle$(specbundle_path));
    }


    if (self.config.grove_config) {
      B.check(self.config.grove_config.grovebundle_path, "hub", "should have grove bundle");
      self.config.grove_config.grovebundle_path = B.path.abs(self.config.grove_config.grovebundle_path, self.config_path);
      tasks.push(self.em.thing__load_grove_thing_via_login$(self.config.grove_config, self.id));
    }

    return Promise.all(tasks);
  });
  it("ui__get_app$", function(d) {
    var ui_id = ["ui_001", "ui_002", "ui_003", "ui_004"];
    var count = 0;
    var app_values = [
      { id: 'app1',
        name: 'myapp1',
        //description: undefined,
        path: B.path.join(appbundle_path, '/app1'),
        //main_ui: undefined,
        graphs: [ 'graph_001', 'graph_002' ],
        uis: [ 'ui_001', 'ui_002' ],
        is_builtin: false 
      },
      { id: 'app1',
        name: 'myapp1',
        //description: undefined,
        path: B.path.join(appbundle_path, '/app1'),
        uis: [ 'ui_001', 'ui_002' ],
        //main_ui: undefined,
        graphs: [ 'graph_001', 'graph_002' ],
        is_builtin: false 
      },
      { id: 'app2',
        name: 'myapp2',
        //description: undefined,
        path: B.path.join(appbundle_path, '/app2'),
        //main_ui: undefined,
        graphs: [ 'graph_003', 'graph_004' ],
        uis: [ 'ui_003', 'ui_004' ],
        is_builtin: false
      },
      { id: 'app2',
        name: 'myapp2',
        //description: undefined,
        path: B.path.join(appbundle_path, '/app2'),
        //main_ui: undefined,
        graphs: [ 'graph_003', 'graph_004' ],
        uis: [ 'ui_003', 'ui_004' ],
        is_builtin: false
      }
    ];

    for (var i = 0; i < ui_id.length; i++) {
      (function(index) {
        em.ui__get_app$(ui_id[index]).then(function(v) {
          count++;
          assert.equal(_.isEqual(v, app_values[index]), true);
          if (count === ui_id.length) {
            d();
          }
        }).done();
      })(i);
    }
  });
exports.create$ = function(_center) {
  var id = _center.id + "__built_in_hub__";
  var assemble = B.fs.read_json(B.path.resolve(__dirname, "./built_in_hub.json"));
  assemble.mnode.$params[1].id = id + "__mnode__";
  var hub;
  return Hub.start$({
    id: id, 
    assemble: assemble,
    config_path: B.path.abs("./built_in_hub.json", module.filename)
  }).then(function(objs) {
    hub = objs.hub;
    return hub;
  });
};
Пример #6
0
/**
 * transform the drivers.json and driver_docs.json into a new object whose key is classname.
 * we use its side effect to change the global var: grove_doc
 * @param  {String} rootpath the path which contains the drivers.json and driver_docs.json
 */
function _create_grove_doc (rootpath) {
  var driver_path = B.path.join(rootpath, "drivers.json");
  var drivers = require(driver_path);
  var driver_docs_path = B.path.join(rootpath, "driver_docs.json");
  var driver_docs = require(driver_docs_path);
  B.check(drivers.length == driver_docs.length, "entity/grove_thing", "array length is not equal");
  grove_doc = {};
  for (var i = 0; i < drivers.length; i++) {
    grove_doc[drivers[i].ClassName] = {
      driver:drivers[i],
      doc:driver_docs[i]
    };
  }
}
  it("app__update$", function(d) {
    var app = {
      id: "new_app_1",
      name: "newname!",
      description: "add the description!!"
    };

    var app_new_value = {
     new_app_1: 
      { id: 'new_app_1',
        name: 'newname!',
        path: B.path.join(appbundle_path, '/new_app_1'),
        //main_ui: undefined,
        graphs: [],
        uis: [],
        is_builtin: false,
        description: 'add the description!!' 
      } 
     };

    em.app__update$(app).then(function() {
      assert.equal(_.isEqual(em.app_store.store.db, app_new_value), true);
      d();
    }).done();
  });
 function require_in_sandbox(p) {
   if (_.isString(p) && p.substr(0, 2) !== "./" && p.substr(0, 3) !== "../") {
     return require(p);
   } else {
     return require(B.path.abs(p, base_path, true));
   }
 }
ServiceCache.prototype.create_service_cache_obj = function(service_obj) {
  var service_cache_obj = {};
  service_cache_obj = _.cloneDeep(service_obj);// set the items in service_obj
  service_cache_obj.shared = {};//2, set the service shared object
  service_cache_obj.hub_shared = hub_shared;//3, set the hub shared object
  var scripts = {
    kernel_s: prepare_script(service_cache_obj, "kernel"),
    start_s : prepare_script(service_cache_obj, "start"),
    stop_s : prepare_script(service_cache_obj, "stop"),
    pause_s : prepare_script(service_cache_obj, "pause"),
    resume_s : prepare_script(service_cache_obj, "resume"),
    after_resume_s : prepare_script(service_cache_obj, "after_resume"),
    service_init_s : prepare_script(service_cache_obj, "service_init"),
    service_destroy_s : prepare_script(service_cache_obj, "service_destroy")
  };
  service_cache_obj = _.assign(service_cache_obj, scripts);//4 set the xxxx_s
  service_cache_obj.is_inited = false;//5 not init yet
  //6 prepare the require
  if(service_obj.type === "nodered_service") {
    service_cache_obj.require_in_sandbox = sb.prepare_require(B.path.dir(service_obj.path));
  } else {
    service_cache_obj.require_in_sandbox = sb.prepare_require(service_obj.path);
  }
  return service_cache_obj;
};
  it("app__list_graphs$", function(d) {

    var app1_graphs = [ 
    { id: 'graph_001',
      name: 'mygraph001',
      app: 'app1',
      path: B.path.join(appbundle_path, '/app1/graphs/graph_001.json') 
    },
    { id: 'graph_002',
      name: 'mygraph002',
      app: 'app1',
      path: B.path.join(appbundle_path, '/app1/graphs/graph_002.json') 
    } ];

    var app2_graphs = [ 
    { id: 'graph_003',
      name: 'mygraph003',
      app: 'app2',
      path: B.path.join(appbundle_path, '/app2/graphs/graph_003.json') 
    },
    { id: 'graph_004',
      name: 'mygraph004',
      app: 'app2',
      path: B.path.join(appbundle_path, '/app2/graphs/graph_004.json') 
    }];

    var app_graphs_arr = [app1_graphs, app2_graphs];


    var graphs_of_app_id = ["app1", "app2"];
    var count = 0;
    for (var i = 0; i < graphs_of_app_id.length; i++) {
      (function(index) {
        em.app__list_graphs$(graphs_of_app_id[index]).then(function(v) {
          count++;
          assert.equal(_.isEqual(v, app_graphs_arr[index]), true);
          if (count === graphs_of_app_id.length)
            d();
        }).done(); 
      })(i);
    }
  });
  it("app__list_uis$", function(d) {
    var app1_uis = [ 
    { id: 'ui_001',
      name: 'myui001',
      path: B.path.join(appbundle_path, '/app1/uis/ui_001.json'),
      app: 'app1' 
    },
    { id: 'ui_002',
      name: 'myui002',
      path: B.path.join(appbundle_path, '/app1/uis/ui_002.json'),
      app: 'app1' 
    }];

    var app2_uis = [ 
    { id: 'ui_003',
      name: 'myui003',
      path: B.path.join(appbundle_path, '/app2/uis/ui_003.json'),
      app: 'app2' 
    },
    { id: 'ui_004',
      name: 'myui004',
      path: B.path.join(appbundle_path, '/app2/uis/ui_004.json'),
      app: 'app2' 
    }];

    var app_uis_arr = [app1_uis, app2_uis];
    var uis_of_app_id = ["app1", "app2"];

    var count = 0;
    for (var i = 0; i < uis_of_app_id.length; i++) {
      (function(index) {
        em.app__list_uis$(uis_of_app_id[index]).then(function(v) {
          count++;
          assert.equal(_.isEqual(v, app_uis_arr[index]), true);
          if (count === uis_of_app_id.length)
            d();
        }).done();
      })(i);
    }
  });
Hub.prototype._call_init_script$ = function() {
  var self = this;
  if (_.isUndefined(self.config.init_script_path)) {
    log("no init script");
    return;
  }
  var init_script_path = B.path.abs(self.config.init_script_path, self.config_path);
  if (!B.fs.file_exists(init_script_path)) {
    log.warn("init script not found", init_script_path);
    return;
  }
  log("call init script:", init_script_path);
  return self.sm.run_hub_script$(init_script_path);
};
Hub.prototype._call_destroy_script$ = function() {
  var self = this;
  if (_.isUndefined(self.config.destroy_script_path)) {
    log("no destroy script");
    return;
  }
  var destroy_script_path = B.path.abs(self.config.destroy_script_path, self.config_path);
  if (!B.fs.file_exists(destroy_script_path)) {
    log.warn("destroy script not found", destroy_script_path);
    return;
  }
  log("call destroy script:", destroy_script_path);
  return self.sm.run_hub_script$(destroy_script_path);
};
  it("ui__get$", function(d) {
    var ui_arr = [
      { id: 'ui_001',
        name: 'myui001',
        app: 'app1',
        path: B.path.join(appbundle_path, '/app1/uis/ui_001.json')
      },
      { id: 'ui_002',
        name: 'myui002',
        app: 'app1',
        path: B.path.join(appbundle_path, '/app1/uis/ui_002.json')
      },
      { id: 'ui_003',
        name: 'myui003',
        app: 'app2',
        path: B.path.join(appbundle_path, '/app2/uis/ui_003.json') 
      },
      { id: 'ui_004',
        name: 'myui004',
        app: 'app2',
        path: B.path.join(appbundle_path, '/app2/uis/ui_004.json') 
      }
    ];

    var uis_id = ["ui_001", "ui_002", "ui_003", "ui_004"];
    var count = 0;
    for (var i = 0; i < uis_id.length; i++) {
      (function(index) {
        em.ui__get$(uis_id[index]).then(function(v) {
          count++;
          assert.equal(_.isEqual(v, ui_arr[index]), true);
          if (count === uis_id.length) 
            d();
        }).done();
      })(i);
    }
  });
Пример #15
0
function prepare_require(base_path) {
  var fs = require("fs");
  var fp = B.path.join(base_path, "__temp.js");
  var code = "exports.myrequire = require;";
  fs.writeFileSync(fp, code);
  var ret = require(fp);
  fs.unlinkSync(fp);
  function require_in_sandbox(p) {
    var g = {};
    save_global_prop(g);
    var r = ret.myrequire(p);
    recover_global_prop(g);
    return r;
  }
  return require_in_sandbox;
}
Пример #16
0
FrontEnd.prototype.api_user__register = function(data) {
  B.check(_.isObject(data) && data.name && _.isString(data.passwd),
    "frontend/user_register", "Failed to register for", data);
  var id = B.unique_id("USER_");
  var self = this;

  data.id = id;
  data.appbundle_path = B.path.join(self.center.appbundle_path, id);

  return self.center.em.user__find$(data.name, null).then(function(user) {
    if (user) {
      throw new Error("User name already exists");
    }
    return self.center.em.user__add$(data);
  });
};
Пример #17
0
 }).then(function(spec) {
   return {
     id: self.widget_id_to_service_id(w.id),
     name: "HOPE UI Service for Widget: " + w.name,
     spec: w.spec,
     thing: self.id,
     type: "ui_service",
     path: B.path.abs("../lib/service_templates/ui", module.filename),
     is_connect: true,
     is_ui: true,
     own_spec: false,
     config: {
       widget_id: w.id,
       app_id: self.app_id,
       cache_size: spec && spec.default_cache_size || 10
     }
   };
 });
Пример #18
0
SessionManager.prototype.run_hub_script$ = function(script_path) {
  log("run_hub_script", script_path);
  var fs = require("fs");
  var vm = require("vm");
  var self = this;
  var sandbox = sb.create_hub_sandbox(self.service_cache.hub_shared,
    B.path.resolve(script_path, ".."));
  var context = fs.readFileSync(script_path);
  var func_string = "(function(){\n" + context + "\n})";
  var func_script = new vm.Script(func_string, 
        {filename: script_path + "__wrap"});
  return new Promise(function(resolve, reject) {
    sandbox.done = function(value)
    {
      log("hub script done", script_path);
      sandbox.fail = B.type.func_noop;
      sandbox.done = B.type.func_noop;
      resolve(value);
    };

    sandbox.fail = function(value)
    {
      log.warn("hub script fail", script_path);
      sandbox.done = B.type.func_noop;
      sandbox.fail = B.type.func_noop;
      reject(value);
    };

    sandbox.throwEXC = function(value)
    {
      log.warn("hub script throw exception", value);
      sandbox.fail(value);
    };

    try {
      var f = func_script.runInNewContext(sandbox);
      f();
    } catch(e) {
      log.warn("hub script catch exception", e);
      sandbox.fail(e);
    }
    
  });
};
Пример #19
0
 .then(function() {
   var bundle_json_path = B.path.join(bundle_path, "spec_bundle.json");
   check(B.fs.file_exists(bundle_json_path), "entity/spec", "the bundle json file not exsit", bundle_json_path);
   var bundle_json = B.fs.read_json(bundle_json_path);
   var bundle = _create_local_bundle(bundle_json, bundle_path);
   var spec_path_array = B.fs.find_files(bundle_path, "*.json");
   var tasks = [];
   spec_path_array.forEach(function(p) {
     if (p === bundle_json_path) {
       return;
     }
     log("load_spec", p);
     var spec_json = B.fs.read_json(p);
     var spec = _create_local_spec(spec_json, p, bundle_path, bundle.id);
     bundle.specs.push(spec.id);
     tasks.push(em.spec_store.set$(spec.id, spec, changed_list));
   });
   tasks.push(em.specbundle_store.set$(bundle.id, bundle, changed_list));
   return Promise.all(tasks);
 });
Пример #20
0
function Config(file_path) {
  this.path = B.path.resolve(file_path);
  this.json = B.fs.read_json_with_comments(this.path);
  this.to_assemble = {};
  this.generated_config = {
    assemble: this.to_assemble
  };

  this.enable_log();

  this.parse_basic();

  this.gen_shared();

  if (this.type === "center") {
    this.gen_center_specific();
  } else if (this.type === "hub") {
    this.gen_hub_specific();
  }

}
Пример #21
0
    service_list.forEach(function(item) {
      var service;
      if (item.service_path) {
        var json_path = B.path.join(item.service_path, "service.json");
        service = B.fs.read_json(json_path);
      } else {
        service = item.servicejson;
      }
      B.check(!_.isUndefined(service), "entity/grove_thing", "service json should not be undefined", item);
      var spec = service.spec;
      spec.id = "spec_" + item.class_name + item.service_name;
      spec.specbundle = specbundle_obj.id;
      if (item.service_path) {
        spec.config[0].default = thing_id;
        spec.config[1].default = item.port_name;
      }
      specbundle_obj.specs.push(spec);
      log("prepare spec:", spec);

      service.spec = spec.id;
      service.type = "grove_service";
      service.id = "groveservice_" + item.class_name + item.port_name + item.service_name + thing_id;
      if (item.service_path) {
        service.path = item.service_path;
        service.type = "grove_semiauto_service";
      } else {
        service.type = "grove_auto_service";
        B.check(!_.isUndefined(item.kerneljs), "entity/grove_thing", "grove_auto_service must contain kerneljs", item);
        service.js = {
          kernel: item.kerneljs
        };
      }
      service.is_connect = true;
      service.own_spec = true;
      service.thing = grovething_obj.id;
      grovething_obj.services.push(service);
      log("prepare service:", service);
    });
  it("ui__update$", function(d) {
    var ui = {
      id: "new_ui_1",
      name: "name_modified",
      description: "add description now",
      app: "new_app_1"
    };

    var ui_new_value =  { 
      new_ui_1: 
        { id: 'new_ui_1',
          name: 'name_modified',
          description: 'add description now',
          app: 'new_app_1',
          path: B.path.join(appbundle_path, '/new_app_1/uis/new_ui_1.json') 
        } 
      };

    em.ui__update$(ui).then(function() {
      assert.equal(_.isEqual(em.ui_store.store.db, ui_new_value), true);
      d();
  }).done();
  });
Пример #23
0
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
var ES = require("../../entity-store");
var E = require("../../entity");
var M = require("../../message");
var B = require("hope-base");
var S = require("../../store");
var SM = require("../index");
var log = B.log.for_category("sm_sample");
//create the em, service_store and service_obj
var service_obj = {
  id: "sm_case1",
  name: "case1",
  spec: "no_need",
  thing: "no_need",
  path: B.path.resolve(__dirname, "./case/case1"),
  is_connect: true,
  own_spec: false,
  type: "hope_service"
};
var service_store = ES.create_servicestore("memory");
service_store.set$(service_obj.id, service_obj).done();
var em = E.create_entity_manager({service_store:service_store});


//create mnode
var route_table = M.create_route_table(S.create_store("memory"));
var router = M.create_router(route_table);
var mnode_master = M.create_mnode(router);
var mnode_slave = M.create_mnode(router);
function prepare_script(service_cache_obj, action) {
  var context;
  var func_string;
  var func_script;
  switch (service_cache_obj.type) {
    case "hope_service":
    case "beihai_service":
    case "oic_service":
    case "ui_service":
    case "grove_semiauto_service":
      var filepath = B.path.join(service_cache_obj.path, action + ".js");

      //1. read the content of the file
      if (B.fs.file_exists(filepath)) {
        context = fs.readFileSync(filepath);
      }
      else if (action === "kernel" || action === "after_resume") {
        context = "";
      }
      else {
        context = "done()";
      }

      //2 wrap the function
      if (action === "kernel") {
        func_string = "(function(IN, CONFIG){\n" + context + "\n})";
      }
      else if (action === "service_init" || action === "service_destroy") {
        func_string = "(function(CONFIG){\n" + context + "\n})";
      }
      else {
        func_string = "(function(CONFIG){\n" + context + "\n})";
      }

      //3 new vm.Script
      func_script = new vm.Script(func_string,
        {filename: service_cache_obj.path + "__" + action});
      return func_script;
    case "grove_auto_service":

      //1. read the content of the prop in service_cache_obj
      if (!_.isUndefined(service_cache_obj.js[action])) {
        context = service_cache_obj.js[action];
      }
      else if (action === "kernel" || action === "after_resume") {
        context = "";
      }
      else {
        context = "done()";
      }

      //2 wrap the function
      if (action === "kernel") {
        func_string = "(function(IN, CONFIG){\n" + context + "\n})";
      }
      else if (action === "service_init" || action === "service_destroy") {
        func_string = "(function(CONFIG){\n" + context + "\n})";
      }
      else {
        func_string = "(function(CONFIG){\n" + context + "\n})";
      }

      //3 new vm.Script
      func_script = new vm.Script(func_string,
        {filename: service_cache_obj.path + "__" + action});
      return func_script;
    case "nodered_service":
      if (action === "after_resume") {
        context = "if (CONFIG._nr.category !== 'config') {\n" +
                  " var f = require('" + service_cache_obj.path.replace(/\\/g, "\\\\") + "');\n" +
                  " __nodered.sendOUT = sendOUT;\n" +
                  " __nodered.sendERR = sendERR;\n" +
                  " __nodered.id = CONFIG._nr.id;\n" +
                  " f(__nodered.RED);\n" +
                  " __nodered.node = new __nodered['Type_' + CONFIG._nr.type](CONFIG);\n" +
                  " hub_shared.__nodered_nodes[CONFIG._nr.id] = __nodered.node;\n" +
                  "};";
        func_string = "(function(CONFIG){\n" + context + "\n})";
      } else if (action === "resume") {
        context = "if (CONFIG._nr.category === 'config') {\n" +
                  " var f = require('" + service_cache_obj.path.replace(/\\/g, "\\\\") + "');\n" +
                  " __nodered.sendOUT = function(){};\n" +
                  " __nodered.sendERR = function(){};\n" +
                  " __nodered.id = CONFIG._nr.id;\n" +
                  " f(__nodered.RED);\n" +
                  " __nodered.node = new __nodered['Type_' + CONFIG._nr.type](CONFIG);\n" +
                  " hub_shared.__nodered_nodes[CONFIG._nr.id] = __nodered.node;\n" +
                  "};\n" +
                  "done();";
        func_string = "(function(CONFIG){\n" + context + "\n})";
      } else if (action === "kernel") {
        func_string = "(function(IN, CONFIG){\n" +
                          "__nodered.sendOUT = sendOUT;\n" +
                          "__nodered.sendERR = sendERR;\n" +
                          "__nodered.node.receive(IN.in1);\n" +
                      "})";
      } else if (action === "pause") {
        func_string = "(function(CONFIG){ Promise.resolve(__nodered.node.close()).then(function(){__nodered.node.afterclose();done();});})";
      } else {
        func_string = "(function(CONFIG){ done() })";
      }
      func_script = new vm.Script(func_string,
        {filename: service_cache_obj.path + "__" + action});
      return func_script;
    default:
      check(false, "sm", "not support the service type:", service_cache_obj.type);
  }
}
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
var B = require("hope-base");
var chai = require("chai");
var spawn = require("child_process").spawn;
var fork = require("child_process").fork;
var Center = require("../index");
var _ = require("lodash");
chai.should();

var broker_child;
var config_path = B.path.abs("../samples/config.json", __filename);
var broker_file = B.path.abs("../start_http_broker.js", __filename);
var hub_exe =  B.path.abs("../../hub/hub", __filename);
var hub_config_path = B.path.abs("../../hub/samples/config.json", __filename);
var config = B.fs.read_json(config_path);

describe("basic_connection >", function() {


  this.timeout(50000);
  function open_broker(d) {
    broker_child = spawn("node", [broker_file]);
    setTimeout(d, 1000);
  }
  
  function close_broker(d) {
describe("spec", function() {
	//create spec_store, specbundle_store
	var specstore;
	var specbundlestore;
	var em;

	before("create_entity_manager", function(d) {
		ES.create_specstore$("memory").then(function(obj1) {
			specstore = obj1;
			return ES.create_specbundlestore$("memory");
		}).then(function(obj2) {
			specbundlestore = obj2;
			em = E.create_entity_manager({
				spec_store:specstore, 
				specbundle_store:specbundlestore
			});
			d();
		}).done();
	});


	var specbundle_path = B.path.join(__dirname, "./spec_bundle");


	var spec1 = 
	{ 
		id: 'spec1',
		name: 'spec1 in myspec1',
		path: '/home/myuser/hope/entity/test/spec_bundle/myspec1/spec1.json',
		specbundle: 'specbundle01' 
	};

	var spec2 = 
	{ 
		id: 'spec2',
		name: 'spec2 in myspec1',
		path: '/home/myuser/hope/entity/test/spec_bundle/myspec1/spec2.json',
		specbundle: 'specbundle01' 
	};

	var spec3 = 
	{
		id: 'spec3',
		name: 'spec3 in myspec2',
		path: '/home/myuser/hope/entity/test/spec_bundle/myspec2/spec3.json',
		specbundle: 'specbundle01'
	};

	var spec4 = 
	{
		id: 'spec4',
		name: 'spec4 in myspec2',
		path: '/home/myuser/hope/entity/test/spec_bundle/myspec2/spec4.json',
		specbundle: 'specbundle01' 
	};

	var specbundle01 = 
	{ 
		id: 'specbundle01',
		name: 'spec_bundle',
		specs: [ 'spec1', 'spec2', 'spec3', 'spec4' ],
		path: '/home/myuser/hope/entity/test/spec_bundle' 
	};

	it("spec__load_from_localbundle$", function(d) {
		var specbundle_in_store = { 
			specbundle01: specbundle01
		};

		
		var spec_in_store = { 
			spec1:  spec1,
			spec2:  spec2,
			spec3:  spec3,
			spec4:  spec4	
		};


		em.spec__load_from_localbundle$(specbundle_path).then(function() {
			assert.equal(_.isEqual(em.specbundle_store.store.db, specbundle_in_store), true);
			assert.equal(_.isEqual(em.spec_store.store.db, spec_in_store), true);
			d();
		}).done();
	});

	it("spec__get$", function(d) {
		var count = 0;
		var spec_arr = ["spec1", "spec2", "spec3", "spec4"];
		var spec_arr_value = [spec1, spec2, spec3, spec4];

		for (var i = 0; i < spec_arr.length; i++) {
			(function(index) {
				em.spec__get$(spec_arr[index]).then(function(v) {
					count++;
					assert.equal(_.isEqual(v, spec_arr_value[index]), true);
					if (count == spec_arr.length)
						d();
				}).done();
			})(i);
		}
	});

	it("spec__list$", function(d) {
		var max_length = 2;
		var spec_list_value = ["spec1", "spec2", "spec3", "spec4"];
		if (max_length > spec_list_value.length)
			max_length = spec_list_value.length;

		em.spec__list$(max_length).then(function(v) {
			assert.equal(_.isEqual(v, spec_list_value.slice(0, max_length)), true);
			d();
		}).done();
	});

	it("spec__get_specbundle$", function(d) {
		em.spec__get_specbundle$("spec1").then(function(v) {
			assert.equal(_.isEqual(v, specbundle01), true);
			d();
		}).done();

	});

	it("specbundle__get$", function(d) {
		var specbundle_id_arr = ["specbundle01"];
		var specbundle_arr = [specbundle01];
		var count = 0;

		for (var i = 0; i < specbundle_id_arr.length; i++) {
			(function(index) {
				em.specbundle__get$(specbundle_id_arr[index]).then(function(v) {
					count++;
					assert.equal(_.isEqual(v, specbundle_arr[index]), true);
					if (count == specbundle_id_arr.length)
						d();
				}).done();
			})(i);
		}
	});

	it("specbundle__list$", function(d) {
		var max_length = 2;
		var specbundle_list_value = [specbundle01];
		if (max_length > specbundle_list_value.length)
			max_length = specbundle_list_value.length;
		em.specbundle__list$(max_length).then(function(v) {
			assert.equal(_.isEqual(v, specbundle_list_value.slice(0, max_length)), true);
			d();
		}).done();
	});

	it("specbundle__list_specs$", function(d) {
		var specbundle_id_arr = ["specbundle01"];
		var specbundle_list_specs_value = [[spec1, spec2, spec3, spec4]];
		var count = 0;

		for (var i = 0; i < specbundle_id_arr.length; i++) {
			(function(index) {
				em.specbundle__list_specs$(specbundle_id_arr[index]).then(function(v) {
					count++;
					assert.equal(_.isEqual(v, specbundle_list_specs_value[index]), true);
					if (count == specbundle_id_arr.length)
						d();
				}).done();
			})(i);
		}
	});
});
/*eslint no-console:0*/
var B = require("hope-base");
var E = require("../index");
var ES = require("../../entity-store");


var appstore = ES.create_appstore("memory");
var graphstore = ES.create_graphstore("memory");
var uistore = ES.create_uistore("memory");
var em = E.create_entity_manager({
  app_store:appstore,
  graph_store:graphstore,
  ui_store:uistore
});

var appbundlepath = B.path.join(__dirname, "./appbundle");

em.app__load_from_bundle$(appbundlepath)
.then(function(list) {
  console.log("==== load bundle ===");
  console.log("[changed_list]", list);
  console.log("[app_store]:", em.app_store.store.db);
  console.log("[graph_store]:", em.graph_store.store.db);
  console.log("[ui_store]:", em.ui_store.store.db);
  console.log("=============\n\n");
}).done(); // 2 apps and 4 graphs

setTimeout(function add_graph() {
  var graph = {
    id: "new_graph_1",
    name: "newgraph1",
 mnode.define_rpc("add_hope_thing", function(thing) {
   return self.em.thing__add_hope_thing$(thing, B.path.abs(self.config.thingbundle_path, self.config_path))
   .then(function(data) {
     return self._prepare_emchanged_data(data);
   });
 });
//----------------------------------------------------------------
// Get all port impls registered first
//----------------------------------------------------------------
var Port = require("./lib/port");

function register_port_impl_file(impl_name, file_path) {
  var impl = require(file_path);
  ["accept", "subscribe", "send", "publish"].forEach(function(type) {
    if (_.isFunction(impl[type])) {
      Port.register_impl(type, impl_name, impl[type]);
    }
  });
}

B.fs.ls(B.path.dir(module.filename) + "/lib/impl_ports")
  .files(".js").each(function(name, fp, base) {
    register_port_impl_file(base, fp);
  });



var MNode = require("./lib/mnode");
var Route = require("./lib/router");
var RouteTable = require("./lib/route_table");
var RouteRule = require("./lib/route_rule");


exports.create_mnode = MNode.create;

exports.create_router = Route.create;
  ui_store:uistore
});

var hub = {
  id: "hub1",
  name: "hub in sample",
  mnode: "no need",
  things: []
};

var specbundle = {
  name: "public specbundle in hub1",
  id: "public_specbundle1"
};

var thingbundle_path = B.path.join(__dirname, "./thingbundle");

em.hub_store.set$(hub.id, hub)
.then(function() {
  return em.thing__load_from_bundle$(thingbundle_path, specbundle, "hub1");
})
.then(function(list) {
  console.log("========= load from bundle =======");
  console.log("[changed_list]", list);
  console.log("[specbundle]:", em.specbundle_store.store.db);
  console.log("[spec]:", em.spec_store.store.db);
  console.log("[hub]:", em.hub_store.store.db);
  console.log("[thing]:", em.thing_store.store.db);
  console.log("[service]:", em.service_store.store.db);
}).done();