use of org.wso2.carbon.apimgt.api.model.OperationPolicyData in project carbon-apimgt by wso2.
the class OperationPoliciesApiServiceImpl method addCommonOperationPolicy.
/**
* Add a common operation policy that can be used by all the APIs
*
* @param policySpecFileInputStream Input stream of the common policy specification file
* @param policySpecFileDetail Common policy specification
* @param synapsePolicyDefinitionFileInputStream Input stream of the synapse policy definition file
* @param synapsePolicyDefinitionFileDetail Synapse definition of the operation policy
* @param ccPolicyDefinitionFileInputStream Input stream of the choreo connect policy definition file
* @param ccPolicyDefinitionFileDetail Choreo connect definition of the operation policy
* @param messageContext message context
* @return Added common operation policy DTO as response
*/
@Override
public Response addCommonOperationPolicy(InputStream policySpecFileInputStream, Attachment policySpecFileDetail, InputStream synapsePolicyDefinitionFileInputStream, Attachment synapsePolicyDefinitionFileDetail, InputStream ccPolicyDefinitionFileInputStream, Attachment ccPolicyDefinitionFileDetail, MessageContext messageContext) throws APIManagementException {
try {
OperationPolicyDefinition ccPolicyDefinition = null;
OperationPolicyDefinition synapseDefinition = null;
OperationPolicySpecification policySpecification;
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
if (policySpecFileInputStream != null) {
String jsonContent = "";
jsonContent = RestApiPublisherUtils.readInputStream(policySpecFileInputStream, policySpecFileDetail);
String fileName = policySpecFileDetail.getDataHandler().getName();
String fileContentType = URLConnection.guessContentTypeFromName(fileName);
if (org.apache.commons.lang3.StringUtils.isBlank(fileContentType)) {
fileContentType = policySpecFileDetail.getContentType().toString();
}
if (APIConstants.YAML_CONTENT_TYPE.equals(fileContentType)) {
jsonContent = CommonUtil.yamlToJson(jsonContent);
}
policySpecification = APIUtil.getValidatedOperationPolicySpecification(jsonContent);
OperationPolicyData operationPolicyData = new OperationPolicyData();
operationPolicyData.setOrganization(organization);
operationPolicyData.setSpecification(policySpecification);
if (synapsePolicyDefinitionFileInputStream != null) {
String synapsePolicyDefinition = RestApiPublisherUtils.readInputStream(synapsePolicyDefinitionFileInputStream, synapsePolicyDefinitionFileDetail);
synapseDefinition = new OperationPolicyDefinition();
synapseDefinition.setContent(synapsePolicyDefinition);
synapseDefinition.setGatewayType(OperationPolicyDefinition.GatewayType.Synapse);
synapseDefinition.setMd5Hash(APIUtil.getMd5OfOperationPolicyDefinition(synapseDefinition));
operationPolicyData.setSynapsePolicyDefinition(synapseDefinition);
}
if (ccPolicyDefinitionFileInputStream != null) {
String choreoConnectPolicyDefinition = RestApiPublisherUtils.readInputStream(ccPolicyDefinitionFileInputStream, ccPolicyDefinitionFileDetail);
ccPolicyDefinition = new OperationPolicyDefinition();
ccPolicyDefinition.setContent(choreoConnectPolicyDefinition);
ccPolicyDefinition.setGatewayType(OperationPolicyDefinition.GatewayType.ChoreoConnect);
ccPolicyDefinition.setMd5Hash(APIUtil.getMd5OfOperationPolicyDefinition(ccPolicyDefinition));
operationPolicyData.setCcPolicyDefinition(ccPolicyDefinition);
}
operationPolicyData.setMd5Hash(APIUtil.getMd5OfOperationPolicy(operationPolicyData));
OperationPolicyData existingPolicy = apiProvider.getCommonOperationPolicyByPolicyName(policySpecification.getName(), organization, false);
String policyID;
if (existingPolicy == null) {
policyID = apiProvider.addCommonOperationPolicy(operationPolicyData, organization);
if (log.isDebugEnabled()) {
log.debug("A common operation policy has been added with name " + policySpecification.getName());
}
} else {
throw new APIManagementException("Existing common operation policy found for the same name.");
}
operationPolicyData.setPolicyId(policyID);
OperationPolicyDataDTO createdPolicy = OperationPolicyMappingUtil.fromOperationPolicyDataToDTO(operationPolicyData);
URI createdPolicyUri = new URI(RestApiConstants.REST_API_PUBLISHER_VERSION + "/" + RestApiConstants.RESOURCE_PATH_OPERATION_POLICIES + "/" + policyID);
return Response.created(createdPolicyUri).entity(createdPolicy).build();
}
} catch (APIManagementException e) {
String errorMessage = "Error while adding a common operation policy." + e.getMessage();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (Exception e) {
RestApiUtil.handleInternalServerError("An Error has occurred while adding common operation policy", e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.OperationPolicyData in project carbon-apimgt by wso2.
the class RestApiPublisherUtils method exportOperationPolicyData.
public static File exportOperationPolicyData(OperationPolicyData policyData) throws APIManagementException {
File exportFolder = null;
try {
exportFolder = CommonUtil.createTempDirectoryFromName(policyData.getSpecification().getName() + "_" + policyData.getSpecification().getVersion());
String exportAPIBasePath = exportFolder.toString();
String archivePath = exportAPIBasePath.concat(File.separator + policyData.getSpecification().getName());
CommonUtil.createDirectory(archivePath);
String policyName = archivePath + File.separator + policyData.getSpecification().getName();
if (policyData.getSpecification() != null) {
CommonUtil.writeDtoToFile(policyName, ExportFormat.YAML, ImportExportConstants.TYPE_POLICY_SPECIFICATION, policyData.getSpecification());
}
if (policyData.getSynapsePolicyDefinition() != null) {
CommonUtil.writeFile(policyName + APIConstants.SYNAPSE_POLICY_DEFINITION_EXTENSION, policyData.getSynapsePolicyDefinition().getContent());
}
if (policyData.getCcPolicyDefinition() != null) {
CommonUtil.writeFile(policyName + APIConstants.CC_POLICY_DEFINITION_EXTENSION, policyData.getCcPolicyDefinition().getContent());
}
CommonUtil.archiveDirectory(exportAPIBasePath);
FileUtils.deleteQuietly(new File(exportAPIBasePath));
return new File(exportAPIBasePath + APIConstants.ZIP_FILE_EXTENSION);
} catch (APIImportExportException | IOException e) {
throw new APIManagementException("Error while exporting operation policy", e);
}
}
use of org.wso2.carbon.apimgt.api.model.OperationPolicyData in project carbon-apimgt by wso2.
the class ExportUtils method addOperationPoliciesToArchive.
/**
* Retrieve the operation policies and store those in the archive directory.
*
* @param archivePath File path to export the endpoint certificates
* @param apiID UUID of the API/ API Product
* @param exportFormat Export format of file
* @param apiProvider API Provider
* @throws APIImportExportException If an error occurs while exporting operation policies
*/
public static void addOperationPoliciesToArchive(String archivePath, String apiID, String tenantDomain, ExportFormat exportFormat, APIProvider apiProvider, API api) throws APIManagementException {
try {
CommonUtil.createDirectory(archivePath + File.separator + ImportExportConstants.POLICIES_DIRECTORY);
Set<URITemplate> uriTemplates = api.getUriTemplates();
for (URITemplate uriTemplate : uriTemplates) {
List<OperationPolicy> operationPolicies = uriTemplate.getOperationPolicies();
if (operationPolicies != null && !operationPolicies.isEmpty()) {
for (OperationPolicy policy : operationPolicies) {
OperationPolicyData policyData = apiProvider.getAPISpecificOperationPolicyByPolicyId(policy.getPolicyId(), apiID, tenantDomain, true);
if (policyData != null) {
String policyName = archivePath + File.separator + ImportExportConstants.POLICIES_DIRECTORY + File.separator + policyData.getSpecification().getName();
// Policy specification and definition will have the same name
if (policyData.getSpecification() != null) {
CommonUtil.writeDtoToFile(policyName, exportFormat, ImportExportConstants.TYPE_POLICY_SPECIFICATION, policyData.getSpecification());
}
if (policyData.getSynapsePolicyDefinition() != null) {
CommonUtil.writeFile(policyName + APIConstants.SYNAPSE_POLICY_DEFINITION_EXTENSION, policyData.getSynapsePolicyDefinition().getContent());
}
if (policyData.getCcPolicyDefinition() != null) {
CommonUtil.writeFile(policyName + APIConstants.CC_POLICY_DEFINITION_EXTENSION, policyData.getCcPolicyDefinition().getContent());
}
}
}
}
}
} catch (IOException | APIImportExportException e) {
throw new APIManagementException("Error while adding operation policy details for API: " + apiID, e);
}
}
use of org.wso2.carbon.apimgt.api.model.OperationPolicyData 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.OperationPolicyData in project carbon-apimgt by wso2.
the class ApiMgtDAO method getCommonOperationPolicyByPolicyName.
private OperationPolicyData getCommonOperationPolicyByPolicyName(Connection connection, String policyName, String tenantDomain, boolean isWithPolicyDefinition) throws SQLException {
String dbQuery = SQLConstants.OperationPolicyConstants.GET_COMMON_OPERATION_POLICY_FROM_POLICY_NAME;
PreparedStatement statement = connection.prepareStatement(dbQuery);
statement.setString(1, policyName);
statement.setString(2, tenantDomain);
ResultSet rs = statement.executeQuery();
OperationPolicyData policyData = null;
if (rs.next()) {
policyData = new OperationPolicyData();
policyData.setOrganization(tenantDomain);
policyData.setPolicyId(rs.getString("POLICY_UUID"));
policyData.setMd5Hash(rs.getString("POLICY_MD5"));
policyData.setSpecification(populatePolicySpecificationFromRS(rs));
}
rs.close();
statement.close();
if (isWithPolicyDefinition && policyData != null) {
if (isWithPolicyDefinition && policyData != null) {
populatePolicyDefinitions(connection, policyData.getPolicyId(), policyData);
}
}
return policyData;
}
Aggregations