Example #1
0
Notebook::Notebook() {
    pugi::xml_node note = XmlInterface::get()->GetDocument()->child("Configuration").child("Notebook");

    file_name_ = std::string(note.attribute("file").as_string());
    mode_ = std::string(note.attribute("mode").as_string("a"));

    Messenger m;
    m.detail("Notebook: " + file_name_ + " mode: " + mode_);

    std::ofstream note_file;

    if (mode_ == "r") {
        note_file.open(file_name_.c_str(), std::ios::out);
    } else if (mode_ == "a") {
        note_file.open(file_name_.c_str(), std::ios::out | std::ios::app);
    } else {
        std::stringstream ss;
        ss << "Notebook: unknown mode";
        ss << " : " << mode_;
        throw IOException(ss.str());
    }

    if (!note_file.good()) {
        std::stringstream ss;
        ss << "Notebook: error opening output file";
        ss << " : " << file_name_;
        throw IOException(ss.str());
    }
    note_file << "# Starting notebook on : " << currentDateTime() << std::endl;
    note_file.close();
}
Example #2
0
void DetectorDriver::Init(RawEvent& rawev) {
    for (vector<TraceAnalyzer *>::iterator it = vecAnalyzer.begin();
	 it != vecAnalyzer.end(); it++) {
        (*it)->Init();
        (*it)->SetLevel(20);
    }

    for (vector<EventProcessor *>::iterator it = vecProcess.begin();
         it != vecProcess.end(); it++) {
        (*it)->Init(rawev);
    }

    try {
        ReadCalXml();
        ReadWalkXml();
    } catch (GeneralException &e) {
        //! Any exception in reading calibration and walk correction
        //! will be intercepted here
        cout << endl;
        cout << "Exception caught at DetectorDriver::Init" << endl;
        cout << "\t" << e.what() << endl;
        Messenger m;
        m.fail();
        exit(EXIT_FAILURE);
    } catch (GeneralWarning &w) {
        cout << "Warning caught at DetectorDriver::Init" << endl;
        cout << "\t" << w.what() << endl;
    }
}
static void userAddTest(Node& node, TestRunner& tr)
{
   tr.group("user add");

   Messenger* messenger = node.getMessenger();

   tr.test("add (valid)");
   {
      Url url("/api/3.0/users");

      // password update
      User user;
      user["email"] = "*****@*****.**";
      user["username"] = "******";
      user["password"] = "******";
      user["confirm"] = "password";
      user["tosAgree"] = "agree";

      assertNoException(
         messenger->postSecureToBitmunk(
            &url, &user, NULL, node.getDefaultUserId()));

      printf("\nUser added.\n");
   }
   tr.passIfNoException();

   tr.ungroup();
}
void DownloadStateEventReactor::directiveCreated(Event& e)
{
   UserId userId = BM_USER_ID(e["details"]["userId"]);
   const char* directiveId = e["details"]["directiveId"]->getString();

   MO_CAT_DEBUG(BM_EVENTREACTOR_DS_CAT,
      "Event reactor handling 'directiveCreated' event for user %" PRIu64 "...",
      userId);

   // process the directive if it is of type "peerbuy":
   DynamicObject& directive = e["details"]["directive"];
   if(strcmp(directive["type"]->getString(), "peerbuy") == 0)
   {
      Messenger* messenger = mNode->getMessenger();

      Url url;
      url.format("%s/api/3.0/system/directives/process/%s?nodeuser=%" PRIu64,
         messenger->getSelfUrl(true).c_str(), directiveId, userId);

      DynamicObject in;
      if(!messenger->post(&url, NULL, &in, userId))
      {
         // schedule exception event
         Event e2;
         e2["type"] = "bitmunk.eventreactor.EventReactor.exception";
         e2["details"]["userId"] = userId;
         e2["details"]["exception"] = Exception::getAsDynamicObject();
         mNode->getEventController()->schedule(e2);
      }
   }
}
Example #5
0
void onMessage() {
	char op = 0;
	op = msg.readChar();
	// s - set color, f - fade to color
	if (op == 's' || op == 'f') {
		int red = msg.readInt();
		int green = msg.readInt();
		int blue = msg.readInt();
		if (op == 'f') {
			fade_to_color(red, green, blue);
		} else if (op == 's') {
			set_color(red, green, blue);
		}
		String color = "colorChange " + String(red) + " " + String(green) + " "
				+ String(blue) + "\n";
		serial.print(color);
	}
	// q - query color
	else if (op == 'q') {
		String color = "currentColor " + String(get_red()) + " " + String(
				get_green()) + " " + String(get_blue()) + "\n";
		serial.print(color);
	} else {
		serial.print("Unknown command.");
		serial.print(op);
		serial.print("\n");
	}
}
Example #6
0
void Globals::SanityCheck() {
    Messenger m;
    std::stringstream ss;

    if (!(revision_ == "A" || revision_ == "D" || revision_ == "F")) {
        ss << "Globals: unknown revision version named "
           << revision_;
        throw GeneralException(ss.str());
    }

    if (clockInSeconds_ <= 0) {
        ss << "Globals: illegal value of clockInSeconds "
            << clockInSeconds_;
        throw GeneralException(ss.str());
    }

    if (adcClockInSeconds_ <= 0) {
        ss << "Globals: illegal value of adcClockInSeconds "
            << adcClockInSeconds_;
        throw GeneralException(ss.str());
    }

    if (filterClockInSeconds_ <= 0) {
        ss << "Globals: illegal value of filterClockInSeconds "
            << filterClockInSeconds_;
        throw GeneralException(ss.str());
    }

    if (eventInSeconds_ <= 0) {
        ss << "Globals: illegal value of eventInSeconds "
            << eventInSeconds_;
        throw GeneralException(ss.str());
    }

    if (hasReject_) {
        ss << "Total number of rejection regions: " << reject_.size();
        m.detail(ss.str());
    } else {
        ss << "Not using rejection regions";
        m.detail(ss.str());
    }

    ss.str("");
    if (energyContraction_ <= 0) {
        ss << "Globals: Surely you don't want to use Energy contraction = "
            << energyContraction_ << ". I'd better stop the program.";
        throw GeneralException(ss.str());
    } else {
        ss << "Energy contraction: " << energyContraction_;
        m.detail(ss.str());
    }

    m.done();
}
Example #7
0
void TreeCorrelator::createPlace(std::map<std::string, std::string>& params,
                                 bool verbose) {
    bool replace = false;
    if (params["replace"] != "")
        replace = strings::to_bool(params["replace"]);

    vector<string> names = split_names(params["name"]);
    for (vector<string>::iterator it = names.begin();
         it != names.end();
         ++it) {

        if (params["type"] != "") {
            if (replace) {
                if (places_.count((*it)) != 1) {
                    stringstream ss;
                    ss << "TreeCorrelator: cannot replace Place " << (*it)
                       << ", it doesn't exist";
                    throw TreeCorrelatorException(ss.str());
                }
                delete places_[(*it)];
                if (verbose) {
                    Messenger m;
                    stringstream ss;
                    ss << "Replacing place " << (*it);
                    m.detail(ss.str(), 1);
                }
            } else {
                if (places_.count((*it)) == 1) {
                    stringstream ss;
                    ss << "TreeCorrelator: place" << (*it) << " already exists";
                    throw TreeCorrelatorException(ss.str());
                }
                if (verbose) {
                    Messenger m;
                    stringstream ss;
                    ss << "Creating place " << (*it);
                    m.detail(ss.str(), 1);
                }
            }
            Place* current = builder.create(params, verbose);
            places_[(*it)] = current;
            if (strings::to_bool(params["init"]))
                current->activate(0.0);
        }

        if (params["parent"] != "root") {
            bool coincidence = strings::to_bool(params["coincidence"]);
            addChild(params["parent"], (*it), coincidence, verbose);
        }

    }
}
static void contributorGetTest(Node& node, TestRunner& tr)
{
   tr.group("contributors");

   Messenger* messenger = node.getMessenger();

   tr.test("id");
   {
      Url url("/api/3.0/contributors/1");

      // get contributor
      DynamicObject contributor;
      assertNoException(
         messenger->getFromBitmunk(&url, contributor));

      printf("\nContributor:\n");
      dumpDynamicObject(contributor, false);
   }
   tr.passIfNoException();

   tr.test("owner");
   {
      Url url("/api/3.0/contributors/?owner=900");

      // get contributor
      DynamicObject contributors;
      assertNoException(
         messenger->getFromBitmunk(&url, contributors));

      printf("\nContributors:\n");
      dumpDynamicObject(contributors, false);
   }
   tr.passIfNoException();

   tr.test("media");
   {
      Url url("/api/3.0/contributors/?media=1");

      // get contributor
      DynamicObject contributors;
      assertNoException(
         messenger->getFromBitmunk(&url, contributors));

      printf("\nContributors:\n");
      dumpDynamicObject(contributors, false);
   }
   tr.passIfNoException();

   tr.ungroup();
}
Example #9
0
static int l_Messenger_retrieveMessages(lua_State *L) {
    Messenger* messenger = nullptr;
    if (lua_hasMessenger(L)) {
	messenger = lua_getMessenger(L);
    }
    else {
	luaL_error(L, "Messenger has not been registered in lua");
    }
    auto messageVector = messenger->retrieveMessages();
    lua_newtable(L);
    int index = 1;
    for (auto msg : messageVector) {
	lua_pushmessage(L, &msg);
	lua_rawseti(L, -1, index++);
    }
    return 1;
}
Example #10
0
void TreeCorrelator::addChild(std::string parent, std::string child,
                             bool coin, bool verbose) {
    if (places_.count(parent) == 1 && places_.count(child) == 1) {
        place(parent)->addChild(place(child), coin);
        if (verbose) {
            Messenger m;
            stringstream ss;
            ss << "Setting " << child
                 << " as a child of " << parent;
            m.detail(ss.str(), 1);
        }
    } else {
        stringstream ss;
        ss << "TreeCorrelator: could not set " << child
           << " as a child of " << parent << endl;
        throw TreeCorrelatorException(ss.str());
    }
}
static void pingPerfTest(Node& node, TestRunner& tr)
{
   tr.group("ping perf");

   Messenger* messenger = node.getMessenger();

   // number of loops for each test
   Config cfg = tr.getApp()->getConfig();
   //node.getConfigManager()->getConfig(
   //   tester->getApp()->getMetaConfig()["groups"]["main"]->getString());
   int n = cfg->hasMember("loops") ? cfg["loops"]->getInt32() : 50;

   tr.test("insecure get");
   {
      Url url("/api/3.0/system/test/ping");

      DynamicObject dummy;
      uint64_t startTime = Timer::startTiming();
      for(int i = 0; i < n; ++i)
      {
         messenger->getFromBitmunk(&url, dummy);
      }
      double dt = Timer::getSeconds(startTime);
      printf("t=%g ms, r=%g ms, r/s=%g",  dt * 1000.0, dt/n * 1000.0, n/dt);
   }
   tr.passIfNoException();

   tr.test("secure get");
   {
      Url url("/api/3.0/system/test/ping");

      DynamicObject dummy;
      uint64_t startTime = Timer::startTiming();
      for(int i = 0; i < n; ++i)
      {
         messenger->getSecureFromBitmunk(&url, dummy, node.getDefaultUserId());
      }
      double dt = Timer::getSeconds(startTime);
      printf("t=%g ms, r=%g ms, r/s=%g",  dt * 1000.0, dt/n * 1000.0, n/dt);
   }
   tr.passIfNoException();

   tr.ungroup();
}
Example #12
0
DetectorDriver::DetectorDriver() : histo(OFFSET, RANGE, "DetectorDriver") {
    Messenger m;
    try {
        m.start("Loading Processors");
        LoadProcessors(m);
    } catch (GeneralException &e) {
        /// Any exception in registering plots in Processors
        /// and possible other exceptions in creating Processors
        /// will be intercepted here
        m.fail();
        cout << "Exception caught at DetectorDriver::DetectorDriver" << endl;
        cout << "\t" << e.what() << endl;
        exit(EXIT_FAILURE);
    } catch (GeneralWarning &w) {
        cout << "Warning found at DetectorDriver::DetectorDriver" << endl;
        cout << "\t" << w.what() << endl;
    }
    m.done();
}
Example #13
0
static bool _doReverseNetTest(
   Node* node, Config& cfg, UserId userId, const char* token,
   string& serverUrl)
{
   bool rval = false;

   // start creating public server URL
   serverUrl = "https://";

   // setup post data, use blank host to indicate to the reverse netaccess
   // service that our public IP should be used in the netaccess test
   // use a 15 seconds timeout in waiting for a response
   DynamicObject out;
   out["host"] = "";
   out["port"] = cfg["port"];
   out["path"] = "/api/3.0/catalog/netaccess/test";
   out["sellerId"] = userId;
   out["token"] = token;
   out["timeout"] = 15;

   DynamicObject in;

   // post to bitmunk
   Url url;
   url.format("/api/3.0/catalog/netaccess/rtest");
   Messenger* m = node->getMessenger();
   if(m->postSecureToBitmunk(&url, &out, &in, userId))
   {
      rval = true;
      serverUrl.append(in["ip"]->getString());
      serverUrl.push_back(':');
      serverUrl.append(cfg["port"]->getString());

      // send event
      Event ev;
      ev["type"] = EVENT_NET_ACCESS_SUCCESS;
      ev["details"]["userId"] = userId;
      ev["details"]["serverUrl"] = serverUrl.c_str();
      node->getEventController()->schedule(ev);
   }

   return rval;
}
static void accountGetPerfTest(Node& node, TestRunner& tr)
{
   tr.group("accounts perf");

   Messenger* messenger = node.getMessenger();

   // number of loops
   int n = 25;

   tr.test("insecure get");
   {
      Url url("/api/3.0/accounts/?owner=900");

      uint64_t startTime = Timer::startTiming();
      for(int i = 0; i < n; ++i)
      {
         User user;
         messenger->getFromBitmunk(&url, user);
      }
      double dt = Timer::getSeconds(startTime);
      printf("t=%g ms, r=%g ms, r/s=%g",  dt * 1000.0, dt/n * 1000.0, n/dt);
   }
   tr.passIfNoException();

   tr.test("secure get");
   {
      Url url("/api/3.0/accounts/?owner=900");

      uint64_t startTime = Timer::startTiming();
      for(int i = 0; i < n; ++i)
      {
         User user;
         messenger->getFromBitmunk(&url, user, node.getDefaultUserId());
      }
      double dt = Timer::getSeconds(startTime);
      printf("t=%g ms, r=%g ms, r/s=%g",  dt * 1000.0, dt/n * 1000.0, n/dt);
   }
   tr.passIfNoException();

   tr.ungroup();
}
static void accountGetTest(Node& node, TestRunner& tr)
{
   tr.group("accounts");

   Messenger* messenger = node.getMessenger();

   tr.test("get");
   {
      Url url("/api/3.0/accounts/?owner=900");

      // get all accounts
      User user;
      messenger->getSecureFromBitmunk(&url, user, node.getDefaultUserId());
      printf("\nAccounts:\n");
      dumpDynamicObject(user);
   }
   tr.passIfNoException();

   tr.ungroup();

   tr.group("account");

   tr.test("get");
   {
      // create url for obtaining users
      Url url("/api/3.0/accounts/9000");

      // get account
      Account account;
      assertNoException(
         messenger->getSecureFromBitmunk(
            &url, account, node.getDefaultUserId()));

      printf("\nAccount:\n");
      dumpDynamicObject(account, false);
   }
   tr.passIfNoException();

   tr.ungroup();
}
static void reviewGetTest(Node& node, TestRunner& tr)
{
   tr.group("reviews");

   Messenger* messenger = node.getMessenger();

   tr.test("user get");
   {
      // create url for obtaining user reviews
      Url url("/api/3.0/reviews/user/900");

      // get account
      DynamicObject reviews;
      assertNoException(
         messenger->getSecureFromBitmunk(
            &url, reviews, node.getDefaultUserId()));

      printf("\nReviews:\n");
      dumpDynamicObject(reviews, false);
   }
   tr.passIfNoException();

   tr.test("media get");
   {
      // create url for obtaining media reviews
      Url url("/api/3.0/reviews/media/1");

      // get account
      DynamicObject reviews;
      assertNoException(
         messenger->getSecureFromBitmunk(
            &url, reviews, node.getDefaultUserId()));

      printf("\nReviews:\n");
      dumpDynamicObject(reviews, false);
   }
   tr.passIfNoException();

   tr.ungroup();
}
Example #17
0
int main(int argc, char* argv[]){
	int rosargc = 1;
	ros::init(rosargc, argv, "flying_drum_machine");
	ros::Time::init();
	ros::Rate r(Global::rate);
	
	Messenger* messenger = new Messenger();
	DrumMachine* dm = new DrumMachine(messenger);
	
	signal(SIGINT, [](int signum) {
		std::cout << "\nDrum machine shutdown" << std::endl;
		quit = true;
	});
	
	
	// In case we need to reset after emergency landing or crash
	messenger->sendToggleState();
	
	// Calibrate the IMU and flat trim
//	ros::service::call("ardrone/flattrim");
//	ros::service::call("ardrone/imu_recalib");
	
	while(!quit){
		ros::spinOnce();
		dm->execute();
		r.sleep();
	}

	// Send a hover command
	messenger->sendControlToDrone(ControlCommand());
	
	// Land
	messenger->sendLand();

	delete messenger;
	delete dm;

	return 0;
}
void DownloadStateEventReactor::postDownloadStateId(
   UserId userId, DownloadStateId dsId, const char* action)
{
   Messenger* messenger = mNode->getMessenger();

   Url url;
   url.format("%s/api/3.0/purchase/contracts/%s?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), action, userId);

   DynamicObject out;
   out["downloadStateId"] = dsId;
   if(!messenger->post(&url, &out, NULL, userId))
   {
      // schedule exception event
      Event e2;
      e2["type"] = "bitmunk.eventreactor.EventReactor.exception";
      BM_ID_SET(e2["details"]["userId"], userId);
      e2["details"]["downloadStateId"] = dsId;
      e2["details"]["exception"] = Exception::getAsDynamicObject();
      mNode->getEventController()->schedule(e2);
   }
}
Example #19
0
void TreeCorrelator::buildTree() {
    pugi::xml_document doc;

    Messenger m;
    m.start("Creating TreeCorrelator");
    pugi::xml_parse_result result = doc.load_file("Config.xml");
    if (!result) {
        stringstream ss;
        ss << "DetectorDriver: error parsing file Config.xml";
        ss << " : " << result.description();
        m.fail();
        throw IOException(ss.str());
    }

    pugi::xml_node tree = doc.child("Configuration").child("TreeCorrelator");
    bool verbose = tree.attribute("verbose").as_bool(false);

    Walker walker;
    walker.traverseTree(tree, string(tree.attribute("name").value()), verbose);

    m.done();
}
static void permissionGetTest(Node& node, TestRunner& tr)
{
   tr.group("permissions");

   Messenger* messenger = node.getMessenger();

   tr.test("group get");
   {
      // create url for obtaining permission group information
      Url url("/api/3.0/permissions/100");

      // get permission group
      PermissionGroup group;
      assertNoException(
         messenger->getFromBitmunk(&url, group));

      printf("\nGroup:\n");
      dumpDynamicObject(group, false);
   }
   tr.passIfNoException();

   tr.ungroup();
}
static void acquireLicenseTest(Node& node, TestRunner& tr)
{
   tr.group("media license");

   Messenger* messenger = node.getMessenger();

   tr.test("acquire signed media");
   {
      // create url for obtaining media license
      Url url("/api/3.0/sva/contracts/media/2");

      // get signed media
      Media media;
      assertNoException(
         messenger->postSecureToBitmunk(
            &url, NULL, &media, node.getDefaultUserId()));

      printf("\nSigned Media:\n");
      dumpDynamicObject(media, false);
   }
   tr.passIfNoException();

   tr.ungroup();
}
Example #22
0
DetectorSummary *RawEvent::GetSummary(const std::string &s, bool construct) {
    map<string, DetectorSummary>::iterator it = sumMap.find(s);
    static set <string> nullSummaries;

    Messenger m;
    stringstream ss;
    if (it == sumMap.end()) {
        if (construct) {
            // construct the summary
            ss << "Constructing detector summary for type " << s;
            m.detail(ss.str());
            sumMap.insert(make_pair(s, DetectorSummary(s, eventList)));
            it = sumMap.find(s);
        } else {
            if (nullSummaries.count(s) == 0) {
                ss << "Returning NULL detector summary for type " << s;
                m.detail(ss.str());
                nullSummaries.insert(s);
            }
            return NULL;
        }
    }
    return &(it->second);
}
Example #23
0
void DetectorDriver::LoadProcessors(Messenger& m) {
    pugi::xml_document doc;
    pugi::xml_parse_result result = doc.load_file("Config.xml");
    if (!result) {
        stringstream ss;
        ss << "DetectorDriver: error parsing file Config.xml";
        ss << " : " << result.description();
        throw IOException(ss.str());
    }

    DetectorLibrary::get();

    pugi::xml_node driver = doc.child("Configuration").child("DetectorDriver");
    for (pugi::xml_node processor = driver.child("Processor"); processor;
        processor = processor.next_sibling("Processor")) {
        string name = processor.attribute("name").value();

        m.detail("Loading " + name);
        if (name == "BetaScintProcessor") {
            double gamma_beta_limit =
                processor.attribute("gamma_beta_limit").as_double(200.e-9);
            if (gamma_beta_limit == 200.e-9)
                m.warning("Using default gamme_beta_limit = 200e-9", 1);
            double energy_contraction =
                processor.attribute("energy_contraction").as_double(1.0);
            if (energy_contraction == 1)
                m.warning("Using default energy contraction = 1", 1);
            vecProcess.push_back(new BetaScintProcessor(gamma_beta_limit,
                                                        energy_contraction));
        } else if (name == "GeProcessor") {
            double gamma_threshold =
                processor.attribute("gamma_threshold").as_double(1.0);
            if (gamma_threshold == 1.0)
                m.warning("Using default gamma_threshold = 1.0", 1);
            double low_ratio =
                processor.attribute("low_ratio").as_double(1.0);
            if (low_ratio == 1.0)
                m.warning("Using default low_ratio = 1.0", 1);
            double high_ratio =
                processor.attribute("high_ratio").as_double(3.0);
            if (high_ratio == 3.0)
                m.warning("Using default high_ratio = 3.0", 1);
            double sub_event =
                processor.attribute("sub_event").as_double(100.e-9);
            if (sub_event == 100.e-9)
                m.warning("Using default sub_event = 100e-9", 1);
            double gamma_beta_limit =
                processor.attribute("gamma_beta_limit").as_double(200.e-9);
            if (gamma_beta_limit == 200.e-9)
                m.warning("Using default gamme_beta_limit = 200e-9", 1);
            double gamma_gamma_limit =
                processor.attribute("gamma_gamma_limit").as_double(200.e-9);
            if (gamma_gamma_limit == 200.e-9)
                m.warning("Using default gamma_gamma_limit = 200e-9", 1);
            double cycle_gate1_min =
                processor.attribute("cycle_gate1_min").as_double(0.0);
            if (cycle_gate1_min == 0.0)
                m.warning("Using default cycle_gate1_min = 0.0", 1);
            double cycle_gate1_max =
                processor.attribute("cycle_gate1_max").as_double(0.0);
            if (cycle_gate1_max == 0.0)
                m.warning("Using default cycle_gate1_max = 0.0", 1);
            double cycle_gate2_min =
                processor.attribute("cycle_gate2_min").as_double(0.0);
            if (cycle_gate2_min == 0.0)
                m.warning("Using default cycle_gate2_min = 0.0", 1);
            double cycle_gate2_max =
                processor.attribute("cycle_gate2_max").as_double(0.0);
            if (cycle_gate2_max == 0.0)
                m.warning("Using default cycle_gate2_max = 0.0", 1);
            vecProcess.push_back(new GeProcessor(gamma_threshold, low_ratio,
                high_ratio, sub_event, gamma_beta_limit, gamma_gamma_limit,
                cycle_gate1_min, cycle_gate1_max, cycle_gate2_min,
                cycle_gate2_max));
        } else if (name == "GeCalibProcessor") {
            double gamma_threshold =
                processor.attribute("gamma_threshold").as_double(1);
            double low_ratio =
                processor.attribute("low_ratio").as_double(1);
            double high_ratio =
                processor.attribute("high_ratio").as_double(3);
            vecProcess.push_back(new GeCalibProcessor(gamma_threshold,
                low_ratio, high_ratio));
        } else if (name == "Hen3Processor") {
            vecProcess.push_back(new Hen3Processor());
        } else if (name == "IonChamberProcessor") {
            vecProcess.push_back(new IonChamberProcessor());
        } else if (name == "LiquidScintProcessor") {
            vecProcess.push_back(new LiquidScintProcessor());
        } else if (name == "LogicProcessor") {
            vecProcess.push_back(new LogicProcessor());
        } else if (name == "NeutronScintProcessor") {
            vecProcess.push_back(new NeutronScintProcessor());
        } else if (name == "PositionProcessor") {
            vecProcess.push_back(new PositionProcessor());
        } else if (name == "PulserProcessor") {
            vecProcess.push_back(new PulserProcessor());
        } else if (name == "SsdProcessor") {
            vecProcess.push_back(new SsdProcessor());
        } else if (name == "VandleProcessor") {
            double res = processor.attribute("res").as_double(2.0);
            double offset = processor.attribute("offset").as_double(200.0);
            unsigned int numStarts = processor.attribute("NumStarts").as_int(2);
            vector<string> types =
                strings::tokenize(processor.attribute("types").as_string(),",");
            vecProcess.push_back(new VandleProcessor(types, res,
                offset, numStarts));
        } else if (name == "TeenyVandleProcessor") {
                vecProcess.push_back(new TeenyVandleProcessor());
        } else if (name == "DoubleBetaProcessor") {
            vecProcess.push_back(new DoubleBetaProcessor());
        } else if (name == "PspmtProcessor") {
                vecProcess.push_back(new PspmtProcessor());
        } else if (name == "TemplateProcessor") {
            vecProcess.push_back(new TemplateProcessor());
        } else if (name == "TemplateExpProcessor") {
            vecProcess.push_back(new TemplateExpProcessor());
	}
#ifdef useroot
        else if (name == "RootProcessor") {
            vecProcess.push_back(new RootProcessor("tree.root", "tree"));
        }
#endif
        else {
            stringstream ss;
            ss << "DetectorDriver: unknown processor type" << name;
            throw GeneralException(ss.str());
        }
        stringstream ss;
        for (pugi::xml_attribute_iterator ait = processor.attributes_begin();
            ait != processor.attributes_end(); ++ait) {
            ss.str("");
            ss << ait->name();
            if (ss.str().compare("name") != 0) {
                ss << " = " << ait->value();
                m.detail(ss.str(), 1);
            }
        }
    }

    for (pugi::xml_node analyzer = driver.child("Analyzer"); analyzer;
        analyzer = analyzer.next_sibling("Analyzer")) {
        string name = analyzer.attribute("name").value();
        m.detail("Loading " + name);

	if(name == "TraceFilterAnalyzer") {
	    vecAnalyzer.push_back(new TraceFilterAnalyzer());
	}/* else if (name == "DoubleTraceAnalyzer") {
            double gain_match = analyzer.attribute("gain_match").as_double(1.0);
            if (gain_match == 1.0)
                m.warning("Using gain_match = 1.0", 1);
            int fast_rise = analyzer.attribute("fast_rise").as_int(10);
            if (fast_rise == 10)
                m.warning("Using fast_rise = 10", 1);
            int fast_gap = analyzer.attribute("fast_gap").as_int(10);
            if (fast_gap == 10)
                m.warning("Using fast_gap = 10", 1);
            int fast_threshold =
                analyzer.attribute("fast_threshold").as_int(50);
            if (fast_threshold == 50)
                m.warning("Using fast_threshold = 50", 1);
            int energy_rise = analyzer.attribute("energy_rise").as_int(50);
            if (energy_rise == 50)
                m.warning("Using energy_rise = 50", 1);
            int energy_gap = analyzer.attribute("energy_gap").as_int(50);
            if (energy_gap == 50)
                m.warning("Using energy_gap = 50", 1);
            int slow_rise = analyzer.attribute("slow_rise").as_int(20);
            if (slow_rise == 20)
                m.warning("Using slow_rise = 20", 1);
            int slow_gap = analyzer.attribute("slow_gap").as_int(20);
            if (slow_gap == 20)
                m.warning("Using slow_gap = 20", 1);
            int slow_threshold =
                analyzer.attribute("slow_threshold").as_int(10);
            if (slow_threshold == 10)
                m.warning("Using slow_threshold = 10", 1);
            else if (name == "DoubleTraceAnalyzer")
                vecAnalyzer.push_back(new DoubleTraceAnalyzer(gain_match,
                    fast_rise, fast_gap, fast_threshold, energy_rise,
                    energy_gap, slow_rise, slow_gap, slow_threshold));
		    }*/ else if (name == "TauAnalyzer") {
            vecAnalyzer.push_back(new TauAnalyzer());
        } else if (name == "TraceExtractor") {
            string type = analyzer.attribute("type").as_string();
            string subtype = analyzer.attribute("subtype").as_string();
            string tag = analyzer.attribute("tag").as_string();
            vecAnalyzer.push_back(new TraceExtractor(type, subtype,tag));
        } else if (name == "WaveformAnalyzer") {
            vecAnalyzer.push_back(new WaveformAnalyzer());
        } else if (name == "FittingAnalyzer") {
            vecAnalyzer.push_back(new FittingAnalyzer());
        } else if (name == "CfdAnalyzer") {
            vecAnalyzer.push_back(new CfdAnalyzer());
        } else {
            stringstream ss;
            ss << "DetectorDriver: unknown analyzer type" << name;
            throw GeneralException(ss.str());
        }

        for (pugi::xml_attribute_iterator ait = analyzer.attributes_begin();
             ait != analyzer.attributes_end(); ++ait) {
            stringstream ss;
            ss << ait->name();
            if (ss.str().compare("name") != 0) {
                ss << " = " << ait->value();
                m.detail(ss.str(), 1);
            }
        }
    }
}
static void mediaGetTest(Node& node, TestRunner& tr)
{
   tr.group("media");

   Messenger* messenger = node.getMessenger();

   tr.test("get");
   {
      // create url for obtaining media
      Url url("/api/3.0/media/2");

      // get media
      Media media;
      assertNoException(
         messenger->getFromBitmunk(&url, media));

      printf("\nMedia:\n");
      dumpDynamicObject(media, false);
   }
   tr.passIfNoException();

   tr.test("invalid get");
   {
      // create url for obtaining media
      Url url("/api/3.0/media/invalidMediaId");

      // get media
      Media media;
      messenger->getFromBitmunk(&url, media);
   }
   tr.passIfException();

   tr.test("all");
   {
      // create url for getting media
      Url url("/api/3.0/media/?start=0&num=5");

      // get results
      DynamicObject results;
      //assertNoException(
      //   messenger->getFromBitmunk(&url, results));

      printf("\nDISABLED FOR PERFORMANCE\n");
      /*
      printf("\nGetting 5 media starting at #0\n(of %" PRIu32 " found)\n",
         results["total"]->getUInt32());
      dumpDynamicObject(results, false);
      */
   }
   tr.passIfNoException();

   tr.test("owned");
   {
      // create url for searching media
      Url url("/api/3.0/media?owner=900");

      // get results
      DynamicObject results;
      assertNoException(
         messenger->getFromBitmunk(&url, results));

      printf("\nMedia owned by user 900\n");
      printf("Results %" PRIu32 "-%" PRIu32 " of %" PRIu32 "\n",
         results["start"]->getUInt32(),
         results["start"]->getUInt32() + results["num"]->getUInt32(),
         results["total"]->getUInt32());
      dumpDynamicObject(results, false);
   }
   tr.passIfNoException();

   tr.test("search");
   {
      // create url for searching media
      Url url("/api/3.0/media/?query=test&start=0&num=10");

      // get results
      DynamicObject results;
      assertNoException(
         messenger->getFromBitmunk(&url, results));

      printf("\nSearching media & contributors for 'test'\n");
      printf("Results %" PRIu32 "-%" PRIu32 " of %" PRIu32 "\n",
         results["start"]->getUInt32(),
         results["start"]->getUInt32() + results["num"]->getUInt32(),
         results["total"]->getUInt32());
      dumpDynamicObject(results, false);
   }
   tr.passIfNoException();

   tr.test("genre media");
   {
      // create url for searching media
      Url url("/api/3.0/media?type=audio&genre=165&start=4&num=5");

      // get results
      DynamicObject results;
      assertNoException(
         messenger->getFromBitmunk(&url, results));

      printf("\nAudio from genre 165\n");
      printf("Results %" PRIu32 "-%" PRIu32 " of %" PRIu32 "\n",
         results["start"]->getUInt32(),
         results["start"]->getUInt32() + results["num"]->getUInt32(),
         results["total"]->getUInt32());
      dumpDynamicObject(results, false);
   }
   tr.passIfNoException();

   tr.test("media list");
   {
      // create url for searching media
      Url url("/api/3.0/media?owner=1&list=1");

      // get results
      DynamicObject results;
      assertNoException(
         messenger->getFromBitmunk(&url, results));

      printf("\nMedia list %s\n", results["name"]->getString());
      printf("\"%s\"\n", results["description"]->getString());
      dumpDynamicObject(results, false);
   }
   tr.passIfNoException();

   tr.ungroup();
}
Example #25
0
void DetectorDriver::ReadCalXml() {
    pugi::xml_document doc;

    pugi::xml_parse_result result = doc.load_file("Config.xml");
    if (!result) {
        stringstream ss;
        ss << "DetectorDriver: error parsing file Config.xml";
        ss << " : " << result.description();
        throw GeneralException(ss.str());
    }

    Messenger m;
    m.start("Loading Calibration");

    pugi::xml_node map = doc.child("Configuration").child("Map");

    /** Note that before this reading in of the xml file, it was already
     * processed for the purpose of creating the channels map.
     * Some sanity checks (module and channel number) were done there
     * so they are not repeated here/
     */
    bool verbose = map.attribute("verbose_calibration").as_bool();
    for (pugi::xml_node module = map.child("Module"); module;
         module = module.next_sibling("Module")) {
        int module_number = module.attribute("number").as_int(-1);
        for (pugi::xml_node channel = module.child("Channel"); channel;
             channel = channel.next_sibling("Channel")) {
            int ch_number = channel.attribute("number").as_int(-1);
            Identifier chanID = DetectorLibrary::get()->at(module_number,
                                                           ch_number);
            bool calibrated = false;
            for (pugi::xml_node cal = channel.child("Calibration");
                cal; cal = cal.next_sibling("Calibration")) {
                string model = cal.attribute("model").as_string("None");
                double min = cal.attribute("min").as_double(0);
                double max =
                  cal.attribute("max").as_double(numeric_limits<double>::max());

                stringstream pars(cal.text().as_string());
                vector<double> parameters;
                while (true) {
                    double p;
                    pars >> p;
                    if (pars)
                        parameters.push_back(p);
                    else
                        break;
                }
                if (verbose) {
                    stringstream ss;
                    ss << "Module " << module_number << ", channel "
                       << ch_number << ": ";
                    ss << " model-" << model;
                    for (vector<double>::iterator it = parameters.begin();
                         it != parameters.end(); ++it)
                        ss << " " << (*it);
                    m.detail(ss.str(), 1);
                }
                cali.AddChannel(chanID, model, min, max, parameters);
                calibrated = true;
            }
            if (!calibrated && verbose) {
                stringstream ss;
                ss << "Module " << module_number << ", channel "
                   << ch_number << ": ";
                ss << " non-calibrated";
                m.detail(ss.str(), 1);
            }
        }
    }
    m.done();
}
static void userGetTest(Node& node, TestRunner& tr)
{
   tr.group("user");

   Messenger* messenger = node.getMessenger();

   tr.test("get self (valid)");
   {
      // create url for obtaining users
      Url url("/api/3.0/users/900");

      // get user
      User user;
      assertNoException(
         messenger->getSecureFromBitmunk(&url, user, node.getDefaultUserId()));

      printf("\nUser:\n");
      dumpDynamicObject(user, false);
   }
   tr.passIfNoException();

   /*
   tr.test("get non-self (valid)");
   {
      // create url for obtaining users
      Url url("/api/3.0/users/900");

      // get user
      User user;
      messenger->getSecureFromBitmunk(&url, user, node.getDefaultUserId());
      assertNoException();

      printf("\nUser:\n");
      dumpDynamicObject(user, false);
   }
   tr.passIfNoException();
   */

   tr.test("get identity (valid)");
   {
      // create url for obtaining identity
      Url url("/api/3.0/users/identity/900");

      // get identity
      Identity identity;
      assertNoException(
         messenger->getSecureFromBitmunk(
            &url, identity, node.getDefaultUserId()));

      printf("\nIdentity:\n");
      dumpDynamicObject(identity, false);
   }
   tr.passIfNoException();

   /*
   tr.test("get identity (invalid)");
   {
      // create url for obtaining identity
      Url url("/api/3.0/users/identity/69766");

      // get identity
      Identity identity;
      messenger->getSecureFromBitmunk((
         &url, identity, node.getDefaultUserId());
      assertException();

      printf("\nIdentity:\n");
      dumpDynamicObject(identity, false);
   }
   tr.passIfException();
   */

   /*
   tr.test("sellerKey");
   {
      // create url for obtaining users
      Url url("/api/3.0/users/keys/seller/900");

      // get user
      DynamicObject sellerKey;
      messenger->getFromBitmunk(&url, sellerKey);
      assertNoException();

      printf("\nSeller Key:\n");
      dumpDynamicObject(sellerKey, false);
   }
   tr.passIfNoException();

   tr.test("friends");
   {
      Url url("/api/3.0/friends/?user=900");

      // get friends
      User user;
      messenger->getSecureFromBitmunk(&url, user, node.getDefaultUserId());
      assertNoException();

      printf("\nUser Friends:\n");
      dumpDynamicObject(user, false);
   }
   tr.passIfNoException();
   */

   tr.ungroup();
}
Example #27
0
void DetectorDriver::ReadWalkXml() {
    pugi::xml_document doc;

    pugi::xml_parse_result result = doc.load_file("Config.xml");
    if (!result) {
        stringstream ss;
        ss << "DetectorDriver: error parsing file Config.xml";
        ss << " : " << result.description();
        throw GeneralException(ss.str());
    }

    Messenger m;
    m.start("Loading Walk Corrections");

    pugi::xml_node map = doc.child("Configuration").child("Map");
    /** See comment in the similiar place at ReadCalXml() */
    bool verbose = map.attribute("verbose_walk").as_bool();
    for (pugi::xml_node module = map.child("Module"); module;
         module = module.next_sibling("Module")) {
        int module_number = module.attribute("number").as_int(-1);
        for (pugi::xml_node channel = module.child("Channel"); channel;
             channel = channel.next_sibling("Channel")) {
            int ch_number = channel.attribute("number").as_int(-1);
            Identifier chanID = DetectorLibrary::get()->at(module_number,
                                                           ch_number);
            bool corrected = false;
            for (pugi::xml_node walkcorr = channel.child("WalkCorrection");
                walkcorr; walkcorr = walkcorr.next_sibling("WalkCorrection")) {
                string model = walkcorr.attribute("model").as_string("None");
                double min = walkcorr.attribute("min").as_double(0);
                double max =
                  walkcorr.attribute("max").as_double(
                                              numeric_limits<double>::max());

                stringstream pars(walkcorr.text().as_string());
                vector<double> parameters;
                while (true) {
                    double p;
                    pars >> p;
                    if (pars)
                        parameters.push_back(p);
                    else
                        break;
                }
                if (verbose) {
                    stringstream ss;
                    ss << "Module " << module_number
                       << ", channel " << ch_number << ": ";
                    ss << " model: " << model;
                    for (vector<double>::iterator it = parameters.begin();
                         it != parameters.end(); ++it)
                        ss << " " << (*it);
                    m.detail(ss.str(), 1);
                }
                walk.AddChannel(chanID, model, min, max, parameters);
                corrected = true;
            }
            if (!corrected && verbose) {
                stringstream ss;
                ss << "Module " << module_number << ", channel "
                << ch_number << ": ";
                ss << " not corrected for walk";
                m.detail(ss.str(), 1);
            }
        }
    }
    m.done();
}
Example #28
0
GeProcessor::GeProcessor(double gammaThreshold, double lowRatio,
                         double highRatio, double subEventWindow,
                         double gammaBetaLimit, double gammaGammaLimit):
                         EventProcessor(OFFSET, RANGE, "ge"),
                         leafToClover() {
    associatedTypes.insert("ge"); // associate with germanium detectors

    gammaThreshold_ = gammaThreshold;
    lowRatio_ = lowRatio;
    highRatio_ = highRatio;
    subEventWindow_ = subEventWindow;
    gammaBetaLimit_ = gammaBetaLimit;
    gammaGammaLimit_ = gammaGammaLimit;

    // previously used:
    // in seconds/bin
    // 1e-6, 10e-6, 100e-6, 1e-3, 10e-3, 100e-3
    timeResolution.push_back(5e-3);
    timeResolution.push_back(10e-3);
    if (timeResolution.size() > MAX_TIMEX) {
        stringstream ss;
        ss << "Number of requested time resolution spectra is greater then"
            << " MAX_TIMEX = " << MAX_TIMEX << "."
            << " See GeProcessor.hpp for details.";
        throw GeneralException(ss.str());
    }

#ifdef GGATES
    Messenger m;
    m.detail("Loading Gamma-gamma gates", 1);

    pugi::xml_document doc;
    pugi::xml_parse_result result = doc.load_file("Config.xml");
    if (!result) {
        stringstream ss;
        ss << "DetectorDriver: error parsing file Config.xml";
        ss << " : " << result.description();
        throw IOException(ss.str());
    }

    pugi::xml_node gamma_gates = doc.child("Configuration").child("GammaGates");
    for (pugi::xml_node gate = gamma_gates.child("Gate"); gate;
         gate = gate.next_sibling("Gate")) {
        vector<LineGate> vg;
        bool completeGate = true;
        for (pugi::xml_node line = gate.child("Line"); line;
             line = line.next_sibling("Line")) {
            double min = line.attribute("min").as_double();
            double max = line.attribute("max").as_double();
            LineGate lg = LineGate(min, max);
            if (lg.Check()) {
                vg.push_back(LineGate(min, max));
            } else {
                completeGate = false;
                continue;
            }
        }
        if (vg.size() != 2 && completeGate) {
            throw GeneralException("Gamma-gamma gate size different than 2 is \
not implemented");
        } else {
static void interactiveCustomCatalogTests(Node& node, TestRunner& tr)
{
   Messenger* messenger = node.getMessenger();

   tr.group("customcatalog+listing updater");

   // generate the ware URLs that will be used throughout the test.
   Url waresUrl;
   waresUrl.format("%s/api/3.0/catalog/wares?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_USER_ID);
   Url wareUrl;
   wareUrl.format("%s/api/3.0/catalog/wares/%s?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_WARE_ID_2, TEST_USER_ID);

   // generate the files URL that will be used to prime the medialibrary
   Url filesUrl;
   filesUrl.format("%s/api/3.2/medialibrary/files?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_USER_ID);
   Url removeUrl;
   removeUrl.format(
      "%s/api/3.2/medialibrary/files/%s?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_FILE_ID_2, TEST_USER_ID);

   // remove any previous files from the media library
   messenger->deleteResource(&removeUrl, NULL, node.getDefaultUserId());
   // pass even if there is an exception - this is meant to just clear any
   // previous entries in the medialibrary database if they existed.
   Exception::clear();

   tr.test("add file to medialibrary (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create a FileInfo object
      string normalizedPath;
      File::normalizePath(
         (sTestDataDir + TEST_FILENAME_2).c_str(), normalizedPath);
      out["path"] = normalizedPath.c_str();
      out["mediaId"] = 2;

      // prepare event waiter
      EventWaiter ew(node.getEventController());
      ew.start("bitmunk.medialibrary.File.updated");
      ew.start("bitmunk.medialibrary.File.exception");

      // add the file to the media library
      assertNoException(
         messenger->post(&filesUrl, &out, &in, node.getDefaultUserId()));

      // wait for file ID set event
      assert(ew.waitForEvent(5*1000));

      // ensure it has an exception
      Event e = ew.popEvent();
      //dumpDynamicObject(e);
      if(e["details"]->hasMember("exception"))
      {
         ExceptionRef ex = Exception::convertToException(
            e["details"]["exception"]);
         Exception::set(ex);
      }
   }
   tr.passIfNoException();

   tr.test("add ware without payee-scheme (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create the outgoing ware object
      FileInfo fi;
      fi["id"] = TEST_FILE_ID_2;

      out["id"] = TEST_WARE_ID_2;
      out["mediaId"] = 2;
      out["description"] = "This ware was added by test-services-customcatalog";
      out["fileInfo"] = fi;
      out["payees"]->setType(Array);
      Payee p1 = out["payees"]->append();
      Payee p2 = out["payees"]->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.10";
      p1["description"] = "This payee is for media ID 2";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.10";
      p2["description"] = "This payee is for media ID 2";

      // add the ware to the custom catalog
      messenger->post(&waresUrl, &out, &in, node.getDefaultUserId());
   }
   tr.passIfNoException();

   printf("\nWaiting for server info to update...\n");
   Thread::sleep(2*1000);

   while(true)
   {
      tr.test("get server info");
      {
         Url serverUrl;
         serverUrl.format("%s/api/3.0/catalog/server?nodeuser=%" PRIu64,
            messenger->getSelfUrl(true).c_str(), TEST_USER_ID);
         DynamicObject in;
         messenger->get(&serverUrl, in, node.getDefaultUserId());
         dumpDynamicObject(in);
      }
      tr.passIfNoException();

      printf(
         "\nSleeping to allow listing updater to run. Hit CTRL+C to quit.\n");
      Thread::sleep(30*1000);
   }

   tr.ungroup();
}
static void customCatalogTests(Node& node, TestRunner& tr)
{
   resetTestEnvironment(node);

   Messenger* messenger = node.getMessenger();

   // generate the ware URLs that will be used throughout the test.
   Url waresUrl;
   waresUrl.format(
      "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_USER_ID);
   Url waresNonDefaultListUrl;
   waresNonDefaultListUrl.format(
      "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&id=%s&default=false",
      messenger->getSelfUrl(true).c_str(), TEST_USER_ID, TEST_WARE_ID_2);
   Url wareUrl;
   wareUrl.format(
      "%s/api/3.0/catalog/wares/%s?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_WARE_ID_2, TEST_USER_ID);

   // generate the files URL that will be used to prime the medialibrary
   Url filesUrl;
   filesUrl.format("%s/api/3.2/medialibrary/files?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_USER_ID);
   Url removeUrl;
   removeUrl.format(
      "%s/api/3.2/medialibrary/files/%s?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_FILE_ID_2, TEST_USER_ID);

   // Create basic and detailed test ware with id=2
   Ware basicWare2;
   Ware detailedWare2;
   {
      basicWare2["id"] = TEST_WARE_ID_2;
      basicWare2["description"] =
         "This ware was added by test-services-customcatalog";

      detailedWare2 = basicWare2.clone();
      detailedWare2["mediaId"] = 2;
      detailedWare2["fileInfos"]->setType(Array);
      FileInfo fi = detailedWare2["fileInfos"]->append();
      fi["id"] = TEST_FILE_ID_2;
      fi["mediaId"] = 2;
      File file((sTestDataDir + TEST_FILENAME_2).c_str());
      fi["extension"] = file->getExtension() + 1;
      fi["contentType"] = "audio/mpeg";
      fi["contentSize"] = TEST_CONTENT_SIZE_2;
      fi["size"] = (uint64_t)file->getLength();
      fi["path"] = file->getAbsolutePath();

      detailedWare2["payees"]->setType(Array);
      Payee p1 = detailedWare2["payees"]->append();
      Payee p2 = detailedWare2["payees"]->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.10";
      p1["description"] = "This payee is for media ID 2";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.10";
      p2["description"] = "This payee is for media ID 2";
   }

   // remove any previous files from the media library
   messenger->deleteResource(&removeUrl, NULL, node.getDefaultUserId());
   // pass even if there is an exception - this is meant to just clear any
   // previous entries in the medialibrary database if they existed.
   Exception::clear();

   tr.group("customcatalog");

   tr.test("add file to medialibrary (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create a FileInfo object
      string normalizedPath;
      File::normalizePath(
         (sTestDataDir + TEST_FILENAME_2).c_str(), normalizedPath);
      out["path"] = normalizedPath.c_str();
      out["mediaId"] = 2;

      // prepare event waiter
      EventWaiter ew(node.getEventController());
      ew.start("bitmunk.medialibrary.File.updated");
      ew.start("bitmunk.medialibrary.File.exception");

      // add the file to the media library
      assertNoException(
         messenger->post(&filesUrl, &out, &in, node.getDefaultUserId()));

      // wait for file ID set event
      assert(ew.waitForEvent(5*1000));

      // ensure it has an exception
      Event e = ew.popEvent();
      //dumpDynamicObject(e);
      if(e["details"]->hasMember("exception"))
      {
         ExceptionRef ex = Exception::convertToException(
            e["details"]["exception"]);
         Exception::set(ex);
      }
      else if(strcmp(
         e["type"]->getString(), "bitmunk.medialibrary.File.updated") == 0)
      {
         // add new mediaLibraryId to the basic and detailed wares
         basicWare2["mediaLibraryId"] = e["details"]["mediaLibraryId"];
         detailedWare2["mediaLibraryId"] = e["details"]["mediaLibraryId"];
      }
   }
   tr.passIfNoException();

   tr.test("add ware without payee-scheme (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create the outgoing ware object
      FileInfo fi;
      fi["id"] = TEST_FILE_ID_2;

      out["id"] = TEST_WARE_ID_2;
      out["mediaId"] = 2;
      out["description"] = "This ware was added by test-services-customcatalog";
      out["fileInfo"] = fi;
      out["payees"]->setType(Array);
      Payee p1 = out["payees"]->append();
      Payee p2 = out["payees"]->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.10";
      p1["description"] = "This payee is for media ID 2";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.10";
      p2["description"] = "This payee is for media ID 2";

      // add the ware to the custom catalog
      messenger->post(&waresUrl, &out, &in, node.getDefaultUserId());

      // set ware payeeSchemeIds
      basicWare2["payeeSchemeId"] = in["payeeSchemeId"];
      detailedWare2["payeeSchemeId"] = in["payeeSchemeId"];
   }
   tr.passIfNoException();

   tr.test("get ware (valid)");
   {
      // get a specific ware from the custom catalog
      Ware receivedWare;
      assertNoException(
         messenger->get(&wareUrl, receivedWare, node.getDefaultUserId()));

      // remove format details for comparison
      if(receivedWare->hasMember("fileInfos") &&
         receivedWare["fileInfos"]->getType() == Array &&
         receivedWare["fileInfos"]->length() == 1)
      {
         receivedWare["fileInfos"][0]->removeMember("formatDetails");
      }

      // check to make sure that the wares match
      assertNamedDynoCmp(
         "Expected ware ResourceSet", detailedWare2,
         "Received ware ResourceSet", receivedWare);
   }
   tr.passIfNoException();

   tr.test("get wares");
   {
      // get a specific ware from the custom catalog
      Ware receivedWareSet;
      Url url;
      url.format(
         "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&id=%s",
         messenger->getSelfUrl(true).c_str(), TEST_USER_ID, TEST_WARE_ID_2);
      assertNoException(
         messenger->get(&url, receivedWareSet, node.getDefaultUserId()));

      // check ware set
      Ware expectedWareSet;
      expectedWareSet["resources"][0] = basicWare2.clone();
      expectedWareSet["total"] = 1;
      expectedWareSet["num"] = 1;
      expectedWareSet["start"] = 0;

      assertNamedDynoCmp(
         "Expected ware ResourceSet", expectedWareSet,
         "Received ware ResourceSet", receivedWareSet);
   }
   tr.passIfNoException();

   tr.test("get wares by fileId");
   {
      // get a specific ware from the custom catalog
      Ware receivedWareSet;
      Url url;
      url.format(
         "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&fileId=%s",
         messenger->getSelfUrl(true).c_str(), TEST_USER_ID, TEST_FILE_ID_2);
      assertNoException(
         messenger->get(&url, receivedWareSet, node.getDefaultUserId()));

      // check ware set
      Ware expectedWareSet;
      expectedWareSet["resources"][0] = basicWare2.clone();
      expectedWareSet["total"] = 1;
      expectedWareSet["num"] = 1;
      expectedWareSet["start"] = 0;

      assertNamedDynoCmp(
         "Expected ware ResourceSet", expectedWareSet,
         "Received ware ResourceSet", receivedWareSet);
   }
   tr.passIfNoException();

   tr.test("get specific unknown wares");
   {
      // get a specific ware from the custom catalog
      Ware receivedWareSet;
      Url url;
      url.format(
         "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&id=%s&id=INVALID",
         messenger->getSelfUrl(true).c_str(), TEST_USER_ID, TEST_WARE_ID_2);
      messenger->get(&url, receivedWareSet, node.getDefaultUserId());

      // check ware set
      Ware expectedWareSet;
      expectedWareSet["resources"][0] = basicWare2.clone();
      expectedWareSet["total"] = 1;
      expectedWareSet["num"] = 2;
      expectedWareSet["start"] = 0;

      assertNamedDynoCmp(
         "Expected ware ResourceSet", expectedWareSet,
         "Received ware ResourceSet", receivedWareSet);
   }
   tr.passIfNoException();

   tr.test("get wares by dup ware+file ids");
   {
      // This test gets the same ware by both ware id and file id and returns
      // duplicate results.

      // get a specific ware from the custom catalog
      Ware receivedWareSet;
      Url url;
      url.format(
         "%s/api/3.0/catalog/wares?nodeuser=%" PRIu64 "&id=%s&fileId=%s",
         messenger->getSelfUrl(true).c_str(), TEST_USER_ID,
         TEST_WARE_ID_2, TEST_FILE_ID_2);
      messenger->get(&url, receivedWareSet, node.getDefaultUserId());

      // check ware set
      Ware expectedWareSet;
      expectedWareSet["resources"][0] = basicWare2.clone();
      expectedWareSet["total"] = 1;
      expectedWareSet["num"] = 2;
      expectedWareSet["start"] = 0;

      assertNamedDynoCmp(
         "Expected ware ResourceSet", expectedWareSet,
         "Received ware ResourceSet", receivedWareSet);
   }
   tr.passIfNoException();

   tr.test("remove ware (valid)");
   {
      // remove the ware
      messenger->deleteResource(&wareUrl, NULL, node.getDefaultUserId());
   }
   tr.passIfNoException();

   /*************************** Payee Scheme tests **************************/
   // generate the payee schemes URL
   Url payeeSchemesUrl;
   payeeSchemesUrl.format("%s/api/3.0/catalog/payees/schemes?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), TEST_USER_ID);
   PayeeSchemeId psId = 0;

   tr.test("add payee scheme (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create the outgoing list of payees to organize into a payee scheme
      out["description"] = "Payee scheme description 1";
      out["payees"]->setType(Array);
      PayeeList payees = out["payees"];
      Payee p1 = payees->append();
      Payee p2 = payees->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.10";
      p1["description"] = "test-services-customcatalog test payee 1";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.10";
      p2["description"] = "test-services-customcatalog test payee 2";

      // add the ware to the custom catalog
      messenger->post(&payeeSchemesUrl, &out, &in, node.getDefaultUserId());

      if(in->hasMember("payeeSchemeId"))
      {
         psId = in["payeeSchemeId"]->getUInt32();
      }
   }
   tr.passIfNoException();

   // generate the payee scheme URL
   Url payeeSchemeIdUrl;
   payeeSchemeIdUrl.format("%s/api/3.0/catalog/payees/schemes/%u?nodeuser=%"
      PRIu64,
      messenger->getSelfUrl(true).c_str(), psId, TEST_USER_ID);
   tr.test("get payee scheme (valid)");
   {
      // Create the expected payee scheme
      PayeeScheme expectedPayeeScheme;
      expectedPayeeScheme["id"] = psId;
      expectedPayeeScheme["userId"] = node.getDefaultUserId();
      expectedPayeeScheme["description"] = "Payee scheme description 1";
      expectedPayeeScheme["payees"]->setType(Array);
      Payee p1 = expectedPayeeScheme["payees"]->append();
      Payee p2 = expectedPayeeScheme["payees"]->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.10";
      p1["description"] = "test-services-customcatalog test payee 1";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.10";
      p2["description"] = "test-services-customcatalog test payee 2";

      // get a specific payee scheme from the custom catalog
      PayeeScheme receivedPayeeScheme;
      messenger->get(
         &payeeSchemeIdUrl, receivedPayeeScheme, node.getDefaultUserId());

      // check payee schemes
      assertNamedDynoCmp(
         "Expected payee scheme", expectedPayeeScheme,
         "Received payee scheme", receivedPayeeScheme);
   }
   tr.passIfNoException();

   tr.test("get all payee schemes (valid)");
   {
      // Create the result set
      ResourceSet expectedResults;
      expectedResults["total"] = 2;
      expectedResults["start"] = 0;
      expectedResults["num"] = 2;

      PayeeScheme ps = expectedResults["resources"]->append();
      ps["id"] = 1;
      ps["userId"] = node.getDefaultUserId();
      ps["description"] = "This ware was added by test-services-customcatalog";
      ps["payees"]->setType(Array);
      Payee p1 = ps["payees"]->append();
      Payee p2 = ps["payees"]->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.10";
      p1["description"] = "This payee is for media ID 2";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.10";
      p2["description"] = "This payee is for media ID 2";

      ps = expectedResults["resources"]->append();
      ps["id"] = 2;
      ps["userId"] = node.getDefaultUserId();
      ps["description"] = "Payee scheme description 1";
      ps["payees"]->setType(Array);
      Payee p3 = ps["payees"]->append();
      Payee p4 = ps["payees"]->append();

      p3["id"] = 900;
      p3["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p3["amount"] = "0.10";
      p3["description"] = "test-services-customcatalog test payee 1";

      p4["id"] = 900;
      p4["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p4["percentage"] = "0.10";
      p4["description"] = "test-services-customcatalog test payee 2";

      // get all payee schemes from the custom catalog
      ResourceSet receivedResults;
      messenger->get(
         &payeeSchemesUrl, receivedResults, node.getDefaultUserId());

      // check payee schemes
      assertNamedDynoCmp(
         "Expected payee scheme ResourceSet", expectedResults,
         "Received payee scheme ResourceSet", receivedResults);
   }
   tr.passIfNoException();

   tr.test("update payee scheme (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create the outgoing list of payees to organize into a payee scheme
      out["description"] = "Payee scheme description 2";
      Payee p1 = out["payees"]->append();
      Payee p2 = out["payees"]->append();

      p1["id"] = 900;
      p1["amountType"] = PAYEE_AMOUNT_TYPE_FLATFEE;
      p1["amount"] = "0.15";
      p1["description"] = "test-services-customcatalog test payee 1 (updated)";

      p2["id"] = 900;
      p2["amountType"] = PAYEE_AMOUNT_TYPE_PTOTAL;
      p2["percentage"] = "0.14";
      p2["description"] = "test-services-customcatalog test payee 2 (updated)";

      // update a pre-existing payee scheme
      assertNoException(
         messenger->post(
            &payeeSchemeIdUrl, &out, &in, node.getDefaultUserId()));

      // ensure that the payee scheme was updated
      assert(in["payeeSchemeId"]->getUInt32() == 2);

      if(in->hasMember("payeeSchemeId"))
      {
         psId = in["payeeSchemeId"]->getUInt32();
      }
   }
   tr.passIfNoException();

   tr.test("add ware with payee scheme (valid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create the outgoing ware object
      FileInfo fi;
      fi["id"] = TEST_FILE_ID_2;
      out["id"] = TEST_WARE_ID_2;
      out["mediaId"] = 2;
      out["description"] = "This ware was added by test-services-customcatalog";
      out["fileInfo"] = fi;
      out["payeeSchemeId"] = psId;

      // add the ware to the custom catalog
      messenger->post(&waresUrl, &out, &in, node.getDefaultUserId());
   }
   tr.passIfNoException();

   tr.test("remove associated payee scheme (invalid)");
   {
      messenger->deleteResource(
         &payeeSchemeIdUrl, NULL, node.getDefaultUserId());
   }
   tr.passIfException();

   tr.test("remove ware associated w/ payee scheme (valid)");
   {
      messenger->deleteResource(
         &wareUrl, NULL, node.getDefaultUserId());
   }
   tr.passIfNoException();

   tr.test("remove payee scheme (valid)");
   {
      messenger->deleteResource(
         &payeeSchemeIdUrl, NULL, node.getDefaultUserId());
   }
   tr.passIfNoException();

   tr.test("create ware w/ invalid payee scheme (invalid)");
   {
      DynamicObject in;
      DynamicObject out;

      // create the outgoing ware object
      FileInfo fi;
      fi["id"] = TEST_FILE_ID_2;
      PayeeScheme ps;
      ps["id"] = psId;

      out["id"] = TEST_WARE_ID_2;
      out["mediaId"] = 2;
      out["description"] = "This ware was added by test-services-customcatalog";
      out["fileInfo"] = fi;
      out["payeeScheme"] = ps;

      // add the ware to the custom catalog
      messenger->post(&waresUrl, &out, &in, node.getDefaultUserId());
   }
   tr.passIfException();

   tr.test("remove ware (invalid)");
   {
      // remove a ware that doesn't exist
      messenger->deleteResource(&wareUrl, NULL, node.getDefaultUserId());
   }
   tr.passIfException();

   tr.ungroup();
}