This repository was archived by the owner on Dec 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathAIDataService.java
More file actions
1060 lines (905 loc) · 37.3 KB
/
AIDataService.java
File metadata and controls
1060 lines (905 loc) · 37.3 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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ai.api;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com) https://www.api.ai
*
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************************************/
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import ai.api.util.IOUtils;
import ai.api.util.StringUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.*;
import java.util.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ai.api.http.HttpClient;
import ai.api.model.AIContext;
import ai.api.model.AIRequest;
import ai.api.model.AIResponse;
import ai.api.model.Entity;
import ai.api.model.Status;
/**
* Do simple requests to the AI Service
*/
public class AIDataService {
private static final Logger Log = LogManager.getLogger(AIDataService.class);
private static final AIServiceContext UNDEFINED_SERVICE_CONTEXT = null;
private static final String REQUEST_METHOD_POST = "POST";
private static final String REQUEST_METHOD_DELETE = "DELETE";
private static final String REQUEST_METHOD_GET = "GET";
private static final String DEFAULT_REQUEST_METHOD = REQUEST_METHOD_POST;
/**
* Cannot be <code>null</code>
*/
private final static Gson GSON = GsonFactory.getDefaultFactory().getGson();
/**
* Cannot be <code>null</code>
*/
private final AIConfiguration config;
/**
* Cannot be <code>null</code>
*/
private final AIServiceContext defaultServiceContext;
/**
* Create new service for given configuration and some predefined service context
*
* @param config Service configuration data. Cannot be <code>null</code>
* @param serviceContext Service context. If <code>null</code> then new context will be created
* @throws IllegalArgumentException If config parameter is null
*/
public AIDataService(final AIConfiguration config, final AIServiceContext serviceContext) {
if (config == null) {
throw new IllegalArgumentException("config should not be null");
}
this.config = config.clone();
if (serviceContext == null) {
this.defaultServiceContext = new AIServiceContextBuilder().generateSessionId().build();
} else {
this.defaultServiceContext = serviceContext;
}
}
/**
* Create new service with unique context for given configuration
*
* @param config Service configuration data. Cannot be <code>null</code>
* @throws IllegalArgumentException If config parameter is null
*/
public AIDataService(final AIConfiguration config) {
this(config, null);
}
/**
* @return Current context used in each request. Never <code>null</code>
*/
public AIServiceContext getContext() {
return defaultServiceContext;
}
/**
* Make request to the AI service.
*
* @param request request object to the service. Cannot be <code>null</code>
* @return response object from service. Never <code>null</code>
*/
public AIResponse request(final AIRequest request) throws AIServiceException {
return request(request, (RequestExtras) null);
}
/**
* Make request to the AI service.
*
* @param request request object to the service. Cannot be <code>null</code>
* @param serviceContext custom service context that should be used instead of the default context
* @return response object from service. Never <code>null</code>
*/
public AIResponse request(final AIRequest request, final AIServiceContext serviceContext)
throws AIServiceException {
return request(request, (RequestExtras) null, serviceContext);
}
/**
* Make request to the AI service.
*
* @param request request object to the service. Cannot be <code>null</code>
* @param requestExtras object that can hold additional contexts and entities
* @return response object from service. Never <code>null</code>
*/
public AIResponse request(final AIRequest request, final RequestExtras requestExtras)
throws AIServiceException {
return request(request, requestExtras, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Make request to the AI service.
*
* @param request request object to the service. Cannot be <code>null</code>
* @param requestExtras object that can hold additional contexts and entities
* @param serviceContext custom service context that should be used instead of the default context
* @return response object from service. Never <code>null</code>
*/
public AIResponse request(final AIRequest request, final RequestExtras requestExtras,
final AIServiceContext serviceContext) throws AIServiceException {
if (request == null) {
throw new IllegalArgumentException("Request argument must not be null");
}
Log.debug("Start request");
try {
request.setLanguage(config.getApiAiLanguage());
request.setSessionId(getSessionId(serviceContext));
if (StringUtils.isEmpty(request.getTimezone())) {
request.setTimezone(getTimeZone(serviceContext));
}
Map<String, String> additionalHeaders = null;
if (requestExtras != null) {
fillRequest(request, requestExtras);
additionalHeaders = requestExtras.getAdditionalHeaders();
}
final String queryData = GSON.toJson(request);
final String response = doTextRequest(config.getQuestionUrl(getSessionId(serviceContext)),
queryData, additionalHeaders, "POST");
if (StringUtils.isEmpty(response)) {
throw new AIServiceException(
"Empty response from ai service. Please check configuration and Internet connection.");
}
Log.debug("Response json: " + response.replaceAll("[\r\n]+", " "));
final AIResponse aiResponse = GSON.fromJson(response, AIResponse.class);
if (aiResponse == null) {
throw new AIServiceException(
"API.AI response parsed as null. Check debug log for details.");
}
if (aiResponse.isError()) {
throw new AIServiceException(aiResponse);
}
aiResponse.cleanup();
return aiResponse;
} catch (final MalformedURLException e) {
Log.error("Malformed url should not be raised", e);
throw new AIServiceException("Wrong configuration. Please, connect to API.AI Service support",
e);
} catch (final JsonSyntaxException je) {
throw new AIServiceException(
"Wrong service answer format. Please, connect to API.AI Service support", je);
}
}
/**
* Make requests to the AI service with voice data.
*
* @param voiceStream voice data stream for recognition. Cannot be <code>null</code>
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse voiceRequest(final InputStream voiceStream) throws AIServiceException {
return voiceRequest(voiceStream, new RequestExtras());
}
/**
* Make requests to the AI service with voice data.
*
* @param voiceStream voice data stream for recognition. Cannot be <code>null</code>
* @param aiContexts additional contexts for request
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse voiceRequest(final InputStream voiceStream, final List<AIContext> aiContexts)
throws AIServiceException {
return voiceRequest(voiceStream, new RequestExtras(aiContexts, null));
}
/**
* Make requests to the AI service with voice data.
*
* @param voiceStream voice data stream for recognition. Cannot be <code>null</code>
* @param requestExtras object that can hold additional contexts and entities
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse voiceRequest(final InputStream voiceStream, final RequestExtras requestExtras)
throws AIServiceException {
return voiceRequest(voiceStream, requestExtras, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Make requests to the AI service with voice data.
*
* @param voiceStream voice data stream for recognition. Cannot be <code>null</code>
* @param requestExtras object that can hold additional contexts and entities
* @param serviceContext custom service context that should be used instead of the default context
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse voiceRequest(final InputStream voiceStream, final RequestExtras requestExtras,
final AIServiceContext serviceContext) throws AIServiceException {
assert voiceStream != null;
Log.debug("Start voice request");
try {
final AIRequest request = new AIRequest();
request.setLanguage(config.getApiAiLanguage());
request.setSessionId(getSessionId(serviceContext));
request.setTimezone(getTimeZone(serviceContext));
Map<String, String> additionalHeaders = null;
if (requestExtras != null) {
fillRequest(request, requestExtras);
additionalHeaders = requestExtras.getAdditionalHeaders();
}
final String queryData = GSON.toJson(request);
Log.debug("Request json: " + queryData);
final String response = doSoundRequest(voiceStream, queryData, additionalHeaders);
if (StringUtils.isEmpty(response)) {
throw new AIServiceException("Empty response from ai service. Please check configuration.");
}
Log.debug("Response json: " + response);
final AIResponse aiResponse = GSON.fromJson(response, AIResponse.class);
if (aiResponse == null) {
throw new AIServiceException(
"API.AI response parsed as null. Check debug log for details.");
}
if (aiResponse.isError()) {
throw new AIServiceException(aiResponse);
}
aiResponse.cleanup();
return aiResponse;
} catch (final MalformedURLException e) {
Log.error("Malformed url should not be raised", e);
throw new AIServiceException("Wrong configuration. Please, connect to AI Service support", e);
} catch (final JsonSyntaxException je) {
throw new AIServiceException(
"Wrong service answer format. Please, connect to API.AI Service support", je);
}
}
/**
* Forget all old contexts
*
* @return true if operation succeed, false otherwise
*/
@Deprecated
public boolean resetContexts() {
final AIRequest cleanRequest = new AIRequest();
cleanRequest.setQuery("empty_query_for_resetting_contexts"); // TODO remove it after protocol
// fix
cleanRequest.setResetContexts(true);
try {
final AIResponse response = request(cleanRequest);
return !response.isError();
} catch (final AIServiceException e) {
Log.error("Exception while contexts clean.", e);
return false;
}
}
/**
* Retrieves the list of all currently active contexts for a session
*
* @return List of contexts, or empty list if there is no any active contexts
* @throws AIServiceException
*/
public List<AIContext> getActiveContexts() throws AIServiceException {
return getActiveContexts(UNDEFINED_SERVICE_CONTEXT);
}
/**
* Retrieves the list of all currently active contexts for a session
*
* @param serviceContext custom service context that should be used instead of the default context
* @return List of contexts, or empty list if there is no any active contexts
* @throws AIServiceException
*/
public List<AIContext> getActiveContexts(final AIServiceContext serviceContext)
throws AIServiceException {
try {
return doRequest(ApiActiveContextListResponse.class,
config.getContextsUrl(getSessionId(serviceContext)), REQUEST_METHOD_GET);
} catch (BadResponseStatusException e) {
throw new AIServiceException(e.response);
}
}
/**
* Retrieves the specified context for a session
*
* @param contextName The context name
* @return <code>null</code> if context not found
* @throws AIServiceException
*/
public AIContext getActiveContext(final String contextName) throws AIServiceException {
return getActiveContext(contextName, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Retrieves the specified context for a session
*
* @param contextName The context name
* @param serviceContext custom service context that should be used instead of the default context
* @return <code>null</code> if context not found
* @throws AIServiceException
*/
public AIContext getActiveContext(final String contextName, final AIServiceContext serviceContext)
throws AIServiceException {
try {
return doRequest(AIContext.class,
config.getContextsUrl(getSessionId(serviceContext), contextName), REQUEST_METHOD_GET);
} catch (BadResponseStatusException e) {
if (e.response.getStatus().getCode() == 404) {
return null;
} else {
throw new AIServiceException(e.response);
}
}
}
/**
* Adds new active contexts for a session
*
* @param contexts Iterable collection of contexts
* @return List of added context names, or empty list if no contexts were added
* @throws AIServiceException
*/
public List<String> addActiveContext(final Iterable<AIContext> contexts)
throws AIServiceException {
return addActiveContext(contexts, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Adds new active contexts for a session
*
* @param contexts Iterable collection of contexts
* @param serviceContext custom service context that should be used instead of the default context
* @return List of added context names, or empty list if no contexts were added
* @throws AIServiceException
*/
public List<String> addActiveContext(final Iterable<AIContext> contexts,
final AIServiceContext serviceContext) throws AIServiceException {
ApiActiveContextNamesResponse response;
try {
response = doRequest(contexts, ApiActiveContextNamesResponse.class,
config.getContextsUrl(getSessionId(serviceContext)), REQUEST_METHOD_POST);
return response.names;
} catch (BadResponseStatusException e) {
throw new AIServiceException(e.response);
}
}
/**
* Adds new active context for a session
*
* @param context New context
* @return Name of added context
* @throws AIServiceException
*/
public String addActiveContext(final AIContext context) throws AIServiceException {
return addActiveContext(context, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Adds new active context for a session
*
* @param context New context
* @param serviceContext custom service context that should be used instead of the default context
* @return Name of added context
* @throws AIServiceException
*/
public String addActiveContext(final AIContext context, final AIServiceContext serviceContext)
throws AIServiceException {
ApiActiveContextNamesResponse response;
try {
response = doRequest(context, ApiActiveContextNamesResponse.class,
config.getContextsUrl(getSessionId(serviceContext)), REQUEST_METHOD_POST);
return response.names != null && response.names.size() > 0 ? response.names.get(0) : null;
} catch (BadResponseStatusException e) {
throw new AIServiceException(e.response);
}
}
/**
* Deletes all active contexts for a session
*
* @throws AIServiceException
*/
public void resetActiveContexts() throws AIServiceException {
resetActiveContexts(UNDEFINED_SERVICE_CONTEXT);
}
/**
* Deletes all active contexts for a session
*
* @param serviceContext custom service context that should be used instead of the default context
* @throws AIServiceException
*/
public void resetActiveContexts(final AIServiceContext serviceContext) throws AIServiceException {
try {
doRequest(AIResponse.class, config.getContextsUrl(getSessionId(serviceContext)),
REQUEST_METHOD_DELETE);
} catch (BadResponseStatusException e) {
throw new AIServiceException(e.response);
}
}
/**
* Deletes the specified context for a session
*
* @param contextName The context name
* @return <code>false</code> if context was not delete, <code>true</code> in otherwise case
* @throws AIServiceException
*/
public boolean removeActiveContext(final String contextName) throws AIServiceException {
return removeActiveContext(contextName, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Deletes the specified context for a session
*
* @param contextName The context name
* @param serviceContext custom service context that should be used instead of the default context
* @return <code>false</code> if context was not delete, <code>true</code> in otherwise case
* @throws AIServiceException
*/
public boolean removeActiveContext(final String contextName,
final AIServiceContext serviceContext) throws AIServiceException {
try {
doRequest(AIResponse.class, config.getContextsUrl(getSessionId(serviceContext), contextName),
REQUEST_METHOD_DELETE);
return true;
} catch (BadResponseStatusException e) {
if (e.response.getStatus().getCode() == 404) {
return false;
} else {
throw new AIServiceException(e.response);
}
}
}
/**
* Add new entity to an agent entity list
*
* @param userEntity new entity data
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse uploadUserEntity(final Entity userEntity) throws AIServiceException {
return uploadUserEntity(userEntity, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Add new entity to an agent entity list
*
* @param userEntity new entity data
* @param serviceContext custom service context that should be used instead of the default context
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse uploadUserEntity(final Entity userEntity, AIServiceContext serviceContext)
throws AIServiceException {
return uploadUserEntities(Collections.singleton(userEntity), serviceContext);
}
/**
* Add a bunch of new entity to an agent entity list
*
* @param userEntities collection of a new entity data
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse uploadUserEntities(final Collection<Entity> userEntities)
throws AIServiceException {
return uploadUserEntities(userEntities, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Add a bunch of new entity to an agent user entity list
*
* @param userEntities collection of a new entity data
* @param serviceContext custom service context that should be used instead of the default context
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse uploadUserEntities(final Collection<Entity> userEntities,
AIServiceContext serviceContext) throws AIServiceException {
return getEntitiesAiResponse(userEntities, config.getUserEntitiesEndpoint(getSessionId(serviceContext)), "POST");
}
/**
* Add a bunch of new entity to an agent entity list
*
* @param entity collection of a new entity data
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse uploadEntity(final Entity entity) throws AIServiceException {
final ArrayList<Entity> entities = new ArrayList<>();
entities.add(entity);
return getEntitiesAiResponse(entities, config.getEntitiesEndpoint(getSessionId(UNDEFINED_SERVICE_CONTEXT)), "POST");
}
/**
* Udate entries to existing entity
*
* @param entity new entity data
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse updateEntityData(final Entity entity) throws AIServiceException {
final ArrayList<Entity> entities = new ArrayList<>();
entities.add(entity);
return getEntitiesAiResponse(entities, config.getEntitiesEndpoint(getSessionId(UNDEFINED_SERVICE_CONTEXT)), "PUT");
}
/**
* Add a bunch of new entity to an agent entity list
*
* @param entities collection of a new entity data
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse uploadEntities(final Collection<Entity> entities) throws AIServiceException {
return getEntitiesAiResponse(entities, config.getEntitiesEndpoint(getSessionId(UNDEFINED_SERVICE_CONTEXT)), "POST");
}
/**
* Add a bunch of new entity to an agent entity list
*
* @param entities collection of a new entity data
* @param serviceContext custom service context that should be used instead of the default context
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse uploadEntities(final Collection<Entity> entities,
AIServiceContext serviceContext) throws AIServiceException {
return getEntitiesAiResponse(entities, config.getEntitiesEndpoint(getSessionId(serviceContext)));
}
private AIResponse getEntitiesAiResponse(Collection<Entity> userEntities, String endpoint) throws AIServiceException {
return getEntitiesAiResponse(userEntities,endpoint,"POST");
}
private AIResponse getEntitiesAiResponse(Collection<Entity> userEntities, String endpoint, String requestMethod) throws AIServiceException {
if (userEntities == null || userEntities.size() == 0) {
throw new AIServiceException("Empty entities list");
}
final String requestData = GSON.toJson(userEntities);
try {
final String response =
doTextRequest(endpoint, requestData, requestMethod);
if (StringUtils.isEmpty(response)) {
throw new AIServiceException(
"Empty response from ai service. Please check configuration and Internet connection.");
}
Log.debug("Response json: " + response);
final AIResponse aiResponse = GSON.fromJson(response, AIResponse.class);
if (aiResponse == null) {
throw new AIServiceException(
"API.AI response parsed as null. Check debug log for details.");
}
if (aiResponse.isError()) {
throw new AIServiceException(aiResponse);
}
aiResponse.cleanup();
return aiResponse;
} catch (final MalformedURLException e) {
Log.error("Malformed url should not be raised", e);
throw new AIServiceException("Wrong configuration. Please, connect to AI Service support", e);
} catch (final JsonSyntaxException je) {
throw new AIServiceException(
"Wrong service answer format. Please, connect to API.AI Service support", je);
}
}
/**
* @param requestJson Cannot be <code>null</code>
* @param serviceContext custom service context that should be used instead of the default context
* @return Response string
* @throws MalformedURLException
* @throws AIServiceException
*/
protected String doTextRequest(final String requestJson, AIServiceContext serviceContext)
throws MalformedURLException, AIServiceException {
return doTextRequest(config.getQuestionUrl(getSessionId(serviceContext)), requestJson);
}
/**
* @param requestJson Cannot be <code>null</code>
* @return Response string
* @throws MalformedURLException
* @throws AIServiceException
*/
protected String doTextRequest(final String requestJson)
throws MalformedURLException, AIServiceException {
return doTextRequest(requestJson, UNDEFINED_SERVICE_CONTEXT);
}
/**
* @param endpoint Cannot be <code>null</code>
* @param requestJson Cannot be <code>null</code>
* @return Response string
* @throws MalformedURLException
* @throws AIServiceException
*/
protected String doTextRequest(final String endpoint, final String requestJson)
throws MalformedURLException, AIServiceException {
return doTextRequest(endpoint, requestJson, "POST");
}
/**
* @param endpoint Cannot be <code>null</code>
* @param requestJson Cannot be <code>null</code>
* @param requestMethod HTTP method to perform the request
* @return Response string
* @throws MalformedURLException
* @throws AIServiceException
*/
protected String doTextRequest(final String endpoint, final String requestJson, String requestMethod)
throws MalformedURLException, AIServiceException {
return doTextRequest(endpoint, requestJson, null, requestMethod);
}
/**
* @param endpoint Cannot be <code>null</code>
* @param requestJson Cannot be <code>null</code>
* @param additionalHeaders
* @param requestMethod
* @return Response string
* @throws MalformedURLException
* @throws AIServiceException
*/
protected String doTextRequest(final String endpoint, final String requestJson,
final Map<String, String> additionalHeaders, String requestMethod)
throws MalformedURLException, AIServiceException {
// TODO call doRequest method
assert endpoint != null;
assert requestJson != null;
HttpURLConnection connection = null;
try {
final URL url = new URL(endpoint);
final String queryData = requestJson;
Log.debug("Request json: " + queryData);
if (config.getProxy() != null) {
connection = (HttpURLConnection) url.openConnection(config.getProxy());
} else {
connection = (HttpURLConnection) url.openConnection();
}
connection.setRequestMethod(requestMethod);
connection.setDoOutput(true);
connection.addRequestProperty("Authorization", "Bearer " + config.getApiKey());
connection.addRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.addRequestProperty("Accept", "application/json");
if (additionalHeaders != null) {
for (final Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.connect();
final BufferedOutputStream outputStream =
new BufferedOutputStream(connection.getOutputStream());
IOUtils.writeAll(queryData, outputStream);
outputStream.close();
final InputStream inputStream = new BufferedInputStream(connection.getInputStream());
final String response = IOUtils.readAll(inputStream);
inputStream.close();
return response;
} catch (final IOException e) {
if (connection != null) {
try {
final InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
final String errorString = IOUtils.readAll(errorStream);
Log.debug(errorString);
return errorString;
} else {
throw new AIServiceException("Can't connect to the api.ai service.", e);
}
} catch (final IOException ex) {
Log.warn("Can't read error response", ex);
}
}
Log.error(
"Can't make request to the API.AI service. Please, check connection settings and API access token.",
e);
throw new AIServiceException(
"Can't make request to the API.AI service. Please, check connection settings and API access token.",
e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* Method extracted for testing purposes
*
* @param voiceStream Cannot be <code>null</code>
* @param queryData Cannot be <code>null</code>
*/
protected String doSoundRequest(final InputStream voiceStream, final String queryData)
throws MalformedURLException, AIServiceException {
return doSoundRequest(voiceStream, queryData, null, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Method extracted for testing purposes
*
* @param voiceStream Cannot be <code>null</code>
* @param queryData Cannot be <code>null</code>
*/
protected String doSoundRequest(final InputStream voiceStream, final String queryData,
final Map<String, String> additionalHeaders)
throws MalformedURLException, AIServiceException {
return doSoundRequest(voiceStream, queryData, additionalHeaders, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Method extracted for testing purposes
*
* @param voiceStream Cannot be <code>null</code>
* @param queryData Cannot be <code>null</code>
*/
protected String doSoundRequest(final InputStream voiceStream, final String queryData,
final Map<String, String> additionalHeaders, final AIServiceContext serviceContext)
throws MalformedURLException, AIServiceException {
// TODO call doRequest method
assert voiceStream != null;
assert queryData != null;
HttpURLConnection connection = null;
HttpClient httpClient = null;
try {
final URL url = new URL(config.getQuestionUrl(getSessionId(serviceContext)));
Log.debug("Connecting to {}", url);
if (config.getProxy() != null) {
connection = (HttpURLConnection) url.openConnection(config.getProxy());
} else {
connection = (HttpURLConnection) url.openConnection();
}
connection.addRequestProperty("Authorization", "Bearer " + config.getApiKey());
connection.addRequestProperty("Accept", "application/json");
if (additionalHeaders != null) {
for (final Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
httpClient = new HttpClient(connection);
httpClient.setWriteSoundLog(config.isWriteSoundLog());
httpClient.connectForMultipart();
httpClient.addFormPart("request", queryData);
httpClient.addFilePart("voiceData", "voice.wav", voiceStream);
httpClient.finishMultipart();
final String response = httpClient.getResponse();
return response;
} catch (final IOException e) {
if (httpClient != null) {
final String errorString = httpClient.getErrorString();
Log.debug(errorString);
if (!StringUtils.isEmpty(errorString)) {
return errorString;
} else if (e instanceof HttpRetryException) {
final AIResponse response = new AIResponse();
final int code = ((HttpRetryException) e).responseCode();
final Status status = Status.fromResponseCode(code);
status.setErrorDetails(((HttpRetryException) e).getReason());
response.setStatus(status);
throw new AIServiceException(response);
}
}
Log.error(
"Can't make request to the API.AI service. Please, check connection settings and API.AI keys.",
e);
throw new AIServiceException(
"Can't make request to the API.AI service. Please, check connection settings and API.AI keys.",
e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
protected <TResponse> TResponse doRequest(final Type responseType, final String endpoint,
final String method) throws AIServiceException, BadResponseStatusException {
return doRequest(responseType, endpoint, method, (Map<String, String>) null);
}
protected <TRequest, TResponse> TResponse doRequest(final TRequest request,
final Type responseType, final String endpoint, final String method)
throws AIServiceException, BadResponseStatusException {
return doRequest(request, responseType, endpoint, method, (Map<String, String>) null);
}
protected <TResponse> TResponse doRequest(final Type responseType, final String endpoint,
final String method, final Map<String, String> additionalHeaders)
throws AIServiceException, BadResponseStatusException {
return doRequest((Object) null, responseType, endpoint, method, additionalHeaders);
}
protected <TRequest, TResponse> TResponse doRequest(final TRequest request,
final Type responseType, final String endpoint, final String method,
final Map<String, String> additionalHeaders)
throws AIServiceException, BadResponseStatusException {
assert endpoint != null;
HttpURLConnection connection = null;
try {
final URL url = new URL(endpoint);
final String queryData = request != null ? GSON.toJson(request) : null;
final String requestMethod = method != null ? method : DEFAULT_REQUEST_METHOD;
Log.debug("Request json: " + queryData);
if (config.getProxy() != null) {
connection = (HttpURLConnection) url.openConnection(config.getProxy());
} else {
connection = (HttpURLConnection) url.openConnection();
}
if (queryData != null && !REQUEST_METHOD_POST.equals(requestMethod)) {
throw new AIServiceException("Non-empty request should be sent using POST method");
}
connection.setRequestMethod(requestMethod);
if (REQUEST_METHOD_POST.equals(requestMethod)) {
connection.setDoOutput(true);
}
connection.addRequestProperty("Authorization", "Bearer " + config.getApiKey());
connection.addRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.addRequestProperty("Accept", "application/json");
if (additionalHeaders != null) {
for (final Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.connect();
if (queryData != null) {
final BufferedOutputStream outputStream =
new BufferedOutputStream(connection.getOutputStream());
IOUtils.writeAll(queryData, outputStream);
outputStream.close();
}
final InputStream inputStream = new BufferedInputStream(connection.getInputStream());
final String response = IOUtils.readAll(inputStream);
inputStream.close();
try {
AIResponse aiResponse = GSON.fromJson(response, AIResponse.class);
if (aiResponse.getStatus() != null && aiResponse.getStatus().getCode() != 200) {
throw new BadResponseStatusException(aiResponse);
}
} catch (JsonParseException e) {
// response is not in a expected format
}
return GSON.fromJson(response, responseType);
} catch (final IOException e) {
if (connection != null) {
try {
final InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
final String errorString = IOUtils.readAll(errorStream);
Log.debug(errorString);
throw new AIServiceException(errorString, e);
} else {
throw new AIServiceException("Can't connect to the api.ai service.", e);
}
} catch (final IOException ex) {
Log.warn("Can't read error response", ex);
}
}
Log.error(
"Can't make request to the API.AI service. Please, check connection settings and API access token.",
e);