AffinityZoneEditor *AffinityZonesDock::createZoneFromName(const QString &zoneName) { auto editor = new AffinityZoneEditor(this); _editorsTabs->addTab(editor, zoneName); if (zoneName == getSettings().value("AffinityZones/currentZone").toString()) _editorsTabs->setCurrentWidget(editor); //restore the settings from save -- even if this is a new panel with the same name as a previous one auto json = getSettings().value("AffinityZones/zones/"+zoneName).toString(); if (not json.isEmpty()) try { Poco::JSON::Parser p; p.parse(json.toStdString()); auto dataObj = p.getHandler()->asVar().extract<Poco::JSON::Object::Ptr>(); editor->loadFromConfig(dataObj); } catch (const Poco::JSON::JSONException &ex) { poco_error_f2(Poco::Logger::get("PothosGui.AffinityZonesDock"), "Failed to load editor for zone '%s' -- %s", zoneName.toStdString(), ex.displayText()); } //now connect the changed signal after initialization+restore changes connect(editor, SIGNAL(settingsChanged(void)), this, SLOT(handleZoneEditorChanged(void))); connect(editor, SIGNAL(settingsChanged(void)), _mapper, SLOT(map(void))); _mapper->setMapping(editor, zoneName); //when to update colors connect(editor, SIGNAL(settingsChanged(void)), this, SLOT(updateTabColors(void))); this->updateTabColors(); return editor; }
void WindowFunction::setType(const std::string &type) { //parse the input Poco::RegularExpression::MatchVec matches; Poco::RegularExpression("^\\s*(\\w+)\\s*(\\((.*)\\))?\\s*$").match(type, 0, matches); if (matches.empty()) throw Pothos::InvalidArgumentException("WindowFunction("+type+")", "cant parse window type"); //parse the args Poco::JSON::Array::Ptr args(new Poco::JSON::Array()); if (matches.size() > 3) { auto argsStr = type.substr(matches[3].offset, matches[3].length); Poco::JSON::Parser p; p.parse("["+argsStr+"]"); args = p.getHandler()->asVar().extract<Poco::JSON::Array::Ptr>(); } //check input auto name = Poco::toLower(type.substr(matches[1].offset, matches[1].length)); if (name == "kaiser") { if (args->size() != 1) throw Pothos::InvalidArgumentException("WindowFunction("+type+")", "expects format: kaiser(beta)"); } else if (args->size() != 0) throw Pothos::InvalidArgumentException("WindowFunction("+type+")", name + " takes no arguments"); //bind window function if (name == "rectangular") _calc = &rectangular; else if (name == "hann") _calc = &hann; else if (name == "hamming") _calc = &hamming; else if (name == "blackman") _calc = &blackman; else if (name == "bartlett") _calc = &bartlett; else if (name == "flattop") _calc = &flattop; else if (name == "kaiser") _calc = std::bind(&kaiser, std::placeholders::_1, std::placeholders::_2, args->getElement<double>(0)); else throw Pothos::InvalidArgumentException("WindowFunction::setType("+type+")", "unknown window name"); this->reload(); }
std::future<bool> UserData::SendFriendResponse(const UUID &id, const UUID &requester, const std::string &response, BooleanCallback success, APIFailureCallback failure) { return std::async(std::launch::async, [=]() -> bool { std::stringstream url; url << "/friends/" << id.toString() << "/response"; std::map<std::string, std::string> params{ std::make_pair("requester_id", requester.toString()), std::make_pair("action", response) }; std::string error; APIRequestManager *manager = APIRequestManager::GetDefaultManager(); boost::optional<std::string> response = manager->Send(url.str(), "POST", params, error); if (response.is_initialized()) { Poco::JSON::Parser parser; auto jsonObject = parser.parse(response.get()).extract<JSONObject::Ptr>(); return jsonObject->getValue<bool>("success"); } else { if (failure) { failure(error); } return false; } }); }
string ExposerConfig::extract_token(string response_string) { try { //Try to extract token Poco::JSON::Parser parser; Poco::Dynamic::Var result = parser.parse(response_string); Poco::JSON::Object::Ptr object = result.extract<Poco::JSON::Object::Ptr>(); string tmptoken = object->get("token"); ostringstream tmpmsg; //tmpmsg << " ===== Got a token: " << tmptoken; tmpmsg << " ===== Got a token."; Log::log(Log::INFO, tmpmsg.str()); return tmptoken; } catch (std::exception &ex) { ostringstream tmpmsg; tmpmsg << "Exception when trying to read token: " << ex.what(); Log::log(Log::ERROR, tmpmsg.str()); return ""; } }
int main(int argc, char** argv) { Poco::JSON::Object::Ptr obj; std::string dir = Poco::Environment::get("POCO_BASE") + "/JSON/samples/Benchmark/"; Poco::Path filePath(dir, "input"); std::ostringstream ostr; if ( filePath.isFile() ) { Poco::File inputFile(filePath); if ( inputFile.exists() ) { Poco::FileInputStream fis(filePath.toString()); Poco::StreamCopier::copyStream(fis, ostr); } else { std::cout << filePath.toString() << " doesn't exist!" << std::endl; return 1; } } std::cout << std::setw(25) << "POCO JSON"; std::string jsonStr = ostr.str(); try { Poco::JSON::DefaultHandler handler; Poco::JSON::Parser parser; parser.setHandler(&handler); Poco::Timestamp time1; parser.parse(jsonStr); Poco::DynamicAny result = handler.result(); Poco::Timestamp time2; printTimeDiff(time1, time2); if ( result.type() == typeid(Poco::JSON::Object::Ptr) ) { obj = result.extract<Poco::JSON::Object::Ptr>(); } //Serialize to string std::ostringstream out; Poco::Timestamp time3; obj->stringify(out); Poco::Timestamp time4; printTimeDiff(time3, time4); std::cout << std::endl; } catch(Poco::JSON::JSONException jsone) { std::cout << jsone.message() << std::endl; } return 0; }
void BaseData::FromJSONString(const std::string &json) { Poco::JSON::Parser parser; std::stringstream stream(json); auto object = parser.parse(stream).extract<JSONObject::Ptr>(); return this->FromJSON(object); }
void GraphDraw::dropEvent(QDropEvent *event) { const auto &byteArray = event->mimeData()->data("text/json/pothos_block"); Poco::JSON::Parser p; p.parse(std::string(byteArray.constData(), byteArray.size())); const auto blockDesc = p.getHandler()->asVar().extract<Poco::JSON::Object::Ptr>(); this->getGraphEditor()->handleAddBlock(blockDesc, event->pos()); QWidget::dropEvent(event); }
void load(Archive & ar, Poco::JSON::Object::Ptr &t, const unsigned int) { bool isNull = false; ar >> isNull; if (isNull) return; std::string s; ar >> s; Poco::JSON::Parser p; p.parse(s); t = p.getHandler()->asVar().extract<Poco::JSON::Object::Ptr>(); }
//! Turn a simple expression into a type-specific container static Poco::Dynamic::Var exprToDynVar(const std::string &expr) { try { Poco::JSON::Parser p; p.parse("["+expr+"]"); return p.getHandler()->asVar().extract<Poco::JSON::Array::Ptr>()->get(0); } catch (const Poco::Exception &){} return expr; }
OpenClKernel::OpenClKernel(const std::string &deviceId, const std::string &portMarkup): _localSize(1), _globalFactor(1.0), _productionFactor(1.0) { const auto colon = deviceId.find(":"); const auto platformIndex = Poco::NumberParser::parseUnsigned(deviceId.substr(0, colon)); const auto deviceIndex = Poco::NumberParser::parseUnsigned(deviceId.substr(colon+1)); /* Identify a platform */ cl_int err = 0; cl_uint num_platforms = 0; cl_platform_id platforms[64]; err = clGetPlatformIDs(64, platforms, &num_platforms); if (err < 0) throw Pothos::Exception("OpenClKernel::clGetPlatformIDs()", clErrToStr(err)); if (platformIndex >= num_platforms) throw Pothos::Exception("OpenClKernel()", "platform index does not exist"); _platform = platforms[platformIndex]; /* Access a device */ cl_uint num_devices = 0; cl_device_id devices[64]; err = clGetDeviceIDs(_platform, CL_DEVICE_TYPE_ALL, 64, devices, &num_devices); if (err < 0) throw Pothos::Exception("OpenClKernel::clGetDeviceIDs()", clErrToStr(err)); if (deviceIndex >= num_devices) throw Pothos::Exception("OpenClKernel()", "device index does not exist"); _device = devices[deviceIndex]; /* Create context */ _context = lookupContextCache(_device); /* Create ports */ _myDomain = "OpenCl_"+std::to_string(size_t(_device)); Poco::JSON::Parser p; p.parse(portMarkup); const auto ports = p.getHandler()->asVar().extract<Poco::JSON::Array::Ptr>(); const auto inputs = ports->getArray(0); const auto outputs = ports->getArray(1); for (size_t i = 0; i < inputs->size(); i++) { this->setupInput(i, Pothos::DType("custom", inputs->getElement<int>(i)), _myDomain); } for (size_t i = 0; i < outputs->size(); i++) { this->setupOutput(i, Pothos::DType("custom", outputs->getElement<int>(i)), _myDomain); } this->registerCall(POTHOS_FCN_TUPLE(OpenClKernel, setSource)); this->registerCall(POTHOS_FCN_TUPLE(OpenClKernel, setLocalSize)); this->registerCall(POTHOS_FCN_TUPLE(OpenClKernel, getLocalSize)); this->registerCall(POTHOS_FCN_TUPLE(OpenClKernel, setGlobalFactor)); this->registerCall(POTHOS_FCN_TUPLE(OpenClKernel, getGlobalFactor)); this->registerCall(POTHOS_FCN_TUPLE(OpenClKernel, setProductionFactor)); this->registerCall(POTHOS_FCN_TUPLE(OpenClKernel, getProductionFactor)); }
/*********************************************************************** * information aquisition **********************************************************************/ static InfoResult getInfo(const std::string &uriStr) { InfoResult info; POTHOS_EXCEPTION_TRY { auto env = Pothos::RemoteClient(uriStr).makeEnvironment("managed"); info.hostInfo = env->findProxy("Pothos/System/HostInfo").call<Pothos::System::HostInfo>("get"); info.numaInfo = env->findProxy("Pothos/System/NumaInfo").call<std::vector<Pothos::System::NumaInfo>>("get"); auto deviceInfo = env->findProxy("Pothos/Util/DeviceInfoUtils").call<std::string>("dumpJson"); Poco::JSON::Parser p; p.parse(deviceInfo); info.deviceInfo = p.getHandler()->asVar().extract<Poco::JSON::Array::Ptr>(); } POTHOS_EXCEPTION_CATCH(const Pothos::Exception &ex) { poco_error_f2(Poco::Logger::get("PothosGui.SystemInfoTree"), "Failed to query system info %s - %s", uriStr, ex.displayText()); }
/* Private */ void SpellData::ParseSpellList(std::string &response, TSpellDataList &items) { Poco::JSON::Parser parser; auto parsed = parser.parse(response); if (parsed.isArray()) { auto spellObjects = parsed.extract<JSONArray::Ptr>(); for (int i = 0; i < spellObjects->size(); i++) { JSONObject *object = spellObjects->getObject(i); auto data = std::make_shared<SpellData>(); data->FromJSON(object); items.push_back(data); } } }
/*********************************************************************** * create JSON stats object **********************************************************************/ static Poco::JSON::Object::Ptr queryWorkStats(const Pothos::Proxy &block) { //try recursive traversal try { auto json = block.call<std::string>("queryJSONStats"); Poco::JSON::Parser p; p.parse(json); return p.getHandler()->asVar().extract<Poco::JSON::Object::Ptr>(); } catch (Pothos::Exception &) {} //otherwise, regular block, query stats auto actor = block.callProxy("get:_actor"); auto workStats = actor.call<Poco::JSON::Object::Ptr>("queryWorkStats"); Poco::JSON::Object::Ptr topStats(new Poco::JSON::Object()); topStats->set(block.call<std::string>("uid"), workStats); return topStats; }
void SpellData::GetSpellById(const UUID &id, std::function<void(SpellDataPtr)> success, APIFailureCallback failure) { APIRequestManager *manager = APIRequestManager::GetDefaultManager(); std::stringstream url; url << "/spell/" << id.toString(); manager->Send(url.str(), "GET", "", [success](std::istream &stream) { Poco::JSON::Parser parser; auto object = parser.parse(stream).extract<JSONObject::Ptr>(); auto data = std::make_shared<SpellData>(); data->FromJSON(object); success(data); }, [failure](const std::string &error) { failure(error); }); }
/*********************************************************************** * String/file parser - make JSON object from string **********************************************************************/ static Poco::JSON::Object::Ptr parseJSONStr(const std::string &json) { //determine markup string or file path bool isPath = false; try {isPath = Poco::File(json).exists();} catch (...){} //parse the json string/file to a JSON object Poco::JSON::Parser p; if (isPath) { std::ifstream ifs(json); p.parse(ifs); } else { p.parse(json); } return p.getHandler()->asVar().extract<Poco::JSON::Object::Ptr>(); }
void SpellData::Save(SpellDataSingleCallback success, APIFailureCallback failure) { APIRequestManager *manager = APIRequestManager::GetDefaultManager(); std::stringstream url; url << "/spell/" << this->GetId().toString(); std::string body = this->ToJSONString(); manager->Send(url.str(), "POST", body, [success](std::istream &stream) { Poco::JSON::Parser parser; auto object = parser.parse(stream).extract<JSONObject::Ptr>(); auto data = std::make_shared<SpellData>(); data->FromJSON(object); success(data); }, [failure](const std::string &error) { failure(error); }); }
Pothos::ThreadPoolArgs::ThreadPoolArgs(const std::string &json): numThreads(0), priority(0.0) { //parse to JSON object Poco::JSON::Parser p; p.parse(json); auto topObj = p.getHandler()->asVar().extract<Poco::JSON::Object::Ptr>(); //parse out the optional fields this->numThreads = topObj->optValue<int>("numThreads", 0); this->priority = topObj->optValue<double>("priority", 0.0); this->affinityMode = topObj->optValue<std::string>("affinityMode", ""); this->yieldMode = topObj->optValue<std::string>("yieldMode", ""); //parse out the affinity list Poco::JSON::Array::Ptr affinityArray; if (topObj->isArray("affinity")) affinityArray = topObj->getArray("affinity"); if (affinityArray) for (size_t i = 0; i < affinityArray->size(); i++) { this->affinity.push_back(affinityArray->getElement<int>(i)); } }
string ExposerConfig::extract_sessionid(string json_string) { try { //Try to extract sessionid Poco::JSON::Parser parser; Poco::Dynamic::Var result = parser.parse(json_string); Poco::JSON::Object::Ptr object = result.extract<Poco::JSON::Object::Ptr>(); string tmpsessionid = object->get("id"); ostringstream tmpmsg; tmpmsg << " ===== Got a sessionid: " << tmpsessionid; Log::log(Log::INFO, tmpmsg.str()); return tmpsessionid; } catch (Poco::Exception &ex) { ostringstream tmpmsg; tmpmsg << "Exception when trying to read sessionid: " << ex.displayText(); Log::log(Log::ERROR, tmpmsg.str()); return ""; } }
bool ChildProcessSession::loadDocument(const char *buffer, int length, StringTokenizer& tokens) { Poco::Mutex::ScopedLock lock(_mutex); int part = -1; if (tokens.count() < 2) { sendTextFrame("error: cmd=load kind=syntax"); return false; } std::string timestamp; parseDocOptions(tokens, part, timestamp); assert(!_docURL.empty()); assert(!_jailedFilePath.empty()); if (_loKitDocument == nullptr) Log::info("Loading new document from URI: [" + _jailedFilePath + "]."); else Log::info("Loading view to document from URI: [" + _jailedFilePath + "]."); if (_loKitDocument != nullptr) { _viewId = _loKitDocument->pClass->createView(_loKitDocument); } else { if ( LIBREOFFICEKIT_HAS(_loKit, registerCallback)) _loKit->pClass->registerCallback(_loKit, myCallback, this); if ((_loKitDocument = _loKit->pClass->documentLoad(_loKit, _jailedFilePath.c_str())) == nullptr) { Log::error("Failed to load: " + _jailedFilePath + ", error: " + _loKit->pClass->getError(_loKit)); sendTextFrame("error: cmd=load kind=failed"); return false; } } _loKitDocument->pClass->setView(_loKitDocument, _viewId); std::string renderingOptions; if (!_docOptions.empty()) { Poco::JSON::Parser parser; Poco::Dynamic::Var var = parser.parse(_docOptions); Poco::JSON::Object::Ptr object = var.extract<Poco::JSON::Object::Ptr>(); renderingOptions = object->get("rendering").toString(); } _loKitDocument->pClass->initializeForRendering(_loKitDocument, (renderingOptions.empty() ? nullptr : renderingOptions.c_str())); if (_docType != "text" && part != -1) { _clientPart = part; _loKitDocument->pClass->setPart(_loKitDocument, part); } _loKitDocument->pClass->registerCallback(_loKitDocument, myCallback, this); if (!getStatus(buffer, length)) return false; _onLoad(_loKitDocument, _viewId); return true; }
std::string Pothos::Topology::dumpJSON(const std::string &request) { //extract input request Poco::JSON::Parser p; p.parse(request.empty()?"{}":request); auto configObj = p.getHandler()->asVar().extract<Poco::JSON::Object::Ptr>(); assert(configObj); const auto modeConfig = configObj->optValue<std::string>("mode", "flat"); //parse request into traversal arguments const bool flatten = (modeConfig == "flat"); const bool traverse = (modeConfig != "rendered"); const auto &flows = (modeConfig == "rendered")?_impl->activeFlatFlows:_impl->flows; //replace rendered names with names from flattened hierarchy Poco::JSON::Object::Ptr flatBlocks; if (modeConfig == "rendered") { Poco::JSON::Parser pFlat; pFlat.parse(this->dumpJSON("{\"mode\":\"flat\"}")); auto flatObj = pFlat.getHandler()->asVar().extract<Poco::JSON::Object::Ptr>(); assert(flatObj); flatBlocks = flatObj->getObject("blocks"); assert(flatBlocks); } //output object Poco::JSON::Object::Ptr topObj(new Poco::JSON::Object()); //create blocks map Poco::JSON::Object::Ptr blocksObj(new Poco::JSON::Object()); topObj->set("blocks", blocksObj); for (const auto &block : getObjSetFromFlowList(flows)) { //gather block info Poco::JSON::Object::Ptr blockObj(new Poco::JSON::Object()); const auto blockId = block.call<std::string>("uid"); blocksObj->set(blockId, blockObj); //replace rendered names with names from flattened hierarchy blockObj->set("name", block.call<std::string>("getName")); if (flatBlocks and flatBlocks->has(blockId)) { blockObj->set("name", flatBlocks->getObject(blockId)->getValue<std::string>("name")); } //input port info Poco::JSON::Array::Ptr inputsArray(new Poco::JSON::Array()); for (const auto &portInfo : block.call<std::vector<PortInfo>>("inputPortInfo")) { inputsArray->add(portInfoToObj(portInfo)); } if (inputsArray->size() > 0) blockObj->set("inputs", inputsArray); //output port info Poco::JSON::Array::Ptr outputsArray(new Poco::JSON::Array()); for (const auto &portInfo : block.call<std::vector<PortInfo>>("outputPortInfo")) { outputsArray->add(portInfoToObj(portInfo)); } if (outputsArray->size() > 0) blockObj->set("outputs", outputsArray); //sub-topology info if (traverse and this->uid() != blockId) try { auto subDump = block.call<std::string>("dumpJSON", "{\"mode\":\"top\"}"); Poco::JSON::Parser psub; psub.parse(subDump); auto subObj = psub.getHandler()->asVar().extract<Poco::JSON::Object::Ptr>(); assert(subObj); std::vector<std::string> names; subObj->getNames(names); for (const auto &name : names) blockObj->set(name, subObj->get(name)); } catch (const Pothos::Exception &){} } //create connections list Poco::JSON::Array::Ptr connsArray(new Poco::JSON::Array()); topObj->set("connections", connsArray); for (const auto &flow : flows) { Poco::JSON::Object::Ptr connObj(new Poco::JSON::Object()); connsArray->add(connObj); connObj->set("srcId", flow.src.uid); connObj->set("srcName", flow.src.name); connObj->set("dstId", flow.dst.uid); connObj->set("dstName", flow.dst.name); } //recursive flatten when instructed while (flatten and flattenDump(topObj)); //return the string-formatted result std::stringstream ss; topObj->stringify(ss, 4); return ss.str(); }
bool MasterProcessSession::_handleInput(const char *buffer, int length) { const std::string firstLine = getFirstLine(buffer, length); StringTokenizer tokens(firstLine, " ", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM); if (tokens[0] == "loolclient") { const auto versionTuple = ParseVersion(tokens[1]); if (std::get<0>(versionTuple) != ProtocolMajorVersionNumber || std::get<1>(versionTuple) != ProtocolMinorVersionNumber) { sendTextFrame("error: cmd=loolclient kind=badversion"); return false; } sendTextFrame("loolserver " + GetProtocolVersion()); return true; } if (haveSeparateProcess()) { // Note that this handles both forwarding requests from the client to the child process, and // forwarding replies from the child process to the client. Or does it? // Snoop at some messages and manipulate tile cache information as needed auto peer = _peer.lock(); if (_kind == Kind::ToPrisoner) { if (tokens[0] == "curpart:" && tokens.count() == 2 && getTokenInteger(tokens[1], "part", _curPart)) { return true; } if (tokens.count() == 2 && tokens[0] == "saveas:") { std::string url; if (!getTokenString(tokens[1], "url", url)) return true; if (peer) { // Save as completed, inform the other (Kind::ToClient) // MasterProcessSession about it. const std::string filePrefix("file:///"); if (url.find(filePrefix) == 0) { // Rewrite file:// URLs, as they are visible to the outside world. Path path(MasterProcessSession::getJailPath(_childId), url.substr(filePrefix.length())); url = filePrefix + path.toString().substr(1); } peer->_saveAsQueue.put(url); } return true; } } if (_kind == Kind::ToPrisoner && peer && peer->_tileCache) { if (tokens[0] == "tile:") { int part, width, height, tilePosX, tilePosY, tileWidth, tileHeight; if (tokens.count() < 8 || !getTokenInteger(tokens[1], "part", part) || !getTokenInteger(tokens[2], "width", width) || !getTokenInteger(tokens[3], "height", height) || !getTokenInteger(tokens[4], "tileposx", tilePosX) || !getTokenInteger(tokens[5], "tileposy", tilePosY) || !getTokenInteger(tokens[6], "tilewidth", tileWidth) || !getTokenInteger(tokens[7], "tileheight", tileHeight)) assert(false); assert(firstLine.size() < static_cast<std::string::size_type>(length)); peer->_tileCache->saveTile(part, width, height, tilePosX, tilePosY, tileWidth, tileHeight, buffer + firstLine.size() + 1, length - firstLine.size() - 1); } else if (tokens[0] == "status:") { peer->_tileCache->saveTextFile(std::string(buffer, length), "status.txt"); } else if (tokens[0] == "commandvalues:") { const std::string stringMsg(buffer, length); const auto index = stringMsg.find_first_of("{"); if (index != std::string::npos) { const std::string stringJSON = stringMsg.substr(index); Poco::JSON::Parser parser; const auto result = parser.parse(stringJSON); const auto object = result.extract<Poco::JSON::Object::Ptr>(); const std::string commandName = object->get("commandName").toString(); if (commandName.find(".uno:CharFontName") != std::string::npos || commandName.find(".uno:StyleApply") != std::string::npos) { // other commands should not be cached peer->_tileCache->saveTextFile(stringMsg, "cmdValues" + commandName + ".txt"); } } } else if (tokens[0] == "partpagerectangles:") { if (tokens.count() > 1 && !tokens[1].empty()) peer->_tileCache->saveTextFile(std::string(buffer, length), "partpagerectangles.txt"); } else if (tokens[0] == "invalidatecursor:") { peer->_tileCache->setEditing(true); } else if (tokens[0] == "invalidatetiles:") { // FIXME temporarily, set the editing on the 1st invalidate, TODO extend // the protocol so that the client can set the editing or view only. peer->_tileCache->setEditing(true); assert(firstLine.size() == static_cast<std::string::size_type>(length)); peer->_tileCache->invalidateTiles(firstLine); } else if (tokens[0] == "renderfont:") { std::string font; if (tokens.count() < 2 || !getTokenString(tokens[1], "font", font)) assert(false); assert(firstLine.size() < static_cast<std::string::size_type>(length)); peer->_tileCache->saveRendering(font, "font", buffer + firstLine.size() + 1, length - firstLine.size() - 1); } } forwardToPeer(buffer, length); return true; } if (tokens[0] == "child") { if (_kind != Kind::ToPrisoner) { sendTextFrame("error: cmd=child kind=invalid"); return false; } if (!_peer.expired()) { sendTextFrame("error: cmd=child kind=invalid"); return false; } if (tokens.count() != 4) { sendTextFrame("error: cmd=child kind=syntax"); return false; } const auto childId = tokens[1]; setId(tokens[2]); const Process::PID pidChild = std::stoull(tokens[3]); std::unique_lock<std::mutex> lock(AvailableChildSessionMutex); AvailableChildSessions.emplace(getId(), shared_from_this()); Log::info() << getName() << " mapped " << this << " childId=" << childId << ", id=" << getId() << " into _availableChildSessions, size=" << AvailableChildSessions.size() << Log::end; _childId = childId; _pidChild = pidChild; lock.unlock(); AvailableChildSessionCV.notify_one(); } else if (_kind == Kind::ToPrisoner) { // Message from child process to be forwarded to client. // I think we should never get here Log::error(getName() + ": Unexpected request [" + tokens[0] + "]."); assert(false); } else if (tokens[0] == "load") { if (_docURL != "") { sendTextFrame("error: cmd=load kind=docalreadyloaded"); return false; } return loadDocument(buffer, length, tokens); } else if (tokens[0] != "canceltiles" && tokens[0] != "clientzoom" && tokens[0] != "clientvisiblearea" && tokens[0] != "commandvalues" && tokens[0] != "disconnect" && tokens[0] != "downloadas" && tokens[0] != "getchildid" && tokens[0] != "gettextselection" && tokens[0] != "paste" && tokens[0] != "insertfile" && tokens[0] != "invalidatetiles" && tokens[0] != "key" && tokens[0] != "mouse" && tokens[0] != "partpagerectangles" && tokens[0] != "renderfont" && tokens[0] != "requestloksession" && tokens[0] != "resetselection" && tokens[0] != "saveas" && tokens[0] != "selectgraphic" && tokens[0] != "selecttext" && tokens[0] != "setclientpart" && tokens[0] != "setpage" && tokens[0] != "status" && tokens[0] != "tile" && tokens[0] != "tilecombine" && tokens[0] != "unload" && tokens[0] != "uno") { sendTextFrame("error: cmd=" + tokens[0] + " kind=unknown"); return false; } else if (_docURL == "") { sendTextFrame("error: cmd=" + tokens[0] + " kind=nodocloaded"); return false; } else if (tokens[0] == "canceltiles") { if (!_peer.expired()) forwardToPeer(buffer, length); } else if (tokens[0] == "commandvalues") { return getCommandValues(buffer, length, tokens); } else if (tokens[0] == "partpagerectangles") { return getPartPageRectangles(buffer, length); } else if (tokens[0] == "invalidatetiles") { return invalidateTiles(buffer, length, tokens); } else if (tokens[0] == "renderfont") { sendFontRendering(buffer, length, tokens); } else if (tokens[0] == "status") { return getStatus(buffer, length); } else if (tokens[0] == "tile") { sendTile(buffer, length, tokens); } else if (tokens[0] == "tilecombine") { sendCombinedTiles(buffer, length, tokens); } else { // All other commands are such that they always require a // LibreOfficeKitDocument session, i.e. need to be handled in // a child process. if (_peer.expired()) dispatchChild(); if (tokens[0] != "requestloksession") { forwardToPeer(buffer, length); } if ((tokens.count() > 1 && tokens[0] == "uno" && tokens[1] == ".uno:Save")) { _tileCache->documentSaved(); } else if (tokens[0] == "disconnect") { // This was the last we would hear from the client on this socket. return handleDisconnect(tokens); } } return true; }
void Controller::handle(const std::vector<std::string>& parameters, Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) { _parameters = parameters; _request = &request; _response = &response; if ( _parameters.size() > 0 ) { _action = _parameters.front(); _parameters.erase(_parameters.begin()); } else { setResponseStatus(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST, "Invalid URI parameters"); return; } for(std::vector<std::string>::iterator it = _parameters.begin(); it != _parameters.end(); ++it) { int pos = it->find_first_of(':'); if ( pos != std::string::npos ) { std::string name = it->substr(0, pos); std::string value = it->substr(pos+1); _namedParameters[name] = value; } } std::string contentType = request.getContentType(); if ( contentType == "application/json" ) { Poco::JSON::Parser parser; try { Poco::Dynamic::Var json = parser.parse(request.stream()); if ( ! json.isEmpty() && json.type() == typeid(Poco::JSON::Object::Ptr) ) { _data->set("filter", json.extract<Poco::JSON::Object::Ptr>()); } } catch(Poco::JSON::JSONException& jsone) { // Make sure everything is read, otherwise this can result // in Bad Request error in the next call. Poco::NullOutputStream nos; Poco::StreamCopier::copyStream(request.stream(), nos); setResponseStatus(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST, "JSON error occurred: " + jsone.displayText()); return; } } else { _form.load(request, request.stream(), *this); } // Make sure everything is read, otherwise this can result // in Bad Request error in the next call. Poco::NullOutputStream nos; Poco::StreamCopier::copyStream(request.stream(), nos); beforeAction(); if ( response.getStatus() != Poco::Net::HTTPResponse::HTTP_OK || _data->has("error") ) { //TODO: return error template file or json error } const ActionMap& actions = getActions(); ActionMap::const_iterator it = actions.find(_action); if ( it == actions.end() ) { setResponseStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND, "Invalid action '" + _action + "' specified."); return; } ActionFn action = it->second; (this->*action)(); afterAction(); }
int CUserMgr::HandleHeader(CMission* pMission) { ST_CMD_HEADER header = *(ST_CMD_HEADER*)pMission->m_pMissionData; CNetUser* pUser = pMission->m_pUser; BOOL bFind = TRUE; //该命令是否被处理 switch (header.usCmd) { case USER_LOGIN: { ST_LOGIN_INFO LoginInfo = *(pStLoginInfo)(pMission->m_pMissionData + HEAD_SIZE); std::cout << "login info: " << LoginInfo.szUserNo << ", pwd: " << LoginInfo.szPWD << std::endl; // _mapUserLock_.lock(); // MAP_USER::iterator itFind = _mapUser_.find(LoginInfo.szUserNo); // if (itFind != _mapUser_.end()) // { // //重复登录提醒, // std::string strSendData = "账号已登录"; // // pUser->SendResponesInfo(USER_RESPONSE_LOGIN, RESULT_LOGIN_FAIL, (char*)strSendData.c_str(), strSendData.length()); // _mapUserLock_.unlock(); // return 1; // } // _mapUserLock_.unlock(); #ifdef TEST_MODE _mapUserLock_.lock(); MAP_USER::iterator itFind2 = _mapUser_.find(LoginInfo.szUserNo); if (itFind2 == _mapUser_.end()) { _mapUser_.insert(MAP_USER::value_type(LoginInfo.szUserNo, pUser)); } else { itFind2->second = pUser; } _mapUserLock_.unlock(); ST_LOGIN_RESULT stResult; ZeroMemory(&stResult, sizeof(stResult)); stResult.nTeacherId = 100; stResult.nUserId = 200; std::string strEzs = "1234567890abcdefghijklmnopqrstuvwxyz"; strncpy(stResult.szEzs, strEzs.c_str(), strEzs.length()); strncpy(stResult.szUserInfo, LoginInfo.szUserNo, 100); char szLoginResult[1024] = { 0 }; memcpy(szLoginResult, (char*)&stResult, sizeof(stResult)); pUser->UpdateLogonInfo(LoginInfo.szUserNo, LoginInfo.szPWD); pUser->SendResponesInfo(USER_RESPONSE_LOGIN, RESULT_SUCCESS, szLoginResult, sizeof(stResult)); return 1; #endif // #ifdef TO_WHTY #if 1 pSCAN_REQ_TASK pTask = NULL; if(SysSet.m_nServerMode == 1) { std::string strAppKey = "SP0000000TEST"; std::string strAppValue = "63d4311d46714a39-a54cf2b0537a79b6TEST"; std::string strMsgFormat = "json"; std::string strMethod = "login111"; std::string strPwd = LoginInfo.szPWD; std::string strUser = LoginInfo.szUserNo; std::string strSha1Src = Poco::format("%sappKey%smessageFormat%smethod%spassword%susername%sv1.0%s", strAppValue, strAppKey, strMsgFormat, strMethod, strPwd, strUser, strAppValue); Poco::SHA1Engine engine; engine.update(strSha1Src); std::string strSHA1 = Poco::DigestEngine::digestToHex(engine.digest()); std::string strSHA1_Up = Poco::toUpper(strSHA1); std::string strUriValue = Poco::format("/router?appKey=%s&messageFormat=%s&method=%s&password=%s&sign=%s&username=%s&v=1.0", strAppKey, strMsgFormat, strMethod, strPwd, strSHA1_Up, strUser); pTask = new SCAN_REQ_TASK; pTask->strUri = SysSet.m_strBackUri + strUriValue; pTask->pUser = pUser; pTask->strMsg = "login2Ty"; pTask->strUser = LoginInfo.szUserNo; pTask->strPwd = LoginInfo.szPWD; std::string strLog = Poco::format("天喻登录: src_SHA1 = %s\nSHA1 = %s\nuri = %s", strSha1Src, strSHA1_Up, pTask->strUri); g_Log.LogOut(strLog); } else { pTask = new SCAN_REQ_TASK; pTask->pUser = pUser; pTask->strUser = LoginInfo.szUserNo; pTask->strPwd = LoginInfo.szPWD; switch (SysSet.m_nUseThirdPlatform) { case 3: //成都佳发,用的天喻系统,登录方法改变 case 1: //武汉天喻 { std::string strAppKey = "SP0000000TEST"; std::string strAppValue = "63d4311d46714a39-a54cf2b0537a79b6TEST"; std::string strMsgFormat = "json"; std::string strMethod = "login111"; if (SysSet.m_nUseThirdPlatform == 3) strMethod = "loginjf"; std::string strPwd = LoginInfo.szPWD; std::string strUser = LoginInfo.szUserNo; std::string strSha1Src = Poco::format("%sappKey%smessageFormat%smethod%spassword%susername%sv1.0%s", strAppValue, strAppKey, strMsgFormat, strMethod, strPwd, strUser, strAppValue); Poco::SHA1Engine engine; engine.update(strSha1Src); std::string strSHA1 = Poco::DigestEngine::digestToHex(engine.digest()); std::string strSHA1_Up = Poco::toUpper(strSHA1); std::string strUriValue = Poco::format("/router?appKey=%s&messageFormat=%s&method=%s&password=%s&sign=%s&username=%s&v=1.0", strAppKey, strMsgFormat, strMethod, strPwd, strSHA1_Up, strUser); pTask->strUri = SysSet.m_str3PlatformUrl + strUriValue; pTask->strMsg = "login2Ty"; } break; case 2: //山西寰烁 { pTask->strUri = SysSet.m_str3PlatformUrl + "?username="******"&password="******"login_SanXi_huanshuo"; } break; default: //默认易考乐学后端平台 { pTask->strUri = SysSet.m_strBackUri + "/login"; pTask->strMsg = "login"; char szTmp[200] = { 0 }; sprintf(szTmp, "username=%s&password=%s", LoginInfo.szUserNo, LoginInfo.szPWD); pTask->strRequest = szTmp; } } std::string strLog = Poco::format("登录命令: msg = %s(%s:%s)\nurl = %s", pTask->strMsg, pTask->strUser, pTask->strPwd, pTask->strUri); g_Log.LogOut(strLog); } #else pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK; pTask->strUri = SysSet.m_strBackUri + "/login"; pTask->pUser = pUser; pTask->strMsg = "login"; pTask->strUser = LoginInfo.szUserNo; pTask->strPwd = LoginInfo.szPWD; char szTmp[200] = { 0 }; sprintf(szTmp, "username=%s&password=%s", LoginInfo.szUserNo, LoginInfo.szPWD); pTask->strRequest = szTmp; #endif g_fmScanReq.lock(); g_lScanReq.push_back(pTask); g_fmScanReq.unlock(); } break; case USER_LOGIN_4TY: { ST_LOGIN_INFO4TY LoginInfo = *(pStLoginInfo4TY)(pMission->m_pMissionData + HEAD_SIZE); std::cout << "login info: " << LoginInfo.szUserNo << ", pwd: " << LoginInfo.szPWD << ", platformcode: " << LoginInfo.szPlatformCode << ", encryption: " << LoginInfo.szEncryption << ", platformUrl: " << LoginInfo.szPlatformUrl << std::endl; std::string strAppKey = "SP0000000TEST"; std::string strAppValue = "63d4311d46714a39-a54cf2b0537a79b6TEST"; std::string strMsgFormat = "json"; std::string strMethod = "login111"; std::string strPwd = LoginInfo.szPWD; std::string strUser = LoginInfo.szUserNo; std::string strEncryption = LoginInfo.szEncryption; std::string strPlatformCode = LoginInfo.szPlatformCode; std::string strPlatformUrl = LoginInfo.szPlatformUrl; std::string strSha1Src = Poco::format("%sappKey%sencryption%smessageFormat%smethod%spassword%splatformUrl%splatformcode%susername%sv1.0%s", \ strAppValue, strAppKey, strEncryption, strMsgFormat, strMethod, strPwd, strPlatformUrl, strPlatformCode, strUser, strAppValue); Poco::SHA1Engine engine; engine.update(strSha1Src); std::string strSHA1 = Poco::DigestEngine::digestToHex(engine.digest()); std::string strSHA1_Up = Poco::toUpper(strSHA1); std::string strUriValue = Poco::format("/router?appKey=%s&encryption=%s&messageFormat=%s&method=%s&password=%s&platformUrl=%s&platformcode=%s&sign=%s&username=%s&v=1.0",\ strAppKey, strEncryption, strMsgFormat, strMethod, strPwd, strPlatformUrl, strPlatformCode, strSHA1_Up, strUser); pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK; if (SysSet.m_nServerMode == 0) //非天喻服务器模式,则进入此处为登录第3方天喻平台 pTask->strUri = SysSet.m_str3PlatformUrl + strUriValue; else pTask->strUri = SysSet.m_strBackUri + strUriValue; pTask->pUser = pUser; pTask->strMsg = "login2Ty"; pTask->strUser = LoginInfo.szUserNo; pTask->strPwd = LoginInfo.szPWD; std::string strLog = Poco::format("天喻登录平台: src_SHA1 = %s\nSHA1 = %s\nuri = %s", strSha1Src, strSHA1_Up, pTask->strUri); g_Log.LogOut(strLog); g_fmScanReq.lock(); g_lScanReq.push_back(pTask); g_fmScanReq.unlock(); } break; case USER_LOGOUT: { char szData[1024] = { 0 }; strncpy(szData, pMission->m_pMissionData + HEAD_SIZE, header.uPackSize); std::string strUser = szData; _mapUserLock_.lock(); MAP_USER::iterator itFind = _mapUser_.find(strUser); if (itFind != _mapUser_.end()) { _mapUser_.erase(itFind); std::string strLog = "账号" + strUser + "退出登录"; pUser->SendResponesInfo(USER_RESPONSE_LOGOUT, RESULT_SUCCESS, (char*)strUser.c_str(), strUser.length()); g_Log.LogOut(strLog); } _mapUserLock_.unlock(); } break; case USER_GETEXAMINFO: { ST_EXAM_INFO stExamInfo = *(pStExamInfo)(pMission->m_pMissionData + HEAD_SIZE); std::string strEzs = stExamInfo.szEzs; int nUserID = stExamInfo.nUserId; std::cout << "获取考试列表: " << pUser->m_Name <<std::endl; #ifdef TEST_MODE #if 1 std::string strExamListPath = SysSet.m_strCurrentDir + "\\ServerTestData\\ServerTestData-examlist.txt"; std::string strJsnData; std::ifstream in(strExamListPath); if (!in) return false; std::string strJsnLine; while (!in.eof()) { getline(in, strJsnLine); strJsnData.append(strJsnLine); } in.close(); pUser->SendResponesInfo(USER_RESPONSE_EXAMINFO, RESULT_EXAMINFO_SUCCESS, (char*)strJsnData.c_str(), strJsnData.length()); return 1; #else Poco::JSON::Object jsnSubject1; jsnSubject1.set("id", 200); jsnSubject1.set("name", CMyCodeConvert::Gb2312ToUtf8("语文")); jsnSubject1.set("code", 1001); jsnSubject1.set("scanTemplateName", "100_200.mod"); Poco::JSON::Object jsnSubject2; jsnSubject2.set("id", 201); jsnSubject2.set("name", CMyCodeConvert::Gb2312ToUtf8("数学")); jsnSubject2.set("code", 1002); jsnSubject2.set("scanTemplateName", "100_201.mod"); Poco::JSON::Array jsnSubjectArry; jsnSubjectArry.add(jsnSubject1); jsnSubjectArry.add(jsnSubject2); Poco::JSON::Object jsnExamObj; jsnExamObj.set("id", 100); jsnExamObj.set("name", CMyCodeConvert::Gb2312ToUtf8("高三期末考试")); Poco::JSON::Object jsnExamTypeObj; jsnExamTypeObj.set("id", 33); jsnExamTypeObj.set("name", CMyCodeConvert::Gb2312ToUtf8("期末考试")); jsnExamObj.set("examType", jsnExamTypeObj); Poco::JSON::Object jsnGrade; jsnGrade.set("id", 5); jsnGrade.set("name", CMyCodeConvert::Gb2312ToUtf8("高三")); jsnGrade.set("aliasName", ""); jsnExamObj.set("grade", jsnGrade); jsnExamObj.set("examSubjects", jsnSubjectArry); jsnExamObj.set("state", 1); Poco::JSON::Array jsnExamArry; jsnExamArry.add(jsnExamObj); Poco::JSON::Object jsnResult; jsnResult.set("exams", jsnExamArry); Poco::JSON::Object jsnStatus; jsnStatus.set("success", true); jsnResult.set("status", jsnStatus); std::stringstream jsnString; jsnResult.stringify(jsnString, 0); pUser->SendResponesInfo(USER_RESPONSE_EXAMINFO, RESULT_EXAMINFO_SUCCESS, (char*)jsnString.str().c_str(), jsnString.str().length()); return 1; #endif #endif // #ifdef TO_WHTY #if 1 pSCAN_REQ_TASK pTask = NULL; if (SysSet.m_nServerMode == 1) { std::string strAppKey = "SP0000000TEST"; std::string strAppValue = "63d4311d46714a39-a54cf2b0537a79b6TEST"; std::string strMsgFormat = "json"; std::string strMethod = "examinfo"; std::string strPersonId; std::string strSchoolID; std::string strTmp = stExamInfo.szEzs; int nPos = strTmp.find("###"); if (nPos != std::string::npos) { std::string strEzs = strTmp.substr(0, nPos); strSchoolID = strTmp.substr(nPos + 3); strPersonId = strEzs; } else { strPersonId = stExamInfo.szEzs; } // std::string strPersonId = stExamInfo.szEzs; std::string strSha1Src = Poco::format("%sappKey%smessageFormat%smethod%sperson_id%sv1.0%s", strAppValue, strAppKey, strMsgFormat, strMethod, strPersonId, strAppValue); Poco::SHA1Engine engine; engine.update(strSha1Src); std::string strSHA1 = Poco::DigestEngine::digestToHex(engine.digest()); std::string strSHA1_Up = Poco::toUpper(strSHA1); // std::string strUriValue = Poco::format("/router?appKey=%s&messageFormat=%s&method=%s&person_id=%s&sign=%s&v=1.0", strAppKey, strMsgFormat, strMethod, strPersonId, strSHA1_Up); std::string strUriValue; if (nPos != std::string::npos) strUriValue = Poco::format("/router?appKey=%s&messageFormat=%s&method=%s&person_id=%s&school_id=%s&sign=%s&v=1.0", strAppKey, strMsgFormat, strMethod, strPersonId, strSchoolID, strSHA1_Up); //2017.6.20添加school_id else strUriValue = Poco::format("/router?appKey=%s&messageFormat=%s&method=%s&person_id=%s&sign=%s&v=1.0", strAppKey, strMsgFormat, strMethod, strPersonId, strSHA1_Up); pTask = new SCAN_REQ_TASK; pTask->strUri = SysSet.m_strBackUri + strUriValue; pTask->pUser = pUser; pTask->strEzs = SysSet.m_strSessionName + strEzs; //"ezs=" + strEzs; pTask->strMsg = "ezs"; std::string strLog = Poco::format("天喻平台,获取考试列表: src_SHA1 = %s\nSHA1 = %s\nuri = %s", strSha1Src, strSHA1_Up, pTask->strUri); g_Log.LogOut(strLog); } else { pTask = new SCAN_REQ_TASK; std::string strUserID = Poco::format("%d", nUserID); if (SysSet.m_nQuYuVersion) pTask->strUri = SysSet.m_strBackUri + "/examinfo"; else pTask->strUri = SysSet.m_strBackUri + "/examinfo/" + strUserID; pTask->pUser = pUser; pTask->strEzs = SysSet.m_strSessionName + strEzs; //"ezs=" + strEzs; pTask->strMsg = "ezs"; } #else pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK; pTask->strUri = SysSet.m_strBackUri + "/examinfo"; pTask->pUser = pUser; pTask->strEzs = SysSet.m_strSessionName + strEzs; //"ezs=" + strEzs; pTask->strMsg = "ezs"; #endif g_fmScanReq.lock(); g_lScanReq.push_back(pTask); g_fmScanReq.unlock(); } break; case USER_SETMODELINFO: { ST_MODELINFO stModelInfo = *(pST_MODELINFO)(pMission->m_pMissionData + HEAD_SIZE); bool bNeedSend = false; char szIndex[50] = { 0 }; sprintf(szIndex, "%d_%d", stModelInfo.nExamID, stModelInfo.nSubjectID); std::cout << "设置考试模板命令: " << szIndex << std::endl; std::stringstream ssLog; ssLog << "设置考试模板命令: " << szIndex << "\n"; MAP_MODEL::iterator itFind = _mapModel_.find(szIndex); if (itFind == _mapModel_.end()) { bNeedSend = true; ssLog << "模板信息映射表中未找到" << szIndex << "的信息,可以发送此模板的信息[Ezs = " << stModelInfo.szEzs << "]\n"; //g_Log.LogOut(strLog); pST_MODELINFO pStModelInfo = new ST_MODELINFO; memcpy(pStModelInfo, &stModelInfo, sizeof(stModelInfo)); pMODELINFO pModelInfo = new MODELINFO; pModelInfo->nExamID = stModelInfo.nExamID; pModelInfo->nSubjectID = stModelInfo.nSubjectID; pModelInfo->strName = stModelInfo.szModelName; pModelInfo->strEzs = stModelInfo.szEzs; pModelInfo->strElectOmr = stModelInfo.szElectOmr; pModelInfo->strMd5 = stModelInfo.szMD5; pModelInfo->pUploadModelInfo = pStModelInfo; pModelInfo->pUser = pUser; _mapModelLock_.lock(); _mapModel_.insert(MAP_MODEL::value_type(szIndex, pModelInfo)); _mapModelLock_.unlock(); ssLog << "添加新的模板信息,等待接收模板文件: " << stModelInfo.szModelName << "\n"; } else { pMODELINFO pModelInfo = itFind->second; try { Poco::File modelFile(CMyCodeConvert::Gb2312ToUtf8(pModelInfo->strPath)); if (!modelFile.exists()) pModelInfo->strMd5 = ""; } catch (Poco::Exception&exc) { } if (pModelInfo->strMd5 != stModelInfo.szMD5) //文件有修改,需要重新发送 { bNeedSend = true; pST_MODELINFO pStModelInfo = new ST_MODELINFO; memcpy(pStModelInfo, &stModelInfo, sizeof(stModelInfo)); SAFE_RELEASE(pModelInfo->pUploadModelInfo); pModelInfo->pUploadModelInfo = pStModelInfo; pModelInfo->pUser = pUser; pModelInfo->nExamID = stModelInfo.nExamID; pModelInfo->nSubjectID = stModelInfo.nSubjectID; pModelInfo->strName = stModelInfo.szModelName; pModelInfo->strEzs = stModelInfo.szEzs; pModelInfo->strElectOmr = stModelInfo.szElectOmr; pModelInfo->strMd5 = stModelInfo.szMD5; ssLog << "模板信息映射表中" << szIndex << "的文件MD5与需要上传的文件MD5信息不一致,可以发送此模板的信息[Ezs = " << pModelInfo->strEzs <<"]"; } else std::cout << "文件未修改,不需要重传" << std::endl; } if (bNeedSend) { pUser->SendResponesInfo(USER_RESPONSE_MODELINFO, RESULT_SETMODELINFO_SEND, (char*)&stModelInfo, sizeof(stModelInfo)); #ifdef TEST_MODE return 1; #endif #if 0 //需要先解压后提交图片MD5再去后端设置信息 Poco::JSON::Object jsnModel; jsnModel.set("examId", stModelInfo.nExamID); jsnModel.set("subjectId", stModelInfo.nSubjectID); jsnModel.set("tmplateName", stModelInfo.szModelName); jsnModel.set("modelElectOmr", stModelInfo.szElectOmr); std::stringstream jsnString; jsnModel.stringify(jsnString, 0); std::string strEzs = stModelInfo.szEzs; pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK; pTask->strUri = SysSet.m_strBackUri + "/scanTemplate"; pTask->pUser = pUser; pTask->strEzs = "ezs=" + strEzs; pTask->strMsg = "setScanModel"; pTask->strRequest = jsnString.str(); g_fmScanReq.lock(); g_lScanReq.push_back(pTask); g_fmScanReq.unlock(); #endif } else pUser->SendResult(USER_RESPONSE_MODELINFO, RESULT_SETMODELINFO_NO); g_Log.LogOut(ssLog.str()); } break; case USER_NEED_DOWN_MODEL: { ST_DOWN_MODEL stModelInfo = *(pST_DOWN_MODEL)(pMission->m_pMissionData + HEAD_SIZE); bool bNeedDown = true; char szIndex[50] = { 0 }; sprintf(szIndex, "%d_%d", stModelInfo.nExamID, stModelInfo.nSubjectID); std::cout << "请求下载模板命令: " << szIndex << std::endl; std::stringstream ssLog; ssLog << "请求下载模板命令: " << szIndex << "\n"; pMODELINFO pModelInfo = NULL; MAP_MODEL::iterator itFind = _mapModel_.find(szIndex); if (itFind == _mapModel_.end()) { pUser->SendResult(USER_RESPONSE_NEEDDOWN, RESULT_DOWNMODEL_FAIL); ssLog << "请求下载的模板文件不存在\n"; break; } else { pModelInfo = itFind->second; if (pModelInfo->strMd5 == stModelInfo.szMD5) //文件未修改,不需要重新下载 bNeedDown = false; } if (bNeedDown) { try { Poco::File fileModel(CMyCodeConvert::Gb2312ToUtf8(pModelInfo->strPath)); stModelInfo.nModelSize = static_cast<int>(fileModel.getSize()); pUser->SendResponesInfo(USER_RESPONSE_NEEDDOWN, RESULT_DOWNMODEL_OK, (char*)&stModelInfo, sizeof(stModelInfo)); ssLog << "可以正常下载"; } catch (Poco::Exception& exc) { std::string strLog = "请求下载模板命令(" + std::string(szIndex) + ")-->检测模板文件路径异常: " + exc.displayText(); std::cout << strLog << std::endl; ssLog << strLog; pUser->SendResult(USER_RESPONSE_NEEDDOWN, RESULT_DOWNMODEL_FAIL); } } else { pUser->SendResult(USER_RESPONSE_NEEDDOWN, RESULT_DOWNMODEL_NONEED); ssLog << "不需要重新下载模板\n"; } g_Log.LogOut(ssLog.str()); } break; case USER_DOWN_MODEL: { ST_DOWN_MODEL stModelInfo = *(pST_DOWN_MODEL)(pMission->m_pMissionData + HEAD_SIZE); std::string strCmdResponse = Poco::format("Get Cmd %d OK", (int)USER_DOWN_MODEL); //pUser->SendResponesInfo(USER_RESPONSE_DOWNMODEL, RESULT_SUCCESS, (char*)strCmdResponse.c_str(), strCmdResponse.length()); bool bNeedDown = true; char szIndex[50] = { 0 }; sprintf(szIndex, "%d_%d", stModelInfo.nExamID, stModelInfo.nSubjectID); std::cout << "开始下载考试模板命令: " << szIndex << std::endl; std::stringstream ssLog; ssLog << "开始下载考试模板命令: " << szIndex << "\n"; MAP_MODEL::iterator itFind = _mapModel_.find(szIndex); if (itFind == _mapModel_.end()) { } else { pMODELINFO pModelInfo = itFind->second; std::string strFileData; std::ifstream fin(pModelInfo->strPath, std::ifstream::binary); if (!fin) { pUser->SendResult(USER_RESPONSE_DOWNMODEL, RESULT_ERROR_FILEIO); return false; } std::stringstream buffer; buffer << fin.rdbuf(); strFileData = buffer.str(); fin.close(); int nLen = strFileData.length(); std::cout << "模板长度: " << nLen << std::endl; ssLog << "模板长度: " << nLen << "\n"; // ofstream out("1.mod", std::ios::binary); // std::stringstream buffer2; // buffer2.write(strFileData.c_str(), strFileData.length()); // int n = buffer2.str().length(); // out << buffer2.str(); // out.close(); pUser->SendResponesInfo(USER_RESPONSE_DOWNMODEL, RESULT_DOWNMODEL_RECV, (char*)strFileData.c_str(), strFileData.length()); std::cout << "下载考试模板文件完成: " << szIndex << std::endl; ssLog << "下载考试模板文件完成: " << szIndex; g_Log.LogOut(ssLog.str()); } } break; case USER_NEED_CREATE_MODEL: { ST_CREATE_MODEL stModelInfo = *(pST_CREATE_MODEL)(pMission->m_pMissionData + HEAD_SIZE); char szIndex[50] = { 0 }; sprintf(szIndex, "%d_%d", stModelInfo.nExamID, stModelInfo.nSubjectID); std::cout << "请求自动创建模板命令: " << szIndex << std::endl; _mapModelLock_.lock(); pMODELINFO pModelInfo = NULL; MAP_MODEL::iterator itFind = _mapModel_.find(szIndex); if (itFind == _mapModel_.end()) //服务器上没有模板,请求后端提供数据生成模板 { pModelInfo = new MODELINFO; pModelInfo->nExamID = stModelInfo.nExamID; pModelInfo->nSubjectID = stModelInfo.nSubjectID; _mapModel_.insert(MAP_MODEL::value_type(szIndex, pModelInfo)); } _mapModelLock_.unlock(); pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK; pTask->strUri = Poco::format("%s/sheet/data/%d/%d", SysSet.m_strBackUri, stModelInfo.nExamID, stModelInfo.nSubjectID); pTask->pUser = pUser; pTask->strMsg = "createModel"; pTask->nExamID = stModelInfo.nExamID; pTask->nSubjectID = stModelInfo.nSubjectID; pTask->strEzs = stModelInfo.szEzs; pTask->strExamName = stModelInfo.szExamName; pTask->strSubjectName = stModelInfo.szSubjectName; g_fmScanReq.lock(); g_lScanReq.push_back(pTask); g_fmScanReq.unlock(); } break; case GET_VERSERVER_ADDR: { std::stringstream ss; ss << SysSet.m_strVerServerIP << ":" << SysSet.m_nVerServerPort; std::string strVerAddr = ss.str(); pUser->SendResponesInfo(RESPONSE_GET_VERSERVER_ADDR, RESULT_SUCCESS, (char*)strVerAddr.c_str(), strVerAddr.length()); std::cout << "回复版本服务器地址信息:" << strVerAddr << std::endl; } break; case USER_GET_BMK: { ST_GET_BMK_INFO stGetBmkInfo = *(pStGetBmkInfo)(pMission->m_pMissionData + HEAD_SIZE); std::cout << "请求报名库命令: " << stGetBmkInfo.nExamID << "_" << stGetBmkInfo.nSubjectID << std::endl; std::string strLog = Poco::format("请求考试的报名库命令: %d_%d", stGetBmkInfo.nExamID, stGetBmkInfo.nSubjectID); g_Log.LogOut(strLog); std::string strEzs = stGetBmkInfo.szEzs; pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK; pTask->strUri = SysSet.m_strBackUri + "/getStudents"; pTask->nExamID = stGetBmkInfo.nExamID; pTask->nSubjectID = stGetBmkInfo.nSubjectID; char szExamInfo[30] = { 0 }; sprintf(szExamInfo, "/%d/%d", stGetBmkInfo.nExamID, stGetBmkInfo.nSubjectID); pTask->strUri.append(szExamInfo); pTask->pUser = pUser; pTask->strEzs = SysSet.m_strSessionName + strEzs; //"ezs=" + strEzs; pTask->strMsg = "getBmk"; Poco::JSON::Object obj; obj.set("examId", stGetBmkInfo.nExamID); obj.set("subjectId", stGetBmkInfo.nSubjectID); stringstream ss; obj.stringify(ss, 0); pTask->strRequest = ss.str(); g_fmScanReq.lock(); g_lScanReq.push_back(pTask); g_fmScanReq.unlock(); } break; case USER_GET_EXAM_BMK: { ST_GET_BMK_INFO stGetBmkInfo = *(pStGetBmkInfo)(pMission->m_pMissionData + HEAD_SIZE); std::string strCmdResponse = Poco::format("Get Cmd %d OK", (int)USER_GET_EXAM_BMK); //pUser->SendResponesInfo(USER_RESPONSE_GET_EXAM_BMK, RESULT_SUCCESS, (char*)strCmdResponse.c_str(), strCmdResponse.length()); std::cout << "请求考试的报名库命令: " << stGetBmkInfo.nExamID << std::endl; std::string strLog = Poco::format("请求考试的报名库命令: %d", stGetBmkInfo.nExamID); g_Log.LogOut(strLog); // #ifdef _DEBUG //测试数据,后期要删 #ifdef TEST_MODE std::string strSendData; std::string strBmkFileName; if (stGetBmkInfo.nExamID == 1354 || stGetBmkInfo.nExamID == 1257 || stGetBmkInfo.nExamID == 1241) { strBmkFileName = Poco::format("ServerTestData-bmk-%d.txt", stGetBmkInfo.nExamID); std::string strExamListPath = SysSet.m_strCurrentDir + "\\ServerTestData\\" + strBmkFileName; std::string strJsnData; std::ifstream in(strExamListPath); if (!in) return false; std::string strJsnLine; while (!in.eof()) { getline(in, strJsnLine); strJsnData.append(strJsnLine); } in.close(); Poco::JSON::Parser parser; Poco::Dynamic::Var result; try { result = parser.parse(strJsnData); Poco::JSON::Object::Ptr object = result.extract<Poco::JSON::Object::Ptr>(); //++添加考试ID和科目ID到结果信息中 Poco::JSON::Object objExam; objExam.set("examId", stGetBmkInfo.nExamID); objExam.set("subjectId", stGetBmkInfo.nSubjectID); object->set("examInfo", objExam); std::stringstream jsnSnString; object->stringify(jsnSnString, 0); //-- strSendData = jsnSnString.str(); } catch (Poco::Exception& exc) { std::cout << "获取考试[" << stGetBmkInfo.nExamID << "]报名库数据异常\n"; return false; } } else { Poco::JSON::Object objBmkTestResult; Poco::JSON::Object objStatus; objStatus.set("success", true); Poco::JSON::Array arryStudent; for (int i = 0; i < 100; i++) { Poco::JSON::Object objStudent; std::string strZkzh = Poco::format("%d", 100 + i); objStudent.set("zkzh", strZkzh); std::string strName = Poco::format("测试%d", i); objStudent.set("name", CMyCodeConvert::Gb2312ToUtf8(strName)); objStudent.set("classRoom", CMyCodeConvert::Gb2312ToUtf8("10001")); objStudent.set("school", CMyCodeConvert::Gb2312ToUtf8("一中")); Poco::JSON::Array arryScanStatus; for (int j = 0; j < 4; j++) { Poco::JSON::Object objSubStatus; objSubStatus.set("subjectID", 590 + j); objSubStatus.set("scaned", (j + i) % 2); arryScanStatus.add(objSubStatus); } objStudent.set("scanStatus", arryScanStatus); arryStudent.add(objStudent); } Poco::JSON::Object objExam; objExam.set("examId", 402); objExam.set("subjectId", 590); objBmkTestResult.set("status", objStatus); objBmkTestResult.set("students", arryStudent); objBmkTestResult.set("examInfo", objExam); std::stringstream jsnSnString; objBmkTestResult.stringify(jsnSnString, 0); strSendData = jsnSnString.str(); } pUser->SendResponesInfo(USER_RESPONSE_GET_EXAM_BMK, RESULT_GET_BMK_SUCCESS, (char*)strSendData.c_str(), strSendData.length()); break; #endif std::string strEzs = stGetBmkInfo.szEzs; pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK; pTask->strUri = SysSet.m_strBackUri + "/getStudents"; pTask->nExamID = stGetBmkInfo.nExamID; pTask->nSubjectID = stGetBmkInfo.nSubjectID; pTask->nTeacherID = _mapSession_[strEzs].nTeacherID; char szExamInfo[30] = { 0 }; sprintf(szExamInfo, "/%d/%d", stGetBmkInfo.nExamID, stGetBmkInfo.nSubjectID); pTask->strUri.append(szExamInfo); pTask->pUser = pUser; pTask->strEzs = SysSet.m_strSessionName + strEzs; //"ezs=" + strEzs; pTask->strMsg = "getExamBmk"; Poco::JSON::Object obj; obj.set("examId", stGetBmkInfo.nExamID); obj.set("subjectId", stGetBmkInfo.nSubjectID); obj.set("teacherId", pTask->nTeacherID); stringstream ss; obj.stringify(ss, 0); pTask->strRequest = ss.str(); g_fmScanReq.lock(); g_lScanReq.push_back(pTask); g_fmScanReq.unlock(); } break; case USER_GET_FILE_UPLOAD_ADDR: { std::cout << "请求不同格式文件服务器地址信息命令: "<< std::endl; int nResult = RESULT_GET_FILE_ADDR_SUCCESS; if (SysSet.m_strFileAddrs.empty()) nResult = RESULT_GET_FILE_ADDR_FAIL; std::string strVerAddr = SysSet.m_strFileAddrs; pUser->SendResponesInfo(USER_RESPONSE_GET_FILE_UPLOAD_ADDR, nResult, (char*)strVerAddr.c_str(), strVerAddr.length()); std::string strLog = "请求不同格式文件服务器地址信息命令: \n" + strVerAddr; g_Log.LogOut(strLog); } break; case USER_NEED_UP_MODEL_PIC: { std::cout << "请求上传模板图像命令: " << std::endl; ST_MODELPIC stModelPic = *(pST_MODELPIC)(pMission->m_pMissionData + HEAD_SIZE); int nResult = RESULT_ERROR_UNKNOWN; std::string strModelPicPath = Poco::format("%s\\%d\\%d_%d_%d%s", CMyCodeConvert::Gb2312ToUtf8(SysSet.m_strModelSavePath), stModelPic.nExamID, \ stModelPic.nExamID, stModelPic.nSubjectID, stModelPic.nIndex, CMyCodeConvert::Gb2312ToUtf8(stModelPic.szExtName)); // std::string strModelPicPath = Poco::format("%s\\%d\\%d_%d_%d_#_%s", CMyCodeConvert::Gb2312ToUtf8(SysSet.m_strModelSavePath), stModelPic.nExamID,\ // stModelPic.nExamID, stModelPic.nSubjectID, stModelPic.nIndex, CMyCodeConvert::Gb2312ToUtf8(stModelPic.szPicName)); std::string strLog; try { Poco::File modelPic(strModelPicPath); if (!modelPic.exists()) { nResult = RESULT_UP_MODEL_PIC_SEND; strLog = "请求上传模板图像命令 ==> 可以发送模板图片:" + strModelPicPath; std::cout << "可以发送模板图片:" << strModelPicPath << std::endl; } else { std::string strMd5 = calcFileMd5(strModelPicPath); if (strMd5 == stModelPic.szMD5) { nResult = RESULT_UP_MODEL_PIC_NONEED; strLog = "请求上传模板图像命令 ==> 不需要发送模板图片:" + strModelPicPath; std::cout << "不需要发送模板图片:" << strModelPicPath << std::endl; } else { nResult = RESULT_UP_MODEL_PIC_SEND; strLog = "请求上传模板图像命令 ==> 可以发送模板图片:" + strModelPicPath; std::cout << "可以发送模板图片:" << strModelPicPath << std::endl; } } } catch (Poco::Exception& e) { strLog = "请求上传模板图像命令 ==> 检测模板图片路径异常:" + e.displayText(); std::cout << "检测模板图片路径异常: "<< e.displayText() << std::endl; nResult = RESULT_UP_MODEL_PIC_SEND; } pUser->SendResponesInfo(USER_RESPONSE_NEED_UP_MODEL_PIC, nResult, (char*)&stModelPic, sizeof(stModelPic)); g_Log.LogOut(strLog); } break; case USER_GET_MODEL_PIC: { char szData[1024] = { 0 }; strncpy(szData, pMission->m_pMissionData + HEAD_SIZE, header.uPackSize); std::string strModelPicInfo = szData; std::cout << "请求下载模板图像命令: " << strModelPicInfo << std::endl; std::stringstream ssLog; ssLog<< "请求下载模板图像命令: " << strModelPicInfo << std::endl; int nPos = strModelPicInfo.find("_"); std::string strExamID = strModelPicInfo.substr(0, nPos); std::string strSubjectID = strModelPicInfo.substr(nPos + 1); std::string strModelPicDir = SysSet.m_strModelSavePath + "\\" + strExamID + "\\"; std::vector<std::string> vecModelPicName; std::vector<std::string> vecModelPicPath; std::string strPaperPath = CMyCodeConvert::Gb2312ToUtf8(strModelPicDir); try { Poco::File modlePicDir(strPaperPath); if (!modlePicDir.exists()) { pUser->SendResult(USER_RESPONSE_GET_MODEL_PIC, RESULT_GET_MODEL_PIC_NOPIC); ssLog << "模板图像不存在"; g_Log.LogOut(ssLog.str()); return false; } } catch (Poco::Exception& e) { } Poco::DirectoryIterator it(strPaperPath); Poco::DirectoryIterator end; while (it != end) { Poco::Path p(it->path()); if (it->isFile()) { std::string strName = p.getFileName(); if (strName.find(strModelPicInfo) != std::string::npos) { std::string strPicPath = p.toString(); vecModelPicName.push_back(strName); vecModelPicPath.push_back(strPicPath); } } it++; } if (vecModelPicPath.size() == 0) { pUser->SendResult(USER_RESPONSE_GET_MODEL_PIC, RESULT_GET_MODEL_PIC_NOPIC); ssLog << "模板图像不存在"; g_Log.LogOut(ssLog.str()); return false; } std::string strSendData; for (int i = 0; i < vecModelPicPath.size(); i++) { std::string strFileData; std::ifstream fin(CMyCodeConvert::Utf8ToGb2312(vecModelPicPath[i]), std::ifstream::binary); if (!fin) { pUser->SendResult(USER_RESPONSE_GET_MODEL_PIC, RESULT_ERROR_FILEIO); ssLog << "读取模板文件失败"; g_Log.LogOut(ssLog.str()); return false; } std::stringstream buffer; buffer << fin.rdbuf(); strFileData = buffer.str(); fin.close(); strSendData.append("#_#_#_#_"); strSendData.append(vecModelPicName[i]); strSendData.append("_*_"); char szLen[20] = { 0 }; sprintf_s(szLen, "%d", strFileData.length()); strSendData.append(szLen); strSendData.append("_#####_"); strSendData.append(strFileData); } pUser->SendResponesInfo(USER_RESPONSE_GET_MODEL_PIC, RESULT_GET_MODEL_PIC_SUCCESS, (char*)strSendData.c_str(), strSendData.length()); ssLog << "模板文件发送完成"; g_Log.LogOut(ssLog.str()); } break; case USER_CHK_NEW_GUARDEXE: { char szData[1024] = { 0 }; strncpy(szData, pMission->m_pMissionData + HEAD_SIZE, header.uPackSize); std::string strClientGuardExeMd5 = szData; if (_strNewGuardExeMd5_.empty()) { std::cout << "服务器上新守护进程不存在" << std::endl; pUser->SendResult(USER_RESPONSE_CHK_NEW_GUARDEXE, RESULT_GET_NEW_GUARDEXE_NOFILE); } else if (_strNewGuardExeMd5_ == strClientGuardExeMd5) { std::cout << "客户端上的守护进程和服务器一致,不需要下载" << std::endl; pUser->SendResult(USER_RESPONSE_CHK_NEW_GUARDEXE, RESULT_GET_NEW_GUARDEXE_NONEED); } else { std::string strGuardExePath = SysSet.m_strNewGuardProcessPath + "EasyTntGuardProcess.exe"; std::string strFileData; std::ifstream fin(strGuardExePath, std::ifstream::binary); if (!fin) { pUser->SendResult(USER_RESPONSE_CHK_NEW_GUARDEXE, RESULT_ERROR_FILEIO); g_Log.LogOut("读取新守护进程文件时打开文件失败: " + strGuardExePath); return false; } std::cout << "正在发送新守护进程文件..." << std::endl; std::stringstream buffer; buffer << fin.rdbuf(); strFileData = buffer.str(); fin.close(); pUser->SendResponesInfo(USER_RESPONSE_CHK_NEW_GUARDEXE, RESULT_GET_NEW_GUARDEXE_SUCCESS, (char*)strFileData.c_str(), strFileData.length()); g_Log.LogOut("新守护进程文件发送完成"); std::cout << "新守护进程文件发送完成" << std::endl; } } break; case KEEPALIVE_PKG: { char szData[1024] = { 0 }; strncpy(szData, pMission->m_pMissionData + HEAD_SIZE, header.uPackSize); std::string strEzs = szData; MAP_SESSION::iterator itSession = _mapSession_.begin(); for (; itSession != _mapSession_.end(); itSession++) { if (itSession->first == strEzs) { itSession->second.tmStamp.update(); itSession->second.nChkHeartPkgFailTimes = 0; break; } } } break; default: bFind = FALSE; break; } if (bFind) { return 1; } return 0; }
int main(int argc, char **argv) { Poco::Stopwatch sw; std::string dir = Poco::Environment::get("POCO_BASE") + "/JSON/samples/Benchmark/"; Poco::Path filePath(dir, "input.big.json"); std::ostringstream ostr; if (filePath.isFile()) { Poco::File inputFile(filePath); if (inputFile.exists()) { sw.start(); Poco::FileInputStream fis(filePath.toString()); Poco::StreamCopier::copyStream(fis, ostr); sw.stop(); } else { std::cout << filePath.toString() << " doesn't exist!" << std::endl; return 1; } } std::cout << "JSON Benchmark" << std::endl; std::cout << "==============" << std::endl; std::string jsonStr = ostr.str(); std::cout << "Total of " << jsonStr.size() << " bytes," << std::endl << "loaded in " << sw.elapsed() << " [us]," << std::endl; std::cout << std::endl << "POCO JSON barebone parse" << std::endl; Poco::JSON::Parser sparser(0); sw.restart(); sparser.parse(jsonStr); sw.stop(); std::cout << "---------------------------------" << std::endl; std::cout << "[std::string] parsed in " << sw.elapsed() << " [us]" << std::endl; std::cout << "---------------------------------" << std::endl; Poco::JSON::Parser iparser(0); std::istringstream istr(jsonStr); sw.restart(); iparser.parse(istr); sw.stop(); std::cout << "----------------------------------------" << std::endl; std::cout << "[std::istringstream] parsed in " << sw.elapsed() << " [us]" << std::endl; std::cout << "----------------------------------------" << std::endl; std::cout << std::endl << "POCO JSON Handle/Stringify" << std::endl; try { Poco::JSON::Parser sparser; sw.restart(); sparser.parse(jsonStr); Poco::DynamicAny result = sparser.result(); sw.stop(); std::cout << "-----------------------------------------" << std::endl; std::cout << "[std::string] parsed/handled in " << sw.elapsed() << " [us]" << std::endl; std::cout << "-----------------------------------------" << std::endl; Poco::JSON::Parser isparser; std::istringstream istr(jsonStr); sw.restart(); isparser.parse(istr); result = isparser.result(); sw.stop(); std::cout << "------------------------------------------------" << std::endl; std::cout << "[std::istringstream] parsed/handled in " << sw.elapsed() << " [us]" << std::endl; std::cout << "------------------------------------------------" << std::endl; // Serialize to string Poco::JSON::Object::Ptr obj; if (result.type() == typeid(Poco::JSON::Object::Ptr)) { obj = result.extract <Poco::JSON::Object::Ptr> (); } std::ostringstream out; sw.restart(); obj->stringify(out); sw.stop(); std::cout << "-----------------------------------" << std::endl; std::cout << "stringified in " << sw.elapsed() << " [us]" << std::endl; std::cout << "-----------------------------------" << std::endl; std::cout << std::endl; } catch(Poco::JSON::JSONException jsone) { std::cout << jsone.message() << std::endl; } return 0; }
void GraphEditor::handlePaste(void) { if (not this->isVisible()) return; auto draw = this->getCurrentGraphDraw(); auto mimeData = QApplication::clipboard()->mimeData(); const bool canPaste = mimeData->hasFormat("text/json/pothos_object_array") and not mimeData->data("text/json/pothos_object_array").isEmpty(); if (not canPaste) return; //extract object array const auto data = mimeData->data("text/json/pothos_object_array"); const std::string dataStr(data.constData(), data.size()); std::istringstream iss(dataStr); Poco::JSON::Parser p; p.parse(iss); auto graphObjects = p.getHandler()->asVar().extract<Poco::JSON::Array::Ptr>(); assert(graphObjects); //rewrite ids std::map<std::string, std::string> oldIdToNew; for (size_t objIndex = 0; objIndex < graphObjects->size(); objIndex++) { const auto jGraphObj = graphObjects->getObject(objIndex); auto oldId = jGraphObj->getValue<std::string>("id"); oldIdToNew[oldId] = this->newId(QString::fromStdString(oldId)).toStdString(); } for (size_t objIndex = 0; objIndex < graphObjects->size();) { for (auto &pair : *graphObjects->getObject(objIndex)) { if (QString::fromStdString(pair.first).endsWith("id", Qt::CaseInsensitive)) { //if not in oldIdToNew, remove from list if (oldIdToNew.count(pair.second) == 0) { graphObjects->remove(objIndex); goto nextObj; } pair.second = oldIdToNew[pair.second]; } } objIndex++; nextObj: continue; } //unselect all objects draw->deselectAllObjs(); //create objects GraphObjectList objsToMove; objsToMove.append(handlePasteType(draw, graphObjects, "Block")); objsToMove.append(handlePasteType(draw, graphObjects, "Breaker")); handlePasteType(draw, graphObjects, "Connection"); //dont append, connection position doesnt matter objsToMove.append(handlePasteType(draw, graphObjects, "Widget")); //deal with initial positions of pasted objects QPointF cornerest(1e6, 1e6); for (auto obj : objsToMove) { cornerest.setX(std::min(cornerest.x(), obj->pos().x())); cornerest.setY(std::min(cornerest.y(), obj->pos().y())); } //determine an acceptable position to center the paste auto view = dynamic_cast<QGraphicsView *>(this->currentWidget()); auto pastePos = view->mapToScene(view->mapFromGlobal(QCursor::pos())); if (not view->sceneRect().contains(pastePos)) { pastePos = view->mapToScene(this->size().width()/2, this->size().height()/2); } //move objects into position for (auto obj : objsToMove) obj->setPos(obj->pos()-cornerest+pastePos); handleStateChange(GraphState("edit-paste", tr("Paste %1").arg(draw->getSelectionDescription()))); }