Ejemplo n.º 1
0
/// Adds the default connector options. Also updates the capabilities structure with the default options.
/// Besides the options addBasicConnectorOptions adds, this function also adds port and interface options.
void Util::Config::addConnectorOptions(int port, JSON::Value & capabilities){
  JSON::Value option;
  option.null();
  option["long"] = "port";
  option["short"] = "p";
  option["arg"] = "integer";
  option["help"] = "TCP port to listen on";
  option["value"].append((long long)port);
  addOption("listen_port", option);
  capabilities["optional"]["port"]["name"] = "TCP port";
  capabilities["optional"]["port"]["help"] = "TCP port to listen on - default if unprovided is "+option["value"][0u].asString();
  capabilities["optional"]["port"]["type"] = "uint";
  capabilities["optional"]["port"]["option"] = "--port";
  capabilities["optional"]["port"]["default"] = option["value"][0u];
  
  option.null();
  option["long"] = "interface";
  option["short"] = "i";
  option["arg"] = "string";
  option["help"] = "Interface address to listen on, or 0.0.0.0 for all available interfaces.";
  option["value"].append("0.0.0.0");
  addOption("listen_interface", option);
  capabilities["optional"]["interface"]["name"] = "Interface";
  capabilities["optional"]["interface"]["help"] = "Address of the interface to listen on - default if unprovided is all interfaces";
  capabilities["optional"]["interface"]["option"] = "--interface";
  capabilities["optional"]["interface"]["type"] = "str";
  
  addBasicConnectorOptions(capabilities);
} //addConnectorOptions
Ejemplo n.º 2
0
 void inputFLV::getNext(bool smart) {
   static JSON::Value thisPack;
   static AMF::Object amf_storage;
   thisPack.null();
   long long int lastBytePos = ftell(inFile);
   FLV::Tag tmpTag;
   while (!feof(inFile) && !FLV::Parse_Error){
     if (tmpTag.FileLoader(inFile)){
       thisPack = tmpTag.toJSON(myMeta, amf_storage);
       thisPack["bpos"] = lastBytePos;
       if ( !selectedTracks.count(thisPack["trackid"].asInt())){
         getNext();
       }
       break;
     }
   }
   if (FLV::Parse_Error){
     FAIL_MSG("FLV error: %s", FLV::Error_Str.c_str());
     thisPack.null();
     thisPacket.null();
     return;
   }
   std::string tmpStr = thisPack.toNetPacked();
   thisPacket.reInit(tmpStr.data(), tmpStr.size());
 }
Ejemplo n.º 3
0
/// Adds the default connector options. Also updates the capabilities structure with the default options.
void Util::Config::addBasicConnectorOptions(JSON::Value & capabilities){
  JSON::Value option;
  option.null();
  option["long"] = "username";
  option["short"] = "u";
  option["arg"] = "string";
  option["help"] = "Username to drop privileges to, or root to not drop provileges.";
  option["value"].append("root");
  addOption("username", option);
  capabilities["optional"]["username"]["name"] = "Username";
  capabilities["optional"]["username"]["help"] = "Username to drop privileges to - default if unprovided means do not drop privileges";
  capabilities["optional"]["username"]["option"] = "--username";
  capabilities["optional"]["username"]["type"] = "str";
  
  option.null();
  option["long"] = "daemon";
  option["short"] = "d";
  option["long_off"] = "nodaemon";
  option["short_off"] = "n";
  option["help"] = "Whether or not to daemonize the process after starting.";
  option["value"].append(1ll);
  addOption("daemonize", option);
  
  option.null();
  option["long"] = "json";
  option["short"] = "j";
  option["help"] = "Output connector info in JSON format, then exit.";
  option["value"].append(0ll);
  addOption("json", option);
}
Ejemplo n.º 4
0
 bool inputFLV::readHeader() {
   JSON::Value lastPack;
   if (!inFile) {
     return false;
   }
   //See whether a separate header file exists.
   DTSC::File tmp(config->getString("input") + ".dtsh");
   if (tmp){
     myMeta = tmp.getMeta();
     return true;
   }
   //Create header file from FLV data
   fseek(inFile, 13, SEEK_SET);
   FLV::Tag tmpTag;
   long long int lastBytePos = 13;
   while (!feof(inFile) && !FLV::Parse_Error){
     if (tmpTag.FileLoader(inFile)){
       lastPack.null();
       lastPack = tmpTag.toJSON(myMeta);
       lastPack["bpos"] = lastBytePos;
       myMeta.update(lastPack);
       lastBytePos = ftell(inFile);
     }
   }
   if (FLV::Parse_Error){
     std::cerr << FLV::Error_Str << std::endl;
     return false;
   }
   std::ofstream oFile(std::string(config->getString("input") + ".dtsh").c_str());
   oFile << myMeta.toJSON().toNetPacked();
   oFile.close();
   return true;
 }
Ejemplo n.º 5
0
void CompositorLoader::ParseStageConnections(CompositeStageConnections& connections, const json::Value& stageJson)
{
	if (stageJson.HasKey("input") && stageJson["input"].GetType() == ArrayVal)
	{
		Array inputArray = stageJson["input"].ToArray();

		for (auto it = inputArray.begin(); it != inputArray.end(); ++it)
		{
			connections.AddRenderTargetInput(it->ToString(""));
		}
	}
	
	if (stageJson.HasKey("output") && stageJson["output"].GetType() == ArrayVal)
	{
		Array inputArray = stageJson["output"].ToArray();

		for (auto it = inputArray.begin(); it != inputArray.end(); ++it)
		{
			connections.AddRenderTarget(it->ToString(""));
		}
	}
	
	if (stageJson.HasKey("depthBuffer") && stageJson["depthBuffer"].GetType() == StringVal)
	{
		connections.SetDepthBuffer(stageJson["depthBuffer"].ToString());
	}
}
Ejemplo n.º 6
0
void CompareJson(json::Value& lhs, json::Value& rhs, json::Value& output) {
  std::string lstr, rstr;
  if (rhs.type() != lhs.type()) return;
  switch (lhs.type()) {
  case json::Value::tString:
    lstr = lhs.getString();
    rstr = rhs.getString();
    if (!lstr.empty() && lstr[0] == '$' && lstr.back() == '$') {
      size_t slash = lstr.find('/');
      std::string cat = lstr.substr(1, slash - 1);
      std::string name = lstr.substr(slash + 1, lstr.length() - slash - 2);
      output[cat][name] = rstr;
    }
    break;
  case json::Value::tArray:
    for (size_t i = 0; i < lhs.length(); ++i) {
      if (i < rhs.length()) {
        CompareJson(lhs[i], rhs[i], output);
      }
    }
    break;
  case json::Value::tObject:
    for (auto it = lhs.begin(); it != lhs.end(); ++it) {
      if (rhs.has(it.key())) {
        CompareJson(*it, rhs[it.key()], output);
      }
    }
    break;
  }
}
Ejemplo n.º 7
0
void Animation::parsePrefab(json::Value& val)
{
	if(val.isMember("sequences") && !val["sequences"].empty())
	{
		json::Value sequences = val["sequences"];

		for(json::Value::iterator it = sequences.begin(); it != sequences.end(); ++it)
		{
			if(!(*it).isMember("start") || !(*it).isMember("end") || !(*it).isMember("fps"))
			{
				szerr << "Animation sequence definition must have start and end frame and fps value." << ErrorStream::error;
				continue;
			}

			sf::Uint32 start	= (*it)["start"].asUInt();
			sf::Uint32 end		= (*it)["end"].asUInt();
			sf::Uint32 fps		= (*it)["fps"].asUInt();

			bool looping		= (*it).get("looping", 0).asBool();
			std::string next	= (*it).get("next", "").asString();

			defineAnimation(it.memberName(), start, end, fps, looping, next);
		}
	}

	if(val.isMember("autoplay"))
	{
		if(val["autoplay"].isString())
		{
			play(val["autoplay"].asString());
		}
	}
}
Ejemplo n.º 8
0
static void couchLoadData(PrintTextA &print) {
	CouchDB db(getTestCouch());
	db.use(DATABASENAME);


	AutoArray<Document, SmallAlloc<50> > savedDocs;

	Changeset chset(db.createChangeset());
	natural id=10000;
	JSON::Value data = db.json.factory->fromString(strdata);
	for (JSON::Iterator iter = data->getFwIter(); iter.hasItems();) {
		const JSON::KeyValue &kv= iter.getNext();
		Document doc;
		doc.edit(db.json)
				("name",kv[0])
				("age",kv[1])
				("height",kv[2])
				("_id",ToString<natural>(id,16));
		id+=14823;
		savedDocs.add(doc);
		chset.update(doc);
	}
	chset.commit(false);
	Set<StringA> uuidmap;

	for (natural i = 0; i < savedDocs.length(); i++) {
		StringA uuid = savedDocs[i]["_id"]->getStringUtf8();
//		print("%1\n") << uuid;
		uuidmap.insert(uuid);
	}
	print("%1") << uuidmap.size();

}
Ejemplo n.º 9
0
void CompositorLoader::ParseStage(ResourceManager& resourceManager, Compositor::Ptr& compositor, const json::Value& stageJson)
{
	if (stageJson.HasKey("disabled") && stageJson["disabled"].ToBool(false))
	{
		return;
	}

	if (!stageJson.HasKey("stage") || stageJson["stage"].GetType() != StringVal)
	{
		throw FormatException("stages[].stage needs to be a string containing the relvative path to a CompositeStage");
	}

	CompositeStageConnections connections;

	ParseStageConnections(connections, stageJson);

	std::string stageFilename = stageJson["stage"].ToString();
	CompositeStage::Ptr stage = resourceManager.LoadResource<CompositeStage>(stageFilename);

	if (stageJson.HasKey("shaderValues"))
	{
		Array defaultValues = stageJson["shaderValues"].ToArray();

		for (auto it = defaultValues.begin(); it != defaultValues.end(); ++it)
		{
			JsonTypeHelper::ParseValueIntoParameters(stage->GetStateParameters(), *it);
		}
	}

	compositor->AddCompositeStage(stage, connections);
}
Ejemplo n.º 10
0
 void CheckAllStreams(JSON::Value & data){
   long long int currTime = Util::epoch();
   for (JSON::ObjIter jit = data.ObjBegin(); jit != data.ObjEnd(); jit++){
     if ( !Util::Procs::isActive(jit->first)){
       startStream(jit->first, jit->second);
     }
     if (currTime - lastBuffer[jit->first] > 5){
       if (jit->second.isMember("error") && jit->second["error"].asString() != ""){
         jit->second["online"] = jit->second["error"];
       }else{
         jit->second["online"] = 0;
       }
     }else{
       jit->second["online"] = 1;
     }
   }
   static JSON::Value strlist;
   bool changed = false;
   if (strlist["config"] != Storage["config"]){
     strlist["config"] = Storage["config"];
     changed = true;
   }
   if (strlist["streams"] != Storage["streams"]){
     strlist["streams"] = Storage["streams"];
     changed = true;
   }
   if (changed){
     WriteFile("/tmp/mist/streamlist", strlist.toString());
   }
 }
Ejemplo n.º 11
0
	static void numberToWide(PrintTextA &print) {
		JSON::PFactory f = JSON::create();
		JSON::Value v = f->newValue((natural)123);
		String tst1 = v->getString();
		String tst2 = v->getString();
		print("%1,%2") << tst1 << tst2;
	}
Ejemplo n.º 12
0
  ///\brief Builds a bootstrap for use in HTTP Dynamic streaming.
  ///\param streamName The name of the stream.
  ///\param metadata The current metadata, used to generate the index.
  ///\param fragnum The index of the current fragment
  ///\return The generated bootstrap.
  std::string dynamicBootstrap(std::string & streamName, JSON::Value & metadata, int fragnum = 0){
    std::string empty;

    MP4::ASRT asrt;
    asrt.setUpdate(false);
    asrt.setVersion(1);
    //asrt.setQualityEntry(empty, 0);
    if (metadata.isMember("live")){
      asrt.setSegmentRun(1, 4294967295ul, 0);
    }else{
      asrt.setSegmentRun(1, metadata["keytime"].size(), 0);
    }

    MP4::AFRT afrt;
    afrt.setUpdate(false);
    afrt.setVersion(1);
    afrt.setTimeScale(1000);
    //afrt.setQualityEntry(empty, 0);
    MP4::afrt_runtable afrtrun;
    if (metadata.isMember("live")){
      // restrict data to last 2 fragments, unless an earlier fragment was expressly requested.
      int count = 0;
      unsigned int begin = std::max(0u, metadata["keynum"].size() - 3);
      while (begin > 0 && fragnum && metadata["keynum"][begin].asInt() > fragnum){
        begin--;
      }
      for (int i = begin; i < metadata["keynum"].size(); i++){
        afrtrun.firstFragment = metadata["keynum"][i].asInt();
        afrtrun.firstTimestamp = metadata["keytime"][i].asInt();
        afrtrun.duration = metadata["keylen"][i].asInt();
        afrt.setFragmentRun(afrtrun, count++);
      }
    }else{
      for (int i = 0; i < metadata["keynum"].size(); i++){
        afrtrun.firstFragment = metadata["keynum"][i].asInt();
        afrtrun.firstTimestamp = metadata["keytime"][i].asInt();
        afrtrun.duration = metadata["keylen"][i].asInt();
        afrt.setFragmentRun(afrtrun, i);
      }
    }

    MP4::ABST abst;
    abst.setVersion(1);
    abst.setBootstrapinfoVersion(1);
    abst.setProfile(0);
    abst.setUpdate(false);
    abst.setTimeScale(1000);
    abst.setLive(false);
    abst.setCurrentMediaTime(metadata["lastms"].asInt());
    abst.setSmpteTimeCodeOffset(0);
    abst.setMovieIdentifier(streamName);
    abst.setSegmentRunTable(asrt, 0);
    abst.setFragmentRunTable(afrt, 0);

#if DEBUG >= 8
    std::cout << "Sending bootstrap:" << std::endl << abst.toPrettyString(0) << std::endl;
#endif
    return std::string((char*)abst.asBox(), (int)abst.boxedSize());
  }
Ejemplo n.º 13
0
  /// Returns a Smooth-format manifest file
  std::string BuildManifest(std::string & MovieId, JSON::Value & metadata){
    std::stringstream Result;
    Result << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
    Result << "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" TimeScale=\"10000000\" Duration=\"" << metadata["lastms"].asInt()
        << "\">\n";
    if (metadata.isMember("audio")){
      Result << "  <StreamIndex Type=\"audio\" QualityLevels=\"1\" Name=\"audio\" Chunks=\"" << metadata["keytime"].size()
          << "\" Url=\"Q({bitrate})/A({start time})\">\n";
      Result << "    <QualityLevel Index=\"0\" Bitrate=\"" << metadata["audio"]["bps"].asInt() * 8 << "\" CodecPrivateData=\"";
      Result << std::hex;
      for (int i = 0; i < metadata["audio"]["init"].asString().size(); i++){
        Result << std::setfill('0') << std::setw(2) << std::right << (int)metadata["audio"]["init"].asString()[i];
      }
      Result << std::dec;
      Result << "\" SamplingRate=\"" << metadata["audio"]["rate"].asInt()
          << "\" Channels=\"2\" BitsPerSample=\"16\" PacketSize=\"4\" AudioTag=\"255\" FourCC=\"AACL\"  />\n";
      for (int i = 0; i < metadata["keytime"].size() - 1; i++){
        Result << "    <c ";
        if (i == 0){
          Result << "t=\"0\" ";
        }
        Result << "d=\"" << 10000 * (metadata["keytime"][i + 1].asInt() - metadata["keytime"][i].asInt()) << "\" />\n";
      }
      Result << "    <c d=\"" << 10000 * (metadata["lastms"].asInt() - metadata["keytime"][metadata["keytime"].size() - 1].asInt()) << "\" />\n";
      Result << "   </StreamIndex>\n";
    }
    if (metadata.isMember("video")){
      Result << "  <StreamIndex Type=\"video\" QualityLevels=\"1\" Name=\"video\" Chunks=\"" << metadata["keytime"].size()
          << "\" Url=\"Q({bitrate})/V({start time})\" MaxWidth=\"" << metadata["video"]["width"].asInt() << "\" MaxHeight=\""
          << metadata["video"]["height"].asInt() << "\" DisplayWidth=\"" << metadata["video"]["width"].asInt() << "\" DisplayHeight=\""
          << metadata["video"]["height"].asInt() << "\">\n";
      Result << "    <QualityLevel Index=\"0\" Bitrate=\"" << metadata["video"]["bps"].asInt() * 8 << "\" CodecPrivateData=\"";
      MP4::AVCC avccbox;
      avccbox.setPayload(metadata["video"]["init"].asString());
      std::string tmpString = avccbox.asAnnexB();
      Result << std::hex;
      for (int i = 0; i < tmpString.size(); i++){
        Result << std::setfill('0') << std::setw(2) << std::right << (int)tmpString[i];
      }
      Result << std::dec;
      Result << "\" MaxWidth=\"" << metadata["video"]["width"].asInt() << "\" MaxHeight=\"" << metadata["video"]["height"].asInt()
          << "\" FourCC=\"AVC1\" />\n";
      for (int i = 0; i < metadata["keytime"].size() - 1; i++){
        Result << "    <c ";
        if (i == 0){
          Result << "t=\"0\" ";
        }
        Result << "d=\"" << 10000 * (metadata["keytime"][i + 1].asInt() - metadata["keytime"][i].asInt()) << "\" />\n";
      }
      Result << "    <c d=\"" << 10000 * (metadata["lastms"].asInt() - metadata["keytime"][metadata["keytime"].size() - 1].asInt()) << "\" />\n";
      Result << "   </StreamIndex>\n";
    }
    Result << "</SmoothStreamingMedia>\n";

#if DEBUG >= 8
    std::cerr << "Sending this manifest:" << std::endl << Result << std::endl;
#endif
    return Result.str();
  } //BuildManifest
Ejemplo n.º 14
0
	static void serializeCycleError(PrintTextA &print) {
		JSON::PFactory f = JSON::create();
		JSON::Value v = f->fromString(jsonSrc);
		JSON::Value arr = v["array"];
		arr->add(v);
		v->erase("text");
		JSON::serialize(v, print.nxChain(), false);
		v->erase("array");
	}
Ejemplo n.º 15
0
/// Adds a single DTSC packet to the stream, updating the internal metadata if needed.
void DTSC::Stream::addPacket(JSON::Value & newPack) {
  livePos newPos;
  newPos.trackID = newPack["trackid"].asInt();
  newPos.seekTime = newPack["time"].asInt();
  if (!metadata.tracks.count(newPos.trackID) && (!newPack.isMember("mark") || newPack["mark"].asStringRef() != "pause")) {
    return;
  }
  if (buffercount > 1 && metadata.tracks[newPos.trackID].keys.size() > 1 && newPos.seekTime < (long long unsigned int)metadata.tracks[newPos.trackID].keys.rbegin()->getTime()) {
    resetStream();
  }
  while (buffers.count(newPos) > 0) {
    newPos.seekTime++;
  }
  while (buffercount == 1 && buffers.size() > 0) {
    cutOneBuffer();
  }
  buffers[newPos] = newPack;
  datapointertype = INVALID;
  std::string tmp = "";
  if (newPack.isMember("trackid") && newPack["trackid"].asInt() > 0) {
    tmp = metadata.tracks[newPack["trackid"].asInt()].type;
  }
  if (newPack.isMember("datatype")) {
    tmp = newPack["datatype"].asStringRef();
  }
  if (tmp == "video") {
    datapointertype = VIDEO;
  }
  if (tmp == "audio") {
    datapointertype = AUDIO;
  }
  if (tmp == "meta") {
    datapointertype = META;
  }
  if (tmp == "pause_marker" || (newPack.isMember("mark") && newPack["mark"].asStringRef() == "pause")) {
    datapointertype = PAUSEMARK;
  }
  if (buffercount > 1) {
    metadata.update(newPack);
    if (newPack.isMember("keyframe") || (long long unsigned int)metadata.tracks[newPos.trackID].keys.rbegin()->getTime() == newPos.seekTime) {
      keyframes[newPos.trackID].insert(newPos);
    }
    metadata.live = true;
    //throw away buffers if buffer time is met
    int trid = buffers.begin()->first.trackID;
    int firstTime = buffers.begin()->first.seekTime;
    int lastTime = buffers.rbegin()->first.seekTime - buffertime;
    while ((!metadata.tracks[trid].keys.size() && firstTime < lastTime) || (metadata.tracks[trid].keys.size() && metadata.tracks[trid].keys.rbegin()->getTime() < lastTime) || (metadata.tracks[trid].keys.size() > 2 && metadata.tracks[trid].keys.rbegin()->getTime() - firstTime > buffertime)) {
      cutOneBuffer();
      trid = buffers.begin()->first.trackID;
      firstTime = buffers.begin()->first.seekTime;
    }
    metadata.bufferWindow = buffertime;
  }

}
Ejemplo n.º 16
0
bool AddressValidator::is_valid(const json::Value& value) {
    if (!value.is_string()) {
        return false;
    }
    const auto& val = value.as_string();
    if ("localhost" == val) {
        return true;
    }
    return std::regex_match(val, m_address_regex);
}
Ejemplo n.º 17
0
///\brief Checks all streams, restoring if needed.
///\param data The stream configuration for the server.
void CheckAllStreams(JSON::Value & data) {
    long long int currTime = Util::epoch();
    for (JSON::ObjIter jit = data.ObjBegin(); jit != data.ObjEnd(); jit++) {
        if ( !Util::Procs::isActive(jit->first)) {
            startStream(jit->first, jit->second);
        }
        if (currTime - lastBuffer[jit->first] > 5) {
            if (jit->second.isMember("source") && jit->second["source"].asString().substr(0, 1) == "/" && jit->second.isMember("error")
                    && jit->second["error"].asString() == "Available") {
                jit->second["online"] = 2;
            } else {
                if (jit->second.isMember("error") && jit->second["error"].asString() == "Available") {
                    jit->second.removeMember("error");
                }
                jit->second["online"] = 0;
            }
        } else {
            // assume all is fine
            jit->second.removeMember("error");
            jit->second["online"] = 1;
            // check if source is valid
            if (jit->second.isMember("live") && !jit->second.isMember("meta") || !jit->second["meta"]) {
                jit->second["online"] = 0;
                jit->second["error"] = "No (valid) source connected";
            } else {
                // for live streams, keep track of activity
                if (jit->second["meta"].isMember("live")) {
                    if (jit->second["meta"]["lastms"] != jit->second["lastms"]) {
                        jit->second["lastms"] = jit->second["meta"]["lastms"];
                        jit->second["last_active"] = currTime;
                    }
                    // mark stream as offline if no activity for 5 seconds
                    if (jit->second.isMember("last_active") && jit->second["last_active"].asInt() < currTime - 5) {
                        jit->second["online"] = 0;
                        jit->second["error"] = "No (valid) source connected";
                    }
                }
            }
        }
    }
    static JSON::Value strlist;
    bool changed = false;
    if (strlist["config"] != Storage["config"]) {
        strlist["config"] = Storage["config"];
        changed = true;
    }
    if (strlist["streams"] != Storage["streams"]) {
        strlist["streams"] = Storage["streams"];
        changed = true;
    }
    if (changed) {
        WriteFile("/tmp/mist/streamlist", strlist.toString());
    }
}
Ejemplo n.º 18
0
void JsonStream::valueToString(json::Value &value, std::string& str)
{
    if(value.GetType() == json::StringVal)
    {
        str = value.ToString();
    }
    else
    {
        mIsOk = false;
        mErrorLog += "JsonStream::valueToString() Error: wrong type\n";
    }
}
Ejemplo n.º 19
0
void ListStrings(json::Value& value, json::Value& data) {
  for (auto& kv : value.getMap()) {
    if (kv.second.type() == json::Value::tObject) {
      for (auto& skv : kv.second.getMap()) {
        data["stringlist"][kv.first][skv.first]["text"] = skv.first;
      }
    } else {
      data["stringlist"]["Global"][kv.first]["text"] = kv.first;
    }
  }
  value.clear();
}
Ejemplo n.º 20
0
void ClientWS::processMessage(JSON::Value v) {
	try {
		JSON::Value result = v["result"];
		JSON::Value error = v["error"];
		JSON::Value context = v["context"];
		JSON::Value method = v["method"];
		JSON::Value id = v["id"];
		JSON::Value params = v["params"];
		if (result != null || error != null) {
			if (id != null && !id->isNull()) {

				natural reqid = id->getUInt();
				const Promise<Result> *p = waitingResults.find(reqid);
				if (p == 0)
					onDispatchError(v);
				else {
					Promise<Result> q = *p;
					waitingResults.erase(reqid);
					if (p) {
						if (error == null || error->isNull()) {
							q.resolve(Result(result,context));
						} else {
							q.reject(RpcError(THISLOCATION,error));
						}
					}
				}
			}//id=null - invalid frame
			else {
				onDispatchError(v);
			}
		} else if (method != null && params != null) {
			if (id == null || id->isNull()) {
				onNotify(method->getStringUtf8(), params, context);
			} else {
				try {
					onIncomeRPC(method->getStringUtf8(), params,context,id);
				} catch (const RpcError &e) {
					sendResponse(id, jsonFactory->newValue(null), e.getError());
				} catch (const jsonsrv::RpcCallError &c) {
					RpcError e(THISLOCATION,jsonFactory,c.getStatus(),c.getStatusMessage());
					sendResponse(id, jsonFactory->newValue(null), e.getError());
				} catch (const std::exception &s) {
					RpcError e(THISLOCATION,jsonFactory,500,s.what());
					sendResponse(id, jsonFactory->newValue(null), e.getError());
				} catch (...) {
					RpcError e(THISLOCATION,jsonFactory,500,"fatal");
					sendResponse(id, jsonFactory->newValue(null), e.getError());
				}

			}
		}

	} catch (...) {
		onDispatchError(v);
	}

}
Ejemplo n.º 21
0
    void build_json_map(const json::Value& json) {
        for (auto it = json.cbegin(); it != json.cend(); ++it) {
            m_json_path.push_key(it.key());
            const auto& json_value = *it;

            m_json_map[m_json_path.get_path()] = json_value;

            if (!json_value.is_array()) {
                build_json_map(json_value);
            }
            m_json_path.pop_key();
        }
    }
Ejemplo n.º 22
0
void TransformJson(json::Value& value, json::Value& data, Func const& func) {
  switch (value.type()) {
  case json::Value::tString:
    value = func(value.getString(), data);
    break;
  case json::Value::tArray:
  case json::Value::tObject:
    for (auto& sub : value) {
      TransformJson(sub, data, func);
    }
    break;
  }
}
Ejemplo n.º 23
0
int main(int argc, char ** argv){
  Util::Config conf(argv[0], PACKAGE_VERSION);
  JSON::Value capa;
  capa["desc"] = "Enables the raw MPEG Transport Stream protocol over TCP.";
  capa["deps"] = "";
  capa["required"]["streamname"]["name"] = "Stream";
  capa["required"]["streamname"]["help"] = "What streamname to serve. For multiple streams, add this protocol multiple times using different ports.";
  capa["required"]["streamname"]["type"] = "str";
  capa["required"]["streamname"]["option"] = "--stream";
  capa["optional"]["tracks"]["name"] = "Tracks";
  capa["optional"]["tracks"]["help"] = "The track IDs of the stream that this connector will transmit separated by spaces";
  capa["optional"]["tracks"]["type"] = "str";
  capa["optional"]["tracks"]["option"] = "--tracks";
  conf.addOption("streamname",
      JSON::fromString("{\"arg\":\"string\",\"short\":\"s\",\"long\":\"stream\",\"help\":\"The name of the stream that this connector will transmit.\"}"));
  conf.addOption("tracks",
      JSON::fromString("{\"arg\":\"string\",\"value\":[\"\"],\"short\": \"t\",\"long\":\"tracks\",\"help\":\"The track IDs of the stream that this connector will transmit separated by spaces.\"}"));
  conf.addConnectorOptions(8888, capa);
  bool ret = conf.parseArgs(argc, argv);
  if (conf.getBool("json")){
    std::cout << capa.toString() << std::endl;
    return -1;
  }
  if (!ret){
    std::cerr << "Usage error: missing argument(s)." << std::endl;
    conf.printHelp(std::cout);
    return 1;
  }
  
  Socket::Server server_socket = Socket::Server(conf.getInteger("listen_port"), conf.getString("listen_interface"));
  if ( !server_socket.connected()){
    return 1;
  }
  conf.activate();

  while (server_socket.connected() && conf.is_active){
    Socket::Connection S = server_socket.accept();
    if (S.connected()){ //check if the new connection is valid
      pid_t myid = fork();
      if (myid == 0){ //if new child, start MAINHANDLER
        return Connector_TS::tsConnector(S, conf.getString("streamname"), conf.getString("tracks"));
      }else{ //otherwise, do nothing or output debugging text
#if DEBUG >= 5
        fprintf(stderr, "Spawned new process %i for socket %i\n", (int)myid, S.getSocket());
#endif
      }
    }
  } //while connected
  server_socket.close();
  return 0;
} //main
Ejemplo n.º 24
0
// Test the containment of JSON objects where one is a JSON string.
TEST(JsonTest, ContainsString)
{
  Try<JSON::Value> _str = JSON::parse("{\"string\" : \"Hello World!\"}");
  ASSERT_SOME(_str);
  const JSON::Value str = _str.get();

  Try<JSON::Value> strTest = JSON::parse("{\"string\" : \"Hello World!\"}");
  EXPECT_TRUE(str.contains(strTest.get()));

  strTest = JSON::parse("{}");
  EXPECT_TRUE(str.contains(strTest.get()));

  strTest = JSON::parse("{\"string\" : \"Goodbye World!\"}");
  EXPECT_FALSE(str.contains(strTest.get()));

  strTest = JSON::parse("{\"string\" : \"\"}");
  EXPECT_FALSE(str.contains(strTest.get()));

  strTest = JSON::parse("{\"string\" : null}");
  EXPECT_FALSE(str.contains(strTest.get()));

  strTest = JSON::parse("{\"string\" : 42}");
  EXPECT_FALSE(str.contains(strTest.get()));

  strTest = JSON::parse("{\"string\" : [42]}");
  EXPECT_FALSE(str.contains(strTest.get()));
}
Ejemplo n.º 25
0
void Positions::loadJSON(const JSON::Value &value, float scale) {
  clear();

  for (unsigned i = 0; i < value.size(); i++) {
    const JSON::List &coord = value.getList(i);
    if (coord.size() != 3) THROWS("Position expected list of length 3");

    push_back(Vector3D(coord.getNumber(0), coord.getNumber(1),
                       coord.getNumber(2)) * scale);
  }

  LOG_DEBUG(3, "Read " << size() << " JSON positions");

  init();
}
Ejemplo n.º 26
0
	Animation::State::KeyFrame::KeyFrame( const Animation& animation, json::Value &config )
	{
		time = config["time"].asFloat();
			
		for (auto it2 = config.begin(); it2 != config.end(); it2++)
		{
			std::map<std::string, Bone*>::const_iterator it = animation.bones.find(it2.key());
			if(it == animation.bones.end())
				continue;
			Bone* bone = it->second;
				
			boneInfo.push_back(std::pair<Bone*, BoneFrameInfo>(bone, BoneFrameInfo(it2.value())));

		}
	}
Ejemplo n.º 27
0
 /// Store and print a log message.
 void Log(std::string kind, std::string message){
   //if last log message equals this one, do not log.
   if (Storage["log"].size() > 0){
     JSON::ArrIter it = Storage["log"].ArrEnd() - 1;
     if (( *it)[2] == message){
       return;
     }
   }
   JSON::Value m;
   m.append(Util::epoch());
   m.append(kind);
   m.append(message);
   Storage["log"].append(m);
   Storage["log"].shrink(100); //limit to 100 log messages
   std::cout << "[" << kind << "] " << message << std::endl;
 }
Ejemplo n.º 28
0
void SimulationInfo::loadJSON(const JSON::Value &value) {
  const JSON::Dict &dict = value.getDict();

  if (dict.has("user")) user = dict["user"]->getString();
  if (dict.has("team")) team = dict["team"]->getString();
  if (dict.has("project")) project = (uint32_t)dict["project"]->getNumber();
  if (dict.has("run")) run = (uint32_t)dict["run"]->getNumber();
  if (dict.has("clone")) clone = (uint32_t)dict["clone"]->getNumber();
  if (dict.has("gen")) gen = (uint32_t)dict["gen"]->getNumber();
  if (dict.has("core_type"))
    coreType = (uint32_t)dict["core_type"]->getNumber();
  if (dict.has("core")) core = dict["core"]->getString();
  if (dict.has("total_iterations"))
    totalIterations = (uint64_t)dict["total_iterations"]->getNumber();
  if (dict.has("iterations_done"))
    iterationsDone = (uint64_t)dict["iterations_done"]->getNumber();
  if (dict.has("energy")) energy = dict["energy"]->getNumber();
  if (dict.has("temperature")) temperature = dict["temperature"]->getNumber();
  if (dict.has("start_time"))
    startTime = Time::parse(dict["start_time"]->getString());
  if (dict.has("timeout")) timeout = (uint64_t)dict["timeout"]->getNumber();
  if (dict.has("deadline")) deadline = (uint64_t)dict["deadline"]->getNumber();
  if (dict.has("eta")) eta = (uint64_t)dict["eta"]->getNumber();
  if (dict.has("progress")) progress = dict["progress"]->getNumber();
  if (dict.has("slot")) slot = (uint32_t)dict["slot"]->getNumber();
}
Ejemplo n.º 29
0
void JsonRpcResponse::setError(const Error& error, const json::Value& clientInfo)
{
   // remove result
   response_.erase(kRpcResult);
   response_.erase(kRpcAsyncHandle);

   const boost::system::error_code& ec = error.code();
   
   if ( ec.category() == jsonRpcCategory() )
   {
      setError(ec);
   }
   else
   {
      // execution error
      json::Object jsonError ;
      copyErrorCodeToJsonError(errc::ExecutionError, &jsonError);
      
      // populate sub-error field with error details
      json::Object executionError;
      executionError["code"] = ec.value();
      std::string errorCategoryName = ec.category().name();
      executionError["category"] = errorCategoryName;
      std::string errorMessage = ec.message();
      executionError["message"] = errorMessage;
      jsonError["error"] = executionError;
      if (!clientInfo.is_null())
      {
         jsonError["client_info"] = clientInfo;
      }

      // set error
      setField(kRpcError, jsonError);
   }      
}
    bool load_schema(const json::Value& schema, SchemaValidator& validator) {
        for (auto it = schema.cbegin(); it != schema.cend(); it++) {
            m_json_path.push_key(it.key());

            if (is_validator_object(*it)) {
                process_json_property(m_json_path.get_path(), *it, validator);
                m_json_path.pop_key();
                continue;
            }

            load_schema(*it, validator);

            m_json_path.pop_key();
        }
        return true;
    }