use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.
the class APIProviderImplTest method testGetAPILifeCycleData.
@Test
public void testGetAPILifeCycleData() throws Exception {
APIIdentifier identifier = new APIIdentifier("admin-AT-carbon.super", "API1", "1.0.0");
String path = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();
APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
Resource apiSourceArtifact = Mockito.mock(Resource.class);
Mockito.when(apiSourceArtifact.getUUID()).thenReturn("12640983654");
PowerMockito.when(APIUtil.getAPIPath(identifier)).thenReturn(path);
PowerMockito.when(apiProvider.registry.get(path)).thenReturn(apiSourceArtifact);
Mockito.when(artifactManager.getGenericArtifact(apiSourceArtifact.getUUID())).thenReturn(artifact);
Mockito.when(artifact.getLifecycleState()).thenReturn("Created");
LifecycleBean bean = getLCBean();
Mockito.when(LifecycleBeanPopulator.getLifecycleBean(path, (UserRegistry) apiProvider.registry, apiProvider.configRegistry)).thenReturn(bean);
Map<String, Object> lcData = apiProvider.getAPILifeCycleData(identifier);
List checkListItems = (List) lcData.get(APIConstants.LC_CHECK_ITEMS);
Assert.assertEquals(2, checkListItems.size());
if (checkListItems.get(0) instanceof CheckListItem) {
CheckListItem checkListItem = (CheckListItem) checkListItems.get(0);
Assert.assertTrue((APIConstants.RESUBSCRIBE_CHECK_LIST_ITEM).equals(checkListItem.getName()) || (APIConstants.DEPRECATE_CHECK_LIST_ITEM).equals(checkListItem.getName()));
if ((APIConstants.RESUBSCRIBE_CHECK_LIST_ITEM).equals(checkListItem.getName())) {
Assert.assertEquals("1", checkListItem.getOrder());
} else {
Assert.assertEquals("0", checkListItem.getOrder());
}
Assert.assertEquals("Created", checkListItem.getLifeCycleStatus());
}
if (checkListItems.get(1) instanceof CheckListItem) {
CheckListItem checkListItem = (CheckListItem) checkListItems.get(1);
Assert.assertTrue((APIConstants.RESUBSCRIBE_CHECK_LIST_ITEM).equals(checkListItem.getName()) || (APIConstants.DEPRECATE_CHECK_LIST_ITEM).equals(checkListItem.getName()));
if ((APIConstants.RESUBSCRIBE_CHECK_LIST_ITEM).equals(checkListItem.getName())) {
Assert.assertEquals("1", checkListItem.getOrder());
} else {
Assert.assertEquals("0", checkListItem.getOrder());
}
Assert.assertEquals("Created", checkListItem.getLifeCycleStatus());
}
}
use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.
the class APIProviderImplTest method testAddFileToDocumentation.
/**
* This method tests adding file to documentation method.
* @throws Exception
*
* @throws GovernanceException Governance Exception.
*/
@Test
public void testAddFileToDocumentation() throws Exception {
String apiUUID = "xxxxxxxx";
String docUUID = "yyyyyyyy";
APIIdentifier identifier = new APIIdentifier("admin-AT-carbon.super", "API1", "1.0.0");
Set<String> environments = new HashSet<String>();
Set<URITemplate> uriTemplates = 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);
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(uriTemplates);
api.setOrganization("carbon.super");
List<Documentation> documentationList = getDocumentationList();
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(APIUtil.getTiers(APIConstants.TIER_RESOURCE_TYPE, "carbon.super")).thenReturn(tiers);
Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
Mockito.when(APIUtil.createAPIArtifactContent(artifact, api)).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(api);
String fileName = "test.txt";
String contentType = "application/force-download";
Documentation doc = new Documentation(DocumentationType.HOWTO, fileName);
doc.setSourceType(DocumentSourceType.FILE);
PowerMockito.when(APIUtil.getDocumentationFilePath(api.getId(), fileName)).thenReturn("filePath");
InputStream inputStream = Mockito.mock(InputStream.class);
// apiProvider.addFileToDocumentation(api.getId(), doc, fileName, inputStream, contentType);
DocumentationContent content = new DocumentationContent();
ResourceFile resourceFile = new ResourceFile(inputStream, contentType);
content.setResourceFile(resourceFile);
apiProvider.addDocumentationContent(apiUUID, docUUID, "carbon.super", content);
}
use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.
the class ApiMgtDAO method updateAPIProduct.
public void updateAPIProduct(APIProduct product, String username) throws APIManagementException {
Connection conn = null;
PreparedStatement ps = null;
if (log.isDebugEnabled()) {
log.debug("updateAPIProduct() : product- " + product.toString());
}
try {
conn = APIMgtDBUtil.getConnection();
conn.setAutoCommit(false);
String query = SQLConstants.UPDATE_PRODUCT_SQL;
ps = conn.prepareStatement(query);
ps.setString(1, product.getProductLevelPolicy());
ps.setString(2, username);
ps.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
ps.setString(4, product.getGatewayVendor());
APIProductIdentifier identifier = product.getId();
ps.setString(5, identifier.getName());
ps.setString(6, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
ps.setString(7, identifier.getVersion());
ps.executeUpdate();
int productId = getAPIID(product.getUuid(), conn);
updateAPIProductResourceMappings(product, productId, conn);
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 API Product: " + e.getMessage(), e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, null);
}
}
use of org.wso2.carbon.apimgt.api.model.Identifier 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.Identifier in project carbon-apimgt by wso2.
the class ApiMgtDAO method isApplicationExist.
/**
* Check whether given application name is available under current subscriber or group
*
* @param appName application name
* @param username subscriber
* @param groupId group of the subscriber
* @param organization identifier of the organization
* @return true if application is available for the subscriber
* @throws APIManagementException if failed to get applications for given subscriber
*/
public boolean isApplicationExist(String appName, String username, String groupId, String organization) throws APIManagementException {
if (username == null) {
return false;
}
Subscriber subscriber = getSubscriber(username);
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
int appId = 0;
String sqlQuery = SQLConstants.GET_APPLICATION_ID_PREFIX;
String whereClauseWithGroupId = " AND (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)" + " AND SUB.USER_ID = ?))";
String whereClauseWithGroupIdCaseInsensitive = " AND (APP.GROUP_ID = ? " + "OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL) AND LOWER(SUB.USER_ID) = LOWER(?)))";
String whereClauseWithMultiGroupId = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM " + "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR ( SUB.USER_ID = ? ) " + "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_ID = ?)))";
String whereClauseWithMultiGroupIdCaseInsensitive = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID " + "FROM AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) " + "OR (LOWER(SUB.USER_ID) = LOWER(?))" + "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_ID = ?)))";
String whereClause = " AND SUB.USER_ID = ? ";
String whereClauseCaseInsensitive = " AND LOWER(SUB.USER_ID) = LOWER(?) ";
try {
connection = APIMgtDBUtil.getConnection();
if (!StringUtils.isEmpty(groupId)) {
if (multiGroupAppSharingEnabled) {
if (forceCaseInsensitiveComparisons) {
sqlQuery += whereClauseWithMultiGroupIdCaseInsensitive;
} else {
sqlQuery += whereClauseWithMultiGroupId;
}
String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
String[] grpIdArray = groupId.split(",");
int noOfParams = grpIdArray.length;
preparedStatement = fillQueryParams(connection, sqlQuery, grpIdArray, 3);
preparedStatement.setString(1, appName);
preparedStatement.setString(2, organization);
int paramIndex = noOfParams + 2;
preparedStatement.setString(++paramIndex, tenantDomain);
preparedStatement.setString(++paramIndex, subscriber.getName());
preparedStatement.setString(++paramIndex, tenantDomain + '/' + groupId);
} else {
if (forceCaseInsensitiveComparisons) {
sqlQuery += whereClauseWithGroupIdCaseInsensitive;
} else {
sqlQuery += whereClauseWithGroupId;
}
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setString(1, appName);
preparedStatement.setString(2, organization);
preparedStatement.setString(3, groupId);
preparedStatement.setString(4, subscriber.getName());
}
} else {
if (forceCaseInsensitiveComparisons) {
sqlQuery += whereClauseCaseInsensitive;
} else {
sqlQuery += whereClause;
}
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setString(1, appName);
preparedStatement.setString(2, organization);
preparedStatement.setString(3, subscriber.getName());
}
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
appId = resultSet.getInt("APPLICATION_ID");
}
if (appId > 0) {
return true;
}
} catch (SQLException e) {
handleException("Error while getting the id of " + appName + " from the persistence store.", e);
} finally {
APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
}
return false;
}
Aggregations