Search in sources :

Example 11 with APIImportExportException

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

the class ApplicationsApiServiceImpl method applicationsImportPost.

/**
 * Import an Application which has been exported to a zip file
 *
 * @param fileInputStream     Content stream of the zip file which contains exported Application
 * @param fileDetail          Meta information of the zip file
 * @param preserveOwner       If true, preserve the original owner of the application
 * @param skipSubscriptions   If true, skip subscriptions of the application
 * @param appOwner            Target owner of the application
 * @param skipApplicationKeys Skip application keys while importing
 * @param update              Update if existing application found or import
 * @param messageContext      Message Context
 * @return imported Application
 */
@Override
public Response applicationsImportPost(InputStream fileInputStream, Attachment fileDetail, Boolean preserveOwner, Boolean skipSubscriptions, String appOwner, Boolean skipApplicationKeys, Boolean update, MessageContext messageContext) throws APIManagementException {
    String ownerId;
    Application application;
    try {
        String username = RestApiCommonUtil.getLoggedInUsername();
        APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
        String extractedFolderPath = CommonUtil.getArchivePathOfExtractedDirectory(fileInputStream, ImportExportConstants.UPLOAD_APPLICATION_FILE_NAME);
        String jsonContent = ImportUtils.getApplicationDefinitionAsJson(extractedFolderPath);
        // Retrieving the field "data" in api.yaml/json and convert it to a JSON object for further processing
        JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA);
        ExportedApplication exportedApplication = new Gson().fromJson(configElement, ExportedApplication.class);
        // Retrieve the application DTO object from the aggregated exported application
        ApplicationDTO applicationDTO = exportedApplication.getApplicationInfo();
        if (!StringUtils.isBlank(appOwner)) {
            ownerId = appOwner;
        } else if (preserveOwner != null && preserveOwner) {
            ownerId = applicationDTO.getOwner();
        } else {
            ownerId = username;
        }
        if (!MultitenantUtils.getTenantDomain(ownerId).equals(MultitenantUtils.getTenantDomain(username))) {
            throw new APIManagementException("Cross Tenant Imports are not allowed", ExceptionCodes.TENANT_MISMATCH);
        }
        String applicationGroupId = String.join(",", applicationDTO.getGroups());
        if (applicationDTO.getGroups() != null && applicationDTO.getGroups().size() > 0) {
            ImportUtils.validateOwner(username, applicationGroupId, apiConsumer);
        }
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        if (APIUtil.isApplicationExist(ownerId, applicationDTO.getName(), applicationGroupId, organization) && update != null && update) {
            int appId = APIUtil.getApplicationId(applicationDTO.getName(), ownerId);
            Application oldApplication = apiConsumer.getApplicationById(appId);
            application = preProcessAndUpdateApplication(ownerId, applicationDTO, oldApplication, oldApplication.getUUID());
        } else {
            application = preProcessAndAddApplication(ownerId, applicationDTO, organization);
            update = Boolean.FALSE;
        }
        List<APIIdentifier> skippedAPIs = new ArrayList<>();
        if (skipSubscriptions == null || !skipSubscriptions) {
            skippedAPIs = ImportUtils.importSubscriptions(exportedApplication.getSubscribedAPIs(), ownerId, application, update, apiConsumer, organization);
        }
        Application importedApplication = apiConsumer.getApplicationById(application.getId());
        importedApplication.setOwner(ownerId);
        ApplicationInfoDTO importedApplicationDTO = ApplicationMappingUtil.fromApplicationToInfoDTO(importedApplication);
        URI location = new URI(RestApiConstants.RESOURCE_PATH_APPLICATIONS + "/" + importedApplicationDTO.getApplicationId());
        // check whether keys need to be skipped while import
        if (skipApplicationKeys == null || !skipApplicationKeys) {
            // if this is an update, old keys will be removed and the OAuth app will be overridden with new values
            if (update) {
                if (applicationDTO.getKeys().size() > 0 && importedApplication.getKeys().size() > 0) {
                    importedApplication.getKeys().clear();
                }
            }
            // Add application keys if present and keys does not exists in the current application
            if (applicationDTO.getKeys().size() > 0 && importedApplication.getKeys().size() == 0) {
                for (ApplicationKeyDTO applicationKeyDTO : applicationDTO.getKeys()) {
                    ImportUtils.addApplicationKey(ownerId, importedApplication, applicationKeyDTO, apiConsumer, update);
                }
            }
        }
        if (skippedAPIs.isEmpty()) {
            return Response.created(location).entity(importedApplicationDTO).build();
        } else {
            APIInfoListDTO skippedAPIListDTO = APIInfoMappingUtil.fromAPIInfoListToDTO(skippedAPIs);
            return Response.created(location).status(207).entity(skippedAPIListDTO).build();
        }
    } catch (URISyntaxException | UserStoreException | APIImportExportException e) {
        throw new APIManagementException("Error while importing Application", e);
    } catch (UnsupportedEncodingException e) {
        throw new APIManagementException("Error while Decoding apiId", e);
    } catch (IOException e) {
        throw new APIManagementException("Error while reading the application definition", e);
    }
}
Also used : ApplicationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationDTO) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) ApplicationInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationInfoDTO) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationKeyDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO) JsonElement(com.google.gson.JsonElement) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) APIInfoListDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIInfoListDTO) JsonParser(com.google.gson.JsonParser)

Example 12 with APIImportExportException

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

the class APIControllerUtil method handleEndpointCertificates.

/**
 * This method will be used to generate Endpoint certificates and meta information related to endpoint certs.
 *
 * @param certificates  JsonArray of endpoint-certificates
 * @param pathToArchive String of the archive project
 * @throws IOException            If an error occurs when generating new certs and yaml file or when moving certs
 * @throws APIManagementException If an error while generating new directory
 */
private static void handleEndpointCertificates(JsonArray certificates, String pathToArchive) throws IOException, APIManagementException {
    JsonArray updatedCertsArray = new JsonArray();
    for (JsonElement certificate : certificates) {
        JsonObject certObject = certificate.getAsJsonObject();
        String alias = certObject.get(ImportExportConstants.ALIAS_JSON_KEY).getAsString();
        CertificateMetadataDTO certificateMetadataDTO = new CertificateMetadataDTO();
        certificateMetadataDTO.setAlias(alias);
        certificateMetadataDTO.setEndpoint(certObject.get(ImportExportConstants.CERTIFICATE_HOST_NAME_PROPERTY).getAsString());
        // Add certificate element to cert object
        JsonElement jsonElement = new Gson().toJsonTree(certificateMetadataDTO);
        JsonObject updatedCertObj = jsonElement.getAsJsonObject();
        String certName = certObject.get(ImportExportConstants.CERTIFICATE_PATH_PROPERTY).getAsString();
        updatedCertObj.addProperty(ImportExportConstants.CERTIFICATE_FILE, certName);
        updatedCertsArray.add(updatedCertObj);
        // check and create a directory
        String endpointCertificatesDirectory = pathToArchive + ImportExportConstants.ENDPOINT_CERTIFICATES_DIRECTORY_PATH;
        if (!CommonUtil.checkFileExistence(endpointCertificatesDirectory)) {
            try {
                CommonUtil.createDirectory(endpointCertificatesDirectory);
            } catch (APIImportExportException e) {
                throw new APIManagementException(e);
            }
        }
        // copy certs file from certificates
        String userCertificatesTempDirectory = pathToArchive + ImportExportConstants.DEPLOYMENT_DIRECTORY + ImportExportConstants.CERTIFICATE_DIRECTORY;
        String sourcePath = userCertificatesTempDirectory + File.separator + certName;
        String destinationPath = endpointCertificatesDirectory + File.separator + certName;
        if (Files.notExists(Paths.get(sourcePath))) {
            String errorMessage = "The mentioned certificate file " + certName + " is not in the certificates directory";
            throw new APIManagementException(errorMessage, ExceptionCodes.ERROR_READING_PARAMS_FILE);
        }
        CommonUtil.moveFile(sourcePath, destinationPath);
    }
    // generate meta-data yaml file
    String metadataFilePath = pathToArchive + ImportExportConstants.ENDPOINT_CERTIFICATES_META_DATA_FILE_PATH;
    try {
        if (CommonUtil.checkFileExistence(metadataFilePath + ImportExportConstants.YAML_EXTENSION)) {
            File oldFile = new File(metadataFilePath + ImportExportConstants.YAML_EXTENSION);
            oldFile.delete();
        }
        if (CommonUtil.checkFileExistence(metadataFilePath + ImportExportConstants.JSON_EXTENSION)) {
            File oldFile = new File(metadataFilePath + ImportExportConstants.JSON_EXTENSION);
            oldFile.delete();
        }
        CommonUtil.writeDtoToFile(metadataFilePath, ExportFormat.JSON, ImportExportConstants.TYPE_ENDPOINT_CERTIFICATES, updatedCertsArray);
    } catch (APIImportExportException e) {
        throw new APIManagementException(e);
    }
}
Also used : JsonArray(com.google.gson.JsonArray) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) CertificateMetadataDTO(org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO) JsonElement(com.google.gson.JsonElement) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) File(java.io.File)

Example 13 with APIImportExportException

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

the class ApisApiServiceImpl method exportAPI.

/**
 * Exports an API from API Manager for a given API using the ApiId. ID. Meta information, API icon, documentation,
 * WSDL and sequences are exported. This service generates a zipped archive which contains all the above mentioned
 * resources for a given API.
 *
 * @param apiId          UUID of an API
 * @param name           Name of the API that needs to be exported
 * @param version        Version of the API that needs to be exported
 * @param providerName   Provider name of the API that needs to be exported
 * @param format         Format of output documents. Can be YAML or JSON
 * @param preserveStatus Preserve API status on export
 * @return
 */
@Override
public Response exportAPI(String apiId, String name, String version, String revisionNum, String providerName, String format, Boolean preserveStatus, Boolean exportLatestRevision, MessageContext messageContext) throws APIManagementException {
    // If not specified status is preserved by default
    preserveStatus = preserveStatus == null || preserveStatus;
    // Default export format is YAML
    ExportFormat exportFormat = StringUtils.isNotEmpty(format) ? ExportFormat.valueOf(format.toUpperCase()) : ExportFormat.YAML;
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        ImportExportAPI importExportAPI = APIImportExportUtil.getImportExportAPI();
        File file = importExportAPI.exportAPI(apiId, name, version, revisionNum, providerName, preserveStatus, exportFormat, Boolean.TRUE, Boolean.FALSE, exportLatestRevision, StringUtils.EMPTY, organization);
        return Response.ok(file).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"").build();
    } catch (APIImportExportException e) {
        throw new APIManagementException("Error while exporting " + RestApiConstants.RESOURCE_API, e);
    }
}
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) ExportFormat(org.wso2.carbon.apimgt.impl.importexport.ExportFormat) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Example 14 with APIImportExportException

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

the class ExportUtils method addMultipleAPISpecificSequencesToArchive.

/**
 * Retrieve multiple API specific sequences for API export, and store it in the archive
 * directory.
 *
 * @param archivePath File path to export the sequences
 * @param api         API
 * @param apiProvider API Provider
 * @throws APIManagementException   If an error occurs while retrieving sequences and writing those
 * @throws APIImportExportException If an error occurs while creating the directory to export sequences
 */
private static void addMultipleAPISpecificSequencesToArchive(String archivePath, API api, APIProvider apiProvider) throws APIManagementException, APIImportExportException {
    String seqArchivePath = archivePath.concat(File.separator + ImportExportConstants.SEQUENCES_RESOURCE);
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    if (!CommonUtil.checkFileExistence(seqArchivePath)) {
        CommonUtil.createDirectory(seqArchivePath);
    }
    // Getting list of API specific custom mediation policies
    List<Mediation> apiSpecificMediationList = apiProvider.getAllApiSpecificMediationPolicies(api.getUuid(), tenantDomain);
    if (!apiSpecificMediationList.isEmpty()) {
        for (Mediation mediation : apiSpecificMediationList) {
            Mediation mediationResource = apiProvider.getApiSpecificMediationPolicyByPolicyId(api.getUuid(), mediation.getUuid(), tenantDomain);
            String individualSequenceExportPath = seqArchivePath + File.separator + mediation.getType().toLowerCase() + ImportExportConstants.SEQUENCE_LOCATION_POSTFIX + File.separator + ImportExportConstants.CUSTOM_TYPE;
            if (!CommonUtil.checkFileExistence(individualSequenceExportPath)) {
                CommonUtil.createDirectory(individualSequenceExportPath);
            }
            writeSequenceToArchive(mediationResource.getConfig(), individualSequenceExportPath, mediation.getName());
        }
    }
}
Also used : Mediation(org.wso2.carbon.apimgt.api.model.Mediation)

Example 15 with APIImportExportException

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

the class ExportUtils method addWSDLtoArchive.

/**
 * Retrieve WSDL for the exporting API and store it in the archive directory.
 *
 * @param archivePath   File path to export the WSDL
 * @param apiIdentifier ID of the requesting API
 * @throws APIImportExportException If an error occurs while retrieving WSDL from the registry or
 *                                  storing in the archive directory
 */
public static void addWSDLtoArchive(String archivePath, APIIdentifier apiIdentifier, APIProvider apiProvider) throws APIImportExportException {
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    String wsdlPath = APIConstants.API_WSDL_RESOURCE_LOCATION + apiIdentifier.getProviderName() + "--" + apiIdentifier.getApiName() + apiIdentifier.getVersion() + APIConstants.WSDL_FILE_EXTENSION;
    try {
        ResourceFile wsdlResource = apiProvider.getWSDL(apiIdentifier.getUUID(), tenantDomain);
        if (wsdlResource != null) {
            CommonUtil.createDirectory(archivePath + File.separator + "WSDL");
            try (InputStream wsdlStream = wsdlResource.getContent();
                OutputStream outputStream = new FileOutputStream(archivePath + File.separator + "WSDL" + File.separator + apiIdentifier.getApiName() + "-" + apiIdentifier.getVersion() + APIConstants.WSDL_FILE_EXTENSION)) {
                IOUtils.copy(wsdlStream, outputStream);
                if (log.isDebugEnabled()) {
                    log.debug("WSDL file: " + wsdlPath + " retrieved successfully");
                }
            }
        } else if (log.isDebugEnabled()) {
            log.debug("WSDL resource does not exists in path: " + wsdlPath + ". Skipping WSDL export.");
        }
    } catch (IOException | APIManagementException e) {
        throw new APIImportExportException("I/O error while writing WSDL: " + wsdlPath + " to file", e);
    }
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) IOException(java.io.IOException)

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