use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class ApiDAOImpl method getUriTemplates.
private Map<String, UriTemplate> getUriTemplates(Connection connection, String apiId) throws SQLException, IOException {
final String query = "SELECT operationMapping.OPERATION_ID AS OPERATION_ID,operationMapping.API_ID AS API_ID," + "operationMapping.HTTP_METHOD AS HTTP_METHOD,operationMapping.URL_PATTERN AS URL_PATTERN," + "operationMapping.AUTH_SCHEME AS AUTH_SCHEME,operationMapping.API_POLICY_ID AS API_POLICY_ID FROM " + "AM_API_OPERATION_MAPPING operationMapping WHERE operationMapping.API_ID = ?";
Map<String, UriTemplate> uriTemplateSet = new HashMap();
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, apiId);
statement.execute();
try (ResultSet rs = statement.getResultSet()) {
while (rs.next()) {
UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder().uriTemplate(rs.getString("URL_PATTERN")).authType(rs.getString("AUTH_SCHEME")).httpVerb(rs.getString("HTTP_METHOD")).templateId(rs.getString("OPERATION_ID")).endpoint(getEndPointsForOperation(connection, apiId, rs.getString("OPERATION_ID")));
String apiPolicyId = rs.getString("API_POLICY_ID");
if (StringUtils.isNotEmpty(apiPolicyId)) {
uriTemplateBuilder.policy(getApiPolicyByUuid(connection, apiPolicyId));
}
uriTemplateSet.put(uriTemplateBuilder.build().getTemplateId(), uriTemplateBuilder.build());
}
}
}
return uriTemplateSet;
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class ApiDAOImpl method getResourcesOfApi.
/**
* @see org.wso2.carbon.apimgt.core.dao.ApiDAO#getResourcesOfApi(String, String)
*/
@Override
public List<UriTemplate> getResourcesOfApi(String apiContext, String apiVersion) throws APIMgtDAOException {
final String query = "SELECT operationMapping.OPERATION_ID AS OPERATION_ID,operationMapping.HTTP_METHOD AS " + "HTTP_METHOD,operationMapping.URL_PATTERN AS URL_PATTERN,operationMapping.AUTH_SCHEME AS AUTH_SCHEME," + "operationMapping.API_POLICY_ID AS API_POLICY_ID FROM AM_API_OPERATION_MAPPING operationMapping," + "AM_API api WHERE operationMapping.API_ID = api.UUID AND api.CONTEXT = ? AND api.VERSION = ?";
List<UriTemplate> uriTemplates = new ArrayList<>();
try (Connection connection = DAOUtil.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setString(1, apiContext);
preparedStatement.setString(2, apiVersion);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
UriTemplate uriTemplate = new UriTemplate.UriTemplateBuilder().uriTemplate(resultSet.getString("URL_PATTERN")).authType(resultSet.getString("AUTH_SCHEME")).httpVerb(resultSet.getString("HTTP_METHOD")).policy(new APIPolicy(resultSet.getString("API_POLICY_ID"), "")).templateId(resultSet.getString("OPERATION_ID")).build();
uriTemplates.add(uriTemplate);
}
}
} catch (SQLException e) {
String msg = "getting API resources for Context: " + apiContext + ", Version: " + apiVersion;
throw new APIMgtDAOException(DAOUtil.DAO_ERROR_PREFIX + msg, e);
}
return uriTemplates;
}
use of org.wso2.carbon.apimgt.api.model.URITemplate 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.api.model.URITemplate in project carbon-apimgt by wso2.
the class APIDefinitionFromSwagger20 method generateCompositeApiFromSwaggerResource.
@Override
public CompositeAPI.Builder generateCompositeApiFromSwaggerResource(String provider, String apiDefinition) throws APIManagementException {
SwaggerParser swaggerParser = new SwaggerParser();
Swagger swagger = swaggerParser.parse(apiDefinition);
if (swagger == null) {
throw new APIManagementException("Swagger could not be generated from provided API definition");
}
Info apiInfo = swagger.getInfo();
if (apiInfo == null) {
throw new APIManagementException("Provided Swagger definition doesn't contain API information");
} else {
String apiName = apiInfo.getTitle();
String apiVersion = apiInfo.getVersion();
String apiDescription = apiInfo.getDescription();
CompositeAPI.Builder apiBuilder = new CompositeAPI.Builder().provider(provider).name(apiName).version(apiVersion).description(apiDescription).context(swagger.getBasePath());
List<APIResource> apiResourceList = parseSwaggerAPIResources(new StringBuilder(apiDefinition));
Map<String, UriTemplate> uriTemplateMap = new HashMap();
for (APIResource apiResource : apiResourceList) {
uriTemplateMap.put(apiResource.getUriTemplate().getTemplateId(), apiResource.getUriTemplate());
}
apiBuilder.uriTemplates(uriTemplateMap);
apiBuilder.id(UUID.randomUUID().toString());
return apiBuilder;
}
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class APIDefinitionFromSwagger20 method generateSwaggerFromResources.
@Override
public String generateSwaggerFromResources(CompositeAPI.Builder api) {
Swagger swagger = new Swagger();
Info info = new Info();
info.setTitle(api.getName());
info.setDescription(api.getDescription());
info.setVersion(api.getVersion());
swagger.setInfo(info);
Map<String, Path> stringPathMap = new HashMap();
for (UriTemplate uriTemplate : api.getUriTemplates().values()) {
String uriTemplateString = uriTemplate.getUriTemplate();
List<Parameter> parameterList = getParameters(uriTemplateString);
if (!HttpMethod.GET.toString().equalsIgnoreCase(uriTemplate.getHttpVerb()) && !HttpMethod.DELETE.toString().equalsIgnoreCase(uriTemplate.getHttpVerb()) && !HttpMethod.OPTIONS.toString().equalsIgnoreCase(uriTemplate.getHttpVerb()) && !HttpMethod.HEAD.toString().equalsIgnoreCase(uriTemplate.getHttpVerb())) {
parameterList.add(getDefaultBodyParameter());
}
Operation operation = new Operation();
operation.setParameters(parameterList);
operation.setOperationId(uriTemplate.getTemplateId());
operation.addResponse("200", getDefaultResponse());
if (stringPathMap.containsKey(uriTemplateString)) {
Path path = stringPathMap.get(uriTemplateString);
path.set(uriTemplate.getHttpVerb().toLowerCase(), operation);
} else {
Path path = new Path();
path.set(uriTemplate.getHttpVerb().toLowerCase(), operation);
stringPathMap.put(uriTemplateString, path);
}
}
swagger.setPaths(stringPathMap);
swagger.setPaths(stringPathMap);
return Json.pretty(swagger);
}
Aggregations