Advertisement
Guest User

Untitled

a guest
Nov 27th, 2015
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 306.17 KB | None | 0 0
  1. <sara xmlns="http://www.automic.com/sara/snsc">
  2. <references>
  3. <variable_types>
  4. <var_type value="1">Yes / No</var_type>
  5. <var_type value="2">Multi Line Text</var_type>
  6. <var_type value="3">Multiple Choice</var_type>
  7. <var_type value="4">Numeric Scale</var_type>
  8. <var_type value="18">Lookup Select Box</var_type>
  9. <var_type value="5">Select Box</var_type>
  10. <var_type value="6">Single Line Text</var_type>
  11. <var_type value="7">CheckBox</var_type>
  12. <var_type value="8">Reference</var_type>
  13. <var_type value="9">Date</var_type>
  14. <var_type value="10">Date/Time</var_type>
  15. <var_type value="11">Label</var_type>
  16. <var_type value="12">Break</var_type>
  17. <var_type value="14">Macro</var_type>
  18. <var_type value="15">UI Page</var_type>
  19. <var_type value="16">Wide Single Line Text</var_type>
  20. <var_type value="17">Macro with Label</var_type>
  21. <var_type value="21">List Collector</var_type>
  22. <var_type value="22">Lookup Multiple Choice</var_type>
  23. <var_type value="23">HTML</var_type>
  24. </variable_types>
  25. </references>
  26. <package name="snsc" version="1.0-SNAPSHOT">
  27. <description/>
  28.  
  29. <system_properties>
  30. <category>
  31. <name>Automic</name>
  32. <title>This category consists of all SARA OAuth client settings</title>
  33. <properties>
  34. <property>
  35. <suffix>mid_server</suffix>
  36. <description>MID Server name to use</description>
  37. <type>string</type>
  38. <value/>
  39. <ignore_cache>false</ignore_cache>
  40. <private>false</private>
  41. </property>
  42. <property>
  43. <suffix>workflow_timeout</suffix>
  44. <description>Specifies the time during that the status of service/workflow is checked continuesly. The interval of checking is specified by the parameter x_ausgh_snsc.workflow_delay. If the value equals 0, the duration time will be forever.
  45. *Note: This value is second(s).</description>
  46. <type>string</type>
  47. <value>0</value>
  48. <ignore_cache>false</ignore_cache>
  49. <private>false</private>
  50. </property>
  51. <property>
  52. <suffix>workflow_delay</suffix>
  53. <description>Specifies the interval of checking a workflow/service's status. If the value equals 0, the time interval will be 60.
  54. *Note: This value is second(s).</description>
  55. <type>string</type>
  56. <value>20</value>
  57. <ignore_cache>false</ignore_cache>
  58. <private>false</private>
  59. </property>
  60. <property>
  61. <suffix>rest_request_timeout</suffix>
  62. <description>Specifies the amount of time the instance waits for a response from the web service provider. If the value equals 0, the timeout will be 60.
  63. *Note: This value is second(s).</description>
  64. <type>string</type>
  65. <value>120</value>
  66. <ignore_cache>false</ignore_cache>
  67. <private>false</private>
  68. </property>
  69. <property>
  70. <suffix>service_active</suffix>
  71. <description>The default active status of services after importing. Can be "true" for active and "false" for inactive.</description>
  72. <type>boolean</type>
  73. <value>true</value>
  74. <ignore_cache>false</ignore_cache>
  75. <private>false</private>
  76. </property>
  77. </properties>
  78. </category>
  79. </system_properties>
  80.  
  81.  
  82. <tables>
  83. <table>
  84. <name>x_ausgh_snsc_sara_oauth</name>
  85. <label>Sara OAuth</label>
  86. <extends_table/>
  87. <user_role>x_ausgh_snsc.user</user_role>
  88. <is_extendable>false</is_extendable>
  89. <dictionary_entries>
  90. <column>
  91. <name>u_access_token</name>
  92. <type>string</type>
  93. <label>Access Token</label>
  94. <max_length>1000</max_length>
  95. <hint>Access token from OAuth</hint>
  96. </column>
  97. <column>
  98. <name>u_refresh_token</name>
  99. <type>string</type>
  100. <label>Refresh Token</label>
  101. <max_length>1000</max_length>
  102. <hint>Refresh token from OAuth</hint>
  103. </column>
  104. <column>
  105. <name>u_token_expiry</name>
  106. <type>string</type>
  107. <label>Token Expiry</label>
  108. <max_length>40</max_length>
  109. <hint>The lived time of token from OAuth</hint>
  110. </column>
  111. <column>
  112. <name>u_token_type</name>
  113. <type>string</type>
  114. <label>Token Type</label>
  115. <max_length>40</max_length>
  116. <hint>The type of token from OAuth</hint>
  117. </column>
  118. <column>
  119. <name>u_user</name>
  120. <type>string</type>
  121. <label>Technical User</label>
  122. <max_length>1000</max_length>
  123. <display>true</display>
  124. <hint>The AE technical user own this token</hint>
  125. </column>
  126. </dictionary_entries>
  127. </table>
  128. <table>
  129. <name>x_ausgh_snsc_sara_variable</name>
  130. <label>Sara Variable</label>
  131. <extends_table>item_option_new</extends_table>
  132. <user_role>x_ausgh_snsc.user</user_role>
  133. <is_extendable>false</is_extendable>
  134. <dictionary_entries>
  135. <column>
  136. <name>u_name</name>
  137. <type>string</type>
  138. <label>Actual Name</label>
  139. <max_length>1000</max_length>
  140. <display>true</display>
  141. <hint>The actual name of variable in AE</hint>
  142. </column>
  143. <column>
  144. <name>u_readonly</name>
  145. <type>boolean</type>
  146. <label>Read Only</label>
  147. <max_length>40</max_length>
  148. <hint>This is read-only field or not</hint>
  149. </column>
  150. <column>
  151. <name>u_is_password</name>
  152. <type>boolean</type>
  153. <label>Is Password</label>
  154. <max_length>40</max_length>
  155. <hint>This field is marked as password or not</hint>
  156. </column>
  157. <column>
  158. <name>u_is_lookup</name>
  159. <type>boolean</type>
  160. <label>Is Lookup Control</label>
  161. <max_length>40</max_length>
  162. <hint>This control is lookup control or not</hint>
  163. </column>
  164. <column>
  165. <name>u_hash</name>
  166. <type>string</type>
  167. <label>Sara Variable Hash</label>
  168. <max_length>32</max_length>
  169. <hint>The hash of current lookup values of control from SAPI</hint>
  170. </column>
  171. </dictionary_entries>
  172. </table>
  173. <table>
  174. <name>x_ausgh_snsc_sara_definition</name>
  175. <label>Sara Definition</label>
  176. <extends_table/>
  177. <user_role>x_ausgh_snsc.user</user_role>
  178. <is_extendable>false</is_extendable>
  179. <dictionary_entries>
  180. <column>
  181. <name>u_name</name>
  182. <type>string</type>
  183. <label>Name</label>
  184. <max_length>1000</max_length>
  185. <display>true</display>
  186. <hint>Name of catalog item or category</hint>
  187. </column>
  188. <column>
  189. <name>u_consume_url</name>
  190. <type>string</type>
  191. <label>Consume URL</label>
  192. <max_length>1000</max_length>
  193. <hint>Consume URL of SAPI service</hint>
  194. </column>
  195. <column>
  196. <name>u_sc_item</name>
  197. <type>reference</type>
  198. <label>Service Catalog Item</label>
  199. <max_length>32</max_length>
  200. <reference>sc_cat_item</reference>
  201. <reference_cascade_rule>delete</reference_cascade_rule>
  202. <hint>The corresponding Catalog item in sc_cat_item table</hint>
  203. </column>
  204. <column>
  205. <name>u_service_catalog_category</name>
  206. <type>reference</type>
  207. <label>Service Catalog Category</label>
  208. <max_length>32</max_length>
  209. <reference>sc_category</reference>
  210. <reference_cascade_rule>delete</reference_cascade_rule>
  211. <hint>The corresponding Category in sc_cateogry table</hint>
  212. </column>
  213. <column>
  214. <name>u_var_set</name>
  215. <type>reference</type>
  216. <label>Sara Variable Set</label>
  217. <max_length>32</max_length>
  218. <reference>item_option_new_set</reference>
  219. <hint>The corresponding Variable Set in item_option_new_set table</hint>
  220. </column>
  221. <column>
  222. <name>u_parent</name>
  223. <type>reference</type>
  224. <label>Parent Category</label>
  225. <max_length>32</max_length>
  226. <reference>sc_category</reference>
  227. <hint>Reference to parent category, for catalog item it's the parent category (or catalog in SAPI term), for category it's the target category when it was imported.</hint>
  228. </column>
  229. <column>
  230. <name>u_type</name>
  231. <type>string</type>
  232. <label>Sara Type</label>
  233. <max_length>40</max_length>
  234. <hint>Type of entity. Can be catalog, service, category</hint>
  235. </column>
  236. <column>
  237. <name>u_hash</name>
  238. <type>string</type>
  239. <label>Sara Object Hash</label>
  240. <max_length>32</max_length>
  241. <hint>The hash of response data from SAPI for Catalog Item</hint>
  242. </column>
  243. </dictionary_entries>
  244. </table>
  245. <table>
  246. <name>x_ausgh_snsc_sara_lookup</name>
  247. <label>Sara Lookup</label>
  248. <extends_table/>
  249. <user_role>catalog</user_role>
  250. <is_extendable>false</is_extendable>
  251. <dictionary_entries>
  252. <column>
  253. <name>u_key</name>
  254. <type>string</type>
  255. <label>Key</label>
  256. <max_length>203</max_length>
  257. <hint>The key value of lookup value</hint>
  258. </column>
  259. <column>
  260. <name>u_display_name</name>
  261. <type>string</type>
  262. <label>Display Name</label>
  263. <display>true</display>
  264. <max_length>1023</max_length>
  265. <hint>The display name value of lookup value</hint>
  266. </column>
  267. <column>
  268. <name>u_control_id</name>
  269. <type>reference</type>
  270. <label>Lookup Control ID</label>
  271. <max_length>32</max_length>
  272. <reference>x_ausgh_snsc_sara_variable</reference>
  273. <reference_cascade_rule>delete</reference_cascade_rule>
  274. <hint>The sys_id of control which owns this lookup value</hint>
  275. </column>
  276. </dictionary_entries>
  277. </table>
  278. <table>
  279. <name>x_ausgh_snsc_sara_config</name>
  280. <label>Sara Configuration</label>
  281. <extends_table/>
  282. <user_role>x_ausgh_snsc.user</user_role>
  283. <is_extendable>false</is_extendable>
  284. <dictionary_entries>
  285. <column>
  286. <name>u_client_id</name>
  287. <type>string</type>
  288. <label>OAuth Client ID</label>
  289. <max_length>1000</max_length>
  290. <display>true</display>
  291. <hint>Identity of OAuth client</hint>
  292. </column>
  293. <column>
  294. <name>u_client_secret</name>
  295. <type>string</type>
  296. <label>OAuth Client Secret</label>
  297. <max_length>1000</max_length>
  298. <hint>OAuth client secret string</hint>
  299. </column>
  300. <column>
  301. <name>u_technical_user</name>
  302. <type>string</type>
  303. <label>Technical User</label>
  304. <max_length>1000</max_length>
  305. <hint>The Technical User for authenticating with OAuth Server</hint>
  306. </column>
  307. <column>
  308. <name>u_sapi_endpoint</name>
  309. <type>string</type>
  310. <label>SAPI Endpoint</label>
  311. <max_length>1000</max_length>
  312. <hint>URL to SAPI root endpoint</hint>
  313. </column>
  314. <column>
  315. <name>u_token_endpoint</name>
  316. <type>string</type>
  317. <label>OAuth Token Endpoint</label>
  318. <max_length>1000</max_length>
  319. <hint>Endpoint for token requesting/refreshing</hint>
  320. </column>
  321. <column>
  322. <name>u_auth_endpoint</name>
  323. <type>string</type>
  324. <label>OAuth Authorization Endpoint</label>
  325. <max_length>1000</max_length>
  326. <hint>Authorization endpoint for OAuth authentication</hint>
  327. </column>
  328. </dictionary_entries>
  329. </table>
  330.  
  331. <table>
  332. <name>x_ausgh_snsc_sc_catalog_ist</name>
  333. <label>Service Catalog ImportSet</label>
  334. <extends_table>sys_import_set_row</extends_table>
  335. <is_extendable>false</is_extendable>
  336. <dictionary_entries>
  337. <column>
  338. <name>title</name>
  339. <type>translated_field</type>
  340. <label>Title</label>
  341. <max_length>100</max_length>
  342. <hint>Title</hint>
  343. <mandatory>true</mandatory>
  344. <display>true</display>
  345. </column>
  346. <column>
  347. <name>active</name>
  348. <type>boolean</type>
  349. <label>Active</label>
  350. <max_length>40</max_length>
  351. <hint/>
  352. </column>
  353. <column>
  354. <name>description</name>
  355. <type>translated_text</type>
  356. <label>Description</label>
  357. <max_length>4000</max_length>
  358. <hint>Description</hint>
  359. </column>
  360. </dictionary_entries>
  361. </table>
  362. <table>
  363. <name>x_ausgh_snsc_sc_category_ist</name>
  364. <label>Service Category ImportSet</label>
  365. <extends_table>sys_import_set_row</extends_table>
  366. <is_extendable>false</is_extendable>
  367. <dictionary_entries>
  368. <column>
  369. <name>title</name>
  370. <type>translated_text</type>
  371. <label>Title</label>
  372. <max_length>100</max_length>
  373. <hint>Title</hint>
  374. <mandatory>true</mandatory>
  375. <display>true</display>
  376. </column>
  377. <column>
  378. <name>homepage_renderer</name>
  379. <type>string</type>
  380. <label>Homepage Renderer</label>
  381. <max_length>32</max_length>
  382. <hint>Homepage Renderer</hint>
  383. </column>
  384. <column>
  385. <name>active</name>
  386. <type>boolean</type>
  387. <label>Active</label>
  388. <max_length>40</max_length>
  389. <hint/>
  390. </column>
  391. <column>
  392. <name>description</name>
  393. <type>translated_text</type>
  394. <label>Description</label>
  395. <max_length>4000</max_length>
  396. <hint>Description</hint>
  397. </column>
  398. <column>
  399. <name>parent</name>
  400. <type>string</type>
  401. <label>Parent</label>
  402. <max_length>32</max_length>
  403. <hint>Parent</hint>
  404. </column>
  405. <column>
  406. <name>sc_catalog</name>
  407. <type>string</type>
  408. <label>Catalog</label>
  409. <max_length>32</max_length>
  410. <hint>Catalog</hint>
  411. </column>
  412.  
  413. </dictionary_entries>
  414. </table>
  415. <table>
  416. <name>x_ausgh_snsc_sc_cat_item_ist</name>
  417. <label>Catalog Item ImportSet</label>
  418. <extends_table>sys_import_set_row</extends_table>
  419. <is_extendable>false</is_extendable>
  420. <dictionary_entries>
  421. <column>
  422. <name>name</name>
  423. <type>translated_text</type>
  424. <label>Name</label>
  425. <max_length>100</max_length>
  426. <hint>Name</hint>
  427. <mandatory>true</mandatory>
  428. <display>true</display>
  429. </column>
  430. <column>
  431. <name>category</name>
  432. <type>string</type>
  433. <label>Category Reference</label>
  434. <max_length>32</max_length>
  435. <hint>Category Reference</hint>
  436. </column>
  437. <column>
  438. <name>active</name>
  439. <type>boolean</type>
  440. <label>Active</label>
  441. <max_length>40</max_length>
  442. <hint/>
  443. </column>
  444. <column>
  445. <name>short_description</name>
  446. <type>translated_text</type>
  447. <label>Short Description</label>
  448. <max_length>200</max_length>
  449. <hint>Short Description</hint>
  450. </column>
  451. <column>
  452. <name>description</name>
  453. <type>translated_html</type>
  454. <label>Description</label>
  455. <max_length>8000</max_length>
  456. <hint>Description</hint>
  457. </column>
  458. <column>
  459. <name>custom_cart</name>
  460. <type>string</type>
  461. <label>Custom Cart</label>
  462. <max_length>32</max_length>
  463. <hint>Custom Cart Reference</hint>
  464. </column>
  465. <column>
  466. <name>use_sc_layout</name>
  467. <type>boolean</type>
  468. <label>Use Catalog Layout</label>
  469. <max_length>40</max_length>
  470. <hint/>
  471. </column>
  472. <column>
  473. <name>no_quantity</name>
  474. <type>boolean</type>
  475. <label>No Quantity</label>
  476. <max_length>40</max_length>
  477. <hint/>
  478. </column>
  479. </dictionary_entries>
  480. </table>
  481. <table>
  482. <name>x_ausgh_snsc_item_option_new_set_ist</name>
  483. <label>Variable Set ImportSet</label>
  484. <extends_table>sys_import_set_row</extends_table>
  485. <is_extendable>false</is_extendable>
  486. <dictionary_entries>
  487. <column>
  488. <name>name</name>
  489. <type>string</type>
  490. <label>Name</label>
  491. <max_length>40</max_length>
  492. <hint>Name</hint>
  493. <mandatory>true</mandatory>
  494. <display>true</display>
  495. </column>
  496. <column>
  497. <name>description</name>
  498. <type>string</type>
  499. <label>Description</label>
  500. <max_length>4000</max_length>
  501. <hint>Description</hint>
  502. </column>
  503. <column>
  504. <name>title</name>
  505. <type>translated_field</type>
  506. <label>Title</label>
  507. <max_length>80</max_length>
  508. <hint>Title</hint>
  509. </column>
  510. <column>
  511. <name>sys_name</name>
  512. <type>string</type>
  513. <label>Display Name</label>
  514. <max_length>255</max_length>
  515. <hint>Display Name</hint>
  516. </column>
  517. </dictionary_entries>
  518. </table>
  519. <table>
  520. <name>x_ausgh_snsc_io_set_item_ist</name>
  521. <label>Catalog Variable Set ImportSet</label>
  522. <extends_table>sys_import_set_row</extends_table>
  523. <is_extendable>false</is_extendable>
  524. <dictionary_entries>
  525. <column>
  526. <name>sc_cat_item</name>
  527. <type>string</type>
  528. <label>Catalog Item</label>
  529. <max_length>32</max_length>
  530. <hint>Catalog Item</hint>
  531. <mandatory>true</mandatory>
  532. <display>true</display>
  533. </column>
  534. <column>
  535. <name>variable_set</name>
  536. <type>string</type>
  537. <label>Variable Set</label>
  538. <max_length>32</max_length>
  539. <hint>Variable Set</hint>
  540. <mandatory>true</mandatory>
  541. </column>
  542. </dictionary_entries>
  543. </table>
  544. <table>
  545. <name>x_ausgh_snsc_sara_definition_ist</name>
  546. <label>Sara Definition ImportSet</label>
  547. <user_role>x_ausgh_snsc.user</user_role>
  548. <is_extendable>false</is_extendable>
  549. <extends_table>sys_import_set_row</extends_table>
  550. <dictionary_entries>
  551. <column>
  552. <name>u_name</name>
  553. <type>string</type>
  554. <label>Name</label>
  555. <max_length>1000</max_length>
  556. <display>true</display>
  557. <hint>Name of catalog item or category</hint>
  558. <mandatory>true</mandatory>
  559. </column>
  560. <column>
  561. <name>u_consume_url</name>
  562. <type>string</type>
  563. <label>Consume URL</label>
  564. <max_length>1000</max_length>
  565. <hint>Consume URL of SAPI service</hint>
  566. </column>
  567. <column>
  568. <name>u_sc_item</name>
  569. <type>string</type>
  570. <label>Service Catalog Item</label>
  571. <max_length>32</max_length>
  572. <hint>The corresponding Catalog item in sc_cat_item table</hint>
  573. </column>
  574. <column>
  575. <name>u_service_catalog_category</name>
  576. <type>string</type>
  577. <label>Service Catalog Category</label>
  578. <max_length>32</max_length>
  579. <hint>The corresponding Category in sc_cateogry table</hint>
  580. </column>
  581. <column>
  582. <name>u_var_set</name>
  583. <type>string</type>
  584. <label>Sara Variable Set</label>
  585. <max_length>32</max_length>
  586. <hint>The corresponding Variable Set in item_option_new_set table</hint>
  587. </column>
  588. <column>
  589. <name>u_parent</name>
  590. <type>string</type>
  591. <label>Parent Category</label>
  592. <max_length>32</max_length>
  593. <hint>Reference to parent category, for catalog item it's the parent category (or catalog in SAPI term), for category it's the target category when it was imported.</hint>
  594. </column>
  595. <column>
  596. <name>u_type</name>
  597. <type>string</type>
  598. <label>Sara Type</label>
  599. <max_length>40</max_length>
  600. <hint>Type of entity. Can be catalog, service, category</hint>
  601. </column>
  602. <column>
  603. <name>u_hash</name>
  604. <type>string</type>
  605. <label>Sara Object Hash</label>
  606. <max_length>32</max_length>
  607. <hint>The hash of response data from SAPI for Catalog Item</hint>
  608. </column>
  609. </dictionary_entries>
  610. </table>
  611. <table>
  612. <name>x_ausgh_snsc_sara_variable_ist</name>
  613. <label>Sara Variable ImportSet</label>
  614. <extends_table>sys_import_set_row</extends_table>
  615. <user_role>x_ausgh_snsc.user</user_role>
  616. <is_extendable>false</is_extendable>
  617. <dictionary_entries>
  618. <column>
  619. <name>u_name</name>
  620. <type>string</type>
  621. <label>Actual Name</label>
  622. <max_length>1000</max_length>
  623. <display>true</display>
  624. <hint>The actual name of variable in AE</hint>
  625. <mandatory>true</mandatory>
  626. <display>true</display>
  627. </column>
  628. <column>
  629. <name>u_readonly</name>
  630. <type>boolean</type>
  631. <label>Read Only</label>
  632. <max_length>40</max_length>
  633. <hint>This is read-only field or not</hint>
  634. </column>
  635. <column>
  636. <name>u_is_password</name>
  637. <type>boolean</type>
  638. <label>Is Password</label>
  639. <max_length>40</max_length>
  640. <hint>This field is marked as password or not</hint>
  641. </column>
  642. <column>
  643. <name>u_is_lookup</name>
  644. <type>boolean</type>
  645. <label>Is Lookup Control</label>
  646. <max_length>40</max_length>
  647. <hint>This control is lookup control or not</hint>
  648. </column>
  649. <column>
  650. <name>u_hash</name>
  651. <type>string</type>
  652. <label>Sara Variable Hash</label>
  653. <max_length>32</max_length>
  654. <hint>The hash of current lookup values of control from SAPI</hint>
  655. </column>
  656. <column>
  657. <name>variable_set</name>
  658. <type>string</type>
  659. <label>Variable Set</label>
  660. <max_length>32</max_length>
  661. <hint>Variable Set</hint>
  662. </column>
  663. <column>
  664. <name>type</name>
  665. <type>string</type>
  666. <label>Type</label>
  667. <max_length>40</max_length>
  668. <hint>Type</hint>
  669. </column>
  670. <column>
  671. <name>macro</name>
  672. <type>string</type>
  673. <label>Macro</label>
  674. <max_length>32</max_length>
  675. <hint>Macro</hint>
  676. </column>
  677. <column>
  678. <name>name</name>
  679. <type>string</type>
  680. <label>Name</label>
  681. <max_length>40</max_length>
  682. <hint>Name</hint>
  683. </column>
  684. <column>
  685. <name>cat_item</name>
  686. <type>string</type>
  687. <label>Catalog Item</label>
  688. <max_length>32</max_length>
  689. <hint>Catalog Item</hint>
  690. </column>
  691. <column>
  692. <name>variable_set</name>
  693. <type>string</type>
  694. <label>Variable Set</label>
  695. <max_length>32</max_length>
  696. <hint>Variable Set</hint>
  697. </column>
  698. <column>
  699. <name>help_text</name>
  700. <type>translated_text</type>
  701. <label>Help text</label>
  702. <max_length>4000</max_length>
  703. <hint>Help text</hint>
  704. </column>
  705. <column>
  706. <name>show_help</name>
  707. <type>boolean</type>
  708. <label>Show help</label>
  709. <max_length>40</max_length>
  710. <hint>Show help</hint>
  711. </column>
  712. <column>
  713. <name>include_none</name>
  714. <type>boolean</type>
  715. <label>Include none</label>
  716. <max_length>40</max_length>
  717. <hint>Include none</hint>
  718. </column>
  719. <column>
  720. <name>default_value</name>
  721. <type>string</type>
  722. <label>Default value</label>
  723. <max_length>512</max_length>
  724. <hint>Default value</hint>
  725. </column>
  726. <column>
  727. <name>question_text</name>
  728. <type>translated_field</type>
  729. <label>Question text</label>
  730. <max_length>255</max_length>
  731. <hint>Question text</hint>
  732. </column>
  733. <column>
  734. <name>mandatory</name>
  735. <type>boolean</type>
  736. <label>Mandatory</label>
  737. <max_length>40</max_length>
  738. <hint>Mandatory</hint>
  739. </column>
  740. <column>
  741. <name>list_table</name>
  742. <type>list_table</type>
  743. <label>List table</label>
  744. <max_length>80</max_length>
  745. <hint>List table</hint>
  746. </column>
  747. <column>
  748. <name>attributes</name>
  749. <type>string</type>
  750. <label>Variable attributes</label>
  751. <max_length>255</max_length>
  752. <hint>Variable attributes</hint>
  753. </column>
  754. <column>
  755. <name>lookup_table</name>
  756. <type>table_name</type>
  757. <label>Lookup from table</label>
  758. <max_length>80</max_length>
  759. <hint>Lookup from table</hint>
  760. </column>
  761. <column>
  762. <name>lookup_value</name>
  763. <type>field_name</type>
  764. <label>Lookup value field</label>
  765. <max_length>80</max_length>
  766. <hint>Lookup value field</hint>
  767. </column>
  768. <column>
  769. <name>reference_qual</name>
  770. <type>string</type>
  771. <label>Reference qual</label>
  772. <max_length>255</max_length>
  773. <hint>Reference qual</hint>
  774. </column>
  775. </dictionary_entries>
  776. </table>
  777. <table>
  778. <name>x_ausgh_snsc_sara_lookup_ist</name>
  779. <label>Sara Lookup ImportSet</label>
  780. <extends_table>sys_import_set_row</extends_table>
  781. <user_role>catalog</user_role>
  782. <is_extendable>false</is_extendable>
  783. <dictionary_entries>
  784. <column>
  785. <name>u_key</name>
  786. <type>string</type>
  787. <label>Key</label>
  788. <max_length>203</max_length>
  789. <hint>The key value of lookup value</hint>
  790. <mandatory>true</mandatory>
  791. <display>true</display>
  792. </column>
  793. <column>
  794. <name>u_display_name</name>
  795. <type>string</type>
  796. <label>Display Name</label>
  797. <display>true</display>
  798. <max_length>1023</max_length>
  799. <hint>The display name value of lookup value</hint>
  800. </column>
  801. <column>
  802. <name>u_control_id</name>
  803. <type>string</type>
  804. <label>Lookup Control ID</label>
  805. <max_length>32</max_length>
  806. <hint>The sys_id of control which owns this lookup value</hint>
  807. </column>
  808. </dictionary_entries>
  809. </table>
  810. </tables>
  811.  
  812.  
  813. <transform_maps>
  814. <transform_map>
  815. <name>x_ausgh_snsc_sc_catalog_transform_map</name>
  816. <source_table>x_ausgh_snsc_sc_catalog_ist</source_table>
  817. <target_table>sc_catalog</target_table>
  818. <copy_empty_fields>true</copy_empty_fields>
  819. <active>true</active>
  820. <run_business_rules>false</run_business_rules>
  821. <fields>
  822. <field>
  823. <source_field>title</source_field>
  824. <coalesce>true</coalesce>
  825. </field>
  826. <field>
  827. <source_field>active</source_field>
  828. </field>
  829. <field>
  830. <source_field>description</source_field>
  831. </field>
  832. </fields>
  833. </transform_map>
  834. <transform_map>
  835. <name>x_ausgh_snsc_sc_category_transform_map</name>
  836. <source_table>x_ausgh_snsc_sc_category_ist</source_table>
  837. <target_table>sc_category</target_table>
  838. <copy_empty_fields>true</copy_empty_fields>
  839. <active>true</active>
  840. <run_business_rules>false</run_business_rules>
  841. <fields>
  842. <field>
  843. <source_field>title</source_field>
  844. <coalesce>true</coalesce>
  845. </field>
  846. <field>
  847. <source_field>homepage_renderer</source_field>
  848. </field>
  849. <field>
  850. <source_field>active</source_field>
  851. </field>
  852. <field>
  853. <source_field>description</source_field>
  854. </field>
  855. <field>
  856. <source_field>parent</source_field>
  857. <coalesce>true</coalesce>
  858. <reference_value_field>sys_id</reference_value_field>
  859. <copy_empty_fields>true</copy_empty_fields>
  860. <choice_action>reject</choice_action>
  861. </field>
  862. <field>
  863. <source_field>sc_catalog</source_field>
  864. </field>
  865. </fields>
  866. </transform_map>
  867. <transform_map>
  868. <name>x_ausgh_snsc_sc_cat_item_transform_map</name>
  869. <source_table>x_ausgh_snsc_sc_cat_item_ist</source_table>
  870. <target_table>sc_cat_item</target_table>
  871. <active>true</active>
  872. <run_business_rules>false</run_business_rules>
  873. <copy_empty_fields>true</copy_empty_fields>
  874. <fields>
  875. <field>
  876. <source_field>name</source_field>
  877. <coalesce>true</coalesce>
  878. </field>
  879. <field>
  880. <source_field>category</source_field>
  881. <coalesce>true</coalesce>
  882. <choice_action>reject</choice_action>
  883. <reference_value_field>sys_id</reference_value_field>
  884. </field>
  885. <field>
  886. <source_field>active</source_field>
  887. </field>
  888. <field>
  889. <source_field>short_description</source_field>
  890. </field>
  891. <field>
  892. <source_field>description</source_field>
  893. </field>
  894. <field>
  895. <source_field>custom_cart</source_field>
  896. <reference_value_field>sys_id</reference_value_field>
  897. <choice_action>reject</choice_action>
  898. </field>
  899. <field>
  900. <source_field>use_sc_layout</source_field>
  901. </field>
  902. <field>
  903. <source_field>no_quantity</source_field>
  904. </field>
  905. </fields>
  906. </transform_map>
  907. <transform_map>
  908. <name>x_ausgh_snsc_item_option_new_set_transform_map</name>
  909. <source_table>x_ausgh_snsc_item_option_new_set_ist</source_table>
  910. <target_table>item_option_new_set</target_table>
  911. <active>true</active>
  912. <run_business_rules>false</run_business_rules>
  913. <copy_empty_fields>true</copy_empty_fields>
  914. <fields>
  915. <field>
  916. <source_field>name</source_field>
  917. <coalesce>true</coalesce>
  918. </field>
  919. <field>
  920. <source_field>description</source_field>
  921. </field>
  922. <field>
  923. <source_field>title</source_field>
  924. </field>
  925. <field>
  926. <source_field>sys_name</source_field>
  927. </field>
  928. </fields>
  929. </transform_map>
  930. <transform_map>
  931. <name>x_ausgh_snsc_io_set_item_transform_map</name>
  932. <source_table>x_ausgh_snsc_io_set_item_ist</source_table>
  933. <target_table>io_set_item</target_table>
  934. <active>true</active>
  935. <run_business_rules>false</run_business_rules>
  936. <copy_empty_fields>true</copy_empty_fields>
  937. <fields>
  938. <field>
  939. <source_field>sc_cat_item</source_field>
  940. <coalesce>true</coalesce>
  941. <reference_value_field>sys_id</reference_value_field>
  942. <choice_action>reject</choice_action>
  943. </field>
  944. <field>
  945. <source_field>variable_set</source_field>
  946. <coalesce>true</coalesce>
  947. <reference_value_field>sys_id</reference_value_field>
  948. <choice_action>reject</choice_action>
  949. </field>
  950. </fields>
  951. </transform_map>
  952. <transform_map>
  953. <name>x_ausgh_snsc_sara_definition_transform_map</name>
  954. <source_table>x_ausgh_snsc_sara_definition_ist</source_table>
  955. <target_table>x_ausgh_snsc_sara_definition</target_table>
  956. <active>true</active>
  957. <run_business_rules>false</run_business_rules>
  958. <copy_empty_fields>true</copy_empty_fields>
  959. <fields>
  960. <field>
  961. <source_field>u_name</source_field>
  962. <coalesce>true</coalesce>
  963. </field>
  964. <field>
  965. <source_field>u_consume_url</source_field>
  966. </field>
  967. <field>
  968. <source_field>u_sc_item</source_field>
  969. </field>
  970. <field>
  971. <source_field>u_service_catalog_category</source_field>
  972. <reference_value_field>sys_id</reference_value_field>
  973. <choice_action>reject</choice_action>
  974. </field>
  975. <field>
  976. <source_field>u_var_set</source_field>
  977. <reference_value_field>sys_id</reference_value_field>
  978. <choice_action>reject</choice_action>
  979. </field>
  980. <field>
  981. <source_field>u_parent</source_field>
  982. <coalesce>true</coalesce>
  983. <reference_value_field>sys_id</reference_value_field>
  984. <choice_action>ignore</choice_action>
  985. </field>
  986. <field>
  987. <source_field>u_type</source_field>
  988. </field>
  989. <field>
  990. <source_field>u_hash</source_field>
  991. </field>
  992. </fields>
  993. </transform_map>
  994. <transform_map>
  995. <name>x_ausgh_snsc_sara_variable_transform_map</name>
  996. <source_table>x_ausgh_snsc_sara_variable_ist</source_table>
  997. <target_table>x_ausgh_snsc_sara_variable</target_table>
  998. <active>true</active>
  999. <run_business_rules>false</run_business_rules>
  1000. <copy_empty_fields>true</copy_empty_fields>
  1001. <fields>
  1002. <field>
  1003. <source_field>u_name</source_field>
  1004. <coalesce>true</coalesce>
  1005. </field>
  1006. <field>
  1007. <source_field>u_readonly</source_field>
  1008. </field>
  1009. <field>
  1010. <source_field>u_is_password</source_field>
  1011. </field>
  1012. <field>
  1013. <source_field>u_is_lookup</source_field>
  1014. </field>
  1015. <field>
  1016. <source_field>u_hash</source_field>
  1017. </field>
  1018. <field>
  1019. <source_field>variable_set</source_field>
  1020. <reference_value_field>name</reference_value_field>
  1021. <choice_action>reject</choice_action>
  1022. </field>
  1023. <field>
  1024. <source_field>type</source_field>
  1025. </field>
  1026. <field>
  1027. <source_field>macro</source_field>
  1028. </field>
  1029. <field>
  1030. <source_field>name</source_field>
  1031. </field>
  1032. <field>
  1033. <source_field>cat_item</source_field>
  1034. <reference_value_field>sys_id</reference_value_field>
  1035. <choice_action>reject</choice_action>
  1036. </field>
  1037. <field>
  1038. <source_field>help_text</source_field>
  1039. </field>
  1040. <field>
  1041. <source_field>show_help</source_field>
  1042. </field>
  1043. <field>
  1044. <source_field>include_none</source_field>
  1045. </field>
  1046. <field>
  1047. <source_field>default_value</source_field>
  1048. </field>
  1049. <field>
  1050. <source_field>question_text</source_field>
  1051. </field>
  1052. <field>
  1053. <source_field>mandatory</source_field>
  1054. </field>
  1055. <field>
  1056. <source_field>list_table</source_field>
  1057. </field>
  1058. <field>
  1059. <source_field>attributes</source_field>
  1060. </field>
  1061. <field>
  1062. <source_field>lookup_table</source_field>
  1063. </field>
  1064. <field>
  1065. <source_field>lookup_value</source_field>
  1066. </field>
  1067. <field>
  1068. <source_field>reference_qual</source_field>
  1069. </field>
  1070. </fields>
  1071. </transform_map>
  1072. <transform_map>
  1073. <name>x_ausgh_snsc_sara_lookup_transform_map</name>
  1074. <source_table>x_ausgh_snsc_sara_lookup_ist</source_table>
  1075. <target_table>x_ausgh_snsc_sara_lookup</target_table>
  1076. <active>true</active>
  1077. <run_business_rules>false</run_business_rules>
  1078. <copy_empty_fields>true</copy_empty_fields>
  1079. <fields>
  1080. <field>
  1081. <source_field>u_key</source_field>
  1082. <coalesce>true</coalesce>
  1083. </field>
  1084. <field>
  1085. <source_field>u_display_name</source_field>
  1086. </field>
  1087. <field>
  1088. <source_field>u_control_id</source_field>
  1089. <coalesce>true</coalesce>
  1090. <reference_value_field>sys_id</reference_value_field>
  1091. <choice_action>ignore</choice_action>
  1092. </field>
  1093. </fields>
  1094. </transform_map>
  1095. </transform_maps>
  1096.  
  1097.  
  1098. <script_includes>
  1099. <script_include>
  1100. <name>SaraCatalogGenerator</name>
  1101. <script><![CDATA[/**
  1102. * Service Catalog Generator to import service definition to Service Catalog
  1103. */
  1104. var SaraCatalogGenerator = Class.create();
  1105. SaraCatalogGenerator.prototype = {
  1106. initialize: function () {
  1107. this.glideHelper = new SaraGlideHelper();
  1108. this.LOGGER = new SaraLog(this);
  1109. },
  1110.  
  1111. /**
  1112. * Save catalog item
  1113. * @param {SaraModel.CatalogItem} catalogItem The catalog item object
  1114. */
  1115. saveItem: function (catalogItem) {
  1116. var LOGGER = this.LOGGER;
  1117.  
  1118. LOGGER.info('Saving catalog item (name = "{0}", service name = {1}) in "{2}" table', catalogItem.getName(), catalogItem.getServiceName(), SaraCommon.TABLE_NAME.SARA_DEFINITION);
  1119.  
  1120. var glideHelper = this.glideHelper;
  1121.  
  1122. // Workflow sys_id of catalogItem if has
  1123. var workflowSysId;
  1124. if (catalogItem.getWorkflow()) {
  1125. workflowSysId = glideHelper.getSysId(SaraCommon.TABLE_NAME.SN_WORKFLOW, {
  1126. 'name': catalogItem.getWorkflow()
  1127. });
  1128. } else {
  1129. LOGGER.error('There is no Workflow for consuming catalog item. Saving catalog item is aborted!');
  1130.  
  1131. return;
  1132. }
  1133.  
  1134. // Custom cart sys_id of catalogItem if has
  1135. var customCartSysId;
  1136. if (catalogItem.getCustomCart()) {
  1137. customCartSysId = glideHelper.getSysId(SaraCommon.TABLE_NAME.SN_UI_MACRO, {
  1138. 'name': catalogItem.getCustomCart()
  1139. });
  1140. }
  1141.  
  1142. var catalogItemId = glideHelper.persistData(SaraCommon.TABLE_NAME.SN_CATALOG_ITEM, {
  1143. 'name': catalogItem.getName(),
  1144. 'category': catalogItem.getCategory(),
  1145. 'active': catalogItem.isActive(),
  1146. 'short_description': catalogItem.getShortDesc(),
  1147. 'description': catalogItem.getDescription(),
  1148. 'workflow': workflowSysId,
  1149. 'custom_cart': customCartSysId,
  1150. 'use_sc_layout': false,
  1151. 'no_quantity': true
  1152. });
  1153.  
  1154. var varSetId = this.saveVariableSet(catalogItem, catalogItemId);
  1155.  
  1156. // Add new row to SaraCommon.TABLE_NAME.SARA_DEFINITION table, holding additional info. about this services like consume URL, links
  1157. // and reference to the variable set that contains Sara fields
  1158. var catItemId = glideHelper.persistData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  1159. 'u_sc_item': catalogItemId,
  1160. 'u_name': catalogItem.getServiceName(),
  1161. 'u_consume_url': catalogItem.getConsumeUrl(),
  1162. 'u_var_set': varSetId,
  1163. 'u_parent': catalogItem.getCategory(),
  1164. 'u_type': 'service',
  1165. 'u_hash': catalogItem.getHash(),
  1166. 'u_is_deleted': false
  1167. });
  1168.  
  1169. LOGGER.info('Saved catalog item (name = "{0}", service name = {1}, sys_id = {2}) in "{3}" table', catalogItem.getName(), catalogItem.getServiceName(), catItemId, SaraCommon.TABLE_NAME.SARA_DEFINITION);
  1170. },
  1171.  
  1172. /**
  1173. * Create Sara Client Scripts with type is Macro and using UI Macro name SaraCommon.CONTROL_NAME.CLIENT_SCRIPTS. This control help us to
  1174. * include all SNSC client scripts
  1175. * @param {String} varSetId The sys_id of variable set
  1176. */
  1177. createSaraClientScripts: function (varSetId) {
  1178. var glideHelper = this.glideHelper;
  1179. var LOGGER = this.LOGGER;
  1180.  
  1181. var macroSaraClientScripts = glideHelper.getData(SaraCommon.TABLE_NAME.SN_UI_MACRO, {
  1182. 'name': SaraCommon.CONTROL_NAME.CLIENT_SCRIPTS
  1183. });
  1184.  
  1185. if (macroSaraClientScripts) {
  1186. var sysId = glideHelper.persistData(SaraCommon.TABLE_NAME.SARA_VARIABLE, {
  1187. 'name': SaraCommon.CONTROL_NAME.CLIENT_SCRIPTS,
  1188. 'type': SaraCommon.VAR_TYPE.MACRO,
  1189. 'u_is_lookup': false,
  1190. 'macro': macroSaraClientScripts['sys_id'],
  1191. 'variable_set': varSetId
  1192. });
  1193.  
  1194. LOGGER.info('Created client scripts (sys_id = {0}) for variable set (sys_id = {1})', sysId, varSetId);
  1195. } else {
  1196. LOGGER.info('There\' no UI Macro named "{0}". Creating Sara client scripts skipped!', SaraCommon.CONTROL_NAME.CLIENT_SCRIPTS);
  1197. }
  1198. },
  1199.  
  1200. /**
  1201. * Create Sara Hidden Variable with type is Macro and using UI Macro name SaraCommon.CONTROL_NAME.HIDDEN_CONTROL. This control help us
  1202. * to run x_ausgh_snsc.SaraVarSet.onLoad() method without creating Catalog Client Script for VariableSet
  1203. * @param {String} varSetId The sys_id of variable set
  1204. */
  1205. createSaraHiddenVariable: function (varSetId) {
  1206. var glideHelper = this.glideHelper;
  1207. var LOGGER = this.LOGGER;
  1208.  
  1209. var macroSaraHiddenControl = glideHelper.getData(SaraCommon.TABLE_NAME.SN_UI_MACRO, {
  1210. 'name': SaraCommon.CONTROL_NAME.HIDDEN_CONTROL
  1211. });
  1212.  
  1213. if (macroSaraHiddenControl) {
  1214. var sysId = glideHelper.persistData(SaraCommon.TABLE_NAME.SARA_VARIABLE, {
  1215. 'name': SaraCommon.CONTROL_NAME.HIDDEN_CONTROL,
  1216. 'type': SaraCommon.VAR_TYPE.MACRO,
  1217. 'u_is_lookup': false,
  1218. 'macro': macroSaraHiddenControl['sys_id'],
  1219. 'variable_set': varSetId
  1220. });
  1221.  
  1222. LOGGER.info('Created hidden variable (sys_id = {0}) for variable set (sys_id = {1})', sysId, varSetId);
  1223. } else {
  1224. LOGGER.info('There\' no UI Macro named "{0}". Creating Sara hidden control skipped!', SaraCommon.CONTROL_NAME.HIDDEN_CONTROL);
  1225. }
  1226. },
  1227.  
  1228. /**
  1229. * Save variable
  1230. * @param {SaraModel.CatalogVariable} variable
  1231. * @param {String} catalogItemId
  1232. * @param {String} varSetId
  1233. * @param {Object} optionals
  1234. * @return {String} sys_id of saved variable
  1235. */
  1236. saveVariable: function (variable, catalogItemId, varSetId, optionals) {
  1237. var glideHelper = this.glideHelper;
  1238. var LOGGER = this.LOGGER;
  1239.  
  1240. LOGGER.info('Saving variable (name = {0}, type = {1}, isLookup = {2})...', variable.getName(), variable.getType(), variable.isLookup());
  1241.  
  1242. var variableData = {
  1243. 'name': variable.getName(),
  1244. 'type': variable.getType(),
  1245. 'u_is_lookup': variable.isLookup(),
  1246. 'u_hash': variable.getHash()
  1247. };
  1248.  
  1249. if (catalogItemId) {
  1250. variableData['cat_item'] = catalogItemId;
  1251. } else if (varSetId) {
  1252. variableData['variable_set'] = varSetId;
  1253. }
  1254.  
  1255. if (variable.getDescription()) {
  1256. variableData['help_text'] = variable.getDescription();
  1257. variableData['show_help'] = true;
  1258. }
  1259.  
  1260. // Include '-- None --' option if type is 'LOOKUP_SELECT_BOX' and there's no defaultValue
  1261. if (variable.getType() === SaraCommon.VAR_TYPE.LOOKUP_SELECT_BOX && (!variable.getDefaultValue() || !variable.getDefaultValue()[0])) {
  1262. variableData['include_none'] = true;
  1263. }
  1264.  
  1265. // Add default value if have and default value is not array
  1266. if (variable.getDefaultValue() && variable.getDefaultValue().length === 1 && variable.getType() !== SaraCommon.VAR_TYPE.LIST_COLLECTOR) {
  1267. variableData['default_value'] = variable.getDefaultValue()[0];
  1268. }
  1269.  
  1270. variableData['question_text'] = variable.getLabel();
  1271. variableData['mandatory'] = variable.isRequired();
  1272.  
  1273. if (optionals) {
  1274. for (prop in optionals) {
  1275. variableData[prop] = optionals[prop];
  1276. }
  1277. }
  1278.  
  1279. // Additional fields for Sara
  1280. variableData['u_name'] = variable.getActualName();
  1281. variableData['u_is_password'] = variable.isPassword();
  1282.  
  1283. // get 'catalog' user role
  1284. var catalogRoleId = glideHelper.getSysId(SaraCommon.TABLE_NAME.SN_ROLE, {
  1285. 'name': 'catalog'
  1286. });
  1287.  
  1288. LOGGER.debug('Variable information: {0}', SaraJSON.stringify(variableData));
  1289.  
  1290. // Save variable to SaraCommon.TABLE_NAME.SARA_VARIABLE table
  1291. var variableId = glideHelper.persistData(SaraCommon.TABLE_NAME.SARA_VARIABLE, variableData);
  1292.  
  1293. // Process variable range for all lookup controls
  1294. if (variable.isLookup()) {
  1295. LOGGER.info('Saving lookup table for lookup control (sys_id = {0})...', variableId);
  1296.  
  1297. // Default value for list collector is list of value id in range table
  1298. var defaultValueForListCollector = [];
  1299.  
  1300. // Update data for lookup controls
  1301. var updateData = {};
  1302.  
  1303. var ranges = variable.getRange();
  1304. if (ranges) {
  1305. // Insert values to lookup table
  1306. for (var i = 0, rangeValue; rangeValue = variable.range[i]; i++) {
  1307. var rangeId = glideHelper.persistData(SaraCommon.TABLE_NAME.SARA_LOOKUP, {
  1308. 'u_key': rangeValue.Value,
  1309. 'u_display_name': rangeValue.Key,
  1310. 'u_control_id': variableId
  1311. });
  1312.  
  1313. if (SaraUtils.inArray(variable.defaultValue, rangeValue.Key)) {
  1314. defaultValueForListCollector.push(rangeId);
  1315. }
  1316. }
  1317.  
  1318. LOGGER.info('Insert {0} values to table "{1}" finished successfully.', ranges.length, SaraCommon.TABLE_NAME.SARA_LOOKUP);
  1319. } else {
  1320. LOGGER.info('Lookup values of {0} is null', variable.getName());
  1321. }
  1322.  
  1323. if (variable.getType() === SaraCommon.VAR_TYPE.LIST_COLLECTOR) {
  1324. updateData['list_table'] = SaraCommon.TABLE_NAME.SARA_LOOKUP;
  1325. updateData['default_value'] = defaultValueForListCollector.join(',');
  1326. updateData['attributes'] = 'no_filter=true';
  1327. } else {
  1328. updateData['lookup_table'] = SaraCommon.TABLE_NAME.SARA_LOOKUP;
  1329. updateData['lookup_value'] = 'u_display_name';
  1330. updateData['reference_qual'] = 'u_control_id=' + variableId;
  1331. }
  1332.  
  1333. LOGGER.debug('Variable updated information: {0}', SaraJSON.stringify(updateData));
  1334.  
  1335. glideHelper.updateData(SaraCommon.TABLE_NAME.SARA_VARIABLE, {
  1336. 'sys_id': variableId
  1337. }, updateData);
  1338. LOGGER.info('Saved lookup table for lookup control (sys_id = {0})', variableId);
  1339. }
  1340.  
  1341. LOGGER.info('Saved variable (name = {0}, type = {1}, isLookup = {2})', variable.getName(), variable.getType(), variable.isLookup());
  1342.  
  1343. return variableId;
  1344. },
  1345.  
  1346. /**
  1347. * Delete variable
  1348. * @param {String} variableId The sys_id of variable
  1349. */
  1350. deleteVariable: function (variableId) {
  1351. var glideHelper = this.glideHelper;
  1352. var LOGGER = this.LOGGER;
  1353.  
  1354. LOGGER.debug('Deleting lookup value of variable (sys_id = {0})...', variableId);
  1355. glideHelper.deleteData(SaraCommon.TABLE_NAME.SARA_LOOKUP, {
  1356. 'u_control_id': variableId
  1357. }, true);
  1358. LOGGER.debug('Deleted lookup value of variable (sys_id = {0})', variableId);
  1359.  
  1360. LOGGER.debug('Deleting variable (sys_id = {0})...', variableId);
  1361. glideHelper.deleteData(SaraCommon.TABLE_NAME.SARA_VARIABLE, {
  1362. 'sys_id': variableId
  1363. }, true);
  1364. LOGGER.debug('Deleted variable (sys_id = {0})', variableId);
  1365. },
  1366.  
  1367. /**
  1368. * Delete all variables of a variable set
  1369. * @param {String} varSetId The sys_id of variable set
  1370. */
  1371. deleteVariables: function (varSetId) {
  1372. var glideHelper = this.glideHelper;
  1373. var LOGGER = this.LOGGER;
  1374.  
  1375. var saraVariables = glideHelper.getData(SaraCommon.TABLE_NAME.SARA_VARIABLE, {
  1376. 'variable_set': varSetId
  1377. }, true);
  1378. LOGGER.info('Found {0} variable(s) of variable set (sys_id = {1})', saraVariables.length, varSetId);
  1379.  
  1380. LOGGER.info('Starting delete all vairables and their lookup value...');
  1381. for (var i = 0, saraVariable; saraVariable = saraVariables[i]; i++) {
  1382. this.deleteVariable(saraVariable['sys_id']);
  1383. }
  1384. LOGGER.info('Ended delete all vairables and their lookup value');
  1385. },
  1386.  
  1387. /**
  1388. * Create catalog category
  1389. * @param {SaraModel.CatalogCategory} catalogCategory
  1390. * @return {String} Category ID from table SaraCommon.TABLE_NAME.SN_CATEGORY
  1391. */
  1392. saveCategory: function (catalogCategory) {
  1393. var glideHelper = this.glideHelper;
  1394. var LOGGER = this.LOGGER;
  1395.  
  1396. // Assign default homepage renderer
  1397. var defaultRendererSysId = glideHelper.getSysId(SaraCommon.TABLE_NAME.SN_HOMEPAGE_RENDERER, {
  1398. 'Name': 'Category Items'
  1399. });
  1400.  
  1401. // Create catalog category without specified 'parent' because of 'PreventSubcategoryCatalogChange' business rule of Eureka
  1402. LOGGER.info('Creating Catalog category {0} (sys_id = {1})...', catalogCategory.getName(), catalogCatId);
  1403. var catalogCatId = glideHelper.persistData(SaraCommon.TABLE_NAME.SN_CATEGORY, {
  1404. 'title': catalogCategory.getTitle(),
  1405. 'homepage_renderer': defaultRendererSysId,
  1406. 'active': catalogCategory.isActive(),
  1407. 'description': catalogCategory.getDescription()
  1408. });
  1409. LOGGER.info('Created Catalog category {0} (sys_id = {1})', catalogCategory.getName(), catalogCatId);
  1410.  
  1411. // Update 'parent' for catalog category after creating successfully
  1412. glideHelper.updateData(SaraCommon.TABLE_NAME.SN_CATEGORY, {
  1413. 'sys_id': catalogCatId
  1414. }, {
  1415. 'parent': catalogCategory.getParent()
  1416. }, true);
  1417.  
  1418. // Add new row to SaraCommon.TABLE_NAME.SARA_DEFINITION table, holding additional info. about this category
  1419. LOGGER.info('Saving Catalog category {0} (sys_id = {1}) into "{2}" table...', catalogCategory.getName(), catalogCatId, SaraCommon.TABLE_NAME.SARA_DEFINITION);
  1420. glideHelper.persistData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  1421. 'u_service_catalog_category': catalogCatId,
  1422. 'u_name': catalogCategory.getName(),
  1423. 'u_consume_url': catalogCategory.getConsumeUrl() || '',
  1424. 'u_parent': catalogCategory.getParent(),
  1425. 'u_type': 'catalog'
  1426. });
  1427. LOGGER.info('Saved Catalog category {0} (sys_id = {1}) into "{2}" table', catalogCategory.getName(), catalogCatId, SaraCommon.TABLE_NAME.SARA_DEFINITION);
  1428.  
  1429. return catalogCatId;
  1430. },
  1431.  
  1432. /**
  1433. * Create default target category named 'SaraCommon.DEFAULT_CATEGORY'
  1434. * @param {String} catalogCatId The catalog category sys_id
  1435. * @return {String} sysId
  1436. */
  1437. createDefaultTargetCategory: function (catalogCateId) {
  1438. var glideHelper = this.glideHelper;
  1439. var LOGGER = this.LOGGER;
  1440. var defaultCategoryName = SaraCommon.DEFAULT_CATEGORY;
  1441.  
  1442. LOGGER.info('Saving category (name = {0})', defaultCategoryName);
  1443. var entity = {
  1444. 'title': defaultCategoryName,
  1445. 'active': true,
  1446. 'description': defaultCategoryName,
  1447. }
  1448.  
  1449. if (catalogCateId) {
  1450. entity['sc_catalog'] = catalogCateId;
  1451. }
  1452.  
  1453. var sysId = glideHelper.persistData(SaraCommon.TABLE_NAME.SN_CATEGORY, entity);
  1454. LOGGER.info('Saved category (name = {0})!', defaultCategoryName);
  1455.  
  1456. return sysId;
  1457. },
  1458.  
  1459. /**
  1460. * Save target category id into SaraCommon.TABLE_NAME.SARA_DEFINITION table
  1461. * @param {String} targetCateId
  1462. */
  1463. saveTargetCategory: function (targetCateId) {
  1464. var glideHelper = this.glideHelper;
  1465. var LOGGER = this.LOGGER;
  1466.  
  1467. var targetCategory = glideHelper.getData(SaraCommon.TABLE_NAME.SN_CATEGORY, {
  1468. 'sys_id': targetCateId
  1469. });
  1470.  
  1471. var sysIdImportedCategory = glideHelper.getSysId(SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  1472. 'u_parent': targetCateId,
  1473. 'u_type': 'category'
  1474. });
  1475.  
  1476. if (sysIdImportedCategory) {
  1477. LOGGER.info('Services have been imported in target category (name = {0})!', targetCategory['title']);
  1478. } else {
  1479. sysIdImportedCategory = glideHelper.persistData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  1480. 'u_name': targetCategory['title'],
  1481. 'u_parent': targetCategory['sys_id'],
  1482. 'u_type': 'category'
  1483. });
  1484.  
  1485. LOGGER.info('Saved target category (name = {0}, sys_id = {1}) into "{2}" table', targetCategory['title'], sysIdImportedCategory, SaraCommon.TABLE_NAME.SARA_DEFINITION);
  1486. }
  1487. },
  1488.  
  1489. /**
  1490. * Update catalog category
  1491. * @param {SaraModel.CatalogCategory} catalog
  1492. */
  1493. updateCategory: function (catalogCategory) {
  1494. if (!catalogCategory.getSysId()) {
  1495. return;
  1496. }
  1497.  
  1498. var glideHelper = this.glideHelper;
  1499. var LOGGER = this.LOGGER;
  1500.  
  1501. LOGGER.info('Updating catalog category (title = {0}, description = {1})...', catalogCategory['title'], catalogCategory['description']);
  1502. glideHelper.updateData(SaraCommon.TABLE_NAME.SN_CATEGORY, {
  1503. 'sys_id': catalogCategory.getSysId()
  1504. }, {
  1505. 'title': catalogCategory.getTitle(),
  1506. 'description': catalogCategory.getDescription()
  1507. });
  1508. LOGGER.info('Updated catalog category (title = {0}, description = {1})', catalogCategory['title'], catalogCategory['description']);
  1509. },
  1510.  
  1511. /**
  1512. * Save variable set for catalog item
  1513. * @param {SaraModel.CatalogItem} catalogItem The catalog item object
  1514. * @param {String} catalogId The sys_id of catalog item in db
  1515. * @return {String} The sys_id of variable set
  1516. */
  1517. saveVariableSet: function (catalogItem, catalogId) {
  1518. var glideHelper = this.glideHelper;
  1519. var LOGGER = this.LOGGER;
  1520. var varSetId = null;
  1521.  
  1522. // Process catalog variables
  1523. if (catalogItem.variables.length > 0) {
  1524. var varSetName = SaraUtils.formatString('VarSet_{0}_{1}', SaraUtils.getTimeStamp(), SaraUtils.getRandom());
  1525.  
  1526. // Create a variable set containing all variables and save variable set to SaraCommon.TABLE_NAME.SN_VARIABLE_SET table
  1527. LOGGER.info('Saving variable set (name = {0})...', varSetName);
  1528. varSetId = glideHelper.persistData(SaraCommon.TABLE_NAME.SN_VARIABLE_SET, {
  1529. 'name': varSetName,
  1530. 'description': SaraUtils.formatString('Variable Set containing all variables belong to "{0}" ({1}) catalog item', catalogItem.getName(), catalogItem.getServiceName()),
  1531. 'title': SaraUtils.formatString('{0} Variable Set', catalogItem.getName()),
  1532. 'display_title': true
  1533. });
  1534. LOGGER.info('Saved variable set (name = {0})', varSetName);
  1535.  
  1536. // Create relation between variable set and catalog item by adding a record to SaraCommon.TABLE_NAME.SN_VARIABLE_SET_ITEM table
  1537. LOGGER.info('Creating relation between variable set (name = {0}, sys_id = {1}) and catalog item (sys_id = {2})...', varSetName, varSetId, catalogId);
  1538. glideHelper.persistData(SaraCommon.TABLE_NAME.SN_VARIABLE_SET_ITEM, {
  1539. 'sc_cat_item': catalogId,
  1540. 'variable_set': varSetId
  1541. });
  1542. LOGGER.info('Created relation between variable set (name = {0}, sys_id = {1}) and catalog item (sys_id = {2})', varSetName, varSetId, catalogId);
  1543.  
  1544. // Creating Sara client scripts
  1545. this.createSaraClientScripts(varSetId);
  1546.  
  1547. // Creating Sara hidden variable
  1548. this.createSaraHiddenVariable(varSetId);
  1549.  
  1550. // process each variable in the set
  1551. LOGGER.info('Importing {0} variables for variable set named "{1}"...', catalogItem.variables.length, varSetName);
  1552. for (var i = 0, variable; variable = catalogItem.variables[i]; i++) {
  1553. this.saveVariable(variable, null, varSetId, {
  1554. 'order': (i * 100)
  1555. });
  1556. }
  1557. LOGGER.info('Imported {0} variables for variable set (name = {1}, sys_id = {2})', catalogItem.variables.length, varSetName, varSetId);
  1558. } else {
  1559. LOGGER.warn('There\' no variable found in catalog item (name = {0}). Skip syncLookup!', catalogItem.getName());
  1560. }
  1561.  
  1562. return varSetId;
  1563. },
  1564.  
  1565. /**
  1566. * Delete variable set for catalog item
  1567. * @param {Object} saraItem The current catalog item in db
  1568. * @param {SaraModel.CatalogItem} catalogItem The catalog item object
  1569. */
  1570. deleteVariableSet: function (saraItem, catalogItem) {
  1571. var glideHelper = this.glideHelper;
  1572. var LOGGER = this.LOGGER;
  1573.  
  1574. LOGGER.info('Getting all variable set of catalog item (name = {0}, sys_id = {1})...', catalogItem.getServiceName(), saraItem['u_sc_item']);
  1575. var setItems = glideHelper.getData(SaraCommon.TABLE_NAME.SN_VARIABLE_SET_ITEM, {
  1576. 'sc_cat_item': saraItem['u_sc_item']
  1577. }, true);
  1578. LOGGER.info('Got {0} variable set(s) of catalog item (name = {1}, sys_id = {2})', setItems.length, catalogItem.getServiceName(), saraItem['u_sc_item']);
  1579.  
  1580. for (var i = 0, setItem; setItem = setItems[i]; i++) {
  1581. this.deleteVariables(setItem['variable_set']);
  1582.  
  1583. LOGGER.info('Deleting variable set (sys_id = {0}) of catalog item (name = {1}, sys_id = {2})...', setItem['variable_set'], catalogItem.getServiceName(), saraItem['u_sc_item']);
  1584. glideHelper.deleteData(SaraCommon.TABLE_NAME.SN_VARIABLE_SET, {
  1585. 'sys_id': setItem['variable_set']
  1586. });
  1587. LOGGER.info('Deleted variable set (sys_id = {0}) of catalog item (name = {1}, sys_id = {2})', setItem['variable_set'], catalogItem.getServiceName(), saraItem['u_sc_item']);
  1588. }
  1589.  
  1590. // Delete relation between all variable sets and catalog item by adding a record to SaraCommon.TABLE_NAME.SN_VARIABLE_SET_ITEM table
  1591. LOGGER.info('Deleting relation between catalog item (name = {0}, sys_id = {1}) with all variable sets...', catalogItem.getServiceName(), saraItem['u_sc_item']);
  1592. glideHelper.deleteData(SaraCommon.TABLE_NAME.SN_VARIABLE_SET_ITEM, {
  1593. 'sc_cat_item': saraItem['u_sc_item']
  1594. }, true);
  1595. LOGGER.info('Deleted relation between catalog item (name = {0}, sys_id = {1}) with all variable sets', catalogItem.getServiceName(), saraItem['u_sc_item']);
  1596. },
  1597.  
  1598. /**
  1599. * Update catalog item
  1600. * @param {Object} saraItem The current catalog item in db
  1601. * @param {SaraModel.CatalogItem} catalogItem The catalog item object
  1602. */
  1603. updateItem: function (saraItem, catalogItem) {
  1604. var glideHelper = this.glideHelper;
  1605. var LOGGER = this.LOGGER;
  1606.  
  1607. LOGGER.info('Updating catalog item (name = "{0}", sys_id = {1})...', catalogItem.getServiceName(), saraItem['u_sc_item']);
  1608.  
  1609. this.deleteVariableSet(saraItem, catalogItem);
  1610. var varSetId = this.saveVariableSet(catalogItem, saraItem['u_sc_item']);
  1611.  
  1612. LOGGER.info('Saving new variable set (sys_id = {0}) and hash ({1}) for catalog item in "{2}" table...', saraItem['sys_id'], catalogItem.getHash(), SaraCommon.TABLE_NAME.SARA_DEFINITION);
  1613. glideHelper.updateData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  1614. 'sys_id': saraItem['sys_id']
  1615. }, {
  1616. 'u_var_set': varSetId,
  1617. 'u_hash': catalogItem.getHash()
  1618. });
  1619. LOGGER.info('Saved new variable set (sys_id = {0}) and hash ({1}) for catalog item in "{2}" table', saraItem['sys_id'], catalogItem.getHash(), SaraCommon.TABLE_NAME.SARA_DEFINITION);
  1620.  
  1621. LOGGER.info('Updated catalog item (name = "{0}", sys_id = {1})', catalogItem.getServiceName(), saraItem['u_sc_item']);
  1622. },
  1623.  
  1624. /**
  1625. * Set active status of item in SaraCommon.TABLE_NAME.SN_CATALOG_ITEM table
  1626. * @param {Object} saraItem The catalog item which will be set active status
  1627. * @param {Boolean} isActive The catalog item is active or not
  1628. */
  1629. setItemActive: function (saraItem, isActive) {
  1630. var glideHelper = this.glideHelper;
  1631. var LOGGER = this.LOGGER;
  1632.  
  1633. // Deactive item in SaraCommon.TABLE_NAME.SN_CATALOG_ITEM table
  1634. LOGGER.info('Setting active status of catalog item (sys_id = {0}) is "{1}" in table "{2}"...', saraItem['u_sc_item'], isActive, SaraCommon.TABLE_NAME.SN_CATALOG_ITEM);
  1635. glideHelper.updateData(SaraCommon.TABLE_NAME.SN_CATALOG_ITEM, {
  1636. 'sys_id': saraItem['u_sc_item']
  1637. }, {
  1638. 'active': isActive
  1639. });
  1640. LOGGER.info('Set active status of catalog item (sys_id = {0}) is "{1}" in table "{2}"', saraItem['u_sc_item'], isActive, SaraCommon.TABLE_NAME.SN_CATALOG_ITEM);
  1641. },
  1642.  
  1643. /**
  1644. * Deactivate item and also remove its information out of SaraCommon.TABLE_NAME.SARA_DEFINITION
  1645. * @param {Object} saraItem The catalog item which will be deactivated and marked as deleted
  1646. * @param {Object} saraCatalog The old catalog data from SaraCommon.TABLE_NAME.SARA_DEFINITION table
  1647. */
  1648. deleteItem: function (saraItem, saraCatalog) {
  1649. var glideHelper = this.glideHelper;
  1650. var LOGGER = this.LOGGER;
  1651.  
  1652. this.setItemActive(saraItem, false);
  1653. LOGGER.info('Deactivated catalog item (sys_id = {0}) in table "{1}"', saraItem['u_sc_item'], SaraCommon.TABLE_NAME.SN_CATALOG_ITEM);
  1654.  
  1655. // Mark catalog item as deleted in SaraCommon.TABLE_NAME.SN_CATALOG_ITEM table
  1656. LOGGER.info('Marking catalog item as deleted (sys_id = {0}) in table "{1}"', saraItem['u_sc_item'], SaraCommon.TABLE_NAME.SN_CATALOG_ITEM);
  1657. glideHelper.updateData(SaraCommon.TABLE_NAME.SN_CATALOG_ITEM, {
  1658. 'sys_id': saraItem['u_sc_item']
  1659. }, {
  1660. 'meta': 'deleted'
  1661. });
  1662. LOGGER.info('Marked catalog item as deleted (sys_id = {0}) in table "{1}"', saraItem['u_sc_item'], SaraCommon.TABLE_NAME.SN_CATALOG_ITEM);
  1663.  
  1664. // Remove item's information in SaraCommon.TABLE_NAME.SARA_DEFINITION table
  1665. LOGGER.info('Deleting catalog item (name = {0}, parent sys_id = {1}) in table "{2}"', saraItem['u_name'], saraItem['u_parent'], SaraCommon.TABLE_NAME.SARA_DEFINITION);
  1666. glideHelper.deleteData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  1667. 'u_name': saraItem['u_name'],
  1668. 'u_parent': saraItem['u_parent'],
  1669. 'u_type': 'service'
  1670. }, true);
  1671. LOGGER.info('Deleted catalog item (name = {0}, parent sys_id = {1}) successfully', saraItem['u_name'], saraCatalog['sys_id']);
  1672. },
  1673.  
  1674. /**
  1675. * Deactivate category and also remove its information out of SaraCommon.TABLE_NAME.SARA_DEFINITION
  1676. * @param {Object} saraCatalog The old catalog data from SaraCommon.TABLE_NAME.SARA_DEFINITION table
  1677. */
  1678. deactivateCategory: function (saraCatalog) {
  1679. var glideHelper = this.glideHelper;
  1680. var LOGGER = this.LOGGER;
  1681.  
  1682. // Deactive items which have parent is this category
  1683. var items = glideHelper.getData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  1684. 'u_parent': saraCatalog['u_service_catalog_category'],
  1685. 'u_type': 'service'
  1686. }, true);
  1687.  
  1688. for (var i = 0, saraItem; saraItem = items[i]; i++) {
  1689. this.deleteItem(saraItem, saraCatalog);
  1690. }
  1691.  
  1692. // Deactive category in 'SaraCommon.TABLE_NAME.SN_CATEGORY' table
  1693. LOGGER.info('Deactivating category (sys_id = {0}) in table "{1}"...', saraCatalog['u_service_catalog_category'], SaraCommon.TABLE_NAME.SN_CATEGORY);
  1694. glideHelper.updateData(SaraCommon.TABLE_NAME.SN_CATEGORY, {
  1695. 'sys_id': saraCatalog['u_service_catalog_category']
  1696. }, {
  1697. 'active': false
  1698. })
  1699. LOGGER.info('Deactivated category (sys_id = {0}) in table "{1}"', saraCatalog['u_service_catalog_category'], SaraCommon.TABLE_NAME.SN_CATEGORY);;
  1700.  
  1701. // Remove category's information in SaraCommon.TABLE_NAME.SARA_DEFINITION table
  1702. LOGGER.info('Deleting category (name = {0}, parent sys_id = {1}) in table "{2}"...', saraCatalog['u_name'], saraCatalog['u_parent'], SaraCommon.TABLE_NAME.SARA_DEFINITION);
  1703. glideHelper.deleteData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  1704. 'u_name': saraCatalog['u_name'],
  1705. 'u_parent': saraCatalog['u_parent'],
  1706. 'u_type': 'catalog'
  1707. }, true);
  1708. LOGGER.info('Deleted category (name = {0}, parent sys_id = {1}) in table "{2}"', saraCatalog['u_name'], saraCatalog['u_parent'], SaraCommon.TABLE_NAME.SARA_DEFINITION);
  1709. },
  1710.  
  1711. /**
  1712. * Creates a new catalog
  1713. */
  1714. createCatalog: function (title, description, active) {
  1715. return this.glideHelper.persistData(SaraCommon.TABLE_NAME.SN_CATALOG, {
  1716. 'title': title,
  1717. 'description': description,
  1718. 'active': active
  1719. });
  1720. },
  1721.  
  1722. type: 'SaraCatalogGenerator'
  1723. };
  1724. ]]></script>
  1725. <description>Service Catalog Generator to import service definition to Service Catalog</description>
  1726. <active>true</active>
  1727. <client_callable>false</client_callable>
  1728. <access>package_private</access>
  1729. </script_include>
  1730.  
  1731. <script_include>
  1732. <name>SaraCommon</name>
  1733. <script><![CDATA[/**
  1734. * This class is comprised of global parameters in SARA connector. It shouldn't be instantiated
  1735. * and fields will be accessed in static-like fashion (think Java), eg.: SaraCommon.username
  1736. */
  1737. var SaraCommon = Class.create();
  1738. SaraCommon.prototype = {
  1739. initialize: function () {},
  1740.  
  1741. type: 'SaraCommon'
  1742. };
  1743.  
  1744. SaraCommon.PROP_PREFIX = 'x_ausgh_snsc';
  1745. SaraCommon.OAUTH_IMPORT_SUCCESS = 0;
  1746. SaraCommon.OAUTH_AUTHENTICATION_FAILED = 1;
  1747. SaraCommon.OAUTH_INVALID_TOKEN = 2;
  1748. SaraCommon.OAUTH_TOKEN_EXPIRED = 3;
  1749.  
  1750. SaraCommon.DEFAULT_CATEGORY = 'Automic Services';
  1751. SaraCommon.CATALOGS_LIMIT = 1000;
  1752. SaraCommon.SERVICES_LIMIT = 10;
  1753.  
  1754. SaraCommon.WORKFLOW_STATUS_CODE = {
  1755. ENDED_OK: 1900
  1756. };
  1757.  
  1758. SaraCommon.CUSTOM_CART_NAME = '';
  1759.  
  1760. SaraCommon.VAR_TYPE = {
  1761. YES_NO: 1,
  1762. MULTI_LINE_TEXT: 2,
  1763. MULTI_CHOICE: 3,
  1764. NUM_SCALE: 4,
  1765. SELECT_BOX: 5,
  1766. SINGLE_LINE_TEXT: 6,
  1767. CHECK_BOX: 7,
  1768. REFERENCE: 8,
  1769. DATE: 9,
  1770. DATE_TIME: 10,
  1771. LABEL: 11,
  1772. BREAK: 12,
  1773. MACRO: 14,
  1774. UI_PAGE: 15,
  1775. WIDE_SINGLE_LINE_TEXT: 16,
  1776. MACRO_WITH_LABEL: 17,
  1777. LOOKUP_SELECT_BOX: 18,
  1778. CONTAINER_START: 19,
  1779. CONTAINER_END: 20,
  1780. LIST_COLLECTOR: 21,
  1781. LOOKUP_MULTI_CHOICE: 22,
  1782. HTML: 23
  1783. };
  1784.  
  1785. SaraCommon.CONTROL_NAME = {
  1786. CLIENT_SCRIPTS: 'sara_client_scripts',
  1787. HIDDEN_CONTROL: 'sara_hidden_control'
  1788. };
  1789.  
  1790. SaraCommon.SCOPED_APP = 'x_ausgh_snsc';
  1791.  
  1792. SaraCommon.SYSTEM_PROPERTY_NAME = {
  1793. MID_SERVER: 'mid_server',
  1794. REST_REQUEST_TIMEOUT: 'rest_request_timeout',
  1795. SERVICE_ACTIVE: 'service_active',
  1796. WORKFLOW_TIMEOUT: 'workflow_timeout',
  1797. WORKFLOW_DELAY: 'workflow_delay'
  1798. };
  1799.  
  1800. SaraCommon.CONFIG_NAME = {
  1801. CLIENT_ID: 'client_id',
  1802. CLIENT_SECRET: 'client_secret',
  1803. TECHNICAL_USER: 'technical_user',
  1804. SAPI_ENDPOINT: 'sapi_endpoint',
  1805. TOKEN_ENDPOINT: 'token_endpoint',
  1806. AUTH_ENDPOINT: 'auth_endpoint'
  1807. };
  1808.  
  1809. SaraCommon.REST_NAME = {
  1810. SAPI: 'Sara - SAPI Services',
  1811. OAUTH: 'Sara - OAuth Services'
  1812. };
  1813.  
  1814. // List of properties will be kept when syncing services
  1815. SaraCommon.KEEP_SERIVCE_PROPERTIES = [];
  1816.  
  1817. SaraCommon.TABLE_NAME = {
  1818. SARA_CONFIG: 'x_ausgh_snsc_sara_config',
  1819. SARA_DEFINITION: 'x_ausgh_snsc_sara_definition',
  1820. SARA_INSTALL_LOG: 'u_snsc_install_log',
  1821. SARA_LOOKUP: 'x_ausgh_snsc_sara_lookup',
  1822. SARA_OAUTH: 'x_ausgh_snsc_sara_oauth',
  1823. SARA_VARIABLE: 'x_ausgh_snsc_sara_variable',
  1824. SN_APPLICATION: 'sys_app',
  1825. SN_APPLICATION_CATEGORY: 'sys_app_category',
  1826. SN_APPLICATION_FILE: 'sys_app_file',
  1827. SN_APPLICATION_MENU: 'sys_app_application',
  1828. SN_APPLICATION_MODULE: 'sys_app_module',
  1829. SN_AUTO_SCRIPT: 'sysauto_script',
  1830. SN_CATALOG: 'sc_catalog',
  1831. SN_CATALOG_ITEM: 'sc_cat_item',
  1832. SN_CATALOG_ITEM_WIZARD: 'sc_cat_item_wizard',
  1833. SN_CATALOG_SCRIPT_CLIENT: 'catalog_script_client',
  1834. SN_CATEGORY: 'sc_category',
  1835. SN_DB_OBJECT: 'sys_db_object',
  1836. SN_DICTIONARY: 'sys_dictionary',
  1837. SN_DOCUMENTATION: 'sys_documentation',
  1838. SN_ECC_QUEUE: 'ecc_queue',
  1839. SN_FIX_SCRIPT: 'sys_script_fix',
  1840. SN_HOMEPAGE_RENDERER: 'sc_homepage_renderer',
  1841. SN_JOURNAL_FIELD: 'sys_journal_field',
  1842. SN_METADATA: 'sys_metadata',
  1843. SN_PROCESSOR: 'sys_processor',
  1844. SN_PROPERTIES: 'sys_properties',
  1845. SN_PROPERTIES_CATEGORY: 'sys_properties_category',
  1846. SN_PROPERTIES_CATEGORY_RELATIONSHIP: 'sys_properties_category_m2m',
  1847. SN_REST_MESSAGE: 'sys_rest_message',
  1848. SN_REST_MESSAGE_FN: 'sys_rest_message_fn',
  1849. SN_REST_MESSAGE_FN_HEADERS: 'sys_rest_message_fn_headers',
  1850. SN_REST_MESSAGE_HEADERS: 'sys_rest_message_headers',
  1851. SN_ROLE: 'sys_user_role',
  1852. SN_SECURITY_ACL: 'sys_security_acl',
  1853. SN_SECURITY_ACL_ROLE: 'sys_security_acl_role',
  1854. SN_SCRIPT_INCLUDES: 'sys_script_include',
  1855. SN_UI_MACRO: 'sys_ui_macro',
  1856. SN_UI_PAGE: 'sys_ui_page',
  1857. SN_UI_SCRIPT: 'sys_ui_script',
  1858. SN_USER: 'sys_user',
  1859. SN_USER_GROUP: 'sys_user_group',
  1860. SN_VARIABLE: 'item_option_new',
  1861. SN_VARIABLE_SET: 'item_option_new_set',
  1862. SN_VARIABLE_SET_ITEM: 'io_set_item',
  1863. SN_VARIABLE_VALUE: 'sys_variable_value',
  1864. SN_WIZARD: 'expert',
  1865. SN_WIZARD_CLIENT_SCRIPT: 'expert_script_client',
  1866. SN_WIZARD_PANEL: 'expert_panel',
  1867. SN_WIZARD_PANEL_TRANSITION: 'expert_panel_transition',
  1868. SN_WIZARD_PANEL_VARIABLE: 'expert_panel_variable',
  1869. SN_WIZARD_VARIABLE: 'expert_variable',
  1870. SN_WORKFLOW: 'wf_workflow',
  1871. SN_WORKFLOW_ACTIVITY: 'wf_activity',
  1872. SN_WORKFLOW_ACTIVITY_DEFINITION: 'wf_activity_definition',
  1873. SN_WORKFLOW_ACTIVITY_VARIABLE: 'wf_activity_variable',
  1874. SN_WORKFLOW_CONDITION: 'wf_condition',
  1875. SN_WORKFLOW_STAGE: 'wf_stage',
  1876. SN_WORKFLOW_TRANSITION: 'wf_transition',
  1877. SN_WORKFLOW_VERSION: 'wf_workflow_version',
  1878. SN_TRANSFORM_MAP: 'sys_transform_map'
  1879. };
  1880.  
  1881. SaraCommon.AUDIT = {
  1882. APPROVAL_HISTORY: 'SNSC_SN_APPROVAL_HISTORY',
  1883. APPROVAL_TIMESTAMP: 'SNSC_SN_APPROVAL_TIMESTAMP',
  1884. ORDER_ID : 'SNSC_SN_ORDER_ID',
  1885. ORDER_NAME: 'SNSC_SN_ORDER_NAME',
  1886. ORDER_TIMESTAMP: 'SNSC_SN_ORDER_TIMESTAMP'
  1887. };
  1888. ]]></script>
  1889. <description>This class is comprised of global parameters in SARA connector. It shouldn't be instantiated and fields will be accessed in static-like fashion (think Java), eg.: SaraCommon.username</description>
  1890. <active>true</active>
  1891. <client_callable>false</client_callable>
  1892. <access>public</access>
  1893. </script_include>
  1894.  
  1895. <script_include>
  1896. <name>SaraConfig</name>
  1897. <script><![CDATA[/**
  1898. * Helper class provides convenient methods to work with SNSC configuration table
  1899. */
  1900. var SaraConfig = Class.create();
  1901. SaraConfig.prototype = {
  1902. initialize: function () {
  1903. this.glideHelper = new SaraGlideHelper();
  1904.  
  1905. this.DEFAULT_CONFIG_VALUES = {};
  1906. this.DEFAULT_CONFIG_VALUES[SaraCommon.CONFIG_NAME.CLIENT_ID] = 'AESYSTEMNAME/1/SERVICE_NOW';
  1907. this.DEFAULT_CONFIG_VALUES[SaraCommon.CONFIG_NAME.CLIENT_SECRET] = 'AES_12345';
  1908. this.DEFAULT_CONFIG_VALUES[SaraCommon.CONFIG_NAME.TECHNICAL_USER] = 'TECHNICAL_USER';
  1909. this.DEFAULT_CONFIG_VALUES[SaraCommon.CONFIG_NAME.SAPI_ENDPOINT] = 'https://mysapihost/';
  1910. this.DEFAULT_CONFIG_VALUES[SaraCommon.CONFIG_NAME.TOKEN_ENDPOINT] = 'https://oauthhost/oauth2/token';
  1911. this.DEFAULT_CONFIG_VALUES[SaraCommon.CONFIG_NAME.AUTH_ENDPOINT] = 'https://oauthhost/oauth2/auth';
  1912. },
  1913.  
  1914. /**
  1915. * Store SARA OAuth client configuration to System Properties
  1916. * @param {object} config The configuration of OAuth Client
  1917. * - @key {String} SaraCommon.CONFIG_NAME.CLIENT_ID Identity of OAuth client
  1918. * - @key {String} SaraCommon.CONFIG_NAME.CLIENT_SECRET OAuth client secret string
  1919. * - @key {String} SaraCommon.CONFIG_NAME.TECHNICAL_USER Technical user
  1920. * - @key {String} SaraCommon.CONFIG_NAME.SAPI_ENDPOINT URL to SAPI root endpoint
  1921. * - @key {String} SaraCommon.CONFIG_NAME.TOKEN_ENDPOINT Endpoint for token requesting/refreshing
  1922. * - @key {String} SaraCommon.CONFIG_NAME.AUTH_ENDPOINT Authorization endpoint for OAuth authentication
  1923. */
  1924. storeClientConfig: function (config) {
  1925. // Clean the old config before storing new one
  1926. this.glideHelper.deleteData(SaraCommon.TABLE_NAME.SARA_CONFIG, {}, true);
  1927.  
  1928. var configData = {};
  1929.  
  1930. for (var key in config) {
  1931. configData['u_' + key] = config[key];
  1932. }
  1933.  
  1934. // Store new config
  1935. this.glideHelper.persistData(SaraCommon.TABLE_NAME.SARA_CONFIG, configData);
  1936. },
  1937.  
  1938. /**
  1939. * Get the object contains SARA client configuration in following order: Client ID, Client Secret, Technical User,
  1940. * SAPI Endpoint, Token Endpoint, Authorization Endpoint
  1941. * @return {Object}
  1942. */
  1943. getClientConfig: function () {
  1944. var saraConfig = this.glideHelper.getData(SaraCommon.TABLE_NAME.SARA_CONFIG, {}, true)[0];
  1945. var configData = {};
  1946.  
  1947. if (saraConfig) {
  1948. for (var key in SaraCommon.CONFIG_NAME) {
  1949. var name = SaraCommon.CONFIG_NAME[key];
  1950.  
  1951. configData[name] = saraConfig['u_' + name];
  1952. }
  1953. } else {
  1954. configData = this.DEFAULT_CONFIG_VALUES;
  1955. }
  1956.  
  1957. return configData;
  1958. },
  1959.  
  1960. /**
  1961. * Get base bath of SAPI endpoint
  1962. * @return {String}
  1963. */
  1964. getBasePath: function () {
  1965. var configData = this.getClientConfig();
  1966.  
  1967. return configData[SaraCommon.CONFIG_NAME.SAPI_ENDPOINT];
  1968. },
  1969.  
  1970. /**
  1971. * Get technical user name
  1972. * @param {String}
  1973. */
  1974. getTechnicalUser: function () {
  1975. var configData = this.getClientConfig();
  1976.  
  1977. return configData[SaraCommon.CONFIG_NAME.TECHNICAL_USER];
  1978. },
  1979.  
  1980. type: 'SaraConfig'
  1981. };
  1982. ]]></script>
  1983. <description>Helper class provides convenient methods to work with SNSC configuration table</description>
  1984. <active>true</active>
  1985. <client_callable>false</client_callable>
  1986. <access>public</access>
  1987. </script_include>
  1988.  
  1989. <script_include>
  1990. <name>SaraConsumer</name>
  1991. <script><![CDATA[/**
  1992. * Sara consumer class to discover all SAPI catalogs, services and import them into SN as the corresponding catalog categories and items
  1993. */
  1994. var SaraConsumer = Class.create();
  1995. SaraConsumer.prototype = {
  1996. initialize: function (tracker) {
  1997. if (tracker !== null && tracker !== undefined) {
  1998. this.tracker = tracker;
  1999. }
  2000.  
  2001. // initialize dependencies
  2002. var midServer = SaraUtils.getMIDServer();
  2003. this.restClient = new SaraRESTClient();
  2004. this.restClient.setMIDServer(midServer);
  2005.  
  2006. this.username = new SaraConfig().getTechnicalUser();
  2007.  
  2008. // inject restClient to the OAuth client instance
  2009. this.oauthClient = new SaraOAuthClient(this.restClient);
  2010. this.tokens = this.oauthClient.getUserTokens(this.username);
  2011.  
  2012. // inject glideHelper
  2013. this.glideHelper = new SaraGlideHelper();
  2014.  
  2015. // Inject generator
  2016. this.generator = new SaraCatalogGenerator();
  2017.  
  2018. this.LOGGER = new SaraLog(this);
  2019.  
  2020. /**
  2021. * Object store catalogs data of SAPI after discovering
  2022. * @structure:
  2023. * {
  2024. * @{catalogName}: @{SaraModel.CatalogCategory},
  2025. * ...
  2026. * }
  2027. */
  2028. this.catalogsData = {};
  2029.  
  2030. /**
  2031. * Object store services data of SAPI after discovering
  2032. * @structure:
  2033. * {
  2034. * @{catalogName}: {
  2035. * @{serviceName}: @{SaraModel.CatalogItem},
  2036. * ...
  2037. * },
  2038. * ...
  2039. * }
  2040. */
  2041. this.servicesData = {};
  2042.  
  2043. // Object store catalogs and services number after discovering
  2044. this.countData = {
  2045. catalogsCount: 0,
  2046. servicesCount: 0
  2047. };
  2048.  
  2049. this.statusCode = '';
  2050. this.errorMessage = '';
  2051. this.errorUrl = '';
  2052. },
  2053.  
  2054. getDefaultCategory: function () {
  2055. return SaraCommon.DEFAULT_CATEGORY;
  2056. },
  2057.  
  2058. /**
  2059. * Get link with limit parametter of catalog or service
  2060. * @param {String} link Origin link
  2061. * @param {String} type can be catalog or service
  2062. * @param {String}
  2063. */
  2064. getLimitLink: function (link, type) {
  2065. var limitString = 'limit=';
  2066. limitString += type === 'catalog' ? SaraCommon.CATALOGS_LIMIT : SaraCommon.SERVICES_LIMIT;
  2067.  
  2068. if (link.indexOf('?') !== -1) {
  2069. limitString = '&' + limitString;
  2070. } else {
  2071. limitString = '?' + limitString;
  2072. }
  2073.  
  2074. return link + limitString;
  2075. },
  2076.  
  2077. /**
  2078. * Private method to check user permission.
  2079. * @return {Object}
  2080. * - @key {String} error
  2081. */
  2082. checkPermission: function () {
  2083. var LOGGER = this.LOGGER;
  2084.  
  2085. if (!gs.hasRole('admin') && !gs.hasRole('groups_admin')) {
  2086. var message = 'You dont\'t have sufficient permission to do this action. Allowed roles: admin, groups_admin';
  2087.  
  2088. LOGGER.error(message);
  2089.  
  2090. return {
  2091. error: message
  2092. }
  2093. }
  2094.  
  2095. // check user tokens
  2096. if (!this.tokens) {
  2097. var message = SaraUtils.formatString('No tokens found for user {0}. Skip import!', this.username);
  2098.  
  2099. LOGGER.error(message);
  2100.  
  2101. return {
  2102. error: message
  2103. }
  2104. }
  2105.  
  2106. LOGGER.info('Tokens found for user {0}', this.username);
  2107.  
  2108. if (!this.tokens[3]) {
  2109. this.tokens[3] = 'bearer';
  2110. }
  2111.  
  2112. return {
  2113. error: false
  2114. }
  2115. },
  2116.  
  2117. /**
  2118. * Make request to SAPI and check the response data
  2119. * @param {String} url
  2120. * @param {Boolean} returnJSONData2
  2121. * @return {Object}
  2122. * - @key {Boolean} error
  2123. * - @key {Object} response
  2124. * - @key {Object} jsonData
  2125. */
  2126. makeSAPIRequest: function (url, returnJSONData2) {
  2127. var LOGGER = this.LOGGER;
  2128.  
  2129. // Make request
  2130. this.tokens = this.oauthClient.getUserTokens(this.username);
  2131. var requestUrl = SaraUtils.buildUrl(url);
  2132. var request = this.restClient.newSAPIRequest('get', requestUrl);
  2133. request.addHeader('Authorization', this.tokens[3] + ' ' + this.tokens[0]);
  2134.  
  2135. // Get response
  2136. var response = this.restClient.executeWithRefreshToken(request);
  2137. var responseObject = response.getResponseObject();
  2138.  
  2139. if (response.haveError()) {
  2140. this.statusCode = responseObject.statusCode;
  2141. this.errorMessage = responseObject.errorMessage;
  2142. this.errorUrl = url;
  2143.  
  2144. return {
  2145. error: true,
  2146. response: response
  2147. };
  2148. }
  2149.  
  2150. var result = {
  2151. error: false,
  2152. response: response,
  2153. jsonData: responseObject.bodyObject
  2154. }
  2155.  
  2156. if (returnJSONData2) {
  2157. var jsonData2 = response.getBodyObject();
  2158. result.jsonData2 = jsonData2;
  2159. }
  2160.  
  2161. return result;
  2162. },
  2163.  
  2164. /**
  2165. * Increment specific percent more for tracker if have
  2166. * @param {Number} percent
  2167. */
  2168. incrementPercent: function (percent) {
  2169. if (this.tracker !== null) {
  2170. this.tracker.incrementPercentComplete(+percent);
  2171. }
  2172. },
  2173.  
  2174. /**
  2175. * Log message for tracker can show what is happening inside of SaraConsumer when importing services.
  2176. * You can format message like SaraUtils.formatString method
  2177. */
  2178. logMessage: function () {
  2179. var LOGGER = this.LOGGER;
  2180.  
  2181. if (this.tracker !== null) {
  2182. var message = SaraUtils.formatString.apply(this, arguments);
  2183.  
  2184. try {
  2185. this.tracker.updateResult({
  2186. msg: message
  2187. });
  2188. } catch (e) {
  2189. LOGGER.error('Error when logging message for tracker: {0}', e);
  2190. }
  2191. }
  2192. },
  2193.  
  2194. /**
  2195. * Discover root url of SAPI
  2196. * @return {Object}
  2197. * - @key {Boolean} error
  2198. * - @key {Object} response
  2199. * - @key {Object} jsonData
  2200. */
  2201. discoverRoot: function () {
  2202. var LOGGER = this.LOGGER;
  2203.  
  2204. LOGGER.info('Starting discoverRoot...');
  2205.  
  2206. // Make request
  2207. var response = this.makeSAPIRequest('/');
  2208.  
  2209. if (response.error) {
  2210. LOGGER.error(response.error);
  2211. LOGGER.info('Ended discoverRoot!');
  2212.  
  2213. return response;
  2214. }
  2215.  
  2216. LOGGER.info('Ended discoverRoot!');
  2217. return response;
  2218. },
  2219.  
  2220. /**
  2221. * Discover catalogs url of SAPI
  2222. * @param {String} catalogsUrl
  2223. * @return {Object}
  2224. * - @key {Boolean} error
  2225. * - @key {Object} response
  2226. * - @key {Object} jsonData
  2227. */
  2228. discoverCatalogs: function (catalogsUrl) {
  2229. var LOGGER = this.LOGGER;
  2230.  
  2231. LOGGER.info('Starting discoverCatalogs...');
  2232.  
  2233. // Set limit for catalogsUrl
  2234. catalogsUrl = this.getLimitLink(catalogsUrl, 'catalog');
  2235.  
  2236. // Make request
  2237. var response = this.makeSAPIRequest(catalogsUrl);
  2238.  
  2239. if (response.error) {
  2240. LOGGER.error(response.error);
  2241. LOGGER.info('Ended discoverCatalogs!');
  2242.  
  2243. return response;
  2244. }
  2245.  
  2246. var jsonData = response.jsonData;
  2247. this.countData.catalogsCount = jsonData['count'];
  2248. LOGGER.info('Found {0} SAPI Catalogs, start discover each catalog.', jsonData['count']);
  2249. LOGGER.info('Ended discoverCatalogs!');
  2250.  
  2251. return response;
  2252. },
  2253.  
  2254. /**
  2255. * Generate hash string of catalogItem. The hash will be generated from 'form' property
  2256. * of catalogItem without 'range' property
  2257. * @param {SaraModel.CatalogItem} catalogItemData
  2258. * @return {String} hash
  2259. */
  2260. generateCatalogItemHash: function (catalogItemData) {
  2261. for (var index in catalogItemData.forms) {
  2262. var form = catalogItemData.forms[index];
  2263.  
  2264. var fields = form.fields;
  2265. for (var index2 in fields) {
  2266. delete fields[index2].range;
  2267. }
  2268. }
  2269. var serviceDataStr = SaraJSON.stringify(catalogItemData);
  2270.  
  2271. var hash = SaraUtils.md5(serviceDataStr);
  2272.  
  2273. return hash;
  2274. },
  2275.  
  2276. /**
  2277. * Get embedded services from catalogData
  2278. * @param {Object} catalogData
  2279. * @return {Array<Object>|Null}
  2280. */
  2281. getEmbeddedService: function (catalogData, index) {
  2282. if (catalogData['_embedded'] && catalogData['_embedded']['service'] && catalogData['_embedded']['service'][0]) {
  2283. if (index !== undefined) {
  2284. return catalogData['_embedded']['service'][index];
  2285. } else {
  2286. return catalogData['_embedded']['service'];
  2287. }
  2288. } else {
  2289. return null;
  2290. }
  2291. },
  2292.  
  2293. /**
  2294. * Discover services from catalog url of SAPI
  2295. * @param {String} catalogUrl
  2296. * @param {String} catalogTitle
  2297. * @param {Boolean} firstTime
  2298. * @return {Object}
  2299. * - @key {Boolean} error
  2300. * - @key {Object} response
  2301. * - @key {Object} jsonData
  2302. */
  2303. discoverServices: function (catalogUrl, catalogTitle, firstTime) {
  2304. var LOGGER = this.LOGGER;
  2305.  
  2306. var name = catalogUrl.replace(/^.*\/(.*)$/, '$1');
  2307. LOGGER.info('Found catalog "{0}" : {1}', name, catalogUrl);
  2308.  
  2309. LOGGER.info('Starting discoverServices...');
  2310. // Add 'embed=service' flag for getting information of services inside catalog
  2311. catalogUrl += '&embed=service';
  2312.  
  2313. // Make request
  2314. var response = this.makeSAPIRequest(catalogUrl, true);
  2315. if (response.error) {
  2316. LOGGER.error(response.error);
  2317. LOGGER.info('Ended discoverServices!');
  2318.  
  2319. return response;
  2320. }
  2321.  
  2322. // Handle response from SAPI
  2323. var catalogData = response.jsonData;
  2324. var catalogName = catalogData.name;
  2325.  
  2326. // This jsonData will be used for generating hash
  2327. var hashData = response.jsonData2;
  2328.  
  2329. // Do this stuff when first discover
  2330. if (firstTime) {
  2331. // Reference catalog object of SNSC
  2332. var catalogCategory = new SaraModel.CatalogCategory();
  2333. catalogCategory.setTitle(catalogTitle);
  2334. catalogCategory.setName(catalogName);
  2335. catalogCategory.setParent('');
  2336. catalogCategory.setActive(true);
  2337. catalogCategory.setDescription(catalogData.shortDescription);
  2338.  
  2339. // Push catalog object to catalogsData and countData
  2340. LOGGER.info('Push catalog object to catalogsData and countData');
  2341. this.catalogsData[catalogName] = catalogCategory;
  2342. this.servicesData[catalogName] = {};
  2343. this.countData.servicesCount += catalogData.count;
  2344. }
  2345.  
  2346. var servicesData = this.getEmbeddedService(catalogData);
  2347.  
  2348. // Handle services data in '_embedded' resource
  2349. if (servicesData) {
  2350. var servicesLink = catalogData['_links']['service'];
  2351. var SERVICE_ACTIVE = SaraUtils.getSaraProperty(SaraCommon.SYSTEM_PROPERTY_NAME.SERVICE_ACTIVE) === 'true';
  2352.  
  2353. LOGGER.info('Found {0} service(s) of {1} at "{2}"', servicesData.length, catalogName, catalogUrl);
  2354.  
  2355. for (var i = 0, service; service = servicesData[i]; i++) {
  2356. var serviceTitle = servicesLink[i]['title'] || servicesLink[i]['href'].replace(/^.*\/(.*)$/, '$1');
  2357. var isActive = SERVICE_ACTIVE && service['active'];
  2358.  
  2359. // Reference service object of SNSC
  2360. var catalogItem = new SaraModel.CatalogItem();
  2361. catalogItem.setName(serviceTitle || service.name);
  2362. catalogItem.setActive(isActive);
  2363. catalogItem.setWorkflow('Sara Service');
  2364. catalogItem.setShortDesc(service.shortDescription);
  2365. catalogItem.setDescription(SaraUtils.nl2br(service.description));
  2366. catalogItem.setServiceName(service.name);
  2367. catalogItem.setConsumeUrl(service['_links']['consume'][0]['href']);
  2368. catalogItem.setCustomCart(SaraCommon.CUSTOM_CART_NAME);
  2369.  
  2370. // Generate hash of catalogItem without 'range'
  2371. var serviceData = this.getEmbeddedService(hashData, i);
  2372. var hash = this.generateCatalogItemHash(serviceData);
  2373. catalogItem.setHash(hash);
  2374.  
  2375. // Handle variables
  2376. var variables = [];
  2377. for (var index in service.forms) {
  2378. var form = service.forms[index];
  2379.  
  2380. var fields = form.fields;
  2381. for (var index2 in fields) {
  2382. var field = fields[index2];
  2383. var variable = SaraUtils.createCatalogVariable(field);
  2384. variables.push(variable);
  2385. }
  2386. }
  2387. catalogItem.setVariables(variables);
  2388.  
  2389. // Push service object to servicesData
  2390. this.servicesData[catalogName][service.name] = catalogItem;
  2391. }
  2392. } else {
  2393. LOGGER.info('No services found in catalog (name = {0})', catalogName);
  2394. }
  2395.  
  2396. LOGGER.info('Ended discoverServices!');
  2397.  
  2398. // Check the next page
  2399. if (catalogData['_links']['next']) {
  2400. var nextUrl = catalogData['_links']['next'][0]['href'];
  2401. this.discoverServices(nextUrl, catalogTitle);
  2402. }
  2403. },
  2404.  
  2405. /**
  2406. * Discover SAPI consumer URL, create corresponding list of Catalog Category and Catalog Item
  2407. * @return {Object}
  2408. * - @key {Boolean} error
  2409. * - @key {Object} response
  2410. */
  2411. discover: function () {
  2412. var LOGGER = this.LOGGER;
  2413.  
  2414. LOGGER.info('Starting discover...');
  2415.  
  2416. // Check permission before do any discover
  2417. var checkData = this.checkPermission();
  2418. if (checkData.error) {
  2419. this.statusCode = 0;
  2420. this.errorMessage = checkData.error;
  2421. LOGGER.error(checkData.error);
  2422. LOGGER.info('Ended discover!');
  2423.  
  2424. return checkData;
  2425. }
  2426.  
  2427. // Log configuration
  2428. var configData = new SaraConfig().getClientConfig();
  2429. LOGGER.info('OAuth Configuration:\n'
  2430. + ' - Client ID = {0}, \n'
  2431. + ' - Client Secret = ***, \n'
  2432. + ' - Technical User = {1}, \n'
  2433. + ' - SAPI Endpoint = {2}, \n'
  2434. + ' - Token Endpoint = {3}, \n'
  2435. + ' - Authorization Endpoint = {4}, \n'
  2436. + ' - MID Server = {5}',
  2437. configData[SaraCommon.CONFIG_NAME.CLIENT_ID],
  2438. configData[SaraCommon.CONFIG_NAME.TECHNICAL_USER],
  2439. configData[SaraCommon.CONFIG_NAME.SAPI_ENDPOINT],
  2440. configData[SaraCommon.CONFIG_NAME.TOKEN_ENDPOINT],
  2441. configData[SaraCommon.CONFIG_NAME.AUTH_ENDPOINT],
  2442. SaraUtils.getMIDServer()
  2443. );
  2444.  
  2445. /* ================================================================================================
  2446. * Discover root
  2447. * ================================================================================================ */
  2448. this.logMessage('Discovering SAPI root...');
  2449.  
  2450. var rootData = this.discoverRoot();
  2451.  
  2452. // Set percent of progress
  2453. this.incrementPercent(5);
  2454.  
  2455. if (rootData.error) {
  2456. LOGGER.info('Ended discover!');
  2457. return rootData;
  2458. }
  2459.  
  2460. rootData = rootData.jsonData;
  2461. if (!rootData['_links'] || !rootData['_links']['catalogs'][0]) {
  2462. var message = 'No catalog consumer URL found, skip discover!';
  2463. this.errorMessage = message;
  2464. LOGGER.error(message);
  2465. LOGGER.info('Ended discover!');
  2466.  
  2467. return rootData;
  2468. }
  2469. LOGGER.info('Found SAPI Catalogs url: {0}', rootData['_links']['catalogs'][0]['href']);
  2470.  
  2471.  
  2472. /* ================================================================================================
  2473. * Discover catalogs
  2474. * ================================================================================================ */
  2475. this.logMessage('Discovering catalogs...');
  2476.  
  2477. var catalogsData = this.discoverCatalogs(rootData['_links']['catalogs'][0]['href']);
  2478.  
  2479. // Set percent of progress
  2480. this.incrementPercent(5);
  2481.  
  2482. if (catalogsData.error) {
  2483. LOGGER.info('Ended discover!');
  2484. return catalogsData;
  2485. }
  2486.  
  2487. catalogsData = catalogsData.jsonData;
  2488. if (!catalogsData['_links'] || !catalogsData['_links']['catalog'] || !catalogsData['_links']['catalog'][0]) {
  2489. var message = 'No SAPI catalog found, skip discover!';
  2490. this.errorMessage = message;
  2491. LOGGER.error(message);
  2492. LOGGER.info('Ended discover!');
  2493.  
  2494. return catalogsData;
  2495. }
  2496.  
  2497. /* ================================================================================================
  2498. * Discover services
  2499. * ================================================================================================ */
  2500. var totalCatalogs = this.countData.catalogsCount;
  2501. this.percentPerCatalog = 40 / totalCatalogs;
  2502.  
  2503. for (var i in catalogsData['_links']['catalog']) {
  2504. var catalog = catalogsData['_links']['catalog'][i];
  2505. var catalogTitle = catalog.title || catalog.href.replace(/^.*\/(.*)$/, '$1');
  2506.  
  2507. this.logMessage('Discovering services of "{0}" catalog...', catalogTitle);
  2508.  
  2509. // Set limit for catalogUrl
  2510. var catalogUrl = this.getLimitLink(catalog.href, 'services');
  2511. var servicesData = this.discoverServices(catalogUrl, catalogTitle, true);
  2512.  
  2513. // Set percent of progress
  2514. this.incrementPercent(this.percentPerCatalog);
  2515.  
  2516. if (servicesData && servicesData.error) {
  2517. LOGGER.info('Ended discover!');
  2518. return servicesData;
  2519. }
  2520. }
  2521.  
  2522. LOGGER.info('Ended discover!');
  2523. return {
  2524. error: false
  2525. };
  2526. },
  2527.  
  2528. /**
  2529. * Get sys_id of default category named 'Automic Services'
  2530. * @param {String} sys_id
  2531. */
  2532. getDefaultCategoryId: function () {
  2533. var generator = this.generator;
  2534. var glideHelper = this.glideHelper;
  2535. var LOGGER = this.LOGGER;
  2536.  
  2537. var serviceCatalogId = glideHelper.getSysId(SaraCommon.TABLE_NAME.SN_CATALOG, {
  2538. 'title': 'Service Catalog'
  2539. });
  2540.  
  2541. if (!serviceCatalogId) {
  2542. // get the first catalog
  2543. var serviceCatalogId = glideHelper.getSysId(SaraCommon.TABLE_NAME.SN_CATALOG);
  2544.  
  2545. // if there's no catalog, create a new one
  2546. if (!serviceCatalogId) {
  2547. serviceCatalogId = generator.createCatalog('Automic Service Catalog', 'Automic Service Catalog', true);
  2548. LOGGER.info('New catalog \'Automic Service Catalog\' was created');
  2549. }
  2550. }
  2551.  
  2552. var catalogName = glideHelper.getData(SaraCommon.TABLE_NAME.SN_CATALOG, {
  2553. 'sys_id': serviceCatalogId
  2554. }).title;
  2555.  
  2556. LOGGER.info('Using catalog {0}', catalogName);
  2557.  
  2558. // create Automic Service category
  2559. var sysId = glideHelper.getSysId(SaraCommon.TABLE_NAME.SN_CATEGORY, {
  2560. 'title': this.getDefaultCategory(),
  2561. 'sc_catalog': serviceCatalogId
  2562. });
  2563.  
  2564. if (!sysId) {
  2565. LOGGER.info('Category (name = {0}) doesn\'t exist', this.getDefaultCategory());
  2566. sysId = generator.createDefaultTargetCategory(serviceCatalogId);
  2567. }
  2568.  
  2569. return sysId;
  2570. },
  2571.  
  2572. /**
  2573. * Import catalog category by using 'catalogsData'
  2574. * @param {String} targetCatId Target category id
  2575. */
  2576. importCategory: function (targetCatId) {
  2577. var glideHelper = this.glideHelper;
  2578. var generator = this.generator;
  2579. var LOGGER = this.LOGGER;
  2580.  
  2581. LOGGER.info('Starting importCategory...');
  2582.  
  2583. // If there's no target category specified, all catalogs will be imported as new ones in category named 'Automic Services'
  2584. if (!targetCatId) {
  2585. LOGGER.info('There is no target category, will import catalogs into category (name = "{0}")', this.getDefaultCategory());
  2586. targetCatId = this.getDefaultCategoryId();
  2587. } else {
  2588. LOGGER.info('Target category = "{0}" ...', targetCatId);
  2589. }
  2590.  
  2591. // Save target category id into SaraCommon.TABLE_NAME.SARA_DEFINITION table
  2592. generator.saveTargetCategory(targetCatId);
  2593.  
  2594. // Get name of all catalogs in AE
  2595. var catalogNames = [];
  2596. for (var catalogName in this.catalogsData) {
  2597. catalogNames.push(catalogName);
  2598. }
  2599. LOGGER.info('Catalogs in AE: {0}', catalogNames.join(', '));
  2600.  
  2601. // Get existed catalogs in SNSC
  2602. var existedCatalogs = glideHelper.getData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  2603. 'u_parent': targetCatId,
  2604. 'u_type': 'catalog'
  2605. }, true);
  2606.  
  2607. if (existedCatalogs.length > 0) {
  2608. LOGGER.info('Detecting the existed catalog in SNSC which doesn\'t exist anymore in AE');
  2609.  
  2610. // Remove the existed catalog in SNSC which doesn't exist anymore in AE
  2611. for (var i = 0, saraCatalog; saraCatalog = existedCatalogs[i]; i++) {
  2612. if (!SaraUtils.inArray(catalogNames, saraCatalog.u_name)) {
  2613. LOGGER.info('Catalog with name = {0} doesn\'t exist anymore in AE', saraCatalog.u_name);
  2614. generator.deactivateCategory(saraCatalog);
  2615. }
  2616. }
  2617. }
  2618.  
  2619. // Set percent of progress
  2620. this.incrementPercent(5);
  2621.  
  2622. // Otherwise, check if there's same name category existing under target category
  2623. for (var catalogName in this.catalogsData) {
  2624. var catalog = this.catalogsData[catalogName];
  2625. var catalogId;
  2626. var isNew = true;
  2627.  
  2628. LOGGER.info('Catalog {0}: {1}', catalogName, SaraJSON.stringify(catalog));
  2629.  
  2630. // Check if there's same name category existing under target category
  2631. var targetCategory = glideHelper.getData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  2632. 'u_name': catalog.name,
  2633. 'u_parent': targetCatId,
  2634. 'u_type': 'catalog'
  2635. });
  2636.  
  2637. if (targetCategory) {
  2638. isNew = false;
  2639. catalogId = targetCategory.u_service_catalog_category;
  2640. }
  2641.  
  2642. catalog.setAsNew(isNew);
  2643. catalog.setParent(targetCatId);
  2644.  
  2645. if (isNew) {
  2646. catalogId = generator.saveCategory(catalog);
  2647. catalog.setSysId(catalogId);
  2648. } else {
  2649. // update category with sys_id = catalogId
  2650. catalog.setSysId(catalogId);
  2651. generator.updateCategory(catalog);
  2652. }
  2653.  
  2654. // Set percent of progress
  2655. this.incrementPercent(this.percentPerCatalog);
  2656. }
  2657.  
  2658. LOGGER.info('Refreshing target category (sys_id = {0})', targetCatId);
  2659.  
  2660. glideHelper.updateData(SaraCommon.TABLE_NAME.SN_CATEGORY, {
  2661. 'sys_id': targetCatId
  2662. }, {
  2663. 'active': false
  2664. });
  2665.  
  2666. glideHelper.updateData(SaraCommon.TABLE_NAME.SN_CATEGORY, {
  2667. 'sys_id': targetCatId
  2668. }, {
  2669. 'active': true
  2670. });
  2671.  
  2672. LOGGER.info('Ended importCategory!');
  2673. },
  2674.  
  2675. /**
  2676. * Import catalog item by using 'servicesData' property
  2677. */
  2678. importItem: function () {
  2679. var LOGGER = this.LOGGER;
  2680.  
  2681. LOGGER.info('Starting importItem...');
  2682.  
  2683. var glideHelper = this.glideHelper;
  2684.  
  2685. for (var categoryName in this.servicesData) {
  2686. var isCatalogNew = this.catalogsData[categoryName].isNew();
  2687. var catalogId = this.catalogsData[categoryName].getSysId();
  2688. var items = this.servicesData[categoryName];
  2689. var itemNames = [];
  2690.  
  2691. // Get existed catalog items in AE
  2692. for (var itemName in items) {
  2693. itemNames.push(itemName);
  2694. }
  2695. LOGGER.info('{0} catalog items under category "{1}": {2}', itemNames.length, categoryName, itemNames.join(', '));
  2696.  
  2697. // Get existed catalog items in SNSC
  2698. var existedItems = glideHelper.getData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  2699. 'u_parent': catalogId,
  2700. 'u_type': 'service'
  2701. }, true);
  2702.  
  2703. if (existedItems.length > 0) {
  2704. LOGGER.info('Detecting the existed catalog item in SNSC which doesn\'t exist anymore in AE...');
  2705.  
  2706. // Remove the existed catalog item in SNSC which doesn't exist anymore in AE
  2707. for (var i = 0, saraItem; saraItem = existedItems[i]; i++) {
  2708. if (!SaraUtils.inArray(itemNames, saraItem.u_name)) {
  2709. LOGGER.info('Catalog item (name = {0}, parent sys_id = {1}) doesn\'t exist anymore in AE', saraItem.u_name, saraItem.u_parent);
  2710. this.generator.deleteItem(saraItem);
  2711. }
  2712. }
  2713. }
  2714.  
  2715. for (var itemName in items) {
  2716. var item = items[itemName];
  2717.  
  2718. // Set catalog category sys_id for item
  2719. item.setCategory(catalogId);
  2720.  
  2721. if (isCatalogNew) {
  2722. this.generator.saveItem(item);
  2723. continue;
  2724. }
  2725.  
  2726. // Check existing item with same name and same parent category id = item.category
  2727. var saraItem = glideHelper.getData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  2728. 'u_name': item.getServiceName(),
  2729. 'u_parent': item.getCategory(),
  2730. 'u_type': 'service'
  2731. });
  2732.  
  2733. if (saraItem) {
  2734. this.generator.setItemActive(saraItem, item.isActive());
  2735.  
  2736. // Check hash of saraItem and item
  2737. LOGGER.debug('New and old hash: {0} - {1}', item.getHash(), saraItem.u_hash);
  2738.  
  2739. if (item.getHash() === saraItem.u_hash) {
  2740. LOGGER.info('Item (name = {0}) is not changed', saraItem.u_name);
  2741. new SaraSync().syncLookup(saraItem, item);
  2742. } else {
  2743. LOGGER.info('Item (name = {0}) is changed', saraItem.u_name);
  2744. this.generator.updateItem(saraItem, item);
  2745. }
  2746. } else {
  2747. // Insert new as normal
  2748. this.generator.saveItem(item);
  2749. }
  2750. }
  2751.  
  2752. // Set percent of progress
  2753. this.incrementPercent(this.percentPerCatalog);
  2754. }
  2755.  
  2756. LOGGER.info('Ended importItem!');
  2757. },
  2758.  
  2759. /**
  2760. * Import catalogs and services after discovering by using 'catalogsData' and 'servicesData'
  2761. * @param {String} targetId The id of category which services will be imported in
  2762. */
  2763. doImport: function (targetId) {
  2764. var LOGGER = this.LOGGER;
  2765.  
  2766. LOGGER.info('Starting doImport...');
  2767.  
  2768. if (this.countData.catalogsCount !== 0) {
  2769. this.logMessage('Importing {0} catalog(s)...', this.countData.catalogsCount);
  2770. this.importCategory(targetId);
  2771.  
  2772. if (this.countData.servicesCount !== 0) {
  2773. this.logMessage('Importing {0} service(s)...', this.countData.servicesCount);
  2774. this.importItem();
  2775. } else {
  2776. this.incrementPercent(25);
  2777. LOGGER.info('There are no service be imported!');
  2778. }
  2779. } else {
  2780. this.incrementPercent(50);
  2781. LOGGER.info('There are no catalog be imported!');
  2782. }
  2783.  
  2784. // Make sure that progress always is 100% when completed
  2785. this.incrementPercent(100);
  2786.  
  2787. LOGGER.info('Ended doImport!');
  2788. },
  2789.  
  2790. /**
  2791. * Discover then import the data
  2792. * @param {String} targetId The id of category which services will be imported in
  2793. * @return {String} The log message
  2794. */
  2795. discoverAndImport: function (targetId) {
  2796. var LOGGER = this.LOGGER;
  2797. var response = this.discover();
  2798. var message = '';
  2799.  
  2800. if (response.error) {
  2801. LOGGER.info('Discover data from SAPI not successfully!');
  2802. return null;
  2803. } else {
  2804. message += SaraUtils.formatString('Imported {0} catalog(s) and {1} service(s)!', this.countData.catalogsCount, this.countData.servicesCount);
  2805. this.doImport(targetId);
  2806.  
  2807. return message;
  2808. }
  2809. },
  2810.  
  2811. /**
  2812. * Refresh 'catalogsData' and 'servicesData':
  2813. * - unsetAsNew() for 'catalogsData' item
  2814. * - unsetParent() for 'catalogsData' item
  2815. * - unsetSysId() for 'catalogsData' item
  2816. * - unsetCategory() for 'servicesData' item
  2817. */
  2818. refreshImportedData: function () {
  2819. var LOGGER = this.LOGGER;
  2820.  
  2821. LOGGER.info('Starting refreshImportedData...');
  2822.  
  2823. for (var catalogName in this.catalogsData) {
  2824. var catalogData = this.catalogsData[catalogName];
  2825.  
  2826. catalogData.unsetAsNew();
  2827. catalogData.unsetParent();
  2828. catalogData.unsetSysId();
  2829. }
  2830.  
  2831. for (var catalogName in this.servicesData) {
  2832. var items = this.servicesData[catalogName];
  2833.  
  2834. for (var itemName in items) {
  2835. var item = items[itemName];
  2836.  
  2837. item.unsetCategory();
  2838. }
  2839. }
  2840. LOGGER.info('Ended refreshImportedData!');
  2841. },
  2842.  
  2843. /**
  2844. * Clean up 'catalogsData' and 'servicesData'
  2845. */
  2846. cleanData: function () {
  2847. this.catalogsData = {};
  2848. this.servicesData = {};
  2849. },
  2850.  
  2851. getCatalogsData: function () {
  2852. return this.catalogsData;
  2853. },
  2854.  
  2855. getCatalogData: function (catalogName) {
  2856. return this.catalogsData[catalogName];
  2857. },
  2858.  
  2859. getServicesData: function (catalogName) {
  2860. if (catalogName) {
  2861. return this.servicesData[catalogName];
  2862. } else {
  2863. return this.servicesData;
  2864. }
  2865. },
  2866.  
  2867. getStatusCode: function () {
  2868. return this.statusCode;
  2869. },
  2870.  
  2871. getErrorMessage: function () {
  2872. return this.errorMessage;
  2873. },
  2874.  
  2875. type: 'SaraConsumer'
  2876. };
  2877. ]]></script>
  2878. <description>SaraConsumer class to discover all SAPI catalogs, services and import them into SN as the corresponding catalog categories and items</description>
  2879. <active>true</active>
  2880. <client_callable>false</client_callable>
  2881. <access>public</access>
  2882. </script_include>
  2883.  
  2884. <script_include>
  2885. <name>SaraConsumerRunner</name>
  2886. <script><![CDATA[/**
  2887. * Runner for SaraConsumer
  2888. */
  2889. var SaraConsumerRunner = Class.create();
  2890. SaraConsumerRunner.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {
  2891. start: function () {
  2892. var LOGGER = new SaraLog(this);
  2893.  
  2894. var targetCatId = this.getParameter('sysparm_catid');
  2895.  
  2896. LOGGER.info('Starting SaraConsumerRunner for importing services into "{0}"...', targetCatId);
  2897.  
  2898. var worker = new GlideScriptedHierarchicalWorker();
  2899. worker.setProgressName('Import Services');
  2900. worker.setBackground(true);
  2901. worker.setScriptIncludeName('x_ausgh_snsc.SaraConsumerWorker');
  2902. worker.setScriptIncludeMethod('run');
  2903. worker.putMethodArg('targetCatId', targetCatId);
  2904. worker.start();
  2905.  
  2906. LOGGER.info('SaraConsumerWorker starts successfully!');
  2907.  
  2908. var progressID = worker.getProgressID();
  2909.  
  2910. LOGGER.info('ID of SaraConsumerWorker is {0}', progressID);
  2911.  
  2912. return progressID;
  2913. },
  2914.  
  2915. type: 'SaraConsumerRunner'
  2916.  
  2917. });
  2918. ]]></script>
  2919. <description>Worker for SaraConsumer</description>
  2920. <active>true</active>
  2921. <client_callable>true</client_callable>
  2922. <access>public</access>
  2923. </script_include>
  2924.  
  2925. <script_include>
  2926. <name>SaraConsumerWorker</name>
  2927. <script><![CDATA[/**
  2928. * Worker for SaraConsumer
  2929. */
  2930. var SaraConsumerWorker = Class.create();
  2931. SaraConsumerWorker.prototype = {
  2932. initialize: function () {
  2933. var LOGGER = this.LOGGER = new SaraLog(this);
  2934. var tracker = null;
  2935. try {
  2936. tracker = GlideExecutionTracker.getLastRunning();
  2937. } catch (e) {
  2938. LOGGER.error('Error when getting tracker: {0}', e);
  2939. }
  2940.  
  2941. this.tracker = tracker;
  2942. },
  2943.  
  2944. run: function (targetCatId) {
  2945. if (targetCatId) {
  2946. try {
  2947. var consumer = new SaraConsumer(this.tracker);
  2948. var result = consumer.discoverAndImport(targetCatId);
  2949.  
  2950. if (!result) {
  2951. var statusCode = consumer.getStatusCode();
  2952. var errorMessage = consumer.getErrorMessage();
  2953.  
  2954. if (statusCode != 200) {
  2955. this.updateTrackerResult('Failed to import Automic services', true);
  2956. this.tracker.fail('Got error: ' + statusCode + ' - ' + errorMessage);
  2957. } else {
  2958. this.updateTrackerResult('Got no service or catalog from server.', false);
  2959. this.tracker.success('Got no service or catalog from server.');
  2960. }
  2961. } else {
  2962. this.updateTrackerResult('Imported successfully', false, result);
  2963. this.tracker.success('Imported successfully!');
  2964. }
  2965. } catch (err) {
  2966. this.updateTrackerResult('Failed to import Automic services', true);
  2967. this.tracker.fail(err);
  2968. }
  2969. } else {
  2970. this.updateTrackerResult('Failed to import Automic services', true);
  2971. this.tracker.fail('Target category id is null!');
  2972. }
  2973. },
  2974.  
  2975. /**
  2976. * Update tracker result
  2977. * @param {String} message The message content
  2978. * @param {Boolean} error Error or not
  2979. * @param {String} info The addition information
  2980. */
  2981. updateTrackerResult: function (message, error, info) {
  2982. var LOGGER = this.LOGGER;
  2983.  
  2984. if (error) {
  2985. LOGGER.error(message);
  2986. } else {
  2987. LOGGER.info(message);
  2988. }
  2989.  
  2990. try {
  2991. this.tracker.updateResult({
  2992. msg: message,
  2993. info: info
  2994. });
  2995. } catch (ex) {
  2996. LOGGER.error('Error when updating result for tracker: {0}', ex);
  2997. }
  2998. },
  2999.  
  3000. type: 'SaraConsumerWorker'
  3001.  
  3002. };
  3003. ]]></script>
  3004. <description>Runner for SaraConsumer</description>
  3005. <active>true</active>
  3006. <client_callable>false</client_callable>
  3007. <access>public</access>
  3008. </script_include>
  3009.  
  3010. <script_include>
  3011. <name>SaraGlideHelper</name>
  3012. <script><![CDATA[/**
  3013. * Helper class provides convenient methods to work with ServiceNow data tables
  3014. */
  3015. var SaraGlideHelper = Class.create();
  3016. SaraGlideHelper.prototype = {
  3017. initialize: function () {},
  3018.  
  3019. /**
  3020. * Common data persistent operation
  3021. * @param {String} table The table name
  3022. * @param {Object} entity Object represents the row to insert
  3023. * @param {Boolean} referencing Insert with references or not
  3024. * @return {String} sys_id of inserted row
  3025. */
  3026. persistData: function (table, entity, referencing) {
  3027. var rec = this._getGlideRecord(table);
  3028. rec.initialize();
  3029.  
  3030. for (key in entity) {
  3031. var value = entity[key];
  3032.  
  3033. if (value === undefined || value === null) {
  3034. value = '';
  3035. }
  3036.  
  3037. // check if key contains 'sys_id'
  3038. var idx = key.indexOf('.sys_id');
  3039. if (idx > 0 && idx == key.length - 7) {
  3040. var propName = key.substring(0, idx);
  3041. rec[propName]['sys_id'] = value;
  3042. } else {
  3043. rec[key] = value;
  3044. }
  3045. }
  3046.  
  3047. if (referencing) {
  3048. return rec.insertWithReferences();
  3049. } else {
  3050. return rec.insert();
  3051. }
  3052. },
  3053.  
  3054. /**
  3055. * Updates record(s) in given table based on the query and entity object holds fields/values to update
  3056. * @param {String} table Target table to update
  3057. * @param {Object} queryObj Query object, property name is the field name to query, value is value to query
  3058. * @param {Object} entity Entity holds fields and values to update
  3059. * @param {Boolean} updateAll Update all matching record(s) or only the first one
  3060. * @param {Boolean} referencing Update with references or not
  3061. */
  3062. updateData: function (table, queryObj, entity, updateAll, referencing) {
  3063. var rec = this._getGlideRecord(table);
  3064. this._buildQuery(rec, queryObj);
  3065. rec.query();
  3066.  
  3067. while (rec.next()) {
  3068. for (key in entity) {
  3069. // check if key contains 'sys_id'
  3070. var idx = key.indexOf('.sys_id');
  3071. if (idx > 0 && idx == key.length - 7) {
  3072. var propName = key.substring(0, idx);
  3073. rec[propName]['sys_id'] = entity[key];
  3074. } else {
  3075. rec[key] = entity[key];
  3076. }
  3077. }
  3078.  
  3079. if (referencing) {
  3080. rec.updateWithReferences();
  3081. } else {
  3082. rec.update();
  3083. }
  3084.  
  3085. if (!updateAll) {
  3086. break;
  3087. }
  3088. }
  3089. },
  3090.  
  3091. /**
  3092. * Retrieve sys_id of a record in given table by key=value query
  3093. * @param {String} table The table name
  3094. * @param {Object} queryObj The object holds the query, property name is the field name to query, value is value to query
  3095. * @param {Boolean} getAll Get sys_id of all matching record(s) or only the first one
  3096. * @return {String|Array<String>} sys_id that found, or null if no record found
  3097. */
  3098. getSysId: function (table, queryObj, getAll) {
  3099. var rec = this._getGlideRecord(table);
  3100. this._buildQuery(rec, queryObj);
  3101. rec.query();
  3102.  
  3103. if (getAll) {
  3104. var results = [];
  3105. while (rec.next()) {
  3106. results.push('' + rec['sys_id']);
  3107. }
  3108.  
  3109. return results;
  3110. } else {
  3111. if (rec.next()) {
  3112. return '' + rec['sys_id'];
  3113. } else {
  3114. return null;
  3115. }
  3116. }
  3117. },
  3118.  
  3119. /**
  3120. * Parse GlideRecordSecure into an object with same properties but value of properties will be converted to String. The
  3121. * original properties will be store in '_origin' property
  3122. * @param {GlideRecordSecure} rec The instance of GlideRecordSecure
  3123. * @return {Object}
  3124. */
  3125. _parseRecord: function (rec) {
  3126. var obj = {
  3127. _origin: rec
  3128. };
  3129.  
  3130. for (var key in rec) {
  3131. try {
  3132. obj[key] = '' + rec[key];
  3133. } catch (e) {
  3134. obj[key] = '' + rec[key].toString();
  3135. }
  3136. }
  3137.  
  3138. return obj;
  3139. },
  3140.  
  3141. /**
  3142. * Query data from given table and query condition, return objects contain information specified in list of key
  3143. * @param {String} table The target table
  3144. * @param {Object} queryObj The object holds the query, property name is the field name to query, value is value to query
  3145. * @param {Boolean} getAll Get all matching record(s) or only the first one
  3146. * @return {Array} Array of object
  3147. */
  3148. getData: function (table, queryObj, getAll) {
  3149. var rec = this._getGlideRecord(table);
  3150. this._buildQuery(rec, queryObj);
  3151. rec.query();
  3152.  
  3153. if (getAll) {
  3154. var result = [];
  3155. while (rec.next()) {
  3156. result.push(this._parseRecord(rec));
  3157. }
  3158.  
  3159. return result;
  3160. } else {
  3161. if (rec.next()) {
  3162. return this._parseRecord(rec);
  3163. } else {
  3164. return null;
  3165. }
  3166. }
  3167. },
  3168.  
  3169. /**
  3170. * Delete record(s) from given table based on a query condition
  3171. * @param {String} table The target table
  3172. * @param {Object} queryObj The object holds the query, property name is the field name to query, value is value to query
  3173. * @param {Boolean} deleteAll Delete all matching record(s) or only the first one
  3174. */
  3175. deleteData: function (table, queryObj, deleteAll) {
  3176. var rec = this._getGlideRecord(table);
  3177. this._buildQuery(rec, queryObj);
  3178.  
  3179. if (deleteAll) {
  3180. rec.deleteMultiple();
  3181. } else {
  3182. rec.query();
  3183. if (rec.next()) {
  3184. rec.deleteRecord();
  3185. }
  3186. }
  3187. },
  3188.  
  3189. /**
  3190. * Build query for GlideRecordSecure and also support Operators
  3191. * @link http://wiki.servicenow.com/index.php?title=Using_GlideRecord_to_Query_Tables
  3192. * @param {GlideRecordSecure} rec
  3193. * @param {Object} queryObj
  3194. * - @key {String} The field name
  3195. * - @value {Array|String|Number} The field value. If array, value will be [Operator, Value]
  3196. */
  3197. _buildQuery: function (rec, queryObj) {
  3198. for (var key in queryObj) {
  3199. var value = queryObj[key];
  3200.  
  3201. if (typeof value === 'object' && value instanceof Array) {
  3202. rec.addQuery(key, value[0], value[1]);
  3203. } else {
  3204. rec.addQuery(key, value);
  3205. }
  3206. }
  3207. },
  3208.  
  3209. /**
  3210. * Get instance of GlideRecordSecure
  3211. * @param {String} table The target table
  3212. * @return {GlideRecordSecure}
  3213. */
  3214. _getGlideRecord: function (table) {
  3215. return new GlideRecordSecure(table);
  3216. },
  3217.  
  3218. type: 'SaraGlideHelper'
  3219. };
  3220. ]]></script>
  3221. <description>Helper class provides convenient methods to work with ServiceNow data tables</description>
  3222. <active>true</active>
  3223. <client_callable>false</client_callable>
  3224. <access>public</access>
  3225. </script_include>
  3226.  
  3227. <script_include>
  3228. <name>SaraJSON</name>
  3229. <script><![CDATA[/**
  3230. * Sara JSON Utilities
  3231. */
  3232. var SaraJSON = Class.create();
  3233. SaraJSON.prototype = {
  3234. initialize: function() {},
  3235.  
  3236. type: 'SaraJSON'
  3237. };
  3238.  
  3239. /*
  3240. JSON.js
  3241. 2013-05-26
  3242.  
  3243. Public Domain.
  3244.  
  3245. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  3246.  
  3247. See http://www.JSON.org/js.html
  3248.  
  3249.  
  3250. This code should be minified before deployment.
  3251. See http://javascript.crockford.com/jsmin.html
  3252.  
  3253. USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
  3254. NOT CONTROL.
  3255.  
  3256.  
  3257. This file creates a global JSON object containing two methods: stringify
  3258. and parse.
  3259.  
  3260. JSON.stringify(value, replacer, space)
  3261. value any JavaScript value, usually an object or array.
  3262.  
  3263. replacer an optional parameter that determines how object
  3264. values are stringified for objects. It can be a
  3265. function or an array of strings.
  3266.  
  3267. space an optional parameter that specifies the indentation
  3268. of nested structures. If it is omitted, the text will
  3269. be packed without extra whitespace. If it is a number,
  3270. it will specify the number of spaces to indent at each
  3271. level. If it is a string (such as '\t' or '&nbsp;'),
  3272. it contains the characters used to indent at each level.
  3273.  
  3274. This method produces a JSON text from a JavaScript value.
  3275.  
  3276. When an object value is found, if the object contains a toJSON
  3277. method, its toJSON method will be called and the result will be
  3278. stringified. A toJSON method does not serialize: it returns the
  3279. value represented by the name/value pair that should be serialized,
  3280. or undefined if nothing should be serialized. The toJSON method
  3281. will be passed the key associated with the value, and this will be
  3282. bound to the value
  3283.  
  3284. For example, this would serialize Dates as ISO strings.
  3285.  
  3286. Date.prototype.toJSON = function (key) {
  3287. function f(n) {
  3288. // Format integers to have at least two digits.
  3289. return n < 10 ? '0' + n : n;
  3290. }
  3291.  
  3292. return this.getUTCFullYear() + '-' +
  3293. f(this.getUTCMonth() + 1) + '-' +
  3294. f(this.getUTCDate()) + 'T' +
  3295. f(this.getUTCHours()) + ':' +
  3296. f(this.getUTCMinutes()) + ':' +
  3297. f(this.getUTCSeconds()) + 'Z';
  3298. };
  3299.  
  3300. You can provide an optional replacer method. It will be passed the
  3301. key and value of each member, with this bound to the containing
  3302. object. The value that is returned from your method will be
  3303. serialized. If your method returns undefined, then the member will
  3304. be excluded from the serialization.
  3305.  
  3306. If the replacer parameter is an array of strings, then it will be
  3307. used to select the members to be serialized. It filters the results
  3308. such that only members with keys listed in the replacer array are
  3309. stringified.
  3310.  
  3311. Values that do not have JSON representations, such as undefined or
  3312. functions, will not be serialized. Such values in objects will be
  3313. dropped; in arrays they will be replaced with null. You can use
  3314. a replacer function to replace those with JSON values.
  3315. JSON.stringify(undefined) returns undefined.
  3316.  
  3317. The optional space parameter produces a stringification of the
  3318. value that is filled with line breaks and indentation to make it
  3319. easier to read.
  3320.  
  3321. If the space parameter is a non-empty string, then that string will
  3322. be used for indentation. If the space parameter is a number, then
  3323. the indentation will be that many spaces.
  3324.  
  3325. Example:
  3326.  
  3327. text = JSON.stringify(['e', {pluribus: 'unum'}]);
  3328. // text is '["e",{"pluribus":"unum"}]'
  3329.  
  3330.  
  3331. text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
  3332. // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
  3333.  
  3334. text = JSON.stringify([new Date()], function (key, value) {
  3335. return this[key] instanceof Date ?
  3336. 'Date(' + this[key] + ')' : value;
  3337. });
  3338. // text is '["Date(---current time---)"]'
  3339.  
  3340.  
  3341. JSON.parse(text, reviver)
  3342. This method parses a JSON text to produce an object or array.
  3343. It can throw a SyntaxError exception.
  3344.  
  3345. The optional reviver parameter is a function that can filter and
  3346. transform the results. It receives each of the keys and values,
  3347. and its return value is used instead of the original value.
  3348. If it returns what it received, then the structure is not modified.
  3349. If it returns undefined then the member is deleted.
  3350.  
  3351. Example:
  3352.  
  3353. // Parse the text. Values that look like ISO date strings will
  3354. // be converted to Date objects.
  3355.  
  3356. myData = JSON.parse(text, function (key, value) {
  3357. var a;
  3358. if (typeof value === 'string') {
  3359. a =
  3360. /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
  3361. if (a) {
  3362. return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
  3363. +a[5], +a[6]));
  3364. }
  3365. }
  3366. return value;
  3367. });
  3368.  
  3369. myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
  3370. var d;
  3371. if (typeof value === 'string' &&
  3372. value.slice(0, 5) === 'Date(' &&
  3373. value.slice(-1) === ')') {
  3374. d = new Date(value.slice(5, -1));
  3375. if (d) {
  3376. return d;
  3377. }
  3378. }
  3379. return value;
  3380. });
  3381.  
  3382.  
  3383. This is a reference implementation. You are free to copy, modify, or
  3384. redistribute.
  3385. */
  3386.  
  3387. /*jslint evil: true, regexp: true */
  3388.  
  3389. /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
  3390. call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
  3391. getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
  3392. lastIndex, length, parse, prototype, push, replace, slice, stringify,
  3393. test, toJSON, toString, valueOf
  3394. */
  3395.  
  3396. (function(JSON) {
  3397. 'use strict';
  3398.  
  3399. function f(n) {
  3400. // Format integers to have at least two digits.
  3401. return n < 10 ? '0' + n : n;
  3402. }
  3403.  
  3404. function toJSON(value) {
  3405. if (value instanceof Date) {
  3406. return isFinite(date.valueOf()) ? date.getUTCFullYear() + '-' +
  3407. f(date.getUTCMonth() + 1) + '-' +
  3408. f(date.getUTCDate()) + 'T' +
  3409. f(date.getUTCHours()) + ':' +
  3410. f(date.getUTCMinutes()) + ':' +
  3411. f(date.getUTCSeconds()) + 'Z' : null;
  3412. } else {
  3413. switch (typeof value) {
  3414. case 'string':
  3415. case 'number':
  3416. case 'boolean':
  3417. return value.valueOf();
  3418. }
  3419. }
  3420. }
  3421.  
  3422. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  3423. escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  3424. gap,
  3425. indent,
  3426. meta = { // table of character substitutions
  3427. '\b': '\\b',
  3428. '\t': '\\t',
  3429. '\n': '\\n',
  3430. '\f': '\\f',
  3431. '\r': '\\r',
  3432. '"': '\\"',
  3433. '\\': '\\\\'
  3434. },
  3435. rep;
  3436.  
  3437.  
  3438. function quote(string) {
  3439.  
  3440. // If the string contains no control characters, no quote characters, and no
  3441. // backslash characters, then we can safely slap some quotes around it.
  3442. // Otherwise we must also replace the offending characters with safe escape
  3443. // sequences.
  3444.  
  3445. escapable.lastIndex = 0;
  3446. return escapable.test(string) ? '"' + string.replace(escapable, function(a) {
  3447. var c = meta[a];
  3448. return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  3449. }) + '"' : '"' + string + '"';
  3450. }
  3451.  
  3452.  
  3453. function str(key, holder) {
  3454.  
  3455. // Produce a string from holder[key].
  3456.  
  3457. var i, // The loop counter.
  3458. k, // The member key.
  3459. v, // The member value.
  3460. length,
  3461. mind = gap,
  3462. partial,
  3463. value = holder[key];
  3464.  
  3465. // If the value has a toJSON method, call it to obtain a replacement value.
  3466.  
  3467. if (value && typeof value === 'object' && typeof toJSON(value) === 'function') {
  3468. value = toJSON(value, key);
  3469. }
  3470.  
  3471. // If we were called with a replacer function, then call the replacer to
  3472. // obtain a replacement value.
  3473.  
  3474. if (typeof rep === 'function') {
  3475. value = rep.call(holder, key, value);
  3476. }
  3477.  
  3478. // What happens next depends on the value's type.
  3479.  
  3480. switch (typeof value) {
  3481. case 'string':
  3482. return quote(value);
  3483.  
  3484. case 'number':
  3485.  
  3486. // JSON numbers must be finite. Encode non-finite numbers as null.
  3487.  
  3488. return isFinite(value) ? String(value) : 'null';
  3489.  
  3490. case 'boolean':
  3491. case 'null':
  3492.  
  3493. // If the value is a boolean or null, convert it to a string. Note:
  3494. // typeof null does not produce 'null'. The case is included here in
  3495. // the remote chance that this gets fixed someday.
  3496.  
  3497. return String(value);
  3498.  
  3499. // If the type is 'object', we might be dealing with an object or an array or
  3500. // null.
  3501.  
  3502. case 'object':
  3503.  
  3504. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  3505. // so watch out for that case.
  3506.  
  3507. /**
  3508. * MUST to check the type of object is Array or not because if value = [''], !value always is true on Rhino
  3509. * @modifiedBy: dhm@automic.com
  3510. */
  3511. if (!value && Object.prototype.toString.apply(value) !== '[object Array]') {
  3512. return 'null';
  3513. }
  3514.  
  3515. // Make an array to hold the partial results of stringifying this object value.
  3516.  
  3517. gap += indent;
  3518. partial = [];
  3519.  
  3520. // Is the value an array?
  3521.  
  3522. if (Object.prototype.toString.apply(value) === '[object Array]') {
  3523.  
  3524. // The value is an array. Stringify every element. Use null as a placeholder
  3525. // for non-JSON values.
  3526.  
  3527. length = value.length;
  3528. for (i = 0; i < length; i += 1) {
  3529. partial[i] = str(i, value) || 'null';
  3530. }
  3531.  
  3532. // Join all of the elements together, separated with commas, and wrap them in
  3533. // brackets.
  3534.  
  3535. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
  3536. gap = mind;
  3537. return v;
  3538. }
  3539.  
  3540. // If the replacer is an array, use it to select the members to be stringified.
  3541.  
  3542. if (rep && typeof rep === 'object') {
  3543. length = rep.length;
  3544. for (i = 0; i < length; i += 1) {
  3545. if (typeof rep[i] === 'string') {
  3546. k = rep[i];
  3547. v = str(k, value);
  3548. if (v) {
  3549. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  3550. }
  3551. }
  3552. }
  3553. } else {
  3554.  
  3555. // Otherwise, iterate through all of the keys in the object.
  3556.  
  3557. for (k in value) {
  3558. if (Object.prototype.hasOwnProperty.call(value, k)) {
  3559. v = str(k, value);
  3560. if (v) {
  3561. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  3562. }
  3563. }
  3564. }
  3565. }
  3566.  
  3567. // Join all of the member texts together, separated with commas,
  3568. // and wrap them in braces.
  3569.  
  3570. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}';
  3571. gap = mind;
  3572. return v;
  3573. }
  3574. }
  3575.  
  3576. // If the JSON object does not yet have a stringify method, give it one.
  3577.  
  3578. if (typeof JSON.stringify !== 'function') {
  3579. JSON.stringify = function(value, replacer, space) {
  3580.  
  3581. // The stringify method takes a value and an optional replacer, and an optional
  3582. // space parameter, and returns a JSON text. The replacer can be a function
  3583. // that can replace values, or an array of strings that will select the keys.
  3584. // A default replacer method can be provided. Use of the space parameter can
  3585. // produce text that is more easily readable.
  3586.  
  3587. var i;
  3588. gap = '';
  3589. indent = '';
  3590.  
  3591. // If the space parameter is a number, make an indent string containing that
  3592. // many spaces.
  3593.  
  3594. if (typeof space === 'number') {
  3595. for (i = 0; i < space; i += 1) {
  3596. indent += ' ';
  3597. }
  3598.  
  3599. // If the space parameter is a string, it will be used as the indent string.
  3600.  
  3601. } else if (typeof space === 'string') {
  3602. indent = space;
  3603. }
  3604.  
  3605. // If there is a replacer, it must be a function or an array.
  3606. // Otherwise, throw an error.
  3607.  
  3608. rep = replacer;
  3609. if (replacer && typeof replacer !== 'function' &&
  3610. (typeof replacer !== 'object' ||
  3611. typeof replacer.length !== 'number')) {
  3612. throw new Error('JSON.stringify');
  3613. }
  3614.  
  3615. // Make a fake root object containing our value under the key of ''.
  3616. // Return the result of stringifying the value.
  3617.  
  3618. return str('', {
  3619. '': value
  3620. });
  3621. };
  3622. }
  3623.  
  3624. // Because with SCOPED_APP, we can't use 'eval' function as the original so we decided to use 'decode' function of
  3625. // ServiceNow's JSON class for our 'SaraJSON.parse'
  3626. if (typeof JSON.parse !== 'function') {
  3627. JSON.parse = function(text, reviver) {
  3628. return new global.JSON().decode(text, reviver);
  3629. };
  3630. }
  3631.  
  3632. })(SaraJSON);
  3633. ]]></script>
  3634. <description>Sara JSON Utilities</description>
  3635. <active>true</active>
  3636. <client_callable>false</client_callable>
  3637. <access>public</access>
  3638. </script_include>
  3639.  
  3640. <script_include>
  3641. <name>SaraLog</name>
  3642. <script><![CDATA[/**
  3643. * Log Utilities for Sara
  3644. */
  3645. var SaraLog = Class.create();
  3646. SaraLog.prototype = {
  3647. /**
  3648. * Init logger
  3649. * @param {Object|String} className The class name of object. Will be append after timestamp.
  3650. * If is not String, will get the className from 'type' property of object
  3651. */
  3652. initialize: function (className) {
  3653. this.className = typeof className === 'string' ? className : className.type;
  3654. },
  3655.  
  3656. _log: function (message) {
  3657. return SaraUtils.formatString('[{0}] [{1}] {2}', SaraUtils.getTimeStamp(), this.className, message.toString());
  3658. },
  3659.  
  3660. info: function () {
  3661. var message = SaraUtils.formatString.apply(this, arguments);
  3662. message = this._log(message);
  3663.  
  3664. gs.info(message);
  3665. },
  3666.  
  3667. debug: function () {
  3668. var message = SaraUtils.formatString.apply(this, arguments);
  3669. message = this._log(message);
  3670.  
  3671. gs.debug(message);
  3672. },
  3673.  
  3674. error: function () {
  3675. var message = SaraUtils.formatString.apply(this, arguments);
  3676. message = this._log(message);
  3677.  
  3678. gs.error(message);
  3679. },
  3680.  
  3681. warn: function () {
  3682. var message = SaraUtils.formatString.apply(this, arguments);
  3683. message = this._log(message);
  3684.  
  3685. gs.warn(message);
  3686. },
  3687.  
  3688. type: 'SaraLog'
  3689.  
  3690. };
  3691. ]]></script>
  3692. <description>Log Utilities for Sara</description>
  3693. <active>true</active>
  3694. <client_callable>false</client_callable>
  3695. <access>public</access>
  3696. </script_include>
  3697.  
  3698. <script_include>
  3699. <name>SaraModel</name>
  3700. <script><![CDATA[/**
  3701. * SARA concepts modelling in Service Now
  3702. */
  3703. var SaraModel = {}
  3704.  
  3705. /**
  3706. * CatalogItem object represents a SN service catalog item
  3707. * @constructor
  3708. */
  3709. SaraModel.CatalogItem = Class.create();
  3710. SaraModel.CatalogItem.prototype = {
  3711. initialize: function () {},
  3712.  
  3713. setName: function (name) {
  3714. this.name = name;
  3715. },
  3716.  
  3717. getName: function () {
  3718. return this.name;
  3719. },
  3720.  
  3721. setCategory: function (category) {
  3722. this.category = category;
  3723. },
  3724.  
  3725. getCategory: function () {
  3726. return this.category;
  3727. },
  3728.  
  3729. unsetCategory: function () {
  3730. delete this.category;
  3731. },
  3732.  
  3733. setActive: function (active) {
  3734. this.active = active;
  3735. },
  3736.  
  3737. isActive: function () {
  3738. return this.active;
  3739. },
  3740.  
  3741. setWorkflow: function (workflow) {
  3742. this.workflow = workflow;
  3743. },
  3744.  
  3745. getWorkflow: function () {
  3746. return this.workflow;
  3747. },
  3748.  
  3749. setShortDesc: function (shortDesc) {
  3750. this.shortDesc = shortDesc;
  3751. },
  3752.  
  3753. getShortDesc: function (shortDesc) {
  3754. return this.shortDesc;
  3755. },
  3756.  
  3757. setDescription: function (description) {
  3758. this.description = description;
  3759. },
  3760.  
  3761. getDescription: function () {
  3762. return this.description;
  3763. },
  3764.  
  3765. setVariables: function (variables) {
  3766. this.variables = variables;
  3767. },
  3768.  
  3769. getVariables: function (variables) {
  3770. return this.variables;
  3771. },
  3772.  
  3773. setConsumeUrl: function (consumeUrl) {
  3774. this.consumeUrl = consumeUrl;
  3775. },
  3776.  
  3777. getConsumeUrl: function () {
  3778. return this.consumeUrl;
  3779. },
  3780.  
  3781. setServiceName: function (serviceName) {
  3782. this.serviceName = serviceName;
  3783. },
  3784.  
  3785. getServiceName: function () {
  3786. return this.serviceName;
  3787. },
  3788.  
  3789. setCustomCart: function (customCart) {
  3790. this.customCart = customCart;
  3791. },
  3792.  
  3793. getCustomCart: function () {
  3794. return this.customCart;
  3795. },
  3796.  
  3797. setHash: function (hash) {
  3798. this.hash = hash;
  3799. },
  3800.  
  3801. getHash: function () {
  3802. return this.hash;
  3803. },
  3804.  
  3805. type: 'SaraModel.CatalogItem'
  3806. };
  3807.  
  3808. /**
  3809. * CatalogVariable object represents a SN service virable
  3810. * @constructor
  3811. */
  3812. SaraModel.CatalogVariable = Class.create();
  3813. SaraModel.CatalogVariable.prototype = {
  3814. initialize: function () {},
  3815.  
  3816. setName: function (name) {
  3817. this.name = name;
  3818. },
  3819.  
  3820. getName: function () {
  3821. return this.name;
  3822. },
  3823.  
  3824. setType: function (type) {
  3825. this.type = type;
  3826. },
  3827.  
  3828. getType: function () {
  3829. return this.type;
  3830. },
  3831.  
  3832. setLabel: function (label) {
  3833. this.label = label;
  3834. },
  3835.  
  3836. getLabel: function () {
  3837. return this.label;
  3838. },
  3839.  
  3840. setDefaultValue: function (defaultValue) {
  3841. this.defaultValue = defaultValue;
  3842. },
  3843.  
  3844. getDefaultValue: function () {
  3845. return this.defaultValue;
  3846. },
  3847.  
  3848. setDescription: function (description) {
  3849. this.description = description;
  3850. },
  3851.  
  3852. getDescription: function () {
  3853. return this.description;
  3854. },
  3855.  
  3856. setRange: function (range) {
  3857. this.range = range;
  3858. },
  3859.  
  3860. getRange: function () {
  3861. return this.range;
  3862. },
  3863.  
  3864. setActualName: function (actualName) {
  3865. this.actualName = actualName;
  3866. },
  3867.  
  3868. getActualName: function () {
  3869. return this.actualName;
  3870. },
  3871.  
  3872. setAsPassword: function (asPassword) {
  3873. this.asPassword = asPassword;
  3874. },
  3875.  
  3876. isPassword: function (isPassword) {
  3877. return this.asPassword;
  3878. },
  3879.  
  3880. setRequired: function (required) {
  3881. this.required = required;
  3882. },
  3883.  
  3884. isRequired: function (required) {
  3885. return this.required;
  3886. },
  3887.  
  3888. setMultiSelect: function (multiSelect) {
  3889. this.multiSelect = multiSelect;
  3890. },
  3891.  
  3892. isMultiSelect: function (multiSelect) {
  3893. return this.multiSelect;
  3894. },
  3895.  
  3896. setAsLookup: function (asLookup) {
  3897. this.asLookup = asLookup;
  3898. },
  3899.  
  3900. isLookup: function () {
  3901. return this.asLookup;
  3902. },
  3903.  
  3904. setHash: function (hash) {
  3905. this.hash = hash;
  3906. },
  3907.  
  3908. getHash: function () {
  3909. return this.hash;
  3910. },
  3911.  
  3912. type: 'SaraModel.CatalogVariable'
  3913. };
  3914.  
  3915. /**
  3916. * CatalogCategory object represents a SN service catalog category
  3917. * @constructor
  3918. */
  3919. SaraModel.CatalogCategory = Class.create();
  3920. SaraModel.CatalogCategory.prototype = {
  3921. initialize: function () {},
  3922.  
  3923. setTitle: function (title) {
  3924. this.title = title;
  3925. },
  3926.  
  3927. getTitle: function () {
  3928. return this.title;
  3929. },
  3930.  
  3931. setName: function (name) {
  3932. this.name = name;
  3933. },
  3934.  
  3935. getName: function () {
  3936. return this.name;
  3937. },
  3938.  
  3939. setParent: function (parent) {
  3940. this.parent = parent;
  3941. },
  3942.  
  3943. getParent: function () {
  3944. return this.parent;
  3945. },
  3946.  
  3947. unsetParent: function () {
  3948. delete this.parent;
  3949. },
  3950.  
  3951. setActive: function (active) {
  3952. this.active = active;
  3953. },
  3954.  
  3955. isActive: function () {
  3956. return this.active;
  3957. },
  3958.  
  3959. setDescription: function (description) {
  3960. this.description = description;
  3961. },
  3962.  
  3963. getDescription: function () {
  3964. return this.description;
  3965. },
  3966.  
  3967. setConsumeUrl: function (consumeUrl) {
  3968. this.consumeUrl = consumeUrl;
  3969. },
  3970.  
  3971. getConsumeUrl: function () {
  3972. return this.consumeUrl;
  3973. },
  3974.  
  3975. setAsNew: function (asNew) {
  3976. this.asNew = asNew;
  3977. },
  3978.  
  3979. isNew: function () {
  3980. return this.asNew;
  3981. },
  3982.  
  3983. unsetAsNew: function () {
  3984. delete this.asNew;
  3985. },
  3986.  
  3987. setSysId: function (sysId) {
  3988. this.sysId = sysId;
  3989. },
  3990.  
  3991. getSysId: function () {
  3992. return this.sysId;
  3993. },
  3994.  
  3995. unsetSysId: function () {
  3996. delete this.sysId;
  3997. },
  3998.  
  3999. type: 'SaraModel.CatalogCategory'
  4000. };
  4001. ]]></script>
  4002. <description>SARA concepts modelling in Service Now</description>
  4003. <active>true</active>
  4004. <client_callable>false</client_callable>
  4005. <access>package_private</access>
  4006. </script_include>
  4007.  
  4008. <script_include>
  4009. <name>SaraOAuthAjax</name>
  4010. <script><![CDATA[/**
  4011. * AJAX facade for SaraOAuthClient
  4012. */
  4013. var SaraOAuthAjax = Class.create();
  4014. SaraOAuthAjax.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {
  4015. /**
  4016. * Get OAuth URL with redirection endpoint and client id in query string
  4017. * @return {String}
  4018. */
  4019. getOAuthUrl: function () {
  4020. var LOGGER = new SaraLog(this);
  4021.  
  4022. try {
  4023. var clientId = this.getParameter('sysparm_client_id').toString();
  4024. var technicalUser = this.getParameter('sysparm_technical_user').toString();
  4025. var authEndpoint = this.getParameter('sysparm_auth_endpoint').toString();
  4026. var redirectionEndpoint = SaraUtils.getRedirectionUrl();
  4027.  
  4028. LOGGER.info('auth_endpoint={0}; redirect_uri={1}; client_id={2}; technical_user={3}', authEndpoint, redirectionEndpoint, clientId, technicalUser);
  4029.  
  4030. return authEndpoint
  4031. + '?redirect_uri=' + escape(redirectionEndpoint)
  4032. + '&client_id=' + escape(clientId)
  4033. + '&user_info=' + escape(technicalUser)
  4034. + '&user_info_editable=false'
  4035. + '&response_type=code';
  4036. } catch (e) {
  4037. this.logError(e);
  4038. }
  4039.  
  4040. return;
  4041. },
  4042.  
  4043. /**
  4044. * Request token by using Username and password
  4045. * @return {String}
  4046. */
  4047. requestToken: function () {
  4048. var LOGGER = new SaraLog(this);
  4049.  
  4050. try {
  4051. var username = this.getParameter('sysparm_username').toString();
  4052. var password = this.getParameter('sysparm_password').toString();
  4053. var technicalUser = this.getParameter('sysparm_technical_user').toString();
  4054.  
  4055. var oauthClient = new SaraOAuthClient();
  4056. var tokens = oauthClient.requestToken(username, password);
  4057.  
  4058. LOGGER.info('Token: {0}', SaraJSON.stringify(tokens));
  4059.  
  4060. if (tokens && !tokens.error && tokens['access_token']) {
  4061. oauthClient.storeUserTokens(technicalUser, tokens['access_token'], tokens['refresh_token'], tokens['expires_in'], tokens['token_type']);
  4062. return 'ok';
  4063. } else {
  4064. return tokens.error ? tokens.error : (!tokens['access_token'] ? 'Empty result' : '');
  4065. }
  4066. } catch (e) {
  4067. this.logError(e);
  4068. }
  4069.  
  4070. return;
  4071. },
  4072.  
  4073. /**
  4074. * Request token by authorization code
  4075. * @return {String}
  4076. */
  4077. requestTokenByCode: function () {
  4078. var LOGGER = new SaraLog(this);
  4079.  
  4080. try {
  4081. var code = this.getParameter('sysparm_code').toString();
  4082. var technicalUser = this.getParameter('sysparm_technical_user').toString();
  4083. LOGGER.info('Request token for user "{0}" by using code {1}', technicalUser, code);
  4084.  
  4085.  
  4086. var config = {};
  4087. config[SaraCommon.CONFIG_NAME.CLIENT_ID] = this.getParameter('sysparm_client_id').toString();
  4088. config[SaraCommon.CONFIG_NAME.CLIENT_SECERT] = this.getParameter('sysparm_client_secret').toString();
  4089. config[SaraCommon.CONFIG_NAME.TOKEN_ENDPOINT] = this.getParameter('sysparm_token_endpoint').toString();
  4090.  
  4091. var oauthClient = new SaraOAuthClient();
  4092. var tokens = oauthClient.requestTokenByCode(code, config);
  4093.  
  4094. LOGGER.info('Token info: {0}', SaraJSON.stringify(tokens));
  4095.  
  4096. if (tokens && !tokens.error && tokens['access_token']) {
  4097. oauthClient.storeUserTokens(technicalUser, tokens['access_token'], tokens['refresh_token'], tokens['expires_in'], tokens['token_type']);
  4098.  
  4099. return 'ok';
  4100. } else {
  4101. return tokens.error ? tokens.error : (!tokens['access_token'] ? 'Empty result' : '');
  4102. }
  4103. } catch (e) {
  4104. this.logError(e);
  4105. }
  4106.  
  4107. return;
  4108. },
  4109.  
  4110. /**
  4111. * Get client configuration
  4112. */
  4113. getConfig: function () {
  4114. var LOGGER = new SaraLog(this);
  4115.  
  4116. try {
  4117. var configData = new SaraConfig().getClientConfig();
  4118.  
  4119. LOGGER.info('OAuth Configuration: \n'
  4120. + ' - Client ID = {0} \n'
  4121. + ' - Client Secret = *** \n'
  4122. + ' - Technical User = {1} \n'
  4123. + ' - SAPI Endpoint = {2} \n'
  4124. + ' - Token Endpoint = {3} \n'
  4125. + ' - Auth Endpoint = {4} \n',
  4126. configData[SaraCommon.CONFIG_NAME.CLIENT_ID],
  4127. configData[SaraCommon.CONFIG_NAME.TECHNICAL_USER],
  4128. configData[SaraCommon.CONFIG_NAME.SAPI_ENDPOINT],
  4129. configData[SaraCommon.CONFIG_NAME.TOKEN_ENDPOINT],
  4130. configData[SaraCommon.CONFIG_NAME.AUTH_ENDPOINT]
  4131. );
  4132.  
  4133. var config = this.newItem('config');
  4134. for (var key in SaraCommon.CONFIG_NAME) {
  4135. var name = SaraCommon.CONFIG_NAME[key];
  4136.  
  4137. config.setAttribute(name, configData[name]);
  4138. }
  4139. } catch (e) {
  4140. this.logError(e);
  4141. }
  4142.  
  4143. return;
  4144. },
  4145.  
  4146. /**
  4147. * Validate access token key
  4148. */
  4149. validateToken: function () {
  4150. var LOGGER = new SaraLog(this);
  4151.  
  4152. try {
  4153. var technicalUser = this.getParameter('sysparm_technical_user').toString();
  4154. var glideHelper = new SaraGlideHelper();
  4155. var saraOAuth = glideHelper.getData(x_ausgh_snsc.SaraCommon.TABLE_NAME.SARA_OAUTH, {
  4156. 'u_user': technicalUser
  4157. });
  4158.  
  4159. if (saraOAuth) {
  4160. var token = saraOAuth['u_access_token'].toString();
  4161. var sapiEndpoint = this.getParameter('sysparm_sapi_endpoint').toString();
  4162. var oauthClient = new SaraOAuthClient();
  4163. var result = oauthClient.validateToken(token, sapiEndpoint);
  4164.  
  4165. LOGGER.debug('Result of validating token: {0}', result.toString());
  4166.  
  4167. if (typeof result === 'boolean') {
  4168. this.addItem('result', {
  4169. isValid: result
  4170. });
  4171. } else {
  4172. this.addItem('result', {
  4173. message: result
  4174. });
  4175. }
  4176. } else {
  4177. LOGGER.info('Technical User "{1}" does not have tokens', technicalUser);
  4178.  
  4179. this.addItem('result', {
  4180. isValid: false
  4181. });
  4182. }
  4183.  
  4184. } catch (e) {
  4185. this.logError(e);
  4186. }
  4187.  
  4188. return;
  4189. },
  4190.  
  4191. /**
  4192. * Log error
  4193. * @param {Error} error
  4194. * @param {SaraLog} LOGGER
  4195. */
  4196. logError: function (error, LOGGER) {
  4197. LOGGER.error('{0}', error);
  4198.  
  4199. this.addItem('error', {
  4200. message: error
  4201. });
  4202. },
  4203.  
  4204. /**
  4205. * Add item in response
  4206. * @param {String} itemName The name of item
  4207. * @param {Object<String, String>} attributes The object contains item's attributes
  4208. */
  4209. addItem: function (itemName, attributes) {
  4210. var item = this.newItem(itemName);
  4211.  
  4212. for (var name in attributes) {
  4213. var value = attributes[name];
  4214.  
  4215. item.setAttribute(name, value);
  4216. }
  4217. },
  4218.  
  4219. type: 'SaraOAuthAjax'
  4220. });
  4221. ]]></script>
  4222. <description>AJAX facade for SaraOAuthClient</description>
  4223. <active>true</active>
  4224. <client_callable>true</client_callable>
  4225. <access>package_private</access>
  4226. </script_include>
  4227.  
  4228. <script_include>
  4229. <name>SaraOAuthClient</name>
  4230. <script><![CDATA[/**
  4231. * This class contains all OAuth-relaled functions
  4232. */
  4233. var SaraOAuthClient = Class.create();
  4234. SaraOAuthClient.prototype = {
  4235. /**
  4236. * Init new OAuth Client from SaraRESTClient object
  4237. * @param {SaraRestCLient} restClient
  4238. */
  4239. initialize: function (restClient) {
  4240. this.glideHelper = new SaraGlideHelper();
  4241. this.saraConfig = new SaraConfig();
  4242. this.LOGGER = new SaraLog(this);
  4243.  
  4244. if (!restClient) {
  4245. this.restClient = new SaraRESTClient();
  4246. this.restClient.setMIDServer(SaraUtils.getMIDServer());
  4247. } else {
  4248. this.restClient = restClient;
  4249. }
  4250. },
  4251.  
  4252. /**
  4253. * Store user tokens into 'SaraCommon.TABLE_NAME.SARA_OAUTH' table
  4254. * @param {String} username The username which owns tokens
  4255. * @param {String} accessToken The access token of user
  4256. * @param {String} refreshToken The refresh token of user
  4257. * @param {String} tokenExpiry The expiry of token
  4258. * @param {String} tokenType The type of token
  4259. * @return {String} The sys_id of user tokens record
  4260. */
  4261. storeUserTokens: function (username, accessToken, refreshToken, tokenExpiry, tokenType) {
  4262. var LOGGER = this.LOGGER;
  4263.  
  4264. if (!username) {
  4265. LOGGER.info('Store user token: Username must not be empty!');
  4266. return;
  4267. }
  4268.  
  4269. if (!accessToken) {
  4270. LOGGER.info('Error: Access token must be non-empty!');
  4271. return;
  4272. }
  4273.  
  4274. LOGGER.info('Preparing for storing user tokens...');
  4275.  
  4276. // Request tokens of user in 'SaraCommon.TABLE_NAME.SARA_OAUTH' table
  4277. var saraOAuth = this.glideHelper.getData(SaraCommon.TABLE_NAME.SARA_OAUTH, {
  4278. 'u_user': username
  4279. });
  4280.  
  4281. // If user's tokens are existed
  4282. if (saraOAuth) {
  4283. LOGGER.info('User\'s tokens are existed. Updating tokens...');
  4284.  
  4285. this.glideHelper.updateData(SaraCommon.TABLE_NAME.SARA_OAUTH, {
  4286. 'sys_id': saraOAuth['sys_id']
  4287. }, {
  4288. 'u_access_token': accessToken,
  4289. 'u_refresh_token': refreshToken,
  4290. 'u_token_expiry': tokenExpiry,
  4291. 'u_token_type': tokenType
  4292. });
  4293.  
  4294. return saraOAuth['sys_id'];
  4295. } else {
  4296. LOGGER.info('Storing user\'s tokens...');
  4297.  
  4298. return this.glideHelper.persistData(SaraCommon.TABLE_NAME.SARA_OAUTH, {
  4299. 'u_user': username,
  4300. 'u_access_token': accessToken,
  4301. 'u_refresh_token': refreshToken,
  4302. 'u_token_expiry': tokenExpiry,
  4303. 'u_token_type': tokenType
  4304. });
  4305. }
  4306. },
  4307.  
  4308. /**
  4309. * Get user tokens by username. The result will be [accessToken, refreshToken, tokenExpiry, tokenType, { createdAt, createdBy, updateAt, updateBy }]
  4310. * @param {String} username
  4311. * @return {Array<String|Object>}
  4312. */
  4313. getUserTokens: function (username) {
  4314. var LOGGER = this.LOGGER;
  4315.  
  4316. if (!username) {
  4317. return null;
  4318. }
  4319.  
  4320. var saraOAuth = this.glideHelper.getData(SaraCommon.TABLE_NAME.SARA_OAUTH, {
  4321. 'u_user': username
  4322. });
  4323.  
  4324. if (saraOAuth) {
  4325. return [
  4326. saraOAuth['u_access_token'],
  4327. saraOAuth['u_refresh_token'],
  4328. saraOAuth['u_token_expiry'],
  4329. saraOAuth['u_token_type'], {
  4330. 'createdAt': saraOAuth['sys_created_on'],
  4331. 'createdBy': saraOAuth['sys_created_by'],
  4332. 'updatedAt': saraOAuth['sys_updated_on'],
  4333. 'updatedBy': saraOAuth['sys_updated_by']
  4334. }
  4335. ];
  4336. } else {
  4337. LOGGER.info('Tokens of "{0}" do not exist!', username);
  4338. return null;
  4339. }
  4340. },
  4341.  
  4342. /**
  4343. * Remove user tokens by username
  4344. * @param {String} username
  4345. * @return {String} The sys_id of deleted record
  4346. */
  4347. removeUserToken: function (username) {
  4348. var LOGGER = this.LOGGER;
  4349.  
  4350. if (!username) {
  4351. return null;
  4352. }
  4353.  
  4354. var saraOAuth = this.glideHelper.getData(SaraCommon.TABLE_NAME.SARA_OAUTH, {
  4355. 'u_user': username
  4356. });
  4357.  
  4358. if (saraOAuth) {
  4359. saraOAuth = this.glideHelper.deleteData(SaraCommon.TABLE_NAME.SARA_OAUTH, {
  4360. 'sys_id': saraOAuth['sys_id']
  4361. });
  4362.  
  4363. return saraOAuth['sys_id'];
  4364. } else {
  4365. LOGGER.info('No token found for user "{0}"', username);
  4366. return null;
  4367. }
  4368. },
  4369.  
  4370. /**
  4371. * Requests user tokens, the request must use client_id/client_secret to authenticate (BASICally) against SARA server,
  4372. * LDAP username/password and grant_type will be embedded in request's body
  4373. * @param {String} username
  4374. * @param {String} password
  4375. * @return {Object} Object contains access token, refresh token, token expiry and token type
  4376. */
  4377. requestToken: function (username, password) {
  4378. var LOGGER = this.LOGGER;
  4379.  
  4380. LOGGER.debug('Preparing for requesting tokens for SARA user {0}...', username);
  4381.  
  4382. var clientInfo = this.saraConfig.getClientConfig();
  4383. var clientId = clientInfo[SaraCommon.CONFIG_NAME.CLIENT_ID];
  4384. var clientSecret = clientInfo[SaraCommon.CONFIG_NAME.CLIENT_SECERT];
  4385. var tokenEndpoint = clientInfo[SaraCommon.CONFIG_NAME.TOKEN_ENDPOINT];
  4386.  
  4387. var request = this.restClient.newOAuthRequest('post', tokenEndpoint);
  4388. request.setBasicAuth(clientId, clientSecret);
  4389.  
  4390. // Add POST body, set Content-Type header
  4391. request.setContentType('application/x-www-form-urlencoded');
  4392. var formEntity = {
  4393. 'grant_type': 'password',
  4394. 'username': username,
  4395. 'password': password
  4396. };
  4397. request.setFormContent(formEntity);
  4398.  
  4399. LOGGER.info('Requesting tokens for SARA user {0}...', username);
  4400. var response = this.restClient.execute(request);
  4401. var responseObject = response.getResponseObject();
  4402.  
  4403. if (response.haveError()) {
  4404. LOGGER.info('Failed to request token for user {0}', username);
  4405.  
  4406. return {
  4407. 'error': responseObject.errorMessage,
  4408. 'error_description': responseObject.errorDescription
  4409. }
  4410. }
  4411.  
  4412. LOGGER.info('Successfully obtain token for user {0}', username);
  4413. return responseObject.bodyObject;
  4414. },
  4415.  
  4416. /**
  4417. * Requests user tokens, the request must use client_id/client_secret to authenticate (BASICally) against SARA server,
  4418. * LDAP redirect_uri/authorization_code and grant_type will be embedded in request's body
  4419. * @param {String} code The authorization code which get from OAuth after logged-in successfully in Auth Endpoint
  4420. * @param {Object} config The config of OAuth Server
  4421. * @return {Object} Object contains access token, refresh token, token expiry and token type
  4422. */
  4423. requestTokenByCode: function (code, config) {
  4424. var LOGGER = this.LOGGER;
  4425.  
  4426. LOGGER.debug('Preparing for requesting tokens by code "{0}"...', code);
  4427.  
  4428. var clientId = config[SaraCommon.CONFIG_NAME.CLIENT_ID];
  4429. var clientSecret = config[SaraCommon.CONFIG_NAME.CLIENT_SECERT];
  4430. var tokenEndpoint = config[SaraCommon.CONFIG_NAME.TOKEN_ENDPOINT];
  4431. var redirectionEndpoint = SaraUtils.getRedirectionUrl();
  4432.  
  4433. var request = this.restClient.newOAuthRequest('post', tokenEndpoint);
  4434. request.setBasicAuth(clientId, clientSecret);
  4435.  
  4436. // Add POST body, set Content-Type header
  4437. request.setContentType('application/x-www-form-urlencoded');
  4438. var formEntity = {
  4439. 'grant_type': 'authorization_code',
  4440. 'redirect_uri': redirectionEndpoint,
  4441. 'code': code
  4442. };
  4443. request.setFormContent(formEntity);
  4444.  
  4445. LOGGER.info('Requesting tokens by code...');
  4446. var response = this.restClient.execute(request);
  4447. var responseObject = response.getResponseObject();
  4448.  
  4449. if (response.haveError()) {
  4450. LOGGER.info('Failed to request token by code');
  4451.  
  4452. return {
  4453. 'error': responseObject.errorMessage,
  4454. 'error_description': responseObject.errorDescription
  4455. }
  4456. }
  4457.  
  4458. LOGGER.info('Successfully obtain token for user by code "{0}"', code);
  4459. return responseObject.bodyObject;
  4460. },
  4461.  
  4462. /**
  4463. * Refresh user tokens
  4464. * @param {String} username
  4465. * @return {Object}
  4466. */
  4467. refreshToken: function (username) {
  4468. var LOGGER = this.LOGGER;
  4469.  
  4470. // Get refresh tokens for this user from 'SaraCommon.TABLE_NAME.SARA_OAUTH' table
  4471. var tokens = this.getUserTokens(username);
  4472. if (!tokens || tokens.length < 1) {
  4473. LOGGER.info('Tokens not found for user {0}', username);
  4474. return null;
  4475. }
  4476.  
  4477. LOGGER.info('Preparing for refreshing tokens for user {0}...', username);
  4478.  
  4479. // Use that refesh token to retrieve new tokens
  4480. var clientInfo = this.saraConfig.getClientConfig();
  4481. var clientId = clientInfo[SaraCommon.CONFIG_NAME.CLIENT_ID];
  4482. var clientSecret = clientInfo[SaraCommon.CONFIG_NAME.CLIENT_SECRET];
  4483. var tokenEndpoint = clientInfo[SaraCommon.CONFIG_NAME.TOKEN_ENDPOINT];
  4484. var request = this.restClient.newOAuthRequest('post', tokenEndpoint);
  4485. request.setBasicAuth(clientId, clientSecret);
  4486.  
  4487. // Add POST body, set Content-Type header
  4488. request.setContentType('application/x-www-form-urlencoded');
  4489. request.setFormContent({
  4490. 'grant_type': 'refresh_token',
  4491. 'refresh_token': tokens[1]
  4492. });
  4493.  
  4494. LOGGER.info('Refreshing tokens for user {0}...', username);
  4495. var response = this.restClient.execute(request);
  4496. var responseObject = response.getResponseObject();
  4497.  
  4498. if (response.haveError()) {
  4499. LOGGER.info('Failed to refresh token for code');
  4500.  
  4501. return {
  4502. 'error': responseObject.errorMessage,
  4503. 'error_description': responseObject.errorDescription
  4504. }
  4505. }
  4506.  
  4507. LOGGER.info('Successfully refresh token for user {0}', username);
  4508. return responseObject.bodyObject;
  4509. },
  4510.  
  4511. /**
  4512. * Validate access token key of user is invalid or expired
  4513. * @param {String} token The access token key of user
  4514. * @param {String} sapiEndpoint The SAPI endpoint
  4515. * @return {Boolean|String}
  4516. */
  4517. validateToken: function (token, sapiEndpoint) {
  4518. var LOGGER = this.LOGGER;
  4519.  
  4520. LOGGER.info('Preparing for validating token "{0}"...', token.toString());
  4521.  
  4522. var configData = this.saraConfig.getClientConfig();
  4523. var request = this.restClient.newSAPIRequest('get', sapiEndpoint);
  4524. request.addHeader('Authorization', 'bearer ' + token);
  4525.  
  4526. var response = this.restClient.executeWithRefreshToken(request);
  4527. var responseObject = response.getResponseObject();
  4528.  
  4529. if (response.haveError()) {
  4530. if (responseObject.statusCode !== 401) {
  4531. var message = SaraUtils.formatString('Error when validating token! Error code: {0} - Error message: {1}', responseObject.statusCode, responseObject.errorMessage);
  4532. LOGGER.error(message);
  4533.  
  4534. return message;
  4535. } else {
  4536. var username = this.saraConfig.getTechnicalUser();
  4537. this.removeUserToken(username);
  4538.  
  4539. return false;
  4540. }
  4541. } else {
  4542. return true;
  4543. }
  4544. },
  4545.  
  4546. type: 'SaraOAuthClient'
  4547. };
  4548. ]]></script>
  4549. <description>This class contains all OAuth-relaled functions</description>
  4550. <active>true</active>
  4551. <client_callable>false</client_callable>
  4552. <access>public</access>
  4553. </script_include>
  4554.  
  4555. <script_include>
  4556. <name>SaraRESTClient</name>
  4557. <script><![CDATA[/**
  4558. * Wraps Service Now RESTMessage in a class to provide convenient methods interacting with SARA REST
  4559. */
  4560. var SaraRESTClient = Class.create();
  4561. SaraRESTClient.prototype = {
  4562. initialize: function () {
  4563. this.LOGGER = new SaraLog(this);
  4564. },
  4565.  
  4566. /**
  4567. * Init new service request from SaraRESTMessage class
  4568. * @param {String} name The name of the REST message record
  4569. * @param {String} method The name of the HTTP method to use, such as GET or PUT
  4570. * @param {String} endpoint The endpoint for the REST message
  4571. * @param {Array<String>} basicAuthCreds The basic authentication headers for the REST message
  4572. * @param {Array<Object>} headers The object contains headers for the REST message
  4573. * @param {Array<Object>} stringParameters The object contains string parameters for the REST message
  4574. * @param {Array<Object>} stringParametersNoEscape The object contains string parameters which will be not escaped for the REST message
  4575. * @return {SaraRESTMessage}
  4576. */
  4577. newServiceRequest: function (name, method, endpoint, basicAuthCreds, headers, stringParameters, stringParametersNoEscape) {
  4578. var restMsg = new SaraRESTMessage(name, method);
  4579.  
  4580. if (endpoint) {
  4581. restMsg.setEndpoint(endpoint);
  4582. }
  4583.  
  4584. if (this.midServer) {
  4585. restMsg.setMIDServer(this.midServer);
  4586. }
  4587.  
  4588. if (basicAuthCreds && basicAuthCreds.length > 1) {
  4589. restMsg.setBasicAuth(basicAuthCreds[0], basicAuthCreds[1]);
  4590. }
  4591.  
  4592. if (headers) {
  4593. for (var i = 0, header; header = headers[i]; i++) {
  4594. if (header['name']) {
  4595. restMsg.addHeader(header['name'], header['value']);
  4596. }
  4597. }
  4598. }
  4599.  
  4600. if (stringParameters) {
  4601. for (var i = 0, stringParameter; stringParameter = stringParameters[i]; i++) {
  4602. if (stringParameter['name']) {
  4603. restMsg.setStringParameter(stringParameter['name'], stringParameter['value']);
  4604. }
  4605. }
  4606. }
  4607.  
  4608. if (stringParametersNoEscape) {
  4609. for (var i = 0, stringParameter; stringParameter = stringParametersNoEscape[i]; i++) {
  4610. if (stringParameter['name']) {
  4611. restMsg.setStringParameterNoEscape(stringParameter['name'], stringParameter['value']);
  4612. }
  4613. }
  4614. }
  4615.  
  4616. return restMsg;
  4617. },
  4618.  
  4619. /**
  4620. * Init new SAPI service request from SaraRESTMessage class
  4621. * @param {String} method The name of the HTTP method to use, such as GET or PUT
  4622. * @param {String} endpoint The endpoint for the REST message
  4623. * @param {Array<String>} basicAuthCreds The basic authentication headers for the REST message
  4624. * @param {Array<Object>} headers The object contains headers for the REST message
  4625. * @param {Array<Object>} stringParameters The object contains string parameters for the REST message
  4626. * @param {Array<Object>} stringParametersNoEscape The object contains string parameters which will be not escaped for the REST message
  4627. * @return {SaraRESTMessage}
  4628. */
  4629. newSAPIRequest: function (method, endpoint, basicAuthCreds, headers, stringParameters, stringParametersNoEscape) {
  4630. return this.newServiceRequest(SaraCommon.REST_NAME.SAPI, method, endpoint, basicAuthCreds, headers)
  4631. },
  4632.  
  4633. /**
  4634. * Init new OAuth service request from SaraRESTMessage class
  4635. * @param {String} method The name of the HTTP method to use, such as GET or PUT
  4636. * @param {String} endpoint The endpoint for the REST message
  4637. * @param {Array<String>} basicAuthCreds The basic authentication headers for the REST message
  4638. * @param {Array<Object>} headers The object contains headers for the REST message
  4639. * @param {Array<Object>} stringParameters The object contains string parameters for the REST message
  4640. * @param {Array<Object>} stringParametersNoEscape The object contains string parameters which will be not escaped for the REST message
  4641. * @return {SaraRESTMessage}
  4642. */
  4643. newOAuthRequest: function (method, endpoint, basicAuthCreds, headers, stringParameters, stringParametersNoEscape) {
  4644. return this.newServiceRequest(SaraCommon.REST_NAME.OAUTH, method, endpoint, basicAuthCreds, headers)
  4645. },
  4646.  
  4647. /**
  4648. * Execute REST Message request
  4649. * @param {SaraRESTMessage} saraRest Sara REST Message object
  4650. * @return {SaraRESTResponse}
  4651. */
  4652. execute: function (saraRest) {
  4653. var LOGGER = this.LOGGER;
  4654.  
  4655. LOGGER.info('Making {0} request to {1}...', saraRest.getMethod(), saraRest.getEndpoint());
  4656. LOGGER.debug(saraRest.dump());
  4657.  
  4658. var response;
  4659. if (this.midServer) {
  4660. response = saraRest.executeViaMIDServer(this.midServer);
  4661. } else {
  4662. response = saraRest.execute();
  4663. }
  4664.  
  4665. return response;
  4666. },
  4667.  
  4668. /**
  4669. * Execute REST Message request with automatically get new token if token is expired
  4670. * @param {SaraRESTMessage} saraRest Sara REST Message object
  4671. * @return {SaraRESTResponse}
  4672. */
  4673. executeWithRefreshToken: function (saraRest) {
  4674. var LOGGER = this.LOGGER;
  4675.  
  4676. // First time request
  4677. var response = this.execute(saraRest);
  4678. var responseObject = response.getResponseObject();
  4679.  
  4680. if (response.haveError()) {
  4681. if (responseObject.statusCode === 401) {
  4682. LOGGER.info('Access token of user is invalid or expired');
  4683.  
  4684. var oauthClient = new SaraOAuthClient(this);
  4685. var username = new SaraConfig().getTechnicalUser();
  4686.  
  4687. LOGGER.info('Trying to refresh token for user "{0}"...', username);
  4688. var tokens = oauthClient.refreshToken(username);
  4689.  
  4690. if (tokens && !tokens.error) {
  4691. LOGGER.info('Refresh token finished successfully.');
  4692. oauthClient.storeUserTokens(username, tokens['access_token'], tokens['refresh_token'], tokens['expires_in'], tokens['token_type']);
  4693.  
  4694. // Request again with new token
  4695. saraRest.addHeader('Authorization', 'bearer ' + tokens['access_token']);
  4696. response = this.execute(saraRest);
  4697. } else {
  4698. LOGGER.error('Error when refreshing token');
  4699.  
  4700. if (!tokens) {
  4701. LOGGER.info('Error: {0} - Error description: {1}', tokens.error, tokens.errorDescription);
  4702. oauthClient.removeUserToken(username);
  4703. }
  4704. }
  4705. }
  4706. }
  4707.  
  4708. return response;
  4709. },
  4710.  
  4711. /**
  4712. * Set MID Server
  4713. * @param {String} midServer The MID Server name
  4714. */
  4715. setMIDServer: function (midServer) {
  4716. this.midServer = midServer;
  4717. },
  4718.  
  4719. type: 'SaraRESTClient'
  4720. };
  4721. ]]></script>
  4722. <description>Wraps Service Now RESTMessage in a class to provide convenient methods interacting with SARA REST</description>
  4723. <active>true</active>
  4724. <client_callable>false</client_callable>
  4725. <access>public</access>
  4726. </script_include>
  4727.  
  4728. <script_include>
  4729. <name>SaraRESTMessage</name>
  4730. <script><![CDATA[/**
  4731. * Wrap original ServiceNow's RESTMessageV2 class to make HTTP request
  4732. */
  4733. var SaraRESTMessage = Class.create();
  4734. SaraRESTMessage.prototype = {
  4735. /**
  4736. * Init Sara REST Message object
  4737. * @param {String} name Name of REST message record
  4738. * @param {String} method The name of the HTTP method to use, such as GET or PUT
  4739. */
  4740. initialize: function (name, method) {
  4741. method = method.toLowerCase();
  4742. this.restMsg = new sn_ws.RESTMessageV2(name, method);
  4743. this.name = name;
  4744. this.method = method;
  4745.  
  4746. this.LOGGER = new SaraLog(this);
  4747. },
  4748.  
  4749. /**
  4750. * Set the content of the REST message body
  4751. * @param {String} content The content of REST Message
  4752. */
  4753. setContent: function (content) {
  4754. this.restMsg.setRequestBody(content);
  4755. },
  4756.  
  4757. /**
  4758. * Set form content for REST Message
  4759. * @param {Object} formData The object contains form data
  4760. */
  4761. setFormContent: function (formData) {
  4762. if (!formData) {
  4763. return;
  4764. }
  4765.  
  4766. var content = '';
  4767.  
  4768. for (var propName in formData) {
  4769. var value = formData[propName];
  4770.  
  4771. if (value instanceof Array) {
  4772. for (var i = 0; i < value.length; i++) {
  4773. var _value = value[i];
  4774.  
  4775. content += (encodeURIComponent(propName) + '=' + encodeURIComponent(_value) + '&');
  4776. }
  4777. } else {
  4778. content += (encodeURIComponent(propName) + '=' + encodeURIComponent(value) + '&');
  4779. }
  4780. }
  4781.  
  4782. if (content.length > 0) {
  4783. content = content.substring(0, content.length - 1);
  4784. this.setContent(content);
  4785. }
  4786. },
  4787.  
  4788. /**
  4789. * Get the content of the REST message body
  4790. * @return {String}
  4791. */
  4792. getContent: function () {
  4793. return this.restMsg.getRequestBody();
  4794. },
  4795.  
  4796. /**
  4797. * Add headers for REST Message
  4798. * @param {String} key The key of header
  4799. * @param {*} value The value of header
  4800. */
  4801. addHeader: function (key, value) {
  4802. var LOGGER = this.LOGGER;
  4803.  
  4804. LOGGER.debug('addHeader: key = "{0}" and value = "{1}"', key, value);
  4805.  
  4806. this.restMsg.setRequestHeader(key, value);
  4807. },
  4808.  
  4809. /**
  4810. * Add type for header named 'content-type'
  4811. * @param {String} type The content type of REST Message
  4812. */
  4813. setContentType: function (type) {
  4814. var LOGGER = this.LOGGER;
  4815.  
  4816. LOGGER.debug('setContentType: type = "{0}"', type);
  4817.  
  4818. this.addHeader('content-type', type);
  4819. },
  4820.  
  4821. /**
  4822. * Set basic authentication headers for the REST message
  4823. * @param {String} usename
  4824. * @param {String} password
  4825. */
  4826. setBasicAuth: function (username, password) {
  4827. var LOGGER = this.LOGGER;
  4828.  
  4829. LOGGER.debug('setBasicAuth: username = "{0}" and password = "{1}"', username, password);
  4830.  
  4831. this.restMsg.setBasicAuth(username, password);
  4832. },
  4833.  
  4834. /**
  4835. * Set a REST message function variable to the specified value
  4836. * @param {String} name The name of parameter
  4837. * @param {String} value The value of parameter
  4838. */
  4839. setStringParameter: function (name, value) {
  4840. var LOGGER = this.LOGGER;
  4841.  
  4842. LOGGER.debug('setStringParameter: name = "{0}" and value = "{1}"', name, value);
  4843.  
  4844. this.restMsg.setStringParameter(name, value);
  4845. },
  4846.  
  4847. /**
  4848. * Set a REST message function variable to the specified value without escaping XML reserved characters
  4849. * @param {String} name The name of parameter
  4850. * @param {String} value The value of parameter
  4851. */
  4852. setStringParameterNoEscape: function (name, value) {
  4853. var LOGGER = this.LOGGER;
  4854.  
  4855. LOGGER.debug('setStringParameterNoEscape: name = "{0}" and value = "{1}"', name, value);
  4856.  
  4857. this.restMsg.setStringParameterNoEscape(name, value);
  4858. },
  4859.  
  4860. /**
  4861. * Set the endpoint for the REST message
  4862. * @param {String} endpoint
  4863. */
  4864. setEndpoint: function (endpoint) {
  4865. var LOGGER = this.LOGGER;
  4866.  
  4867. LOGGER.debug('setEndpoint: endpoint = "{0}"', endpoint);
  4868.  
  4869. this.restMsg.setEndpoint(endpoint);
  4870. },
  4871.  
  4872. /**
  4873. * Get the URL of the endpoint for the REST message.
  4874. * @return {String}
  4875. */
  4876. getEndpoint: function () {
  4877. return this.restMsg.getEndpoint();
  4878. },
  4879.  
  4880. /**
  4881. * Configure the REST message to communicate through a MID Server.
  4882. * @param {String} midServer The name of MID Server
  4883. */
  4884. setMIDServer: function (midServer) {
  4885. var LOGGER = this.LOGGER;
  4886.  
  4887. LOGGER.debug('setMIDServer: midServer = "{0}"', midServer);
  4888.  
  4889. this.restMsg.setMIDServer(midServer);
  4890. },
  4891.  
  4892. /**
  4893. * Send REST Message to endpoint
  4894. * @return {}
  4895. */
  4896. execute: function () {
  4897. return new SaraRESTResponse(this.restMsg.execute());
  4898. },
  4899.  
  4900. /**
  4901. * Execute REST request via MID Server
  4902. * @param {String} midServer The name of MID Server
  4903. */
  4904. executeViaMIDServer: function (midServer) {
  4905. var LOGGER = this.LOGGER;
  4906.  
  4907. if (midServer) {
  4908. this.restMsg.setMIDServer(midServer);
  4909. this.midServer = midServer;
  4910. LOGGER.info('Using MID Server {0}', this.midServer);
  4911. }
  4912.  
  4913. if (!this.midServer) {
  4914. LOGGER.info('No MID Server defined for the request. Request is aborted!');
  4915. return null;
  4916. }
  4917.  
  4918. return new SaraRESTResponse(this.restMsg.execute(), true);
  4919. },
  4920.  
  4921. /**
  4922. * Get method name of this REST Message
  4923. * @return {String}
  4924. */
  4925. getMethod: function () {
  4926. return this.method.toUpperCase();
  4927. },
  4928.  
  4929. /**
  4930. * Dump information of REST Message
  4931. */
  4932. dump: function () {
  4933. var LOGGER = this.LOGGER;
  4934.  
  4935. try {
  4936. var str = this.getMethod() + ' ' + this.getEndpoint() + ' HTTP/1.1';
  4937.  
  4938. var headers = this.restMsg.getRequestHeaders();
  4939. if (headers) {
  4940. for (key in headers) {
  4941. var value = headers[key];
  4942.  
  4943. if (!gs.nil(value)) {
  4944. if (key === 'Authorization') {
  4945. value = '**********************';
  4946. }
  4947.  
  4948. str += SaraUtils.formatString('\n {0}: {1}', key, value);
  4949. }
  4950. }
  4951. }
  4952.  
  4953. var content = this.getContent();
  4954.  
  4955. if (!gs.nil(content) && content !== 'undefined' && content) {
  4956. str += SaraUtils.formatString('\n\n', content);
  4957. }
  4958.  
  4959. return str;
  4960. } catch (error) {
  4961. LOGGER.info('Error in SaraRESTMessage.dump(): ' + error);
  4962. }
  4963. },
  4964.  
  4965. type: 'SaraRESTMessage'
  4966. };
  4967. ]]></script>
  4968. <description>Class extend from original ServiceNow's RESTMessage class to make HTTP request</description>
  4969. <active>true</active>
  4970. <client_callable>false</client_callable>
  4971. <access>package_private</access>
  4972. </script_include>
  4973.  
  4974. <script_include>
  4975. <name>SaraRESTResponse</name>
  4976. <script><![CDATA[/**
  4977. * Wrap original ServiceNow's RESTResponseV2 class to handle response of RESTMessageV2
  4978. */
  4979. var SaraRESTResponse = Class.create();
  4980. SaraRESTResponse.prototype = {
  4981. /**
  4982. * Init Sara REST Response object
  4983. * @param {sn_ws.RESTResponseV2} response The response object of RESTResponseV2
  4984. * @param {Boolean} useMIDServer Get response via MID Server or not
  4985. */
  4986. initialize: function (response, useMIDServer) {
  4987. this.response = response;
  4988.  
  4989. var LOGGER = this.LOGGER = new SaraLog(this);
  4990.  
  4991. if (useMIDServer) {
  4992. var timeout = SaraUtils.getSaraProperty(SaraCommon.SYSTEM_PROPERTY_NAME.REST_REQUEST_TIMEOUT);
  4993. LOGGER.debug('Timeout for REST Message: {0}s', timeout);
  4994. response.waitForResponse(timeout);
  4995. }
  4996.  
  4997. if (response.haveError()) {
  4998. LOGGER.info('Error when requesting REST Message: {0} - {1}', response.getErrorCode(), response.getErrorMessage());
  4999. } else {
  5000. LOGGER.info('Status code: {0}', response.getStatusCode());
  5001. }
  5002.  
  5003. LOGGER.debug('Response body: {0}', response.getBody());
  5004. },
  5005.  
  5006. /**
  5007. * Set the amount of time the instance waits for the response
  5008. * @param {Number} timeoutSecs The amount of time, in seconds, to wait for this response.
  5009. */
  5010. waitForResponse: function (timeoutSecs) {
  5011. this.response.waitForResponse(timeoutSecs);
  5012. },
  5013.  
  5014. /**
  5015. * Get the numeric HTTP status code returned by the REST provider
  5016. * @return {Number}
  5017. */
  5018. getStatusCode: function () {
  5019. return this.response.getStatusCode();
  5020. },
  5021.  
  5022. /**
  5023. * Get the value for a specified header
  5024. * @param {Number} timeoutSecs The name of the header that you want the value for, such as Set-Cookie.
  5025. * @return {String}
  5026. */
  5027. getHeader: function (name) {
  5028. return this.response.getHeader(name);
  5029. },
  5030.  
  5031. /**
  5032. * Get all headers returned in the REST response and the associated values
  5033. * @return {Object}
  5034. */
  5035. getHeaders: function () {
  5036. return this.response.getHeaders();
  5037. },
  5038.  
  5039. /**
  5040. * Get the content of the REST response body
  5041. * @return {String}
  5042. */
  5043. getBody: function () {
  5044. return this.response.getBody();
  5045. },
  5046.  
  5047. /**
  5048. * Indicate if there was an error during the REST transaction
  5049. * @return {Boolean}
  5050. */
  5051. haveError: function () {
  5052. return this.response.haveError();
  5053. },
  5054.  
  5055. /**
  5056. * Get the numeric error code if there was an error during the REST transaction. This error code is
  5057. * specific to the ServiceNow platform, it is not an HTTP error code. Provide this error code if you
  5058. * require assistance from ServiceNow Customer Support
  5059. * @return {Number}
  5060. */
  5061. getErrorCode: function () {
  5062. return this.response.getErrorCode();
  5063. },
  5064.  
  5065. /**
  5066. * Get the error message if there was an error during the REST transaction
  5067. * @return {String}
  5068. */
  5069. getErrorMessage: function () {
  5070. return this.response.getErrorMessage();
  5071. },
  5072.  
  5073. /**
  5074. * Get the fully-resolved query sent to the REST endpoint. This query contains the endpoint URL as well
  5075. * as any values assigned to variables in the REST message
  5076. */
  5077. getQueryString: function () {
  5078. return this, response.getQueryString();
  5079. },
  5080.  
  5081. /**
  5082. * Get response body with format is Object
  5083. * @return {Object|Null}
  5084. */
  5085. getBodyObject: function () {
  5086. var LOGGER = this.LOGGER;
  5087.  
  5088. var body = this.getBody();
  5089. if (body) {
  5090. try {
  5091. body = SaraJSON.parse(body);
  5092. } catch (ex) {
  5093. LOGGER.error('Error when parsing response body to Object: {0}', ex);
  5094. }
  5095. }
  5096.  
  5097. return body;
  5098. },
  5099.  
  5100. /**
  5101. * Get response with format is Object. This response contains body object, status code, error message and
  5102. * error description
  5103. * @return {Object}
  5104. */
  5105. getResponseObject: function () {
  5106. var bodyObject = this.getBodyObject();
  5107. var statusCode = this.getStatusCode();
  5108. var errorMessage = this.getErrorMessage();
  5109. var errorDescription = this.getErrorMessage();
  5110.  
  5111. if (bodyObject) {
  5112. if (bodyObject['error']) {
  5113. errorMessage = bodyObject['error'];
  5114. }
  5115.  
  5116. if (bodyObject['error_description']) {
  5117. errorDescription = bodyObject['error_description'];
  5118. }
  5119. }
  5120.  
  5121. return {
  5122. bodyObject: bodyObject,
  5123. statusCode: statusCode,
  5124. errorMessage: errorMessage,
  5125. errorDescription: errorDescription
  5126. }
  5127. },
  5128.  
  5129. type: 'SaraRESTResponse'
  5130. };
  5131. ]]></script>
  5132. <description>Wrap original ServiceNow's RESTResponseV2 class to handle RESTMessageV2 response</description>
  5133. <active>true</active>
  5134. <client_callable>false</client_callable>
  5135. <access>package_private</access>
  5136. </script_include>
  5137.  
  5138. <script_include>
  5139. <name>SaraSync</name>
  5140. <script><![CDATA[/**
  5141. * Sara Sync Utilities
  5142. */
  5143. var SaraSync = Class.create();
  5144. SaraSync.prototype = {
  5145. initialize: function () {
  5146. this.glideHelper = new SaraGlideHelper();
  5147. this.LOGGER = new SaraLog(this);
  5148. },
  5149.  
  5150. /**
  5151. * Sync services and catalogs of all category which was imported services
  5152. */
  5153. syncServices: function () {
  5154. var glideHelper = this.glideHelper;
  5155. var LOGGER = this.LOGGER;
  5156.  
  5157. var importedCategories = glideHelper.getData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  5158. 'u_type': 'category'
  5159. }, true);
  5160.  
  5161. if (importedCategories.length > 0) {
  5162. LOGGER.info('There are {0} target category(s) which were imported services\n', importedCategories.length);
  5163.  
  5164. var consumer = new SaraConsumer();
  5165. var response = consumer.discover();
  5166.  
  5167. if (response.error) {
  5168. LOGGER.error('Discover data from SAPI not successfully. Syncing services is aborted!');
  5169. return;
  5170. } else {
  5171. for (var i = 0, importedCategory; importedCategory = importedCategories[i]; i++) {
  5172. LOGGER.info('Syncing target category (name = {0}, sys_id = {1})', importedCategory.u_name, importedCategory.u_parent);
  5173.  
  5174. consumer.doImport(importedCategory.u_parent);
  5175. consumer.refreshImportedData();
  5176.  
  5177. LOGGER.info('Target category (name = {0}, sys_id = {1}) is synced!', importedCategory.u_name, importedCategory.u_parent);
  5178. }
  5179. }
  5180. } else {
  5181. LOGGER.warn('No target category found. Skip syncServices!');
  5182. }
  5183. },
  5184.  
  5185. /**
  5186. * Update lookup variable
  5187. * @param {Object} saraVariable The variable from SaraCommon.TABLE_NAME.SARA_DEFINITION, has 'sys_id', 'type', 'name', 'u_hash', 'list_table', 'lookup_table' and 'default_value'
  5188. * @param {SaraModel.CatalogVariable} variable
  5189. */
  5190. updateLookupVariable: function (saraVariable, variable) {
  5191. var glideHelper = this.glideHelper;
  5192. var LOGGER = this.LOGGER;
  5193.  
  5194. LOGGER.info('New and old hash of variable "{0}": {1} - {2}', saraVariable['name'], variable.getHash(), saraVariable['u_hash']);
  5195.  
  5196. if (variable.getHash() === saraVariable['u_hash']) {
  5197. LOGGER.info('Lookup value of variable "{0}" is not changed!', saraVariable['name']);
  5198. } else {
  5199. LOGGER.info('Lookup value of variable "{0}" is changed!', saraVariable['name']);
  5200.  
  5201. // Remove the old data of lookup table
  5202. glideHelper.deleteData(SaraCommon.TABLE_NAME.SARA_LOOKUP, {
  5203. 'u_control_id': saraVariable['sys_id']
  5204. }, true);
  5205. LOGGER.info('Deleted old data of {0} in {1}!', saraVariable['name'], SaraCommon.TABLE_NAME.SARA_LOOKUP);
  5206.  
  5207. var newDefaultValues = [];
  5208. var ranges = variable.getRange();
  5209.  
  5210. // Insert new range values
  5211. for (var i = 0, range; range = ranges[i]; i++) {
  5212. var rangeId = glideHelper.persistData(SaraCommon.TABLE_NAME.SARA_LOOKUP, {
  5213. 'u_key': range.Value,
  5214. 'u_display_name': range.Key,
  5215. 'u_control_id': saraVariable['sys_id']
  5216. });
  5217.  
  5218. if (SaraUtils.inArray(variable.getDefaultValue(), range.Key)) {
  5219. newDefaultValues.push(rangeId);
  5220. }
  5221. }
  5222. LOGGER.info('Inserted new data of {0} in {1}!', saraVariable['name'], SaraCommon.TABLE_NAME.SARA_LOOKUP);
  5223.  
  5224. if (saraVariable['default_value']) {
  5225. newDefaultValues = newDefaultValues.join(',');
  5226.  
  5227. glideHelper.updateData(SaraCommon.TABLE_NAME.SARA_VARIABLE, {
  5228. 'sys_id': saraVariable['sys_id']
  5229. }, {
  5230. 'default_value': newDefaultValues
  5231. });
  5232.  
  5233. LOGGER.info('Updated default value for variable (name = {0}, sys_id = {1}) with new default_value = {2}', saraVariable['name'], saraVariable['sys_id'], newDefaultValues);
  5234. }
  5235. }
  5236. },
  5237.  
  5238. /**
  5239. * Get variable from instance of SaraModel.CatalogItem
  5240. * @param {SaraModel.CatalogItem} catalogItem
  5241. * @param {String} saraVariableName
  5242. * @return {SaraModel.CatalogVariable||Null}
  5243. */
  5244. getVariable: function (catalogItem, saraVariableName) {
  5245. var variables = catalogItem.getVariables();
  5246.  
  5247. for (var i = 0, variable; variable = variables[i]; i++) {
  5248. var variableName = variable.getName();
  5249.  
  5250. if (variableName === saraVariableName) {
  5251. return variable;
  5252. }
  5253. }
  5254.  
  5255. return null;
  5256. },
  5257.  
  5258. /**
  5259. * Sync all lookup values of catalog item
  5260. * @param {String} saraItem The catalog item in SaraCommon.TABLE_NAME.SARA_DEFINITION
  5261. * @param {SaraModel.CatalogItem} catalogItem
  5262. */
  5263. syncLookup: function (saraCatalogItem, catalogItem) {
  5264. var glideHelper = this.glideHelper;
  5265. var LOGGER = this.LOGGER;
  5266.  
  5267. LOGGER.info('Starting syncLookup...');
  5268.  
  5269. if (catalogItem.getVariables()) {
  5270. // Get variable set of catalog item
  5271. var varSetId = saraCatalogItem['u_var_set'];
  5272. LOGGER.info('Found sys_id of variable set of {0} is: {1}', saraCatalogItem['u_name'], varSetId);
  5273.  
  5274. // Get lookup variables of variable set
  5275. var saraLookupVariables = glideHelper.getData(SaraCommon.TABLE_NAME.SARA_VARIABLE, {
  5276. 'variable_set': varSetId,
  5277. 'u_is_lookup': true
  5278. }, true);
  5279.  
  5280. if (saraLookupVariables.length > 0) {
  5281. LOGGER.info('Found {0} lookup variable(s) in variable set (sys_id = {1})', saraLookupVariables.length, varSetId);
  5282.  
  5283. for (var i = 0, saraVariable; saraVariable = saraLookupVariables[i]; i++) {
  5284. var variable = this.getVariable(catalogItem, saraVariable['name']);
  5285.  
  5286. this.updateLookupVariable(saraVariable, variable);
  5287. }
  5288. } else {
  5289. LOGGER.warn('No lookup variable found in variable set (sys_id = {0}). Skip syncLookup!', varSetId);
  5290. }
  5291. } else {
  5292. LOGGER.warn('There\' no variable found in catalog (item name = {0}). Skip syncLookup!', saraCatalogItem['u_name']);
  5293. }
  5294.  
  5295. LOGGER.info('Ended syncLookup!');
  5296. },
  5297.  
  5298. type: 'SaraSync'
  5299. };
  5300. ]]></script>
  5301. <description>Sara Sync Utilities</description>
  5302. <active>true</active>
  5303. <client_callable>false</client_callable>
  5304. <access>public</access>
  5305. </script_include>
  5306.  
  5307. <script_include>
  5308. <name>SaraUtils</name>
  5309. <script><![CDATA[/**
  5310. * Sara Utilities
  5311. */
  5312. var SaraUtils = Class.create();
  5313. SaraUtils.prototype = {
  5314. initialize: function () {},
  5315.  
  5316. type: 'SaraUtils'
  5317. };
  5318.  
  5319. /**
  5320. * Format strings
  5321. * @param {String} string The template string
  5322. * @param {String[]} args Zero or more objects to format, supplied either in a comma-delimited list or as an array
  5323. */
  5324. SaraUtils.formatString = function (string) {
  5325. var args = Array.prototype.slice.call(arguments, 1);
  5326.  
  5327. return string.replace(/\{(\d+)\}/g, function (match, number) {
  5328. return typeof args[number] != 'undefined' ? args[number] : match;
  5329. });
  5330. };
  5331.  
  5332. /**
  5333. * Get Sara property
  5334. * @param {String} name Name of sara property
  5335. * @return {String}
  5336. */
  5337. SaraUtils.getSaraProperty = function (name) {
  5338. return gs.getProperty(SaraCommon.PROP_PREFIX + '.' + name);
  5339. };
  5340.  
  5341. /**
  5342. * Get mid servcer
  5343. * @return {String}
  5344. */
  5345. SaraUtils.getMIDServer = function () {
  5346. return SaraUtils.getSaraProperty(SaraCommon.SYSTEM_PROPERTY_NAME.MID_SERVER);
  5347. };
  5348.  
  5349. /**
  5350. * Get timestamp of current
  5351. * @return {String}
  5352. */
  5353. SaraUtils.getTimeStamp = function () {
  5354. return new Date().valueOf();
  5355. };
  5356.  
  5357. /**
  5358. * Get random number
  5359. * @return {String}
  5360. */
  5361. SaraUtils.getRandom = function () {
  5362. return Math.round(Math.random() * 987654321);
  5363. };
  5364.  
  5365. /**
  5366. * Diff time and return 'h, m, s'
  5367. * @param {Number} time1 The first timestamp
  5368. * @param {Number} time2 The second timestamp
  5369. * @return {String}
  5370. */
  5371. SaraUtils.diffTime = function (time1, time2) {
  5372. var difference = time2 - time1;
  5373.  
  5374. var daysDifference = Math.floor(difference / 1000 / 60 / 60 / 24);
  5375. difference -= daysDifference * 1000 * 60 * 60 * 24;
  5376.  
  5377. var hoursDifference = Math.floor(difference / 1000 / 60 / 60);
  5378. difference -= hoursDifference * 1000 * 60 * 60;
  5379.  
  5380. var minutesDifference = Math.floor(difference / 1000 / 60);
  5381. difference -= minutesDifference * 1000 * 60;
  5382.  
  5383. var secondsDifference = Math.floor(difference / 1000);
  5384. difference -= secondsDifference * 1000;
  5385.  
  5386. var result = '';
  5387.  
  5388. if (daysDifference > 0) {
  5389. result += daysDifference + 'd ';
  5390. }
  5391.  
  5392. if (hoursDifference > 0) {
  5393. result += hoursDifference + 'h ';
  5394. }
  5395.  
  5396. if (minutesDifference > 0) {
  5397. result += minutesDifference + 'm ';
  5398. }
  5399.  
  5400. if (secondsDifference > 0) {
  5401. result += secondsDifference + 's ';
  5402. }
  5403.  
  5404. result += difference + 'ms';
  5405.  
  5406. return result;
  5407. };
  5408.  
  5409. /**
  5410. * Convert '\n' to '<br />' in string
  5411. * @param {String} string
  5412. * @return {String}
  5413. */
  5414. SaraUtils.nl2br = function (string) {
  5415. string = string || '';
  5416.  
  5417. return string.replace(/\n/g, '<br />');
  5418. };
  5419.  
  5420. /**
  5421. * Clean all data of SNSC
  5422. */
  5423. SaraUtils.cleanup = function () {
  5424. var glideHelper = new SaraGlideHelper();
  5425. var LOGGER = new SaraLog('SaraUtils');
  5426. var catItemIds = [];
  5427. var varSetIds = [];
  5428. var catCateIds = [];
  5429. var targetCateIds = [];
  5430.  
  5431. // Get list of catalog item from SaraCommon.TABLE_NAME.SARA_DEFINITION table
  5432. var saraItems = glideHelper.getData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {}, true);
  5433.  
  5434. if (saraItems.length > 0) {
  5435. LOGGER.info('Found {0} item(s) in "{1}"', saraItems.length, SaraCommon.TABLE_NAME.SARA_DEFINITION);
  5436.  
  5437. for (var i = 0, saraItem; saraItem = saraItems[i]; i++) {
  5438. if (saraItem['u_sc_item']) {
  5439. catItemIds.push(saraItem['u_sc_item']);
  5440. }
  5441.  
  5442. if (saraItem['u_var_set']) {
  5443. varSetIds.push(saraItem['u_var_set']);
  5444. }
  5445.  
  5446. if (saraItem['u_service_catalog_category']) {
  5447. catCateIds.push(saraItem['u_service_catalog_category']);
  5448. }
  5449.  
  5450. if (saraItem['u_type'] === 'category') {
  5451. targetCateIds.push(saraItem['u_parent']);
  5452. }
  5453. }
  5454.  
  5455. var message = 'There are :';
  5456. message += SaraUtils.formatString('\n - {0} catalog item(s)', catItemIds.length);
  5457. message += SaraUtils.formatString('\n - {0} variable set(s)', varSetIds.length);
  5458. message += SaraUtils.formatString('\n - {0} category(s)', catCateIds.length);
  5459. message += SaraUtils.formatString('\n - {0} target category(s)', targetCateIds.length);
  5460. LOGGER.info(message);
  5461.  
  5462. if (varSetIds.length > 0) {
  5463. LOGGER.info('Removing {0} variable set(s)...', varSetIds.length);
  5464.  
  5465. for (var i = 0, varSetId; varSetId = varSetIds[i]; i++) {
  5466. // Remove all variables belong to above variable sets
  5467. LOGGER.info('Removing variables from variable set {0}...', varSetId);
  5468. glideHelper.deleteData(SaraCommon.TABLE_NAME.SN_VARIABLE, {
  5469. 'variable_set': varSetId
  5470. }, true);
  5471.  
  5472. // Remove all variable sets
  5473. LOGGER.info('Removing variable set (sys_id = {0})...', varSetId);
  5474. glideHelper.deleteData(SaraCommon.TABLE_NAME.SN_VARIABLE_SET, {
  5475. 'sys_id': varSetId
  5476. }, true);
  5477. }
  5478. }
  5479.  
  5480. // Cleanup service catalog items
  5481. if (catItemIds.length > 0) {
  5482. LOGGER.info('Removing {0} catalog item(s)...', catItemIds.length);
  5483.  
  5484. for (var i = 0, catItemId; catItemId = catItemIds[i]; i++) {
  5485. glideHelper.deleteData(SaraCommon.TABLE_NAME.SN_CATALOG_ITEM, {
  5486. 'sys_id': catItemId
  5487. });
  5488. }
  5489. }
  5490.  
  5491. // Cleanup catalog categories
  5492. if (catCateIds.length > 0) {
  5493. LOGGER.info('Removing {0} catalog category(s)...', catCateIds.length);
  5494.  
  5495. for (var i = 0, catCateId; catCateId = catCateIds[i]; i++) {
  5496. glideHelper.deleteData(SaraCommon.TABLE_NAME.SN_CATEGORY, {
  5497. 'sys_id': catCateId
  5498. });
  5499. }
  5500. }
  5501.  
  5502. // Refresh target categories
  5503. if (targetCateIds.length > 0) {
  5504. LOGGER.info('Refreshing {0} target category(s)...', catCateIds.length);
  5505.  
  5506. for (var i = 0, targetCateId; targetCateId = targetCateIds[i]; i++) {
  5507. glideHelper.updateData(SaraCommon.TABLE_NAME.SN_CATEGORY, {
  5508. 'sys_id': targetCateId
  5509. }, {
  5510. 'active': false
  5511. });
  5512.  
  5513. glideHelper.updateData(SaraCommon.TABLE_NAME.SN_CATEGORY, {
  5514. 'sys_id': targetCateId
  5515. }, {
  5516. 'active': true
  5517. });
  5518.  
  5519. LOGGER.info('Target category (sys_id = {0}) is refreshed.', targetCateId);
  5520. }
  5521. }
  5522.  
  5523. LOGGER.info('Cleaning up {0} table ...', SaraCommon.TABLE_NAME.SARA_DEFINITION);
  5524. glideHelper.deleteData(SaraCommon.TABLE_NAME.SARA_DEFINITION, {}, true);
  5525.  
  5526. LOGGER.info('Cleaning up {0} table ...', SaraCommon.TABLE_NAME.SARA_VARIABLE);
  5527. glideHelper.deleteData(SaraCommon.TABLE_NAME.SARA_VARIABLE, {}, true);
  5528. } else {
  5529. LOGGER.warn('There is no items in "{0}". Skip cleanup!', SaraCommon.TABLE_NAME.SARA_DEFINITION);
  5530. }
  5531. };
  5532.  
  5533. /**
  5534. * Create catalog variable from field information
  5535. * @param {Object} field
  5536. * @return {SaraModel.CatalogVariable}
  5537. */
  5538. SaraUtils.createCatalogVariable = function (field) {
  5539. var defaultValue = '';
  5540. var varType;
  5541. var isLookupControl = false;
  5542.  
  5543. if (field['default'] && field['default'].length > 0) {
  5544. defaultValue = field['default'];
  5545. }
  5546.  
  5547. switch (field.type) {
  5548. case 'Label':
  5549. varType = SaraCommon.VAR_TYPE.LABEL;
  5550. break;
  5551. case 'Number':
  5552. // SN only have NUM_SCALE variable type but not suitable, just use string
  5553. varType = SaraCommon.VAR_TYPE.SINGLE_LINE_TEXT;
  5554. break;
  5555. case 'String':
  5556. varType = SaraCommon.VAR_TYPE.SINGLE_LINE_TEXT;
  5557. break;
  5558. case 'List':
  5559. varType = field.multiSelect ? SaraCommon.VAR_TYPE.LIST_COLLECTOR : SaraCommon.VAR_TYPE.LOOKUP_SELECT_BOX;
  5560. isLookupControl = true;
  5561. break;
  5562. case 'Time':
  5563. varType = SaraCommon.VAR_TYPE.SINGLE_LINE_TEXT;
  5564. break;
  5565. case 'Date':
  5566. varType = SaraCommon.VAR_TYPE.DATE;
  5567. break;
  5568. case 'Timestamp':
  5569. varType = SaraCommon.VAR_TYPE.DATE_TIME;
  5570. break;
  5571. default:
  5572. break;
  5573. }
  5574.  
  5575. var catalogVariable = new SaraModel.CatalogVariable();
  5576. catalogVariable.setName(this.legitVarName(field.name));
  5577. catalogVariable.setType(varType);
  5578. catalogVariable.setLabel(field.caption);
  5579. catalogVariable.setDefaultValue(defaultValue);
  5580. catalogVariable.setDescription(field.description);
  5581. catalogVariable.setRange([]);
  5582. catalogVariable.setAsLookup(isLookupControl);
  5583.  
  5584. if (field.maskAsPassword) {
  5585. catalogVariable.setAsPassword(field.maskAsPassword);
  5586. }
  5587.  
  5588. if (field.range && field.range[0].values) {
  5589. var rangeValue = field.range[0].values;
  5590. catalogVariable.setRange(rangeValue);
  5591.  
  5592. // Generate range hash for variable
  5593. var hash = SaraUtils.md5(SaraJSON.stringify(rangeValue));
  5594. catalogVariable.setHash(hash);
  5595. }
  5596.  
  5597. if (field.name) {
  5598. catalogVariable.setActualName(field.name);
  5599. }
  5600.  
  5601. if (field.required) {
  5602. catalogVariable.setRequired(field.required);
  5603. }
  5604.  
  5605. if (field.multiSelect) {
  5606. catalogVariable.setMultiSelect(field.multiSelect);
  5607. }
  5608.  
  5609. return catalogVariable;
  5610. };
  5611.  
  5612. /**
  5613. * Legitimates variable name that is not qualified business rule validate_variable_name
  5614. * @param {String} varName
  5615. * @return {String}
  5616. */
  5617. SaraUtils.legitVarName = function (varName) {
  5618. var firstLegal = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5619. var firstLetter = varName.charAt(0);
  5620. if (firstLegal.indexOf(firstLetter) == -1) {
  5621. varName = 'v_' + varName;
  5622. }
  5623.  
  5624. var legal = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789';
  5625. for (var i = 0; i < varName.length; i++) {
  5626. var letter = varName.charAt(i);
  5627. if (legal.indexOf(letter) == -1) {
  5628. // replace illegal char with _
  5629. varName = varName.substr(0, i) + '_' + varName.substr(i + 1);
  5630. }
  5631. }
  5632.  
  5633. return varName;
  5634. };
  5635.  
  5636. /**
  5637. * Build url
  5638. * @param {String} url
  5639. * @return {String}
  5640. */
  5641. SaraUtils.buildUrl = function (url) {
  5642. if (!url) {
  5643. url = '';
  5644. }
  5645.  
  5646. var scheme;
  5647. var pattern = /^https?:\/\//i;
  5648. if (pattern.test(url)) {
  5649. scheme = 'absolute';
  5650. } else {
  5651. scheme = 'relative';
  5652. }
  5653.  
  5654. if (scheme === 'relative') {
  5655. var basePath = new SaraConfig().getBasePath();
  5656. if (basePath.charAt(basePath.length - 1) == '/' && url.substring(0, 1) == '/') {
  5657. return basePath + url.substring(1);
  5658. }
  5659.  
  5660. if (basePath.charAt(basePath.length - 1) != '/' && url.substring(0, 1) != '/') {
  5661. return basePath + '/' + url;
  5662. }
  5663.  
  5664. return basePath + url;
  5665. }
  5666.  
  5667. if (url == '/') {
  5668. return new SaraConfig().getBasePath();
  5669. }
  5670.  
  5671. return url;
  5672. };
  5673.  
  5674. /**
  5675. * Gets index of item in array
  5676. * @param {Array} array
  5677. * @param {*} item
  5678. * @return {Number}
  5679. */
  5680. SaraUtils.indexOf = function (array, item) {
  5681. for (var i = 0; i < array.length; ++i) {
  5682. if (array[i] === item) {
  5683. return i;
  5684. }
  5685. }
  5686.  
  5687. return -1;
  5688. };
  5689.  
  5690. /**
  5691. * Detects the array item is in array or not
  5692. * @param {Array} array
  5693. * @param {*} item
  5694. * @return {Boolean}
  5695. */
  5696. SaraUtils.inArray = function (array, item) {
  5697. return SaraUtils.indexOf(array, item) !== -1;
  5698. };
  5699.  
  5700. /**
  5701. * Get redirection endpoint of current instance
  5702. * @return {String} The redirection endpoint
  5703. */
  5704. SaraUtils.getRedirectionUrl = function () {
  5705. return gs.getProperty('glide.servlet.uri') + SaraCommon.SCOPED_APP + '_sara_oauth_callback.do';
  5706. };
  5707.  
  5708. SaraUtils.md5 = function (string, key, raw) {
  5709. /*
  5710. * JavaScript MD5 1.0.1
  5711. * https://github.com/blueimp/JavaScript-MD5
  5712. *
  5713. * Copyright 2011, Sebastian Tschan
  5714. * https://blueimp.net
  5715. *
  5716. * Licensed under the MIT license:
  5717. * http://www.opensource.org/licenses/MIT
  5718. *
  5719. * Based on
  5720. * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  5721. * Digest Algorithm, as defined in RFC 1321.
  5722. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
  5723. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  5724. * Distributed under the BSD License
  5725. * See http://pajhome.org.uk/crypt/md5 for more info.
  5726. */
  5727. /*jslint bitwise: true */
  5728. /*global unescape, define */
  5729.  
  5730. 'use strict';
  5731. /*
  5732. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  5733. * to work around bugs in some JS interpreters.
  5734. */
  5735. function safe_add(x, y) {
  5736. var lsw = (x & 0xFFFF) + (y & 0xFFFF),
  5737. msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  5738. return (msw << 16) | (lsw & 0xFFFF);
  5739. }
  5740. /*
  5741. * Bitwise rotate a 32-bit number to the left.
  5742. */
  5743. function bit_rol(num, cnt) {
  5744. return (num << cnt) | (num >>> (32 - cnt));
  5745. }
  5746. /*
  5747. * These functions implement the four basic operations the algorithm uses.
  5748. */
  5749. function md5_cmn(q, a, b, x, s, t) {
  5750. return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
  5751. }
  5752.  
  5753. function md5_ff(a, b, c, d, x, s, t) {
  5754. return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
  5755. }
  5756.  
  5757. function md5_gg(a, b, c, d, x, s, t) {
  5758. return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
  5759. }
  5760.  
  5761. function md5_hh(a, b, c, d, x, s, t) {
  5762. return md5_cmn(b ^ c ^ d, a, b, x, s, t);
  5763. }
  5764.  
  5765. function md5_ii(a, b, c, d, x, s, t) {
  5766. return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
  5767. }
  5768. /*
  5769. * Calculate the MD5 of an array of little-endian words, and a bit length.
  5770. */
  5771. function binl_md5(x, len) {
  5772. /* append padding */
  5773. x[len >> 5] |= 0x80 << (len % 32);
  5774. x[(((len + 64) >>> 9) << 4) + 14] = len;
  5775. var i, olda, oldb, oldc, oldd,
  5776. a = 1732584193,
  5777. b = -271733879,
  5778. c = -1732584194,
  5779. d = 271733878;
  5780. for (i = 0; i < x.length; i += 16) {
  5781. olda = a;
  5782. oldb = b;
  5783. oldc = c;
  5784. oldd = d;
  5785. a = md5_ff(a, b, c, d, x[i], 7, -680876936);
  5786. d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
  5787. c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
  5788. b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
  5789. a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
  5790. d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
  5791. c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
  5792. b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
  5793. a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
  5794. d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
  5795. c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
  5796. b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
  5797. a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
  5798. d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
  5799. c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
  5800. b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
  5801. a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
  5802. d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
  5803. c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
  5804. b = md5_gg(b, c, d, a, x[i], 20, -373897302);
  5805. a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
  5806. d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
  5807. c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
  5808. b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
  5809. a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
  5810. d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
  5811. c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
  5812. b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
  5813. a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
  5814. d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
  5815. c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
  5816. b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
  5817. a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
  5818. d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
  5819. c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
  5820. b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
  5821. a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
  5822. d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
  5823. c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
  5824. b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
  5825. a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
  5826. d = md5_hh(d, a, b, c, x[i], 11, -358537222);
  5827. c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
  5828. b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
  5829. a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
  5830. d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
  5831. c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
  5832. b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
  5833. a = md5_ii(a, b, c, d, x[i], 6, -198630844);
  5834. d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
  5835. c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
  5836. b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
  5837. a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
  5838. d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
  5839. c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
  5840. b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
  5841. a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
  5842. d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
  5843. c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
  5844. b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
  5845. a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
  5846. d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
  5847. c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
  5848. b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
  5849. a = safe_add(a, olda);
  5850. b = safe_add(b, oldb);
  5851. c = safe_add(c, oldc);
  5852. d = safe_add(d, oldd);
  5853. }
  5854. return [a, b, c, d];
  5855. }
  5856. /*
  5857. * Convert an array of little-endian words to a string
  5858. */
  5859. function binl2rstr(input) {
  5860. var i,
  5861. output = '';
  5862. for (i = 0; i < input.length * 32; i += 8) {
  5863. output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF);
  5864. }
  5865. return output;
  5866. }
  5867. /*
  5868. * Convert a raw string to an array of little-endian words
  5869. * Characters >255 have their high-byte silently ignored.
  5870. */
  5871. function rstr2binl(input) {
  5872. var i,
  5873. output = [];
  5874. output[(input.length >> 2) - 1] = undefined;
  5875. for (i = 0; i < output.length; i += 1) {
  5876. output[i] = 0;
  5877. }
  5878. for (i = 0; i < input.length * 8; i += 8) {
  5879. output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32);
  5880. }
  5881. return output;
  5882. }
  5883. /*
  5884. * Calculate the MD5 of a raw string
  5885. */
  5886. function rstr_md5(s) {
  5887. return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
  5888. }
  5889. /*
  5890. * Calculate the HMAC-MD5, of a key and some data (raw strings)
  5891. */
  5892. function rstr_hmac_md5(key, data) {
  5893. var i,
  5894. bkey = rstr2binl(key),
  5895. ipad = [],
  5896. opad = [],
  5897. hash;
  5898. ipad[15] = opad[15] = undefined;
  5899. if (bkey.length > 16) {
  5900. bkey = binl_md5(bkey, key.length * 8);
  5901. }
  5902. for (i = 0; i < 16; i += 1) {
  5903. ipad[i] = bkey[i] ^ 0x36363636;
  5904. opad[i] = bkey[i] ^ 0x5C5C5C5C;
  5905. }
  5906. hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
  5907. return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
  5908. }
  5909. /*
  5910. * Convert a raw string to a hex string
  5911. */
  5912. function rstr2hex(input) {
  5913. var hex_tab = '0123456789abcdef',
  5914. output = '',
  5915. x,
  5916. i;
  5917. for (i = 0; i < input.length; i += 1) {
  5918. x = input.charCodeAt(i);
  5919. output += hex_tab.charAt((x >>> 4) & 0x0F) +
  5920. hex_tab.charAt(x & 0x0F);
  5921. }
  5922. return output;
  5923. }
  5924. /*
  5925. * Encode a string as utf-8
  5926. */
  5927. function str2rstr_utf8(input) {
  5928. return unescape(encodeURIComponent(input));
  5929. }
  5930. /*
  5931. * Take string arguments and return either raw or hex encoded strings
  5932. */
  5933. function raw_md5(s) {
  5934. return rstr_md5(str2rstr_utf8(s));
  5935. }
  5936.  
  5937. function hex_md5(s) {
  5938. return rstr2hex(raw_md5(s));
  5939. }
  5940.  
  5941. function raw_hmac_md5(k, d) {
  5942. return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d));
  5943. }
  5944.  
  5945. function hex_hmac_md5(k, d) {
  5946. return rstr2hex(raw_hmac_md5(k, d));
  5947. }
  5948.  
  5949. if (!key) {
  5950. if (!raw) {
  5951. return hex_md5(string);
  5952. }
  5953. return raw_md5(string);
  5954. }
  5955. if (!raw) {
  5956. return hex_hmac_md5(key, string);
  5957. }
  5958.  
  5959. return raw_hmac_md5(key, string);
  5960. };
  5961. ]]></script>
  5962. <description>Sara Utilities</description>
  5963. <active>true</active>
  5964. <client_callable>false</client_callable>
  5965. <access>public</access>
  5966. </script_include>
  5967.  
  5968. <script_include>
  5969. <name>SaraTestBench</name>
  5970. <script><![CDATA[/*
  5971. Test bench for Sara Scripts
  5972. Create manually in scope of Automic SNSC
  5973. Use background script to execute:
  5974.  
  5975. var test = new SaraTestBench();
  5976. test.execute();
  5977. */
  5978. var SaraTestBench = Class.create();
  5979. SaraTestBench.prototype = {
  5980. initialize: function () {
  5981. },
  5982.  
  5983. execute: function(){
  5984. SaraTest.resetSummary();
  5985. SaraTransformMapTest.testPersistCatalog();
  5986. SaraTransformMapTest.testPersistCategory();
  5987. SaraTransformMapTest.testPersistCatalogItem();
  5988. SaraTransformMapTest.testPersistVariableSet();
  5989. SaraTransformMapTest.testPersistCatelogVariableSet();
  5990. var summary = SaraTest.getSummary();
  5991. gs.info("=======================================================================================");
  5992. gs.info("SUMMARY");
  5993. gs.info("=======================================================================================");
  5994. gs.info("------ TOTAL: " + summary.total);
  5995. gs.info("------ PASS: " + summary.pass);
  5996. gs.info("------ FAIL: " + summary.fail);
  5997. gs.info("------ IGNORE: " + summary.ignore);
  5998. }
  5999. };
  6000.  
  6001. var SaraTransformMapTest = (function(){
  6002. var logger = new SaraLog("SaraGlideHelperTest");
  6003. var glideHelper = new SaraGlideHelper();
  6004.  
  6005. var catalogId = glideHelper.getSysId("sc_catalog", {title: "Service Catalog"});
  6006. gs.info("catelog id: " + catalogId);
  6007.  
  6008. var getCategory = function(title) {
  6009. return glideHelper.getData("sc_category", {title: title });
  6010. };
  6011.  
  6012. var deleteCategory = function(title, deleteAll) {
  6013. glideHelper.deleteData("sc_category", {title: title },deleteAll);
  6014. glideHelper.deleteData("x_ausgh_snsc_sc_category_ist", {title: title },deleteAll);
  6015. }
  6016.  
  6017. var createCategory = function(title, active, description, parent) {
  6018. glideHelper.persistData("x_ausgh_snsc_sc_category_ist", {
  6019. title: title,
  6020. active: active,
  6021. description: description,
  6022. parent: parent,
  6023. sc_catalog: catalogId
  6024. });
  6025. }
  6026. return {
  6027. testPersistCatalog: function() {
  6028. var catalogName = "snsc test catalog";
  6029. glideHelper.deleteData("sc_catalog", {"title": catalogName});
  6030.  
  6031. SaraTest.test("Persist catalog via Importset", function() {
  6032. glideHelper.persistData("x_ausgh_snsc_sc_catalog_ist", {
  6033. title: catalogName,
  6034. description: "test description",
  6035. active: "true"
  6036. });
  6037.  
  6038. var catalog = glideHelper.getData("sc_catalog", {"title": catalogName});
  6039.  
  6040. SaraTest.assert(catalog !== null, "catalog is transformed correctly");
  6041. SaraTest.assert(catalog.title === catalogName, "catalog title is transformed correctly");
  6042. SaraTest.assert(catalog.description === "test description", "catalog description is transformed correctly");
  6043. gs.info("active: " + catalog.active);
  6044. SaraTest.assert(catalog.active, "catalog active is transformed correctly");
  6045. });
  6046.  
  6047. SaraTest.test("Update catalog via Importset", function() {
  6048. glideHelper.persistData("x_ausgh_snsc_sc_catalog_ist", {
  6049. title: catalogName,
  6050. description: "new test description description",
  6051. active: "false"
  6052. });
  6053.  
  6054. var catalog = glideHelper.getData("sc_catalog", {"title": catalogName});
  6055.  
  6056. SaraTest.assert(catalog !== null, "catalog is transformed correctly");
  6057. SaraTest.assert(catalog.description === "new test description description", "catalog description is updated correctly");
  6058. gs.info("active: " + catalog.active);
  6059. SaraTest.assert(catalog.active == "false", "catalog active is updated correctly");
  6060. });
  6061. },
  6062.  
  6063. testPersistCategory: function() {
  6064. var categoryName1 = "snsc test catagory";
  6065. var categoryName2 = "snsc test sub catagory";
  6066. deleteCategory(categoryName1, true);
  6067. deleteCategory(categoryName2, true);
  6068.  
  6069. SaraTest.test("Persist category via Importset", function() {
  6070. var category = getCategory(categoryName1);
  6071. SaraTest.assert(category === null, "category must not exists");
  6072. var category2 = getCategory(categoryName2);
  6073. SaraTest.assert(category2 === null, "sub category must not exists");
  6074.  
  6075. createCategory(categoryName1,true,"test description", null);
  6076. category = getCategory(categoryName1);
  6077. gs.info(SaraJSON.stringify(category));
  6078. SaraTest.assert(category !== null, "Category ImportSet should be transform to category table");
  6079. SaraTest.assert(category.title === categoryName1, "Assert title transform correctly");
  6080.  
  6081. //create via importset table
  6082. createCategory(categoryName2,true,"test sub description", category.sys_id);
  6083. //get real data
  6084. category2 = getCategory(categoryName2);
  6085. SaraTest.assert(category2 !== null, "Sub category ImportSet should be transform to category table");
  6086. SaraTest.assert(category2.title === categoryName2, "Assert title transform correctly");
  6087.  
  6088. var parent = glideHelper.getData("sc_category", {sys_id:category2.parent});
  6089. SaraTest.assert(parent !== null, "Assert parent transform correctly");
  6090. SaraTest.assert(parent.title === categoryName1, "Assert parent transform correctly");
  6091. });
  6092.  
  6093. SaraTest.test("Save category with same name but different parent should create new category", function() {
  6094. //create another category with different parent and assert that new item is
  6095. //inserted to target table
  6096. gs.info("create another record with name " + categoryName2);
  6097. createCategory(categoryName2,true,"test description 2");
  6098. var records = glideHelper.getData("sc_category", {title:categoryName2}, true);
  6099. SaraTest.assert(records.length === 2, "new category is created");
  6100. });
  6101. },
  6102.  
  6103. testPersistCatalogItem: function() {
  6104. var gh = glideHelper;
  6105. var name = "snsc sample catelog item" + SaraUtils.getRandom();
  6106. gs.info("catelog item name: " + name);
  6107. var description = "whatever";
  6108. var short_description = "short descriprion";
  6109. var categoryName = "snsc item category";
  6110. var category = null;
  6111.  
  6112. SaraTest.test("Persist catalog item via Importset", function(){
  6113. //prepare data
  6114. deleteCategory(categoryName, true);
  6115. createCategory(categoryName, true, "");
  6116. category = getCategory(categoryName);
  6117. gs.info("category id: " + category.sys_id);
  6118. SaraTest.assert(category != null, "category is created successfully");
  6119.  
  6120. gh.persistData("x_ausgh_snsc_sc_cat_item_ist", {
  6121. name: name,
  6122. description: description,
  6123. short_description: short_description,
  6124. use_sc_layout: true,
  6125. no_quantity: true,
  6126. category: category.sys_id,
  6127. active: true
  6128. });
  6129. var item = gh.getData("sc_cat_item", {name: name});
  6130. SaraTest.assert(item.name === name, "item is transformed correctly");
  6131. SaraTest.assert(item.description === description, "description is transformed correctly");
  6132. SaraTest.assert(item.short_description === short_description, "short_description is transformed correctly");
  6133. SaraTest.assert(item.use_sc_layout == "true", "use_sc_layout is transformed correctly");
  6134. SaraTest.assert(item.no_quantity == "true", "no_quantity is transformed correctly");
  6135. SaraTest.assert(item.active == "true", "active is transformed correctly");
  6136. SaraTest.assert(item.category === category.sys_id, "category is transformed correctly");
  6137. });
  6138.  
  6139. SaraTest.test("Catalog item same name different category should create new", function() {
  6140. var newCategoryName = categoryName + SaraUtils.getRandom();
  6141. createCategory(newCategoryName, true, "");
  6142. var newCat = getCategory(newCategoryName);
  6143. gs.info("new category id: " + newCat.sys_id);
  6144. gh.persistData("x_ausgh_snsc_sc_cat_item_ist", {
  6145. name: name,
  6146. description: "new description",
  6147. short_description: "new short description",
  6148. use_sc_layout: false,
  6149. no_quantity: false,
  6150. category: newCat.sys_id,
  6151. active: false
  6152. });
  6153.  
  6154. var records = gh.getData("sc_cat_item", {name: name}, true);
  6155. SaraTest.assert(records.length === 2, "new item is created");
  6156. });
  6157.  
  6158. SaraTest.test("Update catalog item via Importset", function(){
  6159. gh.persistData("x_ausgh_snsc_sc_cat_item_ist", {
  6160. name: name,
  6161. description: "new description",
  6162. short_description: "new short description",
  6163. use_sc_layout: false,
  6164. no_quantity: false,
  6165. category: category.sys_id,
  6166. active: false
  6167. });
  6168. var item = gh.getData("sc_cat_item", {name: name, category: category.sys_id});
  6169. SaraTest.assert(item.name === name, "item is transformed correctly");
  6170. SaraTest.assert(item.description === "new description", "description is transformed correctly");
  6171. SaraTest.assert(item.short_description === "new short description", "short_description is transformed correctly");
  6172. SaraTest.assert(item.use_sc_layout == "false", "use_sc_layout is transformed correctly");
  6173. SaraTest.assert(item.no_quantity == "false", "no_quantity is transformed correctly");
  6174. SaraTest.assert(item.active == "false", "active is transformed correctly");
  6175. SaraTest.assert(item.category === category.sys_id, "category is transformed correctly");
  6176. });
  6177. },
  6178.  
  6179. testPersistVariableSet: function() {
  6180. var varSetName = "snsc test variable set " + SaraUtils.getRandom();
  6181. var varSetTitle = "title";
  6182. var varSetDescription = "test description";
  6183. var varSetDisplayName = "display name";
  6184.  
  6185. var varSetTitleNew = "title new";
  6186. var varSetDescriptionNew = "test description new";
  6187. var varSetDisplayNameNew = "display name new";
  6188.  
  6189. glideHelper.deleteData("item_option_new_set", {"name": ["CONTAINS", "snsc test"]}, true);
  6190.  
  6191. SaraTest.test("Persist variable set via Importset", function() {
  6192. glideHelper.persistData("x_ausgh_snsc_item_option_new_set_ist", {
  6193. name: varSetName,
  6194. title: varSetTitle,
  6195. description: varSetDescription,
  6196. sys_name: varSetDisplayName
  6197. });
  6198.  
  6199. var varSet = glideHelper.getData("item_option_new_set", {"name": varSetName});
  6200.  
  6201. SaraTest.assert(varSet !== null, "varSet is transformed correctly");
  6202. SaraTest.assert(varSet.name === varSetName, "var set name is transformed correctly");
  6203. SaraTest.assert(varSet.title === varSetTitle, "var set title is transformed correctly");
  6204. SaraTest.assert(varSet.description === varSetDescription, "var set description is transformed correctly");
  6205. SaraTest.assert(varSet.sys_name === varSetDisplayName, "var set display name is transformed correctly");
  6206. });
  6207.  
  6208. SaraTest.test("Update var set via Importset", function() {
  6209. glideHelper.persistData("x_ausgh_snsc_item_option_new_set_ist", {
  6210. name: varSetName,
  6211. title: varSetTitleNew,
  6212. description: varSetDescriptionNew
  6213. });
  6214.  
  6215. var varSet = glideHelper.getData("item_option_new_set", {"name": varSetName});
  6216.  
  6217. SaraTest.assert(varSet !== null, "varSet is transformed correctly");
  6218. SaraTest.assert(varSet.name === varSetName, "var set name is transformed correctly");
  6219. SaraTest.assert(varSet.title === varSetTitleNew, "var set title is updated correctly");
  6220. SaraTest.assert(varSet.description === varSetDescriptionNew, "var set description is updated correctly");
  6221. });
  6222. },
  6223.  
  6224. testPersistCatelogVariableSet : function() {
  6225. var varSetName = "snsc test variable set " + SaraUtils.getRandom();
  6226. var varSetTitle = "title";
  6227. var varSetDescription = "test description";
  6228. var varSetDisplayName = "display name";
  6229.  
  6230. var newCategoryName = "snsc category " + SaraUtils.getRandom();
  6231.  
  6232. var catItemName = "snsc cat item " + SaraUtils.getRandom();
  6233.  
  6234. var gh = glideHelper;
  6235.  
  6236. gh.deleteData("item_option_new_set", {"name": ["CONTAINS", "snsc test"]}, true);
  6237.  
  6238. SaraTest.test("Persist catalog variable set via Importset", function() {
  6239. gh.persistData("x_ausgh_snsc_item_option_new_set_ist", {
  6240. name: varSetName,
  6241. title: varSetTitle,
  6242. description: varSetDescription,
  6243. display_name: varSetDisplayName
  6244. });
  6245.  
  6246. var varSet = glideHelper.getData("item_option_new_set", {"name": varSetName});
  6247.  
  6248. SaraTest.assert(varSet !== null, "varSet is transformed correctly");
  6249.  
  6250. createCategory(newCategoryName);
  6251. var newCat = getCategory(newCategoryName);
  6252.  
  6253. gs.info("new category id: " + newCat.sys_id);
  6254.  
  6255. gh.persistData("x_ausgh_snsc_sc_cat_item_ist", {
  6256. name: catItemName,
  6257. description: "new description",
  6258. short_description: "new short description",
  6259. use_sc_layout: true,
  6260. no_quantity: true,
  6261. category: newCat.sys_id,
  6262. active: true
  6263. });
  6264.  
  6265. var catItem = gh.getData("sc_cat_item", {name: catItemName, category: newCat.sys_id});
  6266. SaraTest.assert(catItem != null, "cat item is created successfully");
  6267.  
  6268. //link item and varset via import set
  6269. gh.persistData("x_ausgh_snsc_io_set_item_ist", {sc_cat_item: catItem.sys_id, variable_set: varSet.sys_id});
  6270. //get real
  6271. var catVarSet = gh.getData("io_set_item", {sc_cat_item: catItem.sys_id, variable_set: varSet.sys_id});
  6272.  
  6273. SaraTest.assert(catVarSet !== null, "catalog item variable is created correctly");
  6274. SaraTest.assert(catVarSet.sc_cat_item === catItem.sys_id, "cat item is set correctly");
  6275. SaraTest.assert(catVarSet.varSet === varSet.sys_id, "var set is persisted correctly");
  6276. });
  6277. }
  6278. };
  6279. })();
  6280.  
  6281. var SaraTest = (function() {
  6282. var indent = "";
  6283. var logger = new SaraLog("SaraTest");
  6284. var pass = 0;
  6285. var fail = 0;
  6286. var isIgnore = false;
  6287. var ignored = 0;
  6288.  
  6289. var log = function() {
  6290. logger.info.apply(logger,arguments);
  6291. };
  6292.  
  6293. return {
  6294. resetSummary: function() {
  6295. pass = 0;
  6296. fail = 0;
  6297. ignored = 0;
  6298. },
  6299.  
  6300. getSummary: function() {
  6301. return {
  6302. pass: pass,
  6303. fail: fail,
  6304. ignore: ignored,
  6305. total: pass + fail + ignored
  6306. };
  6307. },
  6308.  
  6309. ignore: function() {
  6310. isIgnore = true;
  6311. },
  6312.  
  6313. assert: function(value, desc) {
  6314. var prefix = ">>>PASS: ";
  6315. if(!value) {
  6316. prefix = "<<<FAIL: ";
  6317. };
  6318. logger.info("{0}{1}{2}", indent, prefix, desc);
  6319. if(!value) {
  6320. var exceptionMsg = prefix + desc;
  6321. throw new Error(exceptionMsg);
  6322. }
  6323. },
  6324. test: function(name, fn) {
  6325. indent = "";
  6326. logger.info("********************************");
  6327. if(isIgnore) {
  6328. logger.info("[IGNORE] {0}", name);
  6329. isIgnore = false;
  6330. ignored++;
  6331. return;
  6332. }
  6333. logger.info("[TEST CASE] {0}", name);
  6334. indent = " ";
  6335. try {
  6336. fn();
  6337. pass++;
  6338. }
  6339. catch(err) {
  6340. gs.error(err);
  6341. fail++;
  6342. }
  6343.  
  6344. indent = "";
  6345. },
  6346. type: "SaraTest"
  6347. };
  6348. })();
  6349. ]]></script>
  6350. <description>Sara Test Bench</description>
  6351. <active>true</active>
  6352. <client_callable>false</client_callable>
  6353. <access>public</access>
  6354. </script_include>
  6355. </script_includes>
  6356.  
  6357.  
  6358. <ui_scripts>
  6359. <ui_script>
  6360. <script_name>SaraVarSet</script_name>
  6361. <script><![CDATA[/**
  6362. * Catalog client script for SaraVariableSet
  6363. */
  6364. var x_ausgh_snsc = x_ausgh_snsc || {};
  6365. x_ausgh_snsc.SaraVarSet = x_ausgh_snsc.SaraVarSet || {};
  6366.  
  6367. (function (SaraVarSet) {
  6368. 'use strict';
  6369.  
  6370. /**
  6371. * OnLoad event handler for Sara variable set
  6372. */
  6373. SaraVarSet.onLoad = function () {
  6374. SaraVarSet.initListCollector();
  6375. SaraVarSet.setSelectBoxWidth();
  6376. };
  6377.  
  6378. /**
  6379. * Init collector filter
  6380. */
  6381. SaraVarSet.initListCollector = function () {
  6382. x_ausgh_snsc.log('Start: SaraVarSet.initListCollector');
  6383. var messageTables = $$('[id$=_select_0_add_remove_message_table]');
  6384. var listWrappers = $$('.list_name');
  6385.  
  6386. for (var i = 0, table; table = messageTables[i]; i++) {
  6387. var name = table.id.replace('_select_0_add_remove_message_table', '');
  6388. var wrapper = listWrappers[i];
  6389. var target;
  6390. var id;
  6391.  
  6392. if (wrapper) {
  6393. target = wrapper;
  6394. } else {
  6395. target = table;
  6396. }
  6397.  
  6398. id = target.nextSibling.id.replace('IO:', '');
  6399.  
  6400. SaraVarSet.getListCollectorData(id, name);
  6401. }
  6402.  
  6403. x_ausgh_snsc.log('End: SaraVarSet.initListCollector');
  6404. };
  6405.  
  6406. /**
  6407. * Get list collector data from lookup table
  6408. * @param {String} id The sys_id of list collector
  6409. * @param {String} name The name of list collector
  6410. */
  6411. SaraVarSet.getListCollectorData = function (id, name) {
  6412. var filterFn = name + 'g_filter';
  6413. var acRequestFn = name + 'acRequest';
  6414.  
  6415. if (window[filterFn] === undefined || window[acRequestFn] === undefined) {
  6416. setTimeout(function () {
  6417. SaraVarSet.getListCollectorData(id, name);
  6418. }, 100);
  6419. return;
  6420. }
  6421.  
  6422. window[filterFn].reset();
  6423. window[filterFn].setQuery('u_control_id=' + id);
  6424. window[acRequestFn](null);
  6425. };
  6426.  
  6427. /**
  6428. * Make all selecbox's width is 250px for preventing the broken of layout when value of option is too long
  6429. */
  6430. SaraVarSet.setSelectBoxWidth = function () {
  6431. x_ausgh_snsc.log('Start: SaraVarSet.setSelectBoxWidth');
  6432. var selectboxes = $$('select.cat_item_option');
  6433.  
  6434. for (var i = 0, selectbox; selectbox = selectboxes[i]; i++) {
  6435. selectbox.style.width = '250px';
  6436. }
  6437.  
  6438. x_ausgh_snsc.log('End: SaraVarSet.setSelectBoxWidth');
  6439. };
  6440.  
  6441. })(x_ausgh_snsc.SaraVarSet);
  6442. ]]></script>
  6443. <description>Catalog client script for SaraVariableSet</description>
  6444. <active>true</active>
  6445. <global>false</global>
  6446. </ui_script>
  6447. <ui_script>
  6448. <script_name>SaraCommon</script_name>
  6449. <script><![CDATA[/**
  6450. * Common client properties for Sara
  6451. */
  6452. var SaraCommon = SaraCommon || {};
  6453.  
  6454. var x_ausgh_snsc = x_ausgh_snsc || {};
  6455. x_ausgh_snsc.SaraCommon = x_ausgh_snsc.SaraCommon || {};
  6456.  
  6457. x_ausgh_snsc.log = function () {
  6458. if (typeof (console) !== 'undefined') {
  6459. if (navigator.appName === 'Microsoft Internet Explorer') {
  6460. if (arguments.length == 1) {
  6461. console.log('[SARA]', arguments[0]);
  6462. } else if (arguments.length === 2) {
  6463. console.log('[SARA]', arguments[0], arguments[1]);
  6464. } else if (arguments.length > 2) {
  6465. console.log('[SARA]', arguments[0], arguments[1], arguments[2]);
  6466. }
  6467. } else {
  6468. console.log('[SARA]', arguments);
  6469. }
  6470. }
  6471. };
  6472.  
  6473. x_ausgh_snsc.config = x_ausgh_snsc.config || {};
  6474.  
  6475. (function (SaraCommon) {
  6476. 'use strict';
  6477.  
  6478. SaraCommon.SCOPED_APP = 'x_ausgh_snsc';
  6479.  
  6480. SaraCommon.CONFIG_NAME = {
  6481. CLIENT_ID: 'client_id',
  6482. CLIENT_SECRET: 'client_secret',
  6483. TECHNICAL_USER: 'technical_user',
  6484. SAPI_ENDPOINT: 'sapi_endpoint',
  6485. TOKEN_ENDPOINT: 'token_endpoint',
  6486. AUTH_ENDPOINT: 'auth_endpoint'
  6487. };
  6488.  
  6489. SaraCommon.CONTROL_NAME = {
  6490. CLIENT_SCRIPTS: 'sara_client_scripts',
  6491. HIDDEN_CONTROL: 'sara_hidden_control'
  6492. };
  6493.  
  6494. })(x_ausgh_snsc.SaraCommon);
  6495. ]]></script>
  6496. <description>Common client properties for Sara</description>
  6497. <active>true</active>
  6498. <global>false</global>
  6499. </ui_script>
  6500. <ui_script>
  6501. <script_name>SaraOAuth</script_name>
  6502. <script><![CDATA[/**
  6503. * Client script for OAuth integration
  6504. */
  6505. var x_ausgh_snsc = x_ausgh_snsc || {};
  6506. x_ausgh_snsc.SaraOAuth = x_ausgh_snsc.SaraOAuth || {};
  6507.  
  6508. (function (SaraOAuth) {
  6509. 'use strict';
  6510.  
  6511. /**
  6512. * Login to OAuth server for authentication
  6513. * @param {String} clientId The client ID of OAuth Server
  6514. * @param {String} technicalUser The tecnical user who owns the tokens
  6515. * @param {String} authEndpoint The authorization endpoint of OAuth Server
  6516. * @param {Object} callback The callback object contains onSuccess and onFail handler
  6517. */
  6518. SaraOAuth.login = function (clientId, technicalUser, authEndpoint, callback) {
  6519. if (confirm('Technical User does not have tokens or Technical User\'s tokens are empty, invalid or expired. Do you want to open OAuth Authorization popup for getting new tokens?')) {
  6520. SaraOAuth.processSuccess = null;
  6521. SaraOAuth.processFail = null;
  6522.  
  6523. if (SaraOAuth.win) {
  6524. SaraOAuth.win.close();
  6525. }
  6526. SaraOAuth.win = null;
  6527.  
  6528. var ga = new x_ausgh_snsc.SaraGlideAjax('SaraOAuthAjax', 'Getting OAuth url...');
  6529. ga.addParam('sysparm_name', 'getOAuthUrl');
  6530. ga.addParam('sysparm_client_id', clientId);
  6531. ga.addParam('sysparm_technical_user', technicalUser);
  6532. ga.addParam('sysparm_auth_endpoint', authEndpoint);
  6533. ga.getXML(function (response) {
  6534. if (callback && callback.onSuccess && typeof (callback.onSuccess) == 'function') {
  6535. SaraOAuth.processSuccess = callback.onSuccess;
  6536. }
  6537.  
  6538. if (callback && callback.onFail && typeof (callback.onFail) == 'function') {
  6539. SaraOAuth.processFail = callback.onFail;
  6540. }
  6541.  
  6542. var w = 500;
  6543. var h = 600;
  6544.  
  6545. var left = (screen.width / 2) - (w / 2);
  6546. var top = (screen.height / 2) - (h / 2);
  6547.  
  6548. var url = response.responseXML.documentElement.getAttribute('answer');
  6549. SaraOAuth.win = window.open(url, 'aelogin', 'width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
  6550. });
  6551. }
  6552. };
  6553.  
  6554. /**
  6555. * Process response from OAuth server. If is 'ok', will call SaraOAuth.processSuccess callback.
  6556. * If is not 'ok', will log the answer and alert message.
  6557. * @param {*} response The response
  6558. */
  6559. SaraOAuth.processResponse = function (response) {
  6560. if (SaraOAuth.win) {
  6561. SaraOAuth.win.close();
  6562. }
  6563.  
  6564. x_ausgh_snsc.log('Callback response is: ' + response);
  6565.  
  6566. if (response === 'ok') {
  6567. if (SaraOAuth.processSuccess && typeof (SaraOAuth.processSuccess) == 'function') {
  6568. SaraOAuth.processSuccess();
  6569. }
  6570. } else {
  6571. var msg;
  6572.  
  6573. if (typeof (response) == 'string' && response.match('^function') != 'function') {
  6574. msg = x_ausgh_snsc.SaraUtils.formatString('Token request finished unsuccessfully{0}. Please try again later or contact administrators.', response ? (', error: ' + response) : '');
  6575. } else {
  6576. msg = 'Token request finished unsuccessfully! Please try again later or contact administrators.';
  6577. }
  6578.  
  6579. alert(msg);
  6580.  
  6581. if (SaraOAuth.processFail && typeof (SaraOAuth.processFail) == 'function') {
  6582. SaraOAuth.processFail();
  6583. }
  6584.  
  6585. x_ausgh_snsc.log(msg);
  6586. }
  6587. };
  6588.  
  6589. /**
  6590. * Get configuration
  6591. * @param {Function} callback The callback will be called when getting configuration
  6592. * successfully with parametter is object with same keys with x_ausgh_snsc.SaraCommon.CONFIG_NAME
  6593. */
  6594. SaraOAuth.getConfig = function (callback) {
  6595. var configData = {};
  6596. var ga = new x_ausgh_snsc.SaraGlideAjax('SaraOAuthAjax', 'Getting OAuth configuration...');
  6597. ga.addParam('sysparm_name', 'getConfig');
  6598.  
  6599. ga.getXML(function (resp) {
  6600. var config = resp.responseXML.getElementsByTagName('config')[0];
  6601.  
  6602. for (var key in x_ausgh_snsc.SaraCommon.CONFIG_NAME) {
  6603. var name = x_ausgh_snsc.SaraCommon.CONFIG_NAME[key];
  6604.  
  6605. configData[name] = config.getAttribute(name);
  6606. }
  6607.  
  6608. callback.call(this, configData);
  6609. });
  6610. };
  6611.  
  6612. /**
  6613. * Check OAuth Token of current technical user is invalid, expired or empty
  6614. * @param {String} technicalUser The tecnical user who owns the tokens
  6615. * @param {String} sapiEndpoint The SAPI endpoint
  6616. * @param {Boolean} hideWizardSubmit Hide submit button of wizard or not when token is empty, expired
  6617. * or invalid
  6618. * @param {Object<String, Function>} callback The callback object contains callbacks when valid,
  6619. * invalid, error:
  6620. * - onValid(); // Will be called when tokens are existed and valid.
  6621. * - onInvalid(); // Will be called when tokens are existed but invalid.
  6622. * - onError(errorMessage); // Will be called when have any error. 'errorMessage' is error message
  6623. * - onExisted(); // Will be called if current technical user has tokens but not validate the token yet.
  6624. * SaraCommon.TABLE_NAME.SARA_OAUTH table
  6625. */
  6626. SaraOAuth.checkOAuthToken = function (technicalUser, sapiEndpoint, hideWizardSubmit, callback) {
  6627. x_ausgh_snsc.log('checkOAuthToken', technicalUser, sapiEndpoint, hideWizardSubmit, callback);
  6628.  
  6629. var ga = new x_ausgh_snsc.SaraGlideAjax('SaraOAuthAjax', 'Validating token...');
  6630. ga.addParam('sysparm_name', 'validateToken');
  6631. ga.addParam('sysparm_technical_user', technicalUser);
  6632. ga.addParam('sysparm_sapi_endpoint', sapiEndpoint);
  6633.  
  6634. ga.getXML(function (resp) {
  6635. var result = resp.responseXML.getElementsByTagName('result')[0];
  6636.  
  6637. if (result) {
  6638. var isValid = result.getAttribute('isValid');
  6639.  
  6640. // Valid
  6641. if (isValid === 'true') {
  6642. if (hideWizardSubmit) {
  6643. x_ausgh_snsc.SaraUtils.setWizardSubmitVisible(true);
  6644. }
  6645.  
  6646. x_ausgh_snsc.log('Access token is valid');
  6647.  
  6648. if (typeof callback.onValid === 'function') {
  6649. callback.onValid.call(this);
  6650. }
  6651.  
  6652. // Invalid
  6653. } else if (isValid === 'false') {
  6654. if (hideWizardSubmit) {
  6655. x_ausgh_snsc.SaraUtils.setWizardSubmitVisible(false);
  6656. }
  6657.  
  6658. x_ausgh_snsc.log('Access token is invalid');
  6659.  
  6660. if (typeof callback.onInvalid === 'function') {
  6661. callback.onInvalid.call(this);
  6662. }
  6663.  
  6664. // Error
  6665. } else {
  6666. var errorMessage = result.getAttribute('message');
  6667. x_ausgh_snsc.log(errorMessage);
  6668.  
  6669.  
  6670. if (typeof callback.onError === 'function') {
  6671. callback.onError.call(this, errorMessage);
  6672. }
  6673. }
  6674. } else {
  6675. var error = resp.responseXML.getElementsByTagName('error')[0];
  6676. var errorMessage;
  6677.  
  6678. if (error) {
  6679. errorMessage = error.getAttribute('message');
  6680. }
  6681.  
  6682. if (typeof callback.onError === 'function') {
  6683. callback.onError.call(this, errorMessage);
  6684. }
  6685. }
  6686. });
  6687. };
  6688.  
  6689. })(x_ausgh_snsc.SaraOAuth);
  6690. ]]></script>
  6691. <description>Client script for OAuth integration</description>
  6692. <active>true</active>
  6693. <global>false</global>
  6694. </ui_script>
  6695. <ui_script>
  6696. <script_name>SaraUtils</script_name>
  6697. <script><![CDATA[/**
  6698. * Sara Utilities
  6699. */
  6700. var x_ausgh_snsc = x_ausgh_snsc || {};
  6701. x_ausgh_snsc.SaraUtils = x_ausgh_snsc.SaraUtils || {};
  6702.  
  6703. (function (SaraUtils) {
  6704. 'use strict';
  6705.  
  6706. /**
  6707. * Format strings
  6708. * @method format
  6709. * @param {String} string The template string
  6710. * @param {String[]} args Zero or more objects to format, supplied either in a comma-delimited list or as an array
  6711. */
  6712. SaraUtils.formatString = function (string) {
  6713. var args = Array.prototype.slice.call(arguments, 1);
  6714.  
  6715. return string.replace(/{(\d+)}/g, function (match, number) {
  6716. return typeof args[number] != 'undefined' ? args[number] : match;
  6717. });
  6718. };
  6719.  
  6720. /**
  6721. * Get parameter value in current URL
  6722. * @param {String} name The name of parameter
  6723. * @return {String}
  6724. */
  6725. SaraUtils.getParmVal = function (name) {
  6726. name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
  6727. var regexS = '[\\?&]' + name + '=([^&#]*)';
  6728. var regex = new RegExp(regexS);
  6729. var results = regex.exec(window.location.href);
  6730.  
  6731. if (results == null) {
  6732. return '';
  6733. } else {
  6734. return unescape(results[1]);
  6735. }
  6736. };
  6737.  
  6738. /**
  6739. * Hide/show submit button of wizard
  6740. * @param {Boolean} isVisible Submit button is visible or not
  6741. */
  6742. SaraUtils.setWizardSubmitVisible = function (isVisible) {
  6743. document.getElementById('expert_next').style.display = isVisible ? '' : 'none';
  6744. };
  6745.  
  6746. /**
  6747. * Set visible of a form control
  6748. * @param {String} name Name of control
  6749. * @param {Boolean} isVisible Control is hidden or visible
  6750. */
  6751. SaraUtils.setFormControlVisible = function (name, isVisible) {
  6752. if (g_form) {
  6753. g_form.setDisplay(name, isVisible);
  6754. }
  6755. }
  6756.  
  6757. })(x_ausgh_snsc.SaraUtils);
  6758. ]]></script>
  6759. <description>Sara Utilities</description>
  6760. <active>true</active>
  6761. <global>false</global>
  6762. </ui_script>
  6763. <ui_script>
  6764. <script_name>SaraGlideAjax</script_name>
  6765. <script><![CDATA[/**
  6766. * Helper class wraps GlideAjax class of ServiceNow and provide Loading Dialog with custom title
  6767. */
  6768. var x_ausgh_snsc = x_ausgh_snsc || {};
  6769. x_ausgh_snsc.SaraGlideAjax = x_ausgh_snsc.SaraGlideAjax || Class.create();
  6770.  
  6771. (function (SaraGlideAjax) {
  6772. 'use strict';
  6773.  
  6774. SaraGlideAjax.prototype = {
  6775. /**
  6776. * Initialize SaraGlideAjax
  6777. * @param {String} className The class name of callable Script Include
  6778. * @param {String} title The title of loading dialog
  6779. */
  6780. initialize: function (className, title) {
  6781. this.title = title;
  6782. this.ga = new GlideAjax(className);
  6783. this.ga.addParam('sysparm_scope', x_ausgh_snsc.SaraCommon.SCOPED_APP);
  6784. this.className = className;
  6785. },
  6786.  
  6787. /**
  6788. * Add parameter for GlideAjax
  6789. * @param {String} key The key of parameter
  6790. * @param {String} value The value of parameter
  6791. */
  6792. addParam: function (key, value) {
  6793. this.ga.addParam(key, value);
  6794. },
  6795.  
  6796. /**
  6797. * Get XML response from server
  6798. * @param {Function} callback The callback will be call after getting response from server
  6799. */
  6800. getXML: function (callback) {
  6801. var loadingDialog = new GlideDialogWindow('hierarchical_progress_viewer');
  6802. loadingDialog.hideCloseButton();
  6803. loadingDialog.setTitle(this.title);
  6804.  
  6805. var className = this.className;
  6806. x_ausgh_snsc.log('Sending request to ' + className + '...');
  6807.  
  6808. this.ga.getXML(function (response) {
  6809. loadingDialog.destroy();
  6810. x_ausgh_snsc.log('Got response from ' + className, response);
  6811.  
  6812. if (typeof callback === 'function') {
  6813. callback.apply(this, arguments);
  6814. }
  6815. });
  6816. },
  6817.  
  6818. type: 'SaraGlideAjax'
  6819. };
  6820.  
  6821. })(x_ausgh_snsc.SaraGlideAjax);
  6822. ]]></script>
  6823. <description>Helper class wraps GlideAjax class of ServiceNow and provide Loading Dialog with custom title</description>
  6824. <active>true</active>
  6825. <global>false</global>
  6826. </ui_script>
  6827. </ui_scripts>
  6828.  
  6829.  
  6830. <ui_pages>
  6831. <ui_page>
  6832. <name>sara_oauth_callback</name>
  6833. <description>OAuth Redirection Endpoint</description>
  6834. <category>general</category>
  6835. <html><![CDATA[<?xml version="1.0" encoding="utf-8" ?>
  6836. <j:jelly trim="false" xmlns:j="jelly:core" xmlns:g="glide" xmlns:j2="null" xmlns:g2="null">
  6837. <g:requires name="x_ausgh_snsc.SaraCommon.jsdbx" params="cache=$[jvar_stamp]" />
  6838. <g:requires name="x_ausgh_snsc.SaraGlideHelper.jsdbx" params="cache=$[jvar_stamp]" />
  6839. <g:requires name="x_ausgh_snsc.SaraGlideAjax.jsdbx" params="cache=$[jvar_stamp]" />
  6840. <g:requires name="x_ausgh_snsc.SaraOAuth.jsdbx" params="cache=$[jvar_stamp]" />
  6841. <g:requires name="x_ausgh_snsc.SaraUtils.jsdbx" params="cache=$[jvar_stamp]" />
  6842. <g:requires name="x_ausgh_snsc.SaraVarSet.jsdbx" params="cache=$[jvar_stamp]" />
  6843.  
  6844. <g:ui_form>
  6845. <p>
  6846. <label>Please wait, processing...</label>
  6847. </p>
  6848. </g:ui_form>
  6849. </j:jelly>
  6850. ]]></html>
  6851. <client_script><![CDATA[var parentWin = (window.opener && window.opener.x_ausgh_snsc.SaraOAuth) ? window.opener : window.parent;
  6852.  
  6853. if (!parentWin || !parentWin.x_ausgh_snsc || !parentWin.x_ausgh_snsc.SaraOAuth || !parentWin.x_ausgh_snsc.SaraOAuth.processResponse || typeof(parentWin.x_ausgh_snsc.SaraOAuth.processResponse) !== 'function') {
  6854. window.location.href = '/home.do';
  6855. } else {
  6856. var code = x_ausgh_snsc.SaraUtils.getParmVal('code');
  6857. x_ausgh_snsc.log('Code: ' + code);
  6858.  
  6859. if (code) {
  6860. var clientId = parentWin.x_ausgh_snsc.config[x_ausgh_snsc.SaraCommon.CONFIG_NAME.CLIENT_ID];
  6861. var clientSecret = parentWin.x_ausgh_snsc.config[x_ausgh_snsc.SaraCommon.CONFIG_NAME.CLIENT_SECRET];
  6862. var technicalUser = parentWin.x_ausgh_snsc.config[x_ausgh_snsc.SaraCommon.CONFIG_NAME.TECHNICAL_USER];
  6863. var tokenEndpoint = parentWin.x_ausgh_snsc.config[x_ausgh_snsc.SaraCommon.CONFIG_NAME.TOKEN_ENDPOINT];
  6864.  
  6865. x_ausgh_snsc.log('Client ID: ' + clientId, 'Client Secret: ' + clientSecret, 'Token Endpoint: ' + tokenEndpoint)
  6866.  
  6867. // Invoke x_ausgh_snsc.SaraOAuthAjax to exchange code for tokens
  6868. x_ausgh_snsc.log('Init GlideAjax for requesting token by code...');
  6869. var ga = new x_ausgh_snsc.SaraGlideAjax('SaraOAuthAjax', 'Requesting token by code...');
  6870. ga.addParam('sysparm_name', 'requestTokenByCode');
  6871. ga.addParam('sysparm_code', code);
  6872. ga.addParam('sysparm_client_id', clientId);
  6873. ga.addParam('sysparm_client_secret', clientSecret);
  6874. ga.addParam('sysparm_technical_user', technicalUser);
  6875. ga.addParam('sysparm_token_endpoint', tokenEndpoint);
  6876.  
  6877. ga.getXML(function (response) {
  6878. var answer = response.responseXML.documentElement.getAttribute('answer');
  6879. parentWin.x_ausgh_snsc.SaraOAuth.processResponse(answer);
  6880. });
  6881. } else {
  6882. x_ausgh_snsc.log('Code is empty!');
  6883. parentWin.x_ausgh_snsc.SaraOAuth.processResponse();
  6884. }
  6885. }
  6886. ]]></client_script>
  6887. <processing_script/>
  6888. </ui_page>
  6889. </ui_pages>
  6890.  
  6891.  
  6892. <ui_macros>
  6893. <ui_macro>
  6894. <name>sara_hidden_control</name>
  6895. <description>UI Marco for Sara Hidden Control</description>
  6896. <category>catalog</category>
  6897. <active>true</active>
  6898. <media_type/>
  6899. <xml><![CDATA[<?xml version="1.0" encoding="utf-8" ?>
  6900. <j:jelly trim="false" xmlns:j="jelly:core" xmlns:g="glide" xmlns:j2="null" xmlns:g2="null">
  6901. <script type="text/javascript">
  6902. $j(function () {
  6903. x_ausgh_snsc.SaraUtils.setFormControlVisible(x_ausgh_snsc.SaraCommon.CONTROL_NAME.HIDDEN_CONTROL, false);
  6904. x_ausgh_snsc.SaraVarSet.onLoad();
  6905. });
  6906. </script>
  6907. </j:jelly>
  6908. ]]></xml>
  6909. </ui_macro>
  6910. <ui_macro>
  6911. <name>sara_client_scripts</name>
  6912. <description/>
  6913. <category>catalog</category>
  6914. <active>true</active>
  6915. <media_type/>
  6916. <xml><![CDATA[<?xml version="1.0" encoding="utf-8" ?>
  6917. <j:jelly trim="false" xmlns:j="jelly:core" xmlns:g="glide" xmlns:j2="null" xmlns:g2="null">
  6918. <g:requires name="x_ausgh_snsc.SaraCommon.jsdbx" params="cache=$[jvar_stamp]" />
  6919. <g:requires name="x_ausgh_snsc.SaraGlideAjax.jsdbx" params="cache=$[jvar_stamp]" />
  6920. <g:requires name="x_ausgh_snsc.SaraOAuth.jsdbx" params="cache=$[jvar_stamp]" />
  6921. <g:requires name="x_ausgh_snsc.SaraUtils.jsdbx" params="cache=$[jvar_stamp]" />
  6922. <g:requires name="x_ausgh_snsc.SaraVarSet.jsdbx" params="cache=$[jvar_stamp]" />
  6923.  
  6924. <script type="text/javascript">
  6925. $j(function () {
  6926. x_ausgh_snsc.SaraUtils.setFormControlVisible(x_ausgh_snsc.SaraCommon.CONTROL_NAME.CLIENT_SCRIPTS, false);
  6927. });
  6928. </script>
  6929. </j:jelly>
  6930. ]]></xml>
  6931. </ui_macro>
  6932. </ui_macros>
  6933.  
  6934.  
  6935. <workflows>
  6936. <workflow>
  6937. <name>Sara Service</name>
  6938. <description>Sara Service workflow</description>
  6939. <start>begin</start>
  6940. <table>sc_req_item</table>
  6941. <active>true</active>
  6942. <published>true</published>
  6943.  
  6944.  
  6945. <stages>
  6946. <stage>
  6947. <name>Initializing</name>
  6948. <order>100</order>
  6949. <value>initializing</value>
  6950. <ola/>
  6951. </stage>
  6952. <stage>
  6953. <name>Transferring</name>
  6954. <order>200</order>
  6955. <value>transferring</value>
  6956. <ola/>
  6957. </stage>
  6958. <stage>
  6959. <name>Transferred</name>
  6960. <order>300</order>
  6961. <value>transferred</value>
  6962. <ola/>
  6963. </stage>
  6964. <stage>
  6965. <name>Transfer Failed</name>
  6966. <order>300</order>
  6967. <value>transfer_failed</value>
  6968. <ola/>
  6969. </stage>
  6970. <stage>
  6971. <name>Consume Failed</name>
  6972. <order>400</order>
  6973. <value>consume_failed</value>
  6974. <ola/>
  6975. </stage>
  6976. <stage>
  6977. <name>Running</name>
  6978. <order>500</order>
  6979. <value>running</value>
  6980. <ola/>
  6981. </stage>
  6982. <stage>
  6983. <name>Ended OK</name>
  6984. <order>900</order>
  6985. <value>ended_ok</value>
  6986. <ola/>
  6987. </stage>
  6988. <stage>
  6989. <name>Ended Failed</name>
  6990. <order>900</order>
  6991. <value>ended_failed</value>
  6992. <ola/>
  6993. </stage>
  6994. <stage>
  6995. <name>Completed</name>
  6996. <order>1000</order>
  6997. <value>completed</value>
  6998. <ola/>
  6999. </stage>
  7000. </stages>
  7001.  
  7002.  
  7003.  
  7004. <activities>
  7005. <activity>
  7006. <name>Begin</name>
  7007. <activity_definition>Begin</activity_definition>
  7008. <stage/>
  7009. <width/>
  7010. <height/>
  7011. <x>1</x>
  7012. <y>1</y>
  7013. <snsc_name>begin</snsc_name>
  7014. </activity>
  7015.  
  7016. <activity>
  7017. <name>Check item's price is 0 or not?</name>
  7018. <activity_definition>If</activity_definition>
  7019. <stage/>
  7020. <width/>
  7021. <height/>
  7022. <x>1</x>
  7023. <y>2</y>
  7024. <snsc_name>check_price</snsc_name>
  7025. <variables>
  7026. <variable>
  7027. <name>script</name>
  7028. <value><![CDATA[function ifScript() {
  7029. var item = (new x_ausgh_snsc.SaraGlideHelper()).getData(x_ausgh_snsc.SaraCommon.TABLE_NAME.SN_CATALOG_ITEM, {
  7030. 'sys_id': current.cat_item.sys_id
  7031. });
  7032.  
  7033. if ((item.price.toString()) === '0') {
  7034. return 'yes';
  7035. }
  7036.  
  7037. return 'no';
  7038. }
  7039.  
  7040. answer = ifScript();
  7041. ]]></value>
  7042. </variable>
  7043. <variable>
  7044. <name>advanced</name>
  7045. <value>1</value>
  7046. </variable>
  7047. </variables>
  7048. </activity>
  7049.  
  7050. <activity>
  7051. <name>Waiting for approval</name>
  7052. <activity_definition>Approval - Group</activity_definition>
  7053. <stage/>
  7054. <width/>
  7055. <height/>
  7056. <x>1</x>
  7057. <y>3</y>
  7058. <snsc_name>waiting_for_approval</snsc_name>
  7059. <variables>
  7060. <variable>
  7061. <name>wait_for</name>
  7062. <value>first_any</value>
  7063. </variable>
  7064. <variable>
  7065. <name>reject_handling</name>
  7066. <value>reject</value>
  7067. </variable>
  7068. </variables>
  7069. </activity>
  7070.  
  7071. <activity>
  7072. <name>Approved</name>
  7073. <activity_definition>Approval Action</activity_definition>
  7074. <stage/>
  7075. <width/>
  7076. <height/>
  7077. <x>2</x>
  7078. <y>3</y>
  7079. <snsc_name>approved</snsc_name>
  7080. <variables>
  7081. <variable>
  7082. <name>action</name>
  7083. <value>approved</value>
  7084. </variable>
  7085. </variables>
  7086. </activity>
  7087.  
  7088. <activity>
  7089. <name>Rejected</name>
  7090. <activity_definition>Approval Action</activity_definition>
  7091. <stage/>
  7092. <width/>
  7093. <height/>
  7094. <x>1</x>
  7095. <y>4</y>
  7096. <snsc_name>rejected</snsc_name>
  7097. <variables>
  7098. <variable>
  7099. <name>action</name>
  7100. <value>rejected</value>
  7101. </variable>
  7102. </variables>
  7103. </activity>
  7104.  
  7105. <activity>
  7106. <name>Initializing</name>
  7107. <activity_definition>Timer</activity_definition>
  7108. <stage>initializing</stage>
  7109. <width/>
  7110. <height/>
  7111. <x>3</x>
  7112. <y>3</y>
  7113. <snsc_name>initializing</snsc_name>
  7114. <variables>
  7115. <variable>
  7116. <name>timer_type</name>
  7117. <value>script</value>
  7118. </variable>
  7119. <variable>
  7120. <name>script</name>
  7121. <value><![CDATA[workflow.info('Initializing ...');
  7122. var currentUser = current.opened_by.user_name.toString();
  7123. workflow.info('Workflow started by {0}', currentUser);
  7124. workflow.scratchpad.openedBy = currentUser;
  7125.  
  7126. var technicalUser = new x_ausgh_snsc.SaraConfig().getTechnicalUser();
  7127. workflow.info('Technical user: {0}', technicalUser);
  7128. workflow.scratchpad.technicalUser = technicalUser;
  7129.  
  7130. // Set 'answer' to the number of seconds this timer should wait
  7131. answer = 2;
  7132. ]]></value>
  7133. </variable>
  7134. </variables>
  7135. </activity>
  7136.  
  7137. <activity>
  7138. <name>Invoke Consume URL</name>
  7139. <activity_definition>Run Script</activity_definition>
  7140. <stage>transferring</stage>
  7141. <width/>
  7142. <height/>
  7143. <x>4</x>
  7144. <y>3</y>
  7145. <snsc_name>invoke_consume</snsc_name>
  7146. <variables>
  7147. <variable>
  7148. <name>script</name>
  7149. <value><![CDATA[var restClient = new x_ausgh_snsc.SaraRESTClient();
  7150. restClient.setMIDServer(x_ausgh_snsc.SaraUtils.getMIDServer());
  7151. var oauthClient = new x_ausgh_snsc.SaraOAuthClient(restClient);
  7152. var glideHelper = new x_ausgh_snsc.SaraGlideHelper();
  7153.  
  7154. // Get tokens, store tokens in workflow scratchpad
  7155. var tokens = oauthClient.getUserTokens(workflow.scratchpad.technicalUser);
  7156.  
  7157. if (!tokens) {
  7158. workflow.info('Cannot find access tokens for this user "{0}". Order will be skipped', workflow.scratchpad.technicalUser);
  7159. } else {
  7160. workflow.scratchpad.executionHref = null;
  7161. workflow.scratchpad.isTransfered = false;
  7162.  
  7163. // get service name & consume URL
  7164. var serviceName, consumeUrl, varSetId;
  7165. var catId = current.cat_item.sys_id;
  7166. var saraItem = glideHelper.getData(x_ausgh_snsc.SaraCommon.TABLE_NAME.SARA_DEFINITION, {
  7167. 'u_sc_item': catId
  7168. });
  7169.  
  7170. if (saraItem) {
  7171. serviceName = saraItem['u_name'];
  7172. consumeUrl = saraItem['u_consume_url'];
  7173. varSetId = saraItem['u_var_set'];
  7174.  
  7175. consumeUrl = x_ausgh_snsc.SaraUtils.buildUrl(consumeUrl);
  7176.  
  7177. workflow.info('Service name = {0}', serviceName);
  7178. workflow.info('Consume URL = {0}', consumeUrl);
  7179. workflow.info('Cat item = {0}', current.cat_item.name);
  7180.  
  7181. var payload = {};
  7182. var payloadFields = {};
  7183. payload.fieldvalues = payloadFields;
  7184.  
  7185. if (varSetId) {
  7186. var saraVariables = glideHelper.getData(x_ausgh_snsc.SaraCommon.TABLE_NAME.SARA_VARIABLE, {
  7187. 'variable_set': varSetId
  7188. }, true);
  7189.  
  7190. for (var i = 0, variable; variable = saraVariables[i]; i++) {
  7191. var variableName = variable['name'];
  7192.  
  7193. if (variableName !== x_ausgh_snsc.SaraCommon.CONTROL_NAME.CLIENT_SCRIPTS
  7194. && variableName !== x_ausgh_snsc.SaraCommon.CONTROL_NAME.HIDDEN_CONTROL
  7195. && variable['u_name']) {
  7196.  
  7197. var currentVariable = current.variables[variableName];
  7198. var currentValue;
  7199.  
  7200. if (variable['type'] === x_ausgh_snsc.SaraCommon.VAR_TYPE.LIST_COLLECTOR.toString()) {
  7201. var values = currentVariable.toString().split(',');
  7202. currentValue = [];
  7203.  
  7204. for (var j = 0, value; value = values[j]; j++) {
  7205. var realValue = glideHelper.getData(x_ausgh_snsc.SaraCommon.TABLE_NAME.SARA_LOOKUP, {
  7206. 'sys_id': value
  7207. });
  7208.  
  7209. currentValue.push(realValue['u_display_name']);
  7210. }
  7211. } else {
  7212. currentValue = [currentVariable.getDisplayValue()];
  7213. }
  7214.  
  7215. payloadFields[variable['u_name']] = currentValue;
  7216. }
  7217. }
  7218. } else {
  7219. workflow.info('There is no variables in catalog item (sys_id = {0})', catId);
  7220. }
  7221.  
  7222. //---------------- audit information ---------------
  7223. workflow.info('Add audit information');
  7224.  
  7225. var payloadParams = {};
  7226. payloadParams[x_ausgh_snsc.SaraCommon.AUDIT.ORDER_ID] = current.request.number.toString();
  7227. payloadParams[x_ausgh_snsc.SaraCommon.AUDIT.ORDER_TIMESTAMP] = current.sys_created_on.toString();
  7228. payloadParams[x_ausgh_snsc.SaraCommon.AUDIT.ORDER_NAME] = current.sys_created_by.toString();
  7229.  
  7230. var approvalHistory = '<<Auto Approval>>';
  7231.  
  7232. if(current.approval_history != null) {
  7233. var journal = glideHelper.getData(x_ausgh_snsc.SaraCommon.TABLE_NAME.SN_JOURNAL_FIELD, {
  7234. 'element_id' : current.sys_id
  7235. });
  7236. if(journal != null) {
  7237. approvalHistory = journal.value.toString();
  7238. }
  7239. }
  7240.  
  7241. payloadParams[x_ausgh_snsc.SaraCommon.AUDIT.APPROVAL_HISTORY] = approvalHistory;
  7242. payloadParams[x_ausgh_snsc.SaraCommon.AUDIT.APPROVAL_TIMESTAMP] = current.approval_set.toString();
  7243.  
  7244. payload.parametervalues = payloadParams;
  7245. //--------------- /audit information ---------------
  7246.  
  7247. var payloadStr = x_ausgh_snsc.SaraJSON.stringify(payload);
  7248. workflow.info(payloadStr);
  7249.  
  7250. // Make request
  7251. if (serviceName) {
  7252. workflow.info('Invoking consume URL...');
  7253.  
  7254. var request = restClient.newSAPIRequest('post', consumeUrl);
  7255. request.setContent('${payload}');
  7256. request.addHeader('content-type', 'application/json;charset=UTF-8');
  7257. request.setStringParameterNoEscape('payload', payloadStr);
  7258.  
  7259. // Add Authorization header
  7260. request.addHeader('Authorization', tokens[3] + ' ' + tokens[0]);
  7261.  
  7262. var response = restClient.executeWithRefreshToken(request);
  7263. var responseObject = response.getResponseObject();
  7264.  
  7265. if (response.haveError()) {
  7266. workflow.info('Order process FAILED.');
  7267. } else {
  7268. workflow.info('Successfully transfered.');
  7269. workflow.info('Response: {0}', response.getBody());
  7270. var resObj = x_ausgh_snsc.SaraJSON.parse(response.getBody());
  7271. var runId = resObj['runID'];
  7272.  
  7273. workflow.scratchpad.isTransfered = true;
  7274.  
  7275. if (runId !== undefined) {
  7276. var executionHref = resObj['_links']['self']['href'];
  7277. workflow.info('Got runId: {0}', runId.toString());
  7278. workflow.info('Got execution href: {0}', executionHref);
  7279. workflow.scratchpad.runId = runId;
  7280. workflow.scratchpad.executionHref = executionHref;
  7281.  
  7282. // save runId to the 'correlation_id' column of current record in 'sc_req_item' table
  7283. current['correlation_id'] = '' + runId;
  7284. current.update();
  7285. } else {
  7286. workflow.info(resObj.message);
  7287. }
  7288. }
  7289.  
  7290. } else {
  7291. workflow.info('Failed to make consume request as no service definition was defined.');
  7292. }
  7293. } else {
  7294. workflow.info('Catalog item (sys_id = {0}) doesn\'t existed any more in {1}!', [catId, x_ausgh_snsc.SaraCommon.TABLE_NAME.SARA_DEFINITION]);
  7295. }
  7296. }
  7297. ]]></value>
  7298. </variable>
  7299. </variables>
  7300. </activity>
  7301.  
  7302. <activity>
  7303. <name>Check transfer result</name>
  7304. <activity_definition>If</activity_definition>
  7305. <stage>transferred</stage>
  7306. <width/>
  7307. <height/>
  7308. <x>5</x>
  7309. <y>3</y>
  7310. <snsc_name>check_transfer</snsc_name>
  7311. <variables>
  7312. <variable>
  7313. <name>script</name>
  7314. <value><![CDATA[// This script needs to set answer to 'yes' or 'no' to indicate the state of the activity.
  7315. //
  7316. // For example,
  7317. //
  7318. answer = ifScript();
  7319.  
  7320. function ifScript() {
  7321. return (workflow.scratchpad.isTransfered == true ? 'yes' : 'no');
  7322. }
  7323. ]]></value>
  7324. </variable>
  7325. <variable>
  7326. <name>advanced</name>
  7327. <value>1</value>
  7328. </variable>
  7329. </variables>
  7330. </activity>
  7331.  
  7332. <activity>
  7333. <name>Transfer Request Failed</name>
  7334. <activity_definition>Log Message</activity_definition>
  7335. <stage>transfer_failed</stage>
  7336. <width/>
  7337. <height/>
  7338. <x>5</x>
  7339. <y>4</y>
  7340. <snsc_name>transfer_failed</snsc_name>
  7341. <variables>
  7342. <variable>
  7343. <name>message</name>
  7344. <value>Transfer request failed, order skipped.</value>
  7345. </variable>
  7346. </variables>
  7347. </activity>
  7348.  
  7349. <activity>
  7350. <name>Check consume result</name>
  7351. <activity_definition>If</activity_definition>
  7352. <stage>transferred</stage>
  7353. <width/>
  7354. <height/>
  7355. <x>6</x>
  7356. <y>4</y>
  7357. <snsc_name>check_consume</snsc_name>
  7358. <variables>
  7359. <variable>
  7360. <name>script</name>
  7361. <value><![CDATA[// This script needs to set answer to 'yes' or 'no' to indicate the state of the activity.
  7362. //
  7363. // For example,
  7364. //
  7365. answer = ifScript();
  7366.  
  7367. function ifScript() {
  7368. return (workflow.scratchpad.executionHref != null ? 'yes' : 'no');
  7369. }
  7370. ]]></value>
  7371. </variable>
  7372. <variable>
  7373. <name>advanced</name>
  7374. <value>1</value>
  7375. </variable>
  7376. </variables>
  7377. </activity>
  7378.  
  7379. <activity>
  7380. <name>Consume Request Failed</name>
  7381. <activity_definition>Log Message</activity_definition>
  7382. <stage>consume_failed</stage>
  7383. <width/>
  7384. <height/>
  7385. <x>6</x>
  7386. <y>5</y>
  7387. <snsc_name>consume_failed</snsc_name>
  7388. <variables>
  7389. <variable>
  7390. <name>message</name>
  7391. <value>Consume request failed, order skipped.</value>
  7392. </variable>
  7393. </variables>
  7394. </activity>
  7395.  
  7396. <activity>
  7397. <name>Workflow Timer</name>
  7398. <activity_definition>Timer</activity_definition>
  7399. <stage>running</stage>
  7400. <width/>
  7401. <height/>
  7402. <x>7</x>
  7403. <y>5</y>
  7404. <snsc_name>workflow_timer</snsc_name>
  7405. <variables>
  7406. <variable>
  7407. <name>timer_type</name>
  7408. <value>script</value>
  7409. </variable>
  7410. <variable>
  7411. <name>script</name>
  7412. <value><![CDATA[if (workflow.scratchpad.delay === undefined) {
  7413. var delay = +x_ausgh_snsc.SaraUtils.getSaraProperty(SaraCommon.SYSTEM_PROPERTY_NAME.WORKFLOW_DELAY);
  7414. var timeout = +x_ausgh_snsc.SaraUtils.getSaraProperty(SaraCommon.SYSTEM_PROPERTY_NAME.WORKFLOW_TIMEOUT);
  7415.  
  7416. // If delay time in config is equal or lesser than 0, let make it '60'
  7417. if (delay <= 0) {
  7418. delay = 60;
  7419. }
  7420.  
  7421. // Make sure that timeout minimum always be '0'
  7422. if (timeout < 0) {
  7423. timeout = 0;
  7424. }
  7425.  
  7426. workflow.scratchpad.counter = 1;
  7427. workflow.scratchpad.maxCount = (timeout / delay) + 1;
  7428. workflow.scratchpad.delay = delay;
  7429. workflow.scratchpad.timeout = timeout;
  7430. }
  7431.  
  7432. answer = workflow.scratchpad.delay;
  7433. ]]></value>
  7434. </variable>
  7435. </variables>
  7436. </activity>
  7437.  
  7438. <activity>
  7439. <name>Retrieve Execution Status</name>
  7440. <activity_definition>Run Script</activity_definition>
  7441. <stage>running</stage>
  7442. <width/>
  7443. <height/>
  7444. <x>8</x>
  7445. <y>5</y>
  7446. <snsc_name>retrieve_status</snsc_name>
  7447. <variables>
  7448. <variable>
  7449. <name>script</name>
  7450. <value><![CDATA[var restClient = new x_ausgh_snsc.SaraRESTClient();
  7451. restClient.setMIDServer(x_ausgh_snsc.SaraUtils.getMIDServer());
  7452. var oauthClient = new x_ausgh_snsc.SaraOAuthClient(restClient);
  7453. var executionHref = x_ausgh_snsc.SaraUtils.buildUrl(workflow.scratchpad.executionHref);
  7454.  
  7455. workflow.scratchpad.ended = 'unknown';
  7456.  
  7457. // Get tokens, store tokens in workflow scratchpad
  7458. var tokens = oauthClient.getUserTokens(workflow.scratchpad.technicalUser);
  7459. var request = restClient.newSAPIRequest('get', executionHref);
  7460. request.addHeader('Authorization', tokens[3] + ' ' + tokens[0]);
  7461.  
  7462. workflow.info('[{0}] Waiting for execution checking response ...', workflow.scratchpad.counter);
  7463. var response = restClient.executeWithRefreshToken(request);
  7464. var responseObject = response.getResponseObject();
  7465.  
  7466. if (response.haveError()) {
  7467. workflow.warn('Status code: {0}, error message: {1}', [responseObject.statusCode, responseObject.errorMessage]);
  7468.  
  7469. workflow.info('Stop retrieving execution status now.');
  7470. } else {
  7471. workflow.info('Response received: {0}', response.getBody());
  7472. var resObj = responseObject.bodyObject;
  7473. var statusCode = resObj.statusCode;
  7474. workflow.info('Status code: {0}, statusText: {1}', [statusCode.toString(), resObj.statusText]);
  7475.  
  7476. if (statusCode >= 1800) {
  7477. if (statusCode === x_ausgh_snsc.SaraCommon.WORKFLOW_STATUS_CODE.ENDED_OK) {
  7478. workflow.info('Execution finished successfully!');
  7479. workflow.scratchpad.ended = 'ENDED_OK';
  7480. } else {
  7481. workflow.scratchpad.ended = statusCode + ' - ' + resObj.statusText;
  7482. }
  7483. }
  7484. }
  7485.  
  7486. workflow.scratchpad.counter++;
  7487. ]]></value>
  7488. </variable>
  7489. </variables>
  7490. </activity>
  7491.  
  7492. <activity>
  7493. <name>Check Timeout</name>
  7494. <activity_definition>If</activity_definition>
  7495. <stage>running</stage>
  7496. <width/>
  7497. <height/>
  7498. <x>9</x>
  7499. <y>5</y>
  7500. <snsc_name>check_timeout</snsc_name>
  7501. <variables>
  7502. <variable>
  7503. <name>script</name>
  7504. <value><![CDATA[function ifScript() {
  7505. var counter = workflow.scratchpad.counter;
  7506. var maxCount = workflow.scratchpad.maxCount;
  7507. var timeout = workflow.scratchpad.timeout;
  7508.  
  7509. if (timeout === 0) {
  7510. if (workflow.scratchpad.ended !== 'unknown') {
  7511. return 'yes';
  7512. }
  7513. } else {
  7514. if (counter <= maxCount) {
  7515. if (workflow.scratchpad.ended !== 'unknown') {
  7516. return 'yes';
  7517. }
  7518. } else {
  7519. return 'yes';
  7520. }
  7521. }
  7522.  
  7523. return 'no';
  7524. }
  7525.  
  7526. answer = ifScript();
  7527. ]]></value>
  7528. </variable>
  7529. <variable>
  7530. <name>advanced</name>
  7531. <value>1</value>
  7532. </variable>
  7533. </variables>
  7534. </activity>
  7535.  
  7536. <activity>
  7537. <name>Check Execution Result</name>
  7538. <activity_definition>If</activity_definition>
  7539. <stage>running</stage>
  7540. <width/>
  7541. <height/>
  7542. <x>10</x>
  7543. <y>6</y>
  7544. <snsc_name>check_result</snsc_name>
  7545. <variables>
  7546. <variable>
  7547. <name>script</name>
  7548. <value><![CDATA[// This script needs to set answer to 'yes' or 'no' to indicate the state of the activity.
  7549.  
  7550. answer = ifScript();
  7551.  
  7552. function ifScript() {
  7553. return (workflow.scratchpad.ended == 'ENDED_OK' ? 'yes' : 'no');
  7554. }
  7555. ]]></value>
  7556. </variable>
  7557. <variable>
  7558. <name>advanced</name>
  7559. <value>1</value>
  7560. </variable>
  7561. </variables>
  7562. </activity>
  7563.  
  7564. <activity>
  7565. <name>Ended Failed</name>
  7566. <activity_definition>Log Message</activity_definition>
  7567. <stage>ended_failed</stage>
  7568. <width/>
  7569. <height/>
  7570. <x>10</x>
  7571. <y>7</y>
  7572. <snsc_name>ended_failed</snsc_name>
  7573. <variables>
  7574. <variable>
  7575. <name>message</name>
  7576. <value>Workflow finished NOT OK.</value>
  7577. </variable>
  7578. </variables>
  7579. </activity>
  7580.  
  7581. <activity>
  7582. <name>Ended OK</name>
  7583. <activity_definition>Log Message</activity_definition>
  7584. <stage>ended_ok</stage>
  7585. <width/>
  7586. <height/>
  7587. <x>11</x>
  7588. <y>7</y>
  7589. <snsc_name>ended_ok</snsc_name>
  7590. <variables>
  7591. <variable>
  7592. <name>message</name>
  7593. <value>Workflow finished successfully.</value>
  7594. </variable>
  7595. </variables>
  7596. </activity>
  7597.  
  7598. <activity>
  7599. <name>End</name>
  7600. <activity_definition>End</activity_definition>
  7601. <stage>completed</stage>
  7602. <width/>
  7603. <height/>
  7604. <x>2</x>
  7605. <y>8</y>
  7606. <snsc_name>end</snsc_name>
  7607. </activity>
  7608. </activities>
  7609.  
  7610.  
  7611.  
  7612. <transitions>
  7613.  
  7614. <transition>
  7615. <from>begin</from>
  7616. <to>check_price</to>
  7617. <condition>
  7618. <name>Always</name>
  7619. <condition>true</condition>
  7620. <order>1</order>
  7621. <description/>
  7622. </condition>
  7623. </transition>
  7624.  
  7625.  
  7626. <transition>
  7627. <from>check_price</from>
  7628. <to>waiting_for_approval</to>
  7629. <condition>
  7630. <name>No</name>
  7631. <condition>activity.result == 'no'</condition>
  7632. <order>1</order>
  7633. <description/>
  7634. </condition>
  7635. </transition>
  7636.  
  7637.  
  7638. <transition>
  7639. <from>check_price</from>
  7640. <to>approved</to>
  7641. <condition>
  7642. <name>Yes</name>
  7643. <condition>activity.result == 'yes'</condition>
  7644. <order>1</order>
  7645. <description/>
  7646. </condition>
  7647. </transition>
  7648.  
  7649.  
  7650. <transition>
  7651. <from>waiting_for_approval</from>
  7652. <to>rejected</to>
  7653. <condition>
  7654. <name>Rejected</name>
  7655. <condition>activity.result == 'rejected'</condition>
  7656. <order>1</order>
  7657. <description/>
  7658. </condition>
  7659. </transition>
  7660.  
  7661.  
  7662. <transition>
  7663. <from>rejected</from>
  7664. <to>end</to>
  7665. <condition>
  7666. <name>Always</name>
  7667. <condition>true</condition>
  7668. <order>1</order>
  7669. <description/>
  7670. </condition>
  7671. </transition>
  7672.  
  7673.  
  7674. <transition>
  7675. <from>waiting_for_approval</from>
  7676. <to>approved</to>
  7677. <condition>
  7678. <name>Approved</name>
  7679. <condition>activity.result == 'approved' || activity.result == 'skipped'</condition>
  7680. <order>1</order>
  7681. <description/>
  7682. </condition>
  7683. </transition>
  7684.  
  7685.  
  7686. <transition>
  7687. <from>approved</from>
  7688. <to>initializing</to>
  7689. <condition>
  7690. <name>Always</name>
  7691. <condition>true</condition>
  7692. <order>1</order>
  7693. <description/>
  7694. </condition>
  7695. </transition>
  7696.  
  7697.  
  7698. <transition>
  7699. <from>initializing</from>
  7700. <to>invoke_consume</to>
  7701. <condition>
  7702. <name>Always</name>
  7703. <condition>true</condition>
  7704. <order>1</order>
  7705. <description/>
  7706. </condition>
  7707. </transition>
  7708.  
  7709.  
  7710. <transition>
  7711. <from>invoke_consume</from>
  7712. <to>check_transfer</to>
  7713. <condition>
  7714. <name>Always</name>
  7715. <condition>true</condition>
  7716. <order>1</order>
  7717. <description/>
  7718. </condition>
  7719. </transition>
  7720.  
  7721.  
  7722. <transition>
  7723. <from>check_transfer</from>
  7724. <to>transfer_failed</to>
  7725. <condition>
  7726. <name>No</name>
  7727. <condition>activity.result == 'no'</condition>
  7728. <order>1</order>
  7729. <description/>
  7730. </condition>
  7731. </transition>
  7732.  
  7733.  
  7734. <transition>
  7735. <from>transfer_failed</from>
  7736. <to>end</to>
  7737. <condition>
  7738. <name>Always</name>
  7739. <condition>true</condition>
  7740. <order>1</order>
  7741. <description/>
  7742. </condition>
  7743. </transition>
  7744.  
  7745.  
  7746. <transition>
  7747. <from>check_transfer</from>
  7748. <to>check_consume</to>
  7749. <condition>
  7750. <name>Yes</name>
  7751. <condition>activity.result == 'yes'</condition>
  7752. <order>1</order>
  7753. <description/>
  7754. </condition>
  7755. </transition>
  7756.  
  7757.  
  7758. <transition>
  7759. <from>check_consume</from>
  7760. <to>consume_failed</to>
  7761. <condition>
  7762. <name>No</name>
  7763. <condition>activity.result == 'no'</condition>
  7764. <order>1</order>
  7765. <description/>
  7766. </condition>
  7767. </transition>
  7768.  
  7769.  
  7770. <transition>
  7771. <from>consume_failed</from>
  7772. <to>end</to>
  7773. <condition>
  7774. <name>Always</name>
  7775. <condition>true</condition>
  7776. <order>1</order>
  7777. <description/>
  7778. </condition>
  7779. </transition>
  7780.  
  7781.  
  7782. <transition>
  7783. <from>check_consume</from>
  7784. <to>workflow_timer</to>
  7785. <condition>
  7786. <name>Yes</name>
  7787. <condition>activity.result == 'yes'</condition>
  7788. <order>1</order>
  7789. <description/>
  7790. </condition>
  7791. </transition>
  7792.  
  7793.  
  7794. <transition>
  7795. <from>workflow_timer</from>
  7796. <to>retrieve_status</to>
  7797. <condition>
  7798. <name>Always</name>
  7799. <condition>true</condition>
  7800. <order>1</order>
  7801. <description/>
  7802. </condition>
  7803. </transition>
  7804.  
  7805.  
  7806. <transition>
  7807. <from>retrieve_status</from>
  7808. <to>check_timeout</to>
  7809. <condition>
  7810. <name>Always</name>
  7811. <condition>true</condition>
  7812. <order>1</order>
  7813. <description/>
  7814. </condition>
  7815. </transition>
  7816.  
  7817.  
  7818. <transition>
  7819. <from>check_timeout</from>
  7820. <to>workflow_timer</to>
  7821. <condition>
  7822. <name>No</name>
  7823. <condition>activity.result == 'no'</condition>
  7824. <order>2</order>
  7825. <description/>
  7826. </condition>
  7827. </transition>
  7828.  
  7829.  
  7830. <transition>
  7831. <from>check_timeout</from>
  7832. <to>check_result</to>
  7833. <condition>
  7834. <name>Yes</name>
  7835. <condition>activity.result == 'yes'</condition>
  7836. <order>1</order>
  7837. <description/>
  7838. </condition>
  7839. </transition>
  7840.  
  7841.  
  7842. <transition>
  7843. <from>check_result</from>
  7844. <to>ended_failed</to>
  7845. <condition>
  7846. <name>No</name>
  7847. <condition>activity.result == 'no'</condition>
  7848. <order>2</order>
  7849. <description/>
  7850. </condition>
  7851. </transition>
  7852.  
  7853.  
  7854. <transition>
  7855. <from>ended_failed</from>
  7856. <to>end</to>
  7857. <condition>
  7858. <name>Always</name>
  7859. <condition>true</condition>
  7860. <order>1</order>
  7861. <description/>
  7862. </condition>
  7863. </transition>
  7864.  
  7865.  
  7866. <transition>
  7867. <from>check_result</from>
  7868. <to>ended_ok</to>
  7869. <condition>
  7870. <name>Yes</name>
  7871. <condition>activity.result == 'yes'</condition>
  7872. <order>1</order>
  7873. <description/>
  7874. </condition>
  7875. </transition>
  7876.  
  7877.  
  7878. <transition>
  7879. <from>ended_ok</from>
  7880. <to>end</to>
  7881. <condition>
  7882. <name>Always</name>
  7883. <condition>true</condition>
  7884. <order>1</order>
  7885. <description/>
  7886. </condition>
  7887. </transition>
  7888. </transitions>
  7889.  
  7890. </workflow>
  7891. </workflows>
  7892.  
  7893.  
  7894. <fix_scripts>
  7895. <fix_script>
  7896. <name>Sara - Create Scheduler for auto-sync</name>
  7897. <description>Create Scheduler for auto-sync service and lookup value</description>
  7898. <active>true</active>
  7899. <run_once>true</run_once>
  7900. <script><![CDATA[var glideHelper = new x_ausgh_snsc.SaraGlideHelper();
  7901.  
  7902. glideHelper.persistData(x_ausgh_snsc.SaraCommon.TABLE_NAME.SN_AUTO_SCRIPT, {
  7903. 'name': 'SaraAutoSync',
  7904. 'script': 'new x_ausgh_snsc.SaraSync().syncServices();',
  7905. 'active': true,
  7906. 'run_type': 'periodically',
  7907. 'run_period': '02:00:00',
  7908. 'sys_class_name': 'sysauto_script',
  7909. 'run_dayofweek': 1
  7910. });
  7911. ]]></script>
  7912. </fix_script>
  7913. <fix_script>
  7914. <name>Sara - Remove Scheduler for auto-sync</name>
  7915. <description>Remove Scheduler for auto-sync service and lookup value</description>
  7916. <active>true</active>
  7917. <run_once>true</run_once>
  7918. <script><![CDATA[var glideHelper = new x_ausgh_snsc.SaraGlideHelper();
  7919.  
  7920. glideHelper.deleteData(x_ausgh_snsc.SaraCommon.TABLE_NAME.SN_AUTO_SCRIPT, {
  7921. 'name': 'SaraAutoSync'
  7922. }, true);
  7923. ]]></script>
  7924. </fix_script>
  7925. </fix_scripts>
  7926.  
  7927.  
  7928. <wizards>
  7929. <wizard>
  7930. <name>Automic OAuth Configuration</name>
  7931. <type>expert</type>
  7932. <banner_type>fixed</banner_type>
  7933. <roles>admin</roles>
  7934. <first_panel>OAuth Client</first_panel>
  7935. <variables>
  7936. <variable>
  7937. <name>sara_client_scripts</name>
  7938. <type>14</type>
  7939. <class>expert_variable</class>
  7940. <question>Sara Client Scripts</question>
  7941. <order>0</order>
  7942. <mandatory>false</mandatory>
  7943. <active>true</active>
  7944. <panel>Config OAuth Client</panel>
  7945. <macro>sara_client_scripts</macro>
  7946. </variable>
  7947. <variable>
  7948. <name>client_id</name>
  7949. <type>6</type>
  7950. <class>expert_variable</class>
  7951. <question>Client ID</question>
  7952. <order>100</order>
  7953. <mandatory>true</mandatory>
  7954. <active>true</active>
  7955. <panel>Config OAuth Client</panel>
  7956. </variable>
  7957. <variable>
  7958. <name>client_secret</name>
  7959. <type>6</type>
  7960. <class>expert_variable</class>
  7961. <question>Client Secret</question>
  7962. <order>200</order>
  7963. <mandatory>true</mandatory>
  7964. <active>true</active>
  7965. <panel>Config OAuth Client</panel>
  7966. </variable>
  7967. <variable>
  7968. <name>technical_user</name>
  7969. <type>6</type>
  7970. <class>expert_variable</class>
  7971. <question>Technical User</question>
  7972. <order>300</order>
  7973. <mandatory>true</mandatory>
  7974. <active>true</active>
  7975. <panel>Config OAuth Client</panel>
  7976. </variable>
  7977. <variable>
  7978. <name>sapi_endpoint</name>
  7979. <type>6</type>
  7980. <class>expert_variable</class>
  7981. <question>SAPI Endpoint</question>
  7982. <order>400</order>
  7983. <mandatory>true</mandatory>
  7984. <active>true</active>
  7985. <panel>Config OAuth Client</panel>
  7986. </variable>
  7987. <variable>
  7988. <name>token_endpoint</name>
  7989. <type>6</type>
  7990. <class>expert_variable</class>
  7991. <question>Token Endpoint</question>
  7992. <order>500</order>
  7993. <mandatory>true</mandatory>
  7994. <active>true</active>
  7995. <panel>Config OAuth Client</panel>
  7996. </variable>
  7997. <variable>
  7998. <name>auth_endpoint</name>
  7999. <type>6</type>
  8000. <class>expert_variable</class>
  8001. <question>Authorization Endpoint</question>
  8002. <order>600</order>
  8003. <mandatory>true</mandatory>
  8004. <active>true</active>
  8005. <panel>Config OAuth Client</panel>
  8006. </variable>
  8007. </variables>
  8008.  
  8009. <panels>
  8010. <panel>
  8011. <name>Config OAuth Client</name>
  8012. <title>Config OAuth Client</title>
  8013. <class>expert_panel</class>
  8014. <description>Config OAuth Server Endpoints, Client ID, Client Secret, SAPI Endpoint and Technical User for SNSC. OAuth login popup will be shown in case Technical User doesn't have tokens or Technical User's tokens are empty, invalid or expired.</description>
  8015. <previous_message>Previous</previous_message>
  8016. <next_message>Store OAuth Client Settings</next_message>
  8017. <complete_message>Done</complete_message>
  8018. <client_script>
  8019. <name>SARA OAuth Client OnLoad</name>
  8020. <active>true</active>
  8021. <type>onLoad</type>
  8022. <script><![CDATA[function onLoad() {
  8023. g_form.getControl(x_ausgh_snsc.SaraCommon.CONFIG_NAME.CLIENT_SECRET).type = 'password';
  8024. x_ausgh_snsc.oldConfig = {};
  8025.  
  8026. x_ausgh_snsc.SaraOAuth.getConfig(function (configData) {
  8027. for (var name in configData) {
  8028. var value = configData[name];
  8029.  
  8030. g_form.setValue(name, value);
  8031. x_ausgh_snsc.oldConfig[name] = value;
  8032. }
  8033. });
  8034. }
  8035. ]]></script>
  8036. </client_script>
  8037. <client_script>
  8038. <name>SARA OAuth Client OnSubmit</name>
  8039. <active>true</active>
  8040. <type>onSubmit</type>
  8041. <script><![CDATA[function onSubmit() {
  8042. if (x_ausgh_snsc.isTokenValid) {
  8043. return true;
  8044. } else {
  8045. var isChange = false;
  8046. for (var name in x_ausgh_snsc.oldConfig) {
  8047. if (x_ausgh_snsc.oldConfig[name] !== g_form.getValue(name).toString() && name !== x_ausgh_snsc.SaraCommon.CONFIG_NAME.SAPI_ENDPOINT) {
  8048. isChange = true;
  8049. break;
  8050. }
  8051. }
  8052.  
  8053. if (isChange && !x_ausgh_snsc.notChange) {
  8054. getToken();
  8055. } else {
  8056. // Clean all existing messages
  8057. g_form.clearMessages();
  8058.  
  8059. // Check if Sara tokens exist for Technical User
  8060. var technicalUser = g_form.getValue(x_ausgh_snsc.SaraCommon.CONFIG_NAME.TECHNICAL_USER).toString();
  8061. var sapiEndpoint = g_form.getValue(x_ausgh_snsc.SaraCommon.CONFIG_NAME.SAPI_ENDPOINT).toString();
  8062. x_ausgh_snsc.SaraOAuth.checkOAuthToken(technicalUser, sapiEndpoint, false, {
  8063. onValid: function () {
  8064. x_ausgh_snsc.isTokenValid = true;
  8065. g_expert.next();
  8066. },
  8067. onInvalid: function () {
  8068. x_ausgh_snsc.isTokenValid = false;
  8069. getToken();
  8070. },
  8071. onError: function (errorMessage) {
  8072. x_ausgh_snsc.isTokenValid = false;
  8073. g_form.addErrorMessage(errorMessage);
  8074. }
  8075. });
  8076. }
  8077. }
  8078.  
  8079. return false;
  8080. }
  8081.  
  8082. function getToken() {
  8083. x_ausgh_snsc.log('Preparing for openning OAuth login popup...');
  8084.  
  8085. for (var key in x_ausgh_snsc.SaraCommon.CONFIG_NAME) {
  8086. var name = x_ausgh_snsc.SaraCommon.CONFIG_NAME[key];
  8087.  
  8088. x_ausgh_snsc.config[name] = g_form.getValue(name).toString();
  8089. }
  8090.  
  8091. x_ausgh_snsc.SaraOAuth.login(
  8092. x_ausgh_snsc.config[x_ausgh_snsc.SaraCommon.CONFIG_NAME.CLIENT_ID],
  8093. x_ausgh_snsc.config[x_ausgh_snsc.SaraCommon.CONFIG_NAME.TECHNICAL_USER],
  8094. x_ausgh_snsc.config[x_ausgh_snsc.SaraCommon.CONFIG_NAME.AUTH_ENDPOINT], {
  8095. onSuccess: function () {
  8096. x_ausgh_snsc.notChange = true;
  8097. g_expert.next();
  8098. }
  8099. }
  8100. );
  8101. }
  8102. ]]></script>
  8103. </client_script>
  8104. </panel>
  8105. <panel>
  8106. <name>Config OAuth Client Completed</name>
  8107. <title>Config OAuth Client Completed</title>
  8108. <class>expert_panel</class>
  8109. <description/>
  8110. <previous_message>Previous</previous_message>
  8111. <next_message>Next</next_message>
  8112. <complete_message>Done</complete_message>
  8113. </panel>
  8114. </panels>
  8115.  
  8116. <transitions>
  8117. <transition>
  8118. <from>Config OAuth Client</from>
  8119. <to>Config OAuth Client Completed</to>
  8120. <order>100</order>
  8121. <condition/>
  8122. <transition_script><![CDATA[var LOGGER = new x_ausgh_snsc.SaraLog('sara_oauth_client_transition');
  8123.  
  8124. gs.addInfoMessage('Client ID = ' + wizard[x_ausgh_snsc.SaraCommon.CONFIG_NAME.CLIENT_ID]
  8125. + ', Client Secret = ***'
  8126. + ', Technical User = ' + wizard[x_ausgh_snsc.SaraCommon.CONFIG_NAME.TECHNICAL_USER]
  8127. + ', SAPI Endpoint = ' + wizard[x_ausgh_snsc.SaraCommon.CONFIG_NAME.SAPI_ENDPOINT]
  8128. + ', Token Endpoint = ' + wizard[x_ausgh_snsc.SaraCommon.CONFIG_NAME.TOKEN_ENDPOINT]
  8129. + ', Authorization Endpoint = ' + wizard[x_ausgh_snsc.SaraCommon.CONFIG_NAME.AUTH_ENDPOINT]);
  8130.  
  8131. var saraConfig = new x_ausgh_snsc.SaraConfig();
  8132. try {
  8133. var configData = {};
  8134. for (var key in x_ausgh_snsc.SaraCommon.CONFIG_NAME) {
  8135. var name = x_ausgh_snsc.SaraCommon.CONFIG_NAME[key];
  8136.  
  8137. configData[name] = wizard[name];
  8138. }
  8139.  
  8140. saraConfig.storeClientConfig(configData);
  8141. LOGGER.info('OAuth Configuration updated:\n'
  8142. + ' - Client ID = {0}, \n'
  8143. + ' - Client Secret = ***, \n'
  8144. + ' - Technical User = {1} \n'
  8145. + ' - SAPI Endpoint = {2}, \n'
  8146. + ' - Token Endpoint = {3}, \n'
  8147. + ' - Authorization Endpoint = {4}',
  8148. configData[x_ausgh_snsc.SaraCommon.CONFIG_NAME.CLIENT_ID],
  8149. configData[x_ausgh_snsc.SaraCommon.CONFIG_NAME.TECHNICAL_USER],
  8150. configData[x_ausgh_snsc.SaraCommon.CONFIG_NAME.SAPI_ENDPOINT],
  8151. configData[x_ausgh_snsc.SaraCommon.CONFIG_NAME.TOKEN_ENDPOINT],
  8152. configData[x_ausgh_snsc.SaraCommon.CONFIG_NAME.AUTH_ENDPOINT]
  8153. );
  8154.  
  8155. gs.addInfoMessage('Successfully update Automic OAuth client settings');
  8156. } catch (err) {
  8157. LOGGER.info('Error on update Automic OAuth client settings: {0}', err);
  8158.  
  8159. gs.addInfoMessage('Failed to update Automic OAuth client settings');
  8160. }
  8161. ]]></transition_script>
  8162. </transition>
  8163. </transitions>
  8164. </wizard>
  8165.  
  8166. <wizard>
  8167. <name>Automic Import Services</name>
  8168. <type>expert</type>
  8169. <banner_type>fixed</banner_type>
  8170. <roles>admin</roles>
  8171. <first_panel>Import Services</first_panel>
  8172. <variables>
  8173. <variable>
  8174. <name>sara_client_scripts</name>
  8175. <type>14</type>
  8176. <class>expert_variable</class>
  8177. <question>Sara Client Scripts</question>
  8178. <order>0</order>
  8179. <mandatory>false</mandatory>
  8180. <active>true</active>
  8181. <panel>Import Services</panel>
  8182. <macro>sara_client_scripts</macro>
  8183. </variable>
  8184. <variable>
  8185. <name>sara_message</name>
  8186. <type>6</type>
  8187. <class>expert_variable</class>
  8188. <question>Sara Message</question>
  8189. <order>100</order>
  8190. <mandatory>false</mandatory>
  8191. <active>true</active>
  8192. <panel>Import Services</panel>
  8193. </variable>
  8194. <variable>
  8195. <name>sara_target_category</name>
  8196. <type>18</type>
  8197. <class>expert_variable</class>
  8198. <question>Select Target Category</question>
  8199. <order>200</order>
  8200. <mandatory>true</mandatory>
  8201. <active>true</active>
  8202. <lookup_table>sc_category</lookup_table>
  8203. <lookup_value>sys_id</lookup_value>
  8204. <lookup_label>title</lookup_label>
  8205. <panel>Import Services</panel>
  8206. </variable>
  8207. </variables>
  8208.  
  8209. <panels>
  8210. <panel>
  8211. <name>Import Services</name>
  8212. <title>Import Services</title>
  8213. <class>expert_panel</class>
  8214. <description>Import SARA services to Service Catalog. Error messages will be shown in case Technical User doesn't have tokens or Technical User's tokens empty, invalid or expired.</description>
  8215. <previous_message>Previous</previous_message>
  8216. <next_message>Import Services</next_message>
  8217. <complete_message>Done</complete_message>
  8218. <client_script>
  8219. <name>Import Services OnLoad</name>
  8220. <active>true</active>
  8221. <type>onLoad</type>
  8222. <script><![CDATA[function onLoad() {
  8223. x_ausgh_snsc.SaraUtils.setFormControlVisible('sara_message', false);
  8224. x_ausgh_snsc.SaraUtils.setWizardSubmitVisible(false);
  8225.  
  8226. x_ausgh_snsc.SaraOAuth.getConfig(function (configData) {
  8227. for (var key in configData) {
  8228. var value = configData[key];
  8229.  
  8230. x_ausgh_snsc.config[key] = value;
  8231.  
  8232. if (!value) {
  8233. g_form.addErrorMessage('OAuth Configuration "' + key + '" is empty. Please check the current OAuth configuration.');
  8234. x_ausgh_snsc.SaraUtils.setWizardSubmitVisible(false);
  8235. break;
  8236. }
  8237. }
  8238.  
  8239. setTimeout(function () {
  8240. checkToken();
  8241. }, 100);
  8242. });
  8243. }
  8244.  
  8245. function checkToken() {
  8246. var technicalUser = x_ausgh_snsc.config[x_ausgh_snsc.SaraCommon.CONFIG_NAME.TECHNICAL_USER];
  8247. var sapiEndpoint = x_ausgh_snsc.config[x_ausgh_snsc.SaraCommon.CONFIG_NAME.SAPI_ENDPOINT];
  8248. x_ausgh_snsc.SaraOAuth.checkOAuthToken(technicalUser, sapiEndpoint, true, {
  8249. onValid: function () {
  8250. x_ausgh_snsc.SaraUtils.setWizardSubmitVisible(true);
  8251. },
  8252. onInvalid: function () {
  8253. g_form.addErrorMessage('Tokens are empty, invalid or expired! Please contact your administrator for resolving this problem.');
  8254. },
  8255. onError: function (errorMessage) {
  8256. g_form.addErrorMessage(errorMessage);
  8257. }
  8258. });
  8259. }
  8260. ]]></script>
  8261. </client_script>
  8262. <client_script>
  8263. <name>Import Services OnSubmit</name>
  8264. <active>true</active>
  8265. <type>onSubmit</type>
  8266. <script><![CDATA[function onSubmit() {
  8267. if (x_ausgh_snsc.isOk) {
  8268. return true;
  8269. }
  8270.  
  8271. var importDialog = new GlideDialogWindow('hierarchical_progress_viewer');
  8272. importDialog.setPreference('sysparm_ajax_processor', 'x_ausgh_snsc.SaraConsumerRunner');
  8273. importDialog.setPreference('sysparm_catid', g_form.getValue('sara_target_category').toString());
  8274. importDialog.setSize(400, 300);
  8275. importDialog.setTitle('Importing service...');
  8276.  
  8277. importDialog.on('executionComplete', function (trackerObj) {
  8278. x_ausgh_snsc.log('executionComplete', trackerObj);
  8279.  
  8280. if (trackerObj.result && trackerObj.result.info) {
  8281. importDialog.setTitle(trackerObj.result.msg);
  8282. g_form.setValue('sara_message', trackerObj.result.info);
  8283.  
  8284. x_ausgh_snsc.isOk = true;
  8285. x_ausgh_snsc.log('Go to next panel', x_ausgh_snsc.isOk);
  8286. g_expert.next();
  8287.  
  8288.  
  8289. x_ausgh_snsc.log('Destroy diablog', importDialog);
  8290. importDialog.destroy();
  8291. }
  8292. });
  8293.  
  8294. importDialog.on("renderStatus", function (trackerObj) {
  8295. x_ausgh_snsc.log('renderStatus', trackerObj);
  8296.  
  8297. if (trackerObj && trackerObj.result && trackerObj.result.msg) {
  8298. importDialog.setTitle(trackerObj.result.msg);
  8299. }
  8300. });
  8301.  
  8302. // Render the viewer
  8303. importDialog.render();
  8304.  
  8305. return false;
  8306. }
  8307. ]]></script>
  8308. </client_script>
  8309. </panel>
  8310. <panel>
  8311. <name>Import Services Completed</name>
  8312. <title>Import Services Completed</title>
  8313. <class>expert_panel</class>
  8314. <description/>
  8315. <previous_message>Previous</previous_message>
  8316. <next_message>Next</next_message>
  8317. <complete_message>Done</complete_message>
  8318. </panel>
  8319. </panels>
  8320.  
  8321. <transitions>
  8322. <transition>
  8323. <from>Import Services</from>
  8324. <to>Import Services Completed</to>
  8325. <order>100</order>
  8326. <condition>[sara_target_category]!=^EQ</condition>
  8327. <transition_script><![CDATA[gs.addInfoMessage(wizard.sara_message.toString());
  8328. ]]></transition_script>
  8329. </transition>
  8330. </transitions>
  8331. </wizard>
  8332.  
  8333. <wizard>
  8334. <name>Automic Clean-up</name>
  8335. <type>expert</type>
  8336. <banner_type>fixed</banner_type>
  8337. <roles>admin</roles>
  8338. <first_panel>Automic Cleanup</first_panel>
  8339. <variables>
  8340. <variable/>
  8341. </variables>
  8342.  
  8343. <panels>
  8344. <panel>
  8345. <name>Cleanup Catalog Items</name>
  8346. <title>Cleanup Catalog Items</title>
  8347. <class>expert_panel</class>
  8348. <description>Cleanup all Automic SARA stuffs. This will delete all subcategories and service items.</description>
  8349. <previous_message>Previous</previous_message>
  8350. <next_message>Cleanup</next_message>
  8351. <complete_message>Done</complete_message>
  8352. </panel>
  8353. <panel>
  8354. <name>Cleanup Catalog Items Completed</name>
  8355. <title>Cleanup Catalog Items Completed</title>
  8356. <class>expert_panel</class>
  8357. <description>Cleanup successfully!</description>
  8358. <previous_message>Previous</previous_message>
  8359. <next_message>Next</next_message>
  8360. <complete_message>Done</complete_message>
  8361. </panel>
  8362. </panels>
  8363.  
  8364. <transitions>
  8365. <transition>
  8366. <from>Cleanup Catalog Items</from>
  8367. <to>Cleanup Catalog Items Completed</to>
  8368. <order>100</order>
  8369. <condition/>
  8370. <transition_script>
  8371. <![CDATA[x_ausgh_snsc.SaraUtils.cleanup();]]>
  8372. </transition_script>
  8373. </transition>
  8374. </transitions>
  8375. </wizard>
  8376. </wizards>
  8377.  
  8378.  
  8379. <processors>
  8380. <processor>
  8381. <name>SaraUpdateStatus</name>
  8382. <type>script</type>
  8383. <active>true</active>
  8384. <description>Sara REST api for updating status of worflow remotely</description>
  8385. <path>sara_update_status</path>
  8386. <script><![CDATA[var LOGGER = new x_ausgh_snsc.SaraLog('SaraUpdateStatus');
  8387. var runId = g_request.getParameter('runId');
  8388. var status = g_request.getParameter('status');
  8389. var error = 0;
  8390. var result = {};
  8391.  
  8392. LOGGER.info('SaraUpdateStatus: RunId = {0}, Status = {1}', runId, status);
  8393. LOGGER.info('SaraUpdateStatus: Request user = ' + gs.getUserName());
  8394.  
  8395. if (!runId) {
  8396. error += 1;
  8397. }
  8398.  
  8399. if (!status) {
  8400. error += 1;
  8401. }
  8402.  
  8403. if (error === 0) {
  8404. runId = +runId;
  8405.  
  8406. if (isNaN(runId)) {
  8407. result = {
  8408. code: 99,
  8409. message: 'The runId must be digits!'
  8410. };
  8411. } else {
  8412. var glideHelper = new x_ausgh_snsc.SaraGlideHelper();
  8413. var reqItem = glideHelper.getData('sc_req_item', {
  8414. 'correlation_id': runId.toString()
  8415. });
  8416.  
  8417. if (reqItem) {
  8418. LOGGER.info('Found current request item (correlation_id = {0}, sys_id = {1})', runId, reqItem['sys_id']);
  8419.  
  8420. try {
  8421. glideHelper.updateData('sc_req_item', {
  8422. 'sys_id': reqItem['sys_id']
  8423. }, {
  8424. 'comments': status,
  8425. 'display_state': status
  8426. });
  8427.  
  8428. result = {
  8429. code: 200,
  8430. message: 'Update OK!',
  8431. sysId: reqItem['sys_id']
  8432. };
  8433. } catch (e) {
  8434. result = {
  8435. code: 99,
  8436. message: err
  8437. };
  8438. }
  8439. } else {
  8440. var message = x_ausgh_snsc.SaraUtils.formatString('No request item (correlation_id = {0}) found! Update status failed.', runId);
  8441. LOGGER.info(message);
  8442.  
  8443. result = {
  8444. code: 99,
  8445. message: message
  8446. };
  8447. }
  8448. }
  8449. } else {
  8450. result = {
  8451. code: 99,
  8452. message: 'The runId and status must be not null!'
  8453. }
  8454. }
  8455.  
  8456. var response = x_ausgh_snsc.SaraJSON.stringify(result);
  8457.  
  8458. LOGGER.debug('SaraUpdateStatus: {0}', response);
  8459.  
  8460. g_processor.writeOutput('application/json', response);
  8461. ]]></script>
  8462. </processor>
  8463. </processors>
  8464.  
  8465.  
  8466. <snsc_application>
  8467. <application>
  8468. <name>Automic SNSC</name>
  8469. <short_description>Automic ServiceNow Service Connector Application</short_description>
  8470. <active>true</active>
  8471. <user_role>x_ausgh_snsc.user</user_role>
  8472. <version>1.0.2</version>
  8473. <menu>u_ausgh_snsc_menu</menu>
  8474. <scope>x_ausgh_snsc</scope>
  8475. </application>
  8476. <application_menu>
  8477. <name>u_ausgh_snsc_menu</name>
  8478. <active>true</active>
  8479. <category>Custom Applications</category>
  8480. <title>Automic SNSC</title>
  8481. <roles>x_ausgh_snsc.user</roles>
  8482. <hint>Automic ServiceNow Service Connector Application</hint>
  8483. </application_menu>
  8484. <user_role>
  8485. <name>x_ausgh_snsc.user</name>
  8486. <description>User role for SNSC application</description>
  8487. </user_role>
  8488. </snsc_application>
  8489.  
  8490.  
  8491. <modules>
  8492. <module>
  8493. <title>Automic Configuration</title>
  8494. <order>0</order>
  8495. <active>true</active>
  8496. <link_type>SEPARATOR</link_type>
  8497. </module>
  8498. <module>
  8499. <title>Automic Clean-up</title>
  8500. <reference>wizard</reference>
  8501. <reference_name>Automic Clean-up</reference_name>
  8502. <order>10</order>
  8503. <active>true</active>
  8504. <link_type>DIRECT</link_type>
  8505. <query>/expert_shell.do?sysparm_sys_id=@{sys_id}&amp;sysparm_initial=true</query>
  8506. </module>
  8507. <module>
  8508. <title>Automic Import Services</title>
  8509. <reference>wizard</reference>
  8510. <reference_name>Automic Import Services</reference_name>
  8511. <order>20</order>
  8512. <active>true</active>
  8513. <link_type>DIRECT</link_type>
  8514. <query>/expert_shell.do?sysparm_sys_id=@{sys_id}&amp;sysparm_initial=true</query>
  8515. </module>
  8516. <module>
  8517. <title>Automic OAuth Configuration</title>
  8518. <reference>wizard</reference>
  8519. <reference_name>Automic OAuth Configuration</reference_name>
  8520. <order>30</order>
  8521. <active>true</active>
  8522. <link_type>DIRECT</link_type>
  8523. <query>/expert_shell.do?sysparm_sys_id=@{sys_id}&amp;sysparm_initial=true</query>
  8524. </module>
  8525. <module>
  8526. <title>Automic SNSC Components</title>
  8527. <order>100</order>
  8528. <active>true</active>
  8529. <link_type>SEPARATOR</link_type>
  8530. </module>
  8531. <module>
  8532. <title>Sara Tables</title>
  8533. <order>110</order>
  8534. <active>true</active>
  8535. <link_type>LIST</link_type>
  8536. <table_name>sys_db_object</table_name>
  8537. <filter>nameSTARTSWITHx_ausgh_snsc_</filter>
  8538. </module>
  8539. <module>
  8540. <title>Sara Transform Maps</title>
  8541. <order>115</order>
  8542. <active>true</active>
  8543. <link_type>LIST</link_type>
  8544. <table_name>sys_transform_map</table_name>
  8545. <filter>nameSTARTSWITHx_ausgh_snsc_</filter>
  8546. </module>
  8547. <module>
  8548. <title>Sara System Properties</title>
  8549. <reference>system_property</reference>
  8550. <reference_name>Automic</reference_name>
  8551. <order>120</order>
  8552. <active>true</active>
  8553. <link_type>DIRECT</link_type>
  8554. <query>/sys_properties_category.do?sys_id=@{sys_id}</query>
  8555. </module>
  8556. <module>
  8557. <title>Sara Script Includes</title>
  8558. <order>130</order>
  8559. <active>true</active>
  8560. <link_type>LIST</link_type>
  8561. <table_name>sys_script_include</table_name>
  8562. <filter>nameSTARTSWITHSara</filter>
  8563. </module>
  8564. <module>
  8565. <title>Sara UI Scripts</title>
  8566. <order>140</order>
  8567. <active>true</active>
  8568. <link_type>LIST</link_type>
  8569. <table_name>sys_ui_script</table_name>
  8570. <filter>nameSTARTSWITHx_ausgh_snsc.Sara</filter>
  8571. </module>
  8572. <module>
  8573. <title>Sara Fix Scripts</title>
  8574. <order>140</order>
  8575. <active>true</active>
  8576. <link_type>LIST</link_type>
  8577. <table_name>sys_script_fix</table_name>
  8578. <filter>nameSTARTSWITHSara</filter>
  8579. </module>
  8580. <module>
  8581. <title>Sara UI Pages</title>
  8582. <order>150</order>
  8583. <active>true</active>
  8584. <link_type>LIST</link_type>
  8585. <table_name>sys_ui_page</table_name>
  8586. <filter>nameSTARTSWITHsara_</filter>
  8587. </module>
  8588. <module>
  8589. <title>Sara UI Macros</title>
  8590. <order>160</order>
  8591. <active>true</active>
  8592. <link_type>LIST</link_type>
  8593. <table_name>sys_ui_macro</table_name>
  8594. <filter>nameSTARTSWITHsara_</filter>
  8595. </module>
  8596. <module>
  8597. <title>Sara Processors</title>
  8598. <order>170</order>
  8599. <active>true</active>
  8600. <link_type>LIST</link_type>
  8601. <table_name>sys_processor</table_name>
  8602. <filter>nameSTARTSWITHSara</filter>
  8603. </module>
  8604. <module>
  8605. <title>Sara Wizards</title>
  8606. <order>180</order>
  8607. <active>true</active>
  8608. <link_type>LIST</link_type>
  8609. <table_name>expert</table_name>
  8610. <filter>nameSTARTSWITHAutomic</filter>
  8611. </module>
  8612. <module>
  8613. <title>Sara Schedulers</title>
  8614. <order>190</order>
  8615. <active>true</active>
  8616. <link_type>LIST</link_type>
  8617. <table_name>sysauto</table_name>
  8618. <filter>nameSTARTSWITHSara</filter>
  8619. </module>
  8620. <module>
  8621. <title>Sara REST Messages</title>
  8622. <order>200</order>
  8623. <active>true</active>
  8624. <link_type>LIST</link_type>
  8625. <table_name>sys_rest_message</table_name>
  8626. <filter>nameSTARTSWITHSara</filter>
  8627. </module>
  8628. <module>
  8629. <title>Support</title>
  8630. <order>900</order>
  8631. <active>true</active>
  8632. <link_type>SEPARATOR</link_type>
  8633. </module>
  8634. <module>
  8635. <title>Used ServiceNow's Tables</title>
  8636. <order>910</order>
  8637. <active>true</active>
  8638. <link_type>LIST</link_type>
  8639. <table_name>sys_db_object</table_name>
  8640. <query>name=sc_category^ORname=sc_cat_item^ORname=item_option_new_set^ORname=io_set_item^ORname=sysauto_script^ORname=item_option_new</query>
  8641. </module>
  8642. <module>
  8643. <title>Sara Transform History</title>
  8644. <order>915</order>
  8645. <active>true</active>
  8646. <link_type>LIST</link_type>
  8647. <table_name>sys_import_set_run</table_name>
  8648. <query>sys_transform_mapSTARTSWITHx_ausgh_snsc</query>
  8649. </module>
  8650. <module>
  8651. <title>Contact Us</title>
  8652. <order>920</order>
  8653. <active>true</active>
  8654. <link_type>DIRECT</link_type>
  8655. <query>https://automationpassion.com/contact_us.do</query>
  8656. </module>
  8657. </modules>
  8658.  
  8659.  
  8660. <rest_messages>
  8661. <rest_message>
  8662. <name>Sara - SAPI Services</name>
  8663. <description>Sara Outbound Web Service for SAPI</description>
  8664. <rest_endpoint>${sapiEndpoint}</rest_endpoint>
  8665. </rest_message>
  8666. <rest_message>
  8667. <name>Sara - OAuth Services</name>
  8668. <description>Sara Outbound Web Service for OAuth</description>
  8669. <rest_endpoint>${oauthEndpoint}</rest_endpoint>
  8670. </rest_message>
  8671. </rest_messages>
  8672.  
  8673. </package>
  8674. </sara>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement