forked from intercom/intercom-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncRawTicketsClient.java
More file actions
727 lines (703 loc) · 44.8 KB
/
Copy pathAsyncRawTicketsClient.java
File metadata and controls
727 lines (703 loc) · 44.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
/**
* This file was auto-generated by Fern from our API Definition.
*/
package com.intercom.api.resources.tickets;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.intercom.api.core.ClientOptions;
import com.intercom.api.core.IntercomApiException;
import com.intercom.api.core.IntercomException;
import com.intercom.api.core.IntercomHttpResponse;
import com.intercom.api.core.MediaTypes;
import com.intercom.api.core.ObjectMappers;
import com.intercom.api.core.RequestOptions;
import com.intercom.api.core.pagination.SyncPagingIterable;
import com.intercom.api.errors.BadRequestError;
import com.intercom.api.errors.NotFoundError;
import com.intercom.api.errors.UnauthorizedError;
import com.intercom.api.resources.jobs.types.Jobs;
import com.intercom.api.resources.tickets.requests.CreateTicketRequest;
import com.intercom.api.resources.tickets.requests.DeleteTicketRequest;
import com.intercom.api.resources.tickets.requests.EnqueueCreateTicketRequest;
import com.intercom.api.resources.tickets.requests.FindTicketRequest;
import com.intercom.api.resources.tickets.requests.ReplyToTicketRequest;
import com.intercom.api.resources.tickets.requests.UpdateTicketRequest;
import com.intercom.api.resources.tickets.types.DeleteTicketResponse;
import com.intercom.api.resources.tickets.types.Ticket;
import com.intercom.api.types.CursorPages;
import com.intercom.api.types.Error;
import com.intercom.api.types.SearchRequest;
import com.intercom.api.types.StartingAfterPaging;
import com.intercom.api.types.TicketList;
import com.intercom.api.types.TicketReply;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.jetbrains.annotations.NotNull;
public class AsyncRawTicketsClient {
protected final ClientOptions clientOptions;
public AsyncRawTicketsClient(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
}
/**
* You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins.
*/
public CompletableFuture<IntercomHttpResponse<TicketReply>> reply(ReplyToTicketRequest request) {
return reply(request, null);
}
/**
* You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins.
*/
public CompletableFuture<IntercomHttpResponse<TicketReply>> reply(
ReplyToTicketRequest request, RequestOptions requestOptions) {
HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl())
.newBuilder()
.addPathSegments("tickets")
.addPathSegment(request.getTicketId())
.addPathSegments("reply")
.build();
RequestBody body;
try {
body = RequestBody.create(
ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON);
} catch (JsonProcessingException e) {
throw new IntercomException("Failed to serialize request", e);
}
Request okhttpRequest = new Request.Builder()
.url(httpUrl)
.method("POST", body)
.headers(Headers.of(clientOptions.headers(requestOptions)))
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
OkHttpClient client = clientOptions.httpClient();
if (requestOptions != null && requestOptions.getTimeout().isPresent()) {
client = clientOptions.httpClientWithTimeout(requestOptions);
}
CompletableFuture<IntercomHttpResponse<TicketReply>> future = new CompletableFuture<>();
client.newCall(okhttpRequest).enqueue(new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
String responseBodyString = responseBody != null ? responseBody.string() : "{}";
if (response.isSuccessful()) {
future.complete(new IntercomHttpResponse<>(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, TicketReply.class), response));
return;
}
try {
switch (response.code()) {
case 400:
future.completeExceptionally(new BadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class),
response));
return;
case 401:
future.completeExceptionally(new UnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class),
response));
return;
case 404:
future.completeExceptionally(new NotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class),
response));
return;
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
Object errorBody = ObjectMappers.parseErrorBody(responseBodyString);
future.completeExceptionally(new IntercomApiException(
"Error with status code " + response.code(), response.code(), errorBody, response));
return;
} catch (IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
});
return future;
}
/**
* You can create a new ticket.
*/
public CompletableFuture<IntercomHttpResponse<Optional<Ticket>>> create(CreateTicketRequest request) {
return create(request, null);
}
/**
* You can create a new ticket.
*/
public CompletableFuture<IntercomHttpResponse<Optional<Ticket>>> create(
CreateTicketRequest request, RequestOptions requestOptions) {
HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl())
.newBuilder()
.addPathSegments("tickets")
.build();
RequestBody body;
try {
body = RequestBody.create(
ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON);
} catch (JsonProcessingException e) {
throw new IntercomException("Failed to serialize request", e);
}
Request okhttpRequest = new Request.Builder()
.url(httpUrl)
.method("POST", body)
.headers(Headers.of(clientOptions.headers(requestOptions)))
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
OkHttpClient client = clientOptions.httpClient();
if (requestOptions != null && requestOptions.getTimeout().isPresent()) {
client = clientOptions.httpClientWithTimeout(requestOptions);
}
CompletableFuture<IntercomHttpResponse<Optional<Ticket>>> future = new CompletableFuture<>();
client.newCall(okhttpRequest).enqueue(new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
String responseBodyString = responseBody != null ? responseBody.string() : "{}";
if (response.isSuccessful()) {
future.complete(new IntercomHttpResponse<>(
ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, new TypeReference<Optional<Ticket>>() {}),
response));
return;
}
try {
if (response.code() == 401) {
future.completeExceptionally(new UnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response));
return;
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
Object errorBody = ObjectMappers.parseErrorBody(responseBodyString);
future.completeExceptionally(new IntercomApiException(
"Error with status code " + response.code(), response.code(), errorBody, response));
return;
} catch (IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
});
return future;
}
/**
* Enqueues ticket creation for asynchronous processing, returning if the job was enqueued successfully to be processed. We attempt to perform a best-effort validation on inputs before tasks are enqueued. If the given parameters are incorrect, we won't enqueue the job.
*/
public CompletableFuture<IntercomHttpResponse<Jobs>> enqueueCreateTicket(EnqueueCreateTicketRequest request) {
return enqueueCreateTicket(request, null);
}
/**
* Enqueues ticket creation for asynchronous processing, returning if the job was enqueued successfully to be processed. We attempt to perform a best-effort validation on inputs before tasks are enqueued. If the given parameters are incorrect, we won't enqueue the job.
*/
public CompletableFuture<IntercomHttpResponse<Jobs>> enqueueCreateTicket(
EnqueueCreateTicketRequest request, RequestOptions requestOptions) {
HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl())
.newBuilder()
.addPathSegments("tickets/enqueue")
.build();
RequestBody body;
try {
body = RequestBody.create(
ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON);
} catch (JsonProcessingException e) {
throw new IntercomException("Failed to serialize request", e);
}
Request okhttpRequest = new Request.Builder()
.url(httpUrl)
.method("POST", body)
.headers(Headers.of(clientOptions.headers(requestOptions)))
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
OkHttpClient client = clientOptions.httpClient();
if (requestOptions != null && requestOptions.getTimeout().isPresent()) {
client = clientOptions.httpClientWithTimeout(requestOptions);
}
CompletableFuture<IntercomHttpResponse<Jobs>> future = new CompletableFuture<>();
client.newCall(okhttpRequest).enqueue(new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
String responseBodyString = responseBody != null ? responseBody.string() : "{}";
if (response.isSuccessful()) {
future.complete(new IntercomHttpResponse<>(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Jobs.class), response));
return;
}
try {
switch (response.code()) {
case 400:
future.completeExceptionally(new BadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class),
response));
return;
case 401:
future.completeExceptionally(new UnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class),
response));
return;
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
Object errorBody = ObjectMappers.parseErrorBody(responseBodyString);
future.completeExceptionally(new IntercomApiException(
"Error with status code " + response.code(), response.code(), errorBody, response));
return;
} catch (IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
});
return future;
}
/**
* You can fetch the details of a single ticket.
*/
public CompletableFuture<IntercomHttpResponse<Optional<Ticket>>> get(FindTicketRequest request) {
return get(request, null);
}
/**
* You can fetch the details of a single ticket.
*/
public CompletableFuture<IntercomHttpResponse<Optional<Ticket>>> get(
FindTicketRequest request, RequestOptions requestOptions) {
HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl())
.newBuilder()
.addPathSegments("tickets")
.addPathSegment(request.getTicketId())
.build();
Request.Builder _requestBuilder = new Request.Builder()
.url(httpUrl)
.method("GET", null)
.headers(Headers.of(clientOptions.headers(requestOptions)))
.addHeader("Accept", "application/json");
Request okhttpRequest = _requestBuilder.build();
OkHttpClient client = clientOptions.httpClient();
if (requestOptions != null && requestOptions.getTimeout().isPresent()) {
client = clientOptions.httpClientWithTimeout(requestOptions);
}
CompletableFuture<IntercomHttpResponse<Optional<Ticket>>> future = new CompletableFuture<>();
client.newCall(okhttpRequest).enqueue(new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
String responseBodyString = responseBody != null ? responseBody.string() : "{}";
if (response.isSuccessful()) {
future.complete(new IntercomHttpResponse<>(
ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, new TypeReference<Optional<Ticket>>() {}),
response));
return;
}
try {
if (response.code() == 401) {
future.completeExceptionally(new UnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response));
return;
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
Object errorBody = ObjectMappers.parseErrorBody(responseBodyString);
future.completeExceptionally(new IntercomApiException(
"Error with status code " + response.code(), response.code(), errorBody, response));
return;
} catch (IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
});
return future;
}
/**
* You can update a ticket.
*/
public CompletableFuture<IntercomHttpResponse<Optional<Ticket>>> update(UpdateTicketRequest request) {
return update(request, null);
}
/**
* You can update a ticket.
*/
public CompletableFuture<IntercomHttpResponse<Optional<Ticket>>> update(
UpdateTicketRequest request, RequestOptions requestOptions) {
HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl())
.newBuilder()
.addPathSegments("tickets")
.addPathSegment(request.getTicketId())
.build();
RequestBody body;
try {
body = RequestBody.create(
ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON);
} catch (JsonProcessingException e) {
throw new IntercomException("Failed to serialize request", e);
}
Request okhttpRequest = new Request.Builder()
.url(httpUrl)
.method("PUT", body)
.headers(Headers.of(clientOptions.headers(requestOptions)))
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
OkHttpClient client = clientOptions.httpClient();
if (requestOptions != null && requestOptions.getTimeout().isPresent()) {
client = clientOptions.httpClientWithTimeout(requestOptions);
}
CompletableFuture<IntercomHttpResponse<Optional<Ticket>>> future = new CompletableFuture<>();
client.newCall(okhttpRequest).enqueue(new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
String responseBodyString = responseBody != null ? responseBody.string() : "{}";
if (response.isSuccessful()) {
future.complete(new IntercomHttpResponse<>(
ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, new TypeReference<Optional<Ticket>>() {}),
response));
return;
}
try {
switch (response.code()) {
case 400:
future.completeExceptionally(new BadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class),
response));
return;
case 401:
future.completeExceptionally(new UnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class),
response));
return;
case 404:
future.completeExceptionally(new NotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class),
response));
return;
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
Object errorBody = ObjectMappers.parseErrorBody(responseBodyString);
future.completeExceptionally(new IntercomApiException(
"Error with status code " + response.code(), response.code(), errorBody, response));
return;
} catch (IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
});
return future;
}
/**
* You can delete a ticket using the Intercom provided ID.
*/
public CompletableFuture<IntercomHttpResponse<DeleteTicketResponse>> deleteTicket(DeleteTicketRequest request) {
return deleteTicket(request, null);
}
/**
* You can delete a ticket using the Intercom provided ID.
*/
public CompletableFuture<IntercomHttpResponse<DeleteTicketResponse>> deleteTicket(
DeleteTicketRequest request, RequestOptions requestOptions) {
HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl())
.newBuilder()
.addPathSegments("tickets")
.addPathSegment(request.getTicketId())
.build();
Request.Builder _requestBuilder = new Request.Builder()
.url(httpUrl)
.method("DELETE", null)
.headers(Headers.of(clientOptions.headers(requestOptions)))
.addHeader("Accept", "application/json");
Request okhttpRequest = _requestBuilder.build();
OkHttpClient client = clientOptions.httpClient();
if (requestOptions != null && requestOptions.getTimeout().isPresent()) {
client = clientOptions.httpClientWithTimeout(requestOptions);
}
CompletableFuture<IntercomHttpResponse<DeleteTicketResponse>> future = new CompletableFuture<>();
client.newCall(okhttpRequest).enqueue(new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
String responseBodyString = responseBody != null ? responseBody.string() : "{}";
if (response.isSuccessful()) {
future.complete(new IntercomHttpResponse<>(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteTicketResponse.class),
response));
return;
}
try {
switch (response.code()) {
case 401:
future.completeExceptionally(new UnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class),
response));
return;
case 404:
future.completeExceptionally(new NotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class),
response));
return;
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
Object errorBody = ObjectMappers.parseErrorBody(responseBodyString);
future.completeExceptionally(new IntercomApiException(
"Error with status code " + response.code(), response.code(), errorBody, response));
return;
} catch (IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
});
return future;
}
/**
* You can search for multiple tickets by the value of their attributes in order to fetch exactly which ones you want.
* <p>To search for tickets, you send a <code>POST</code> request to <code>https://api.intercom.io/tickets/search</code>.</p>
* <p>This will accept a query object in the body which will define your filters.
* {% admonition type="warning" name="Optimizing search queries" %}
* Search queries can be complex, so optimizing them can help the performance of your search.
* Use the <code>AND</code> and <code>OR</code> operators to combine multiple filters to get the exact results you need and utilize
* pagination to limit the number of results returned. The default is <code>20</code> results per page.
* See the <a href="https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request">pagination section</a> for more details on how to use the <code>starting_after</code> param.
* {% /admonition %}</p>
* <h3>Nesting & Limitations</h3>
* <p>You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4).
* There are some limitations to the amount of multiples there can be:</p>
* <ul>
* <li>There's a limit of max 2 nested filters</li>
* <li>There's a limit of max 15 filters for each AND or OR group</li>
* </ul>
* <h3>Accepted Fields</h3>
* <p>Most keys listed as part of the Ticket model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as <code>created_at</code> accepts a date, the <code>value</code> cannot be a string such as <code>"foobar"</code>).
* The <code>source.body</code> field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a <code>"I need support"</code> body - the query should contain a <code>=</code> operator with the value <code>"support"</code> for such conversation to be returned. A query with a <code>=</code> operator and a <code>"need support"</code> value will not yield a result.</p>
* <p>| Field | Type |
* | :---------------------------------------- | :--------------------------------------------------------------------------------------- |
* | id | String |
* | created_at | Date (UNIX timestamp) |
* | updated_at | Date (UNIX timestamp) |
* | title | String |
* | description | String |
* | category | String |
* | ticket_type_id | String |
* | contact_ids | String |
* | teammate_ids | String |
* | admin_assignee_id | String |
* | team_assignee_id | String |
* | open | Boolean |
* | state | String |
* | snoozed_until | Date (UNIX timestamp) |
* | ticket_attribute.{id} | String or Boolean or Date (UNIX timestamp) or Float or Integer |</p>
* <p>{% admonition type="info" name="Searching by Category" %}
* When searching for tickets by the <strong><code>category</code></strong> field, specific terms must be used instead of the category names:</p>
* <ul>
* <li>For <strong>Customer</strong> category tickets, use the term <code>request</code>.</li>
* <li>For <strong>Back-office</strong> category tickets, use the term <code>task</code>.</li>
* <li>For <strong>Tracker</strong> category tickets, use the term <code>tracker</code>.
* {% /admonition %}</li>
* </ul>
* <h3>Accepted Operators</h3>
* <p>{% admonition type="info" name="Searching based on <code>created_at</code>" %}
* You may use the <code><=</code> or <code>>=</code> operators to search by <code>created_at</code>.
* {% /admonition %}</p>
* <p>The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (<code>"="</code>). The operator has to be compatible with the field's type (eg. you cannot search with <code>></code> for a given string value as it's only compatible for integer's and dates).</p>
* <p>| Operator | Valid Types | Description |
* | :------- | :----------------------------- | :----------------------------------------------------------- |
* | = | All | Equals |
* | != | All | Doesn't Equal |
* | IN | All | In Shortcut for <code>OR</code> queries Values most be in Array |
* | NIN | All | Not In Shortcut for <code>OR !</code> queries Values must be in Array |
* | > | Integer Date (UNIX Timestamp) | Greater (or equal) than |
* | < | Integer Date (UNIX Timestamp) | Lower (or equal) than |
* | ~ | String | Contains |
* | !~ | String | Doesn't Contain |
* | ^ | String | Starts With |
* | $ | String | Ends With |</p>
*/
public CompletableFuture<IntercomHttpResponse<SyncPagingIterable<Optional<Ticket>>>> search(SearchRequest request) {
return search(request, null);
}
/**
* You can search for multiple tickets by the value of their attributes in order to fetch exactly which ones you want.
* <p>To search for tickets, you send a <code>POST</code> request to <code>https://api.intercom.io/tickets/search</code>.</p>
* <p>This will accept a query object in the body which will define your filters.
* {% admonition type="warning" name="Optimizing search queries" %}
* Search queries can be complex, so optimizing them can help the performance of your search.
* Use the <code>AND</code> and <code>OR</code> operators to combine multiple filters to get the exact results you need and utilize
* pagination to limit the number of results returned. The default is <code>20</code> results per page.
* See the <a href="https://developers.intercom.com/docs/build-an-integration/learn-more/rest-apis/pagination/#example-search-conversations-request">pagination section</a> for more details on how to use the <code>starting_after</code> param.
* {% /admonition %}</p>
* <h3>Nesting & Limitations</h3>
* <p>You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4).
* There are some limitations to the amount of multiples there can be:</p>
* <ul>
* <li>There's a limit of max 2 nested filters</li>
* <li>There's a limit of max 15 filters for each AND or OR group</li>
* </ul>
* <h3>Accepted Fields</h3>
* <p>Most keys listed as part of the Ticket model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as <code>created_at</code> accepts a date, the <code>value</code> cannot be a string such as <code>"foobar"</code>).
* The <code>source.body</code> field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a <code>"I need support"</code> body - the query should contain a <code>=</code> operator with the value <code>"support"</code> for such conversation to be returned. A query with a <code>=</code> operator and a <code>"need support"</code> value will not yield a result.</p>
* <p>| Field | Type |
* | :---------------------------------------- | :--------------------------------------------------------------------------------------- |
* | id | String |
* | created_at | Date (UNIX timestamp) |
* | updated_at | Date (UNIX timestamp) |
* | title | String |
* | description | String |
* | category | String |
* | ticket_type_id | String |
* | contact_ids | String |
* | teammate_ids | String |
* | admin_assignee_id | String |
* | team_assignee_id | String |
* | open | Boolean |
* | state | String |
* | snoozed_until | Date (UNIX timestamp) |
* | ticket_attribute.{id} | String or Boolean or Date (UNIX timestamp) or Float or Integer |</p>
* <p>{% admonition type="info" name="Searching by Category" %}
* When searching for tickets by the <strong><code>category</code></strong> field, specific terms must be used instead of the category names:</p>
* <ul>
* <li>For <strong>Customer</strong> category tickets, use the term <code>request</code>.</li>
* <li>For <strong>Back-office</strong> category tickets, use the term <code>task</code>.</li>
* <li>For <strong>Tracker</strong> category tickets, use the term <code>tracker</code>.
* {% /admonition %}</li>
* </ul>
* <h3>Accepted Operators</h3>
* <p>{% admonition type="info" name="Searching based on <code>created_at</code>" %}
* You may use the <code><=</code> or <code>>=</code> operators to search by <code>created_at</code>.
* {% /admonition %}</p>
* <p>The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string (<code>"="</code>). The operator has to be compatible with the field's type (eg. you cannot search with <code>></code> for a given string value as it's only compatible for integer's and dates).</p>
* <p>| Operator | Valid Types | Description |
* | :------- | :----------------------------- | :----------------------------------------------------------- |
* | = | All | Equals |
* | != | All | Doesn't Equal |
* | IN | All | In Shortcut for <code>OR</code> queries Values most be in Array |
* | NIN | All | Not In Shortcut for <code>OR !</code> queries Values must be in Array |
* | > | Integer Date (UNIX Timestamp) | Greater (or equal) than |
* | < | Integer Date (UNIX Timestamp) | Lower (or equal) than |
* | ~ | String | Contains |
* | !~ | String | Doesn't Contain |
* | ^ | String | Starts With |
* | $ | String | Ends With |</p>
*/
public CompletableFuture<IntercomHttpResponse<SyncPagingIterable<Optional<Ticket>>>> search(
SearchRequest request, RequestOptions requestOptions) {
HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl())
.newBuilder()
.addPathSegments("tickets/search")
.build();
RequestBody body;
try {
body = RequestBody.create(
ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON);
} catch (JsonProcessingException e) {
throw new IntercomException("Failed to serialize request", e);
}
Request okhttpRequest = new Request.Builder()
.url(httpUrl)
.method("POST", body)
.headers(Headers.of(clientOptions.headers(requestOptions)))
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
OkHttpClient client = clientOptions.httpClient();
if (requestOptions != null && requestOptions.getTimeout().isPresent()) {
client = clientOptions.httpClientWithTimeout(requestOptions);
}
CompletableFuture<IntercomHttpResponse<SyncPagingIterable<Optional<Ticket>>>> future =
new CompletableFuture<>();
client.newCall(okhttpRequest).enqueue(new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
String responseBodyString = responseBody != null ? responseBody.string() : "{}";
if (response.isSuccessful()) {
TicketList parsedResponse =
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, TicketList.class);
Optional<String> startingAfter = parsedResponse
.getPages()
.flatMap(CursorPages::getNext)
.flatMap(StartingAfterPaging::getStartingAfter);
Optional<StartingAfterPaging> pagination = request.getPagination()
.map((StartingAfterPaging pagination_) -> StartingAfterPaging.builder()
.from(pagination_)
.startingAfter(startingAfter)
.build());
SearchRequest nextRequest = SearchRequest.builder()
.from(request)
.pagination(pagination)
.build();
List<Optional<Ticket>> result =
parsedResponse.getTickets().orElse(Collections.emptyList());
future.complete(new IntercomHttpResponse<>(
new SyncPagingIterable<Optional<Ticket>>(
startingAfter.isPresent(), result, parsedResponse, () -> {
try {
return search(nextRequest, requestOptions)
.get()
.body();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}),
response));
return;
}
Object errorBody = ObjectMappers.parseErrorBody(responseBodyString);
future.completeExceptionally(new IntercomApiException(
"Error with status code " + response.code(), response.code(), errorBody, response));
return;
} catch (IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
future.completeExceptionally(new IntercomException("Network error executing HTTP request", e));
}
});
return future;
}
}