Search in sources :

Example 51 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class APIMappingUtil method fromAPItoDTO.

public static APIDTO fromAPItoDTO(APIProduct model, String organization) throws APIManagementException {
    APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
    APIDTO dto = new APIDTO();
    dto.setName(model.getId().getName());
    dto.setVersion(model.getId().getVersion());
    String providerName = model.getId().getProviderName();
    dto.setProvider(APIUtil.replaceEmailDomainBack(providerName));
    dto.setId(model.getUuid());
    dto.setContext(model.getContext());
    dto.setDescription(model.getDescription());
    dto.setLifeCycleStatus(model.getState());
    dto.setType(model.getType());
    dto.setAvgRating(String.valueOf(model.getRating()));
    /* todo: created and last updated times
        if (null != model.getLastUpdated()) {
            Date lastUpdateDate = model.getLastUpdated();
            Timestamp timeStamp = new Timestamp(lastUpdateDate.getTime());
            dto.setLastUpdatedTime(String.valueOf(timeStamp));
        }

        String createdTimeStamp = model.getCreatedTime();
        if (null != createdTimeStamp) {
            Date date = new Date(Long.valueOf(createdTimeStamp));
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            String dateFormatted = formatter.format(date);
            dto.setCreatedTime(dateFormatted);
        } */
    String apiDefinition = null;
    if (model.isAsync()) {
        // for asyncAPI retrieve asyncapi.yml specification
        apiDefinition = apiConsumer.getAsyncAPIDefinition(model.getUuid(), organization);
    } else {
        // retrieve open API definition
        if (model.getDefinition() != null) {
            apiDefinition = model.getDefinition();
        } else {
            apiDefinition = apiConsumer.getOpenAPIDefinition(model.getUuid(), organization);
        }
    }
    dto.setApiDefinition(apiDefinition);
    Set<String> apiTags = model.getTags();
    List<String> tagsToReturn = new ArrayList<>();
    tagsToReturn.addAll(apiTags);
    dto.setTags(tagsToReturn);
    Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = model.getAvailableTiers();
    List<APITiersDTO> tiersToReturn = new ArrayList<>();
    // set the monetization status of this API (enabled or disabled)
    APIMonetizationInfoDTO monetizationInfoDTO = new APIMonetizationInfoDTO();
    monetizationInfoDTO.enabled(model.getMonetizationStatus());
    dto.setMonetization(monetizationInfoDTO);
    for (org.wso2.carbon.apimgt.api.model.Tier currentTier : apiTiers) {
        APITiersDTO apiTiersDTO = new APITiersDTO();
        apiTiersDTO.setTierName(currentTier.getName());
        apiTiersDTO.setTierPlan(currentTier.getTierPlan());
        // monetization attributes are applicable only for commercial tiers
        if (APIConstants.COMMERCIAL_TIER_PLAN.equalsIgnoreCase(currentTier.getTierPlan())) {
            APIMonetizationAttributesDTO monetizationAttributesDTO = new APIMonetizationAttributesDTO();
            if (MapUtils.isNotEmpty(currentTier.getMonetizationAttributes())) {
                Map<String, String> monetizationAttributes = currentTier.getMonetizationAttributes();
                // check the billing plan (fixed or price per request)
                if (!StringUtils.isBlank(monetizationAttributes.get(APIConstants.Monetization.FIXED_PRICE))) {
                    monetizationAttributesDTO.setFixedPrice(monetizationAttributes.get(APIConstants.Monetization.FIXED_PRICE));
                } else if (!StringUtils.isBlank(monetizationAttributes.get(APIConstants.Monetization.PRICE_PER_REQUEST))) {
                    monetizationAttributesDTO.setPricePerRequest(monetizationAttributes.get(APIConstants.Monetization.PRICE_PER_REQUEST));
                }
                monetizationAttributesDTO.setCurrencyType(monetizationAttributes.get(APIConstants.Monetization.CURRENCY) != null ? monetizationAttributes.get(APIConstants.Monetization.CURRENCY) : StringUtils.EMPTY);
                monetizationAttributesDTO.setBillingCycle(monetizationAttributes.get(APIConstants.Monetization.BILLING_CYCLE) != null ? monetizationAttributes.get(APIConstants.Monetization.BILLING_CYCLE) : StringUtils.EMPTY);
            }
            apiTiersDTO.setMonetizationAttributes(monetizationAttributesDTO);
        }
        tiersToReturn.add(apiTiersDTO);
    }
    dto.setTiers(tiersToReturn);
    List<APIOperationsDTO> operationList = new ArrayList<>();
    Map<String, ScopeInfoDTO> uniqueScopes = new HashMap<>();
    for (APIProductResource productResource : model.getProductResources()) {
        URITemplate uriTemplate = productResource.getUriTemplate();
        APIOperationsDTO operation = new APIOperationsDTO();
        operation.setTarget(uriTemplate.getUriTemplate());
        operation.setVerb(uriTemplate.getHTTPVerb());
        operationList.add(operation);
        List<Scope> scopes = uriTemplate.retrieveAllScopes();
        for (Scope scope : scopes) {
            if (!uniqueScopes.containsKey(scope.getKey())) {
                ScopeInfoDTO scopeInfoDTO = new ScopeInfoDTO().key(scope.getKey()).name(scope.getName()).description(scope.getDescription());
                if (StringUtils.isNotBlank(scope.getRoles())) {
                    scopeInfoDTO.roles(Arrays.asList(scope.getRoles().trim().split(",")));
                }
                uniqueScopes.put(scope.getKey(), scopeInfoDTO);
            }
        }
    }
    dto.setOperations(operationList);
    dto.setScopes(new ArrayList<>(uniqueScopes.values()));
    dto.setTransport(Arrays.asList(model.getTransports().split(",")));
    APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
    apiBusinessInformationDTO.setBusinessOwner(model.getBusinessOwner());
    apiBusinessInformationDTO.setBusinessOwnerEmail(model.getBusinessOwnerEmail());
    apiBusinessInformationDTO.setTechnicalOwner(model.getTechnicalOwner());
    apiBusinessInformationDTO.setTechnicalOwnerEmail(model.getTechnicalOwnerEmail());
    dto.setBusinessInformation(apiBusinessInformationDTO);
    if (!StringUtils.isBlank(model.getThumbnailUrl())) {
        dto.setHasThumbnail(true);
    }
    if (model.getAdditionalProperties() != null) {
        JSONObject additionalProperties = model.getAdditionalProperties();
        List<APIAdditionalPropertiesDTO> additionalPropertiesList = new ArrayList<>();
        for (Object propertyKey : additionalProperties.keySet()) {
            APIAdditionalPropertiesDTO additionalPropertiesDTO = new APIAdditionalPropertiesDTO();
            String key = (String) propertyKey;
            int index = key.lastIndexOf(APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX);
            additionalPropertiesDTO.setValue((String) additionalProperties.get(key));
            if (index > 0) {
                additionalPropertiesDTO.setName(key.substring(0, index));
                additionalPropertiesDTO.setDisplay(true);
                additionalPropertiesList.add(additionalPropertiesDTO);
            }
        }
        dto.setAdditionalProperties(additionalPropertiesList);
    }
    if (model.getEnvironments() != null) {
        List<String> environmentListToReturn = new ArrayList<>(model.getEnvironments());
        dto.setEnvironmentList(environmentListToReturn);
    }
    dto.setAuthorizationHeader(model.getAuthorizationHeader());
    if (model.getApiSecurity() != null) {
        dto.setSecurityScheme(Arrays.asList(model.getApiSecurity().split(",")));
    }
    // Since same APIInfoDTO is used for APIProduct in StoreUI set default AdvertisedInfo to the DTO
    AdvertiseInfoDTO advertiseInfoDTO = new AdvertiseInfoDTO();
    advertiseInfoDTO.setAdvertised(false);
    dto.setAdvertiseInfo(advertiseInfoDTO);
    String apiTenant = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(model.getId().getProviderName()));
    String subscriptionAvailability = model.getSubscriptionAvailability();
    String subscriptionAllowedTenants = model.getSubscriptionAvailableTenants();
    dto.setIsSubscriptionAvailable(isSubscriptionAvailable(apiTenant, subscriptionAvailability, subscriptionAllowedTenants));
    return dto;
}
Also used : AdvertiseInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdvertiseInfoDTO) HashMap(java.util.HashMap) APITiersDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APITiersDTO) ArrayList(java.util.ArrayList) APIAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIAdditionalPropertiesDTO) APIBusinessInformationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIBusinessInformationDTO) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) APIMonetizationInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIMonetizationInfoDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) Tier(org.wso2.carbon.apimgt.api.model.Tier) ScopeInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ScopeInfoDTO) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIOperationsDTO) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) APIMonetizationAttributesDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIMonetizationAttributesDTO)

Example 52 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method getAPIByAPIId.

private APIDTO getAPIByAPIId(String apiId, String organization) {
    try {
        APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
        ApiTypeWrapper api = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
        String status = api.getStatus();
        // Extracting clicked API name by the user, for the recommendation system
        String userName = RestApiCommonUtil.getLoggedInUsername();
        apiConsumer.publishClickedAPI(api, userName);
        if (APIConstants.PUBLISHED.equals(status) || APIConstants.PROTOTYPED.equals(status) || APIConstants.DEPRECATED.equals(status)) {
            return APIMappingUtil.fromAPItoDTO(api, organization);
        } else {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, log);
        }
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else {
            String errorMessage = "Error while retrieving API : " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

Example 53 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class CompositeApisApiServiceImpl method compositeApisApiIdPut.

/**
 * Updates an API by UUID
 *
 * @param apiId             UUID of API
 * @param body              Updated API details
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @param request           msf4j request object
 * @return Updated API
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response compositeApisApiIdPut(String apiId, CompositeAPIDTO body, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIStore apiStore = RestApiUtil.getConsumer(username);
        String existingFingerprint = compositeApisApiIdGetFingerprint(apiId, null, null, request);
        if (!StringUtils.isEmpty(ifMatch) && !StringUtils.isEmpty(existingFingerprint) && !ifMatch.contains(existingFingerprint)) {
            return Response.status(Response.Status.PRECONDITION_FAILED).build();
        }
        CompositeAPI.Builder api = CompositeAPIMappingUtil.toAPI(body).id(apiId);
        apiStore.updateCompositeApi(api);
        String newFingerprint = compositeApisApiIdGetFingerprint(apiId, null, null, request);
        CompositeAPIDTO apidto = CompositeAPIMappingUtil.toCompositeAPIDTO(apiStore.getCompositeAPIbyId(apiId));
        return Response.ok().header(HttpHeaders.ETAG, "\"" + newFingerprint + "\"").entity(apidto).build();
    } catch (APIManagementException e) {
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) CompositeAPIDTO(org.wso2.carbon.apimgt.rest.api.store.dto.CompositeAPIDTO) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Example 54 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class APIMappingUtil method toAPIDTO.

/**
 * Converts {@link APIDTO} to a {@link API}.
 *
 * @param api API
 * @return API DTO
 */
public static APIDTO toAPIDTO(API api) {
    APIDTO apiDTO = new APIDTO();
    apiDTO.setId(api.getId());
    apiDTO.setName(api.getName());
    apiDTO.setProvider(api.getProvider());
    apiDTO.setLifeCycleStatus(api.getLifeCycleStatus());
    apiDTO.setVersion(api.getVersion());
    apiDTO.setContext(api.getContext());
    apiDTO.setDescription(api.getDescription());
    api.getPolicies().forEach(policy -> apiDTO.addPoliciesItem(policy.getPolicyName()));
    apiDTO.setLabels(new ArrayList<>(api.getLabels()));
    return apiDTO;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.store.dto.APIDTO)

Example 55 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisImportDefinitionPost.

/**
 * Import an API from a Swagger or WSDL
 *
 * @param type                 definition type. If not specified, default will be SWAGGER
 * @param fileInputStream      file content stream, can be either archive or a single text file
 * @param fileDetail           file details
 * @param url                  URL of the definition
 * @param additionalProperties Additional attributes specified as a stringified JSON with API's schema
 * @param ifMatch              If-Match header value
 * @param ifUnmodifiedSince    If-Unmodified-Since header value
 * @param implementationType   WSDL based API implementation type (SOAP or HTTP_BINDING)
 * @param request              msf4j request object
 * @return Imported API
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apisImportDefinitionPost(String type, InputStream fileInputStream, FileInfo fileDetail, String url, String additionalProperties, String implementationType, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        if (StringUtils.isBlank(type)) {
            type = APIDefinitionValidationResponseDTO.DefinitionTypeEnum.SWAGGER.toString();
        }
        Response response = buildResponseIfParamsInvalid(type, fileInputStream, url);
        if (response != null) {
            return response;
        }
        API.APIBuilder apiBuilder = null;
        APIDTO additionalPropertiesAPI = null;
        if (!StringUtils.isBlank(additionalProperties)) {
            if (log.isDebugEnabled()) {
                log.debug("Deseriallizing additionalProperties: " + additionalProperties);
            }
            ObjectMapper mapper = new ObjectMapper();
            additionalPropertiesAPI = mapper.readValue(additionalProperties, APIDTO.class);
            apiBuilder = MappingUtil.toAPI(additionalPropertiesAPI);
            if (log.isDebugEnabled()) {
                log.debug("Successfully deseriallized additionalProperties: " + additionalProperties);
            }
        }
        APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
        String uuid = "";
        if (APIDefinitionValidationResponseDTO.DefinitionTypeEnum.SWAGGER.toString().equals(type)) {
            if (log.isDebugEnabled()) {
                log.debug("Adding an API by importing a swagger.");
            }
            if (fileInputStream != null) {
                uuid = apiPublisher.addApiFromDefinition(fileInputStream);
            } else {
                URL swaggerUrl = new URL(url);
                HttpURLConnection urlConn = (HttpURLConnection) swaggerUrl.openConnection();
                uuid = apiPublisher.addApiFromDefinition(urlConn);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Adding an API by importing a WSDL.");
            }
            // context, version when creating an API from WSDL
            if (additionalPropertiesAPI != null) {
                final String soap = RestApiConstants.IMPORT_DEFINITION_WSDL_IMPL_TYPE_SOAP;
                final String httpBinding = RestApiConstants.IMPORT_DEFINITION_WSDL_IMPL_TYPE_HTTP;
                if (implementationType != null && !soap.equals(implementationType) && !httpBinding.equals(implementationType)) {
                    String msg = "Invalid implementation type. Should be one of '" + soap + "' or '" + httpBinding + "'";
                    log.error(msg);
                    ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900700L, msg);
                    return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
                }
                boolean isHttpBinding = httpBinding.equals(implementationType);
                if (fileInputStream != null) {
                    if (fileDetail.getFileName() == null) {
                        String msg = "File name cannot be null.";
                        log.error(msg);
                        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900700L, msg);
                        return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
                    }
                    if (fileDetail.getFileName().endsWith(".zip")) {
                        uuid = apiPublisher.addAPIFromWSDLArchive(apiBuilder, fileInputStream, isHttpBinding);
                        if (log.isDebugEnabled()) {
                            log.debug("Successfully added API with WSDL archive " + fileDetail.getFileName());
                        }
                    } else if (fileDetail.getFileName().endsWith(".wsdl")) {
                        uuid = apiPublisher.addAPIFromWSDLFile(apiBuilder, fileInputStream, isHttpBinding);
                        if (log.isDebugEnabled()) {
                            log.debug("Successfully added API with WSDL file " + fileDetail.getFileName());
                        }
                    } else {
                        String msg = "Unsupported extension type of file: " + fileDetail.getFileName();
                        log.error(msg);
                        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900700L, msg);
                        return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
                    }
                } else {
                    uuid = apiPublisher.addAPIFromWSDLURL(apiBuilder, url, isHttpBinding);
                    if (log.isDebugEnabled()) {
                        log.debug("Successfully added API with WSDL URL " + url);
                    }
                }
            } else {
                String msg = "'additionalProperties' should be specified when creating an API from WSDL";
                log.error(msg);
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900700L, msg);
                return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
            }
        }
        API returnAPI = apiPublisher.getAPIbyUUID(uuid);
        return Response.status(Response.Status.CREATED).entity(MappingUtil.toAPIDto(returnAPI)).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding new API";
        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();
    } catch (IOException e) {
        String errorMessage = "Error while adding new API";
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorMessage, 900313L, errorMessage);
        log.error(errorMessage, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
    }
}
Also used : HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) IOException(java.io.IOException) URL(java.net.URL) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) Response(javax.ws.rs.core.Response) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO) HttpURLConnection(java.net.HttpURLConnection) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) API(org.wso2.carbon.apimgt.core.models.API) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)29 HashMap (java.util.HashMap)28 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)27 ArrayList (java.util.ArrayList)25 API (org.wso2.carbon.apimgt.api.model.API)25 IOException (java.io.IOException)18 API (org.wso2.carbon.apimgt.core.models.API)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)15 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO)15 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)14 File (java.io.File)12 Response (javax.ws.rs.core.Response)12 Map (java.util.Map)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)11 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)11 Test (org.junit.Test)10 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)10 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)10 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)10 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)10