tup.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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. }
  332. /**
  333. * 编码,结果的包头4个字节为整个包的长度,网络字节序
  334. *
  335. * @throw runtime_error
  336. * @param buff: 编码结果输出参数
  337. */
  338. void encode(vector<char>& buff)
  339. {
  340. encodeBuff<vector<char>>(buff);
  341. }
  342. /**
  343. * 编码,结果的包头4个字节为整个包的长度,网络字节序
  344. * @throw runtime_error
  345. * @param buff:存放编码结果的buffer指针
  346. * @param len: 输入buff长度,输出编码结果长度
  347. */
  348. void encode(char* buff, size_t & len)
  349. {
  350. TarsOutputStream<TWriter>& os = UniAttribute<TWriter, TReader>::os;
  351. os.reset();
  352. doEncode(os);
  353. os.reset();
  354. writeTo(os);
  355. tars::Int32 iHeaderLen = htonl(sizeof(tars::Int32) + os.getLength());
  356. if (len < sizeof(tars::Int32) + os.getLength()) throw runtime_error("encode error, buffer length too short");
  357. memcpy(buff, &iHeaderLen, sizeof(tars::Int32));
  358. memcpy(buff + sizeof(tars::Int32), os.getBuffer(), os.getLength());
  359. len = sizeof(tars::Int32) + os.getLength();
  360. }
  361. /** 解码
  362. *
  363. * @throw runtime_error
  364. * @param buff:待解码字节流的buffer指针
  365. * @param len: 待解码字节流的长度
  366. */
  367. void decode(const char* buff, size_t len)
  368. {
  369. if(len < sizeof(tars::Int32)) throw runtime_error("packet length too short, first 4 bytes must be buffer length.");
  370. TarsInputStream<TReader> &is = UniAttribute<TWriter, TReader,Alloc>::is;
  371. is.reset();
  372. is.setBuffer(buff + sizeof(tars::Int32), len - sizeof(tars::Int32));
  373. readFrom(is);
  374. UniAttribute<TWriter, TReader,Alloc>::_iVer = iVersion;
  375. is.reset();
  376. is.setBuffer(sBuffer);
  377. UniAttribute<TWriter, TReader,Alloc>::_data.clear();
  378. is.read(UniAttribute<TWriter, TReader,Alloc>::_data, 0, true);
  379. }
  380. public:
  381. /**
  382. * 获取消息version
  383. * @return tars::Short
  384. */
  385. tars::Short getVersion() const { return iVersion; }
  386. /**
  387. * 获取消息ID
  388. * @return tars::Int32
  389. */
  390. tars::Int32 getRequestId() const { return iRequestId; }
  391. /**
  392. * 设置请求ID
  393. * @param value
  394. */
  395. void setRequestId(tars::Int32 value) { iRequestId = value; }
  396. /**
  397. * 获取对象名称
  398. * @return const std::string&
  399. */
  400. const std::string& getServantName() const { return sServantName; }
  401. /**
  402. * 设置对象名称
  403. * @param value
  404. */
  405. void setServantName(const std::string& value) { sServantName = value; }
  406. /**
  407. * 获取方法名
  408. * @return const std::string&
  409. */
  410. const std::string& getFuncName() const { return sFuncName; }
  411. /**
  412. * 设置方法名
  413. * @param value
  414. */
  415. void setFuncName(const std::string& value) { sFuncName = value; }
  416. protected:
  417. template<typename T>
  418. void encodeBuff(T& buff)
  419. {
  420. TarsOutputStream<TWriter>& os = UniAttribute<TWriter, TReader>::os;
  421. os.reset();
  422. doEncode(os);
  423. os.reset();
  424. tars::Int32 iHeaderLen = 0;
  425. // 先预留4个字节长度
  426. os.writeBuf((const char *)&iHeaderLen, sizeof(iHeaderLen));
  427. writeTo(os);
  428. os.swap(buff);
  429. assert(buff.size() >= 4);
  430. iHeaderLen = htonl((int)(buff.size()));
  431. memcpy(&buff[0], (const char *)&iHeaderLen, sizeof(iHeaderLen));
  432. }
  433. /**
  434. * 内部编码
  435. */
  436. void doEncode(TarsOutputStream<TWriter>& os)
  437. {
  438. //ServantName、FuncName不能为空
  439. if (sServantName.empty()) throw runtime_error("ServantName must not be empty");
  440. if (sFuncName.empty()) throw runtime_error("FuncName must not be empty");
  441. os.reset();
  442. os.write(UniAttribute<TWriter, TReader>::_data, 0);
  443. os.swap(sBuffer);
  444. os.reset();
  445. }
  446. };
  447. /////////////////////////////////////////////////////////////////////////////////
  448. // 调用TARS的服务时使用的类
  449. template<typename TWriter = BufferWriter, typename TReader = BufferReader,template<typename> class Alloc = std::allocator>
  450. struct TarsUniPacket: public UniPacket<TWriter, TReader,Alloc>
  451. {
  452. public:
  453. TarsUniPacket(){};
  454. TarsUniPacket(const UniPacket<TWriter, TReader,Alloc> &tup)
  455. : UniPacket<TWriter, TReader,Alloc>(tup) {};
  456. /**
  457. * 设置协议版本
  458. * @param value
  459. */
  460. void setTarsVersion(tars::Short value) { UniPacket<TWriter, TReader,Alloc>::setVersion(value); }
  461. /**
  462. * 设置调用类型
  463. * @param value
  464. */
  465. void setTarsPacketType(tars::Char value) { this->cPacketType = value; }
  466. /**
  467. * 设置消息类型
  468. * @param value
  469. */
  470. void setTarsMessageType(tars::Int32 value) { this->iMessageType = value; }
  471. /**
  472. * 设置超时时间
  473. * @param value
  474. */
  475. void setTarsTimeout(tars::Int32 value) { this->iTimeout = value; }
  476. /**
  477. * 设置参数编码内容
  478. * @param value
  479. */
  480. void setTarsBuffer(const vector<tars::Char>& value) { this->sBuffer = value; }
  481. /**
  482. * 设置上下文
  483. * @param value
  484. */
  485. void setTarsContext(const map<std::string, std::string>& value) { this->context = value; }
  486. /**
  487. * 设置特殊消息的状态值
  488. * @param value
  489. */
  490. void setTarsStatus(const map<std::string, std::string>& value) { this->status = value; }
  491. /**
  492. * 获取协议版本
  493. * @return tars::Short
  494. */
  495. tars::Short getTarsVersion() const { return this->iVersion; }
  496. /**
  497. * 获取调用类型
  498. * @return tars::Char
  499. */
  500. tars::Char getTarsPacketType() const { return this->cPacketType; }
  501. /**
  502. * 获取消息类型
  503. * @return tars::Int32
  504. */
  505. tars::Int32 getTarsMessageType() const { return this->iMessageType; }
  506. /**
  507. * 获取超时时间
  508. * @return tars::Int32
  509. */
  510. tars::Int32 getTarsTimeout() const { return this->iTimeout; }
  511. /**
  512. * 获取参数编码后内容
  513. * @return const vector<tars::Char>&
  514. */
  515. const vector<tars::Char>& getTarsBuffer() const { return this->sBuffer; }
  516. /**
  517. * 获取上下文信息
  518. * @return const map<std::string,std::string>&
  519. */
  520. const map<std::string, std::string>& getTarsContext() const { return this->context; }
  521. /**
  522. * 获取特殊消息的状态值
  523. * @return const map<std::string,std::string>&
  524. */
  525. const map<std::string, std::string>& getTarsStatus() const { return this->status; }
  526. /**
  527. * 获取调用tars的返回值
  528. *
  529. * @retrun tars::Int32
  530. */
  531. tars::Int32 getTarsResultCode() const
  532. {
  533. map<std::string, std::string>::const_iterator it;
  534. if((it = this->status.find(STATUS_RESULT_CODE)) == this->status.end())
  535. {
  536. return 0;
  537. }
  538. else
  539. {
  540. return atoi(it->second.c_str());
  541. }
  542. }
  543. /**
  544. * 获取调用tars的返回描述
  545. *
  546. * @retrun string
  547. */
  548. string getTarsResultDesc() const
  549. {
  550. map<std::string, std::string>::const_iterator it;
  551. if((it = this->status.find(STATUS_RESULT_DESC)) == this->status.end())
  552. {
  553. return "";
  554. }
  555. else
  556. {
  557. return it->second;
  558. }
  559. }
  560. };
  561. // #ifdef __GNUC__
  562. // # if __GNUC__ >3 || __GNUC_MINOR__ > 3
  563. // typedef UniAttribute<BufferWriter,BufferReader, __gnu_cxx::__pool_alloc> UniAttrPoolAlloc;
  564. // typedef UniPacket<BufferWriter,BufferReader, __gnu_cxx::__pool_alloc> UniPacketPoolAlloc;
  565. // typedef TarsUniPacket<BufferWriter,BufferReader, __gnu_cxx::__pool_alloc> TarsUniPacketPoolAlloc;
  566. // # endif
  567. // #endif
  568. }
  569. ////////////////////////////////////////////////////////////////////////////////////////////////
  570. #endif