aspose_cells_cloud 20.7 → 20.11.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (311) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +46 -52
  4. data/lib/aspose_cells_cloud.rb +7 -1
  5. data/lib/aspose_cells_cloud/api/cells_api.rb +19867 -19233
  6. data/lib/aspose_cells_cloud/api_client.rb +493 -489
  7. data/lib/aspose_cells_cloud/api_error.rb +18 -8
  8. data/lib/aspose_cells_cloud/configuration.rb +4 -4
  9. data/lib/aspose_cells_cloud/models/cells_cloud_file_info.rb +230 -0
  10. data/lib/aspose_cells_cloud/models/{error.rb → cells_error.rb} +1 -1
  11. data/lib/aspose_cells_cloud/models/files_upload_result.rb +1 -1
  12. data/lib/aspose_cells_cloud/models/save_result.rb +8 -26
  13. data/lib/aspose_cells_cloud/models/sparkline.rb +226 -0
  14. data/lib/aspose_cells_cloud/models/sparkline_group.rb +434 -0
  15. data/lib/aspose_cells_cloud/models/sparkline_group_response.rb +221 -0
  16. data/lib/aspose_cells_cloud/models/sparkline_groups.rb +200 -0
  17. data/lib/aspose_cells_cloud/models/sparkline_groups_response.rb +221 -0
  18. data/lib/aspose_cells_cloud/models/split_result.rb +1 -1
  19. data/lib/aspose_cells_cloud/models/text_water_marker_request.rb +239 -239
  20. data/lib/aspose_cells_cloud/version.rb +25 -25
  21. data/spec/api/cells_api_spec.rb +2 -1
  22. data/spec/api/cells_auto_filter_api_spec.rb +2 -1
  23. data/spec/api/cells_chart_area_api_spec.rb +2 -1
  24. data/spec/api/cells_charts_api_spec.rb +2 -1
  25. data/spec/api/cells_conditional_formattings_api_spec.rb +2 -1
  26. data/spec/api/cells_hypelinks_api_spec.rb +2 -1
  27. data/spec/api/cells_list_objects_api_spec.rb +2 -1
  28. data/spec/api/cells_ole_objects_api_spec.rb +2 -1
  29. data/spec/api/cells_page_breaks_api_spec.rb +2 -1
  30. data/spec/api/cells_page_setup_api_spec.rb +2 -1
  31. data/spec/api/cells_pictures_api_spec.rb +2 -1
  32. data/spec/api/cells_pivot_tables_api_spec.rb +33 -1
  33. data/spec/api/cells_properties_api_spec.rb +2 -1
  34. data/spec/api/cells_ranges_api_spec.rb +2 -1
  35. data/spec/api/cells_save_as_api_spec.rb +2 -1
  36. data/spec/api/cells_shapes_api_spec.rb +3 -2
  37. data/spec/api/cells_simple_spec.rb +2 -1
  38. data/spec/api/cells_sparkline_group_spec.rb +43 -0
  39. data/spec/api/cells_storage_api_spec.rb +69 -68
  40. data/spec/api/cells_storage_spec.rb +3 -2
  41. data/spec/api/cells_task_api_spec.rb +2 -1
  42. data/spec/api/cells_workbook_api_spec.rb +3 -2
  43. data/spec/api/cells_worksheet_validations_api_spec.rb +2 -1
  44. data/spec/api/cells_worksheets_api_spec.rb +60 -58
  45. data/spec/spec_helper.rb +6 -3
  46. metadata +12 -297
  47. data/Gemfile +0 -7
  48. data/Rakefile +0 -8
  49. data/aspose_cells_cloud-20.2.gem +0 -0
  50. data/aspose_cells_cloud-20.4.gem +0 -0
  51. data/aspose_cells_cloud-20.6.gem +0 -0
  52. data/aspose_cells_cloud.gemspec +0 -48
  53. data/data/Book1.xlsx +0 -0
  54. data/data/ImportData.xlsx +0 -0
  55. data/data/NewCopy.xlsx +0 -0
  56. data/data/OLEDoc.docx +0 -0
  57. data/data/PivTestFile2.xlsx +0 -0
  58. data/data/ReportData.xml +0 -1
  59. data/data/TestCase.xlsx +0 -0
  60. data/data/TestImportData.xlsx +0 -0
  61. data/data/TestImportDataCSV.csv +0 -3
  62. data/data/WaterMark.png +0 -0
  63. data/data/markdowntest.md +0 -41
  64. data/data/myDocument.xlsx +0 -0
  65. data/data/word.jpg +0 -0
  66. data/docs/AboveAverage.md +0 -10
  67. data/docs/AccessTokenResponse.md +0 -15
  68. data/docs/Area.md +0 -13
  69. data/docs/AutoFilter.md +0 -11
  70. data/docs/AutoFilterResponse.md +0 -10
  71. data/docs/AutoFitterOptions.md +0 -10
  72. data/docs/AutoShape.md +0 -42
  73. data/docs/AutoShapeResponse.md +0 -10
  74. data/docs/AutoShapes.md +0 -9
  75. data/docs/AutoShapesResponse.md +0 -10
  76. data/docs/Border.md +0 -10
  77. data/docs/CalculationOptions.md +0 -11
  78. data/docs/Cell.md +0 -24
  79. data/docs/CellArea.md +0 -11
  80. data/docs/CellResponse.md +0 -10
  81. data/docs/CellValue.md +0 -12
  82. data/docs/Cells.md +0 -14
  83. data/docs/CellsApi.md +0 -14581
  84. data/docs/CellsCloudResponse.md +0 -9
  85. data/docs/CellsColor.md +0 -12
  86. data/docs/CellsDocumentProperties.md +0 -9
  87. data/docs/CellsDocumentPropertiesResponse.md +0 -10
  88. data/docs/CellsDocumentProperty.md +0 -11
  89. data/docs/CellsDocumentPropertyResponse.md +0 -10
  90. data/docs/CellsObjectOperateTaskParameter.md +0 -10
  91. data/docs/CellsResponse.md +0 -10
  92. data/docs/Chart.md +0 -51
  93. data/docs/ChartArea.md +0 -21
  94. data/docs/ChartAreaResponse.md +0 -10
  95. data/docs/ChartFrame.md +0 -21
  96. data/docs/ChartOperateParameter.md +0 -17
  97. data/docs/Charts.md +0 -9
  98. data/docs/ChartsResponse.md +0 -10
  99. data/docs/Color.md +0 -11
  100. data/docs/ColorFilter.md +0 -12
  101. data/docs/ColorFilterRequest.md +0 -10
  102. data/docs/ColorScale.md +0 -13
  103. data/docs/Column.md +0 -13
  104. data/docs/ColumnResponse.md +0 -10
  105. data/docs/Columns.md +0 -11
  106. data/docs/ColumnsResponse.md +0 -10
  107. data/docs/Comment.md +0 -19
  108. data/docs/CommentResponse.md +0 -10
  109. data/docs/Comments.md +0 -9
  110. data/docs/CommentsResponse.md +0 -10
  111. data/docs/ConditionalFormatting.md +0 -10
  112. data/docs/ConditionalFormattingIcon.md +0 -10
  113. data/docs/ConditionalFormattingResponse.md +0 -10
  114. data/docs/ConditionalFormattingValue.md +0 -10
  115. data/docs/ConditionalFormattings.md +0 -10
  116. data/docs/ConditionalFormattingsResponse.md +0 -10
  117. data/docs/ConvertTaskParameter.md +0 -10
  118. data/docs/CopyOptions.md +0 -13
  119. data/docs/CreatePivotTableRequest.md +0 -14
  120. data/docs/CustomFilter.md +0 -9
  121. data/docs/CustomParserConfig.md +0 -10
  122. data/docs/DataBar.md +0 -19
  123. data/docs/DataBarBorder.md +0 -9
  124. data/docs/DataSorter.md +0 -11
  125. data/docs/DifSaveOptions.md +0 -15
  126. data/docs/DiscUsage.md +0 -9
  127. data/docs/DynamicFilter.md +0 -10
  128. data/docs/Error.md +0 -11
  129. data/docs/ErrorDetails.md +0 -9
  130. data/docs/FileSource.md +0 -9
  131. data/docs/FileVersion.md +0 -14
  132. data/docs/FileVersions.md +0 -8
  133. data/docs/FilesList.md +0 -8
  134. data/docs/FilesUploadResult.md +0 -9
  135. data/docs/FillFormat.md +0 -13
  136. data/docs/FillFormatResponse.md +0 -10
  137. data/docs/FilterColumn.md +0 -16
  138. data/docs/Font.md +0 -17
  139. data/docs/FontSetting.md +0 -12
  140. data/docs/FormatCondition.md +0 -22
  141. data/docs/GradientFill.md +0 -11
  142. data/docs/GradientFillStop.md +0 -10
  143. data/docs/HorizontalPageBreak.md +0 -10
  144. data/docs/HorizontalPageBreakResponse.md +0 -10
  145. data/docs/HorizontalPageBreaks.md +0 -9
  146. data/docs/HorizontalPageBreaksResponse.md +0 -10
  147. data/docs/HtmlSaveOptions.md +0 -27
  148. data/docs/Hyperlink.md +0 -12
  149. data/docs/HyperlinkResponse.md +0 -10
  150. data/docs/Hyperlinks.md +0 -10
  151. data/docs/HyperlinksResponse.md +0 -10
  152. data/docs/IconFilter.md +0 -9
  153. data/docs/IconSet.md +0 -13
  154. data/docs/ImageSaveOptions.md +0 -27
  155. data/docs/ImportBatchDataOption.md +0 -12
  156. data/docs/ImportCSVDataOption.md +0 -17
  157. data/docs/ImportDataTaskParameter.md +0 -10
  158. data/docs/ImportDoubleArrayOption.md +0 -15
  159. data/docs/ImportIntArrayOption.md +0 -15
  160. data/docs/ImportOption.md +0 -11
  161. data/docs/ImportStringArrayOption.md +0 -15
  162. data/docs/Legend.md +0 -23
  163. data/docs/LegendResponse.md +0 -10
  164. data/docs/Line.md +0 -26
  165. data/docs/LineFormat.md +0 -24
  166. data/docs/LineResponse.md +0 -10
  167. data/docs/Link.md +0 -11
  168. data/docs/LinkElement.md +0 -8
  169. data/docs/ListColumn.md +0 -9
  170. data/docs/ListObject.md +0 -23
  171. data/docs/ListObjectOperateParameter.md +0 -9
  172. data/docs/ListObjectResponse.md +0 -10
  173. data/docs/ListObjects.md +0 -9
  174. data/docs/ListObjectsResponse.md +0 -10
  175. data/docs/MHtmlSaveOptions.md +0 -27
  176. data/docs/MarkdownSaveOptions.md +0 -18
  177. data/docs/MergedCell.md +0 -12
  178. data/docs/MergedCellResponse.md +0 -10
  179. data/docs/MergedCells.md +0 -10
  180. data/docs/MergedCellsResponse.md +0 -10
  181. data/docs/MultipleFilter.md +0 -7
  182. data/docs/MultipleFilters.md +0 -9
  183. data/docs/Name.md +0 -15
  184. data/docs/NameResponse.md +0 -10
  185. data/docs/Names.md +0 -10
  186. data/docs/NamesResponse.md +0 -10
  187. data/docs/NegativeBarFormat.md +0 -11
  188. data/docs/ObjectExist.md +0 -9
  189. data/docs/OdsSaveOptions.md +0 -15
  190. data/docs/OleObject.md +0 -49
  191. data/docs/OleObjectResponse.md +0 -10
  192. data/docs/OleObjects.md +0 -9
  193. data/docs/OleObjectsResponse.md +0 -10
  194. data/docs/OoxmlSaveOptions.md +0 -16
  195. data/docs/OperateObject.md +0 -9
  196. data/docs/OperateObjectPosition.md +0 -13
  197. data/docs/OperateParameter.md +0 -8
  198. data/docs/PageBreakOperateParameter.md +0 -14
  199. data/docs/PageSection.md +0 -12
  200. data/docs/PageSectionsResponse.md +0 -10
  201. data/docs/PageSetup.md +0 -42
  202. data/docs/PageSetupOperateParameter.md +0 -9
  203. data/docs/PageSetupResponse.md +0 -10
  204. data/docs/PasswordRequest.md +0 -8
  205. data/docs/PasteOptions.md +0 -11
  206. data/docs/PatternFill.md +0 -14
  207. data/docs/PdfSaveOptions.md +0 -25
  208. data/docs/PdfSecurityOptions.md +0 -17
  209. data/docs/PicFormatOption.md +0 -13
  210. data/docs/Picture.md +0 -48
  211. data/docs/PictureResponse.md +0 -10
  212. data/docs/Pictures.md +0 -9
  213. data/docs/PicturesResponse.md +0 -10
  214. data/docs/PivotField.md +0 -46
  215. data/docs/PivotFieldResponse.md +0 -10
  216. data/docs/PivotFilter.md +0 -16
  217. data/docs/PivotFilterResponse.md +0 -10
  218. data/docs/PivotFiltersResponse.md +0 -10
  219. data/docs/PivotItem.md +0 -11
  220. data/docs/PivotTable.md +0 -76
  221. data/docs/PivotTableFieldRequest.md +0 -8
  222. data/docs/PivotTableOperateParameter.md +0 -16
  223. data/docs/PivotTableResponse.md +0 -10
  224. data/docs/PivotTables.md +0 -9
  225. data/docs/PivotTablesResponse.md +0 -10
  226. data/docs/ProtectSheetParameter.md +0 -23
  227. data/docs/Range.md +0 -16
  228. data/docs/RangeCopyRequest.md +0 -11
  229. data/docs/RangeSetOutlineBorderRequest.md +0 -11
  230. data/docs/RangeSetStyleRequest.md +0 -9
  231. data/docs/RangeValueResponse.md +0 -10
  232. data/docs/Ranges.md +0 -8
  233. data/docs/RangesResponse.md +0 -10
  234. data/docs/ResultDestination.md +0 -10
  235. data/docs/Row.md +0 -15
  236. data/docs/RowResponse.md +0 -10
  237. data/docs/Rows.md +0 -11
  238. data/docs/RowsResponse.md +0 -10
  239. data/docs/SaveOptions.md +0 -15
  240. data/docs/SaveResponse.md +0 -10
  241. data/docs/SaveResult.md +0 -10
  242. data/docs/SaveResultTaskParameter.md +0 -9
  243. data/docs/ShadowEffect.md +0 -14
  244. data/docs/Shape.md +0 -42
  245. data/docs/ShapeOperateParameter.md +0 -9
  246. data/docs/ShapeResponse.md +0 -10
  247. data/docs/Shapes.md +0 -9
  248. data/docs/ShapesResponse.md +0 -10
  249. data/docs/SingleValue.md +0 -9
  250. data/docs/SingleValueResponse.md +0 -10
  251. data/docs/SmartMarkerTaskParameter.md +0 -10
  252. data/docs/SolidFill.md +0 -10
  253. data/docs/SortKey.md +0 -10
  254. data/docs/SplitResult.md +0 -8
  255. data/docs/SplitResultDocument.md +0 -9
  256. data/docs/SplitResultResponse.md +0 -10
  257. data/docs/SplitWorkbookTaskParameter.md +0 -13
  258. data/docs/SpreadsheetML2003SaveOptions.md +0 -18
  259. data/docs/StorageExist.md +0 -8
  260. data/docs/StorageFile.md +0 -12
  261. data/docs/Style.md +0 -31
  262. data/docs/StyleResponse.md +0 -10
  263. data/docs/SvgSaveOptions.md +0 -16
  264. data/docs/TaskData.md +0 -8
  265. data/docs/TaskDescription.md +0 -9
  266. data/docs/TaskParameter.md +0 -7
  267. data/docs/TextItem.md +0 -9
  268. data/docs/TextItems.md +0 -9
  269. data/docs/TextItemsResponse.md +0 -10
  270. data/docs/TextOptions.md +0 -23
  271. data/docs/TextureFill.md +0 -13
  272. data/docs/ThemeColor.md +0 -9
  273. data/docs/TilePicOption.md +0 -13
  274. data/docs/Title.md +0 -28
  275. data/docs/TitleResponse.md +0 -10
  276. data/docs/Top10.md +0 -10
  277. data/docs/Top10Filter.md +0 -11
  278. data/docs/TxtSaveOptions.md +0 -19
  279. data/docs/Validation.md +0 -24
  280. data/docs/ValidationResponse.md +0 -10
  281. data/docs/Validations.md +0 -10
  282. data/docs/ValidationsResponse.md +0 -10
  283. data/docs/ValueType.md +0 -7
  284. data/docs/VerticalPageBreak.md +0 -10
  285. data/docs/VerticalPageBreakResponse.md +0 -10
  286. data/docs/VerticalPageBreaks.md +0 -9
  287. data/docs/VerticalPageBreaksResponse.md +0 -10
  288. data/docs/Workbook.md +0 -18
  289. data/docs/WorkbookEncryptionRequest.md +0 -10
  290. data/docs/WorkbookOperateParameter.md +0 -8
  291. data/docs/WorkbookProtectionRequest.md +0 -9
  292. data/docs/WorkbookReplaceResponse.md +0 -11
  293. data/docs/WorkbookResponse.md +0 -10
  294. data/docs/WorkbookSettings.md +0 -52
  295. data/docs/WorkbookSettingsOperateParameter.md +0 -9
  296. data/docs/WorkbookSettingsResponse.md +0 -10
  297. data/docs/Worksheet.md +0 -39
  298. data/docs/WorksheetMovingRequest.md +0 -9
  299. data/docs/WorksheetReplaceResponse.md +0 -11
  300. data/docs/WorksheetResponse.md +0 -10
  301. data/docs/Worksheets.md +0 -9
  302. data/docs/WorksheetsResponse.md +0 -10
  303. data/docs/XlsSaveOptions.md +0 -15
  304. data/docs/XlsbSaveOptions.md +0 -15
  305. data/docs/XpsSaveOptions.md +0 -15
  306. data/git_push.sh +0 -55
  307. data/runTest.sh +0 -4
  308. data/spec/api/cells_autoshapes_api_spec.rb +0 -66
  309. data/spec/api/cells_one_spec.rb +0 -37
  310. data/test.pdf +0 -0
  311. data/testResult.txt +0 -15
@@ -1,489 +1,493 @@
1
- =begin
2
- --------------------------------------------------------------------------------------------------------------------
3
- Copyright (c) 2020 Aspose.Cells Cloud
4
- Permission is hereby granted, free of charge, to any person obtaining a copy
5
- of this software and associated documentation files (the "Software"), to deal
6
- in the Software without restriction, including without limitation the rights
7
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- copies of the Software, and to permit persons to whom the Software is
9
- furnished to do so, subject to the following conditions:
10
- The above copyright notice and this permission notice shall be included in all
11
- copies or substantial portions of the Software.
12
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
18
- SOFTWARE.
19
- --------------------------------------------------------------------------------------------------------------------
20
-
21
- =end
22
-
23
- require 'date'
24
- require 'json'
25
- require 'logger'
26
- require 'tempfile'
27
- require 'uri'
28
- require 'faraday'
29
- require_relative 'version'
30
- require_relative 'api_error'
31
-
32
- module AsposeCellsCloud
33
- class ApiClient
34
- # The Configuration object holding settings to be used in the API client.
35
- attr_accessor :config
36
-
37
- # Defines the headers to be used in HTTP requests of all API calls by default.
38
- #
39
- # @return [Hash]
40
- attr_accessor :default_headers
41
-
42
- attr_accessor :get_access_token_time
43
- # Initializes the ApiClient
44
- # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
45
- def initialize(config = Configuration.default)
46
- @config = config
47
-
48
- @default_headers = {
49
- 'Content-Type' => "application/json",
50
- 'x-aspose-client' => "ruby sdk",
51
- 'x-aspose-version' => "#{ AsposeCellsCloud::VERSION }"
52
- }
53
- end
54
-
55
- def self.default
56
- @@default ||= ApiClient.new
57
- end
58
-
59
- # Call an API with given options.
60
- #
61
- # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
62
- # the data deserialized from response body (could be nil), response status code and response headers.
63
- def call_api(http_method, path, opts = {})
64
- response = build_request(http_method, path, opts)
65
- download_file response if opts[:return_type] == 'File'
66
-
67
- if @config.debugging
68
- @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
69
- end
70
-
71
- unless response.success?
72
-
73
- if response.status == 0
74
- # Errors from libcurl will be made visible here
75
- fail ApiError.new(:code => 0,
76
- :message => response.reason_phrase)
77
- else
78
- fail ApiError.new(:code => response.status,
79
- :response_headers => response.headers,
80
- :response_body => response.body),
81
- response.reason_phrase
82
- end
83
- end
84
-
85
- if opts[:return_type]
86
- data = deserialize(response, opts[:return_type])
87
- else
88
- data = nil
89
- end
90
- [data, response.status, response.headers]
91
- end
92
-
93
- # Builds the HTTP request
94
- #
95
- # @param [String] http_method HTTP method/verb (e.g. POST)
96
- # @param [String] path URL path (e.g. /account/new)
97
- # @option opts [Hash] :header_params Header parameters
98
- # @option opts [Hash] :query_params Query parameters
99
- # @option opts [Hash] :form_params Query parameters
100
- # @option opts [Object] :body HTTP body (JSON/XML)
101
- # @return [Faraday::Response] A Faraday Response
102
- def build_request(http_method, path, opts = {})
103
- url = build_request_url(path)
104
- http_method = http_method.to_sym.downcase
105
-
106
- header_params = @default_headers.merge(opts[:header_params] || {})
107
- query_params = opts[:query_params] || {}
108
- form_params = opts[:form_params] || {}
109
- body = opts[:body] || {}
110
-
111
- update_params_for_auth! header_params, query_params, opts[:auth_names]
112
-
113
- req_opts = {
114
- :method => http_method,
115
- :headers => header_params,
116
- :params => query_params,
117
- :body => body
118
- }
119
-
120
- if [:post, :patch, :put, :delete].include?(http_method)
121
- req_body = build_request_body(header_params, form_params, opts[:body])
122
- req_opts.update :body => req_body
123
- if @config.debugging
124
- @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
125
- end
126
- end
127
-
128
- # OAuth 2.0
129
- req_opts[:params] = opts[:query_params]
130
-
131
- add_o_auth_token(req_opts)
132
-
133
-
134
- conn = Faraday.new url, {:params => query_params, :headers => header_params} do |f|
135
- f.request :multipart
136
- f.request :url_encoded
137
- f.adapter Faraday.default_adapter
138
- end
139
-
140
- if req_opts[:body] == {}
141
- req_opts[:body] = nil
142
- end
143
-
144
- case http_method
145
- when :post
146
- return conn.post url, req_opts[:body]
147
- when :put
148
- return conn.put url, req_opts[:body]
149
- when :get
150
- return conn.get url, req_opts[:body]
151
- else
152
- return conn.delete url do |c|
153
- c.body = req_opts[:body]
154
- end
155
- end
156
- end
157
-
158
- # Check if the given MIME is a JSON MIME.
159
- # JSON MIME examples:
160
- # application/json
161
- # application/json; charset=UTF8
162
- # APPLICATION/JSON
163
- # */*
164
- # @param [String] mime MIME
165
- # @return [Boolean] True if the MIME is application/json
166
- def json_mime?(mime)
167
- (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
168
- end
169
-
170
- # Deserialize the response to the given return type.
171
- #
172
- # @param [Response] response HTTP response
173
- # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
174
- def deserialize(response, return_type)
175
- body = response.body
176
-
177
- # handle file downloading - return the File instance processed in request callbacks
178
- # note that response body is empty when the file is written in chunks in request on_body callback
179
- return @tempfile if return_type == 'File'
180
-
181
- return nil if body.nil? || body.empty?
182
-
183
- # return response body directly for String return type
184
- return body if return_type == 'String'
185
-
186
- # ensuring a default content type
187
- content_type = response.headers['Content-Type'] || 'application/json'
188
-
189
- raise "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
190
-
191
- begin
192
- data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
193
- rescue JSON::ParserError => e
194
- if %w(String Date DateTime).include?(return_type)
195
- data = body
196
- else
197
- raise e
198
- end
199
- end
200
-
201
- convert_to_type data, return_type
202
- end
203
-
204
- # Convert data to the given return type.
205
- # @param [Object] data Data to be converted
206
- # @param [String] return_type Return type
207
- # @return [Mixed] Data in a particular type
208
- def convert_to_type(data, return_type)
209
- return nil if data.nil?
210
- case return_type
211
- when 'String'
212
- data.to_s
213
- when 'Integer'
214
- data.to_i
215
- when 'Float'
216
- data.to_f
217
- when 'BOOLEAN'
218
- data == true
219
- when 'DateTime'
220
- # parse date time (expecting ISO 8601 format)
221
- DateTime.parse data
222
- when 'Date'
223
- # parse date time (expecting ISO 8601 format)
224
- Date.parse data
225
- when 'Object'
226
- # generic object (usually a Hash), return directly
227
- data
228
- when /\AArray<(.+)>\z/
229
- # e.g. Array<Pet>
230
- sub_type = $1
231
- data.map {|item| convert_to_type(item, sub_type) }
232
- when /\AHash\<String, (.+)\>\z/
233
- # e.g. Hash<String, Integer>
234
- sub_type = $1
235
- {}.tap do |hash|
236
- data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
237
- end
238
- else
239
- # models, e.g. Pet
240
- AsposeCellsCloud.const_get(return_type).new.tap do |model|
241
- model.build_from_hash data
242
- end
243
- end
244
- end
245
-
246
- # Save response body into a file in (the defined) temporary folder, using the filename
247
- # from the "Content-Disposition" header if provided, otherwise a random filename.
248
- # The response body is written to the file in chunks in order to handle files which
249
- # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
250
- # process can use.
251
- #
252
- # @see Configuration#temp_folder_path
253
- def download_file(response)
254
- tempfile = nil
255
- encoding = nil
256
-
257
- content_disposition = response.headers['Content-Disposition']
258
- if content_disposition and content_disposition =~ /filename=/i
259
- filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
260
- prefix = sanitize_filename(filename)
261
- else
262
- prefix = 'download-'
263
- end
264
- prefix = prefix + '-' unless prefix.end_with?('-')
265
- encoding = response.body.encoding
266
- tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
267
- @tempfile = tempfile
268
-
269
- tempfile.write(response.body)
270
-
271
- response.on_complete do |resp|
272
- tempfile.close
273
- @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
274
- "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
275
- "will be deleted automatically with GC. It's also recommended to delete the temp file "\
276
- "explicitly with `tempfile.delete`"
277
- end
278
- end
279
-
280
- # Sanitize filename by removing path.
281
- # e.g. ../../sun.gif becomes sun.gif
282
- #
283
- # @param [String] filename the filename to be sanitized
284
- # @return [String] the sanitized filename
285
- def sanitize_filename(filename)
286
- filename.gsub(/.*[\/\\]/, '')
287
- end
288
-
289
- def build_request_url(path)
290
- # Add leading and trailing slashes to path
291
- path = "/#{path}".gsub(/\/+/, '/')
292
- URI.encode(@config.base_url + path)
293
- end
294
-
295
- # Builds the HTTP request body
296
- #
297
- # @param [Hash] header_params Header parameters
298
- # @param [Hash] form_params Query parameters
299
- # @param [Object] body HTTP body (JSON/XML)
300
- # @return [String] HTTP body data in the form of string
301
- def build_request_body(header_params, form_params, body)
302
- # http form
303
- if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
304
- header_params['Content-Type'] == 'multipart/form-data'
305
- data = {}
306
- form_params.each do |key, value|
307
- case value
308
- when ::File
309
- data[key] = Faraday::UploadIO.new(value.path, MimeMagic.by_magic(value).to_s, key)
310
- when ::Array, nil
311
- # let typhoeus handle File, Array and nil parameters
312
- data[key] = value
313
- else
314
- data[key] = value.to_s
315
- end
316
- end
317
- elsif body
318
- data = body.is_a?(String) ? body : body.to_json
319
- else
320
- data = nil
321
- end
322
- data
323
- end
324
-
325
- # Update hearder and query params based on authentication settings.
326
- #
327
- # @param [Hash] header_params Header parameters
328
- # @param [Hash] query_params Query parameters
329
- # @param [String] auth_names Authentication scheme name
330
- def update_params_for_auth!(header_params, query_params, auth_names)
331
- Array(auth_names).each do |auth_name|
332
- auth_setting = @config.auth_settings[auth_name]
333
- next unless auth_setting
334
- case auth_setting[:in]
335
- when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
336
- when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
337
- else raise ArgumentError, 'Authentication token must be in `query` of `header`'
338
- end
339
- end
340
- end
341
-
342
- # Sets user agent in HTTP header
343
- #
344
- # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0)
345
- def user_agent=(user_agent)
346
- @user_agent = user_agent
347
- @default_headers['User-Agent'] = @user_agent
348
- end
349
-
350
- # Return Accept header based on an array of accepts provided.
351
- # @param [Array] accepts array for Accept
352
- # @return [String] the Accept header (e.g. application/json)
353
- def select_header_accept(accepts)
354
- return nil if accepts.nil? || accepts.empty?
355
- # use JSON when present, otherwise use all of the provided
356
- json_accept = accepts.find { |s| json_mime?(s) }
357
- return json_accept || accepts.join(',')
358
- end
359
-
360
- # Return Content-Type header based on an array of content types provided.
361
- # @param [Array] content_types array for Content-Type
362
- # @return [String] the Content-Type header (e.g. application/json)
363
- def select_header_content_type(content_types)
364
- # use application/json by default
365
- return 'application/json' if content_types.nil? || content_types.empty?
366
- # use JSON when present, otherwise use the first one
367
- json_content_type = content_types.find { |s| json_mime?(s) }
368
- return json_content_type || content_types.first
369
- end
370
-
371
- # Convert object (array, hash, object, etc) to JSON string.
372
- # @param [Object] model object to be converted into JSON string
373
- # @return [String] JSON string representation of the object
374
- def object_to_http_body(model)
375
- return '"' + model + '"' if model.is_a?(String)
376
- return model if model.nil?
377
- local_body = nil
378
- if model.is_a?(Array)
379
- local_body = model.map{|m| object_to_hash(m) }
380
- else
381
- local_body = object_to_hash(model)
382
- end
383
- local_body.to_json
384
- end
385
-
386
- # Convert object(non-array) to hash.
387
- # @param [Object] obj object to be converted into JSON string
388
- # @return [String] JSON string representation of the object
389
- def object_to_hash(obj)
390
- if obj.respond_to?(:to_hash)
391
- obj.to_hash
392
- else
393
- obj
394
- end
395
- end
396
-
397
- # Build parameter value according to the given collection format.
398
- # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
399
- def build_collection_param(param, collection_format)
400
- case collection_format
401
- when :csv
402
- param.join(',')
403
- when :ssv
404
- param.join(' ')
405
- when :tsv
406
- param.join("\t")
407
- when :pipes
408
- param.join('|')
409
- when :multi
410
- # return the array directly as faraday will handle it as expected
411
- param
412
- else
413
- fail "unknown collection format: #{collection_format.inspect}"
414
- end
415
- end
416
-
417
- # Request access and refresh tokens if needed
418
- def request_token_if_needed
419
- # check token exists
420
- if @config.access_token
421
- now = Time.now
422
- time_difference = now - $get_access_token_time
423
- if time_difference < 86300
424
- return
425
- end
426
- end
427
-
428
- # resource path
429
- local_var_path = "/connect/token"
430
- if @config.api_version === "v1.1"
431
- local_var_path ="/oauth2/token"
432
- end
433
- url = build_request_url(local_var_path).gsub('/'+config.api_version, '')
434
- #url = build_request_url(local_var_path).gsub('/v3.0', '')
435
-
436
- # header parameters
437
- header_params = {}
438
- # HTTP header 'Content-Type'
439
- header_params['Content-Type'] = select_header_content_type(['application/x-www-form-urlencoded'])
440
-
441
- query_params = {}
442
- # form parameters
443
- form_params = {}
444
- form_params["grant_type"] = 'client_credentials'
445
- form_params["client_id"] = @config.app_sid
446
- form_params["client_secret"] = @config.app_key
447
-
448
- body = {}
449
-
450
-
451
- req_opts = {
452
- :headers => header_params,
453
- :params => query_params,
454
- :body => body
455
- }
456
-
457
-
458
- req_body = build_request_body(header_params, form_params, body)
459
- req_opts.update :body => req_body
460
-
461
- req_opts[:params] = query_params
462
-
463
-
464
- conn = Faraday.new url, {:params => query_params, :headers => header_params} do |f|
465
- f.request :multipart
466
- f.request :url_encoded
467
- f.adapter Faraday.default_adapter
468
- end
469
-
470
- if req_opts[:body] == {}
471
- req_opts[:body] = nil
472
- end
473
-
474
-
475
- response = conn.post url, form_params, req_opts[:body]
476
- data = JSON.parse("[#{response.body}]", :symbolize_names => true)[0]
477
-
478
- @config.access_token = data[:access_token]
479
-
480
- $get_access_token_time = Time.now
481
- end
482
-
483
- # Adds OAuth2.0 token
484
- def add_o_auth_token(req_opts)
485
- req_opts[:headers][:Authorization] = "Bearer " + @config.access_token
486
- end
487
-
488
- end
489
- end
1
+ =begin
2
+ --------------------------------------------------------------------------------------------------------------------
3
+ Copyright (c) 2020 Aspose.Cells Cloud
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
18
+ SOFTWARE.
19
+ --------------------------------------------------------------------------------------------------------------------
20
+
21
+ =end
22
+
23
+ require 'date'
24
+ require 'json'
25
+ require 'logger'
26
+ require 'tempfile'
27
+ require 'uri'
28
+ require 'faraday'
29
+ require_relative 'version'
30
+ require_relative 'api_error'
31
+
32
+ module AsposeCellsCloud
33
+ class ApiClient
34
+ # The Configuration object holding settings to be used in the API client.
35
+ attr_accessor :config
36
+
37
+ # Defines the headers to be used in HTTP requests of all API calls by default.
38
+ #
39
+ # @return [Hash]
40
+ attr_accessor :default_headers
41
+
42
+ attr_accessor :get_access_token_time
43
+ # Initializes the ApiClient
44
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
45
+ def initialize(config = Configuration.default)
46
+ @config = config
47
+
48
+ @default_headers = {
49
+ 'Content-Type' => "application/json",
50
+ 'x-aspose-client' => "ruby sdk",
51
+ 'x-aspose-version' => "#{ AsposeCellsCloud::VERSION }"
52
+ }
53
+ end
54
+
55
+ def self.default
56
+ @@default ||= ApiClient.new
57
+ end
58
+
59
+ # Call an API with given options.
60
+ #
61
+ # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
62
+ # the data deserialized from response body (could be nil), response status code and response headers.
63
+ def call_api(http_method, path, opts = {})
64
+ response = build_request(http_method, path, opts)
65
+ download_file response if opts[:return_type] == 'File'
66
+
67
+ if @config.debugging
68
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
69
+ end
70
+
71
+ unless response.success?
72
+
73
+ if response.status == 0
74
+ # Errors from libcurl will be made visible here
75
+ fail ApiError.new(:code => 0,
76
+ :message => response.reason_phrase)
77
+ else
78
+ fail ApiError.new(:code => response.status,
79
+ :response_headers => response.headers,
80
+ :response_body => response.body),
81
+ response.reason_phrase
82
+ end
83
+ end
84
+
85
+ if opts[:return_type]
86
+ data = deserialize(response, opts[:return_type])
87
+ else
88
+ data = nil
89
+ end
90
+ [data, response.status, response.headers]
91
+ end
92
+
93
+ # Builds the HTTP request
94
+ #
95
+ # @param [String] http_method HTTP method/verb (e.g. POST)
96
+ # @param [String] path URL path (e.g. /account/new)
97
+ # @option opts [Hash] :header_params Header parameters
98
+ # @option opts [Hash] :query_params Query parameters
99
+ # @option opts [Hash] :form_params Query parameters
100
+ # @option opts [Object] :body HTTP body (JSON/XML)
101
+ # @return [Faraday::Response] A Faraday Response
102
+ def build_request(http_method, path, opts = {})
103
+ url = build_request_url(path)
104
+ http_method = http_method.to_sym.downcase
105
+
106
+ header_params = @default_headers.merge(opts[:header_params] || {})
107
+ query_params = opts[:query_params] || {}
108
+ form_params = opts[:form_params] || {}
109
+ body = opts[:body] || {}
110
+
111
+ update_params_for_auth! header_params, query_params, opts[:auth_names]
112
+
113
+ req_opts = {
114
+ :method => http_method,
115
+ :headers => header_params,
116
+ :params => query_params,
117
+ :body => body
118
+ }
119
+
120
+ if [:post, :patch, :put, :delete].include?(http_method)
121
+ req_body = build_request_body(header_params, form_params, opts[:body])
122
+ req_opts.update :body => req_body
123
+ if @config.debugging
124
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
125
+ end
126
+ end
127
+
128
+ # OAuth 2.0
129
+ req_opts[:params] = opts[:query_params]
130
+
131
+ if @config.access_token
132
+ add_o_auth_token(req_opts)
133
+ end
134
+
135
+ conn = Faraday.new url, {:params => query_params, :headers => header_params} do |f|
136
+ f.request :multipart
137
+ f.request :url_encoded
138
+ f.adapter Faraday.default_adapter
139
+ end
140
+
141
+ if req_opts[:body] == {}
142
+ req_opts[:body] = nil
143
+ end
144
+
145
+ case http_method
146
+ when :post
147
+ return conn.post url, req_opts[:body]
148
+ when :put
149
+ return conn.put url, req_opts[:body]
150
+ when :get
151
+ return conn.get url, req_opts[:body]
152
+ else
153
+ return conn.delete url do |c|
154
+ c.body = req_opts[:body]
155
+ end
156
+ end
157
+ end
158
+
159
+ # Check if the given MIME is a JSON MIME.
160
+ # JSON MIME examples:
161
+ # application/json
162
+ # application/json; charset=UTF8
163
+ # APPLICATION/JSON
164
+ # */*
165
+ # @param [String] mime MIME
166
+ # @return [Boolean] True if the MIME is application/json
167
+ def json_mime?(mime)
168
+ (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
169
+ end
170
+
171
+ # Deserialize the response to the given return type.
172
+ #
173
+ # @param [Response] response HTTP response
174
+ # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
175
+ def deserialize(response, return_type)
176
+ body = response.body
177
+
178
+ # handle file downloading - return the File instance processed in request callbacks
179
+ # note that response body is empty when the file is written in chunks in request on_body callback
180
+ return @tempfile if return_type == 'File'
181
+
182
+ return nil if body.nil? || body.empty?
183
+
184
+ # return response body directly for String return type
185
+ return body if return_type == 'String'
186
+
187
+ # ensuring a default content type
188
+ content_type = response.headers['Content-Type'] || 'application/json'
189
+
190
+ raise "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
191
+
192
+ begin
193
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
194
+ rescue JSON::ParserError => e
195
+ if %w(String Date DateTime).include?(return_type)
196
+ data = body
197
+ else
198
+ raise e
199
+ end
200
+ end
201
+
202
+ convert_to_type data, return_type
203
+ end
204
+
205
+ # Convert data to the given return type.
206
+ # @param [Object] data Data to be converted
207
+ # @param [String] return_type Return type
208
+ # @return [Mixed] Data in a particular type
209
+ def convert_to_type(data, return_type)
210
+ return nil if data.nil?
211
+ case return_type
212
+ when 'String'
213
+ data.to_s
214
+ when 'Integer'
215
+ data.to_i
216
+ when 'Float'
217
+ data.to_f
218
+ when 'BOOLEAN'
219
+ data == true
220
+ when 'DateTime'
221
+ # parse date time (expecting ISO 8601 format)
222
+ DateTime.parse data
223
+ when 'Date'
224
+ # parse date time (expecting ISO 8601 format)
225
+ Date.parse data
226
+ when 'Object'
227
+ # generic object (usually a Hash), return directly
228
+ data
229
+ when /\AArray<(.+)>\z/
230
+ # e.g. Array<Pet>
231
+ sub_type = $1
232
+ data.map {|item| convert_to_type(item, sub_type) }
233
+ when /\AHash\<String, (.+)\>\z/
234
+ # e.g. Hash<String, Integer>
235
+ sub_type = $1
236
+ {}.tap do |hash|
237
+ data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
238
+ end
239
+ else
240
+ # models, e.g. Pet
241
+ AsposeCellsCloud.const_get(return_type).new.tap do |model|
242
+ model.build_from_hash data
243
+ end
244
+ end
245
+ end
246
+
247
+ # Save response body into a file in (the defined) temporary folder, using the filename
248
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
249
+ # The response body is written to the file in chunks in order to handle files which
250
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
251
+ # process can use.
252
+ #
253
+ # @see Configuration#temp_folder_path
254
+ def download_file(response)
255
+ tempfile = nil
256
+ encoding = nil
257
+
258
+ content_disposition = response.headers['Content-Disposition']
259
+ if content_disposition and content_disposition =~ /filename=/i
260
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
261
+ prefix = sanitize_filename(filename)
262
+ else
263
+ prefix = 'download-'
264
+ end
265
+ prefix = prefix + '-' unless prefix.end_with?('-')
266
+ encoding = response.body.encoding
267
+ tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
268
+ @tempfile = tempfile
269
+
270
+ tempfile.write(response.body)
271
+
272
+ response.on_complete do |resp|
273
+ tempfile.close
274
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
275
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
276
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
277
+ "explicitly with `tempfile.delete`"
278
+ end
279
+ end
280
+
281
+ # Sanitize filename by removing path.
282
+ # e.g. ../../sun.gif becomes sun.gif
283
+ #
284
+ # @param [String] filename the filename to be sanitized
285
+ # @return [String] the sanitized filename
286
+ def sanitize_filename(filename)
287
+ filename.gsub(/.*[\/\\]/, '')
288
+ end
289
+
290
+ def build_request_url(path)
291
+ # Add leading and trailing slashes to path
292
+ path = "/#{path}".gsub(/\/+/, '/')
293
+ URI.encode(@config.base_url + path)
294
+ end
295
+
296
+ # Builds the HTTP request body
297
+ #
298
+ # @param [Hash] header_params Header parameters
299
+ # @param [Hash] form_params Query parameters
300
+ # @param [Object] body HTTP body (JSON/XML)
301
+ # @return [String] HTTP body data in the form of string
302
+ def build_request_body(header_params, form_params, body)
303
+ # http form
304
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
305
+ header_params['Content-Type'] == 'multipart/form-data'
306
+ data = {}
307
+ form_params.each do |key, value|
308
+ case value
309
+ when ::File
310
+ data[key] = Faraday::UploadIO.new(value.path, MimeMagic.by_magic(value).to_s, key)
311
+ when ::Array, nil
312
+ # let typhoeus handle File, Array and nil parameters
313
+ data[key] = value
314
+ else
315
+ data[key] = value.to_s
316
+ end
317
+ end
318
+ elsif body
319
+ data = body.is_a?(String) ? body : body.to_json
320
+ else
321
+ data = nil
322
+ end
323
+ data
324
+ end
325
+
326
+ # Update hearder and query params based on authentication settings.
327
+ #
328
+ # @param [Hash] header_params Header parameters
329
+ # @param [Hash] query_params Query parameters
330
+ # @param [String] auth_names Authentication scheme name
331
+ def update_params_for_auth!(header_params, query_params, auth_names)
332
+ Array(auth_names).each do |auth_name|
333
+ auth_setting = @config.auth_settings[auth_name]
334
+ next unless auth_setting
335
+ case auth_setting[:in]
336
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
337
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
338
+ else raise ArgumentError, 'Authentication token must be in `query` of `header`'
339
+ end
340
+ end
341
+ end
342
+
343
+ # Sets user agent in HTTP header
344
+ #
345
+ # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0)
346
+ def user_agent=(user_agent)
347
+ @user_agent = user_agent
348
+ @default_headers['User-Agent'] = @user_agent
349
+ end
350
+
351
+ # Return Accept header based on an array of accepts provided.
352
+ # @param [Array] accepts array for Accept
353
+ # @return [String] the Accept header (e.g. application/json)
354
+ def select_header_accept(accepts)
355
+ return nil if accepts.nil? || accepts.empty?
356
+ # use JSON when present, otherwise use all of the provided
357
+ json_accept = accepts.find { |s| json_mime?(s) }
358
+ return json_accept || accepts.join(',')
359
+ end
360
+
361
+ # Return Content-Type header based on an array of content types provided.
362
+ # @param [Array] content_types array for Content-Type
363
+ # @return [String] the Content-Type header (e.g. application/json)
364
+ def select_header_content_type(content_types)
365
+ # use application/json by default
366
+ return 'application/json' if content_types.nil? || content_types.empty?
367
+ # use JSON when present, otherwise use the first one
368
+ json_content_type = content_types.find { |s| json_mime?(s) }
369
+ return json_content_type || content_types.first
370
+ end
371
+
372
+ # Convert object (array, hash, object, etc) to JSON string.
373
+ # @param [Object] model object to be converted into JSON string
374
+ # @return [String] JSON string representation of the object
375
+ def object_to_http_body(model)
376
+ return '"' + model + '"' if model.is_a?(String)
377
+ return model if model.nil?
378
+ local_body = nil
379
+ if model.is_a?(Array)
380
+ local_body = model.map{|m| object_to_hash(m) }
381
+ else
382
+ local_body = object_to_hash(model)
383
+ end
384
+ local_body.to_json
385
+ end
386
+
387
+ # Convert object(non-array) to hash.
388
+ # @param [Object] obj object to be converted into JSON string
389
+ # @return [String] JSON string representation of the object
390
+ def object_to_hash(obj)
391
+ if obj.respond_to?(:to_hash)
392
+ obj.to_hash
393
+ else
394
+ obj
395
+ end
396
+ end
397
+
398
+ # Build parameter value according to the given collection format.
399
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
400
+ def build_collection_param(param, collection_format)
401
+ case collection_format
402
+ when :csv
403
+ param.join(',')
404
+ when :ssv
405
+ param.join(' ')
406
+ when :tsv
407
+ param.join("\t")
408
+ when :pipes
409
+ param.join('|')
410
+ when :multi
411
+ # return the array directly as faraday will handle it as expected
412
+ param
413
+ else
414
+ fail "unknown collection format: #{collection_format.inspect}"
415
+ end
416
+ end
417
+
418
+ # Request access and refresh tokens if needed
419
+ def request_token_if_needed
420
+ # check token exists
421
+ if @config.client_id.nil? && @config.client_secret.nil?
422
+ return
423
+ end
424
+ if @config.access_token
425
+ now = Time.now
426
+ time_difference = now - $get_access_token_time
427
+ if time_difference < 86300
428
+ return
429
+ end
430
+ end
431
+
432
+ # resource path
433
+ local_var_path = "/connect/token"
434
+ if @config.api_version === "v1.1"
435
+ local_var_path ="/oauth2/token"
436
+ end
437
+ url = build_request_url(local_var_path).gsub('/'+config.api_version, '')
438
+ #url = build_request_url(local_var_path).gsub('/v3.0', '')
439
+
440
+ # header parameters
441
+ header_params = {}
442
+ # HTTP header 'Content-Type'
443
+ header_params['Content-Type'] = select_header_content_type(['application/x-www-form-urlencoded'])
444
+
445
+ query_params = {}
446
+ # form parameters
447
+ form_params = {}
448
+ form_params["grant_type"] = 'client_credentials'
449
+ form_params["client_id"] = @config.client_id
450
+ form_params["client_secret"] = @config.client_secret
451
+
452
+ body = {}
453
+
454
+
455
+ req_opts = {
456
+ :headers => header_params,
457
+ :params => query_params,
458
+ :body => body
459
+ }
460
+
461
+
462
+ req_body = build_request_body(header_params, form_params, body)
463
+ req_opts.update :body => req_body
464
+
465
+ req_opts[:params] = query_params
466
+
467
+
468
+ conn = Faraday.new url, {:params => query_params, :headers => header_params} do |f|
469
+ f.request :multipart
470
+ f.request :url_encoded
471
+ f.adapter Faraday.default_adapter
472
+ end
473
+
474
+ if req_opts[:body] == {}
475
+ req_opts[:body] = nil
476
+ end
477
+
478
+
479
+ response = conn.post url, form_params, req_opts[:body]
480
+ data = JSON.parse("[#{response.body}]", :symbolize_names => true)[0]
481
+
482
+ @config.access_token = data[:access_token]
483
+
484
+ $get_access_token_time = Time.now
485
+ end
486
+
487
+ # Adds OAuth2.0 token
488
+ def add_o_auth_token(req_opts)
489
+ req_opts[:headers][:Authorization] = "Bearer " + @config.access_token
490
+ end
491
+
492
+ end
493
+ end