Search in sources :

Example 66 with Provider

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

the class ImportUtils method getLifeCycleAction.

/**
 * This method returns the lifecycle action which can be used to transit from currentStatus to targetStatus.
 *
 * @param tenantDomain  Tenant domain
 * @param currentStatus Current status to do status transition
 * @param targetStatus  Target status to do status transition
 * @return Lifecycle action or null if target is not reachable
 * @throws APIImportExportException If getting lifecycle action failed
 */
public static String getLifeCycleAction(String tenantDomain, String currentStatus, String targetStatus, APIProvider provider) throws APIManagementException {
    // No need to change the lifecycle if both the statuses are same
    if (StringUtils.equalsIgnoreCase(currentStatus, targetStatus)) {
        return null;
    }
    LifeCycle lifeCycle = new LifeCycle();
    // Parse DOM of APILifeCycle
    try {
        String data = provider.getLifecycleConfiguration(tenantDomain);
        DocumentBuilderFactory factory = APIUtil.getSecuredDocumentBuilder();
        DocumentBuilder builder = factory.newDocumentBuilder();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
        Document doc = builder.parse(inputStream);
        Element root = doc.getDocumentElement();
        // Get all nodes with state
        NodeList states = root.getElementsByTagName("state");
        int nStates = states.getLength();
        for (int i = 0; i < nStates; i++) {
            Node node = states.item(i);
            Node id = node.getAttributes().getNamedItem("id");
            if (id != null && !id.getNodeValue().isEmpty()) {
                LifeCycleTransition lifeCycleTransition = new LifeCycleTransition();
                NodeList transitions = node.getChildNodes();
                int nTransitions = transitions.getLength();
                for (int j = 0; j < nTransitions; j++) {
                    Node transition = transitions.item(j);
                    // Add transitions
                    if (ImportExportConstants.NODE_TRANSITION.equals(transition.getNodeName())) {
                        Node target = transition.getAttributes().getNamedItem("target");
                        Node action = transition.getAttributes().getNamedItem("event");
                        if (target != null && action != null) {
                            lifeCycleTransition.addTransition(target.getNodeValue().toLowerCase(), action.getNodeValue());
                        }
                    }
                }
                lifeCycle.addLifeCycleState(id.getNodeValue().toLowerCase(), lifeCycleTransition);
            }
        }
    } catch (ParserConfigurationException | SAXException e) {
        throw new APIManagementException("Error parsing APILifeCycle for tenant: " + tenantDomain, e);
    } catch (UnsupportedEncodingException e) {
        throw new APIManagementException("Error parsing unsupported encoding for APILifeCycle in tenant: " + tenantDomain, e);
    } catch (IOException e) {
        throw new APIManagementException("Error reading APILifeCycle for tenant: " + tenantDomain, e);
    }
    // Retrieve lifecycle action
    LifeCycleTransition transition = lifeCycle.getTransition(currentStatus.toLowerCase());
    if (transition != null) {
        return transition.getAction(targetStatus.toLowerCase());
    }
    return null;
}
Also used : LifeCycle(org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) JsonElement(com.google.gson.JsonElement) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) LifeCycleTransition(org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycleTransition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 67 with Provider

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

the class ImportUtils method importDependentAPIs.

/**
 * This method imports dependent APIs of the API Product.
 *
 * @param path                     Location of the extracted folder of the API Product
 * @param currentUser              The current logged in user
 * @param isDefaultProviderAllowed Decision to keep or replace the provider
 * @param apiProvider              API provider
 * @param overwriteAPIs            Whether to overwrite the APIs or not
 * @param apiProductDto            API Product DTO
 * @param tokenScopes              Scopes of the token
 * @param organization  Organization Identifier
 * @return Modified API Product DTO with the correct API UUIDs
 * @throws IOException              If there is an error while reading an API file
 * @throws APIImportExportException If there is an error in importing an API
 * @throws APIManagementException   If failed to get the API Provider of an API, or failed when
 *                                  checking the existence of an API
 */
private static APIProductDTO importDependentAPIs(String path, String currentUser, boolean isDefaultProviderAllowed, APIProvider apiProvider, boolean overwriteAPIs, Boolean rotateRevision, APIProductDTO apiProductDto, String[] tokenScopes, String organization) throws IOException, APIManagementException {
    JsonObject dependentAPIParamsConfigObject = null;
    // Retrieve the dependent APIs param configurations from the params file of the API Product
    JsonObject dependentAPIsParams = APIControllerUtil.getDependentAPIsParams(path);
    String apisDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY;
    File apisDirectory = new File(apisDirectoryPath);
    File[] apisDirectoryListing = apisDirectory.listFiles();
    if (apisDirectoryListing != null) {
        for (File apiDirectory : apisDirectoryListing) {
            String apiDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY + File.separator + apiDirectory.getName();
            // API in the API directory will be retrieved if available
            if (dependentAPIsParams != null) {
                dependentAPIParamsConfigObject = APIControllerUtil.getDependentAPIParams(dependentAPIsParams, apiDirectory.getName());
                // If the "certificates" directory is specified, copy it inside Deployment directory of the
                // dependent API since there may be certificates required for APIs
                String deploymentCertificatesDirectoryPath = path + ImportExportConstants.DEPLOYMENT_DIRECTORY + ImportExportConstants.CERTIFICATE_DIRECTORY;
                if (CommonUtil.checkFileExistence(deploymentCertificatesDirectoryPath)) {
                    try {
                        CommonUtil.copyDirectory(deploymentCertificatesDirectoryPath, apiDirectoryPath + ImportExportConstants.DEPLOYMENT_DIRECTORY + ImportExportConstants.CERTIFICATE_DIRECTORY);
                    } catch (APIImportExportException e) {
                        throw new APIManagementException("Error while copying the directory " + deploymentCertificatesDirectoryPath, e);
                    }
                }
            }
            JsonElement jsonObject = retrieveValidatedDTOObject(apiDirectoryPath, isDefaultProviderAllowed, currentUser, ImportExportConstants.TYPE_API);
            APIDTO apiDtoToImport = new Gson().fromJson(jsonObject, APIDTO.class);
            API importedApi = null;
            String apiName = apiDtoToImport.getName();
            String apiVersion = apiDtoToImport.getVersion();
            if (isDefaultProviderAllowed) {
                APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(apiDtoToImport.getProvider()), apiName, apiVersion);
                // Checking whether the API exists
                if (apiProvider.isAPIAvailable(apiIdentifier, organization)) {
                    // otherwise do not update the API. (Just skip it)
                    if (Boolean.TRUE.equals(overwriteAPIs)) {
                        importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.TRUE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
                    }
                } else {
                    // If the API is not already imported, import it
                    importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.FALSE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
                }
            } else {
                // Retrieve the current tenant domain of the logged in user
                String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser));
                // Get the provider of the API if the API is in current user's tenant domain.
                String apiProviderInCurrentTenantDomain = APIUtil.getAPIProviderFromAPINameVersionTenant(apiName, apiVersion, currentTenantDomain);
                if (StringUtils.isBlank(apiProviderInCurrentTenantDomain)) {
                    // If there is no API in the current tenant domain (which means the provider name is blank)
                    // then the API should be imported freshly
                    importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.FALSE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
                } else {
                    // otherwise do not import/update the API. (Just skip it)
                    if (Boolean.TRUE.equals(overwriteAPIs)) {
                        importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.TRUE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
                    }
                }
            }
            if (importedApi == null) {
                // Retrieve the API from the environment (This happens when you have not specified
                // the overwrite flag, so that we should retrieve the API from inside)
                importedApi = retrieveApiToOverwrite(apiDtoToImport.getName(), apiDtoToImport.getVersion(), MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)), apiProvider, Boolean.FALSE, organization);
            }
            updateApiUuidInApiProduct(apiProductDto, importedApi);
        }
    } else {
        String msg = "No dependent APIs supplied. Continuing ...";
        log.info(msg);
    }
    return apiProductDto;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) File(java.io.File)

Example 68 with Provider

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

the class ImportUtils method addAPIWsdl.

/**
 * This method adds the WSDL to the registry, if there is a WSDL associated with the API.
 *
 * @param pathToArchive Location of the extracted folder of the API
 * @param importedApi   The imported API object
 * @param apiProvider   API Provider
 * @throws APIManagementException If an error occurs while adding WSDL
 */
private static void addAPIWsdl(String pathToArchive, API importedApi, APIProvider apiProvider) throws APIManagementException {
    String wsdlFileName = importedApi.getId().getApiName() + "-" + importedApi.getId().getVersion() + APIConstants.WSDL_FILE_EXTENSION;
    String wsdlPath = pathToArchive + ImportExportConstants.WSDL_LOCATION + wsdlFileName;
    if (CommonUtil.checkFileExistence(wsdlPath)) {
        try (FileInputStream inputStream = new FileInputStream(wsdlPath)) {
            String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
            String fileExtension = FilenameUtils.getExtension(wsdlPath);
            PublisherCommonUtils.addWsdl(fileExtension, inputStream, importedApi, apiProvider, tenantDomain);
        } catch (FileNotFoundException e) {
            throw new APIManagementException("WSDL file of the API: " + importedApi.getId().getName() + " is not found.", e, ExceptionCodes.NO_WSDL_FOUND_IN_WSDL_ARCHIVE);
        } catch (IOException e) {
            throw new APIManagementException("Error reading the WSDL file of the API: " + importedApi.getId().getName(), e, ExceptionCodes.CANNOT_PROCESS_WSDL_CONTENT);
        }
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Example 69 with Provider

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

the class PublisherCommonUtils method addDocumentationContentForFile.

/**
 * Add documentation content of files.
 *
 * @param inputStream  Input Stream
 * @param mediaType    Media type of the document
 * @param filename     File name
 * @param apiProvider  API Provider
 * @param apiId        API/API Product UUID
 * @param documentId   Document ID
 * @param organization organization of the API
 * @throws APIManagementException If an error occurs while adding the documentation file
 */
public static void addDocumentationContentForFile(InputStream inputStream, String mediaType, String filename, APIProvider apiProvider, String apiId, String documentId, String organization) throws APIManagementException {
    DocumentationContent content = new DocumentationContent();
    ResourceFile resourceFile = new ResourceFile(inputStream, mediaType);
    resourceFile.setName(filename);
    content.setResourceFile(resourceFile);
    content.setSourceType(DocumentationContent.ContentSourceType.FILE);
    apiProvider.addDocumentationContent(apiId, documentId, organization, content);
}
Also used : DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile)

Example 70 with Provider

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

the class PublisherCommonUtils method addWsdl.

/**
 * Add WSDL file of an API.
 *
 * @param fileContentType Content type of the file
 * @param fileInputStream Input Stream
 * @param api             API to which the WSDL belongs to
 * @param apiProvider     API Provider
 * @param tenantDomain    Tenant domain of the API
 * @throws APIManagementException If an error occurs while adding the WSDL resource
 */
public static void addWsdl(String fileContentType, InputStream fileInputStream, API api, APIProvider apiProvider, String tenantDomain) throws APIManagementException {
    ResourceFile wsdlResource;
    if (APIConstants.APPLICATION_ZIP.equals(fileContentType) || APIConstants.APPLICATION_X_ZIP_COMPRESSED.equals(fileContentType)) {
        wsdlResource = new ResourceFile(fileInputStream, APIConstants.APPLICATION_ZIP);
    } else {
        wsdlResource = new ResourceFile(fileInputStream, fileContentType);
    }
    api.setWsdlResource(wsdlResource);
    apiProvider.addWSDLResource(api.getUuid(), wsdlResource, null, tenantDomain);
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)82 ArrayList (java.util.ArrayList)70 API (org.wso2.carbon.apimgt.api.model.API)64 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)50 Test (org.junit.Test)49 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)45 HashMap (java.util.HashMap)40 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)36 IOException (java.io.IOException)35 Resource (org.wso2.carbon.registry.core.Resource)34 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)32 HashSet (java.util.HashSet)30 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)29 UserStoreException (org.wso2.carbon.user.api.UserStoreException)29 PreparedStatement (java.sql.PreparedStatement)28 Connection (java.sql.Connection)27 SQLException (java.sql.SQLException)27 ResultSet (java.sql.ResultSet)25 QName (javax.xml.namespace.QName)25 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)25