Search in sources :

Example 26 with APIImportExportException

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

the class RestApiPublisherUtils method exportOperationPolicyData.

public static File exportOperationPolicyData(OperationPolicyData policyData) throws APIManagementException {
    File exportFolder = null;
    try {
        exportFolder = CommonUtil.createTempDirectoryFromName(policyData.getSpecification().getName() + "_" + policyData.getSpecification().getVersion());
        String exportAPIBasePath = exportFolder.toString();
        String archivePath = exportAPIBasePath.concat(File.separator + policyData.getSpecification().getName());
        CommonUtil.createDirectory(archivePath);
        String policyName = archivePath + File.separator + policyData.getSpecification().getName();
        if (policyData.getSpecification() != null) {
            CommonUtil.writeDtoToFile(policyName, ExportFormat.YAML, ImportExportConstants.TYPE_POLICY_SPECIFICATION, policyData.getSpecification());
        }
        if (policyData.getSynapsePolicyDefinition() != null) {
            CommonUtil.writeFile(policyName + APIConstants.SYNAPSE_POLICY_DEFINITION_EXTENSION, policyData.getSynapsePolicyDefinition().getContent());
        }
        if (policyData.getCcPolicyDefinition() != null) {
            CommonUtil.writeFile(policyName + APIConstants.CC_POLICY_DEFINITION_EXTENSION, policyData.getCcPolicyDefinition().getContent());
        }
        CommonUtil.archiveDirectory(exportAPIBasePath);
        FileUtils.deleteQuietly(new File(exportAPIBasePath));
        return new File(exportAPIBasePath + APIConstants.ZIP_FILE_EXTENSION);
    } catch (APIImportExportException | IOException e) {
        throw new APIManagementException("Error while exporting operation policy", e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException)

Example 27 with APIImportExportException

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

the class APIProviderImplTest method testAddAPIRevision.

/**
 * This method tests adding a new API Revision
 *
 * @throws APIManagementException
 */
@Test
public void testAddAPIRevision() throws APIManagementException, APIPersistenceException, APIImportExportException, ArtifactSynchronizerException {
    ImportExportAPI importExportAPI = Mockito.mock(ImportExportAPI.class);
    ArtifactSaver artifactSaver = Mockito.mock(ArtifactSaver.class);
    Mockito.doNothing().when(artifactSaver).saveArtifact(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(File.class));
    Mockito.when(GatewayArtifactsMgtDAO.getInstance()).thenReturn(gatewayArtifactsMgtDAO);
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, importExportAPI, gatewayArtifactsMgtDAO, artifactSaver);
    APIIdentifier apiId = new APIIdentifier("admin", "PizzaShackAPI", "1.0.0", "63e1e37e-a5b8-4be6-86a5-d6ae0749f131");
    API api = new API(apiId);
    api.setContext("/test");
    api.setStatus(APIConstants.CREATED);
    String apiPath = "/apimgt/applicationdata/provider/admin/PizzaShackAPI/1.0.0/api";
    APIRevision apiRevision = new APIRevision();
    apiRevision.setApiUUID("63e1e37e-a5b8-4be6-86a5-d6ae0749f131");
    apiRevision.setDescription("test description revision 1");
    Mockito.when(apimgtDAO.getRevisionCountByAPI(Mockito.anyString())).thenReturn(0);
    Mockito.when(apimgtDAO.getMostRecentRevisionId(Mockito.anyString())).thenReturn(0);
    Mockito.when(APIUtil.getAPIIdentifierFromUUID(Mockito.anyString())).thenReturn(apiId);
    Mockito.when(APIUtil.getAPIPath(apiId)).thenReturn(apiPath);
    PowerMockito.when(apiPersistenceInstance.addAPIRevision(any(Organization.class), Mockito.anyString(), Mockito.anyInt())).thenReturn("b55e0fc3-9829-4432-b99e-02056dc91838");
    Mockito.when(APIUtil.getTenantConfig(Mockito.anyString())).thenReturn(new JSONObject());
    try {
        apiProvider.addAPIRevision(apiRevision, superTenantDomain);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
Also used : ArtifactSaver(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.ArtifactSaver) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) JSONObject(org.json.simple.JSONObject) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) File(java.io.File) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) XMLStreamException(javax.xml.stream.XMLStreamException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) BlockConditionNotFoundException(org.wso2.carbon.apimgt.api.BlockConditionNotFoundException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) DuplicateAPIException(org.wso2.carbon.apimgt.api.model.DuplicateAPIException) IOException(java.io.IOException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) OMException(org.apache.axiom.om.OMException) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 28 with APIImportExportException

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

the class ExportUtils method getEndpointURLs.

/**
 * Get endpoint url list from endpoint config.
 *
 * @param endpointConfig JSON converted endpoint config
 * @param type           End point type - production/sandbox
 * @return List of host names
 */
private static List<String> getEndpointURLs(JSONObject endpointConfig, String type, String apiName) throws APIImportExportException {
    List<String> urls = new ArrayList<>();
    if (endpointConfig != null) {
        try {
            if (endpointConfig.has(type)) {
                Object item = endpointConfig.get(type);
                if (item instanceof JSONArray) {
                    JSONArray endpointsJSON = new JSONArray(endpointConfig.getJSONArray(type).toString());
                    for (int i = 0; i < endpointsJSON.length(); i++) {
                        try {
                            String urlValue = endpointsJSON.getJSONObject(i).get(APIConstants.API_DATA_URL).toString();
                            urls.add(urlValue);
                        } catch (JSONException ex) {
                            log.error("Endpoint URL extraction from endpoints JSON object failed in API: " + apiName, ex);
                        }
                    }
                } else if (item instanceof JSONObject) {
                    JSONObject endpointJSON = new JSONObject(endpointConfig.getJSONObject(type).toString());
                    try {
                        String urlValue = endpointJSON.get(APIConstants.API_DATA_URL).toString();
                        urls.add(urlValue);
                    } catch (JSONException ex) {
                        log.error("Endpoint URL extraction from endpoint JSON object failed in API: " + apiName, ex);
                    }
                }
            }
        } catch (JSONException ex) {
            throw new APIImportExportException("Endpoint type: " + type + " not found in API: " + apiName);
        }
    }
    return urls;
}
Also used : JSONObject(org.json.JSONObject) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.JSONObject)

Example 29 with APIImportExportException

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

the class ExportUtils method addDocumentationToArchive.

/**
 * Retrieve documentation for the exporting API or API Product and store it in the archive directory.
 * FILE, INLINE, MARKDOWN and URL documentations are handled.
 *
 * @param archivePath  File path to export the documents
 * @param identifier   ID of the requesting API or API Product
 * @param exportFormat Format for export
 * @param apiProvider  API Provider
 * @param type         Type of the Project (whether an API or an API Product)
 * @throws APIImportExportException If an error occurs while retrieving documents from the
 *                                  registry or storing in the archive directory
 * @throws APIManagementException   If an error occurs while retrieving document details
 */
public static void addDocumentationToArchive(String archivePath, Identifier identifier, ExportFormat exportFormat, APIProvider apiProvider, String type) throws APIImportExportException, APIManagementException {
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    List<Documentation> docList = StringUtils.equals(type, APIConstants.API_IDENTIFIER_TYPE) ? apiProvider.getAllDocumentation(identifier.getUUID(), tenantDomain) : apiProvider.getAllDocumentation(identifier);
    if (!docList.isEmpty()) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String docDirectoryPath = archivePath + File.separator + ImportExportConstants.DOCUMENT_DIRECTORY;
        CommonUtil.createDirectory(docDirectoryPath);
        try {
            for (Documentation doc : docList) {
                // Retrieving the document again since objects in docList might have missing fields
                Documentation individualDocument = apiProvider.getDocumentation(identifier.getUUID(), doc.getId(), tenantDomain);
                String sourceType = individualDocument.getSourceType().name();
                String resourcePath = null;
                InputStream inputStream = null;
                String localFileName = null;
                String individualDocDirectoryPath = docDirectoryPath + File.separator + cleanFolderName(individualDocument.getName());
                CommonUtil.createDirectory(individualDocDirectoryPath);
                DocumentationContent documentationContent = apiProvider.getDocumentationContent(identifier.getUUID(), doc.getId(), tenantDomain);
                if (documentationContent != null) {
                    if (Documentation.DocumentSourceType.FILE.toString().equalsIgnoreCase(sourceType)) {
                        localFileName = individualDocument.getFilePath().substring(individualDocument.getFilePath().lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1);
                        inputStream = documentationContent.getResourceFile().getContent();
                        individualDocument.setFilePath(localFileName);
                    } else if (Documentation.DocumentSourceType.INLINE.toString().equalsIgnoreCase(sourceType) || Documentation.DocumentSourceType.MARKDOWN.toString().equalsIgnoreCase(sourceType)) {
                        // Inline/Markdown content file name would be same as the documentation name
                        localFileName = individualDocument.getName();
                        inputStream = new ByteArrayInputStream(documentationContent.getTextContent().getBytes());
                    }
                }
                CommonUtil.writeDtoToFile(individualDocDirectoryPath + ImportExportConstants.DOCUMENT_FILE_NAME, exportFormat, ImportExportConstants.TYPE_DOCUMENTS, DocumentationMappingUtil.fromDocumentationToDTO(individualDocument));
                if (inputStream != null) {
                    // Check whether resource exists in the registry
                    try (OutputStream outputStream = new FileOutputStream(individualDocDirectoryPath + File.separator + localFileName)) {
                        IOUtils.copy(inputStream, outputStream);
                    }
                } else {
                    // Log error and avoid throwing as we give capability to export document artifact without
                    // the content if does not exists
                    log.error("Documentation resource for API/API Product: " + identifier.getName() + " not found in " + resourcePath);
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("Documentation retrieved successfully for API/API Product: " + identifier.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + identifier.getVersion());
            }
        } catch (IOException e) {
            throw new APIImportExportException("I/O error while writing documentation to file for API/API Product: " + identifier.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + identifier.getVersion(), e);
        }
    } else if (log.isDebugEnabled()) {
        log.debug("No documentation found for API/API Product: " + identifier + ". Skipping documentation export.");
    }
}
Also used : DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent) GsonBuilder(com.google.gson.GsonBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) Gson(com.google.gson.Gson) IOException(java.io.IOException)

Example 30 with APIImportExportException

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

the class ExportUtils method exportApi.

/**
 * Exports an API from API Manager for a given API. Meta information, API icon, documentation,
 * WSDL and sequences are exported.
 *
 * @param apiProvider          API Provider
 * @param apiIdentifier        API Identifier
 * @param apiDtoToReturn       API DTO
 * @param userName             Username
 * @param exportFormat         Format of output documents. Can be YAML or JSON
 * @param preserveStatus       Preserve API status on export
 * @param preserveDocs         Preserve documentation on Export.
 * @param originalDevPortalUrl Original DevPortal URL (redirect URL) for the original Store
 *                             (This is used for advertise only APIs).
 * @param organization          Organization
 * @return
 * @throws APIManagementException If an error occurs while getting governance registry
 */
public static File exportApi(APIProvider apiProvider, APIIdentifier apiIdentifier, APIDTO apiDtoToReturn, API api, String userName, ExportFormat exportFormat, boolean preserveStatus, boolean preserveDocs, String originalDevPortalUrl, String organization) throws APIManagementException, APIImportExportException {
    int tenantId;
    // If explicitly advertise only property has been specified as true, make it true and update the API DTO.
    if (StringUtils.isNotBlank(originalDevPortalUrl)) {
        setAdvertiseOnlySpecificPropertiesToDTO(apiDtoToReturn, originalDevPortalUrl);
    }
    // Create temp location for storing API data
    File exportFolder = CommonUtil.createTempDirectory(apiIdentifier);
    String exportAPIBasePath = exportFolder.toString();
    String archivePath = exportAPIBasePath.concat(File.separator + apiIdentifier.getApiName() + "-" + apiIdentifier.getVersion());
    tenantId = APIUtil.getTenantId(userName);
    CommonUtil.createDirectory(archivePath);
    if (preserveDocs) {
        addThumbnailToArchive(archivePath, apiIdentifier, apiProvider);
        addDocumentationToArchive(archivePath, apiIdentifier, exportFormat, apiProvider, APIConstants.API_IDENTIFIER_TYPE);
    } else {
        if (StringUtils.equals(apiDtoToReturn.getType().toString().toLowerCase(), APIConstants.API_TYPE_SOAPTOREST.toLowerCase())) {
            addSOAPToRESTMediationToArchive(archivePath, api);
        }
    }
    if (StringUtils.equals(apiDtoToReturn.getType().toString().toLowerCase(), APIConstants.API_TYPE_SOAP.toLowerCase()) && preserveDocs) {
        addWSDLtoArchive(archivePath, apiIdentifier, apiProvider);
    } else if (log.isDebugEnabled()) {
        log.debug("No WSDL URL found for API: " + apiIdentifier + ". Skipping WSDL export.");
    }
    // Set API status to created if the status is not preserved
    if (!preserveStatus) {
        apiDtoToReturn.setLifeCycleStatus(APIConstants.CREATED);
    }
    String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
    addOperationPoliciesToArchive(archivePath, apiDtoToReturn.getId(), tenantDomain, exportFormat, apiProvider, api);
    addGatewayEnvironmentsToArchive(archivePath, apiDtoToReturn.getId(), exportFormat, apiProvider);
    if (!ImportUtils.isAdvertiseOnlyAPI(apiDtoToReturn)) {
        addEndpointCertificatesToArchive(archivePath, apiDtoToReturn, tenantId, exportFormat);
        addRuntimeSequencesToArchive(archivePath, api);
        if (preserveDocs) {
            addMultipleAPISpecificSequencesToArchive(archivePath, api, apiProvider);
        }
        // Export mTLS authentication related certificates
        if (log.isDebugEnabled()) {
            log.debug("Mutual SSL enabled. Exporting client certificates.");
        }
        addClientCertificatesToArchive(archivePath, apiIdentifier, tenantId, apiProvider, exportFormat, organization);
    }
    addAPIMetaInformationToArchive(archivePath, apiDtoToReturn, exportFormat, apiProvider, apiIdentifier, organization);
    CommonUtil.archiveDirectory(exportAPIBasePath);
    FileUtils.deleteQuietly(new File(exportAPIBasePath));
    return new File(exportAPIBasePath + APIConstants.ZIP_FILE_EXTENSION);
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) 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