use of org.wso2.carbon.apimgt.api.model.Tier in project carbon-apimgt by wso2.
the class ApiMgtDAO method addSubscription.
private int addSubscription(Connection connection, ApiTypeWrapper apiTypeWrapper, Application application, String subscriptionStatus, String subscriber) throws APIManagementException, SQLException {
final boolean isProduct = apiTypeWrapper.isAPIProduct();
int subscriptionId = -1;
int id = -1;
String apiUUID;
Identifier identifier;
String tier;
// Query to check if this subscription already exists
String checkDuplicateQuery = SQLConstants.CHECK_EXISTING_SUBSCRIPTION_API_SQL;
if (!isProduct) {
identifier = apiTypeWrapper.getApi().getId();
apiUUID = apiTypeWrapper.getApi().getUuid();
if (apiUUID != null) {
id = getAPIID(apiUUID);
}
if (id == -1) {
id = identifier.getId();
}
} else {
identifier = apiTypeWrapper.getApiProduct().getId();
id = apiTypeWrapper.getApiProduct().getProductId();
apiUUID = apiTypeWrapper.getApiProduct().getUuid();
}
int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
try (PreparedStatement ps = connection.prepareStatement(checkDuplicateQuery)) {
ps.setInt(1, id);
ps.setInt(2, application.getId());
try (ResultSet resultSet = ps.executeQuery()) {
// If the subscription already exists
if (resultSet.next()) {
String subStatus = resultSet.getString("SUB_STATUS");
String subCreationStatus = resultSet.getString("SUBS_CREATE_STATE");
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(String.format("Subscription already exists for API/API Prouct %s in Application %s", apiTypeWrapper.getName(), application.getName()));
throw new SubscriptionAlreadyExistingException(String.format("Subscription already exists for" + " API/API Prouct %s in Application %s", apiTypeWrapper.getName(), application.getName()));
} else if (APIConstants.SubscriptionStatus.UNBLOCKED.equals(subStatus) && APIConstants.SubscriptionCreatedStatus.UN_SUBSCRIBE.equals(subCreationStatus)) {
deleteSubscriptionByApiIDAndAppID(id, application.getId(), connection);
} else if (APIConstants.SubscriptionStatus.BLOCKED.equals(subStatus) || APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED.equals(subStatus)) {
log.error(String.format(String.format("Subscription to API/API Prouct %%s through application" + " %%s was blocked"), apiTypeWrapper.getName(), application.getName()));
throw new SubscriptionBlockedException(String.format("Subscription to API/API Product %s " + "through application %s was blocked", apiTypeWrapper.getName(), application.getName()));
} else if (APIConstants.SubscriptionStatus.REJECTED.equals(subStatus)) {
throw new SubscriptionBlockedException("Subscription to API " + apiTypeWrapper.getName() + " through application " + application.getName() + " was rejected");
}
}
}
}
// 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);
String subscriptionIDColumn = "SUBSCRIPTION_ID";
String subscriptionUUID = UUID.randomUUID().toString();
if (connection.getMetaData().getDriverName().contains("PostgreSQL")) {
subscriptionIDColumn = "subscription_id";
}
try (PreparedStatement preparedStForInsert = connection.prepareStatement(sqlQuery, new String[] { subscriptionIDColumn })) {
if (!isProduct) {
tier = apiTypeWrapper.getApi().getId().getTier();
preparedStForInsert.setString(1, tier);
preparedStForInsert.setString(10, tier);
} else {
tier = apiTypeWrapper.getApiProduct().getId().getTier();
preparedStForInsert.setString(1, tier);
preparedStForInsert.setString(10, tier);
}
preparedStForInsert.setInt(2, id);
preparedStForInsert.setInt(3, application.getId());
preparedStForInsert.setString(4, subscriptionStatus != null ? subscriptionStatus : 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, subscriptionUUID);
preparedStForInsert.executeUpdate();
try (ResultSet rs = preparedStForInsert.getGeneratedKeys()) {
while (rs.next()) {
// subscriptionId = rs.getInt(1);
subscriptionId = Integer.parseInt(rs.getString(1));
}
}
}
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, subscriptionUUID, id, apiUUID, application.getId(), application.getUUID(), tier, (subscriptionStatus != null ? subscriptionStatus : APIConstants.SubscriptionStatus.UNBLOCKED));
return subscriptionId;
}
use of org.wso2.carbon.apimgt.api.model.Tier in project carbon-apimgt by wso2.
the class ApiMgtDAO method getThrottleTierPermission.
public TierPermissionDTO getThrottleTierPermission(String tierName, int tenantId) throws APIManagementException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
TierPermissionDTO tierPermission = null;
try {
String getTierPermissionQuery = SQLConstants.GET_THROTTLE_TIER_PERMISSION_SQL;
conn = APIMgtDBUtil.getConnection();
ps = conn.prepareStatement(getTierPermissionQuery);
ps.setString(1, tierName);
ps.setInt(2, tenantId);
resultSet = ps.executeQuery();
while (resultSet.next()) {
tierPermission = new TierPermissionDTO();
tierPermission.setTierName(tierName);
tierPermission.setPermissionType(resultSet.getString("PERMISSIONS_TYPE"));
String roles = resultSet.getString("ROLES");
if (roles != null) {
String[] roleList = roles.split(",");
tierPermission.setRoles(roleList);
}
}
} catch (SQLException e) {
handleException("Failed to get Tier permission information for Tier " + tierName, e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
}
return tierPermission;
}
use of org.wso2.carbon.apimgt.api.model.Tier in project carbon-apimgt by wso2.
the class CertificateMgtDAO method updateClientCertificate.
/**
* To update an already existing client certificate.
*
* @param certificate : Specific certificate.
* @param alias : Alias of the certificate.
* @param tier : Name of tier related with the certificate.
* @param tenantId : ID of the tenant.
* @param organization : Organization
* @return true if the update succeeds, unless false.
* @throws CertificateManagementException Certificate Management Exception.
*/
public boolean updateClientCertificate(String certificate, String alias, String tier, int tenantId, String organization) throws CertificateManagementException {
List<ClientCertificateDTO> clientCertificateDTOList = getClientCertificates(tenantId, alias, null, organization);
ClientCertificateDTO clientCertificateDTO;
if (clientCertificateDTOList.size() == 0) {
if (log.isDebugEnabled()) {
log.debug("Client certificate update request is received for a non-existing alias " + alias + " of " + "tenant " + tenantId);
}
return false;
}
clientCertificateDTO = clientCertificateDTOList.get(0);
if (StringUtils.isNotEmpty(certificate)) {
clientCertificateDTO.setCertificate(certificate);
}
if (StringUtils.isNotEmpty(tier)) {
clientCertificateDTO.setTierName(tier);
}
try (Connection connection = APIMgtDBUtil.getConnection()) {
try {
connection.setAutoCommit(false);
deleteClientCertificate(connection, null, alias, tenantId);
addClientCertificate(connection, clientCertificateDTO.getCertificate(), clientCertificateDTO.getApiIdentifier(), alias, clientCertificateDTO.getTierName(), tenantId, organization);
connection.commit();
} catch (SQLException e) {
handleConnectionRollBack(connection);
handleException("Error while updating client certificate for the API for the alias " + alias, e);
}
} catch (SQLException e) {
handleException("Error while updating client certificate for the API for the alias " + alias, e);
}
return true;
}
use of org.wso2.carbon.apimgt.api.model.Tier in project carbon-apimgt by wso2.
the class APIProviderImplTest method testUpdateAPI_InCreatedState.
@Test
public void testUpdateAPI_InCreatedState() throws Exception {
APIIdentifier identifier = new APIIdentifier("admin-AT-carbon.super", "API1", "1.0.0");
Set<String> environments = new HashSet<String>();
Set<URITemplate> uriTemplates = new HashSet<URITemplate>();
Set<URITemplate> newUriTemplates = new HashSet<URITemplate>();
Tier tier = new Tier("Gold");
Map<String, Tier> tiers = new TreeMap<>();
tiers.put("Gold", tier);
URITemplate uriTemplate1 = new URITemplate();
uriTemplate1.setHTTPVerb("POST");
uriTemplate1.setAuthType("Application");
uriTemplate1.setUriTemplate("/add");
uriTemplate1.setThrottlingTier("Gold");
uriTemplates.add(uriTemplate1);
URITemplate uriTemplate2 = new URITemplate();
uriTemplate2.setHTTPVerb("PUT");
uriTemplate2.setAuthType("Application");
uriTemplate2.setUriTemplate("/update");
uriTemplate2.setThrottlingTier("Gold");
newUriTemplates.add(uriTemplate1);
newUriTemplates.add(uriTemplate2);
final API api = new API(identifier);
api.setStatus(APIConstants.CREATED);
api.setVisibility("public");
api.setAccessControl("all");
api.setTransports("http,https");
api.setContext("/test");
api.setEnvironments(environments);
api.setUriTemplates(newUriTemplates);
api.setOrganization("carbon.super");
API oldApi = new API(identifier);
oldApi.setStatus(APIConstants.CREATED);
oldApi.setVisibility("public");
oldApi.setAccessControl("all");
oldApi.setContext("/test");
oldApi.setEnvironments(environments);
api.setUriTemplates(uriTemplates);
oldApi.setOrganization("carbon.super");
List<Documentation> documentationList = getDocumentationList();
Documentation documentation = documentationList.get(1);
Mockito.when(APIUtil.getAPIDocPath(api.getId())).thenReturn(documentation.getFilePath());
APIProviderImplWrapper apiProviderImplWrapper = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO);
Resource docResource = Mockito.mock(Resource.class);
Mockito.when(docResource.getUUID()).thenReturn(documentation.getId());
Mockito.when(apiProviderImplWrapper.registry.get(documentation.getFilePath())).thenReturn(docResource);
GenericArtifact docArtifact = Mockito.mock(GenericArtifact.class);
Mockito.when(artifactManager.getGenericArtifact(documentation.getId())).thenReturn(docArtifact);
Mockito.when(APIUtil.getDocumentation(docArtifact)).thenReturn(documentation);
Mockito.when(docArtifact.getPath()).thenReturn(artifactPath);
PowerMockito.doNothing().when(APIUtil.class, "clearResourcePermissions", Mockito.any(), Mockito.any(), Mockito.anyInt());
String[] roles = { "admin", "subscriber" };
APIUtil.setResourcePermissions("admin", "Public", roles, artifactPath);
Mockito.when(docArtifact.getAttribute(APIConstants.DOC_FILE_PATH)).thenReturn("docFilePath");
final APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, documentationList, null);
RegistryService registryService = Mockito.mock(RegistryService.class);
UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
RealmService realmService = Mockito.mock(RealmService.class);
TenantManager tenantManager = Mockito.mock(TenantManager.class);
Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
Mockito.when(APIUtil.createAPIArtifactContent(artifact, oldApi)).thenReturn(artifact);
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
Mockito.when(registryService.getConfigSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
apiProvider.addAPI(oldApi);
// mock has permission
Resource apiSourceArtifact = Mockito.mock(Resource.class);
Mockito.when(apiSourceArtifact.getUUID()).thenReturn("12640983654");
String apiSourcePath = "path";
PowerMockito.when(APIUtil.getAPIPath(api.getId())).thenReturn(apiSourcePath);
PowerMockito.when(APIUtil.getAPIPath(oldApi.getId())).thenReturn(apiSourcePath);
PowerMockito.when(apiProvider.registry.get(apiSourcePath)).thenReturn(apiSourceArtifact);
// API Status is CREATED and user has permission
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)).thenReturn("CREATED");
Mockito.when(artifactManager.getGenericArtifact(apiSourceArtifact.getUUID())).thenReturn(artifact);
PowerMockito.when(APIUtil.hasPermission(null, APIConstants.Permissions.API_PUBLISH)).thenReturn(true);
PowerMockito.when(APIUtil.hasPermission(null, APIConstants.Permissions.API_CREATE)).thenReturn(true);
Mockito.when(apimgtDAO.getDefaultVersion(identifier)).thenReturn("1.0.0");
Mockito.when(apimgtDAO.getPublishedDefaultVersion(identifier)).thenReturn("1.0.0");
// updateDefaultAPIInRegistry
String defaultAPIPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion() + APIConstants.API_RESOURCE_NAME;
Resource defaultAPISourceArtifact = Mockito.mock(Resource.class);
String defaultAPIUUID = "12640983600";
Mockito.when(defaultAPISourceArtifact.getUUID()).thenReturn(defaultAPIUUID);
Mockito.when(apiProvider.registry.get(defaultAPIPath)).thenReturn(defaultAPISourceArtifact);
GenericArtifact defaultAPIArtifact = Mockito.mock(GenericArtifact.class);
Mockito.when(artifactManager.getGenericArtifact(defaultAPIUUID)).thenReturn(defaultAPIArtifact);
Mockito.doNothing().when(artifactManager).updateGenericArtifact(defaultAPIArtifact);
TestUtils.mockAPIMConfiguration(APIConstants.API_GATEWAY_TYPE, APIConstants.API_GATEWAY_TYPE_SYNAPSE, -1234);
// updateApiArtifact
PowerMockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
Mockito.when(artifact.getId()).thenReturn("12640983654");
PowerMockito.when(GovernanceUtils.getArtifactPath(apiProvider.registry, "12640983654")).thenReturn(apiSourcePath);
// Mock Updating API
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
apiProvider.createAPI(api);
return null;
}
}).when(artifactManager).updateGenericArtifact(artifact);
APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
GatewayArtifactSynchronizerProperties synchronizerProperties = new GatewayArtifactSynchronizerProperties();
Mockito.when(config.getGatewayArtifactSynchronizerProperties()).thenReturn(synchronizerProperties);
PowerMockito.when(apiPersistenceInstance.getPublisherAPI(any(Organization.class), any(String.class))).thenReturn(publisherAPI);
Mockito.when(APIUtil.getTiers(APIConstants.TIER_RESOURCE_TYPE, "carbon.super")).thenReturn(tiers);
apiProvider.updateAPI(api, oldApi);
Assert.assertEquals(0, api.getEnvironments().size());
tiers.remove("Gold", tier);
tier = new Tier("Unlimited");
tiers.put("Unlimited", tier);
try {
apiProvider.updateAPI(api, oldApi);
} catch (APIManagementException ex) {
Assert.assertTrue(ex.getMessage().contains("Invalid x-throttling tier Gold found in api definition for " + "resource POST /add"));
}
}
use of org.wso2.carbon.apimgt.api.model.Tier in project carbon-apimgt by wso2.
the class AbstractAPIManagerTestCase method testAddSubscriber.
@Test
public void testAddSubscriber() throws APIManagementException, org.wso2.carbon.user.api.UserStoreException {
int tenantId = -1234;
AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(null, null, null, tenantManager, apiMgtDAO);
Mockito.when(tenantManager.getTenantId(Mockito.anyString())).thenThrow(UserStoreException.class).thenReturn(tenantId);
PowerMockito.mockStatic(APIUtil.class);
SortedMap<String, String> claimValues = new TreeMap<String, String>();
claimValues.put("admin@wso2.om", APIConstants.EMAIL_CLAIM);
PowerMockito.when(APIUtil.getClaims(API_PROVIDER, tenantId, DEFAULT_DIALECT_URI)).thenReturn(claimValues);
try {
abstractAPIManager.addSubscriber(API_PROVIDER, SAMPLE_RESOURCE_ID);
Assert.fail("User store exception not thrown for error scenario");
} catch (APIManagementException e) {
Assert.assertTrue(e.getMessage().contains("Error while adding the subscriber"));
}
Mockito.doThrow(APIManagementException.class).doNothing().when(apiMgtDAO).addSubscriber((Subscriber) Mockito.any(), Mockito.anyString());
try {
abstractAPIManager.addSubscriber(API_PROVIDER, SAMPLE_RESOURCE_ID);
Assert.fail("APIM exception not thrown for error scenario");
} catch (APIManagementException e) {
Assert.assertTrue(e.getMessage().contains("Error while adding the subscriber"));
}
PowerMockito.mockStatic(APIUtil.class);
PowerMockito.when(APIUtil.isEnabledUnlimitedTier()).thenReturn(true, false);
Mockito.doNothing().when(apiMgtDAO).addSubscriber((Subscriber) Mockito.any(), Mockito.anyString());
abstractAPIManager.addSubscriber(API_PROVIDER, SAMPLE_RESOURCE_ID);
List<Tier> tierValues = new ArrayList<Tier>();
tierValues.add(new Tier("Gold"));
tierValues.add(new Tier("Silver"));
Map<String, Tier> tierMap = new HashMap<String, Tier>();
tierMap.put("Gold", new Tier("Gold"));
tierMap.put("Silver", new Tier("Silver"));
PowerMockito.when(APIUtil.getTiers(Mockito.anyInt(), Mockito.anyString())).thenReturn(tierMap);
PowerMockito.when(APIUtil.sortTiers(Mockito.anySet())).thenReturn(tierValues);
abstractAPIManager.addSubscriber(API_PROVIDER, SAMPLE_RESOURCE_ID);
Mockito.verify(apiMgtDAO, Mockito.times(3)).addSubscriber((Subscriber) Mockito.any(), Mockito.anyString());
}
Aggregations