use of org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException in project carbon-apimgt by wso2.
the class APIStoreImpl method addApplication.
@Override
public ApplicationCreationResponse addApplication(Application application) throws APIManagementException {
ApplicationCreationResponse applicationResponse = null;
try {
if (getApplicationDAO().isApplicationNameExists(application.getName())) {
String message = "An application already exists with a duplicate name - " + application.getName();
log.error(message);
throw new APIMgtResourceAlreadyExistsException(message, ExceptionCodes.APPLICATION_ALREADY_EXISTS);
}
// Tier validation
Policy tier = application.getPolicy();
if (tier == null) {
String message = "Tier name cannot be null - " + application.getName();
log.error(message);
throw new APIManagementException(message, ExceptionCodes.TIER_CANNOT_BE_NULL);
} else {
Policy policy = getPolicyDAO().getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.application, tier.getPolicyName());
if (policy == null) {
String message = "Specified tier " + tier.getPolicyName() + " is invalid";
log.error(message);
throw new APIManagementException(message, ExceptionCodes.TIER_CANNOT_BE_NULL);
}
application.setPolicy(policy);
}
// Generate UUID for application
String generatedUuid = UUID.randomUUID().toString();
application.setId(generatedUuid);
String permissionString = application.getPermissionString();
if (permissionString != null && !("").equals(permissionString)) {
HashMap roleNamePermissionList;
roleNamePermissionList = getAPIPermissionArray(permissionString);
application.setPermissionMap(roleNamePermissionList);
}
application.setCreatedTime(LocalDateTime.now());
getApplicationDAO().addApplication(application);
WorkflowExecutor appCreationWFExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
ApplicationCreationWorkflow workflow = new ApplicationCreationWorkflow(getApplicationDAO(), getWorkflowDAO(), getApiGateway());
workflow.setApplication(application);
workflow.setCreatedBy(getUsername());
workflow.setWorkflowReference(application.getId());
workflow.setExternalWorkflowReference(UUID.randomUUID().toString());
workflow.setCreatedTime(LocalDateTime.now());
String workflowDescription = "Application [ " + application.getName() + " ] creation request from application creator - " + getUsername() + " with throttling tier - " + tier.getPolicyName() + "";
workflow.setWorkflowDescription(workflowDescription);
WorkflowResponse response = appCreationWFExecutor.execute(workflow);
workflow.setStatus(response.getWorkflowStatus());
if (WorkflowStatus.CREATED != response.getWorkflowStatus()) {
completeWorkflow(appCreationWFExecutor, workflow);
} else {
getApplicationDAO().updateApplicationState(generatedUuid, APIMgtConstants.ApplicationStatus.APPLICATION_ONHOLD);
addWorkflowEntries(workflow);
}
APIUtils.logDebug("successfully added application with appId " + application.getId(), log);
applicationResponse = new ApplicationCreationResponse(application.getId(), response);
} catch (APIMgtDAOException e) {
String errorMsg = "Error occurred while creating the application - " + application.getName();
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
} catch (ParseException e) {
String errorMsg = "Error occurred while parsing the permission json from swagger in application - " + application.getName();
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION);
} catch (WorkflowException e) {
String errorMsg = "Error occurred in workflow";
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, ExceptionCodes.WORKFLOW_EXCEPTION);
}
return applicationResponse;
}
use of org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException in project carbon-apimgt by wso2.
the class APIProviderImpl method createNewAPIVersion.
public API createNewAPIVersion(String existingApiId, String newVersion, Boolean isDefaultVersion, String organization) throws APIManagementException {
API existingAPI = getAPIbyUUID(existingApiId, organization);
if (existingAPI == null) {
throw new APIMgtResourceNotFoundException("API not found for id " + existingApiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, existingApiId));
}
if (newVersion.equals(existingAPI.getId().getVersion())) {
throw new APIMgtResourceAlreadyExistsException("Version " + newVersion + " exists for api " + existingAPI.getId().getApiName());
}
existingAPI.setOrganization(organization);
APIIdentifier existingAPIId = existingAPI.getId();
String existingAPICreatedTime = existingAPI.getCreatedTime();
String existingAPIStatus = existingAPI.getStatus();
boolean isExsitingAPIdefaultVersion = existingAPI.isDefaultVersion();
String existingContext = existingAPI.getContext();
String existingVersionTimestamp = existingAPI.getVersionTimestamp();
APIIdentifier newApiId = new APIIdentifier(existingAPI.getId().getProviderName(), existingAPI.getId().getApiName(), newVersion);
existingAPI.setUuid(null);
existingAPI.setId(newApiId);
existingAPI.setStatus(APIConstants.CREATED);
existingAPI.setDefaultVersion(isDefaultVersion);
existingAPI.setVersionTimestamp("");
// We need to change the context by setting the new version
// This is a change that is coming with the context version strategy
String existingAPIContextTemplate = existingAPI.getContextTemplate();
existingAPI.setContext(existingAPIContextTemplate.replace("{version}", newVersion));
Map<String, List<OperationPolicy>> operationPoliciesMap = extractAndDropOperationPoliciesFromURITemplate(existingAPI.getUriTemplates());
API newAPI = addAPI(existingAPI);
String newAPIId = newAPI.getUuid();
if (!operationPoliciesMap.isEmpty()) {
// clone common or API specific operation policy.
Map<String, String> clonedOperationPolicyMap = cloneOperationPoliciesToAPI(existingApiId, newAPI, operationPoliciesMap);
// attach policy to uri template.
attachOperationPoliciesToAPI(newAPI, clonedOperationPolicyMap, operationPoliciesMap);
}
// copy docs
List<Documentation> existingDocs = getAllDocumentation(existingApiId, organization);
if (existingDocs != null) {
for (Documentation documentation : existingDocs) {
Documentation newDoc = addDocumentation(newAPIId, documentation, organization);
DocumentationContent content = getDocumentationContent(existingApiId, documentation.getId(), // TODO see whether we can optimize this
organization);
if (content != null) {
addDocumentationContent(newAPIId, newDoc.getId(), organization, content);
}
}
}
// copy icon
ResourceFile icon = getIcon(existingApiId, organization);
if (icon != null) {
setThumbnailToAPI(newAPIId, icon, organization);
}
// copy sequences
List<Mediation> mediationPolicies = getAllApiSpecificMediationPolicies(existingApiId, organization);
if (mediationPolicies != null) {
for (Mediation mediation : mediationPolicies) {
Mediation policy = getApiSpecificMediationPolicyByPolicyId(existingApiId, mediation.getUuid(), organization);
addApiSpecificMediationPolicy(newAPIId, policy, organization);
}
}
// copy wsdl
if (!APIConstants.API_TYPE_SOAPTOREST.equals(existingAPI.getType()) && existingAPI.getWsdlUrl() != null) {
ResourceFile wsdl = getWSDL(existingApiId, organization);
if (wsdl != null) {
addWSDLResource(newAPIId, wsdl, null, organization);
}
}
// copy graphql definition
String graphQLSchema = getGraphqlSchemaDefinition(existingApiId, organization);
if (graphQLSchema != null) {
saveGraphqlSchemaDefinition(newAPIId, graphQLSchema, organization);
}
// update old api
// revert back to old values before update.
existingAPI.setUuid(existingApiId);
existingAPI.setStatus(existingAPIStatus);
existingAPI.setId(existingAPIId);
existingAPI.setContext(existingContext);
existingAPI.setCreatedTime(existingAPICreatedTime);
// update existing api with the original timestamp
existingAPI.setVersionTimestamp(existingVersionTimestamp);
if (isDefaultVersion) {
existingAPI.setDefaultVersion(false);
} else {
existingAPI.setDefaultVersion(isExsitingAPIdefaultVersion);
}
try {
apiPersistenceInstance.updateAPI(new Organization(organization), APIMapper.INSTANCE.toPublisherApi(existingAPI));
} catch (APIPersistenceException e) {
throw new APIManagementException("Error while updating API details", e);
}
return getAPIbyUUID(newAPIId, organization);
}
use of org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException in project carbon-apimgt by wso2.
the class RestApiUtilTest method testisDueToResourceAlreadyExistsWithAPIMgtResourceAlreadyExistsException.
@Test
public void testisDueToResourceAlreadyExistsWithAPIMgtResourceAlreadyExistsException() throws Exception {
APIMgtResourceAlreadyExistsException apiMgtResourceAlreadyExistsException = new APIMgtResourceAlreadyExistsException("New Sample exception");
Throwable testThrowable = new Throwable();
PowerMockito.spy(RestApiUtil.class);
PowerMockito.doReturn(apiMgtResourceAlreadyExistsException).when(RestApiUtil.class, "getPossibleErrorCause", testThrowable);
Assert.assertTrue("Invalid exception has been passed.", RestApiUtil.isDueToResourceAlreadyExists(testThrowable));
}
use of org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method createNewAPIVersion.
@Override
public Response createNewAPIVersion(String newVersion, String apiId, Boolean defaultVersion, String serviceVersion, MessageContext messageContext) throws APIManagementException {
URI newVersionedApiUri;
APIDTO newVersionedApi = new APIDTO();
ServiceEntry service = new ServiceEntry();
try {
APIIdentifier apiIdentifierFromTable = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
if (apiIdentifierFromTable == null) {
throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
}
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
int tenantId = APIUtil.getInternalOrganizationId(organization);
API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
if (existingAPI == null) {
throw new APIMgtResourceNotFoundException("API not found for id " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
}
if (newVersion.equals(existingAPI.getId().getVersion())) {
throw new APIMgtResourceAlreadyExistsException("Version " + newVersion + " exists for api " + existingAPI.getId().getApiName(), ExceptionCodes.from(API_VERSION_ALREADY_EXISTS, newVersion, existingAPI.getId().getApiName()));
}
if (StringUtils.isNotEmpty(serviceVersion)) {
String serviceName = existingAPI.getServiceInfo("name");
ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
service = serviceCatalog.getServiceByNameAndVersion(serviceName, serviceVersion, tenantId);
if (service == null) {
throw new APIManagementException("No matching service version found", ExceptionCodes.SERVICE_VERSION_NOT_FOUND);
}
}
if (StringUtils.isNotEmpty(serviceVersion) && !serviceVersion.equals(existingAPI.getServiceInfo("version"))) {
APIDTO apidto = createAPIDTO(existingAPI, newVersion);
if (ServiceEntry.DefinitionType.OAS2.equals(service.getDefinitionType()) || ServiceEntry.DefinitionType.OAS3.equals(service.getDefinitionType())) {
newVersionedApi = importOpenAPIDefinition(service.getEndpointDef(), null, null, apidto, null, service, organization);
} else if (ServiceEntry.DefinitionType.ASYNC_API.equals(service.getDefinitionType())) {
newVersionedApi = importAsyncAPISpecification(service.getEndpointDef(), null, apidto, null, service, organization);
}
} else {
API versionedAPI = apiProvider.createNewAPIVersion(apiId, newVersion, defaultVersion, organization);
newVersionedApi = APIMappingUtil.fromAPItoDTO(versionedAPI);
}
// This URI used to set the location header of the POST response
newVersionedApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + newVersionedApi.getId());
return Response.created(newVersionedApiUri).entity(newVersionedApi).build();
} catch (APIManagementException e) {
if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while copying API : " + apiId, e, log);
} else {
throw e;
}
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving API location of " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException in project carbon-apimgt by wso2.
the class ServicesApiServiceImpl method importService.
@Override
public Response importService(InputStream fileInputStream, Attachment fileDetail, Boolean overwrite, String verifier, MessageContext messageContext) throws APIManagementException {
String userName = RestApiCommonUtil.getLoggedInUsername();
int tenantId = APIUtil.getTenantId(userName);
String tempDirPath = FileBasedServicesImportExportManager.createDir(RestApiConstants.JAVA_IO_TMPDIR);
List<ServiceInfoDTO> serviceList;
HashMap<String, ServiceEntry> serviceEntries;
HashMap<String, String> newResourcesHash;
List<ServiceEntry> serviceListToImport = new ArrayList<>();
List<ServiceEntry> serviceListToIgnore = new ArrayList<>();
List<ServiceEntry> servicesWithInvalidDefinition = new ArrayList<>();
// unzip the uploaded zip
try {
FileBasedServicesImportExportManager importExportManager = new FileBasedServicesImportExportManager(tempDirPath);
importExportManager.importService(fileInputStream);
} catch (APIMgtResourceAlreadyExistsException e) {
RestApiUtil.handleResourceAlreadyExistsError("Error while importing Service", e, log);
}
newResourcesHash = Md5HashGenerator.generateHash(tempDirPath);
serviceEntries = ServiceEntryMappingUtil.fromDirToServiceEntryMap(tempDirPath);
Map<String, Boolean> validationResults = new HashMap<>();
if (overwrite && StringUtils.isNotEmpty(verifier)) {
validationResults = validateVerifier(verifier, tenantId);
}
try {
for (Map.Entry<String, ServiceEntry> entry : serviceEntries.entrySet()) {
String key = entry.getKey();
serviceEntries.get(key).setMd5(newResourcesHash.get(key));
ServiceEntry service = serviceEntries.get(key);
byte[] definitionFileByteArray = getDefinitionFromInput(service.getEndpointDef());
if (validateAndRetrieveServiceDefinition(definitionFileByteArray, service.getDefUrl(), service.getDefinitionType()).isValid() || (ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType()) && APIMWSDLReader.validateWSDLFile(definitionFileByteArray).isValid())) {
service.setEndpointDef(new ByteArrayInputStream(definitionFileByteArray));
} else {
servicesWithInvalidDefinition.add(service);
}
if (overwrite) {
if (StringUtils.isNotEmpty(verifier) && validationResults.containsKey(service.getKey()) && !validationResults.get(service.getKey())) {
serviceListToIgnore.add(service);
} else {
serviceListToImport.add(service);
}
} else {
serviceListToImport.add(service);
}
}
} catch (IOException e) {
RestApiUtil.handleInternalServerError("Error when reading the service definition content", log);
}
if (servicesWithInvalidDefinition.size() > 0) {
serviceList = ServiceEntryMappingUtil.fromServiceListToDTOList(servicesWithInvalidDefinition);
String errorMsg = "The Service import has been failed as invalid service definition provided";
return Response.status(Response.Status.BAD_REQUEST).entity(getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 400L, errorMsg, new JSONArray(serviceList).toString())).build();
}
if (serviceListToIgnore.size() > 0) {
serviceList = ServiceEntryMappingUtil.fromServiceListToDTOList(serviceListToIgnore);
String errorMsg = "The Service import has been failed since to verifier validation fails";
return Response.status(Response.Status.BAD_REQUEST).entity(getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 400L, errorMsg, new JSONArray(serviceList).toString())).build();
} else {
List<ServiceEntry> importedServiceList = new ArrayList<>();
List<ServiceEntry> retrievedServiceList = new ArrayList<>();
try {
if (serviceListToImport.size() > 0) {
importedServiceList = serviceCatalog.importServices(serviceListToImport, tenantId, userName, overwrite);
}
} catch (APIManagementException e) {
if (ExceptionCodes.SERVICE_IMPORT_FAILED_WITHOUT_OVERWRITE.getErrorCode() == e.getErrorHandler().getErrorCode()) {
RestApiUtil.handleBadRequest("Cannot update existing services when overwrite is false", log);
} else {
RestApiUtil.handleInternalServerError("Error when importing services to service catalog", e, log);
}
}
if (importedServiceList == null) {
RestApiUtil.handleBadRequest("Cannot update the name or version or key or definition type of an " + "existing service", log);
}
for (ServiceEntry service : importedServiceList) {
retrievedServiceList.add(serviceCatalog.getServiceByKey(service.getKey(), tenantId));
}
serviceList = ServiceEntryMappingUtil.fromServiceListToDTOList(retrievedServiceList);
return Response.ok().entity(ServiceEntryMappingUtil.fromServiceInfoDTOToServiceInfoListDTO(serviceList)).build();
}
}
Aggregations