use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.
the class APIStoreImpl method addCompositeApiFromDefinition.
/**
* {@inheritDoc}
*/
@Override
public String addCompositeApiFromDefinition(String swaggerResourceUrl) throws APIManagementException {
try {
URL url = new URL(swaggerResourceUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoOutput(true);
urlConn.setRequestMethod(APIMgtConstants.HTTP_GET);
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
String responseStr = new String(IOUtils.toByteArray(urlConn.getInputStream()), StandardCharsets.UTF_8);
CompositeAPI.Builder apiBuilder = apiDefinitionFromSwagger20.generateCompositeApiFromSwaggerResource(getUsername(), responseStr);
apiBuilder.apiDefinition(responseStr);
addCompositeApi(apiBuilder);
return apiBuilder.getId();
} else {
throw new APIManagementException("Error while getting swagger resource from url : " + url, ExceptionCodes.API_DEFINITION_MALFORMED);
}
} catch (UnsupportedEncodingException e) {
String msg = "Unsupported encoding exception while getting the swagger resource from url";
log.error(msg, e);
throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
} catch (ProtocolException e) {
String msg = "Protocol exception while getting the swagger resource from url";
log.error(msg, e);
throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
} catch (MalformedURLException e) {
String msg = "Malformed url while getting the swagger resource from url";
log.error(msg, e);
throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
} catch (IOException e) {
String msg = "Error while getting the swagger resource from url";
log.error(msg, e);
throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
}
}
use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 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.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.
the class APIStoreImpl method createNewCompositeApiVersion.
/**
* {@inheritDoc}
*/
@Override
public String createNewCompositeApiVersion(String apiId, String newVersion) throws APIManagementException {
// 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);
}
String newVersionedId;
try {
CompositeAPI api = getApiDAO().getCompositeAPI(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);
}
CompositeAPI.Builder apiBuilder = new CompositeAPI.Builder(api);
apiBuilder.id(UUID.randomUUID().toString());
apiBuilder.version(newVersion);
apiBuilder.context(api.getContext().replace(api.getVersion(), newVersion));
apiBuilder.copiedFromApiId(api.getId());
if (StringUtils.isEmpty(apiBuilder.getApiDefinition())) {
apiBuilder.apiDefinition(apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder));
}
getApiDAO().addApplicationAssociatedAPI(apiBuilder.build());
newVersionedId = apiBuilder.getId();
} catch (APIMgtDAOException e) {
String errorMsg = "Couldn't create new API version from " + apiId;
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
}
return newVersionedId;
}
use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.
the class APIDefinitionFromSwagger20TestCase method testAddNewScopeToNonExistingSecurityDefinition.
@Test()
public void testAddNewScopeToNonExistingSecurityDefinition() throws IOException, APIManagementException {
APIDefinitionFromSwagger20 apiDefinitionFromSwagger20 = new APIDefinitionFromSwagger20();
String sampleApi = IOUtils.toString(this.getClass().getResourceAsStream(File.separator + "swagger" + File.separator + "swaggerWithOutAuthorization.yaml"));
Scope scope = new Scope();
scope.setName("apim:api_delete");
scope.setDescription("Delete API");
String scopeAddedSwagger = apiDefinitionFromSwagger20.addScopeToSwaggerDefinition(sampleApi, scope);
Map<String, String> scopes = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(scopeAddedSwagger);
Assert.assertTrue(scopes.containsKey("apim:api_delete"));
}
use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.
the class APIDefinitionFromSwagger20TestCase method testGenerateMergedResourceDefinitionWhileAddingRootLevelSecurity.
@Test
public void testGenerateMergedResourceDefinitionWhileAddingRootLevelSecurity() throws IOException {
APIDefinitionFromSwagger20 apiDefinitionFromSwagger20 = new APIDefinitionFromSwagger20();
String sampleApi = IOUtils.toString(this.getClass().getResourceAsStream(File.separator + "swagger" + File.separator + "swaggerWithoutRootLevelSecurity.yaml"));
UriTemplate uriTemplate1 = new UriTemplate.UriTemplateBuilder().uriTemplate("/apis").httpVerb("post").scopes(Arrays.asList("apim:api_create")).build();
UriTemplate uriTemplate2 = new UriTemplate.UriTemplateBuilder().uriTemplate("/endpoints").httpVerb("post").scopes(Arrays.asList("apim:api_create")).build();
Map<String, UriTemplate> hasTemplateMap = new HashMap<>();
hasTemplateMap.put(APIUtils.generateOperationIdFromPath(uriTemplate1.getUriTemplate(), uriTemplate1.getHttpVerb()), uriTemplate1);
hasTemplateMap.put(APIUtils.generateOperationIdFromPath(uriTemplate2.getUriTemplate(), uriTemplate2.getHttpVerb()), uriTemplate2);
API api = new API.APIBuilder("admin", "admin", "1.0.0").uriTemplates(hasTemplateMap).id(UUID.randomUUID().toString()).scopes(Arrays.asList("apim:api_create")).build();
apiDefinitionFromSwagger20.generateMergedResourceDefinition(sampleApi, api);
}
Aggregations