use of org.wso2.carbon.apimgt.api.model.OperationPolicyData in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method getOperationPolicyForAPIByPolicyId.
/**
* Get the API specific operation policy specification by providing the policy ID
*
* @param apiId API UUID
* @param operationPolicyId UUID of the operation policy
* @param messageContext message context
* @return Operation policy DTO as response
*/
@Override
public Response getOperationPolicyForAPIByPolicyId(String apiId, String operationPolicyId, MessageContext messageContext) {
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
// validate whether api exists or not
validateAPIExistence(apiId);
OperationPolicyData existingPolicy = apiProvider.getAPISpecificOperationPolicyByPolicyId(operationPolicyId, apiId, organization, false);
if (existingPolicy != null) {
OperationPolicyDataDTO policyDataDTO = OperationPolicyMappingUtil.fromOperationPolicyDataToDTO(existingPolicy);
return Response.ok().entity(policyDataDTO).build();
} else {
throw new APIMgtResourceNotFoundException("Couldn't retrieve an existing operation policy with ID: " + operationPolicyId + " for API " + apiId, ExceptionCodes.from(ExceptionCodes.OPERATION_POLICY_NOT_FOUND, operationPolicyId));
}
} catch (APIManagementException e) {
if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PATH_OPERATION_POLICIES, operationPolicyId, e, log);
} else {
String errorMessage = "Error while getting an API specific operation policy with ID :" + operationPolicyId + " for API " + apiId + " " + e.getMessage();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
} catch (Exception e) {
RestApiUtil.handleInternalServerError("An Error has occurred while getting the operation policy with ID " + operationPolicyId + "operation policy for API " + apiId, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.OperationPolicyData in project carbon-apimgt by wso2.
the class ImportUtils method validateOperationPolicies.
public static Set<URITemplate> validateOperationPolicies(API api, APIProvider provider, String extractedFolderPath, Map<String, List<OperationPolicy>> extractedPoliciesMap, String tenantDomain) {
String policyDirectory = extractedFolderPath + File.separator + ImportExportConstants.POLICIES_DIRECTORY;
Set<URITemplate> uriTemplates = api.getUriTemplates();
for (URITemplate uriTemplate : uriTemplates) {
String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
if (extractedPoliciesMap.containsKey(key)) {
List<OperationPolicy> operationPolicies = extractedPoliciesMap.get(key);
List<OperationPolicy> validatedOperationPolicies = new ArrayList<>();
if (operationPolicies != null && !operationPolicies.isEmpty()) {
for (OperationPolicy policy : operationPolicies) {
try {
OperationPolicySpecification policySpec = getOperationPolicySpecificationFromFile(policyDirectory, policy.getPolicyName());
OperationPolicyData operationPolicyData = new OperationPolicyData();
operationPolicyData.setSpecification(policySpec);
operationPolicyData.setOrganization(tenantDomain);
operationPolicyData.setApiUUID(api.getUuid());
OperationPolicyDefinition synapseDefinition = APIUtil.getOperationPolicyDefinitionFromFile(policyDirectory, policy.getPolicyName(), APIConstants.SYNAPSE_POLICY_DEFINITION_EXTENSION);
if (synapseDefinition != null) {
synapseDefinition.setGatewayType(OperationPolicyDefinition.GatewayType.Synapse);
operationPolicyData.setSynapsePolicyDefinition(synapseDefinition);
}
OperationPolicyDefinition ccDefinition = APIUtil.getOperationPolicyDefinitionFromFile(policyDirectory, policy.getPolicyName(), APIConstants.CC_POLICY_DEFINITION_EXTENSION);
if (ccDefinition != null) {
ccDefinition.setGatewayType(OperationPolicyDefinition.GatewayType.ChoreoConnect);
operationPolicyData.setCcPolicyDefinition(ccDefinition);
}
operationPolicyData.setMd5Hash(APIUtil.getMd5OfOperationPolicy(operationPolicyData));
String policyID = provider.importOperationPolicy(operationPolicyData, tenantDomain);
policy.setPolicyId(policyID);
validatedOperationPolicies.add(policy);
} catch (APIManagementException e) {
log.error(e);
}
}
}
uriTemplate.setOperationPolicies(validatedOperationPolicies);
}
}
return uriTemplates;
}
use of org.wso2.carbon.apimgt.api.model.OperationPolicyData in project carbon-apimgt by wso2.
the class ApiMgtDAO method addURITemplates.
/**
* Add URI Templates to database with resource scope mappings by passing the DB connection.
*
* @param apiId API Id
* @param api API
* @param tenantId tenant Id
* @param connection Existing DB Connection
* @throws SQLException If a SQL error occurs while adding URI Templates
*/
private void addURITemplates(int apiId, API api, int tenantId, Connection connection) throws SQLException, APIManagementException {
String dbProductName = connection.getMetaData().getDatabaseProductName();
String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
try (PreparedStatement uriMappingPrepStmt = connection.prepareStatement(SQLConstants.ADD_URL_MAPPING_SQL, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "URL_MAPPING_ID") });
PreparedStatement uriScopeMappingPrepStmt = connection.prepareStatement(SQLConstants.ADD_API_RESOURCE_SCOPE_MAPPING);
PreparedStatement operationPolicyMappingPrepStmt = connection.prepareStatement(SQLConstants.OperationPolicyConstants.ADD_API_OPERATION_POLICY_MAPPING)) {
Map<String, String> updatedPoliciesMap = new HashMap<>();
Set<String> usedClonedPolicies = new HashSet<String>();
for (URITemplate uriTemplate : api.getUriTemplates()) {
uriMappingPrepStmt.setInt(1, apiId);
uriMappingPrepStmt.setString(2, uriTemplate.getHTTPVerb());
uriMappingPrepStmt.setString(3, uriTemplate.getAuthType());
uriMappingPrepStmt.setString(4, uriTemplate.getUriTemplate());
// If API policy is available then set it for all the resources.
if (StringUtils.isEmpty(api.getApiLevelPolicy())) {
uriMappingPrepStmt.setString(5, (StringUtils.isEmpty(uriTemplate.getThrottlingTier())) ? APIConstants.UNLIMITED_TIER : uriTemplate.getThrottlingTier());
} else {
uriMappingPrepStmt.setString(5, (StringUtils.isEmpty(api.getApiLevelPolicy())) ? APIConstants.UNLIMITED_TIER : api.getApiLevelPolicy());
}
InputStream is = null;
if (uriTemplate.getMediationScript() != null) {
is = new ByteArrayInputStream(uriTemplate.getMediationScript().getBytes(Charset.defaultCharset()));
}
if (connection.getMetaData().getDriverName().contains("PostgreSQL") || connection.getMetaData().getDatabaseProductName().contains("DB2")) {
if (uriTemplate.getMediationScript() != null) {
uriMappingPrepStmt.setBinaryStream(6, is, uriTemplate.getMediationScript().getBytes(Charset.defaultCharset()).length);
} else {
uriMappingPrepStmt.setBinaryStream(6, is, 0);
}
} else {
uriMappingPrepStmt.setBinaryStream(6, is);
}
uriMappingPrepStmt.execute();
int uriMappingId = -1;
try (ResultSet resultIdSet = uriMappingPrepStmt.getGeneratedKeys()) {
while (resultIdSet.next()) {
uriMappingId = resultIdSet.getInt(1);
}
}
if (uriMappingId != -1) {
for (Scope uriTemplateScope : uriTemplate.retrieveAllScopes()) {
String scopeKey = uriTemplateScope.getKey();
if (log.isDebugEnabled()) {
log.debug("Adding scope to resource mapping for scope key: " + scopeKey + " and URL mapping Id: " + uriMappingId);
}
uriScopeMappingPrepStmt.setString(1, scopeKey);
uriScopeMappingPrepStmt.setInt(2, uriMappingId);
uriScopeMappingPrepStmt.setInt(3, tenantId);
uriScopeMappingPrepStmt.addBatch();
}
if (uriTemplate.getOperationPolicies() != null) {
for (OperationPolicy policy : uriTemplate.getOperationPolicies()) {
if (!updatedPoliciesMap.keySet().contains(policy.getPolicyId())) {
OperationPolicyData existingPolicy = getAPISpecificOperationPolicyByPolicyID(policy.getPolicyId(), api.getUuid(), 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,
// it can be a common policy and we need to verify that it has not been previously cloned
// for the API before cloning again.
clonedPolicyId = getClonedPolicyIdForCommonPolicyId(connection, policy.getPolicyId(), api.getUuid());
if (clonedPolicyId == null) {
clonedPolicyId = cloneOperationPolicy(connection, policy.getPolicyId(), api.getUuid(), 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.
updatedPoliciesMap.put(policy.getPolicyId(), clonedPolicyId);
}
Gson gson = new Gson();
String paramJSON = gson.toJson(policy.getParameters());
if (log.isDebugEnabled()) {
log.debug("Adding operation policy " + policy.getPolicyName() + " for API " + api.getId().getApiName() + " to URL mapping Id " + uriMappingId);
}
operationPolicyMappingPrepStmt.setInt(1, uriMappingId);
operationPolicyMappingPrepStmt.setString(2, updatedPoliciesMap.get(policy.getPolicyId()));
operationPolicyMappingPrepStmt.setString(3, policy.getDirection());
operationPolicyMappingPrepStmt.setString(4, paramJSON);
operationPolicyMappingPrepStmt.setInt(5, policy.getOrder());
operationPolicyMappingPrepStmt.addBatch();
}
}
}
uriTemplate.setId(uriMappingId);
}
// end URITemplate list iteration
uriScopeMappingPrepStmt.executeBatch();
operationPolicyMappingPrepStmt.executeBatch();
cleanUnusedClonedOperationPolicies(connection, usedClonedPolicies, api.getUuid());
}
}
use of org.wso2.carbon.apimgt.api.model.OperationPolicyData in project carbon-apimgt by wso2.
the class OperationPolicyMappingUtil method fromOperationPolicyDataListToDTO.
public static OperationPolicyDataListDTO fromOperationPolicyDataListToDTO(List<OperationPolicyData> policyDataList, int offset, int limit) {
List<OperationPolicyDataDTO> operationPolicyList = new ArrayList<>();
if (policyDataList == null) {
policyDataList = new ArrayList<>();
}
int size = policyDataList.size();
int start = offset < size && offset >= 0 ? offset : Integer.MAX_VALUE;
int end = Math.min(offset + limit - 1, size - 1);
for (int i = start; i <= end; i++) {
operationPolicyList.add(fromOperationPolicyDataToDTO(policyDataList.get(i)));
}
PaginationDTO paginationDTO = new PaginationDTO();
paginationDTO.setLimit(limit);
paginationDTO.setOffset(offset);
paginationDTO.setTotal(size);
OperationPolicyDataListDTO dataListDTO = new OperationPolicyDataListDTO();
dataListDTO.setList(operationPolicyList);
dataListDTO.setCount(operationPolicyList.size());
dataListDTO.setPagination(paginationDTO);
return dataListDTO;
}
use of org.wso2.carbon.apimgt.api.model.OperationPolicyData in project carbon-apimgt by wso2.
the class OperationPolicyMappingUtil method fromOperationPolicyDataToDTO.
public static OperationPolicyDataDTO fromOperationPolicyDataToDTO(OperationPolicyData policyData) {
OperationPolicyDataDTO policyDataDTO = new OperationPolicyDataDTO();
OperationPolicySpecification policySpecification = policyData.getSpecification();
policyDataDTO.setId(policyData.getPolicyId());
policyDataDTO.setMd5(policyData.getMd5Hash());
policyDataDTO.setIsAPISpecific(policyData.isApiSpecificPolicy());
policyDataDTO.setName(policySpecification.getName());
policyDataDTO.setDisplayName(policySpecification.getDisplayName());
policyDataDTO.setDescription(policySpecification.getDescription());
policyDataDTO.setSupportedGateways(policySpecification.getSupportedGateways());
policyDataDTO.setSupportedApiTypes(policySpecification.getSupportedApiTypes());
policyDataDTO.setApplicableFlows(policySpecification.getApplicableFlows());
policyDataDTO.setMultipleAllowed(policySpecification.isMultipleAllowed());
policyDataDTO.setCategory(policySpecification.getCategory().toString());
if (policySpecification.getPolicyAttributes() != null) {
List<OperationPolicySpecAttributeDTO> specAttributeDtoList = new ArrayList<>();
for (OperationPolicySpecAttribute specAttribute : policySpecification.getPolicyAttributes()) {
OperationPolicySpecAttributeDTO specAttributeDTO = fromOperationPolicySpecAttributesToDTO(specAttribute);
specAttributeDtoList.add(specAttributeDTO);
}
policyDataDTO.setPolicyAttributes(specAttributeDtoList);
}
return policyDataDTO;
}
Aggregations