use of org.wso2.carbon.apimgt.api.model.APIProductResource in project carbon-apimgt by wso2.
the class ApiMgtDAO method addAPIProductResourceMappings.
/**
* Add api product url mappings to DB
* - url templeates to product mappings (resource bundling) - AM_API_PRODUCT_MAPPING
*
* @param productResources
* @param organization
* @param connection
* @throws APIManagementException
*/
public void addAPIProductResourceMappings(List<APIProductResource> productResources, String organization, Connection connection) throws APIManagementException {
String addProductResourceMappingSql = SQLConstants.ADD_PRODUCT_RESOURCE_MAPPING_SQL;
boolean isNewConnection = false;
try {
if (connection == null) {
connection = APIMgtDBUtil.getConnection();
isNewConnection = true;
}
Set<String> usedClonedPolicies = new HashSet<>();
Map<String, String> clonedPoliciesMap = new HashMap<>();
// add the duplicate resources in each API in the API product.
for (APIProductResource apiProductResource : productResources) {
APIProductIdentifier productIdentifier = apiProductResource.getProductIdentifier();
String uuid;
if (productIdentifier.getUUID() != null) {
uuid = productIdentifier.getUUID();
} else {
uuid = getUUIDFromIdentifier(productIdentifier, organization, connection);
}
int productId = getAPIID(uuid, connection);
int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(productIdentifier.getProviderName()));
String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
URITemplate uriTemplateOriginal = apiProductResource.getUriTemplate();
int urlMappingId = uriTemplateOriginal.getId();
// Adding to AM_API_URL_MAPPING table
PreparedStatement getURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_URL_MAPPINGS_WITH_SCOPE_BY_URL_MAPPING_ID);
getURLMappingsStatement.setInt(1, urlMappingId);
List<URITemplate> urlMappingList = new ArrayList<>();
try (ResultSet rs = getURLMappingsStatement.executeQuery()) {
while (rs.next()) {
URITemplate uriTemplate = new URITemplate();
uriTemplate.setHTTPVerb(rs.getString("HTTP_METHOD"));
uriTemplate.setAuthType(rs.getString("AUTH_SCHEME"));
uriTemplate.setUriTemplate(rs.getString("URL_PATTERN"));
uriTemplate.setThrottlingTier(rs.getString("THROTTLING_TIER"));
String script = null;
InputStream mediationScriptBlob = rs.getBinaryStream("MEDIATION_SCRIPT");
if (mediationScriptBlob != null) {
script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
}
uriTemplate.setMediationScript(script);
if (!StringUtils.isEmpty(rs.getString("SCOPE_NAME"))) {
Scope scope = new Scope();
scope.setKey(rs.getString("SCOPE_NAME"));
uriTemplate.setScope(scope);
}
if (rs.getInt("API_ID") != 0) {
// Adding api id to uri template id just to store value
uriTemplate.setId(rs.getInt("API_ID"));
}
List<OperationPolicy> operationPolicies = getOperationPoliciesOfURITemplate(urlMappingId);
uriTemplate.setOperationPolicies(operationPolicies);
urlMappingList.add(uriTemplate);
}
}
Map<String, URITemplate> uriTemplateMap = new HashMap<>();
for (URITemplate urlMapping : urlMappingList) {
if (urlMapping.getScope() != null) {
URITemplate urlMappingNew = urlMapping;
URITemplate urlMappingExisting = uriTemplateMap.get(urlMapping.getUriTemplate() + urlMapping.getHTTPVerb());
if (urlMappingExisting != null && urlMappingExisting.getScopes() != null) {
if (!urlMappingExisting.getScopes().contains(urlMapping.getScope())) {
urlMappingExisting.setScopes(urlMapping.getScope());
uriTemplateMap.put(urlMappingExisting.getUriTemplate() + urlMappingExisting.getHTTPVerb(), urlMappingExisting);
}
} else {
urlMappingNew.setScopes(urlMapping.getScope());
uriTemplateMap.put(urlMappingNew.getUriTemplate() + urlMappingNew.getHTTPVerb(), urlMappingNew);
}
} else if (urlMapping.getId() != 0) {
URITemplate urlMappingExisting = uriTemplateMap.get(urlMapping.getUriTemplate() + urlMapping.getHTTPVerb());
if (urlMappingExisting == null) {
uriTemplateMap.put(urlMapping.getUriTemplate() + urlMapping.getHTTPVerb(), urlMapping);
}
} else {
uriTemplateMap.put(urlMapping.getUriTemplate() + urlMapping.getHTTPVerb(), urlMapping);
}
}
PreparedStatement insertURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_URL_MAPPINGS);
for (URITemplate urlMapping : uriTemplateMap.values()) {
insertURLMappingsStatement.setInt(1, urlMapping.getId());
insertURLMappingsStatement.setString(2, urlMapping.getHTTPVerb());
insertURLMappingsStatement.setString(3, urlMapping.getAuthType());
insertURLMappingsStatement.setString(4, urlMapping.getUriTemplate());
insertURLMappingsStatement.setString(5, urlMapping.getThrottlingTier());
insertURLMappingsStatement.setString(6, String.valueOf(productId));
insertURLMappingsStatement.addBatch();
}
insertURLMappingsStatement.executeBatch();
// Add to AM_API_RESOURCE_SCOPE_MAPPING table and to AM_API_PRODUCT_MAPPING
PreparedStatement getRevisionedURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_URL_MAPPINGS_ID);
PreparedStatement insertScopeResourceMappingStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_SCOPE_RESOURCE_MAPPING);
PreparedStatement insertProductResourceMappingStatement = connection.prepareStatement(addProductResourceMappingSql);
String dbProductName = connection.getMetaData().getDatabaseProductName();
PreparedStatement insertOperationPolicyMappingStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.ADD_API_OPERATION_POLICY_MAPPING, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "OPERATION_POLICY_MAPPING_ID") });
for (URITemplate urlMapping : uriTemplateMap.values()) {
getRevisionedURLMappingsStatement.setInt(1, urlMapping.getId());
getRevisionedURLMappingsStatement.setString(2, urlMapping.getHTTPVerb());
getRevisionedURLMappingsStatement.setString(3, urlMapping.getAuthType());
getRevisionedURLMappingsStatement.setString(4, urlMapping.getUriTemplate());
getRevisionedURLMappingsStatement.setString(5, urlMapping.getThrottlingTier());
getRevisionedURLMappingsStatement.setString(6, String.valueOf(productId));
if (!urlMapping.getScopes().isEmpty()) {
try (ResultSet rs = getRevisionedURLMappingsStatement.executeQuery()) {
while (rs.next()) {
for (Scope scope : urlMapping.getScopes()) {
insertScopeResourceMappingStatement.setString(1, scope.getKey());
insertScopeResourceMappingStatement.setInt(2, rs.getInt(1));
insertScopeResourceMappingStatement.setInt(3, tenantId);
insertScopeResourceMappingStatement.addBatch();
}
}
}
}
try (ResultSet rs = getRevisionedURLMappingsStatement.executeQuery()) {
while (rs.next()) {
insertProductResourceMappingStatement.setInt(1, productId);
insertProductResourceMappingStatement.setInt(2, rs.getInt(1));
insertProductResourceMappingStatement.setString(3, "Current API");
insertProductResourceMappingStatement.addBatch();
}
}
try (ResultSet rs = getRevisionedURLMappingsStatement.executeQuery()) {
while (rs.next()) {
for (OperationPolicy policy : urlMapping.getOperationPolicies()) {
if (!clonedPoliciesMap.keySet().contains(policy.getPolicyId())) {
OperationPolicyData existingPolicy = getAPISpecificOperationPolicyByPolicyID(policy.getPolicyId(), uuid, tenantDomain, false);
String clonedPolicyId = policy.getPolicyId();
if (existingPolicy != null) {
if (existingPolicy.isClonedPolicy()) {
usedClonedPolicies.add(clonedPolicyId);
}
} else {
// Even though the policy ID attached is not in the API specific policy list for the product uuid,
// it can be from the dependent API and we need to verify that it has not been previously cloned
// for the product before cloning again.
clonedPolicyId = getClonedPolicyIdForCommonPolicyId(connection, policy.getPolicyId(), uuid);
if (clonedPolicyId == null) {
clonedPolicyId = cloneOperationPolicy(connection, policy.getPolicyId(), uuid, null);
}
usedClonedPolicies.add(clonedPolicyId);
// usedClonedPolicies set will not contain used API specific policies that are not cloned.
// TODO: discuss whether we need to clone API specific policies as well
}
// Updated policies map will record the updated policy ID for the used policy ID.
// If the policy has been cloned to the API specific policy list, we need to use the
// updated policy Id.
clonedPoliciesMap.put(policy.getPolicyId(), clonedPolicyId);
}
Gson gson = new Gson();
String paramJSON = gson.toJson(policy.getParameters());
insertOperationPolicyMappingStatement.setInt(1, rs.getInt(1));
insertOperationPolicyMappingStatement.setString(2, clonedPoliciesMap.get(policy.getPolicyId()));
insertOperationPolicyMappingStatement.setString(3, policy.getDirection());
insertOperationPolicyMappingStatement.setString(4, paramJSON);
insertOperationPolicyMappingStatement.setInt(5, policy.getOrder());
insertOperationPolicyMappingStatement.executeUpdate();
}
}
}
}
insertScopeResourceMappingStatement.executeBatch();
insertProductResourceMappingStatement.executeBatch();
}
} catch (SQLException e) {
handleException("Error while adding API product Resources", e);
} finally {
if (isNewConnection) {
APIMgtDBUtil.closeAllConnections(null, connection, null);
}
}
}
use of org.wso2.carbon.apimgt.api.model.APIProductResource in project carbon-apimgt by wso2.
the class ApiMgtDAO method getAPIProductResourceMappings.
/**
* get resource mapping of the api product
* TODO://Get resource scopes from AM_API_RESOURCE_SCOPE table and retrieve scope meta data and bindings from KM.
*
* @param productIdentifier api product identifier
* @throws APIManagementException
*/
public List<APIProductResource> getAPIProductResourceMappings(APIProductIdentifier productIdentifier) throws APIManagementException {
int productId = getAPIProductId(productIdentifier);
List<APIProductResource> productResourceList = new ArrayList<>();
try (Connection connection = APIMgtDBUtil.getConnection()) {
if (checkAPIUUIDIsARevisionUUID(productIdentifier.getUUID()) == null) {
String sql = SQLConstants.GET_RESOURCES_OF_PRODUCT;
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setInt(1, productId);
ps.setString(2, String.valueOf(productId));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
APIProductResource resource = new APIProductResource();
APIIdentifier apiId = new APIIdentifier(rs.getString("API_PROVIDER"), rs.getString("API_NAME"), rs.getString("API_VERSION"));
apiId.setUuid(rs.getString("API_UUID"));
resource.setProductIdentifier(productIdentifier);
resource.setApiIdentifier(apiId);
resource.setApiName(rs.getString("API_NAME"));
URITemplate uriTemplate = new URITemplate();
uriTemplate.setUriTemplate(rs.getString("URL_PATTERN"));
uriTemplate.setResourceURI(rs.getString("URL_PATTERN"));
uriTemplate.setHTTPVerb(rs.getString("HTTP_METHOD"));
int uriTemplateId = rs.getInt("URL_MAPPING_ID");
uriTemplate.setId(uriTemplateId);
uriTemplate.setAuthType(rs.getString("AUTH_SCHEME"));
uriTemplate.setThrottlingTier(rs.getString("THROTTLING_TIER"));
try (PreparedStatement scopesStatement = connection.prepareStatement(SQLConstants.GET_SCOPE_KEYS_BY_URL_MAPPING_ID)) {
scopesStatement.setInt(1, uriTemplateId);
try (ResultSet scopesResult = scopesStatement.executeQuery()) {
while (scopesResult.next()) {
Scope scope = new Scope();
scope.setKey(scopesResult.getString("SCOPE_NAME"));
uriTemplate.setScopes(scope);
}
}
}
try (PreparedStatement policiesStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.GET_OPERATION_POLICIES_BY_URI_TEMPLATE_ID)) {
policiesStatement.setInt(1, uriTemplateId);
try (ResultSet policiesResult = policiesStatement.executeQuery()) {
List<OperationPolicy> operationPolicies = new ArrayList<>();
while (policiesResult.next()) {
OperationPolicy policy = populateOperationPolicyWithRS(policiesResult);
operationPolicies.add(policy);
}
uriTemplate.setOperationPolicies(operationPolicies);
}
}
resource.setUriTemplate(uriTemplate);
productResourceList.add(resource);
}
}
}
} else {
String sql = SQLConstants.GET_RESOURCES_OF_PRODUCT_REVISION;
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setInt(1, productId);
ps.setString(2, productIdentifier.getUUID());
ps.setString(3, productIdentifier.getUUID());
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
APIProductResource resource = new APIProductResource();
APIIdentifier apiId = new APIIdentifier(rs.getString("API_PROVIDER"), rs.getString("API_NAME"), rs.getString("API_VERSION"));
apiId.setUuid(rs.getString("API_UUID"));
resource.setProductIdentifier(productIdentifier);
resource.setApiIdentifier(apiId);
resource.setApiName(rs.getString("API_NAME"));
URITemplate uriTemplate = new URITemplate();
uriTemplate.setUriTemplate(rs.getString("URL_PATTERN"));
uriTemplate.setResourceURI(rs.getString("URL_PATTERN"));
uriTemplate.setHTTPVerb(rs.getString("HTTP_METHOD"));
int uriTemplateId = rs.getInt("URL_MAPPING_ID");
uriTemplate.setId(uriTemplateId);
uriTemplate.setAuthType(rs.getString("AUTH_SCHEME"));
uriTemplate.setThrottlingTier(rs.getString("THROTTLING_TIER"));
try (PreparedStatement scopesStatement = connection.prepareStatement(SQLConstants.GET_SCOPE_KEYS_BY_URL_MAPPING_ID)) {
scopesStatement.setInt(1, uriTemplateId);
try (ResultSet scopesResult = scopesStatement.executeQuery()) {
while (scopesResult.next()) {
Scope scope = new Scope();
scope.setKey(scopesResult.getString("SCOPE_NAME"));
uriTemplate.setScopes(scope);
}
}
}
try (PreparedStatement policiesStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.GET_OPERATION_POLICIES_BY_URI_TEMPLATE_ID)) {
policiesStatement.setInt(1, uriTemplateId);
try (ResultSet policiesResult = policiesStatement.executeQuery()) {
List<OperationPolicy> operationPolicies = new ArrayList<>();
while (policiesResult.next()) {
OperationPolicy policy = populateOperationPolicyWithRS(policiesResult);
operationPolicies.add(policy);
}
uriTemplate.setOperationPolicies(operationPolicies);
}
}
resource.setUriTemplate(uriTemplate);
productResourceList.add(resource);
}
}
}
}
} catch (SQLException e) {
handleException("Failed to get product resources of api product : " + productIdentifier, e);
}
return productResourceList;
}
use of org.wso2.carbon.apimgt.api.model.APIProductResource in project carbon-apimgt by wso2.
the class APIProviderImpl method updateAPIProduct.
@Override
public Map<API, List<APIProductResource>> updateAPIProduct(APIProduct product) throws APIManagementException, FaultGatewaysException {
Map<API, List<APIProductResource>> apiToProductResourceMapping = new HashMap<>();
// validate resources and set api identifiers and resource ids to product
List<APIProductResource> resources = product.getProductResources();
for (APIProductResource apiProductResource : resources) {
API api;
APIProductIdentifier productIdentifier = apiProductResource.getProductIdentifier();
String apiUUID;
if (productIdentifier != null) {
APIIdentifier productAPIIdentifier = apiProductResource.getApiIdentifier();
String emailReplacedAPIProviderName = APIUtil.replaceEmailDomain(productAPIIdentifier.getProviderName());
APIIdentifier emailReplacedAPIIdentifier = new APIIdentifier(emailReplacedAPIProviderName, productAPIIdentifier.getApiName(), productAPIIdentifier.getVersion());
apiUUID = apiMgtDAO.getUUIDFromIdentifier(emailReplacedAPIIdentifier, product.getOrganization());
api = getAPIbyUUID(apiUUID, tenantDomain);
} else {
apiUUID = apiProductResource.getApiId();
api = getAPIbyUUID(apiUUID, tenantDomain);
}
if (api.getSwaggerDefinition() != null) {
api.setSwaggerDefinition(getOpenAPIDefinition(apiUUID, tenantDomain));
}
if (!apiToProductResourceMapping.containsKey(api)) {
apiToProductResourceMapping.put(api, new ArrayList<>());
}
List<APIProductResource> apiProductResources = apiToProductResourceMapping.get(api);
apiProductResources.add(apiProductResource);
// if API does not exist, getLightweightAPIByUUID() method throws exception. so no need to handle NULL
apiProductResource.setApiIdentifier(api.getId());
apiProductResource.setProductIdentifier(product.getId());
if (api.isAdvertiseOnly()) {
apiProductResource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
} else {
apiProductResource.setEndpointConfig(api.getEndpointConfig());
}
apiProductResource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
URITemplate uriTemplate = apiProductResource.getUriTemplate();
Map<String, URITemplate> templateMap = apiMgtDAO.getURITemplatesForAPI(api);
if (uriTemplate == null) {
// TODO handle if no resource is defined. either throw an error or add all the resources of that API
// to the product
} else {
String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
if (templateMap.containsKey(key)) {
// Since the template ID is not set from the request, we manually set it.
uriTemplate.setId(templateMap.get(key).getId());
} else {
throw new APIManagementException("API with id " + apiProductResource.getApiId() + " does not have a resource " + uriTemplate.getUriTemplate() + " with http method " + uriTemplate.getHTTPVerb());
}
}
}
APIProduct oldApi = getAPIProductbyUUID(product.getUuid(), CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
Gson gson = new Gson();
Map<String, String> oldMonetizationProperties = gson.fromJson(oldApi.getMonetizationProperties().toString(), HashMap.class);
if (oldMonetizationProperties != null && !oldMonetizationProperties.isEmpty()) {
Map<String, String> newMonetizationProperties = gson.fromJson(product.getMonetizationProperties().toString(), HashMap.class);
if (newMonetizationProperties != null) {
for (Map.Entry<String, String> entry : oldMonetizationProperties.entrySet()) {
String newValue = newMonetizationProperties.get(entry.getKey());
if (StringUtils.isAllBlank(newValue)) {
newMonetizationProperties.put(entry.getKey(), entry.getValue());
}
}
JSONParser parser = new JSONParser();
try {
JSONObject jsonObj = (JSONObject) parser.parse(gson.toJson(newMonetizationProperties));
product.setMonetizationProperties(jsonObj);
} catch (ParseException e) {
throw new APIManagementException("Error when parsing monetization properties ", e);
}
}
}
invalidateResourceCache(product.getContext(), product.getId().getVersion(), Collections.EMPTY_SET);
// todo : check whether permissions need to be updated and pass it along
updateApiProductArtifact(product, true, true);
apiMgtDAO.updateAPIProduct(product, userNameWithoutChange);
int productId = apiMgtDAO.getAPIProductId(product.getId());
APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_UPDATE.name(), tenantId, tenantDomain, product.getId().getName(), productId, product.getId().getUUID(), product.getId().getVersion(), product.getType(), product.getContext(), product.getId().getProviderName(), APIConstants.LC_PUBLISH_LC_STATE);
APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
return apiToProductResourceMapping;
}
use of org.wso2.carbon.apimgt.api.model.APIProductResource in project carbon-apimgt by wso2.
the class APIProviderImpl method getAssociatedAPIs.
private Set<API> getAssociatedAPIs(APIProduct apiProduct) throws APIManagementException {
List<APIProductResource> productResources = apiProduct.getProductResources();
Set<API> apis = new HashSet<>();
for (APIProductResource productResource : productResources) {
API api = getAPIbyUUID(productResource.getApiId(), CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
apis.add(api);
}
return apis;
}
use of org.wso2.carbon.apimgt.api.model.APIProductResource in project carbon-apimgt by wso2.
the class APIProviderImpl method updateProductResourceMappings.
public void updateProductResourceMappings(API api, String organization, List<APIProductResource> productResources) throws APIManagementException {
// get uri templates of API again
Map<String, URITemplate> apiResources = apiMgtDAO.getURITemplatesForAPI(api);
for (APIProductResource productResource : productResources) {
URITemplate uriTemplate = productResource.getUriTemplate();
String productResourceKey = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
// set new uri template ID to the product resource
int updatedURITemplateId = apiResources.get(productResourceKey).getId();
uriTemplate.setId(updatedURITemplateId);
}
apiMgtDAO.addAPIProductResourceMappings(productResources, organization, null);
}
Aggregations