use of org.wso2.carbon.apimgt.api.model.APIRevision in project carbon-apimgt by wso2.
the class OASParserUtil method getAPIOpenAPIDefinitionTimeStamps.
/**
* This method returns the timestamps for a given API
*
* @param apiIdentifier
* @param registry
* @return
* @throws APIManagementException
*/
public static Map<String, String> getAPIOpenAPIDefinitionTimeStamps(APIIdentifier apiIdentifier, Registry registry) throws APIManagementException {
Map<String, String> timeStampMap = new HashMap<String, String>();
String resourcePath;
APIRevision apiRevision = ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(apiIdentifier.getUUID());
if (apiRevision != null && apiRevision.getApiUUID() != null) {
resourcePath = APIUtil.getRevisionPath(apiRevision.getApiUUID(), apiRevision.getId());
} else {
resourcePath = APIUtil.getOpenAPIDefinitionFilePath(apiIdentifier.getName(), apiIdentifier.getVersion(), apiIdentifier.getProviderName());
}
try {
if (registry.resourceExists(resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME)) {
Resource apiDocResource = registry.get(resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME);
Date lastModified = apiDocResource.getLastModified();
Date createdTime = apiDocResource.getCreatedTime();
if (lastModified != null) {
timeStampMap.put("UPDATED_TIME", String.valueOf(lastModified.getTime()));
} else {
timeStampMap.put("CREATED_TIME", String.valueOf(createdTime.getTime()));
}
} else {
if (log.isDebugEnabled()) {
log.debug("Resource " + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME + " not found at " + resourcePath);
}
}
} catch (RegistryException e) {
handleException("Error while retrieving OpenAPI v2.0 or v3.0.0 updated time for " + apiIdentifier.getApiName() + '-' + apiIdentifier.getVersion(), e);
}
return timeStampMap;
}
use of org.wso2.carbon.apimgt.api.model.APIRevision in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method deleteAPIRevision.
/**
* Delete a revision of an API
*
* @param apiId UUID of the API
* @param revisionId Revision ID of the API
* @param messageContext message context object
* @return response with 204 status code and no content
*/
@Override
public Response deleteAPIRevision(String apiId, String revisionId, MessageContext messageContext) throws APIManagementException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
// validate if api exists
APIInfo apiInfo = validateAPIExistence(apiId);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(apiInfo.getStatus().toString());
apiProvider.deleteAPIRevision(apiId, revisionId, organization);
List<APIRevision> apiRevisions = apiProvider.getAPIRevisions(apiId);
APIRevisionListDTO apiRevisionListDTO = APIMappingUtil.fromListAPIRevisiontoDTO(apiRevisions);
return Response.ok().entity(apiRevisionListDTO).build();
}
use of org.wso2.carbon.apimgt.api.model.APIRevision in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method getAPIMonetization.
/**
* Get API monetization status and monetized tier to billing plan mapping
*
* @param apiId API ID
* @param messageContext message context
* @return API monetization status and monetized tier to billing plan mapping
*/
@Override
public Response getAPIMonetization(String apiId, MessageContext messageContext) {
try {
if (StringUtils.isBlank(apiId)) {
String errorMessage = "API ID cannot be empty or null when retrieving monetized plans.";
RestApiUtil.handleBadRequest(errorMessage, log);
}
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
String uuid;
APIRevision apiRevision = ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(apiId);
if (apiRevision != null && apiRevision.getApiUUID() != null) {
uuid = apiRevision.getApiUUID();
} else {
uuid = apiId;
}
API api = apiProvider.getAPIbyUUID(apiId, organization);
Monetization monetizationImplementation = apiProvider.getMonetizationImplClass();
Map<String, String> monetizedPoliciesToPlanMapping = monetizationImplementation.getMonetizedPoliciesToPlanMapping(api);
APIMonetizationInfoDTO monetizationInfoDTO = APIMappingUtil.getMonetizedTiersDTO(uuid, organization, monetizedPoliciesToPlanMapping);
return Response.ok().entity(monetizationInfoDTO).build();
} catch (APIManagementException e) {
String errorMessage = "Failed to retrieve monetized plans for API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (MonetizationException e) {
String errorMessage = "Failed to fetch monetized plans of API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return Response.serverError().build();
}
use of org.wso2.carbon.apimgt.api.model.APIRevision in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method getAPILifecycleHistory.
/**
* Retrieves API Lifecycle history information
*
* @param apiId API Id
* @param ifNoneMatch If-None-Match header value
* @return API Lifecycle history information
*/
@Override
public Response getAPILifecycleHistory(String apiId, String ifNoneMatch, MessageContext messageContext) {
try {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
API api;
APIRevision apiRevision = ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(apiId);
if (apiRevision != null && apiRevision.getApiUUID() != null) {
api = apiProvider.getAPIbyUUID(apiRevision.getApiUUID(), organization);
} else {
api = apiProvider.getAPIbyUUID(apiId, organization);
}
return Response.ok().entity(PublisherCommonUtils.getLifecycleHistoryDTO(api.getUuid(), apiProvider)).build();
} catch (APIManagementException e) {
// Auth failure occurs when cross tenant accessing APIs. Sends 404, since we don't need to expose the existence of the resource
if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
} else if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving the lifecycle " + "events of API : " + apiId, e, log);
} else {
String errorMessage = "Error while retrieving the lifecycle events of API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.APIRevision in project carbon-apimgt by wso2.
the class ApiMgtDAO method addAPIRevision.
/**
* Adds an API revision record to the database
*
* @param apiRevision content of the revision
* @throws APIManagementException if an error occurs when adding a new API revision
*/
public void addAPIRevision(APIRevision apiRevision) throws APIManagementException {
try (Connection connection = APIMgtDBUtil.getConnection()) {
try {
connection.setAutoCommit(false);
// Adding to AM_REVISION table
PreparedStatement statement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.ADD_API_REVISION);
statement.setInt(1, apiRevision.getId());
statement.setString(2, apiRevision.getApiUUID());
statement.setString(3, apiRevision.getRevisionUUID());
statement.setString(4, apiRevision.getDescription());
statement.setString(5, apiRevision.getCreatedBy());
statement.setTimestamp(6, new Timestamp(System.currentTimeMillis()));
statement.executeUpdate();
// Retrieve API ID
APIIdentifier apiIdentifier = APIUtil.getAPIIdentifierFromUUID(apiRevision.getApiUUID());
int apiId = getAPIID(apiRevision.getApiUUID(), connection);
int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
// Adding to AM_API_URL_MAPPING table
PreparedStatement getURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_URL_MAPPINGS_WITH_SCOPE_AND_PRODUCT_ID);
getURLMappingsStatement.setInt(1, apiId);
List<URITemplate> urlMappingList = new ArrayList<>();
try (ResultSet rs = getURLMappingsStatement.executeQuery()) {
while (rs.next()) {
String script = null;
URITemplate uriTemplate = new URITemplate();
uriTemplate.setHTTPVerb(rs.getString(1));
uriTemplate.setAuthType(rs.getString(2));
uriTemplate.setUriTemplate(rs.getString(3));
uriTemplate.setThrottlingTier(rs.getString(4));
InputStream mediationScriptBlob = rs.getBinaryStream(5);
if (mediationScriptBlob != null) {
script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
}
uriTemplate.setMediationScript(script);
if (!StringUtils.isEmpty(rs.getString(6))) {
Scope scope = new Scope();
scope.setKey(rs.getString(6));
uriTemplate.setScope(scope);
}
if (rs.getInt(7) != 0) {
// Adding product id to uri template id just to store value
uriTemplate.setId(rs.getInt(7));
}
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);
}
}
setOperationPoliciesToURITemplatesMap(apiRevision.getApiUUID(), uriTemplateMap);
PreparedStatement insertURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_URL_MAPPINGS);
for (URITemplate urlMapping : uriTemplateMap.values()) {
insertURLMappingsStatement.setInt(1, apiId);
insertURLMappingsStatement.setString(2, urlMapping.getHTTPVerb());
insertURLMappingsStatement.setString(3, urlMapping.getAuthType());
insertURLMappingsStatement.setString(4, urlMapping.getUriTemplate());
insertURLMappingsStatement.setString(5, urlMapping.getThrottlingTier());
insertURLMappingsStatement.setString(6, apiRevision.getRevisionUUID());
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_REVISIONED_URL_MAPPINGS_ID);
PreparedStatement insertScopeResourceMappingStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_SCOPE_RESOURCE_MAPPING);
PreparedStatement insertProductResourceMappingStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_PRODUCT_RESOURCE_MAPPING);
PreparedStatement insertOperationPolicyMappingStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.ADD_API_OPERATION_POLICY_MAPPING);
Map<String, String> clonedPolicyMap = new HashMap<>();
for (URITemplate urlMapping : uriTemplateMap.values()) {
getRevisionedURLMappingsStatement.setInt(1, apiId);
getRevisionedURLMappingsStatement.setString(2, apiRevision.getRevisionUUID());
getRevisionedURLMappingsStatement.setString(3, urlMapping.getHTTPVerb());
getRevisionedURLMappingsStatement.setString(4, urlMapping.getAuthType());
getRevisionedURLMappingsStatement.setString(5, urlMapping.getUriTemplate());
getRevisionedURLMappingsStatement.setString(6, urlMapping.getThrottlingTier());
try (ResultSet rs = getRevisionedURLMappingsStatement.executeQuery()) {
while (rs.next()) {
if (urlMapping.getScopes() != null) {
for (Scope scope : urlMapping.getScopes()) {
insertScopeResourceMappingStatement.setString(1, scope.getKey());
insertScopeResourceMappingStatement.setInt(2, rs.getInt(1));
insertScopeResourceMappingStatement.setInt(3, tenantId);
insertScopeResourceMappingStatement.addBatch();
}
}
if (urlMapping.getId() != 0) {
insertProductResourceMappingStatement.setInt(1, urlMapping.getId());
insertProductResourceMappingStatement.setInt(2, rs.getInt(1));
insertProductResourceMappingStatement.addBatch();
}
if (urlMapping.getOperationPolicies().size() > 0) {
for (OperationPolicy policy : urlMapping.getOperationPolicies()) {
if (!clonedPolicyMap.keySet().contains(policy.getPolicyId())) {
// Since we are creating a new revision, if the policy is not found in the policy map,
// we have to clone the policy.
String clonedPolicyId = revisionOperationPolicy(connection, policy.getPolicyId(), apiRevision.getApiUUID(), apiRevision.getRevisionUUID(), tenantDomain);
// policy ID is stored in a map as same policy can be applied to multiple operations
// and we only need to create the policy once.
clonedPolicyMap.put(policy.getPolicyId(), clonedPolicyId);
}
Gson gson = new Gson();
String paramJSON = gson.toJson(policy.getParameters());
insertOperationPolicyMappingStatement.setInt(1, rs.getInt(1));
insertOperationPolicyMappingStatement.setString(2, clonedPolicyMap.get(policy.getPolicyId()));
insertOperationPolicyMappingStatement.setString(3, policy.getDirection());
insertOperationPolicyMappingStatement.setString(4, paramJSON);
insertOperationPolicyMappingStatement.setInt(5, policy.getOrder());
insertOperationPolicyMappingStatement.addBatch();
}
}
}
}
}
insertScopeResourceMappingStatement.executeBatch();
insertProductResourceMappingStatement.executeBatch();
insertOperationPolicyMappingStatement.executeBatch();
// Adding to AM_API_CLIENT_CERTIFICATE
PreparedStatement getClientCertificatesStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_CLIENT_CERTIFICATES);
getClientCertificatesStatement.setInt(1, apiId);
List<ClientCertificateDTO> clientCertificateDTOS = new ArrayList<>();
try (ResultSet rs = getClientCertificatesStatement.executeQuery()) {
while (rs.next()) {
ClientCertificateDTO clientCertificateDTO = new ClientCertificateDTO();
clientCertificateDTO.setAlias(rs.getString(1));
clientCertificateDTO.setCertificate(APIMgtDBUtil.getStringFromInputStream(rs.getBinaryStream(2)));
clientCertificateDTO.setTierName(rs.getString(3));
clientCertificateDTOS.add(clientCertificateDTO);
}
}
PreparedStatement insertClientCertificateStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_CLIENT_CERTIFICATES);
for (ClientCertificateDTO clientCertificateDTO : clientCertificateDTOS) {
insertClientCertificateStatement.setInt(1, tenantId);
insertClientCertificateStatement.setString(2, clientCertificateDTO.getAlias());
insertClientCertificateStatement.setInt(3, apiId);
insertClientCertificateStatement.setBinaryStream(4, getInputStream(clientCertificateDTO.getCertificate()));
insertClientCertificateStatement.setBoolean(5, false);
insertClientCertificateStatement.setString(6, clientCertificateDTO.getTierName());
insertClientCertificateStatement.setString(7, apiRevision.getRevisionUUID());
insertClientCertificateStatement.addBatch();
}
insertClientCertificateStatement.executeBatch();
// Adding to AM_GRAPHQL_COMPLEXITY table
PreparedStatement getGraphQLComplexityStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_GRAPHQL_COMPLEXITY);
List<CustomComplexityDetails> customComplexityDetailsList = new ArrayList<>();
getGraphQLComplexityStatement.setInt(1, apiId);
try (ResultSet rs1 = getGraphQLComplexityStatement.executeQuery()) {
while (rs1.next()) {
CustomComplexityDetails customComplexityDetails = new CustomComplexityDetails();
customComplexityDetails.setType(rs1.getString("TYPE"));
customComplexityDetails.setField(rs1.getString("FIELD"));
customComplexityDetails.setComplexityValue(rs1.getInt("COMPLEXITY_VALUE"));
customComplexityDetailsList.add(customComplexityDetails);
}
}
PreparedStatement insertGraphQLComplexityStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_GRAPHQL_COMPLEXITY);
for (CustomComplexityDetails customComplexityDetails : customComplexityDetailsList) {
insertGraphQLComplexityStatement.setString(1, UUID.randomUUID().toString());
insertGraphQLComplexityStatement.setInt(2, apiId);
insertGraphQLComplexityStatement.setString(3, customComplexityDetails.getType());
insertGraphQLComplexityStatement.setString(4, customComplexityDetails.getField());
insertGraphQLComplexityStatement.setInt(5, customComplexityDetails.getComplexityValue());
insertGraphQLComplexityStatement.setString(6, apiRevision.getRevisionUUID());
insertGraphQLComplexityStatement.addBatch();
}
insertGraphQLComplexityStatement.executeBatch();
updateLatestRevisionNumber(connection, apiRevision.getApiUUID(), apiRevision.getId());
addAPIRevisionMetaData(connection, apiRevision.getApiUUID(), apiRevision.getRevisionUUID());
connection.commit();
} catch (SQLException e) {
connection.rollback();
handleException("Failed to add API Revision entry of API UUID " + apiRevision.getApiUUID(), e);
}
} catch (SQLException e) {
handleException("Failed to add API Revision entry of API UUID " + apiRevision.getApiUUID(), e);
}
}
Aggregations