use of org.wso2.carbon.apimgt.core.template.APIConfigContext in project carbon-apimgt by wso2.
the class APIPublisherImpl method addAPI.
/**
* Adds a new API to the system
*
* @param apiBuilder API model object
* @return UUID of the added API.
* @throws APIManagementException if failed to add API
*/
@Override
public String addAPI(API.APIBuilder apiBuilder) throws APIManagementException {
API createdAPI;
APIGateway gateway = getApiGateway();
apiBuilder.provider(getUsername());
if (StringUtils.isEmpty(apiBuilder.getId())) {
apiBuilder.id(UUID.randomUUID().toString());
}
LocalDateTime localDateTime = LocalDateTime.now();
apiBuilder.createdTime(localDateTime);
apiBuilder.lastUpdatedTime(localDateTime);
apiBuilder.createdBy(getUsername());
apiBuilder.updatedBy(getUsername());
if (apiBuilder.getLabels().isEmpty()) {
List<String> labelSet = new ArrayList<>();
labelSet.add(getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_GATEWAY));
labelSet.add(getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_STORE));
apiBuilder.labels(labelSet);
}
Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
validateEndpoints(apiEndpointMap, false);
try {
if (!isApiNameExist(apiBuilder.getName()) && !isContextExist(apiBuilder.getContext())) {
LifecycleState lifecycleState = getApiLifecycleManager().addLifecycle(APIMgtConstants.API_LIFECYCLE, getUsername());
apiBuilder.associateLifecycle(lifecycleState);
createUriTemplateList(apiBuilder, false);
List<UriTemplate> list = new ArrayList<>(apiBuilder.getUriTemplates().values());
List<TemplateBuilderDTO> resourceList = new ArrayList<>();
validateApiPolicy(apiBuilder.getApiPolicy());
validateSubscriptionPolicies(apiBuilder);
for (UriTemplate uriTemplate : list) {
TemplateBuilderDTO dto = new TemplateBuilderDTO();
dto.setTemplateId(uriTemplate.getTemplateId());
dto.setUriTemplate(uriTemplate.getUriTemplate());
dto.setHttpVerb(uriTemplate.getHttpVerb());
Map<String, Endpoint> map = uriTemplate.getEndpoint();
if (map.containsKey(APIMgtConstants.PRODUCTION_ENDPOINT)) {
Endpoint endpoint = map.get(APIMgtConstants.PRODUCTION_ENDPOINT);
dto.setProductionEndpoint(endpoint);
}
if (map.containsKey(APIMgtConstants.SANDBOX_ENDPOINT)) {
Endpoint endpoint = map.get(APIMgtConstants.SANDBOX_ENDPOINT);
dto.setSandboxEndpoint(endpoint);
}
resourceList.add(dto);
}
GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
String gatewayConfig = gatewaySourceGenerator.getConfigStringFromTemplate(resourceList);
if (log.isDebugEnabled()) {
log.debug("API " + apiBuilder.getName() + "gateway config: " + gatewayConfig);
}
apiBuilder.gatewayConfig(gatewayConfig);
if (StringUtils.isEmpty(apiBuilder.getApiDefinition())) {
apiBuilder.apiDefinition(apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder));
}
if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
Map<String, Integer> roleNamePermissionList;
roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
apiBuilder.permissionMap(roleNamePermissionList);
}
createdAPI = apiBuilder.build();
APIUtils.validate(createdAPI);
// Add API to gateway
gateway.addAPI(createdAPI);
if (log.isDebugEnabled()) {
log.debug("API : " + apiBuilder.getName() + " has been identifier published to gateway");
}
Set<String> apiRoleList;
// if the API has role based visibility, add the API with role checking
if (API.Visibility.PUBLIC == createdAPI.getVisibility()) {
getApiDAO().addAPI(createdAPI);
} else if (API.Visibility.RESTRICTED == createdAPI.getVisibility()) {
// get all the roles in the system
Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
// get the roles needed to be associated with the API
apiRoleList = createdAPI.getVisibleRoles();
if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
getApiDAO().addAPI(createdAPI);
}
}
APIUtils.logDebug("API " + createdAPI.getName() + "-" + createdAPI.getVersion() + " was created " + "successfully.", log);
// 'API_M Functions' related code
// Create a payload with event specific details
Map<String, String> eventPayload = new HashMap<>();
eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, createdAPI.getId());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, createdAPI.getName());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, createdAPI.getVersion());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, createdAPI.getDescription());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, createdAPI.getContext());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, createdAPI.getLifeCycleStatus());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_PERMISSION, createdAPI.getApiPermission());
// This will notify all the EventObservers(Asynchronous)
ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_CREATION, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
} else {
String message = "Duplicate API already Exist with name/Context " + apiBuilder.getName();
log.error(message);
throw new APIManagementException(message, ExceptionCodes.API_ALREADY_EXISTS);
}
} catch (APIMgtDAOException e) {
String errorMsg = "Error occurred while creating the API - " + apiBuilder.getName();
log.error(errorMsg);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
} catch (LifecycleException | ParseException e) {
String errorMsg = "Error occurred while Associating the API - " + apiBuilder.getName();
log.error(errorMsg);
throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
} catch (APITemplateException e) {
String message = "Error generating API configuration for API " + apiBuilder.getName();
log.error(message, e);
throw new APIManagementException(message, ExceptionCodes.TEMPLATE_EXCEPTION);
} catch (GatewayException e) {
String message = "Error occurred while adding API - " + apiBuilder.getName() + " to gateway";
log.error(message, e);
throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
}
return apiBuilder.getId();
}
use of org.wso2.carbon.apimgt.core.template.APIConfigContext in project carbon-apimgt by wso2.
the class APIPublisherImpl method updateApiGatewayConfig.
/**
* {@inheritDoc}
*/
@Override
public void updateApiGatewayConfig(String apiId, String configString) throws APIManagementException {
API api = getAPIbyUUID(apiId);
GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
APIConfigContext apiConfigContext = new APIConfigContext(api, config.getGatewayPackageName());
gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
try {
String swagger = gatewaySourceGenerator.getSwaggerFromGatewayConfig(configString);
getApiDAO().updateApiDefinition(apiId, swagger, getUsername());
getApiDAO().updateGatewayConfig(apiId, configString, getUsername());
} catch (APIMgtDAOException e) {
log.error("Couldn't update configuration for apiId " + apiId, e);
throw new APIManagementException("Couldn't update configuration for apiId " + apiId, e.getErrorHandler());
} catch (APITemplateException e) {
log.error("Error generating swagger from gateway config " + apiId, e);
throw new APIManagementException("Error generating swagger from gateway config " + apiId, ExceptionCodes.TEMPLATE_EXCEPTION);
}
}
use of org.wso2.carbon.apimgt.core.template.APIConfigContext in project carbon-apimgt by wso2.
the class APIPublisherImpl method updateAPI.
/**
* Updates design and implementation of an existing API. This method must not be used to change API status.
* Implementations should throw an exceptions when such attempts are made. All life cycle state changes
* should be carried out using the changeAPIStatus method of this interface.
*
* @param apiBuilder {@code org.wso2.carbon.apimgt.core.models.API.APIBuilder} model object
* @throws APIManagementException if failed to update API
*/
@Override
public void updateAPI(API.APIBuilder apiBuilder) throws APIManagementException {
APIGateway gateway = getApiGateway();
apiBuilder.provider(getUsername());
apiBuilder.updatedBy(getUsername());
try {
API originalAPI = getAPIbyUUID(apiBuilder.getId());
if (originalAPI != null) {
// Checks whether the logged in user has the "UPDATE" permission for the API
verifyUserPermissionsToUpdateAPI(getUsername(), originalAPI);
apiBuilder.createdTime(originalAPI.getCreatedTime());
// workflow status is an internal property and shouldn't be allowed to update externally
apiBuilder.workflowStatus(originalAPI.getWorkflowStatus());
if ((originalAPI.getName().equals(apiBuilder.getName())) && (originalAPI.getVersion().equals(apiBuilder.getVersion())) && (originalAPI.getProvider().equals(apiBuilder.getProvider())) && originalAPI.getLifeCycleStatus().equalsIgnoreCase(apiBuilder.getLifeCycleStatus())) {
if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
apiBuilder.apiPermission(replaceGroupNamesWithId(apiBuilder.getApiPermission()));
Map<String, Integer> roleNamePermissionList;
roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
apiBuilder.permissionMap(roleNamePermissionList);
}
Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
validateEndpoints(apiEndpointMap, true);
validateLabels(apiBuilder.getLabels(), originalAPI.hasOwnGateway());
createUriTemplateList(apiBuilder, true);
validateApiPolicy(apiBuilder.getApiPolicy());
validateSubscriptionPolicies(apiBuilder);
String updatedSwagger = apiDefinitionFromSwagger20.generateMergedResourceDefinition(getApiDAO().getApiSwaggerDefinition(apiBuilder.getId()), apiBuilder.build());
String gatewayConfig = getApiGatewayConfig(apiBuilder.getId());
GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(gatewayConfig, updatedSwagger);
API api = apiBuilder.build();
// Add API to gateway
gateway.updateAPI(api);
if (log.isDebugEnabled()) {
log.debug("API : " + apiBuilder.getName() + " has been successfully updated in gateway");
}
if (originalAPI.getContext() != null && !originalAPI.getContext().equals(apiBuilder.getContext())) {
if (!checkIfAPIContextExists(api.getContext())) {
// if the API has public visibility, update the API without any role checking
if (API.Visibility.PUBLIC == api.getVisibility()) {
getApiDAO().updateAPI(api.getId(), api);
} else if (API.Visibility.RESTRICTED == api.getVisibility()) {
// get all the roles in the system
Set<String> availableRoles = APIUtils.getAllAvailableRoles();
// get the roles needed to be associated with the API
Set<String> apiRoleList = api.getVisibleRoles();
// if the API has role based visibility, update the API with role checking
if (APIUtils.checkAllowedRoles(availableRoles, apiRoleList)) {
getApiDAO().updateAPI(api.getId(), api);
}
}
getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
} else {
throw new APIManagementException("Context already Exist", ExceptionCodes.API_ALREADY_EXISTS);
}
} else {
// if the API has public visibility, update the API without any role checking
if (API.Visibility.PUBLIC == api.getVisibility()) {
getApiDAO().updateAPI(api.getId(), api);
} else if (API.Visibility.RESTRICTED == api.getVisibility()) {
// get all the roles in the system
Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
// get the roles needed to be associated with the API
Set<String> apiRoleList = api.getVisibleRoles();
// if the API has role based visibility, update the API with role checking
if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
getApiDAO().updateAPI(api.getId(), api);
}
}
getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
}
if (log.isDebugEnabled()) {
log.debug("API " + api.getName() + "-" + api.getVersion() + " was updated successfully.");
// '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_DESCRIPTION, api.getDescription());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, api.getContext());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, api.getLifeCycleStatus());
// This will notify all the EventObservers(Asynchronous)
ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_UPDATE, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
}
} else {
APIUtils.verifyValidityOfApiUpdate(apiBuilder, originalAPI);
}
} else {
log.error("Couldn't found API with ID " + apiBuilder.getId());
throw new APIManagementException("Couldn't found API with ID " + apiBuilder.getId(), ExceptionCodes.API_NOT_FOUND);
}
} catch (APIMgtDAOException e) {
String errorMsg = "Error occurred while updating the API - " + apiBuilder.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 - " + apiBuilder.getName();
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION);
} catch (GatewayException e) {
String message = "Error occurred while updating API - " + apiBuilder.getName() + " in gateway";
log.error(message, e);
throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
}
}
use of org.wso2.carbon.apimgt.core.template.APIConfigContext in project carbon-apimgt by wso2.
the class GatewaySourceGeneratorImpl method getConfigStringFromTemplate.
@Override
public String getConfigStringFromTemplate(List<TemplateBuilderDTO> apiResources) throws APITemplateException {
StringWriter writer = new StringWriter();
String templatePath = "resources" + File.separator + "template" + File.separator + "template.xml";
try {
// build the context for template and apply the necessary decorators
apiConfigContext.validate();
ConfigContext configContext = new ResourceConfigContext(apiConfigContext, apiResources);
VelocityContext context = configContext.getContext();
VelocityEngine velocityengine = new VelocityEngine();
velocityengine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityengine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute());
velocityengine.init();
Template template = velocityengine.getTemplate(templatePath);
template.merge(context, writer);
} catch (ResourceNotFoundException e) {
log.error("Template " + templatePath + " not Found", e);
throw new APITemplateException("Template " + templatePath + " not Found", ExceptionCodes.TEMPLATE_EXCEPTION);
} catch (ParseErrorException e) {
log.error("Syntax error in " + templatePath, e);
throw new APITemplateException("Syntax error in " + templatePath, ExceptionCodes.TEMPLATE_EXCEPTION);
}
return writer.toString();
}
use of org.wso2.carbon.apimgt.core.template.APIConfigContext in project carbon-apimgt by wso2.
the class GatewaySourceGeneratorImpl method getCompositeAPIConfigStringFromTemplate.
@Override
public String getCompositeAPIConfigStringFromTemplate(List<TemplateBuilderDTO> apiResources, List<CompositeAPIEndpointDTO> compositeApiEndpoints) throws APITemplateException {
StringWriter writer = new StringWriter();
String templatePath = "resources" + File.separator + "template" + File.separator + "composite_template.xml";
try {
// build the context for template and apply the necessary decorators
apiConfigContext.validate();
CompositeAPIConfigContext configContext = new CompositeAPIConfigContext(apiConfigContext, apiResources, compositeApiEndpoints);
VelocityContext context = configContext.getContext();
VelocityEngine velocityengine = new VelocityEngine();
velocityengine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityengine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute());
velocityengine.init();
Template template = velocityengine.getTemplate(templatePath);
template.merge(context, writer);
} catch (ResourceNotFoundException e) {
log.error("Template " + templatePath + " not Found", e);
throw new APITemplateException("Template " + templatePath + " not Found", ExceptionCodes.TEMPLATE_EXCEPTION);
} catch (ParseErrorException e) {
log.error("Syntax error in " + templatePath, e);
throw new APITemplateException("Syntax error in " + templatePath, ExceptionCodes.TEMPLATE_EXCEPTION);
}
return writer.toString();
}
Aggregations