tup.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. /**
  2. * Tencent is pleased to support the open source community by making Tars available.
  3. *
  4. * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
  5. *
  6. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  7. * in compliance with the License. You may obtain a copy of the License at
  8. *
  9. * https://opensource.org/licenses/BSD-3-Clause
  10. *
  11. * Unless required by applicable law or agreed to in writing, software distributed
  12. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  14. * specific language governing permissions and limitations under the License.
  15. */
  16. #ifndef _WUP_H_
  17. #define _WUP_H_
  18. #include <map>
  19. #include <string>
  20. #include <vector>
  21. #include <sstream>
  22. //支持iphone
  23. #ifdef __APPLE__
  24. #include "RequestF.h"
  25. #elif defined ANDROID // android
  26. #include "RequestF.h"
  27. #else
  28. #include "tup/RequestF.h"
  29. #endif
  30. // #ifdef __GNUC__
  31. // # if __GNUC__ >3 || __GNUC_MINOR__ > 3
  32. // # include <ext/pool_allocator.h>
  33. // # endif
  34. // #endif
  35. using namespace std;
  36. using namespace tars;
  37. namespace tup
  38. {
  39. //存放tars返回值的key
  40. const string STATUS_RESULT_CODE = "STATUS_RESULT_CODE";
  41. const string STATUS_RESULT_DESC = "STATUS_RESULT_DESC";
  42. /////////////////////////////////////////////////////////////////////////////////
  43. // 属性封装类
  44. template<typename TWriter = BufferWriter, typename TReader = BufferReader,template<typename> class Alloc = std::allocator >
  45. //template<typename> class Alloc = __gnu_cxx::__pool_alloc >
  46. class UniAttribute
  47. {
  48. typedef vector<char,Alloc<char> > VECTOR_CHAR_TYPE;
  49. typedef map<string, VECTOR_CHAR_TYPE, less<string>,Alloc< pair<const string,VECTOR_CHAR_TYPE > > > VECTOR_CHAR_IN_MAP_TYPE;
  50. typedef map<string, VECTOR_CHAR_IN_MAP_TYPE, less<string>,Alloc< pair<const string,VECTOR_CHAR_IN_MAP_TYPE > > > WUP_DATA_TYPE;
  51. public:
  52. /**
  53. * 构造函数
  54. */
  55. UniAttribute()
  56. {
  57. _iVer = 3;
  58. }
  59. void setVersion(short iVer)
  60. {
  61. _iVer = iVer;
  62. }
  63. /**
  64. * 添加属性值
  65. *
  66. * @param T: 属性类型
  67. * @param name:属性名称
  68. * @param t: 属性值
  69. */
  70. template<typename T> void put(const string& name, const T& t)
  71. {
  72. os.reset();
  73. os.write(t, 0);
  74. VECTOR_CHAR_TYPE & v = _data[name];
  75. os.swap(v);
  76. // v.assign(os.getBuffer(), os.getBuffer() + os.getLength());
  77. }
  78. void putUnknown(const string& name, const string& value)
  79. {
  80. os.reset();
  81. os.writeUnknownV2(value);
  82. VECTOR_CHAR_TYPE & v = _data[name];
  83. os.swap(v);
  84. // v.assign(os.getBuffer(), os.getBuffer() + os.getLength());
  85. }
  86. void getUnknown(const string& name, string& value)
  87. {
  88. typename VECTOR_CHAR_IN_MAP_TYPE::iterator mit;
  89. mit = _data.find(name);
  90. if (mit != _data.end() && mit->second.size()>2)
  91. {
  92. //去掉DataHead::eStructBegin,DataHead::eStructEnd
  93. value = string(&mit->second[0]+1, mit->second.size()-2);
  94. return;
  95. }
  96. throw runtime_error(string("UniAttribute not found key:") + name);
  97. }
  98. /**
  99. * 获取属性值,属性不存在则抛出异常
  100. *
  101. * @throw runtime_error
  102. * @param T: 属性类型
  103. * @param name:属性名称
  104. * @param t: 属性值输出参数
  105. */
  106. template<typename T> void get(const string& name, T& t)
  107. {
  108. typename VECTOR_CHAR_IN_MAP_TYPE::iterator mit;
  109. mit = _data.find(name);
  110. if (mit != _data.end())
  111. {
  112. is.reset();
  113. is.setBuffer(mit->second);
  114. is.read(t, 0, true);
  115. return;
  116. }
  117. throw runtime_error(string("UniAttribute not found key:") + name);
  118. }
  119. /**
  120. * 获取属性值,属性不存在则抛出异常
  121. *
  122. * @throw runtime_error
  123. * @param T: 属性类型
  124. * @param name:属性名称
  125. * @return T: 属性值
  126. */
  127. template<typename T> T get(const string& name)
  128. {
  129. T t;
  130. get<T>(name, t);
  131. return t;
  132. }
  133. /**
  134. * 获取属性值,忽略异常,不存在的属性返回缺省值
  135. *
  136. * @param T: 属性类型
  137. * @param name:属性名称
  138. * @param t: 属性值输出参数
  139. * @param def: 默认值
  140. */
  141. template<typename T> void getByDefault(const string& name, T& t, const T& def)
  142. {
  143. try
  144. {
  145. get<T>(name, t);
  146. }
  147. catch (runtime_error& e)
  148. {
  149. t = def;
  150. }
  151. }
  152. /**
  153. * 获取属性值(忽略异常,def为缺省值)
  154. *
  155. * @param T: 属性类型
  156. * @param name:属性名称
  157. * @param: 默认值
  158. * @return T: 属性值
  159. */
  160. template<typename T> T getByDefault(const string& name, const T& def)
  161. {
  162. T t;
  163. getByDefault<T>(name, t, def);
  164. return t;
  165. }
  166. /**
  167. *清除全部属性值
  168. */
  169. void clear()
  170. {
  171. _data.clear();
  172. }
  173. /** 编码
  174. *
  175. * @param buff: 编码结果输出参数
  176. */
  177. void encode(string& buff)
  178. {
  179. os.reset();
  180. os.write(_data, 0);
  181. os.swap(buff);
  182. // buff.assign(os.getBuffer(), os.getLength());
  183. }
  184. /** 编码
  185. *
  186. * @param buff: 编码结果输出参数
  187. */
  188. void encode(vector<char>& buff)
  189. {
  190. os.reset();
  191. os.write(_data, 0);
  192. os.swap(buff);
  193. // buff.assign(os.getBuffer(), os.getBuffer() + os.getLength());
  194. }
  195. /** 编码
  196. *
  197. * @throw runtime_error
  198. * @param buff:输出存放编码结果的buffer指针
  199. * @param len: 输入buff长度,输出编码结果长度
  200. */
  201. void encode(char* buff, size_t & len)
  202. {
  203. os.reset();
  204. os.write(_data, 0);
  205. if(len < os.getLength()) throw runtime_error("encode error, buffer length too short");
  206. memcpy(buff, os.getBuffer(), os.getLength());
  207. len = os.getLength();
  208. }
  209. /** 解码
  210. *
  211. * @throw runtime_error
  212. * @param buff:待解码字节流的buffer指针
  213. * @param len: 待解码字节流的长度
  214. */
  215. void decode(const char* buff, size_t len)
  216. {
  217. is.reset();
  218. is.setBuffer(buff, len);
  219. _data.clear();
  220. is.read(_data, 0, true);
  221. }
  222. /**
  223. * 解码
  224. *
  225. * @throw runtime_error
  226. * @param buff: 待解码的字节流
  227. */
  228. void decode(const vector<char>& buff)
  229. {
  230. is.reset();
  231. is.setBuffer(buff);
  232. _data.clear();
  233. is.read(_data, 0, true);
  234. }
  235. /**
  236. * 获取已有的属性
  237. *
  238. * @return const map<string,map<string,vector<char>>>& : 属性map
  239. */
  240. const map<string, vector<char> >& getData() const
  241. {
  242. return _data;
  243. }
  244. /**
  245. * 判断属性集合是否为空
  246. *
  247. * @return bool:属性是否为空
  248. */
  249. bool isEmpty()
  250. {
  251. return _data.empty();
  252. }
  253. /**
  254. * 获取属性集合大小
  255. *
  256. * @return size_t: 集合大小
  257. */
  258. size_t size()
  259. {
  260. return _data.size();
  261. }
  262. /**
  263. * 判断属性是否存在
  264. *
  265. * @param key:属性名称
  266. * @return bool:是否存在
  267. */
  268. bool containsKey(const string & key)
  269. {
  270. return _data.find(key) != _data.end();
  271. }
  272. protected:
  273. VECTOR_CHAR_IN_MAP_TYPE _data;
  274. short _iVer;
  275. public:
  276. TarsInputStream<TReader> is;
  277. TarsOutputStream<TWriter> os;
  278. };
  279. /////////////////////////////////////////////////////////////////////////////////
  280. // 请求、回应包封装类
  281. template<typename TWriter = BufferWriter, typename TReader = BufferReader,template<typename> class Alloc = std::allocator >
  282. struct UniPacket : protected RequestPacket, public UniAttribute<TWriter, TReader, Alloc>
  283. {
  284. public:
  285. /**
  286. * 构造函数
  287. */
  288. UniPacket()
  289. {
  290. iVersion = 3; cPacketType = 0;
  291. iMessageType = 0; iRequestId = 0;
  292. sServantName = ""; sFuncName = "";
  293. iTimeout = 0; sBuffer.clear();
  294. context.clear(); status.clear();
  295. UniAttribute<TWriter, TReader,Alloc>::_iVer = iVersion;
  296. UniAttribute<TWriter, TReader,Alloc>::_data.clear();
  297. UniAttribute<TWriter, TReader,Alloc>::_data.clear();
  298. }
  299. /**
  300. * 拷贝构造
  301. * @param tup
  302. */
  303. UniPacket(const UniPacket &tup) { *this = tup;}
  304. void setVersion(short iVer)
  305. {
  306. UniAttribute<TWriter, TReader,Alloc>::_iVer = iVer;
  307. iVersion = iVer;
  308. }
  309. /**
  310. * 由请求包生成回应包基本结构,回填关键的请求信息
  311. *
  312. * @return UniPacket: 回应包
  313. */
  314. UniPacket createResponse()
  315. {
  316. UniPacket respPacket;
  317. respPacket.sServantName = sServantName;
  318. respPacket.sFuncName = sFuncName;
  319. respPacket.iRequestId = iRequestId;
  320. return respPacket;
  321. }
  322. /**
  323. * 编码,结果的包头4个字节为整个包的长度,网络字节序
  324. *
  325. * @throw runtime_error
  326. * @param buff: 编码结果输出参数
  327. */
  328. void encode(string& buff)
  329. {
  330. encodeBuff<string>(buff);
  331. // TarsOutputStream<TWriter> &os = UniAttribute<TWriter, TReader,Alloc>::os;
  332. // os.reset();
  333. // doEncode(os);
  334. // tars::Int32 iHeaderLen = htonl(sizeof(tars::Int32) + os.getLength());
  335. // buff.assign((const char*)&iHeaderLen, sizeof(tars::Int32));
  336. // buff.append(os.getBuffer(), os.getLength());
  337. }
  338. /**
  339. * 编码,结果的包头4个字节为整个包的长度,网络字节序
  340. *
  341. * @throw runtime_error
  342. * @param buff: 编码结果输出参数
  343. */
  344. void encode(vector<char>& buff)
  345. {
  346. encodeBuff<vector<char>>(buff);
  347. // TarsOutputStream<TWriter> & os = UniAttribute<TWriter, TReader,Alloc>::os;
  348. // os.reset();
  349. // doEncode(os);
  350. // tars::Int32 iHeaderLen = htonl(sizeof(tars::Int32) + os.getLength());
  351. // buff.resize(sizeof(tars::Int32) + os.getLength());
  352. // memcpy(&buff[0], &iHeaderLen, sizeof(tars::Int32));
  353. // memcpy(&buff[sizeof(tars::Int32)], os.getBuffer(), os.getLength());
  354. }
  355. /**
  356. * 编码,结果的包头4个字节为整个包的长度,网络字节序
  357. * @throw runtime_error
  358. * @param buff:存放编码结果的buffer指针
  359. * @param len: 输入buff长度,输出编码结果长度
  360. */
  361. void encode(char* buff, size_t & len)
  362. {
  363. TarsOutputStream<TWriter>& os = UniAttribute<TWriter, TReader>::os;
  364. os.reset();
  365. doEncode(os);
  366. os.reset();
  367. writeTo(os);
  368. tars::Int32 iHeaderLen = htonl(sizeof(tars::Int32) + os.getLength());
  369. if (len < sizeof(tars::Int32) + os.getLength()) throw runtime_error("encode error, buffer length too short");
  370. memcpy(buff, &iHeaderLen, sizeof(tars::Int32));
  371. memcpy(buff + sizeof(tars::Int32), os.getBuffer(), os.getLength());
  372. len = sizeof(tars::Int32) + os.getLength();
  373. // TarsOutputStream<TWriter> &os = UniAttribute<TWriter, TReader,Alloc>::os;
  374. // os.reset();
  375. // doEncode(os);
  376. // tars::Int32 iHeaderLen = htonl(sizeof(tars::Int32) + os.getLength());
  377. // if(len < sizeof(tars::Int32) + os.getLength()) throw runtime_error("encode error, buffer length too short");
  378. // memcpy(buff, &iHeaderLen, sizeof(tars::Int32));
  379. // memcpy(buff + sizeof(tars::Int32), os.getBuffer(), os.getLength());
  380. // len = sizeof(tars::Int32) + os.getLength();
  381. }
  382. /** 解码
  383. *
  384. * @throw runtime_error
  385. * @param buff:待解码字节流的buffer指针
  386. * @param len: 待解码字节流的长度
  387. */
  388. void decode(const char* buff, size_t len)
  389. {
  390. if(len < sizeof(tars::Int32)) throw runtime_error("packet length too short, first 4 bytes must be buffer length.");
  391. TarsInputStream<TReader> &is = UniAttribute<TWriter, TReader,Alloc>::is;
  392. is.reset();
  393. is.setBuffer(buff + sizeof(tars::Int32), len - sizeof(tars::Int32));
  394. readFrom(is);
  395. UniAttribute<TWriter, TReader,Alloc>::_iVer = iVersion;
  396. is.reset();
  397. is.setBuffer(sBuffer);
  398. UniAttribute<TWriter, TReader,Alloc>::_data.clear();
  399. is.read(UniAttribute<TWriter, TReader,Alloc>::_data, 0, true);
  400. }
  401. public:
  402. /**
  403. * 获取消息version
  404. * @return tars::Short
  405. */
  406. tars::Short getVersion() const { return iVersion; }
  407. /**
  408. * 获取消息ID
  409. * @return tars::Int32
  410. */
  411. tars::Int32 getRequestId() const { return iRequestId; }
  412. /**
  413. * 设置请求ID
  414. * @param value
  415. */
  416. void setRequestId(tars::Int32 value) { iRequestId = value; }
  417. /**
  418. * 获取对象名称
  419. * @return const std::string&
  420. */
  421. const std::string& getServantName() const { return sServantName; }
  422. /**
  423. * 设置对象名称
  424. * @param value
  425. */
  426. void setServantName(const std::string& value) { sServantName = value; }
  427. /**
  428. * 获取方法名
  429. * @return const std::string&
  430. */
  431. const std::string& getFuncName() const { return sFuncName; }
  432. /**
  433. * 设置方法名
  434. * @param value
  435. */
  436. void setFuncName(const std::string& value) { sFuncName = value; }
  437. protected:
  438. template<typename T>
  439. void encodeBuff(T& buff)
  440. {
  441. TarsOutputStream<TWriter>& os = UniAttribute<TWriter, TReader>::os;
  442. os.reset();
  443. doEncode(os);
  444. os.reset();
  445. tars::Int32 iHeaderLen = 0;
  446. // 先预留4个字节长度
  447. os.writeBuf((const char *)&iHeaderLen, sizeof(iHeaderLen));
  448. writeTo(os);
  449. os.swap(buff);
  450. assert(buff.size() >= 4);
  451. iHeaderLen = htonl((int)(buff.size()));
  452. memcpy(&buff[0], (const char *)&iHeaderLen, sizeof(iHeaderLen));
  453. }
  454. /**
  455. * 内部编码
  456. */
  457. void doEncode(TarsOutputStream<TWriter>& os)
  458. {
  459. //ServantName、FuncName不能为空
  460. if (sServantName.empty()) throw runtime_error("ServantName must not be empty");
  461. if (sFuncName.empty()) throw runtime_error("FuncName must not be empty");
  462. os.reset();
  463. os.write(UniAttribute<TWriter, TReader>::_data, 0);
  464. os.swap(sBuffer);
  465. os.reset();
  466. }
  467. // /**
  468. // * 内部编码
  469. // */
  470. // void doEncode(TarsOutputStream<TWriter>& os)
  471. // {
  472. // //ServantName、FuncName不能为空
  473. // if(sServantName.empty()) throw runtime_error("ServantName must not be empty");
  474. // if(sFuncName.empty()) throw runtime_error("FuncName must not be empty");
  475. // os.reset();
  476. // os.write(UniAttribute<TWriter, TReader,Alloc>::_data, 0);
  477. // sBuffer.assign(os.getBuffer(), os.getBuffer() + os.getLength());
  478. // os.reset();
  479. // writeTo(os);
  480. // }
  481. };
  482. /////////////////////////////////////////////////////////////////////////////////
  483. // 调用TARS的服务时使用的类
  484. template<typename TWriter = BufferWriter, typename TReader = BufferReader,template<typename> class Alloc = std::allocator>
  485. struct TarsUniPacket: public UniPacket<TWriter, TReader,Alloc>
  486. {
  487. public:
  488. TarsUniPacket(){};
  489. TarsUniPacket(const UniPacket<TWriter, TReader,Alloc> &tup)
  490. : UniPacket<TWriter, TReader,Alloc>(tup) {};
  491. /**
  492. * 设置协议版本
  493. * @param value
  494. */
  495. void setTarsVersion(tars::Short value) { UniPacket<TWriter, TReader,Alloc>::setVersion(value); }
  496. /**
  497. * 设置调用类型
  498. * @param value
  499. */
  500. void setTarsPacketType(tars::Char value) { this->cPacketType = value; }
  501. /**
  502. * 设置消息类型
  503. * @param value
  504. */
  505. void setTarsMessageType(tars::Int32 value) { this->iMessageType = value; }
  506. /**
  507. * 设置超时时间
  508. * @param value
  509. */
  510. void setTarsTimeout(tars::Int32 value) { this->iTimeout = value; }
  511. /**
  512. * 设置参数编码内容
  513. * @param value
  514. */
  515. void setTarsBuffer(const vector<tars::Char>& value) { this->sBuffer = value; }
  516. /**
  517. * 设置上下文
  518. * @param value
  519. */
  520. void setTarsContext(const map<std::string, std::string>& value) { this->context = value; }
  521. /**
  522. * 设置特殊消息的状态值
  523. * @param value
  524. */
  525. void setTarsStatus(const map<std::string, std::string>& value) { this->status = value; }
  526. /**
  527. * 获取协议版本
  528. * @return tars::Short
  529. */
  530. tars::Short getTarsVersion() const { return this->iVersion; }
  531. /**
  532. * 获取调用类型
  533. * @return tars::Char
  534. */
  535. tars::Char getTarsPacketType() const { return this->cPacketType; }
  536. /**
  537. * 获取消息类型
  538. * @return tars::Int32
  539. */
  540. tars::Int32 getTarsMessageType() const { return this->iMessageType; }
  541. /**
  542. * 获取超时时间
  543. * @return tars::Int32
  544. */
  545. tars::Int32 getTarsTimeout() const { return this->iTimeout; }
  546. /**
  547. * 获取参数编码后内容
  548. * @return const vector<tars::Char>&
  549. */
  550. const vector<tars::Char>& getTarsBuffer() const { return this->sBuffer; }
  551. /**
  552. * 获取上下文信息
  553. * @return const map<std::string,std::string>&
  554. */
  555. const map<std::string, std::string>& getTarsContext() const { return this->context; }
  556. /**
  557. * 获取特殊消息的状态值
  558. * @return const map<std::string,std::string>&
  559. */
  560. const map<std::string, std::string>& getTarsStatus() const { return this->status; }
  561. /**
  562. * 获取调用tars的返回值
  563. *
  564. * @retrun tars::Int32
  565. */
  566. tars::Int32 getTarsResultCode() const
  567. {
  568. map<std::string, std::string>::const_iterator it;
  569. if((it = this->status.find(STATUS_RESULT_CODE)) == this->status.end())
  570. {
  571. return 0;
  572. }
  573. else
  574. {
  575. return atoi(it->second.c_str());
  576. }
  577. }
  578. /**
  579. * 获取调用tars的返回描述
  580. *
  581. * @retrun string
  582. */
  583. string getTarsResultDesc() const
  584. {
  585. map<std::string, std::string>::const_iterator it;
  586. if((it = this->status.find(STATUS_RESULT_DESC)) == this->status.end())
  587. {
  588. return "";
  589. }
  590. else
  591. {
  592. return it->second;
  593. }
  594. }
  595. };
  596. // #ifdef __GNUC__
  597. // # if __GNUC__ >3 || __GNUC_MINOR__ > 3
  598. // typedef UniAttribute<BufferWriter,BufferReader, __gnu_cxx::__pool_alloc> UniAttrPoolAlloc;
  599. // typedef UniPacket<BufferWriter,BufferReader, __gnu_cxx::__pool_alloc> UniPacketPoolAlloc;
  600. // typedef TarsUniPacket<BufferWriter,BufferReader, __gnu_cxx::__pool_alloc> TarsUniPacketPoolAlloc;
  601. // # endif
  602. // #endif
  603. }
  604. ////////////////////////////////////////////////////////////////////////////////////////////////
  605. #endif