Search in sources :

Example 41 with APIImportExportException

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

the class ExportUtils method getEndpointCertificateContentAndMetaData.

/**
 * Get Endpoint Certificate MetaData and Certificate detail and build JSON Array.
 *
 * @param tenantId          Tenant id of the user
 * @param url               Url of the endpoint
 * @param certDirectoryPath Directory path to export the certificates
 * @return JSON Array of certificate details
 * @throws APIImportExportException If an error occurs while retrieving endpoint certificate metadata and content
 */
private static JsonArray getEndpointCertificateContentAndMetaData(int tenantId, String url, String certDirectoryPath) throws APIImportExportException {
    List<CertificateMetadataDTO> certificateMetadataDTOS;
    CertificateManager certificateManager = CertificateManagerImpl.getInstance();
    try {
        certificateMetadataDTOS = certificateManager.getCertificates(tenantId, null, url);
    } catch (APIManagementException e) {
        throw new APIImportExportException("Error retrieving certificate meta data. For tenantId: " + tenantId + " hostname: " + url, e);
    }
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonArray certificatesList = new JsonArray();
    certificateMetadataDTOS.forEach(metadataDTO -> {
        try (ByteArrayInputStream certificate = certificateManager.getCertificateContent(metadataDTO.getAlias())) {
            byte[] certificateContent = IOUtils.toByteArray(certificate);
            String certificateContentEncoded = APIConstants.BEGIN_CERTIFICATE_STRING.concat(System.lineSeparator()).concat(new String(Base64.encodeBase64(certificateContent))).concat(System.lineSeparator()).concat(APIConstants.END_CERTIFICATE_STRING);
            CommonUtil.writeFile(certDirectoryPath + File.separator + metadataDTO.getAlias() + ".crt", certificateContentEncoded);
            // Add the file name to the Certificate Metadata
            JsonObject modifiedCertificateMetadata = (JsonObject) gson.toJsonTree(metadataDTO);
            modifiedCertificateMetadata.addProperty(ImportExportConstants.CERTIFICATE_FILE, metadataDTO.getAlias() + ".crt");
            certificatesList.add(modifiedCertificateMetadata);
        } catch (APIManagementException e) {
            log.error("Error retrieving certificate content. For tenantId: " + tenantId + " hostname: " + url + " alias: " + metadataDTO.getAlias(), e);
        } catch (IOException e) {
            log.error("Error while converting certificate content to Byte Array. For tenantId: " + tenantId + " hostname: " + url + " alias: " + metadataDTO.getAlias(), e);
        } catch (APIImportExportException e) {
            log.error("Error while writing the certificate content. For tenantId: " + tenantId + " hostname: " + url + " alias: " + metadataDTO.getAlias(), e);
        }
    });
    return certificatesList;
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) CertificateManager(org.wso2.carbon.apimgt.impl.certificatemgt.CertificateManager) IOException(java.io.IOException) JsonArray(com.google.gson.JsonArray) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) CertificateMetadataDTO(org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO) ByteArrayInputStream(java.io.ByteArrayInputStream) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException)

Example 42 with APIImportExportException

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

the class ExportUtils method getClientCertificateContentAndMetaData.

/**
 * Get Client Certificate MetaData and Certificate detail and build JSON list.
 *
 * @param clientCertificateDTOs client certificates list DTOs
 * @param certDirectoryPath     directory path to export the certificates
 * @return list of certificate detail JSON objects
 */
private static JsonArray getClientCertificateContentAndMetaData(List<ClientCertificateDTO> clientCertificateDTOs, String certDirectoryPath) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonArray certificatesList = new JsonArray();
    clientCertificateDTOs.forEach(metadataDTO -> {
        try {
            String certificateContent = metadataDTO.getCertificate();
            String certificateContentEncoded = APIConstants.BEGIN_CERTIFICATE_STRING.concat(System.lineSeparator()).concat(certificateContent).concat(System.lineSeparator()).concat(APIConstants.END_CERTIFICATE_STRING);
            CommonUtil.writeFile(certDirectoryPath + File.separator + metadataDTO.getAlias() + ".crt", certificateContentEncoded);
            // Add the file name to the Certificate Metadata
            metadataDTO.setCertificate(metadataDTO.getAlias() + ".crt");
            JsonObject certificateMetadata = (JsonObject) gson.toJsonTree(metadataDTO);
            certificatesList.add(certificateMetadata);
        } catch (APIImportExportException e) {
            log.error("Error while writing the certificate content. For alias: " + metadataDTO.getAlias(), e);
        }
    });
    return certificatesList;
}
Also used : JsonArray(com.google.gson.JsonArray) GsonBuilder(com.google.gson.GsonBuilder) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject)

Example 43 with APIImportExportException

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

the class ImportUtils method retrieveValidatedGraphqlSchemaFromArchive.

/**
 * Validate GraphQL Schema definition from the archive directory and return it.
 *
 * @param pathToArchive Path to API archive
 * @throws APIImportExportException If an error occurs while reading the file
 */
public static String retrieveValidatedGraphqlSchemaFromArchive(String pathToArchive) throws APIManagementException {
    File file = new File(pathToArchive + ImportExportConstants.GRAPHQL_SCHEMA_DEFINITION_LOCATION);
    try {
        String schemaDefinition = loadGraphqlSDLFile(pathToArchive);
        GraphQLValidationResponseDTO graphQLValidationResponseDTO = PublisherCommonUtils.validateGraphQLSchema(file.getName(), schemaDefinition);
        if (!graphQLValidationResponseDTO.isIsValid()) {
            throw new APIManagementException("Error occurred while importing the API. Invalid GraphQL schema definition found. " + graphQLValidationResponseDTO.getErrorMessage());
        }
        return schemaDefinition;
    } catch (IOException e) {
        throw new APIManagementException("Error while reading API meta information from path: " + pathToArchive, e, ExceptionCodes.ERROR_READING_META_DATA);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) IOException(java.io.IOException) GraphQLValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLValidationResponseDTO) File(java.io.File)

Example 44 with APIImportExportException

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

the class ImportUtils method addEndpointCertificates.

/**
 * This method import endpoint certificate.
 *
 * @param pathToArchive location of the extracted folder of the API
 * @param importedApi   the imported API object
 * @throws APIImportExportException If an error occurs while importing endpoint certificates from file
 */
private static void addEndpointCertificates(String pathToArchive, API importedApi, APIProvider apiProvider, int tenantId) throws APIManagementException {
    String jsonContent = null;
    String pathToEndpointsCertificatesDirectory = pathToArchive + File.separator + ImportExportConstants.ENDPOINT_CERTIFICATES_DIRECTORY;
    String pathToYamlFile = pathToEndpointsCertificatesDirectory + ImportExportConstants.ENDPOINTS_CERTIFICATE_FILE + ImportExportConstants.YAML_EXTENSION;
    String pathToJsonFile = pathToEndpointsCertificatesDirectory + ImportExportConstants.ENDPOINTS_CERTIFICATE_FILE + ImportExportConstants.JSON_EXTENSION;
    try {
        // try loading file as YAML
        if (CommonUtil.checkFileExistence(pathToYamlFile)) {
            if (log.isDebugEnabled()) {
                log.debug("Found certificate file " + pathToYamlFile);
            }
            String yamlContent = FileUtils.readFileToString(new File(pathToYamlFile));
            jsonContent = CommonUtil.yamlToJson(yamlContent);
        } else if (CommonUtil.checkFileExistence(pathToJsonFile)) {
            // load as a json fallback
            if (log.isDebugEnabled()) {
                log.debug("Found certificate file " + pathToJsonFile);
            }
            jsonContent = FileUtils.readFileToString(new File(pathToJsonFile));
        }
        if (jsonContent == null) {
            log.debug("No certificate file found to be added, skipping certificate import.");
            return;
        }
        JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA);
        JsonArray certificates = addFileContentToCertificates(configElement.getAsJsonArray(), pathToEndpointsCertificatesDirectory);
        for (JsonElement certificate : certificates) {
            updateAPIWithCertificate(certificate, apiProvider, importedApi, tenantId);
        }
    } catch (IOException e) {
        throw new APIManagementException("Error in reading certificates file", e);
    }
}
Also used : JsonArray(com.google.gson.JsonArray) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) IOException(java.io.IOException) File(java.io.File) JsonParser(com.google.gson.JsonParser)

Example 45 with APIImportExportException

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

the class ImportExportAPIServiceImpl method exportAPIProduct.

@Override
public File exportAPIProduct(String apiId, String revisionUUID, boolean preserveStatus, ExportFormat format, boolean preserveDocs, boolean preserveCredentials, String organization) throws APIManagementException, APIImportExportException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String userName = RestApiCommonUtil.getLoggedInUsername();
    APIProductIdentifier apiProductIdentifier = APIUtil.getAPIProductIdentifierFromUUID(apiId);
    APIProduct product = apiProvider.getAPIProductbyUUID(revisionUUID, organization);
    APIProductDTO apiProductDtoToReturn = APIMappingUtil.fromAPIProducttoDTO(product);
    return ExportUtils.exportApiProduct(apiProvider, apiProductIdentifier, apiProductDtoToReturn, userName, format, preserveStatus, preserveDocs, preserveCredentials, organization);
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

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