use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.
the class APIPublisherImpl method createNewAPIVersion.
/**
* Create a new version of the <code>api</code>, with version <code>newVersion</code>
*
* @param apiId The API to be copied
* @param newVersion The version of the new API
* @return UUID of the newly created version.
* @throws APIManagementException If an error occurs while trying to create
* the new version of the API
*/
@Override
public String createNewAPIVersion(String apiId, String newVersion) throws APIManagementException {
String newVersionedId;
LifecycleState lifecycleState;
// validate parameters
if (StringUtils.isEmpty(newVersion)) {
String errorMsg = "New API version cannot be empty";
log.error(errorMsg);
throw new APIManagementException(errorMsg, ExceptionCodes.PARAMETER_NOT_PROVIDED);
}
if (StringUtils.isEmpty(apiId)) {
String errorMsg = "API ID cannot be empty";
log.error(errorMsg);
throw new APIManagementException(errorMsg, ExceptionCodes.PARAMETER_NOT_PROVIDED);
}
try {
API api = getApiDAO().getAPI(apiId);
if (api.getVersion().equals(newVersion)) {
String errMsg = "New API version " + newVersion + " cannot be same as the previous version for " + "API " + api.getName();
log.error(errMsg);
throw new APIManagementException(errMsg, ExceptionCodes.API_ALREADY_EXISTS);
}
API.APIBuilder apiBuilder = new API.APIBuilder(api);
apiBuilder.id(UUID.randomUUID().toString());
apiBuilder.version(newVersion);
apiBuilder.context(api.getContext().replace(api.getVersion(), newVersion));
lifecycleState = getApiLifecycleManager().addLifecycle(APIMgtConstants.API_LIFECYCLE, getUsername());
apiBuilder.associateLifecycle(lifecycleState);
apiBuilder.copiedFromApiId(api.getId());
if (StringUtils.isEmpty(apiBuilder.getApiDefinition())) {
apiBuilder.apiDefinition(apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder));
}
getApiDAO().addAPI(apiBuilder.build());
newVersionedId = apiBuilder.getId();
sendNotification(apiId, apiBuilder.getName(), newVersion);
} catch (APIMgtDAOException e) {
String errorMsg = "Couldn't create new API version from " + apiId;
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
} catch (LifecycleException e) {
String errorMsg = "Couldn't Associate new API Lifecycle from " + apiId;
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
}
return newVersionedId;
}
use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.
the class APIPublisherImpl method deleteAPI.
/**
* Delete an API
*
* @param identifier UUID of the API.
* @throws APIManagementException if failed to remove the API
*/
@Override
public void deleteAPI(String identifier) throws APIManagementException {
APIGateway gateway = getApiGateway();
try {
if (getAPISubscriptionCountByAPI(identifier) == 0) {
API api = getAPIbyUUID(identifier);
// Checks whether the user has required permissions to delete the API
verifyUserPermissionsToDeleteAPI(getUsername(), api);
String apiWfStatus = api.getWorkflowStatus();
API.APIBuilder apiBuilder = new API.APIBuilder(api);
// Delete API in gateway
gateway.deleteAPI(api);
if (log.isDebugEnabled()) {
log.debug("API : " + api.getName() + " has been successfully removed from the gateway");
}
if (!getApiDAO().isAPIVersionsExist(api.getName())) {
Map<String, String> scopeMap = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(getApiSwaggerDefinition(identifier));
for (String scope : scopeMap.keySet()) {
try {
getKeyManager().deleteScope(scope);
} catch (KeyManagementException e) {
// We ignore the error due to if scope get deleted from other end that will affect to delete
// api.
log.warn("Scope couldn't delete from Key Manager", e);
}
}
}
getApiDAO().deleteAPI(identifier);
// Deleting API specific endpoints
if (api.getEndpoint() != null) {
for (Map.Entry<String, Endpoint> entry : api.getEndpoint().entrySet()) {
Endpoint endpoint = entry.getValue();
if (APIMgtConstants.API_SPECIFIC_ENDPOINT.equals(endpoint.getApplicableLevel())) {
deleteEndpoint(endpoint.getId());
}
}
}
getApiLifecycleManager().removeLifecycle(apiBuilder.getLifecycleInstanceId());
APIUtils.logDebug("API with id " + identifier + " was deleted successfully.", log);
if (APILCWorkflowStatus.PENDING.toString().equals(apiWfStatus)) {
cleanupPendingTaskForAPIStateChange(identifier);
}
// 'API_M Functions' related code
// Create a payload with event specific details
Map<String, String> eventPayload = new HashMap<>();
eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, api.getId());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, api.getName());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, api.getVersion());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_PROVIDER, api.getProvider());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, api.getDescription());
// This will notify all the EventObservers(Asynchronous)
ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_DELETION, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
} else {
throw new ApiDeleteFailureException("API with " + identifier + " already have subscriptions");
}
} catch (APIMgtDAOException e) {
String errorMsg = "Error occurred while deleting the API with id " + identifier;
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
} catch (LifecycleException e) {
String errorMsg = "Error occurred while Disassociating the API with Lifecycle id " + identifier;
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
} catch (GatewayException e) {
String message = "Error occurred while deleting API with id - " + identifier + " from gateway";
log.error(message, e);
throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
}
}
use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.
the class APIStoreImplTestCase method testGetAPIWithNotAllowedLifecycleStates.
@Test(description = "Test get API with not allowed lifecycle states (Created, Maintenance, Retired)")
public void testGetAPIWithNotAllowedLifecycleStates() throws APIManagementException {
String exceptionShouldThrowError = "Exception should be thrown when accessing an API in %s state";
String matchedErrorMessage = "Attempt to access an API which is in a restricted state";
ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
Policy policy = new SubscriptionPolicy(UUID, TIER);
Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, TIER)).thenReturn(policy);
APIStore apiStore = getApiStoreImpl(apiDAO, Mockito.mock(ApplicationDAO.class), Mockito.mock(APISubscriptionDAO.class), Mockito.mock(WorkflowDAO.class), Mockito.mock(APIGateway.class), policyDAO);
API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI();
String apiId = apiBuilder.getId();
List<String> notAllowedStates = new ArrayList<String>() {
{
add(APIStatus.CREATED.getStatus());
add(APIStatus.MAINTENANCE.getStatus());
add(APIStatus.RETIRED.getStatus());
}
};
for (String notAllowedState : notAllowedStates) {
apiBuilder.lifeCycleStatus(notAllowedState);
API api = apiBuilder.build();
Mockito.when(apiDAO.getAPI(apiId)).thenReturn(api);
try {
apiStore.getAPIbyUUID(apiId);
Assert.fail(exceptionShouldThrowError);
} catch (APIManagementException e) {
Assert.assertTrue(e.getMessage().contains(matchedErrorMessage));
}
}
}
use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.
the class APIPublisherImplTestCase method testAddAPILifecycleFailure.
@Test(description = "Test add api with API Lifecycle failed", expectedExceptions = { LifecycleException.class, APIManagementException.class })
public void testAddAPILifecycleFailure() throws LifecycleException, APIManagementException {
API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI();
ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
LabelDAO labelDao = Mockito.mock(LabelDAO.class);
APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
Mockito.when(apiLifecycleManager.addLifecycle(APIMgtConstants.API_LIFECYCLE, USER)).thenThrow(new LifecycleException("Couldn't add api lifecycle"));
APIGateway gateway = Mockito.mock(APIGateway.class);
APIPublisherImpl apiPublisher = getApiPublisherImpl(apiDAO, apiLifecycleManager, labelDao, gateway);
apiPublisher.addAPI(apiBuilder);
Mockito.verify(apiLifecycleManager, Mockito.times(1)).addLifecycle(APIMgtConstants.API_LIFECYCLE, USER);
Mockito.verify(apiDAO, Mockito.times(1)).addAPI(apiBuilder.build());
}
use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method apisGet.
/**
* Retrieve a list of APIs with given gateway labels and status.
*
* @param labels Gateway labels
* @param status Lifecycle status
* @param request msf4j request object
* @return 200 OK if the opration was successful
* @throws NotFoundException If failed to retrieve APIs
*/
@Override
public Response apisGet(String labels, String status, Request request) throws NotFoundException {
APIListDTO apiListDTO;
try {
APIMgtAdminService adminService = RestApiUtil.getAPIMgtAdminService();
if (labels != null && !labels.isEmpty()) {
String[] gatewayLabels = labels.split(",");
List<String> labelList = new ArrayList<String>(Arrays.asList(gatewayLabels));
if (status != null && !status.isEmpty()) {
apiListDTO = MappingUtil.toAPIListDTO(adminService.getAPIsByStatus(labelList, status));
return Response.ok().entity(apiListDTO).build();
} else {
apiListDTO = MappingUtil.toAPIListDTO(adminService.getAPIsByGatewayLabel(labelList));
return Response.ok().entity(apiListDTO).build();
}
} else {
apiListDTO = new APIListDTO();
return Response.ok().entity(apiListDTO).build();
}
} catch (APIManagementException e) {
String errorMessage = "Error while retrieving APIs";
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
log.error(errorMessage, e);
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
}
}
Aggregations