Search in sources :

Example 61 with Property

use of org.wso2.carbon.identity.application.common.model.Property in project carbon-apimgt by wso2.

the class AbstractAPIManager method searchPaginatedAPIsByContent.

/**
 * Search api resources by their content
 *
 * @param registry
 * @param searchQuery
 * @param start
 * @param end
 * @return
 * @throws APIManagementException
 */
public Map<String, Object> searchPaginatedAPIsByContent(Registry registry, int tenantId, String searchQuery, int start, int end, boolean limitAttributes) throws APIManagementException {
    SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator());
    SortedSet<APIProduct> apiProductSet = new TreeSet<APIProduct>(new APIProductNameComparator());
    Map<Documentation, API> docMap = new HashMap<Documentation, API>();
    Map<Documentation, APIProduct> productDocMap = new HashMap<Documentation, APIProduct>();
    Map<String, Object> result = new HashMap<String, Object>();
    int totalLength = 0;
    boolean isMore = false;
    // SortedSet<Object> compoundResult = new TreeSet<Object>(new ContentSearchResultNameComparator());
    ArrayList<Object> compoundResult = new ArrayList<Object>();
    try {
        GenericArtifactManager apiArtifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifactManager docArtifactManager = APIUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
        String paginationLimit = getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_APIS_PER_PAGE);
        // If the Config exists use it to set the pagination limit
        final int maxPaginationLimit;
        if (paginationLimit != null) {
            // The additional 1 added to the maxPaginationLimit is to help us determine if more
            // APIs may exist so that we know that we are unable to determine the actual total
            // API count. We will subtract this 1 later on so that it does not interfere with
            // the logic of the rest of the application
            int pagination = Integer.parseInt(paginationLimit);
            // leading to some of the APIs not being displayed
            if (pagination < 11) {
                pagination = 11;
                log.warn("Value of '" + APIConstants.API_STORE_APIS_PER_PAGE + "' is too low, defaulting to 11");
            }
            maxPaginationLimit = start + pagination + 1;
        } else // Else if the config is not specified we go with default functionality and load all
        {
            maxPaginationLimit = Integer.MAX_VALUE;
        }
        PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        if (tenantId == -1) {
            tenantId = MultitenantConstants.SUPER_TENANT_ID;
        }
        UserRegistry systemUserRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getRegistry(CarbonConstants.REGISTRY_SYSTEM_USERNAME, tenantId);
        ContentBasedSearchService contentBasedSearchService = new ContentBasedSearchService();
        String newSearchQuery = getSearchQuery(searchQuery);
        String[] searchQueries = newSearchQuery.split("&");
        String apiState = "";
        String publisherRoles = "";
        Map<String, String> attributes = new HashMap<String, String>();
        for (String searchCriterea : searchQueries) {
            String[] keyVal = searchCriterea.split("=");
            if (APIConstants.STORE_VIEW_ROLES.equals(keyVal[0])) {
                attributes.put("propertyName", keyVal[0]);
                attributes.put("rightPropertyValue", keyVal[1]);
                attributes.put("rightOp", "eq");
            } else if (APIConstants.PUBLISHER_ROLES.equals(keyVal[0])) {
                publisherRoles = keyVal[1];
            } else {
                if (APIConstants.LCSTATE_SEARCH_KEY.equals(keyVal[0])) {
                    apiState = keyVal[1];
                    continue;
                }
                attributes.put(keyVal[0], keyVal[1]);
            }
        }
        // check whether the new document indexer is engaged
        RegistryConfigLoader registryConfig = RegistryConfigLoader.getInstance();
        Map<String, Indexer> indexerMap = registryConfig.getIndexerMap();
        Indexer documentIndexer = indexerMap.get(APIConstants.DOCUMENT_MEDIA_TYPE_KEY);
        String complexAttribute;
        if (documentIndexer != null && documentIndexer instanceof DocumentIndexer) {
            // field check on document_indexed was added to prevent unindexed(by new DocumentIndexer) from coming up as search results
            // on indexed documents this property is always set to true
            complexAttribute = ClientUtils.escapeQueryChars(APIConstants.API_RXT_MEDIA_TYPE) + " OR mediaType_s:(" + ClientUtils.escapeQueryChars(APIConstants.DOCUMENT_RXT_MEDIA_TYPE) + " AND document_indexed_s:true)";
            // this was designed this way so that content search can be fully functional if registry is re-indexed after engaging DocumentIndexer
            if (!StringUtils.isEmpty(publisherRoles)) {
                complexAttribute = "(" + ClientUtils.escapeQueryChars(APIConstants.API_RXT_MEDIA_TYPE) + " AND publisher_roles_ss:" + publisherRoles + ") OR mediaType_s:(" + ClientUtils.escapeQueryChars(APIConstants.DOCUMENT_RXT_MEDIA_TYPE) + " AND publisher_roles_s:" + publisherRoles + ")";
            }
        } else {
            // document indexer required for document content search is not engaged, therefore carry out the search only for api artifact contents
            complexAttribute = ClientUtils.escapeQueryChars(APIConstants.API_RXT_MEDIA_TYPE);
            if (!StringUtils.isEmpty(publisherRoles)) {
                complexAttribute = "(" + ClientUtils.escapeQueryChars(APIConstants.API_RXT_MEDIA_TYPE) + " AND publisher_roles_ss:" + publisherRoles + ")";
            }
        }
        attributes.put(APIConstants.DOCUMENTATION_SEARCH_MEDIA_TYPE_FIELD, complexAttribute);
        attributes.put(APIConstants.API_OVERVIEW_STATUS, apiState);
        SearchResultsBean resultsBean = contentBasedSearchService.searchByAttribute(attributes, systemUserRegistry);
        String errorMsg = resultsBean.getErrorMessage();
        if (errorMsg != null) {
            handleException(errorMsg);
        }
        ResourceData[] resourceData = resultsBean.getResourceDataList();
        if (resourceData == null || resourceData.length == 0) {
            result.put("apis", compoundResult);
            result.put("length", 0);
            result.put("isMore", isMore);
        }
        totalLength = PaginationContext.getInstance().getLength();
        // Check to see if we can speculate that there are more APIs to be loaded
        if (maxPaginationLimit == totalLength) {
            // More APIs exist, cannot determine total API count without incurring perf hit
            isMore = true;
            // Remove the additional 1 added earlier when setting max pagination limit
            --totalLength;
        }
        for (ResourceData data : resourceData) {
            String resourcePath = data.getResourcePath();
            if (resourcePath.contains(APIConstants.APIMGT_REGISTRY_LOCATION)) {
                int index = resourcePath.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
                resourcePath = resourcePath.substring(index);
                Resource resource = registry.get(resourcePath);
                if (APIConstants.DOCUMENT_RXT_MEDIA_TYPE.equals(resource.getMediaType()) || APIConstants.DOCUMENTATION_INLINE_CONTENT_TYPE.equals(resource.getMediaType())) {
                    if (resourcePath.contains(APIConstants.INLINE_DOCUMENT_CONTENT_DIR)) {
                        int indexOfContents = resourcePath.indexOf(APIConstants.INLINE_DOCUMENT_CONTENT_DIR);
                        resourcePath = resourcePath.substring(0, indexOfContents) + data.getName();
                    }
                    Resource docResource = registry.get(resourcePath);
                    String docArtifactId = docResource.getUUID();
                    GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docArtifactId);
                    Documentation doc = APIUtil.getDocumentation(docArtifact);
                    API associatedAPI = null;
                    APIProduct associatedAPIProduct = null;
                    int indexOfDocumentation = resourcePath.indexOf(APIConstants.DOCUMENTATION_KEY);
                    String apiPath = resourcePath.substring(0, indexOfDocumentation) + APIConstants.API_KEY;
                    Resource apiResource = registry.get(apiPath);
                    String apiArtifactId = apiResource.getUUID();
                    if (apiArtifactId != null) {
                        GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
                        if (apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE).equals(APIConstants.AuditLogConstants.API_PRODUCT)) {
                            associatedAPIProduct = APIUtil.getAPIProduct(apiArtifact, registry);
                        } else {
                            associatedAPI = APIUtil.getAPI(apiArtifact, registry);
                        }
                    } else {
                        throw new GovernanceException("artifact id is null of " + apiPath);
                    }
                    if (associatedAPI != null && doc != null) {
                        docMap.put(doc, associatedAPI);
                    }
                    if (associatedAPIProduct != null && doc != null) {
                        productDocMap.put(doc, associatedAPIProduct);
                    }
                } else {
                    String apiArtifactId = resource.getUUID();
                    API api;
                    APIProduct apiProduct;
                    if (apiArtifactId != null) {
                        GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
                        if (apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE).equals(APIConstants.API_PRODUCT)) {
                            apiProduct = APIUtil.getAPIProduct(apiArtifact, registry);
                            apiProductSet.add(apiProduct);
                        } else {
                            api = APIUtil.getAPI(apiArtifact, registry);
                            apiSet.add(api);
                        }
                    } else {
                        throw new GovernanceException("artifact id is null for " + resourcePath);
                    }
                }
            }
        }
        compoundResult.addAll(apiSet);
        compoundResult.addAll(apiProductSet);
        compoundResult.addAll(docMap.entrySet());
        compoundResult.addAll(productDocMap.entrySet());
        compoundResult.sort(new ContentSearchResultNameComparator());
    } catch (RegistryException e) {
        handleException("Failed to search APIs by content", e);
    } catch (IndexerException e) {
        handleException("Failed to search APIs by content", e);
    }
    result.put("apis", compoundResult);
    result.put("length", totalLength);
    result.put("isMore", isMore);
    return result;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) DocumentIndexer(org.wso2.carbon.apimgt.impl.indexing.indexer.DocumentIndexer) Indexer(org.wso2.carbon.registry.indexing.indexer.Indexer) TreeSet(java.util.TreeSet) SearchResultsBean(org.wso2.carbon.registry.indexing.service.SearchResultsBean) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) DocumentIndexer(org.wso2.carbon.apimgt.impl.indexing.indexer.DocumentIndexer) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) ResourceData(org.wso2.carbon.registry.common.ResourceData) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) ContentBasedSearchService(org.wso2.carbon.registry.indexing.service.ContentBasedSearchService) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) RegistryConfigLoader(org.wso2.carbon.registry.indexing.RegistryConfigLoader) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) JSONObject(org.json.simple.JSONObject) ContentSearchResultNameComparator(org.wso2.carbon.apimgt.impl.utils.ContentSearchResultNameComparator) APIAPIProductNameComparator(org.wso2.carbon.apimgt.impl.utils.APIAPIProductNameComparator) APIProductNameComparator(org.wso2.carbon.apimgt.impl.utils.APIProductNameComparator)

Example 62 with Property

use of org.wso2.carbon.identity.application.common.model.Property in project carbon-apimgt by wso2.

the class APIProviderImpl method updateApiArtifact.

private String updateApiArtifact(API api, boolean updateMetadata, boolean updatePermissions) throws APIManagementException {
    // Validate Transports
    validateAndSetTransports(api);
    validateAndSetAPISecurity(api);
    boolean transactionCommitted = false;
    String apiUUID = null;
    try {
        registry.beginTransaction();
        String apiArtifactId = registry.get(APIUtil.getAPIPath(api.getId())).getUUID();
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when updating API artifact ID " + api.getId();
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        String oldStatus = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
        Resource apiResource = registry.get(artifact.getPath());
        String oldAccessControlRoles = api.getAccessControlRoles();
        if (apiResource != null) {
            oldAccessControlRoles = registry.get(artifact.getPath()).getProperty(APIConstants.PUBLISHER_ROLES);
        }
        GenericArtifact updateApiArtifact = APIUtil.createAPIArtifactContent(artifact, api);
        String artifactPath = GovernanceUtils.getArtifactPath(registry, updateApiArtifact.getId());
        org.wso2.carbon.registry.core.Tag[] oldTags = registry.getTags(artifactPath);
        if (oldTags != null) {
            for (org.wso2.carbon.registry.core.Tag tag : oldTags) {
                registry.removeTag(artifactPath, tag.getTagName());
            }
        }
        Set<String> tagSet = api.getTags();
        if (tagSet != null) {
            for (String tag : tagSet) {
                registry.applyTag(artifactPath, tag);
            }
        }
        if (updateMetadata && api.getEndpointConfig() != null && !api.getEndpointConfig().isEmpty()) {
            // If WSDL URL get change only we update registry WSDL resource. If its registry resource patch we
            // will skip registry update. Only if this API created with WSDL end point type we need to update
            // wsdls for each update.
            // check for wsdl endpoint
            org.json.JSONObject response1 = new org.json.JSONObject(api.getEndpointConfig());
            boolean isWSAPI = APIConstants.APITransportType.WS.toString().equals(api.getType());
            String wsdlURL;
            if (!APIUtil.isStreamingApi(api) && "wsdl".equalsIgnoreCase(response1.get("endpoint_type").toString()) && response1.has("production_endpoints")) {
                wsdlURL = response1.getJSONObject("production_endpoints").get("url").toString();
                if (APIUtil.isValidWSDLURL(wsdlURL, true)) {
                    String path = APIUtil.createWSDL(registry, api);
                    if (path != null) {
                        // reset the wsdl path to permlink
                        updateApiArtifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
                    }
                }
            }
        }
        artifactManager.updateGenericArtifact(updateApiArtifact);
        // write API Status to a separate property. This is done to support querying APIs using custom query (SQL)
        // to gain performance
        String apiStatus = api.getStatus().toUpperCase();
        saveAPIStatus(artifactPath, apiStatus);
        String[] visibleRoles = new String[0];
        String publisherAccessControlRoles = api.getAccessControlRoles();
        updateRegistryResources(artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
        // propagate api status change and access control roles change to document artifact
        String newStatus = updateApiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
        if (!StringUtils.equals(oldStatus, newStatus) || !StringUtils.equals(oldAccessControlRoles, publisherAccessControlRoles)) {
            APIUtil.notifyAPIStateChangeToAssociatedDocuments(artifact, registry);
        }
        if (updatePermissions) {
            APIUtil.clearResourcePermissions(artifactPath, api.getId(), ((UserRegistry) registry).getTenantId());
            String visibleRolesList = api.getVisibleRoles();
            if (visibleRolesList != null) {
                visibleRoles = visibleRolesList.split(",");
            }
            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
        }
        // attaching api categories to the API
        List<APICategory> attachedApiCategories = api.getApiCategories();
        artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
        if (attachedApiCategories != null) {
            for (APICategory category : attachedApiCategories) {
                artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
            }
        }
        registry.commitTransaction();
        transactionCommitted = true;
        apiUUID = updateApiArtifact.getId();
        if (updatePermissions) {
            APIManagerConfiguration config = getAPIManagerConfiguration();
            boolean isSetDocLevelPermissions = Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_API_DOC_VISIBILITY_LEVELS));
            String docRootPath = APIUtil.getAPIDocPath(api.getId());
            if (isSetDocLevelPermissions) {
                // Retain the docs
                List<Documentation> docs = getAllDocumentation(api.getId());
                for (Documentation doc : docs) {
                    if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
                        String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
                        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
                        if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
                            String contentPath = APIUtil.getAPIDocContentPath(api.getId(), doc.getName());
                            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, contentPath, registry);
                        } else if (Documentation.DocumentSourceType.FILE.equals(doc.getSourceType()) && doc.getFilePath() != null) {
                            String filePath = APIUtil.getDocumentationFilePath(api.getId(), doc.getFilePath().split("files" + RegistryConstants.PATH_SEPARATOR)[1]);
                            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, filePath, registry);
                        }
                    }
                }
            } else {
                APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, docRootPath, registry);
            }
        } else {
            // In order to support content search feature - we need to update resource permissions of document resources
            // if their visibility is set to API level.
            List<Documentation> docs = getAllDocumentation(api.getId());
            if (docs != null) {
                for (Documentation doc : docs) {
                    if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
                        String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
                        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
                    }
                }
            }
        }
    } catch (Exception e) {
        try {
            registry.rollbackTransaction();
        } catch (RegistryException re) {
            // Throwing an error from this level will mask the original exception
            log.error("Error while rolling back the transaction for API: " + api.getId().getApiName(), re);
        }
        handleException("Error while performing registry transaction operation", e);
    } finally {
        try {
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException ex) {
            handleException("Error occurred while rolling back the transaction.", ex);
        }
    }
    return apiUUID;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) XMLStreamException(javax.xml.stream.XMLStreamException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) IOException(java.io.IOException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.PersistenceException) UnsupportedPolicyTypeException(org.wso2.carbon.apimgt.api.UnsupportedPolicyTypeException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) NotificationException(org.wso2.carbon.apimgt.impl.notification.exception.NotificationException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) OMException(org.apache.axiom.om.OMException) JSONObject(org.json.simple.JSONObject) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 63 with Property

use of org.wso2.carbon.identity.application.common.model.Property in project carbon-apimgt by wso2.

the class APIManagerConfiguration method readChildElements.

private void readChildElements(OMElement serverConfig, Stack<String> nameStack) throws APIManagementException {
    for (Iterator childElements = serverConfig.getChildElements(); childElements.hasNext(); ) {
        OMElement element = (OMElement) childElements.next();
        String localName = element.getLocalName();
        nameStack.push(localName);
        if ("APIKeyValidator".equals(localName)) {
            OMElement keyManagerServiceUrl = element.getFirstChildWithName(new QName(APIConstants.AUTHSERVER_URL));
            if (keyManagerServiceUrl != null) {
                String serviceUrl = keyManagerServiceUrl.getText();
                addKeyManagerConfigsAsSystemProperties(APIUtil.replaceSystemProperty(serviceUrl));
            }
        } else if (TOKEN_REVOCATION_NOTIFIERS.equals(localName)) {
            tokenRevocationClassName = element.getAttributeValue(new QName("class"));
        } else if (REALTIME_NOTIFIER.equals(localName)) {
            Iterator revocationPropertiesIterator = element.getChildrenWithLocalName("Property");
            Properties properties = new Properties();
            while (revocationPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) revocationPropertiesIterator.next();
                properties.setProperty(propertyElem.getAttributeValue(new QName("name")), propertyElem.getText());
            }
            realtimeNotifierProperties = properties;
        } else if (PERSISTENT_NOTIFIER.equals(localName)) {
            Iterator revocationPropertiesIterator = element.getChildrenWithLocalName("Property");
            Properties properties = new Properties();
            while (revocationPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) revocationPropertiesIterator.next();
                if (propertyElem.getAttributeValue(new QName("name")).equalsIgnoreCase("password")) {
                    if (secretResolver.isInitialized() && secretResolver.isTokenProtected(TOKEN_REVOCATION_NOTIFIERS_PASSWORD)) {
                        properties.setProperty(propertyElem.getAttributeValue(new QName("name")), secretResolver.resolve(TOKEN_REVOCATION_NOTIFIERS_PASSWORD));
                    } else {
                        properties.setProperty(propertyElem.getAttributeValue(new QName("name")), propertyElem.getText());
                    }
                } else {
                    properties.setProperty(propertyElem.getAttributeValue(new QName("name")), propertyElem.getText());
                }
            }
            persistentNotifierProperties = properties;
        } else if ("Analytics".equals(localName)) {
            OMElement properties = element.getFirstChildWithName(new QName("Properties"));
            Iterator analyticsPropertiesIterator = properties.getChildrenWithLocalName("Property");
            Map<String, String> analyticsProps = new HashMap<>();
            while (analyticsPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) analyticsPropertiesIterator.next();
                String name = propertyElem.getAttributeValue(new QName("name"));
                String value = propertyElem.getText();
                analyticsProps.put(name, value);
            }
            OMElement authTokenElement = element.getFirstChildWithName(new QName("AuthToken"));
            String resolvedAuthToken = MiscellaneousUtil.resolve(authTokenElement, secretResolver);
            analyticsProps.put("auth.api.token", resolvedAuthToken);
            analyticsProperties = analyticsProps;
        } else if ("PersistenceConfigs".equals(localName)) {
            OMElement properties = element.getFirstChildWithName(new QName("Properties"));
            Iterator analyticsPropertiesIterator = properties.getChildrenWithLocalName("Property");
            Map<String, String> persistenceProps = new HashMap<>();
            while (analyticsPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) analyticsPropertiesIterator.next();
                String name = propertyElem.getAttributeValue(new QName("name"));
                String value = propertyElem.getText();
                persistenceProps.put(name, value);
            }
            persistenceProperties = persistenceProps;
        } else if (APIConstants.REDIS_CONFIG.equals(localName)) {
            OMElement redisHost = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_HOST));
            OMElement redisPort = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_PORT));
            OMElement redisUser = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_USER));
            OMElement redisPassword = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_PASSWORD));
            OMElement redisDatabaseId = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_DATABASE_ID));
            OMElement redisConnectionTimeout = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_CONNECTION_TIMEOUT));
            OMElement redisIsSslEnabled = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_IS_SSL_ENABLED));
            OMElement propertiesElement = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_PROPERTIES));
            redisConfig.setRedisEnabled(true);
            redisConfig.setHost(redisHost.getText());
            redisConfig.setPort(Integer.parseInt(redisPort.getText()));
            if (redisUser != null && redisPassword != null && redisDatabaseId != null && redisConnectionTimeout != null && redisIsSslEnabled != null) {
                redisConfig.setUser(redisUser.getText());
                redisConfig.setPassword(MiscellaneousUtil.resolve(redisPassword, secretResolver).toCharArray());
                redisConfig.setDatabaseId(Integer.parseInt(redisDatabaseId.getText()));
                redisConfig.setConnectionTimeout(Integer.parseInt(redisConnectionTimeout.getText()));
                redisConfig.setSslEnabled(Boolean.parseBoolean(redisIsSslEnabled.getText()));
            }
            if (propertiesElement != null) {
                Iterator<OMElement> properties = propertiesElement.getChildElements();
                if (properties != null) {
                    while (properties.hasNext()) {
                        OMElement propertyNode = properties.next();
                        if (APIConstants.CONFIG_REDIS_MAX_TOTAL.equals(propertyNode.getLocalName())) {
                            redisConfig.setMaxTotal(Integer.parseInt(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_MAX_IDLE.equals(propertyNode.getLocalName())) {
                            redisConfig.setMaxIdle(Integer.parseInt(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_MIN_IDLE.equals(propertyNode.getLocalName())) {
                            redisConfig.setMinIdle(Integer.parseInt(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TEST_ON_BORROW.equals(propertyNode.getLocalName())) {
                            redisConfig.setTestOnBorrow(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TEST_ON_RETURN.equals(propertyNode.getLocalName())) {
                            redisConfig.setTestOnReturn(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TEST_WHILE_IDLE.equals(propertyNode.getLocalName())) {
                            redisConfig.setTestWhileIdle(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_BLOCK_WHEN_EXHAUSTED.equals(propertyNode.getLocalName())) {
                            redisConfig.setBlockWhenExhausted(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_MIN_EVICTABLE_IDLE_TIME_IN_MILLIS.equals(propertyNode.getLocalName())) {
                            redisConfig.setMinEvictableIdleTimeMillis(Long.parseLong(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TIME_BETWEEN_EVICTION_RUNS_IN_MILLIS.equals(propertyNode.getLocalName())) {
                            redisConfig.setTimeBetweenEvictionRunsMillis(Long.parseLong(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_NUM_TESTS_PER_EVICTION_RUNS.equals(propertyNode.getLocalName())) {
                            redisConfig.setNumTestsPerEvictionRun(Integer.parseInt(propertyNode.getText()));
                        }
                    }
                }
            }
        } else if (elementHasText(element)) {
            String key = getKey(nameStack);
            String value = MiscellaneousUtil.resolve(element, secretResolver);
            addToConfiguration(key, APIUtil.replaceSystemProperty(value));
        } else if ("Environments".equals(localName)) {
            Iterator environmentIterator = element.getChildrenWithLocalName("Environment");
            apiGatewayEnvironments = new LinkedHashMap<String, Environment>();
            while (environmentIterator.hasNext()) {
                OMElement environmentElem = (OMElement) environmentIterator.next();
                setEnvironmentConfig(environmentElem);
            }
        } else if (APIConstants.EXTERNAL_API_STORES.equals(localName)) {
            // Initialize 'externalAPIStores' config elements
            Iterator apistoreIterator = element.getChildrenWithLocalName("ExternalAPIStore");
            externalAPIStores = new HashSet<APIStore>();
            while (apistoreIterator.hasNext()) {
                APIStore store = new APIStore();
                OMElement storeElem = (OMElement) apistoreIterator.next();
                String type = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_TYPE));
                // Set Store type [eg:wso2]
                store.setType(type);
                String className = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_CLASS_NAME));
                try {
                    store.setPublisher((APIPublisher) APIUtil.getClassInstance(className));
                } catch (InstantiationException e) {
                    String msg = "One or more classes defined in" + APIConstants.EXTERNAL_API_STORE_CLASS_NAME + "cannot be instantiated";
                    log.error(msg, e);
                    throw new APIManagementException(msg, e);
                } catch (IllegalAccessException e) {
                    String msg = "One or more classes defined in" + APIConstants.EXTERNAL_API_STORE_CLASS_NAME + "cannot be access";
                    log.error(msg, e);
                    throw new APIManagementException(msg, e);
                } catch (ClassNotFoundException e) {
                    String msg = "One or more classes defined in" + APIConstants.EXTERNAL_API_STORE_CLASS_NAME + "cannot be found";
                    log.error(msg, e);
                    throw new APIManagementException(msg, e);
                }
                String name = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_ID));
                if (name == null) {
                    log.error("The ExternalAPIStore name attribute is not defined in api-manager.xml.");
                }
                // Set store name
                store.setName(name);
                OMElement configDisplayName = storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_DISPLAY_NAME));
                String displayName = (configDisplayName != null) ? APIUtil.replaceSystemProperty(configDisplayName.getText()) : name;
                // Set store display name
                store.setDisplayName(displayName);
                store.setEndpoint(APIUtil.replaceSystemProperty(storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_ENDPOINT)).getText()));
                store.setPublished(false);
                if (APIConstants.WSO2_API_STORE_TYPE.equals(type)) {
                    OMElement password = storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_PASSWORD));
                    if (password != null) {
                        String value = MiscellaneousUtil.resolve(password, secretResolver);
                        store.setPassword(APIUtil.replaceSystemProperty(value));
                        store.setUsername(APIUtil.replaceSystemProperty(storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_USERNAME)).getText()));
                    } else {
                        log.error("The user-credentials of API Publisher is not defined in the <ExternalAPIStore> " + "config of api-manager.xml.");
                    }
                }
                externalAPIStores.add(store);
            }
        } else if (APIConstants.LOGIN_CONFIGS.equals(localName)) {
            Iterator loginConfigIterator = element.getChildrenWithLocalName(APIConstants.LOGIN_CONFIGS);
            while (loginConfigIterator.hasNext()) {
                OMElement loginOMElement = (OMElement) loginConfigIterator.next();
                parseLoginConfig(loginOMElement);
            }
        } else if (APIConstants.AdvancedThrottleConstants.THROTTLING_CONFIGURATIONS.equals(localName)) {
            setThrottleProperties(serverConfig);
        } else if (APIConstants.WorkflowConfigConstants.WORKFLOW.equals(localName)) {
            setWorkflowProperties(serverConfig);
        } else if (APIConstants.ApplicationAttributes.APPLICATION_ATTRIBUTES.equals(localName)) {
            Iterator iterator = element.getChildrenWithLocalName(APIConstants.ApplicationAttributes.ATTRIBUTE);
            while (iterator.hasNext()) {
                OMElement omElement = (OMElement) iterator.next();
                Iterator attributes = omElement.getChildElements();
                JSONObject jsonObject = new JSONObject();
                boolean isHidden = Boolean.parseBoolean(omElement.getAttributeValue(new QName(APIConstants.ApplicationAttributes.HIDDEN)));
                boolean isRequired = Boolean.parseBoolean(omElement.getAttributeValue(new QName(APIConstants.ApplicationAttributes.REQUIRED)));
                jsonObject.put(APIConstants.ApplicationAttributes.HIDDEN, isHidden);
                while (attributes.hasNext()) {
                    OMElement attribute = (OMElement) attributes.next();
                    if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.NAME)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.ATTRIBUTE, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.DESCRIPTION)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.DESCRIPTION, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.TOOLTIP)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.TOOLTIP, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.TYPE)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.TYPE, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.DEFAULT) && isRequired) {
                        jsonObject.put(APIConstants.ApplicationAttributes.DEFAULT, attribute.getText());
                    }
                }
                if (isHidden && isRequired && !jsonObject.containsKey(APIConstants.ApplicationAttributes.DEFAULT)) {
                    log.error("A default value needs to be given for required, hidden application attributes.");
                }
                jsonObject.put(APIConstants.ApplicationAttributes.REQUIRED, isRequired);
                applicationAttributes.add(jsonObject);
            }
        } else if (APIConstants.Monetization.MONETIZATION_CONFIG.equals(localName)) {
            OMElement additionalAttributes = element.getFirstChildWithName(new QName(APIConstants.Monetization.ADDITIONAL_ATTRIBUTES));
            if (additionalAttributes != null) {
                setMonetizationAdditionalAttributes(additionalAttributes);
            }
        } else if (APIConstants.JWT_CONFIGS.equals(localName)) {
            setJWTConfiguration(element);
        } else if (APIConstants.TOKEN_ISSUERS.equals(localName)) {
            setJWTTokenIssuers(element);
        } else if (APIConstants.API_RECOMMENDATION.equals(localName)) {
            setRecommendationConfigurations(element);
        } else if (APIConstants.GlobalCacheInvalidation.GLOBAL_CACHE_INVALIDATION.equals(localName)) {
            setGlobalCacheInvalidationConfiguration(element);
        } else if (APIConstants.KeyManager.EVENT_HUB_CONFIGURATIONS.equals(localName)) {
            setEventHubConfiguration(element);
        } else if (APIConstants.GatewayArtifactSynchronizer.SYNC_RUNTIME_ARTIFACTS_PUBLISHER_CONFIG.equals(localName)) {
            setRuntimeArtifactsSyncPublisherConfig(element);
        } else if (APIConstants.GatewayArtifactSynchronizer.SYNC_RUNTIME_ARTIFACTS_GATEWAY_CONFIG.equals(localName)) {
            setRuntimeArtifactsSyncGatewayConfig(element);
        } else if (APIConstants.SkipListConstants.SKIP_LIST_CONFIG.equals(localName)) {
            setSkipListConfigurations(element);
        } else if (APIConstants.ExtensionListenerConstants.EXTENSION_LISTENERS.equals(localName)) {
            setExtensionListenerConfigurations(element);
        } else if (APIConstants.JWT_AUDIENCES.equals(localName)) {
            setRestApiJWTAuthAudiences(element);
        }
        readChildElements(element, nameStack);
        nameStack.pop();
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) GatewayArtifactSynchronizerProperties(org.wso2.carbon.apimgt.impl.dto.GatewayArtifactSynchronizerProperties) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) Properties(java.util.Properties) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) Iterator(java.util.Iterator) Environment(org.wso2.carbon.apimgt.api.model.Environment) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment) APIPublisher(org.wso2.carbon.apimgt.api.model.APIPublisher) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet) APIStore(org.wso2.carbon.apimgt.api.model.APIStore)

Example 64 with Property

use of org.wso2.carbon.identity.application.common.model.Property in project carbon-apimgt by wso2.

the class APIManagerConfiguration method setEnvironmentConfig.

/**
 * Set property values for each gateway environments defined in the api-manager.xml config file
 *
 * @param environmentElem OMElement of a single environment in the gateway environments list
 */
void setEnvironmentConfig(OMElement environmentElem) throws APIManagementException {
    Environment environment = new Environment();
    environment.setType(environmentElem.getAttributeValue(new QName("type")));
    String showInConsole = environmentElem.getAttributeValue(new QName("api-console"));
    if (showInConsole != null) {
        environment.setShowInConsole(Boolean.parseBoolean(showInConsole));
    } else {
        environment.setShowInConsole(true);
    }
    String isDefault = environmentElem.getAttributeValue(new QName("isDefault"));
    if (isDefault != null) {
        environment.setDefault(Boolean.parseBoolean(isDefault));
    } else {
        environment.setDefault(false);
    }
    environment.setName(APIUtil.replaceSystemProperty(environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_NAME)).getText()));
    environment.setDisplayName(APIUtil.replaceSystemProperty(environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_DISPLAY_NAME)).getText()));
    if (StringUtils.isEmpty(environment.getDisplayName())) {
        environment.setDisplayName(environment.getName());
    }
    environment.setServerURL(APIUtil.replaceSystemProperty(environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_SERVER_URL)).getText()));
    environment.setUserName(APIUtil.replaceSystemProperty(environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_USERNAME)).getText()));
    OMElement passwordElement = environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_PASSWORD));
    String resolvedPassword = MiscellaneousUtil.resolve(passwordElement, secretResolver);
    environment.setPassword(APIUtil.replaceSystemProperty(resolvedPassword));
    String provider = environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_PROVIDER)).getText();
    if (StringUtils.isNotEmpty(provider)) {
        environment.setProvider(APIUtil.replaceSystemProperty(provider));
    } else {
        environment.setProvider(APIUtil.replaceSystemProperty(DEFAULT_PROVIDER));
    }
    environment.setApiGatewayEndpoint(APIUtil.replaceSystemProperty(environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_ENDPOINT)).getText()));
    OMElement websocketGatewayEndpoint = environmentElem.getFirstChildWithName(new QName(APIConstants.API_WEBSOCKET_GATEWAY_ENDPOINT));
    if (websocketGatewayEndpoint != null) {
        environment.setWebsocketGatewayEndpoint(APIUtil.replaceSystemProperty(websocketGatewayEndpoint.getText()));
    } else {
        environment.setWebsocketGatewayEndpoint(WEBSOCKET_DEFAULT_GATEWAY_URL);
    }
    OMElement webSubGatewayEndpoint = environmentElem.getFirstChildWithName(new QName(APIConstants.API_WEBSUB_GATEWAY_ENDPOINT));
    if (webSubGatewayEndpoint != null) {
        environment.setWebSubGatewayEndpoint(APIUtil.replaceSystemProperty(webSubGatewayEndpoint.getText()));
    } else {
        environment.setWebSubGatewayEndpoint(WEBSUB_DEFAULT_GATEWAY_URL);
    }
    OMElement description = environmentElem.getFirstChildWithName(new QName("Description"));
    if (description != null) {
        environment.setDescription(description.getText());
    } else {
        environment.setDescription("");
    }
    environment.setReadOnly(true);
    List<VHost> vhosts = new LinkedList<>();
    environment.setVhosts(vhosts);
    environment.setEndpointsAsVhost();
    Iterator vhostIterator = environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOSTS)).getChildrenWithLocalName(APIConstants.API_GATEWAY_VIRTUAL_HOST);
    while (vhostIterator.hasNext()) {
        OMElement vhostElem = (OMElement) vhostIterator.next();
        String httpEp = APIUtil.replaceSystemProperty(vhostElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOST_HTTP_ENDPOINT)).getText());
        String httpsEp = APIUtil.replaceSystemProperty(vhostElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOST_HTTPS_ENDPOINT)).getText());
        String wsEp = APIUtil.replaceSystemProperty(vhostElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOST_WS_ENDPOINT)).getText());
        String wssEp = APIUtil.replaceSystemProperty(vhostElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOST_WSS_ENDPOINT)).getText());
        String webSubHttpEp = APIUtil.replaceSystemProperty(vhostElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOST_WEBSUB_HTTP_ENDPOINT)).getText());
        String webSubHttpsEp = APIUtil.replaceSystemProperty(vhostElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOST_WEBSUB_HTTPS_ENDPOINT)).getText());
        // Prefix websub endpoints with 'websub_' so that the endpoint URL
        // would begin with: 'websub_http://', since API type is identified by the URL protocol below.
        webSubHttpEp = "websub_" + webSubHttpEp;
        webSubHttpsEp = "websub_" + webSubHttpsEp;
        VHost vhost = VHost.fromEndpointUrls(new String[] { httpEp, httpsEp, wsEp, wssEp, webSubHttpEp, webSubHttpsEp });
        vhosts.add(vhost);
    }
    OMElement properties = environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_ADDITIONAL_PROPERTIES));
    Map<String, String> additionalProperties = new HashMap<>();
    if (properties != null) {
        Iterator gatewayAdditionalProperties = properties.getChildrenWithLocalName(APIConstants.API_GATEWAY_ADDITIONAL_PROPERTY);
        while (gatewayAdditionalProperties.hasNext()) {
            OMElement propertyElem = (OMElement) gatewayAdditionalProperties.next();
            String propName = propertyElem.getAttributeValue(new QName("name"));
            String resolvedValue = MiscellaneousUtil.resolve(propertyElem, secretResolver);
            additionalProperties.put(propName, resolvedValue);
        }
    }
    environment.setAdditionalProperties(additionalProperties);
    if (!apiGatewayEnvironments.containsKey(environment.getName())) {
        apiGatewayEnvironments.put(environment.getName(), environment);
    } else {
        // This will happen only on server startup therefore we log and continue the startup
        log.error("Duplicate environment name found in api-manager.xml " + environment.getName());
    }
}
Also used : VHost(org.wso2.carbon.apimgt.api.model.VHost) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) QName(javax.xml.namespace.QName) Iterator(java.util.Iterator) Environment(org.wso2.carbon.apimgt.api.model.Environment) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment) OMElement(org.apache.axiom.om.OMElement) LinkedList(java.util.LinkedList)

Example 65 with Property

use of org.wso2.carbon.identity.application.common.model.Property in project carbon-apimgt by wso2.

the class RegistryPersistenceUtil method getAPI.

/**
 * This Method is different from getAPI method, as this one returns
 * URLTemplates without aggregating duplicates. This is to be used for building synapse config.
 *
 * @param artifact
 * @param registry
 * @return API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException
 */
public static API getAPI(GovernanceArtifact artifact, Registry registry) throws APIManagementException {
    API api;
    try {
        String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion, artifact.getId());
        api = new API(apiIdentifier);
        // set uuid
        api.setUuid(artifact.getId());
        // set rating
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        // String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR
        // + RegistryPersistenceUtil.replaceEmailDomain(api.getId().getProviderName())
        // + RegistryConstants.PATH_SEPARATOR + api.getId().getName() + RegistryConstants.PATH_SEPARATOR
        // + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.API_KEY;
        Resource apiResource = registry.get(artifactPath);
        api = setResourceProperties(api, apiResource, artifactPath);
        // set description
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        // set url
        api.setStatus(getLcStateFromArtifact(artifact));
        api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
        api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL));
        api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL));
        api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
        api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
        api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
        api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
        api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
        api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
        api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
        api.setEndpointSecured(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED)));
        api.setEndpointAuthDigest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST)));
        api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME));
        if (!((APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD).equals(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)))) {
            api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD));
        } else {
            // If APIEndpointPasswordRegistryHandler is enabled take password from the registry hidden property
            api.setEndpointUTPassword(apiResource.getProperty(APIConstants.REGISTRY_HIDDEN_ENDPOINT_PROPERTY));
        }
        api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
        api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
        api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
        api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
        api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        api.setProductionMaxTps(artifact.getAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS));
        api.setSandboxMaxTps(artifact.getAttribute(APIConstants.API_SANDBOX_THROTTLE_MAXTPS));
        api.setGatewayVendor(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR));
        api.setAsyncTransportProtocols(artifact.getAttribute(APIConstants.ASYNC_API_TRANSPORT_PROTOCOLS));
        int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
        try {
            String strCacheTimeout = artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT);
            if (strCacheTimeout != null && !strCacheTimeout.isEmpty()) {
                cacheTimeout = Integer.parseInt(strCacheTimeout);
            }
        } catch (NumberFormatException e) {
            if (log.isWarnEnabled()) {
                log.warn("Error while retrieving cache timeout from the registry for " + apiIdentifier);
            }
        // ignore the exception and use default cache timeout value
        }
        api.setCacheTimeout(cacheTimeout);
        api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
        api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
        api.setApiExternalProductionEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_PRODUCTION_ENDPOINT));
        api.setApiExternalSandboxEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_SANDBOX_ENDPOINT));
        api.setAdvertiseOnlyAPIVendor(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY_API_VENDOR));
        api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
        api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
        String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
        Set<Tier> availableTiers = new HashSet<Tier>();
        if (tiers != null) {
            String[] tiersArray = tiers.split("\\|\\|");
            for (String tierName : tiersArray) {
                availableTiers.add(new Tier(tierName));
            }
        }
        api.setAvailableTiers(availableTiers);
        // This contains the resolved context
        api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        // We set the context template here
        api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
        api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST)));
        api.setEnableSchemaValidation(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA)));
        api.setEnableStore(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE)));
        api.setTestKey(artifact.getAttribute(APIConstants.API_OVERVIEW_TESTKEY));
        Set<String> tags = new HashSet<String>();
        Tag[] tag = registry.getTags(artifactPath);
        for (Tag tag1 : tag) {
            tags.add(tag1.getTagName());
        }
        api.setTags(tags);
        api.setLastUpdated(apiResource.getLastModified());
        api.setCreatedTime(String.valueOf(apiResource.getCreatedTime().getTime()));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setEnvironments(getEnvironments(artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS)));
        api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
        api.setWebsubSubscriptionConfiguration(getWebsubSubscriptionConfigurationFromArtifact(artifact));
        api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
        api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
        // set data and status related to monetization
        api.setMonetizationEnabled(Boolean.parseBoolean(artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS)));
        String monetizationInfo = artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES);
        api.setWsUriMapping(getWsUriMappingFromArtifact(artifact));
        api.setAudience(artifact.getAttribute(APIConstants.API_OVERVIEW_AUDIENCE));
        api.setVersionTimestamp(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP));
        // set selected clusters which API needs to be deployed
        String deployments = artifact.getAttribute(APIConstants.API_OVERVIEW_DEPLOYMENTS);
        if (StringUtils.isNotBlank(monetizationInfo)) {
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(monetizationInfo);
            api.setMonetizationProperties(jsonObj);
        }
        api.setApiCategories(getAPICategoriesFromAPIGovernanceArtifact(artifact, tenantId));
        // get endpoint config string from artifact, parse it as a json and set the environment list configured with
        // non empty URLs to API object
        String keyManagers = artifact.getAttribute(APIConstants.API_OVERVIEW_KEY_MANAGERS);
        if (StringUtils.isNotEmpty(keyManagers)) {
            api.setKeyManagers(new Gson().fromJson(keyManagers, List.class));
        } else {
            api.setKeyManagers(Arrays.asList(APIConstants.API_LEVEL_ALL_KEY_MANAGERS));
        }
        try {
            api.setEnvironmentList(extractEnvironmentListForAPI(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)));
        } catch (ParseException e) {
            String msg = "Failed to parse endpoint config JSON of API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        } catch (ClassCastException e) {
            String msg = "Invalid endpoint config JSON found in API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        }
    } catch (GovernanceException e) {
        String msg = "Failed to get API for artifact ";
        throw new APIManagementException(msg, e);
    } catch (RegistryException e) {
        String msg = "Failed to get LastAccess time or Rating";
        throw new APIManagementException(msg, e);
    } catch (UserStoreException e) {
        String msg = "Failed to get User Realm of API Provider";
        throw new APIManagementException(msg, e);
    } catch (ParseException e) {
        String msg = "Failed to get parse monetization information.";
        throw new APIManagementException(msg, e);
    }
    return api;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) Resource(org.wso2.carbon.registry.core.Resource) Gson(com.google.gson.Gson) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) List(java.util.List) ArrayList(java.util.ArrayList) Tag(org.wso2.carbon.registry.core.Tag) ParseException(org.json.simple.parser.ParseException) HashSet(java.util.HashSet)

Aggregations

HashMap (java.util.HashMap)42 ArrayList (java.util.ArrayList)32 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)32 Resource (org.wso2.carbon.registry.core.Resource)23 Map (java.util.Map)21 Test (org.junit.Test)21 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)21 DataResponse (org.wso2.carbon.bpmn.rest.model.common.DataResponse)17 API (org.wso2.carbon.apimgt.api.model.API)16 UserStoreException (org.wso2.carbon.user.api.UserStoreException)16 Path (javax.ws.rs.Path)14 Produces (javax.ws.rs.Produces)14 JSONObject (org.json.simple.JSONObject)14 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)14 List (java.util.List)13 IOException (java.io.IOException)11 QName (javax.xml.namespace.QName)11 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)11 Properties (java.util.Properties)10 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)10