-
Notifications
You must be signed in to change notification settings - Fork 616
/
ApiMgtDAO.java
12780 lines (11521 loc) · 555 KB
/
ApiMgtDAO.java
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
/*
* Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.
*/
package org.wso2.carbon.apimgt.impl.dao;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.BlockConditionAlreadyExistsException;
import org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException;
import org.wso2.carbon.apimgt.api.dto.ConditionDTO;
import org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO;
import org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.APIKey;
import org.wso2.carbon.apimgt.api.model.APIStatus;
import org.wso2.carbon.apimgt.api.model.APIStore;
import org.wso2.carbon.apimgt.api.model.AccessTokenInfo;
import org.wso2.carbon.apimgt.api.model.Application;
import org.wso2.carbon.apimgt.api.model.ApplicationConstants;
import org.wso2.carbon.apimgt.api.model.BlockConditionsDTO;
import org.wso2.carbon.apimgt.api.model.Comment;
import org.wso2.carbon.apimgt.api.model.KeyManager;
import org.wso2.carbon.apimgt.api.model.Label;
import org.wso2.carbon.apimgt.api.model.LifeCycleEvent;
import org.wso2.carbon.apimgt.api.model.OAuthAppRequest;
import org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo;
import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.api.model.SubscribedAPI;
import org.wso2.carbon.apimgt.api.model.Subscriber;
import org.wso2.carbon.apimgt.api.model.Tier;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.api.model.policy.APIPolicy;
import org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy;
import org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit;
import org.wso2.carbon.apimgt.api.model.policy.Condition;
import org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy;
import org.wso2.carbon.apimgt.api.model.policy.HeaderCondition;
import org.wso2.carbon.apimgt.api.model.policy.IPCondition;
import org.wso2.carbon.apimgt.api.model.policy.JWTClaimsCondition;
import org.wso2.carbon.apimgt.api.model.policy.Pipeline;
import org.wso2.carbon.apimgt.api.model.policy.Policy;
import org.wso2.carbon.apimgt.api.model.policy.PolicyConstants;
import org.wso2.carbon.apimgt.api.model.policy.QueryParameterCondition;
import org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy;
import org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit;
import org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.impl.ThrottlePolicyConstants;
import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants;
import org.wso2.carbon.apimgt.impl.dto.APIInfoDTO;
import org.wso2.carbon.apimgt.impl.dto.APIKeyInfoDTO;
import org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO;
import org.wso2.carbon.apimgt.impl.dto.APISubscriptionInfoDTO;
import org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO;
import org.wso2.carbon.apimgt.impl.dto.TierPermissionDTO;
import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO;
import org.wso2.carbon.apimgt.impl.factory.KeyManagerHolder;
import org.wso2.carbon.apimgt.impl.factory.SQLConstantManagerFactory;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.impl.utils.APIVersionComparator;
import org.wso2.carbon.apimgt.impl.utils.ApplicationUtils;
import org.wso2.carbon.apimgt.impl.utils.LRUCache;
import org.wso2.carbon.apimgt.impl.utils.RemoteUserManagerClient;
import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants;
import org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutorFactory;
import org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus;
import org.wso2.carbon.core.util.CryptoException;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException;
import org.wso2.carbon.user.core.util.UserCoreUtil;
import org.wso2.carbon.utils.DBUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class represent the ApiMgtDAO.
*/
public class ApiMgtDAO {
private static final Log log = LogFactory.getLog(ApiMgtDAO.class);
private static ApiMgtDAO INSTANCE = null;
private boolean forceCaseInsensitiveComparisons = false;
private boolean multiGroupAppSharingEnabled = false;
private static boolean initialAutoCommit = false;
private final Object scopeMutex = new Object();
private ApiMgtDAO() {
APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance()
.getAPIManagerConfigurationService().getAPIManagerConfiguration();
String caseSensitiveComparison = ServiceReferenceHolder.getInstance().
getAPIManagerConfigurationService().getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS);
if (caseSensitiveComparison != null) {
forceCaseInsensitiveComparisons = Boolean.parseBoolean(caseSensitiveComparison);
}
multiGroupAppSharingEnabled = APIUtil.isMultiGroupAppSharingEnabled();
}
public List<String> getAPIVersionsMatchingApiName(String apiName, String username) throws APIManagementException {
Connection conn = null;
PreparedStatement ps = null;
List<String> versionList = new ArrayList<String>();
ResultSet resultSet = null;
String sqlQuery = SQLConstants.GET_VERSIONS_MATCHES_API_NAME_SQL;
try {
conn = APIMgtDBUtil.getConnection();
ps = conn.prepareStatement(sqlQuery);
ps.setString(1, apiName);
ps.setString(2, username);
resultSet = ps.executeQuery();
while (resultSet.next()) {
versionList.add(resultSet.getString("API_VERSION"));
}
} catch (SQLException e) {
handleException("Failed to get API versions matches API name" + apiName, e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
}
return versionList;
}
/**
* Method to get the instance of the ApiMgtDAO.
*
* @return {@link ApiMgtDAO} instance
*/
public static ApiMgtDAO getInstance() {
if (INSTANCE == null) {
INSTANCE = new ApiMgtDAO();
}
return INSTANCE;
}
/**
* Persist the details of the token generation request (allowed domains & validity period) to be used back
* when approval has been granted.
*
* @param dto DTO related to Application Registration.
* @param onlyKeyMappingEntry When this flag is enabled, only AM_APPLICATION_KEY_MAPPING will get affected.
* @throws APIManagementException if failed to create entries in AM_APPLICATION_REGISTRATION and
* AM_APPLICATION_KEY_MAPPING tables.
*/
public void createApplicationRegistrationEntry(ApplicationRegistrationWorkflowDTO dto, boolean onlyKeyMappingEntry)
throws APIManagementException {
Connection conn = null;
PreparedStatement ps = null;
PreparedStatement queryPs = null;
PreparedStatement appRegPs = null;
ResultSet resultSet = null;
Application application = dto.getApplication();
Subscriber subscriber = application.getSubscriber();
String jsonString = dto.getAppInfoDTO().getOAuthApplicationInfo().getJsonString();
String registrationQuery = SQLConstants.GET_APPLICATION_REGISTRATION_SQL;
String registrationEntry = SQLConstants.ADD_APPLICATION_REGISTRATION_SQL;
String keyMappingEntry = SQLConstants.ADD_APPLICATION_KEY_MAPPING_SQL;
try {
conn = APIMgtDBUtil.getConnection();
conn.setAutoCommit(false);
queryPs = conn.prepareStatement(registrationQuery);
queryPs.setInt(1, subscriber.getId());
queryPs.setInt(2, application.getId());
queryPs.setString(3, dto.getKeyType());
resultSet = queryPs.executeQuery();
if (resultSet.next()) {
throw new APIManagementException("Application '" + application.getName() + "' is already registered.");
}
if (!onlyKeyMappingEntry) {
appRegPs = conn.prepareStatement(registrationEntry);
appRegPs.setInt(1, subscriber.getId());
appRegPs.setString(2, dto.getWorkflowReference());
appRegPs.setInt(3, application.getId());
appRegPs.setString(4, dto.getKeyType());
appRegPs.setString(5, dto.getDomainList());
appRegPs.setLong(6, dto.getValidityTime());
appRegPs.setString(7, (String) dto.getAppInfoDTO().getOAuthApplicationInfo().getParameter("tokenScope"));
appRegPs.setString(8, jsonString);
appRegPs.execute();
}
ps = conn.prepareStatement(keyMappingEntry);
ps.setInt(1, application.getId());
ps.setString(2, dto.getKeyType());
ps.setString(3, dto.getStatus().toString());
ps.execute();
conn.commit();
} catch (SQLException e) {
try {
if (conn != null) {
conn.rollback();
}
} catch (SQLException e1) {
handleException("Error occurred while Rolling back changes done on Application Registration", e1);
}
handleException("Error occurred while creating an " +
"Application Registration Entry for Application : " + application.getName(), e);
} finally {
APIMgtDBUtil.closeStatement(queryPs);
APIMgtDBUtil.closeStatement(appRegPs);
APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
}
}
public OAuthApplicationInfo getOAuthApplication(String consumerKey) throws APIManagementException {
OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sqlQuery = SQLConstants.GET_OAUTH_APPLICATION_SQL;
try {
conn = APIMgtDBUtil.getConnection();
ps = conn.prepareStatement(sqlQuery);
ps.setString(1, consumerKey);
rs = ps.executeQuery();
while (rs.next()) {
oAuthApplicationInfo.setClientId(consumerKey);
oAuthApplicationInfo.setCallBackURL(rs.getString("CALLBACK_URL"));
oAuthApplicationInfo.setClientSecret(APIUtil.decryptToken(rs.getString("CONSUMER_SECRET")));
oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_REDIRECT_URIS, rs.getString
("CALLBACK_URL"));
oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_CLIENT_NAME, rs.getString("APP_NAME"));
oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_CLIENT_GRANT, rs.getString("GRANT_TYPES"));
}
} catch (SQLException e) {
handleException("Error while executing SQL for getting OAuth application info", e);
} catch (CryptoException e) {
handleException("Unable to decrypt consumer secret of consumer key " + consumerKey, e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, rs);
}
return oAuthApplicationInfo;
}
/**
* Get the creator of the OAuth App.
*
* @param consumerKey Client ID of the OAuth App
* @return {@code Subscriber} with name and TenantId set.
* @throws APIManagementException
*/
public Subscriber getOwnerForConsumerApp(String consumerKey) throws APIManagementException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String username;
Subscriber subscriber = null;
String sqlQuery = SQLConstants.GET_OWNER_FOR_CONSUMER_APP_SQL;
try {
conn = APIMgtDBUtil.getConnection();
ps = conn.prepareStatement(sqlQuery);
ps.setString(1, consumerKey);
rs = ps.executeQuery();
while (rs.next()) {
username = rs.getString("USERNAME");
String domainName = rs.getString(APIConstants.IDENTITY_OAUTH2_FIELD_USER_DOMAIN);
String endUsernameWithDomain = UserCoreUtil.addDomainToName(username, domainName);
subscriber = new Subscriber(endUsernameWithDomain);
subscriber.setTenantId(rs.getInt("TENANT_ID"));
}
} catch (SQLException e) {
handleException("Error while executing SQL for getting User Id : SQL " + sqlQuery, e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, rs);
}
return subscriber;
}
/**
* Get Subscribed APIs for given userId
*
* @param userId id of the user
* @return APIInfoDTO[]
* @throws APIManagementException if failed to get Subscribed APIs
*/
public APIInfoDTO[] getSubscribedAPIsOfUser(String userId) throws APIManagementException {
List<APIInfoDTO> apiInfoDTOList = new ArrayList<APIInfoDTO>();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
//identify logged in user
String loginUserName = getLoginUserName(userId);
String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(loginUserName);
int tenantId = APIUtil.getTenantId(loginUserName);
String sqlQuery = SQLConstants.GET_SUBSCRIBED_APIS_OF_USER_SQL;
if (forceCaseInsensitiveComparisons) {
sqlQuery = SQLConstants.GET_SUBSCRIBED_APIS_OF_USER_CASE_INSENSITIVE_SQL;
}
try {
conn = APIMgtDBUtil.getConnection();
ps = conn.prepareStatement(sqlQuery);
ps.setString(1, tenantAwareUsername);
ps.setInt(2, tenantId);
rs = ps.executeQuery();
while (rs.next()) {
APIInfoDTO infoDTO = new APIInfoDTO();
infoDTO.setProviderId(APIUtil.replaceEmailDomain(rs.getString("API_PROVIDER")));
infoDTO.setApiName(rs.getString("API_NAME"));
infoDTO.setVersion(rs.getString("API_VERSION"));
apiInfoDTOList.add(infoDTO);
}
} catch (SQLException e) {
handleException("Error while executing SQL", e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, rs);
}
return apiInfoDTOList.toArray(new APIInfoDTO[apiInfoDTOList.size()]);
}
/**
* Get API key information for given API
*
* @param apiInfoDTO API info
* @return APIKeyInfoDTO[]
* @throws APIManagementException if failed to get key info for given API
*/
public APIKeyInfoDTO[] getSubscribedUsersForAPI(APIInfoDTO apiInfoDTO) throws APIManagementException {
APIKeyInfoDTO[] apiKeyInfoDTOs = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<APIKeyInfoDTO> apiKeyInfoList = new ArrayList<APIKeyInfoDTO>();
String sqlQuery = SQLConstants.GET_SUBSCRIBED_USERS_FOR_API_SQL;
try {
conn = APIMgtDBUtil.getConnection();
ps = conn.prepareStatement(sqlQuery);
ps.setString(1, APIUtil.replaceEmailDomainBack(apiInfoDTO.getProviderId()));
ps.setString(2, apiInfoDTO.getApiName());
ps.setString(3, apiInfoDTO.getVersion());
rs = ps.executeQuery();
while (rs.next()) {
String userId = rs.getString(APIConstants.SUBSCRIBER_FIELD_USER_ID);
APIKeyInfoDTO apiKeyInfoDTO = new APIKeyInfoDTO();
apiKeyInfoDTO.setUserId(userId);
apiKeyInfoList.add(apiKeyInfoDTO);
}
apiKeyInfoDTOs = apiKeyInfoList.toArray(new APIKeyInfoDTO[apiKeyInfoList.size()]);
} catch (SQLException e) {
handleException("Error while executing SQL", e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, rs);
}
return apiKeyInfoDTOs;
}
/**
* This method is to update the access token
*
* @param userId id of the user
* @param apiInfoDTO Api info
* @param statusEnum Status of the access key
* @throws APIManagementException if failed to update the access token
*/
public void changeAccessTokenStatus(String userId, APIInfoDTO apiInfoDTO, String statusEnum)
throws APIManagementException {
Connection conn = null;
PreparedStatement ps = null;
String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(userId);
int tenantId = APIUtil.getTenantId(userId);
String accessTokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
accessTokenStoreTable = getAccessTokenStoreTableNameOfUserId(userId, accessTokenStoreTable);
String sqlQuery = SQLConstants.CHANGE_ACCESS_TOKEN_STATUS_PREFIX +
accessTokenStoreTable + SQLConstants.CHANGE_ACCESS_TOKEN_STATUS_DEFAULT_SUFFIX;
if (forceCaseInsensitiveComparisons) {
sqlQuery = SQLConstants.CHANGE_ACCESS_TOKEN_STATUS_PREFIX +
accessTokenStoreTable + SQLConstants.CHANGE_ACCESS_TOKEN_STATUS_CASE_INSENSITIVE_SUFFIX;
}
try {
conn = APIMgtDBUtil.getConnection();
conn.setAutoCommit(false);
ps = conn.prepareStatement(sqlQuery);
ps.setString(1, statusEnum);
ps.setString(2, tenantAwareUsername);
ps.setInt(3, tenantId);
ps.setString(4, APIUtil.replaceEmailDomainBack(apiInfoDTO.getProviderId()));
ps.setString(5, apiInfoDTO.getApiName());
ps.setString(6, apiInfoDTO.getVersion());
int count = ps.executeUpdate();
if (log.isDebugEnabled()) {
log.debug("Number of rows being updated : " + count);
}
conn.commit();
} catch (SQLException e) {
try {
if (conn != null) {
conn.rollback();
}
} catch (SQLException e1) {
log.error("Failed to rollback the changeAccessTokenStatus operation", e1);
}
handleException("Error while executing SQL", e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, null);
}
}
public boolean validateSubscriptionDetails(String context, String version, String consumerKey,
APIKeyValidationInfoDTO infoDTO) throws APIManagementException {
boolean defaultVersionInvoked = false;
String apiTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(context);
if (apiTenantDomain == null) {
apiTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
}
int apiOwnerTenantId = APIUtil.getTenantIdFromTenantDomain(apiTenantDomain);
//Check if the api version has been prefixed with _default_
if (version != null && version.startsWith(APIConstants.DEFAULT_VERSION_PREFIX)) {
defaultVersionInvoked = true;
//Remove the prefix from the version.
version = version.split(APIConstants.DEFAULT_VERSION_PREFIX)[1];
}
String sql;
boolean isAdvancedThrottleEnabled = APIUtil.isAdvanceThrottlingEnabled();
if (!isAdvancedThrottleEnabled) {
if (defaultVersionInvoked) {
sql = SQLConstants.VALIDATE_SUBSCRIPTION_KEY_DEFAULT_SQL;
} else {
sql = SQLConstants.VALIDATE_SUBSCRIPTION_KEY_VERSION_SQL;
}
} else {
if (defaultVersionInvoked) {
sql = SQLConstants.ADVANCED_VALIDATE_SUBSCRIPTION_KEY_DEFAULT_SQL;
} else {
sql = SQLConstants.ADVANCED_VALIDATE_SUBSCRIPTION_KEY_VERSION_SQL;
}
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = APIMgtDBUtil.getConnection();
conn.setAutoCommit(true);
ps = conn.prepareStatement(sql);
ps.setString(1, context);
ps.setString(2, consumerKey);
if (!isAdvancedThrottleEnabled) {
if (!defaultVersionInvoked) {
ps.setString(3, version);
}
} else {
ps.setInt(3, apiOwnerTenantId);
if (!defaultVersionInvoked) {
ps.setString(4, version);
}
}
rs = ps.executeQuery();
if (rs.next()) {
String subscriptionStatus = rs.getString("SUB_STATUS");
String type = rs.getString("KEY_TYPE");
if (APIConstants.SubscriptionStatus.BLOCKED.equals(subscriptionStatus)) {
infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_BLOCKED);
infoDTO.setAuthorized(false);
return false;
} else if (APIConstants.SubscriptionStatus.ON_HOLD.equals(subscriptionStatus) || APIConstants
.SubscriptionStatus.REJECTED.equals(subscriptionStatus)) {
infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.SUBSCRIPTION_INACTIVE);
infoDTO.setAuthorized(false);
return false;
} else if (APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED.equals(subscriptionStatus) &&
!APIConstants.API_KEY_TYPE_SANDBOX.equals(type)) {
infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_BLOCKED);
infoDTO.setType(type);
infoDTO.setAuthorized(false);
return false;
}
String tokenType = rs.getString("TOKEN_TYPE");
if (APIConstants.JWT.equals(tokenType)) {
infoDTO.setAuthorized(false);
return false;
}
String apiProvider = rs.getString("API_PROVIDER");
String subTier = rs.getString("TIER_ID");
String appTier = rs.getString("APPLICATION_TIER");
infoDTO.setTier(subTier);
infoDTO.setSubscriber(rs.getString("USER_ID"));
infoDTO.setApplicationId(rs.getString("APPLICATION_ID"));
infoDTO.setApiName(rs.getString("API_NAME"));
infoDTO.setApiPublisher(apiProvider);
infoDTO.setApplicationName(rs.getString("NAME"));
infoDTO.setApplicationTier(appTier);
infoDTO.setType(type);
//Advanced Level Throttling Related Properties
if (APIUtil.isAdvanceThrottlingEnabled()) {
String apiTier = rs.getString("API_TIER");
String subscriberUserId = rs.getString("USER_ID");
String subscriberTenant = MultitenantUtils.getTenantDomain(subscriberUserId);
int apiId = rs.getInt("API_ID");
int subscriberTenantId = APIUtil.getTenantId(subscriberUserId);
int apiTenantId = APIUtil.getTenantId(apiProvider);
//TODO isContentAware
boolean isContentAware = isAnyPolicyContentAware(conn, apiTier, appTier, subTier, subscriberTenantId, apiTenantId, apiId);
infoDTO.setContentAware(isContentAware);
//TODO this must implement as a part of throttling implementation.
int spikeArrest = 0;
String apiLevelThrottlingKey = "api_level_throttling_key";
if (rs.getInt("RATE_LIMIT_COUNT") > 0) {
spikeArrest = rs.getInt("RATE_LIMIT_COUNT");
}
String spikeArrestUnit = null;
if (rs.getString("RATE_LIMIT_TIME_UNIT") != null) {
spikeArrestUnit = rs.getString("RATE_LIMIT_TIME_UNIT");
}
boolean stopOnQuotaReach = rs.getBoolean("STOP_ON_QUOTA_REACH");
List<String> list = new ArrayList<String>();
list.add(apiLevelThrottlingKey);
infoDTO.setSpikeArrestLimit(spikeArrest);
infoDTO.setSpikeArrestUnit(spikeArrestUnit);
infoDTO.setStopOnQuotaReach(stopOnQuotaReach);
infoDTO.setSubscriberTenantDomain(subscriberTenant);
if (apiTier != null && apiTier.trim().length() > 0) {
infoDTO.setApiTier(apiTier);
}
//We also need to set throttling data list associated with given API. This need to have policy id and
// condition id list for all throttling tiers associated with this API.
infoDTO.setThrottlingDataList(list);
}
return true;
}
infoDTO.setAuthorized(false);
infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN);
} catch (SQLException e) {
handleException("Exception occurred while validating Subscription.", e);
} finally {
try {
conn.setAutoCommit(false);
} catch (SQLException e) {
}
APIMgtDBUtil.closeAllConnections(ps, conn, rs);
}
return false;
}
private boolean isAnyPolicyContentAware(Connection conn, String apiPolicy, String appPolicy,
String subPolicy, int subscriptionTenantId, int appTenantId, int apiId) throws APIManagementException {
boolean isAnyContentAware = false;
// only check if using CEP based throttling.
ResultSet resultSet = null;
PreparedStatement ps = null;
String sqlQuery = SQLConstants.ThrottleSQLConstants.IS_ANY_POLICY_CONTENT_AWARE_SQL;
try {
String dbProdName = conn.getMetaData().getDatabaseProductName();
ps = conn.prepareStatement(sqlQuery);
ps.setString(1, apiPolicy);
ps.setInt(2, subscriptionTenantId);
ps.setString(3, apiPolicy);
ps.setInt(4, subscriptionTenantId);
ps.setInt(5, apiId);
ps.setInt(6, subscriptionTenantId);
ps.setInt(7, apiId);
ps.setInt(8, subscriptionTenantId);
ps.setString(9, subPolicy);
ps.setInt(10, subscriptionTenantId);
ps.setString(11, appPolicy);
ps.setInt(12, appTenantId);
resultSet = ps.executeQuery();
// We only expect one result if all are not content aware.
if (resultSet == null) {
throw new APIManagementException(" Result set Null");
}
int count = 0;
if (resultSet.next()) {
count = resultSet.getInt(1);
if (count > 0) {
isAnyContentAware = true;
}
}
} catch (SQLException e) {
handleException("Failed to get content awareness of the policies ", e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, null, resultSet);
}
return isAnyContentAware;
}
public void addSubscriber(Subscriber subscriber, String groupingId) throws APIManagementException {
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
conn = APIMgtDBUtil.getConnection();
conn.setAutoCommit(false);
String query = SQLConstants.ADD_SUBSCRIBER_SQL;
ps = conn.prepareStatement(query, new String[]{"subscriber_id"});
ps.setString(1, subscriber.getName());
ps.setInt(2, subscriber.getTenantId());
ps.setString(3, subscriber.getEmail());
Timestamp timestamp = new Timestamp(subscriber.getSubscribedDate().getTime());
ps.setTimestamp(4, timestamp);
ps.setString(5, subscriber.getName());
ps.setTimestamp(6, timestamp);
ps.setTimestamp(7, timestamp);
ps.executeUpdate();
int subscriberId = 0;
rs = ps.getGeneratedKeys();
if (rs.next()) {
subscriberId = Integer.parseInt(rs.getString(1));
}
subscriber.setId(subscriberId);
conn.commit();
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();
} catch (SQLException e1) {
log.error("Error while rolling back the failed operation", e1);
}
}
handleException("Error in adding new subscriber: " + e.getMessage(), e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, rs);
}
}
public void updateSubscriber(Subscriber subscriber) throws APIManagementException {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = APIMgtDBUtil.getConnection();
conn.setAutoCommit(false);
String query = SQLConstants.UPDATE_SUBSCRIBER_SQL;
ps = conn.prepareStatement(query);
ps.setString(1, subscriber.getName());
ps.setInt(2, subscriber.getTenantId());
ps.setString(3, subscriber.getEmail());
ps.setTimestamp(4, new Timestamp(subscriber.getSubscribedDate().getTime()));
ps.setString(5, subscriber.getName());
ps.setTimestamp(6, new Timestamp(System.currentTimeMillis()));
ps.setInt(7, subscriber.getId());
ps.executeUpdate();
conn.commit();
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();
} catch (SQLException e1) {
log.error("Error while rolling back the failed operation", e1);
}
}
handleException("Error in updating subscriber: " + e.getMessage(), e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, null);
}
}
public Subscriber getSubscriber(int subscriberId) throws APIManagementException {
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
conn = APIMgtDBUtil.getConnection();
String query = SQLConstants.GET_SUBSCRIBER_SQL;
ps = conn.prepareStatement(query);
ps.setInt(1, subscriberId);
rs = ps.executeQuery();
if (rs.next()) {
Subscriber subscriber = new Subscriber(rs.getString("USER_ID"));
subscriber.setId(subscriberId);
subscriber.setTenantId(rs.getInt("TENANT_ID"));
subscriber.setEmail(rs.getString("EMAIL_ADDRESS"));
subscriber.setSubscribedDate(new java.util.Date(rs.getTimestamp("DATE_SUBSCRIBED").getTime()));
return subscriber;
}
} catch (SQLException e) {
handleException("Error while retrieving subscriber: " + e.getMessage(), e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, rs);
}
return null;
}
public int addSubscription(APIIdentifier identifier, String context, int applicationId, String status,
String subscriber) throws APIManagementException {
Connection conn = null;
ResultSet resultSet = null;
PreparedStatement ps = null;
PreparedStatement preparedStForInsert = null;
ResultSet rs = null;
int subscriptionId = -1;
int apiId;
try {
conn = APIMgtDBUtil.getConnection();
conn.setAutoCommit(false);
apiId = getAPIID(identifier, conn);
//Query to check if this subscription already exists
String checkDuplicateQuery = SQLConstants.CHECK_EXISTING_SUBSCRIPTION_SQL;
ps = conn.prepareStatement(checkDuplicateQuery);
ps.setInt(1, apiId);
ps.setInt(2, applicationId);
resultSet = ps.executeQuery();
//If the subscription already exists
if (resultSet.next()) {
String subStatus = resultSet.getString("SUB_STATUS");
String subCreationStatus = resultSet.getString("SUBS_CREATE_STATE");
String applicationName = getApplicationNameFromId(applicationId);
if ((APIConstants.SubscriptionStatus.UNBLOCKED.equals(subStatus) ||
APIConstants.SubscriptionStatus.ON_HOLD.equals(subStatus) ||
APIConstants.SubscriptionStatus.REJECTED.equals(subStatus)) &&
APIConstants.SubscriptionCreatedStatus.SUBSCRIBE.equals(subCreationStatus)) {
//Throw error saying subscription already exists.
log.error("Subscription already exists for API " + identifier.getApiName() + " in Application " +
applicationName);
throw new SubscriptionAlreadyExistingException("Subscription already exists for API " +
identifier.getApiName() + " in Application " +
applicationName);
} else if (APIConstants.SubscriptionStatus.UNBLOCKED.equals(subStatus) && APIConstants
.SubscriptionCreatedStatus.UN_SUBSCRIBE.equals(subCreationStatus)) {
deleteSubscriptionByApiIDAndAppID(apiId, applicationId, conn);
} else if (APIConstants.SubscriptionStatus.BLOCKED.equals(subStatus) || APIConstants
.SubscriptionStatus.PROD_ONLY_BLOCKED.equals(subStatus)) {
log.error("Subscription to API " + identifier.getApiName() + " through application " +
applicationName + " was blocked");
throw new APIManagementException("Subscription to API " + identifier.getApiName() + " through " +
"application " + applicationName + " was blocked");
}
}
//This query to update the AM_SUBSCRIPTION table
String sqlQuery = SQLConstants.ADD_SUBSCRIPTION_SQL;
//Adding data to the AM_SUBSCRIPTION table
//ps = conn.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS);
preparedStForInsert = conn.prepareStatement(sqlQuery, new String[]{"SUBSCRIPTION_ID"});
if (conn.getMetaData().getDriverName().contains("PostgreSQL")) {
preparedStForInsert = conn.prepareStatement(sqlQuery, new String[]{"subscription_id"});
}
preparedStForInsert.setString(1, identifier.getTier());
preparedStForInsert.setInt(2, apiId);
preparedStForInsert.setInt(3, applicationId);
preparedStForInsert.setString(4, status != null ? status : APIConstants.SubscriptionStatus.UNBLOCKED);
preparedStForInsert.setString(5, APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
preparedStForInsert.setString(6, subscriber);
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
preparedStForInsert.setTimestamp(7, timestamp);
preparedStForInsert.setTimestamp(8, timestamp);
preparedStForInsert.setString(9, UUID.randomUUID().toString());
preparedStForInsert.executeUpdate();
rs = preparedStForInsert.getGeneratedKeys();
while (rs.next()) {
//subscriptionId = rs.getInt(1);
subscriptionId = Integer.parseInt(rs.getString(1));
}
// finally commit transaction
conn.commit();
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();
} catch (SQLException e1) {
log.error("Failed to rollback the add subscription ", e1);
}
}
handleException("Failed to add subscriber data ", e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
APIMgtDBUtil.closeAllConnections(preparedStForInsert, null, rs);
}
return subscriptionId;
}
/**
* Removes the subscription entry from AM_SUBSCRIPTIONS for identifier.
*
* @param identifier APIIdentifier
* @param applicationId ID of the application which has the subscription
* @throws APIManagementException
*/
public void removeSubscription(APIIdentifier identifier, int applicationId)
throws APIManagementException {
Connection conn = null;
ResultSet resultSet = null;
PreparedStatement ps = null;
int apiId = -1;
String uuid;
try {
conn = APIMgtDBUtil.getConnection();
conn.setAutoCommit(false);
apiId = getAPIID(identifier, conn);
String subscriptionUUIDQuery = SQLConstants.GET_SUBSCRIPTION_UUID_SQL;
ps = conn.prepareStatement(subscriptionUUIDQuery);
ps.setInt(1, apiId);
ps.setInt(2, applicationId);
resultSet = ps.executeQuery();
if (resultSet.next()) {
uuid = resultSet.getString("UUID");
SubscribedAPI subscribedAPI = new SubscribedAPI(uuid);
removeSubscription(subscribedAPI, conn);
} else {
throw new APIManagementException("UUID does not exist for the given apiId:" + apiId + " and " +
"application id:" + applicationId);
}
conn.commit();
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();
} catch (SQLException ex) {
log.error("Failed to rollback the add subscription ", ex);
}
}
handleException("Failed to add subscriber data ", e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
}
}
/**
* Removes a subscription specified by SubscribedAPI object
*
* @param subscription SubscribedAPI object
* @param conn database connection object
* @throws APIManagementException
*/
public void removeSubscription(SubscribedAPI subscription, Connection conn) throws APIManagementException {
ResultSet resultSet = null;
PreparedStatement ps = null;
PreparedStatement preparedStForUpdateOrDelete = null;
String subStatus = null;
try {
String subscriptionStatusQuery = SQLConstants.GET_SUBSCRIPTION_STATUS_BY_UUID_SQL;
ps = conn.prepareStatement(subscriptionStatusQuery);
ps.setString(1, subscription.getUUID());
resultSet = ps.executeQuery();
if (resultSet.next()) {
subStatus = resultSet.getString("SUB_STATUS");
}
// If the user was unblocked, remove the entry from DB, else change the status and keep the entry.
String updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_SQL;
String deleteQuery = SQLConstants.REMOVE_SUBSCRIPTION_SQL;
if (APIConstants.SubscriptionStatus.BLOCKED.equals(subStatus) || APIConstants.SubscriptionStatus
.PROD_ONLY_BLOCKED.equals(subStatus)) {
preparedStForUpdateOrDelete = conn.prepareStatement(updateQuery);
preparedStForUpdateOrDelete.setString(1, subscription.getUUID());
} else {
preparedStForUpdateOrDelete = conn.prepareStatement(deleteQuery);
preparedStForUpdateOrDelete.setString(1, subscription.getUUID());
}
preparedStForUpdateOrDelete.executeUpdate();
} catch (SQLException e) {
log.error("Failed to add subscriber data ", e);
handleException("Failed to add subscriber data ", e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, null, resultSet);
APIMgtDBUtil.closeAllConnections(preparedStForUpdateOrDelete, null, null);
}
}
/**
* Removes a subscription by id by force without considering the subscription blocking state of the user
*
* @param subscription_id id of subscription
* @throws APIManagementException
*/
public void removeSubscriptionById(int subscription_id) throws APIManagementException {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = APIMgtDBUtil.getConnection();
conn.setAutoCommit(false);
String sqlQuery = SQLConstants.REMOVE_SUBSCRIPTION_BY_ID_SQL;
ps = conn.prepareStatement(sqlQuery);
ps.setInt(1, subscription_id);
ps.executeUpdate();
conn.commit();
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();
} catch (SQLException e1) {
log.error("Failed to rollback remove subscription ", e1);
}
}
handleException("Failed to remove subscription data ", e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, null);
}
}
public void removeAllSubscriptions(APIIdentifier apiIdentifier) throws APIManagementException {
Connection conn = null;