Пример #1
0
std::string Platform::getResourceString(Resource resource)
{
    size_t size = Resources::getResourceSize(resource);
    char * data = new char[size];
    Resources::getResourceData(resource, data);
    std::string dataStr(data, size);
    delete[] data;
    return dataStr;
}
NS_IMETHODIMP
AutoMounterSetting::Observe(nsISupports* aSubject,
                            const char* aTopic,
                            const PRUnichar* aData)
{
  if (strcmp(aTopic, MOZSETTINGS_CHANGED) != 0) {
    return NS_OK;
  }

  // Note that this function gets called for any and all settings changes,
  // so we need to carefully check if we have the one we're interested in.
  //
  // The string that we're interested in will be a JSON string that looks like:
  //  {"key":"ums.autoMount","value":true}

  nsCOMPtr<nsIThreadJSContextStack> stack =
    do_GetService("@mozilla.org/js/xpc/ContextStack;1");
  if (!stack) {
    ERR("Failed to get JSContextStack");
    return NS_OK;
  }
  JSContext* cx = stack->GetSafeJSContext();
  if (!cx) {
    ERR("Failed to GetSafeJSContext");
    return NS_OK;
  }
  nsDependentString dataStr(aData);
  JS::Value val;
  if (!JS_ParseJSON(cx, dataStr.get(), dataStr.Length(), &val) ||
      !val.isObject()) {
    return NS_OK;
  }
  JSObject& obj(val.toObject());
  JS::Value key;
  if (!JS_GetProperty(cx, &obj, "key", &key) ||
      !key.isString()) {
    return NS_OK;
  }
  JSBool match;
  if (!JS_StringEqualsAscii(cx, key.toString(), UMS_MODE, &match) ||
      (match != JS_TRUE)) {
    return NS_OK;
  }
  JS::Value value;
  if (!JS_GetProperty(cx, &obj, "value", &value) ||
      !value.isInt32()) {
    return NS_OK;
  }
  int32_t mode = value.toInt32();
  SetAutoMounterMode(mode);

  return NS_OK;
}
Пример #3
0
bool DDGNode::findDataLinkDest(DDGNode*& ptr, const std::string& path, const BaseLink* link)
{
    std::string pathStr, dataStr(" "); // non-empty data to specify that a data name is optionnal for DDGNode (as it can be a DataEngine)
    if (link)
    {
        if (!link->parseString(path, &pathStr, &dataStr))
            return false;
    }
    else
    {
        if (!BaseLink::ParseString(path, &pathStr, &dataStr, this->getOwner()))
            return false;
    }
    bool self = (pathStr.empty() || pathStr == "[]");
    if (dataStr == "") // no Data -> we look for a DataEngine
    {
        if (self)
        {
            ptr = this;
            return true;
        }
        else
        {
            Base* owner = this->getOwner();
            DataEngine* obj = NULL;
            if (!owner)
                return false;
            if (!owner->findLinkDest(obj, path, link))
                return false;
            ptr = obj;
            return true;
        }
    }
    Base* owner = this->getOwner();
    if (!owner)
        return false;
    if (self)
    {
        ptr = owner->findData(dataStr);
        return (ptr != NULL);
    }
    else
    {
        Base* obj = NULL;
        if (!owner->findLinkDest(obj, BaseLink::CreateString(pathStr), link))
            return false;
        if (!obj)
            return false;
        ptr = obj->findData(dataStr);
        return (ptr != NULL);
    }
    return false;
}
Пример #4
0
size_t
RESTHttpClient::processResponseHeader( void *buffer, size_t size, size_t nmemb, void *userp )
{
    RESTHttpClient *client = (RESTHttpClient *) userp;
    size_t length = size * nmemb;
    RESTRepresentation &dataRep = client->getInboundRepresentation();

    std::string dataStr( (const char *)buffer, length );

    boost::regex headerRE("([A-Za-z0-9]*): (.*)");
    boost::cmatch match;

    if( boost::regex_match( dataStr.c_str(), match, headerRE ) )
    {
        dataRep.addHTTPHeader( match[1].str(), match[2].str() );
    }

    return length;
}
Пример #5
0
bool Infogrames::load(Common::SeekableReadStream &dum) {
	int subSong = 0;
	int i;
	uint32 size;

	size = dum.size();
	if (size < 20)
		return false;

	_data = new uint8[size];
	dum.seek(0);
	dum.read(_data, size);

	Common::MemoryReadStream dataStr(_data, size);

	dataStr.seek(subSong * 2);
	dataStr.seek(dataStr.readUint16BE());
	_subSong = _data + dataStr.pos();
	if (_subSong > (_data + size))
		return false;

	_speedCounter = dataStr.readUint16BE();
	_speed = _speedCounter;
	_volSlideBlocks = _subSong + dataStr.readUint16BE();
	_periodSlideBlocks = _subSong + dataStr.readUint16BE();
	for (i = 0; i < 4; i++) {
		_chn[i].cmdBlockIndices = _subSong + dataStr.readUint16BE();
		_chn[i].flags = 0x81;
	}
	_cmdBlocks = _data + dataStr.pos() + 2;

	if ((_volSlideBlocks > (_data + size)) ||
			(_periodSlideBlocks > (_data + size)) ||
			(_chn[0].cmdBlockIndices > (_data + size)) ||
			(_chn[1].cmdBlockIndices > (_data + size)) ||
			(_chn[2].cmdBlockIndices > (_data + size)) ||
			(_chn[3].cmdBlockIndices > (_data + size)) ||
			(_cmdBlocks > (_data + size)))
		return false;

	startPaula();
	return true;
}
Пример #6
0
    void TCPSocket::_Write(const ValueList& args, KValueRef result)
    {
        args.VerifyException("write", "s|o");

        BytesRef data;
        if (args.at(0)->IsString())
        {
            std::string dataStr(args.GetString(0));
            data = new Bytes(dataStr);
        }
        else
        {
            data = args.GetObject(0).cast<Bytes>();
            if (data.isNull())
            {
                throw ValueException::FromString("Argument is not Bytes object");
            }
        }

        Write(data);
    }
/**
 * @brief RequestHandler::handlePost
 * @param uri
 * @param p_data
 * @return
 */
void RequestHandler::handleRequest(ConnectionInfo &conInfo)
{
    vector<string> parsedURI = parseURI(conInfo.url);

    string p_image[] = {"index", "images", "IDENTIFIER", ""};
    string p_searchImage[] = {"index", "searcher", ""};
    string p_ioIndex[] = {"index", "io", ""};

    Json::Value ret;
    conInfo.answerCode = MHD_HTTP_OK;

    if (testURIWithPattern(parsedURI, p_image)
        && conInfo.connectionType == PUT)
    {
        u_int32_t i_imageId = atoi(parsedURI[2].c_str());

        u_int32_t i_ret = featureExtractor->processNewImage(
            i_imageId, conInfo.uploadedData.size(), conInfo.uploadedData.data());

        ret["type"] = Converter::codeToString(i_ret);
        ret["image_id"] = Json::Value(i_imageId);
    }
    else if (testURIWithPattern(parsedURI, p_image)
             && conInfo.connectionType == DELETE)
    {
        u_int32_t i_imageId = atoi(parsedURI[2].c_str());

        u_int32_t i_ret = index->removeImage(i_imageId);
        ret["type"] = Converter::codeToString(i_ret);
        ret["image_id"] = Json::Value(i_imageId);
    }
    else if (testURIWithPattern(parsedURI, p_searchImage)
             && conInfo.connectionType == POST)
    {
        SearchRequest req;

        req.imageData = conInfo.uploadedData;
        req.client = NULL;
        u_int32_t i_ret = imageSearcher->searchImage(req);

        ret["type"] = Converter::codeToString(i_ret);
        if (i_ret == OK)
        {
            Json::Value imageIds(Json::arrayValue);
            for (unsigned i = 0; i < req.results.size(); ++i)
                imageIds.append(req.results[i]);
            ret["image_ids"] = imageIds;
        }
    }
    else if (testURIWithPattern(parsedURI, p_ioIndex)
             && conInfo.connectionType == POST)
    {
        string dataStr(conInfo.uploadedData.begin(),
                       conInfo.uploadedData.end());

        Json::Value data = StringToJson(dataStr);
        u_int32_t i_ret;
        if (data["type"] == "LOAD")
            i_ret = index->load(data["index_path"].asString());
        else if (data["type"] == "WRITE")
            i_ret = index->write(data["index_path"].asString());
        else if (data["type"] == "CLEAR")
            i_ret = index->clear();
        else
            i_ret = ERROR_GENERIC;

        ret["type"] = Converter::codeToString(i_ret);
    }
    else
    {
        conInfo.answerCode = MHD_HTTP_INTERNAL_SERVER_ERROR;
        ret["type"] = Converter::codeToString(ERROR_GENERIC);
    }

    conInfo.answerString = JsonToString(ret);
}
Пример #8
0
	// Received new data:
	void received(int id, asio::streambuf &readBuffer, std::size_t bytesTransferred)
	{
		string dataStr(boost::asio::buffer_cast<const char*>(readBuffer.data()), readBuffer.size());
		string error;

		//we're expecting a new request:
		if (mState==REQUEST || mState==WAIT_LONGPOLL)
		{
			//if there is still an outstanding longpoll, cancel it:
			if (mState==WAIT_LONGPOLL)
			{
				respond(true);
			}

			//resize data to first delimiter:
			dataStr.resize(dataStr.find(delimiter)+delimiter.length());
			readBuffer.consume(dataStr.length());

			DEB(id << " got http REQUEST: \n" << dataStr);

			//determine the kind of request:
 			smatch what;
 			if (!regex_search(
 				dataStr,
 				what,
 				boost::regex("^(GET|POST) ([^? ]*)([^ ]*) HTTP/(1..)$")
 			))
 			{
				error="Cant parse request.";
 			}
			else
			{
				mRequestType=what[1];
				mRequestUrl=what[2];
				mRequestQuery=what[3];
				mRequestVersion=what[4];
				DEB("REQUEST query: " << mRequestQuery);

				//create a regex iterator for http headers
				mHeaders.clear();
				boost::sregex_iterator headerI(
					dataStr.begin(),
					dataStr.end(),
					boost::regex("^([[:alnum:]-]*): (.*?)$")
				);

				//parse http headers
				while (headerI!=sregex_iterator())
				{
					string header=(*headerI)[1].str();
					string value=(*headerI)[2].str();

					//headers handling is lowercase in synapse!
					transform(header.begin(), header.end(), header.begin(), ::tolower);

					mHeaders[header]=value;
					headerI++;
				}

				//this header MUST be set on longpoll requests:
				//if the client doesnt has one yet, httpSessionMan will assign a new one.
				try
				{
					mAuthCookie=mHeaders["x-synapse-authcookie"];
				}
				catch(...)
				{
					mAuthCookie=0;
				}

				//proceed based on requestType:
				//a GET or empty POST:
				if (mRequestType=="GET" || (int)mHeaders["content-length"]==0)
				{
					if (respond())
					{
						mState=REQUEST;
					}
					else
					{
						DEB(id << " is now waiting for longpoll results");
						mState=WAIT_LONGPOLL;
					}
					return;
				}
				//a POST with content:
				else
				{
					if ( (int)mHeaders["content-length"]<0  || (int)mHeaders["content-length"] > config["maxContent"] )
					{
						error="Invalid Content-Length";
					}
					else
					{
						//change state to read the contents of the POST:
						mState=CONTENT;
						return;
					}
				}
			}
		}
		else
		//we're expecting the contents of a POST request.
		if (mState==CONTENT)
		{
			if (readBuffer.size() < mHeaders["content-length"])
			{
				error="Didn't receive enough content-bytes!";
				DEB(id <<  " ERROR: Expected " << mHeaders["content-length"].str() << " bytes, but only got: " << bytesTransferred);
			}
			else
			{
				dataStr.resize(mHeaders["content-length"]);
				readBuffer.consume(mHeaders["content-length"]);
				DEB(id << " got http CONTENT with length=" << dataStr.size() << ": \n" << dataStr);

				//POST to the special send url?
				if (mRequestUrl=="/synapse/send")
				{
					error=httpSessionMan.sendMessage(mAuthCookie, dataStr);
					if (error=="")
					{
						//DONT:respond with jsondata if we have something in the queue anyways
						//DONT:respondJsonQueue(false,false);
						//we cant do this, because then the order of messages isnt garanteed. so just respond with a boring empty string:
						respondString(200, "");
					}
					else
						respondError(400, error);

					mState=REQUEST;
					return;
				}
				else
				{
					//ignore whatever is posted, and just respond normally:
					DEB(id << " ignored POST content");
					if (respond())
						mState=REQUEST;
					else
						mState=WAIT_LONGPOLL;
					return;
				}
			}
		}

		//ERROR(id << " had error while processing http data: " << error);
		error="Bad request: "+error;
		respondError(400, error);
		doDisconnect();
		return;

	}
Пример #9
0
void LoaderCutsceneDAT::load(CutsceneTracks &tracks, FileHandle file)
{
	std::string dataStr(file->data, file->length);
	std::stringstream ss(dataStr);

	int numZooms = 0;
	ss >> numZooms;
	ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

	for(int i = 0; i < numZooms; ++i) {
		float t = 0.f;
		float z = 0.f;
		ss >> t;
		ss.ignore(1, ',');
		ss >> z;
		ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
		tracks.zoom[t] = z;
		tracks.duration = std::max(t, tracks.duration);
	}

	ss.ignore(std::numeric_limits<std::streamsize>::max(), ';');

	int numRotations = 0;
	ss >> numRotations;
	ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

	for(int i = 0; i < numRotations; ++i) {
		float t = 0.f;
		float r = 0.f;
		ss >> t;
		ss.ignore(1, ',');
		ss >> r;
		ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
		tracks.rotation[t] = r;
		tracks.duration = std::max(t, tracks.duration);
	}

	ss.ignore(std::numeric_limits<std::streamsize>::max(), ';');

	int numPositions = 0;
	ss >> numPositions;
	ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

	for(int i = 0; i < numPositions; ++i) {
		float t = 0.f;
		glm::vec3 p;
		ss >> t;
		ss.ignore(1, ',');
		ss >> p.x;
		ss.ignore(1, ',');
		ss >> p.y;
		ss.ignore(1, ',');
		ss >> p.z;
		ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
		tracks.position[t] = p;
		tracks.duration = std::max(t, tracks.duration);
	}

	ss.ignore(std::numeric_limits<std::streamsize>::max(), ';');

	int numTargets = 0;
	ss >> numTargets;
	ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

	for(int i = 0; i < numTargets; ++i) {
		float t = 0.f;
		glm::vec3 p;
		ss >> t;
		ss.ignore(1, ',');
		ss >> p.x;
		ss.ignore(1, ',');
		ss >> p.y;
		ss.ignore(1, ',');
		ss >> p.z;
		ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
		tracks.target[t] = p;
		tracks.duration = std::max(t, tracks.duration);
	}
}