Search in sources :

Example 1 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class APIProviderImpl method addAPIRevision.

/**
 * Adds a new APIRevision to an existing API
 *
 * @param apiRevision APIRevision
 * @throws APIManagementException if failed to add APIRevision
 */
@Override
public String addAPIRevision(APIRevision apiRevision, String organization) throws APIManagementException {
    int revisionCountPerAPI = apiMgtDAO.getRevisionCountByAPI(apiRevision.getApiUUID());
    int maxRevisionCount = getMaxRevisionCount(organization);
    if (revisionCountPerAPI >= maxRevisionCount) {
        String errorMessage = "Maximum number of revisions per API has reached. " + "Need to remove stale revision to create a new Revision for API with API UUID:" + apiRevision.getApiUUID();
        throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.MAXIMUM_REVISIONS_REACHED, apiRevision.getApiUUID()));
    }
    int revisionId = apiMgtDAO.getMostRecentRevisionId(apiRevision.getApiUUID()) + 1;
    apiRevision.setId(revisionId);
    APIIdentifier apiId = APIUtil.getAPIIdentifierFromUUID(apiRevision.getApiUUID());
    if (apiId == null) {
        throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiRevision.getApiUUID(), ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiRevision.getApiUUID()));
    }
    apiId.setUuid(apiRevision.getApiUUID());
    String revisionUUID;
    try {
        revisionUUID = apiPersistenceInstance.addAPIRevision(new Organization(organization), apiId.getUUID(), revisionId);
    } catch (APIPersistenceException e) {
        String errorMessage = "Failed to add revision registry artifacts";
        throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.ERROR_CREATING_API_REVISION, apiRevision.getApiUUID()));
    }
    if (StringUtils.isEmpty(revisionUUID)) {
        String errorMessage = "Failed to retrieve revision uuid";
        throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.API_REVISION_UUID_NOT_FOUND));
    }
    apiRevision.setRevisionUUID(revisionUUID);
    apiMgtDAO.addAPIRevision(apiRevision);
    if (importExportAPI != null) {
        try {
            File artifact = importExportAPI.exportAPI(apiRevision.getApiUUID(), revisionUUID, true, ExportFormat.JSON, false, true, organization);
            // Keeping the organization as tenant domain since MG does not support organization-wise deployment
            // Artifacts will be deployed in ST for all organizations
            gatewayArtifactsMgtDAO.addGatewayAPIArtifactAndMetaData(apiRevision.getApiUUID(), apiId.getApiName(), apiId.getVersion(), apiRevision.getRevisionUUID(), tenantDomain, APIConstants.HTTP_PROTOCOL, artifact);
            if (artifactSaver != null) {
                // Keeping the organization as tenant domain since MG does not support organization-wise deployment
                // Artifacts will be deployed in ST for all organizations
                artifactSaver.saveArtifact(apiRevision.getApiUUID(), apiId.getApiName(), apiId.getVersion(), apiRevision.getRevisionUUID(), tenantDomain, artifact);
            }
        } catch (APIImportExportException | ArtifactSynchronizerException e) {
            throw new APIManagementException("Error while Store the Revision Artifact", ExceptionCodes.from(ExceptionCodes.API_REVISION_UUID_NOT_FOUND));
        }
    }
    return revisionUUID;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Example 2 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class CommonUtil method addToArchive.

/**
 * Add files of the directory to the archive.
 *
 * @param directoryToZip  Location of the archive
 * @param file            File to be included in the archive
 * @param zipOutputStream Output stream
 * @throws APIImportExportException If an error occurs while writing files to the archive
 */
private static void addToArchive(File directoryToZip, File file, ZipOutputStream zipOutputStream) throws APIImportExportException {
    try (FileInputStream fileInputStream = new FileInputStream(file)) {
        // Get relative path from archive directory to the specific file
        String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1);
        if (File.separatorChar != ImportExportConstants.ZIP_FILE_SEPARATOR) {
            zipFilePath = zipFilePath.replace(File.separatorChar, ImportExportConstants.ZIP_FILE_SEPARATOR);
        }
        ZipEntry zipEntry = new ZipEntry(zipFilePath);
        zipOutputStream.putNextEntry(zipEntry);
        IOUtils.copy(fileInputStream, zipOutputStream);
        zipOutputStream.closeEntry();
    } catch (IOException e) {
        String errorMessage = "I/O error while writing files to archive";
        throw new APIImportExportException(errorMessage, e);
    }
}
Also used : ZipEntry(java.util.zip.ZipEntry) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Example 3 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class MicroGatewayArtifactGenerator method generateGatewayArtifact.

@Override
public RuntimeArtifactDto generateGatewayArtifact(List<APIRuntimeArtifactDto> apiRuntimeArtifactDtoList) throws APIManagementException {
    try {
        DeploymentDescriptorDto descriptorDto = new DeploymentDescriptorDto();
        Map<String, ApiProjectDto> deploymentsMap = new HashMap<>();
        // "tempDirectory" is the root artifact directory
        File tempDirectory = CommonUtil.createTempDirectory(null);
        for (APIRuntimeArtifactDto apiRuntimeArtifactDto : apiRuntimeArtifactDtoList) {
            if (apiRuntimeArtifactDto.isFile()) {
                InputStream artifact = (InputStream) apiRuntimeArtifactDto.getArtifact();
                String fileName = apiRuntimeArtifactDto.getApiId().concat("-").concat(apiRuntimeArtifactDto.getRevision()).concat(APIConstants.ZIP_FILE_EXTENSION);
                Path path = Paths.get(tempDirectory.getAbsolutePath(), fileName);
                FileUtils.copyInputStreamToFile(artifact, path.toFile());
                ApiProjectDto apiProjectDto = deploymentsMap.get(fileName);
                if (apiProjectDto == null) {
                    apiProjectDto = new ApiProjectDto();
                    deploymentsMap.put(fileName, apiProjectDto);
                    apiProjectDto.setApiFile(fileName);
                    apiProjectDto.setEnvironments(new HashSet<>());
                    apiProjectDto.setOrganizationId(apiRuntimeArtifactDto.getOrganization());
                }
                // environment is unique for a revision in a deployment
                // create new environment
                EnvironmentDto environment = new EnvironmentDto();
                environment.setName(apiRuntimeArtifactDto.getLabel());
                environment.setVhost(apiRuntimeArtifactDto.getVhost());
                // ignored if the name of the environment is same
                apiProjectDto.getEnvironments().add(environment);
            }
        }
        descriptorDto.setDeployments(new HashSet<>(deploymentsMap.values()));
        String descriptorFile = Paths.get(tempDirectory.getAbsolutePath(), APIConstants.GatewayArtifactConstants.DEPLOYMENT_DESCRIPTOR_FILE).toString();
        CommonUtil.writeDtoToFile(descriptorFile, ExportFormat.JSON, APIConstants.GatewayArtifactConstants.DEPLOYMENT_DESCRIPTOR_FILE_TYPE, descriptorDto);
        // adding env_properties.json
        Map<String, Map<String, Environment>> environmentSpecificAPIProperties = getEnvironmentSpecificAPIProperties(apiRuntimeArtifactDtoList);
        String environmentSpecificAPIPropertyFile = Paths.get(tempDirectory.getAbsolutePath(), APIConstants.GatewayArtifactConstants.ENVIRONMENT_SPECIFIC_API_PROPERTY_FILE).toString();
        CommonUtil.writeDtoToFile(environmentSpecificAPIPropertyFile, ExportFormat.JSON, APIConstants.GatewayArtifactConstants.ENVIRONMENT_SPECIFIC_API_PROPERTY_FILE, APIConstants.GatewayArtifactConstants.ENVIRONMENT_SPECIFIC_API_PROPERTY_KEY_NAME, environmentSpecificAPIProperties);
        CommonUtil.archiveDirectory(tempDirectory.getAbsolutePath());
        FileUtils.deleteQuietly(tempDirectory);
        RuntimeArtifactDto runtimeArtifactDto = new RuntimeArtifactDto();
        runtimeArtifactDto.setArtifact(new File(tempDirectory.getAbsolutePath() + APIConstants.ZIP_FILE_EXTENSION));
        runtimeArtifactDto.setFile(true);
        return runtimeArtifactDto;
    } catch (APIImportExportException | IOException e) {
        throw new APIManagementException("Error while Generating API artifact", e);
    }
}
Also used : Path(java.nio.file.Path) HashMap(java.util.HashMap) InputStream(java.io.InputStream) EnvironmentDto(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.dto.EnvironmentDto) RuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.RuntimeArtifactDto) APIRuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto) IOException(java.io.IOException) ApiProjectDto(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.dto.ApiProjectDto) APIRuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) DeploymentDescriptorDto(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.dto.DeploymentDescriptorDto)

Example 4 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class CommonUtil method transferFile.

/**
 * This method uploads a given file to specified location
 *
 * @param uploadedInputStream input stream of the file
 * @param newFileName         name of the file to be created
 * @param storageLocation     destination of the new file
 * @throws APIImportExportException If the file transfer fails
 */
public static void transferFile(InputStream uploadedInputStream, String newFileName, String storageLocation) throws APIImportExportException {
    try (FileOutputStream outFileStream = new FileOutputStream(new File(storageLocation, newFileName))) {
        int read;
        byte[] bytes = new byte[1024];
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            outFileStream.write(bytes, 0, read);
        }
    } catch (IOException e) {
        String errorMessage = "Error in transferring files.";
        throw new APIImportExportException(errorMessage, e);
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) IOException(java.io.IOException) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Example 5 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class WSO2APIPublisher method exportAPIArchive.

/**
 * Exports API as an advertised API using APIImportExportManager.
 *
 * @param api API artifact to import
 * @return API archive
 * @throws APIManagementException If an error occurs while exporting API.
 */
private File exportAPIArchive(API api) throws APIManagementException {
    File apiArchive;
    String tenantDomain = null;
    int tenantId;
    try {
        // Get tenant domain and ID to generate the original DevPortal URL (redirect URL) for the original Store
        tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
        tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        // Export API as an archive file and set it as a multipart entity in the request
        ImportExportAPI importExportAPI = APIImportExportUtil.getImportExportAPI();
        apiArchive = importExportAPI.exportAPI(api.getUuid(), api.getId().getName(), api.getId().getVersion(), String.valueOf(api.getRevisionId()), api.getId().getProviderName(), Boolean.TRUE, ExportFormat.JSON, Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, getExternalStoreRedirectURLForAPI(tenantId, api.getUuid()), api.getOrganization());
        if (log.isDebugEnabled()) {
            log.debug("API successfully exported to file: " + apiArchive.getName());
        }
    } catch (APIImportExportException e) {
        String errorMessage = "Error while exporting API: " + api.getId().getApiName() + " version: " + api.getId().getVersion();
        throw new APIManagementException(errorMessage, e);
    } catch (UserStoreException e) {
        String errorMessage = "Error while getting tenantId for tenant domain: " + tenantDomain + " when exporting API:" + api.getId().getApiName() + " version: " + api.getId().getVersion();
        throw new APIManagementException(errorMessage, e);
    }
    return apiArchive;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) File(java.io.File)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)30 APIImportExportException (org.wso2.carbon.apimgt.impl.importexport.APIImportExportException)30 IOException (java.io.IOException)24 File (java.io.File)20 Gson (com.google.gson.Gson)11 JsonObject (com.google.gson.JsonObject)10 ResourceFile (org.wso2.carbon.apimgt.api.model.ResourceFile)10 JsonArray (com.google.gson.JsonArray)9 JsonElement (com.google.gson.JsonElement)9 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)8 API (org.wso2.carbon.apimgt.api.model.API)6 GsonBuilder (com.google.gson.GsonBuilder)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 FileOutputStream (java.io.FileOutputStream)5 InputStream (java.io.InputStream)5 ArrayList (java.util.ArrayList)5 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)5 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)4 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)4 JsonParser (com.google.gson.JsonParser)3