Search in sources :

Example 6 with ServiceEntry

use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method createNewAPIVersion.

@Override
public Response createNewAPIVersion(String newVersion, String apiId, Boolean defaultVersion, String serviceVersion, MessageContext messageContext) throws APIManagementException {
    URI newVersionedApiUri;
    APIDTO newVersionedApi = new APIDTO();
    ServiceEntry service = new ServiceEntry();
    try {
        APIIdentifier apiIdentifierFromTable = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
        if (apiIdentifierFromTable == null) {
            throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
        }
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        int tenantId = APIUtil.getInternalOrganizationId(organization);
        API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
        if (existingAPI == null) {
            throw new APIMgtResourceNotFoundException("API not found for id " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
        }
        if (newVersion.equals(existingAPI.getId().getVersion())) {
            throw new APIMgtResourceAlreadyExistsException("Version " + newVersion + " exists for api " + existingAPI.getId().getApiName(), ExceptionCodes.from(API_VERSION_ALREADY_EXISTS, newVersion, existingAPI.getId().getApiName()));
        }
        if (StringUtils.isNotEmpty(serviceVersion)) {
            String serviceName = existingAPI.getServiceInfo("name");
            ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
            service = serviceCatalog.getServiceByNameAndVersion(serviceName, serviceVersion, tenantId);
            if (service == null) {
                throw new APIManagementException("No matching service version found", ExceptionCodes.SERVICE_VERSION_NOT_FOUND);
            }
        }
        if (StringUtils.isNotEmpty(serviceVersion) && !serviceVersion.equals(existingAPI.getServiceInfo("version"))) {
            APIDTO apidto = createAPIDTO(existingAPI, newVersion);
            if (ServiceEntry.DefinitionType.OAS2.equals(service.getDefinitionType()) || ServiceEntry.DefinitionType.OAS3.equals(service.getDefinitionType())) {
                newVersionedApi = importOpenAPIDefinition(service.getEndpointDef(), null, null, apidto, null, service, organization);
            } else if (ServiceEntry.DefinitionType.ASYNC_API.equals(service.getDefinitionType())) {
                newVersionedApi = importAsyncAPISpecification(service.getEndpointDef(), null, apidto, null, service, organization);
            }
        } else {
            API versionedAPI = apiProvider.createNewAPIVersion(apiId, newVersion, defaultVersion, organization);
            newVersionedApi = APIMappingUtil.fromAPItoDTO(versionedAPI);
        }
        // This URI used to set the location header of the POST response
        newVersionedApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + newVersionedApi.getId());
        return Response.created(newVersionedApiUri).entity(newVersionedApi).build();
    } catch (APIManagementException e) {
        if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while copying API : " + apiId, e, log);
        } else {
            throw e;
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving API location of " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) URISyntaxException(java.net.URISyntaxException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) URI(java.net.URI) ServiceEntry(org.wso2.carbon.apimgt.api.model.ServiceEntry) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ServiceCatalogImpl(org.wso2.carbon.apimgt.impl.ServiceCatalogImpl)

Example 7 with ServiceEntry

use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method importAsyncAPISpecification.

private APIDTO importAsyncAPISpecification(InputStream definition, String definitionUrl, APIDTO apiDTOFromProperties, Attachment fileDetail, ServiceEntry service, String organization) {
    // validate and retrieve the AsyncAPI specification
    Map validationResponseMap = null;
    boolean isServiceAPI = false;
    try {
        if (service != null) {
            isServiceAPI = true;
        }
        validationResponseMap = validateAsyncAPISpecification(definitionUrl, definition, fileDetail, true, isServiceAPI);
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error occurred while validating API Definition", e, log);
    }
    AsyncAPISpecificationValidationResponseDTO validationResponseDTO = (AsyncAPISpecificationValidationResponseDTO) validationResponseMap.get(RestApiConstants.RETURN_DTO);
    APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
    if (!validationResponseDTO.isIsValid()) {
        ErrorDTO errorDTO = APIMappingUtil.getErrorDTOFromErrorListItems(validationResponseDTO.getErrors());
        throw RestApiUtil.buildBadRequestException(errorDTO);
    }
    // Import the API and Definition
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String definitionToAdd = validationResponse.getJsonContent();
        String protocol = validationResponse.getProtocol();
        if (isServiceAPI) {
            apiDTOFromProperties.setType(PublisherCommonUtils.getAPIType(service.getDefinitionType(), protocol));
        }
        if (!APIConstants.WSO2_GATEWAY_ENVIRONMENT.equals(apiDTOFromProperties.getGatewayVendor())) {
            apiDTOFromProperties.getPolicies().add(APIConstants.DEFAULT_SUB_POLICY_ASYNC_UNLIMITED);
            apiDTOFromProperties.setAsyncTransportProtocols(AsyncApiParser.getTransportProtocolsForAsyncAPI(definitionToAdd));
        }
        API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(apiDTOFromProperties, apiProvider, RestApiCommonUtil.getLoggedInUsername(), organization);
        if (isServiceAPI) {
            apiToAdd.setServiceInfo("key", service.getKey());
            apiToAdd.setServiceInfo("md5", service.getMd5());
            if (!APIConstants.API_TYPE_WEBSUB.equals(protocol.toUpperCase())) {
                apiToAdd.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), protocol));
            }
        }
        apiToAdd.setAsyncApiDefinition(definitionToAdd);
        // load topics from AsyncAPI
        apiToAdd.setUriTemplates(new AsyncApiParser().getURITemplates(definitionToAdd, APIConstants.API_TYPE_WS.equals(apiToAdd.getType()) || !APIConstants.WSO2_GATEWAY_ENVIRONMENT.equals(apiToAdd.getGatewayVendor())));
        apiToAdd.setOrganization(organization);
        apiToAdd.setAsyncApiDefinition(definitionToAdd);
        apiProvider.addAPI(apiToAdd);
        return APIMappingUtil.fromAPItoDTO(apiProvider.getAPIbyUUID(apiToAdd.getUuid(), organization));
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding new API : " + apiDTOFromProperties.getProvider() + "-" + apiDTOFromProperties.getName() + "-" + apiDTOFromProperties.getVersion() + " - " + e.getMessage();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) AsyncAPISpecificationValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseDTO) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) AsyncApiParser(org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 8 with ServiceEntry

use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.

the class Md5HashGenerator method validateInputParams.

/**
 * This traversal through the directories and calculate md5
 *
 * @param files list of files available directory location
 * @return HashMap<String, String>
 */
private static HashMap<String, String> validateInputParams(File[] files) {
    for (File file : files) {
        if (file.isDirectory()) {
            // Else is not required since this for taking only the directories. If it is an empty zip, then
            // the final map will be empty.
            File[] fileArray = file.listFiles();
            if (fileArray != null) {
                // Order files according to the alphabetical order of file names when concatenating hashes.
                Arrays.sort(fileArray, NameFileComparator.NAME_COMPARATOR);
                String key = null;
                for (File yamlFile : fileArray) {
                    if (yamlFile.getName().startsWith(APIConstants.METADATA_FILE_NAME)) {
                        // This if only check whether the file start with the name "metadata".
                        try {
                            ServiceEntry service = fromFileToServiceEntry(yamlFile, null);
                            key = service.getKey();
                        } catch (IOException e) {
                            RestApiUtil.handleBadRequest("Failed to fetch metadata information", log);
                        }
                    }
                }
                try {
                    endpoints.put(key, calculateHash(fileArray));
                } catch (NoSuchAlgorithmException | IOException e) {
                    RestApiUtil.handleInternalServerError("Failed to generate MD5 Hash due to " + e.getMessage(), log);
                } catch (ArrayIndexOutOfBoundsException e) {
                    RestApiUtil.handleBadRequest("Required metadata.yaml or definition.yaml is missing", log);
                }
            }
        }
    }
    return endpoints;
}
Also used : IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) File(java.io.File) ServiceEntry(org.wso2.carbon.apimgt.api.model.ServiceEntry) ServiceEntryMappingUtil.fromFileToServiceEntry(org.wso2.carbon.apimgt.rest.api.service.catalog.utils.ServiceEntryMappingUtil.fromFileToServiceEntry)

Example 9 with ServiceEntry

use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.

the class ServiceEntryMappingUtil method fromServiceToDTO.

public static ServiceDTO fromServiceToDTO(ServiceEntry service, boolean shrink) {
    ServiceDTO serviceDTO = new ServiceDTO();
    serviceDTO.setId(service.getUuid());
    serviceDTO.setName(service.getName());
    serviceDTO.setVersion(service.getVersion());
    serviceDTO.setMd5(service.getMd5());
    serviceDTO.setServiceKey(service.getKey());
    if (!shrink) {
        serviceDTO.setServiceUrl(service.getServiceUrl());
        serviceDTO.setDefinitionType(ServiceDTO.DefinitionTypeEnum.fromValue(service.getDefinitionType().toString()));
        serviceDTO.setDefinitionUrl(service.getDefUrl());
        serviceDTO.setDescription(service.getDescription());
        serviceDTO.setSecurityType(ServiceDTO.SecurityTypeEnum.fromValue(service.getSecurityType().toString()));
        serviceDTO.setMutualSSLEnabled(service.isMutualSSLEnabled());
        serviceDTO.setCreatedTime(String.valueOf(service.getCreatedTime()));
        serviceDTO.setLastUpdatedTime(String.valueOf(service.getLastUpdatedTime()));
        serviceDTO.setUsage(service.getUsage());
    }
    return serviceDTO;
}
Also used : ServiceDTO(org.wso2.carbon.apimgt.rest.api.service.catalog.dto.ServiceDTO)

Example 10 with ServiceEntry

use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.

the class ServicesApiServiceImpl method addService.

@Override
public Response addService(ServiceDTO serviceDTO, InputStream definitionFileInputStream, Attachment definitionFileDetail, String inlineContent, MessageContext messageContext) {
    String userName = RestApiCommonUtil.getLoggedInUsername();
    int tenantId = APIUtil.getTenantId(userName);
    try {
        validateInputParams(definitionFileInputStream, definitionFileDetail, inlineContent);
        ServiceEntry existingService = serviceCatalog.getServiceByKey(serviceDTO.getServiceKey(), tenantId);
        if (existingService != null) {
            RestApiUtil.handleResourceAlreadyExistsError("Error while adding Service : A service already " + "exists with key: " + serviceDTO.getServiceKey(), log);
        }
        byte[] definitionFileByteArray;
        if (definitionFileInputStream != null) {
            definitionFileByteArray = getDefinitionFromInput(definitionFileInputStream);
        } else {
            definitionFileByteArray = inlineContent.getBytes();
        }
        ServiceEntry service = ServiceCatalogUtils.createServiceFromDTO(serviceDTO, definitionFileByteArray);
        if (!validateAndRetrieveServiceDefinition(definitionFileByteArray, serviceDTO.getServiceUrl(), service.getDefinitionType()).isValid()) {
            String errorMsg = "The Service import has been failed as invalid service definition provided";
            return Response.status(Response.Status.BAD_REQUEST).entity(getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 400L, errorMsg, StringUtils.EMPTY)).build();
        }
        String serviceId = serviceCatalog.addService(service, tenantId, userName);
        ServiceEntry createdService = serviceCatalog.getServiceByUUID(serviceId, tenantId);
        return Response.ok().entity(ServiceEntryMappingUtil.fromServiceToDTO(createdService, false)).build();
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error when validating the service definition", log);
    } catch (IOException e) {
        RestApiUtil.handleInternalServerError("Error when reading the file content", log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) IOException(java.io.IOException) ServiceEntry(org.wso2.carbon.apimgt.api.model.ServiceEntry)

Aggregations

ServiceEntry (org.wso2.carbon.apimgt.api.model.ServiceEntry)24 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)15 API (org.wso2.carbon.apimgt.api.model.API)8 IOException (java.io.IOException)7 HashMap (java.util.HashMap)7 PreparedStatement (java.sql.PreparedStatement)6 SQLException (java.sql.SQLException)6 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)6 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 Connection (java.sql.Connection)5 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)5 ResultSet (java.sql.ResultSet)4 APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)4 ServiceCatalogImpl (org.wso2.carbon.apimgt.impl.ServiceCatalogImpl)4 File (java.io.File)3 LinkedHashMap (java.util.LinkedHashMap)3 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)3