use of org.wso2.carbon.device.mgt.common.operation.mgt.Operation in project carbon-apimgt by wso2.
the class APIMWSDLUtils method getUriTemplatesForWSDLOperations.
/**
* Generates URI templates to be assigned to an API from a set of operations extracted from WSDL.
*
* @param operations a Set of {@link WSDLOperation} objects
* @return Map of URI Templates
*/
public static Map<String, UriTemplate> getUriTemplatesForWSDLOperations(Set<WSDLOperation> operations, boolean isHttpBinding) {
Map<String, UriTemplate> uriTemplateMap = new HashMap<>();
// add default "POST /" operation if no http binding methods required or operations are not provided
if (!isHttpBinding || operations == null || operations.isEmpty()) {
if (log.isDebugEnabled()) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Adding the POST / operation. ");
stringBuilder.append("isHttpBinding: ").append(isHttpBinding).append(". ");
stringBuilder.append("operations are null?: ").append(operations == null).append(". ");
if (operations != null) {
stringBuilder.append("operations are empty?: ").append(operations.isEmpty()).append(". ");
}
log.debug(stringBuilder.toString());
}
UriTemplate.UriTemplateBuilder builderForPOSTRootCtx = new UriTemplate.UriTemplateBuilder();
builderForPOSTRootCtx.uriTemplate("/");
builderForPOSTRootCtx.httpVerb("POST");
builderForPOSTRootCtx.policy(APIUtils.getDefaultAPIPolicy());
builderForPOSTRootCtx.templateId(APIUtils.generateOperationIdFromPath("/", "POST"));
uriTemplateMap.put(builderForPOSTRootCtx.getTemplateId(), builderForPOSTRootCtx.build());
return uriTemplateMap;
}
// add URI templates for operations
for (WSDLOperation operation : operations) {
if (log.isDebugEnabled()) {
log.debug("Adding URI template for WSDL operation: " + operation.getVerb() + ", " + operation.getURI());
}
UriTemplate.UriTemplateBuilder builder = new UriTemplate.UriTemplateBuilder();
builder.uriTemplate(operation.getURI().startsWith("/") ? operation.getURI() : "/" + operation.getURI());
builder.httpVerb(operation.getVerb());
builder.policy(APIUtils.getDefaultAPIPolicy());
builder.templateId(APIUtils.generateOperationIdFromPath(builder.getUriTemplate(), operation.getVerb()));
builder.contentType(operation.getContentType());
List<URITemplateParam> uriTemplateParams = getUriTemplatesParamsForWSDLOperationParams(operation.getParameters());
builder.parameters(uriTemplateParams);
uriTemplateMap.put(builder.getTemplateId(), builder.build());
}
return uriTemplateMap;
}
use of org.wso2.carbon.device.mgt.common.operation.mgt.Operation in project carbon-apimgt by wso2.
the class LabelsApiServiceImpl method labelsLabelIdDelete.
/**
* Delete label by label id
*
* @param labelId Id of the label
* @param request msf4j request object
* @return 200 OK if the operation is successful
* @throws NotFoundException If failed to find the particular resource
*/
@Override
public Response labelsLabelIdDelete(String labelId, Request request) throws NotFoundException {
try {
if (labelId != null) {
APIMgtAdminService apiMgtAdminService = RestApiUtil.getAPIMgtAdminService();
apiMgtAdminService.deleteLabel(labelId);
} else {
// mandatory parameters not provided
String errorMessage = "Label Id parameter should be provided";
ErrorHandler errorHandler = ExceptionCodes.PARAMETER_NOT_PROVIDED;
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorHandler);
log.error(errorMessage);
return Response.status(errorHandler.getHttpStatusCode()).entity(errorDTO).build();
}
} catch (APIManagementException e) {
String errorMessage = "Error occurred while deleting the label [labelId] " + labelId;
HashMap<String, String> paramList = new HashMap<String, String>();
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
log.error(errorMessage, e);
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
}
return Response.status(Response.Status.NO_CONTENT).build();
}
use of org.wso2.carbon.device.mgt.common.operation.mgt.Operation in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method apisApiIdDedicatedGatewayPut.
/**
* Add or update Dedicated Gateway of an API
*
* @param apiId UUID of API
* @param body DedicatedGatewayDTO
* @param ifMatch If-Match header value
* @param ifUnmodifiedSince If-Unmodified-Since header value
* @param request msf4j request object
* @return 200 OK if the operation was successful
* @throws NotFoundException when the particular resource does not exist
*/
@Override
public Response apisApiIdDedicatedGatewayPut(String apiId, DedicatedGatewayDTO body, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
String username = RestApiUtil.getLoggedInUsername(request);
try {
APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
if (!apiPublisher.isAPIExists(apiId)) {
String errorMessage = "API not found : " + apiId;
APIMgtResourceNotFoundException e = new APIMgtResourceNotFoundException(errorMessage, ExceptionCodes.API_NOT_FOUND);
HashMap<String, String> paramList = new HashMap<String, String>();
paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
log.error(errorMessage, e);
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
}
String existingFingerprint = apisApiIdGetFingerprint(apiId, null, null, request);
if (!StringUtils.isEmpty(ifMatch) && !StringUtils.isEmpty(existingFingerprint) && !ifMatch.contains(existingFingerprint)) {
return Response.status(Response.Status.PRECONDITION_FAILED).build();
}
DedicatedGateway dedicatedGateway = MappingUtil.fromDTOtoDedicatedGateway(body, apiId, username);
apiPublisher.updateDedicatedGateway(dedicatedGateway);
DedicatedGateway updatedDedicatedGateway = apiPublisher.getDedicatedGateway(apiId);
String newFingerprint = apisApiIdGetFingerprint(apiId, null, null, request);
return Response.ok().header(HttpHeaders.ETAG, "\"" + newFingerprint + "\"").entity(MappingUtil.toDedicatedGatewayDTO(updatedDedicatedGateway)).build();
} catch (APIManagementException e) {
String errorMessage = "Error while updating dedicated gateway of the API : " + apiId;
HashMap<String, String> paramList = new HashMap<String, String>();
paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
log.error(errorMessage, e);
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
}
}
use of org.wso2.carbon.device.mgt.common.operation.mgt.Operation in project carbon-apimgt by wso2.
the class APIPublisherImpl method getAPIPermissionsOfLoggedInUser.
/**
* This method retrieves the set of overall permissions for a given api for the logged in user
*
* @param loggedInUserName - Logged in user
* @param api - The API whose permissions for the logged in user is retrieved
* @return The overall list of permissions for the given API for the logged in user
*/
private List<String> getAPIPermissionsOfLoggedInUser(String loggedInUserName, API api) throws APIManagementException {
Set<String> permissionArrayForUser = new HashSet<>();
Map<String, Integer> permissionMap = api.getPermissionMap();
String provider = api.getProvider();
// TODO: Remove the check for admin after IS adds an ID to admin user
if (loggedInUserName.equals(provider) || permissionMap == null || permissionMap.isEmpty() || "admin".equals(loggedInUserName)) {
permissionArrayForUser.add(APIMgtConstants.Permission.READ);
permissionArrayForUser.add(APIMgtConstants.Permission.UPDATE);
permissionArrayForUser.add(APIMgtConstants.Permission.DELETE);
permissionArrayForUser.add(APIMgtConstants.Permission.MANAGE_SUBSCRIPTION);
} else {
try {
String userId = getIdentityProvider().getIdOfUser(loggedInUserName);
List<String> loggedInUserRoles = getIdentityProvider().getRoleIdsOfUser(userId);
List<String> permissionRoleList = getRolesFromPermissionMap(permissionMap);
List<String> rolesOfUserWithAPIPermissions = null;
// To prevent a possible null pointer exception
if (loggedInUserRoles == null) {
loggedInUserRoles = new ArrayList<>();
}
// get the intersection - retainAll() transforms first set to the result of intersection
loggedInUserRoles.retainAll(permissionRoleList);
if (!loggedInUserRoles.isEmpty()) {
rolesOfUserWithAPIPermissions = loggedInUserRoles;
}
if (rolesOfUserWithAPIPermissions != null) {
Integer aggregatePermissions = 0;
// Calculating aggregate permissions using Bitwise OR operation
for (String role : rolesOfUserWithAPIPermissions) {
aggregatePermissions |= permissionMap.get(role);
}
permissionArrayForUser = new HashSet<>(APIUtils.constructApiPermissionsListForValue(aggregatePermissions));
}
} catch (IdentityProviderException e) {
String errorMsg = "Error occurred while calling SCIM endpoint to retrieve user " + loggedInUserName + "'s information";
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
}
}
List<String> finalAggregatedPermissionList = new ArrayList<>();
finalAggregatedPermissionList.addAll(permissionArrayForUser);
if (log.isDebugEnabled()) {
String message = "Aggregate permissions of user " + loggedInUserName + " for the API " + api.getName() + " are " + StringUtils.join(finalAggregatedPermissionList, ", ") + ".";
log.debug(message);
}
return finalAggregatedPermissionList;
}
use of org.wso2.carbon.device.mgt.common.operation.mgt.Operation in project carbon-apimgt by wso2.
the class ApiImportExportManager method getAPIDetails.
/**
* Retrieves all API details of the APIs for the given search query. API details consist of:
* 1. API {@link org.wso2.carbon.apimgt.core.models.API}
* 2. Document Info {@link org.wso2.carbon.apimgt.core.models.DocumentInfo}
* 3. Document Content {@link org.wso2.carbon.apimgt.core.models.DocumentContent}
* 4. Swagger Definition
* 5. Gateway Definition
* 6. Thumbnail content
*
* @param limit number of max results
* @param offset starting location when returning a limited set of results
* @param query searchQuery
* @return {@link APIDetails} instance
* @throws APIManagementException if an error occurs while retrieving API details
*/
public Set<APIDetails> getAPIDetails(Integer limit, Integer offset, String query) throws APIManagementException {
Set<APIDetails> apiDetailSet = new HashSet<>();
// search for APIs
List<API> apis = apiPublisher.searchAPIs(limit, offset, query);
if (apis == null || apis.isEmpty()) {
// no APIs found, return
return apiDetailSet;
}
// iterate and collect all information
for (API api : apis) {
api = apiPublisher.getAPIbyUUID(api.getId());
// get endpoints at API Level
Map<String, Endpoint> endpoints = api.getEndpoint();
if (endpoints.isEmpty()) {
log.error("No Endpoints found for api: " + api.getName() + ", version: " + api.getVersion());
// skip this API
// continue;
}
Set<Endpoint> endpointSet = new HashSet<>();
for (Map.Entry<String, Endpoint> endpointEntry : endpoints.entrySet()) {
if (APIMgtConstants.GLOBAL_ENDPOINT.equals(endpointEntry.getValue().getApplicableLevel())) {
Endpoint endpoint = new Endpoint.Builder(apiPublisher.getEndpoint(endpointEntry.getValue().getId())).id("").build();
endpoints.replace(endpointEntry.getKey(), endpoint);
endpointSet.add(endpoint);
}
}
// get Endpoints at Resource Level
Map<String, UriTemplate> uriTemplateMap = api.getUriTemplates();
uriTemplateMap.forEach((k, v) -> {
UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder(v);
Map<String, Endpoint> resourceEndpoints = uriTemplateBuilder.getEndpoint();
resourceEndpoints.forEach((type, value) -> {
Endpoint endpoint = null;
if (APIMgtConstants.GLOBAL_ENDPOINT.equals(value.getApplicableLevel())) {
try {
endpoint = new Endpoint.Builder(apiPublisher.getEndpoint(value.getId())).id("").build();
endpointSet.add(endpoint);
} catch (APIManagementException e) {
log.error("Error in getting endpoints for Resource: " + v.getTemplateId(), e);
}
} else {
endpoint = new Endpoint.Builder(value).id("").build();
}
resourceEndpoints.replace(type, endpoint);
});
uriTemplateMap.replace(k, uriTemplateBuilder.endpoint(resourceEndpoints).build());
});
api = new API.APIBuilder(api).endpoint(endpoints).uriTemplates(uriTemplateMap).build();
// get swagger definition
String swaggerDefinition;
try {
swaggerDefinition = apiPublisher.getApiSwaggerDefinition(api.getId());
} catch (APIManagementException e) {
log.error("Error in getting Swagger configuration for api: " + api.getName() + ", version: " + api.getVersion(), e);
// skip this API
continue;
}
// get gateway configuration
String gatewayConfig;
try {
gatewayConfig = apiPublisher.getApiGatewayConfig(api.getId());
} catch (APIManagementException e) {
log.error("Error in getting gateway configuration for api: " + api.getName() + ", version: " + api.getVersion(), e);
// skip this API
continue;
}
// get doc information
List<DocumentInfo> documentInfo = null;
try {
documentInfo = apiPublisher.getAllDocumentation(api.getId(), 0, Integer.MAX_VALUE);
} catch (APIManagementException e) {
log.error("Error in getting documentation content for api: " + api.getName() + ", version: " + api.getVersion(), e);
// no need to skip the API as docs don't affect API functionality
}
Set<DocumentContent> documentContents = new HashSet<>();
if (documentInfo != null && !documentInfo.isEmpty()) {
// iterate and collect document content
for (DocumentInfo aDocumentInfo : documentInfo) {
try {
documentContents.add(apiPublisher.getDocumentationContent(aDocumentInfo.getId()));
} catch (APIManagementException e) {
log.error("Error in getting documentation content for api: " + api.getName() + ", version: " + api.getVersion() + ", doc id: " + aDocumentInfo.getId(), e);
// no need to skip the API as docs don't affect API functionality
}
}
}
// get thumbnail
InputStream thumbnailStream = null;
try {
thumbnailStream = apiPublisher.getThumbnailImage(api.getId());
} catch (APIManagementException e) {
log.error("Error in getting thumbnail for api: " + api.getName() + ", version: " + api.getVersion(), e);
// no need to skip the API as thumbnail don't affect API functionality
}
// search operation returns a summary of APIs, need to get all details of APIs
APIDetails apiDetails = new APIDetails(api, swaggerDefinition);
apiDetails.setGatewayConfiguration(gatewayConfig);
apiDetails.setEndpoints(endpointSet);
if (documentInfo != null && !documentInfo.isEmpty()) {
apiDetails.addDocumentInformation(documentInfo);
}
if (!documentContents.isEmpty()) {
apiDetails.addDocumentContents(documentContents);
}
if (thumbnailStream != null) {
apiDetails.setThumbnailStream(thumbnailStream);
}
apiDetailSet.add(apiDetails);
}
return apiDetailSet;
}
Aggregations