Search in sources :

Example 21 with Attributes

use of org.wso2.balana.xacml3.Attributes in project carbon-apimgt by wso2.

the class AbstractAPIManager method populateDevPortalAPIInformation.

protected void populateDevPortalAPIInformation(String uuid, String organization, API api) throws APIManagementException, OASPersistenceException, ParseException {
    Organization org = new Organization(organization);
    // UUID
    if (api.getUuid() == null) {
        api.setUuid(uuid);
    }
    api.setOrganization(organization);
    // environment
    String environmentString = null;
    if (api.getEnvironments() != null) {
        environmentString = String.join(",", api.getEnvironments());
    }
    api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIIdentifier apiId = api.getId();
    String currentApiUuid = uuid;
    if (api.isRevision() && api.getRevisionedApiId() != null) {
        currentApiUuid = api.getRevisionedApiId();
    }
    // TODO try to use a single query to get info from db
    // Ratings
    int internalId = apiMgtDAO.getAPIID(currentApiUuid);
    api.setRating(APIUtil.getAverageRating(internalId));
    apiId.setId(internalId);
    // api level tier
    String apiLevelTier = apiMgtDAO.getAPILevelTier(internalId);
    api.setApiLevelPolicy(apiLevelTier);
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = api.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (api.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(APIUtil.getInternalOrganizationId(organization));
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, api.getId().getApiName());
    api.setAvailableTiers(availableTier);
    // Scopes
    Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(currentApiUuid, organization);
    api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
    // templates
    String resourceConfigsString = null;
    if (api.getSwaggerDefinition() != null) {
        resourceConfigsString = api.getSwaggerDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
    }
    api.setSwaggerDefinition(resourceConfigsString);
    if (api.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
        api.setGraphQLSchema(getGraphqlSchemaDefinition(uuid, organization));
    }
    JSONParser jsonParser = new JSONParser();
    JSONObject paths = null;
    if (resourceConfigsString != null) {
        JSONObject resourceConfigsJSON = (JSONObject) jsonParser.parse(resourceConfigsString);
        paths = (JSONObject) resourceConfigsJSON.get(APIConstants.SWAGGER_PATHS);
    }
    Set<URITemplate> uriTemplates = apiMgtDAO.getURITemplatesOfAPI(api.getUuid());
    for (URITemplate uriTemplate : uriTemplates) {
        String uTemplate = uriTemplate.getUriTemplate();
        String method = uriTemplate.getHTTPVerb();
        List<Scope> oldTemplateScopes = uriTemplate.retrieveAllScopes();
        List<Scope> newTemplateScopes = new ArrayList<>();
        if (!oldTemplateScopes.isEmpty()) {
            for (Scope templateScope : oldTemplateScopes) {
                Scope scope = scopeToKeyMapping.get(templateScope.getKey());
                newTemplateScopes.add(scope);
            }
        }
        uriTemplate.addAllScopes(newTemplateScopes);
        uriTemplate.setResourceURI(api.getUrl());
        uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
        // AWS Lambda: set arn & timeout to URI template
        if (paths != null) {
            JSONObject path = (JSONObject) paths.get(uTemplate);
            if (path != null) {
                JSONObject operation = (JSONObject) path.get(method.toLowerCase());
                if (operation != null) {
                    if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME)) {
                        uriTemplate.setAmznResourceName((String) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME));
                    }
                    if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)) {
                        uriTemplate.setAmznResourceTimeout(((Long) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)).intValue());
                    }
                }
            }
        }
    }
    if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equalsIgnoreCase(api.getImplementation())) {
        for (URITemplate template : uriTemplates) {
            template.setMediationScript(template.getAggregatedMediationScript());
        }
    }
    api.setUriTemplates(uriTemplates);
    // CORS . if null is returned, set default config from the configuration
    if (api.getCorsConfiguration() == null) {
        api.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = api.getApiCategories();
    if (categories != null) {
        List<String> categoriesOfAPI = new ArrayList<String>();
        for (APICategory apiCategory : categories) {
            categoriesOfAPI.add(apiCategory.getName());
        }
        List<APICategory> categoryList = new ArrayList<>();
        if (!categoriesOfAPI.isEmpty()) {
            // category array retrieved from artifact has only the category name, therefore we need to fetch
            // categories
            // and fill out missing attributes before attaching the list to the api
            List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
            for (String categoryName : categoriesOfAPI) {
                for (APICategory category : allCategories) {
                    if (categoryName.equals(category.getName())) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        api.setApiCategories(categoryList);
    }
}
Also used : Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) APICategory(org.wso2.carbon.apimgt.api.model.APICategory) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 22 with Attributes

use of org.wso2.balana.xacml3.Attributes in project carbon-apimgt by wso2.

the class AbstractAPIManager method populateAPIProductInformation.

protected void populateAPIProductInformation(String uuid, String organization, APIProduct apiProduct) throws APIManagementException, OASPersistenceException, ParseException {
    Organization org = new Organization(organization);
    apiProduct.setOrganization(organization);
    ApiMgtDAO.getInstance().setAPIProductFromDB(apiProduct);
    apiProduct.setRating(Float.toString(APIUtil.getAverageRating(apiProduct.getProductId())));
    List<APIProductResource> resources = ApiMgtDAO.getInstance().getAPIProductResourceMappings(apiProduct.getId());
    Map<String, Scope> uniqueAPIProductScopeKeyMappings = new LinkedHashMap<>();
    for (APIProductResource resource : resources) {
        List<Scope> resourceScopes = resource.getUriTemplate().retrieveAllScopes();
        ListIterator it = resourceScopes.listIterator();
        while (it.hasNext()) {
            Scope resourceScope = (Scope) it.next();
            String scopeKey = resourceScope.getKey();
            if (!uniqueAPIProductScopeKeyMappings.containsKey(scopeKey)) {
                resourceScope = APIUtil.getScopeByName(scopeKey, organization);
                uniqueAPIProductScopeKeyMappings.put(scopeKey, resourceScope);
            } else {
                resourceScope = uniqueAPIProductScopeKeyMappings.get(scopeKey);
            }
            it.set(resourceScope);
        }
    }
    for (APIProductResource resource : resources) {
        String resourceAPIUUID = resource.getApiIdentifier().getUUID();
        resource.setApiId(resourceAPIUUID);
        try {
            PublisherAPI publisherAPI = apiPersistenceInstance.getPublisherAPI(org, resourceAPIUUID);
            API api = APIMapper.INSTANCE.toApi(publisherAPI);
            if (api.isAdvertiseOnly()) {
                resource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
            } else {
                resource.setEndpointConfig(api.getEndpointConfig());
            }
            resource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
        } catch (APIPersistenceException e) {
            throw new APIManagementException("Error while retrieving the api for api product " + e);
        }
    }
    apiProduct.setProductResources(resources);
    // UUID
    if (apiProduct.getUuid() == null) {
        apiProduct.setUuid(uuid);
    }
    // environment
    String environmentString = null;
    if (apiProduct.getEnvironments() != null) {
        environmentString = String.join(",", apiProduct.getEnvironments());
    }
    apiProduct.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIProductIdentifier productIdentifier = apiProduct.getId();
    WorkflowDTO workflow;
    String currentApiProductUuid = uuid;
    if (apiProduct.isRevision() && apiProduct.getRevisionedApiProductId() != null) {
        currentApiProductUuid = apiProduct.getRevisionedApiProductId();
    }
    workflow = APIUtil.getAPIWorkflowStatus(currentApiProductUuid, WF_TYPE_AM_API_PRODUCT_STATE);
    if (workflow != null) {
        WorkflowStatus status = workflow.getStatus();
        apiProduct.setWorkflowStatus(status.toString());
    }
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = apiProduct.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (apiProduct.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(tenantId);
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, apiProduct.getId().getName());
    apiProduct.setAvailableTiers(availableTier);
    // Scopes
    /*
        Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(api.getId(), requestedTenantDomain);
        apiProduct.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
        */
    // templates
    String resourceConfigsString = null;
    if (apiProduct.getDefinition() != null) {
        resourceConfigsString = apiProduct.getDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
        apiProduct.setDefinition(resourceConfigsString);
    }
    // CORS . if null is returned, set default config from the configuration
    if (apiProduct.getCorsConfiguration() == null) {
        apiProduct.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = apiProduct.getApiCategories();
    if (categories != null) {
        List<String> categoriesOfAPI = new ArrayList<String>();
        for (APICategory apiCategory : categories) {
            categoriesOfAPI.add(apiCategory.getName());
        }
        List<APICategory> categoryList = new ArrayList<>();
        if (!categoriesOfAPI.isEmpty()) {
            // category array retrieved from artifact has only the category name, therefore we need to fetch
            // categories
            // and fill out missing attributes before attaching the list to the api
            List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
            // todo-category: optimize this loop with breaks
            for (String categoryName : categoriesOfAPI) {
                for (APICategory category : allCategories) {
                    if (categoryName.equals(category.getName())) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        apiProduct.setApiCategories(categoryList);
    }
}
Also used : WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Tier(org.wso2.carbon.apimgt.api.model.Tier) ListIterator(java.util.ListIterator) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 23 with Attributes

use of org.wso2.balana.xacml3.Attributes in project carbon-apimgt by wso2.

the class APIUtil method getMediationPolicyAttributes.

/**
 * Returns attributes correspond to the given mediation policy name and direction
 *
 * @param policyName name of the  sequence
 * @param tenantId   logged in user's tenantId
 * @param direction  in/out/fault
 * @param identifier API identifier
 * @return attributes(path, uuid) of the given mediation sequence or null
 * @throws APIManagementException If failed to get the uuid of the mediation sequence
 */
public static Map<String, String> getMediationPolicyAttributes(String policyName, int tenantId, String direction, APIIdentifier identifier) throws APIManagementException {
    org.wso2.carbon.registry.api.Collection seqCollection = null;
    String seqCollectionPath = "";
    Map<String, String> mediationPolicyAttributes = new HashMap<>(3);
    try {
        UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);
        if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN.equals(direction)) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + "/" + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN);
        } else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT.equals(direction)) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + "/" + APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT);
        } else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT.equals(direction)) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + "/" + APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT);
        }
        if (seqCollection == null) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier, direction));
        }
        if (seqCollection != null) {
            String[] childPaths = seqCollection.getChildren();
            for (String childPath : childPaths) {
                Resource mediationPolicy = registry.get(childPath);
                OMElement seqElment = APIUtil.buildOMElement(mediationPolicy.getContentStream());
                String seqElmentName = seqElment.getAttributeValue(new QName("name"));
                if (policyName.equals(seqElmentName)) {
                    mediationPolicyAttributes.put("path", childPath);
                    mediationPolicyAttributes.put("uuid", mediationPolicy.getUUID());
                    mediationPolicyAttributes.put("name", policyName);
                    return mediationPolicyAttributes;
                }
            }
        }
        // If the sequence not found the default sequences, check in custom sequences
        seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier, direction));
        if (seqCollection != null) {
            String[] childPaths = seqCollection.getChildren();
            for (String childPath : childPaths) {
                Resource mediationPolicy = registry.get(childPath);
                OMElement seqElment = APIUtil.buildOMElement(mediationPolicy.getContentStream());
                if (policyName.equals(seqElment.getAttributeValue(new QName("name")))) {
                    mediationPolicyAttributes.put("path", childPath);
                    mediationPolicyAttributes.put("uuid", mediationPolicy.getUUID());
                    mediationPolicyAttributes.put("name", policyName);
                    return mediationPolicyAttributes;
                }
            }
        }
    } catch (Exception e) {
        String msg = "Issue is in accessing the Registry";
        log.error(msg);
        throw new APIManagementException(msg, e);
    }
    return mediationPolicyAttributes;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) OMElement(org.apache.axiom.om.OMElement) KeyStoreException(java.security.KeyStoreException) JSONException(org.json.JSONException) XMLStreamException(javax.xml.stream.XMLStreamException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ExceptionException(org.wso2.carbon.core.commons.stub.loggeduserinfo.ExceptionException) APIMgtInternalException(org.wso2.carbon.apimgt.api.APIMgtInternalException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URISyntaxException(java.net.URISyntaxException) SignatureException(java.security.SignatureException) RemoteException(java.rmi.RemoteException) CertificateEncodingException(javax.security.cert.CertificateEncodingException) AuthorizationFailedException(org.wso2.carbon.registry.core.secure.AuthorizationFailedException) EventPublisherException(org.wso2.carbon.apimgt.eventing.EventPublisherException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) ValidationException(org.everit.json.schema.ValidationException) CryptoException(org.wso2.carbon.core.util.CryptoException) NotifierException(org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SocketException(java.net.SocketException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) CertificateException(java.security.cert.CertificateException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Collection(java.util.Collection)

Example 24 with Attributes

use of org.wso2.balana.xacml3.Attributes in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method searchContentForDevPortal.

@Override
public DevPortalContentSearchResult searchContentForDevPortal(Organization org, String searchQuery, int start, int offset, UserContext ctx) throws APIPersistenceException {
    log.debug("Requested query for devportal content search: " + searchQuery);
    Map<String, String> attributes = RegistrySearchUtil.getDevPortalSearchAttributes(searchQuery, ctx, isAllowDisplayAPIsWithMultipleStatus());
    if (log.isDebugEnabled()) {
        log.debug("Search attributes : " + attributes);
    }
    DevPortalContentSearchResult result = null;
    boolean isTenantFlowStarted = false;
    try {
        RegistryHolder holder = getRegistry(ctx.getUserame(), org.getName());
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        String tenantAwareUsername = getTenantAwareUsername(ctx.getUserame());
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(tenantAwareUsername);
        GenericArtifactManager apiArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifactManager docArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
        int maxPaginationLimit = getMaxPaginationLimit();
        PaginationContext.init(start, offset, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        int tenantId = holder.getTenantId();
        if (tenantId == -1) {
            tenantId = MultitenantConstants.SUPER_TENANT_ID;
        }
        UserRegistry systemUserRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getRegistry(CarbonConstants.REGISTRY_SYSTEM_USERNAME, tenantId);
        ContentBasedSearchService contentBasedSearchService = new ContentBasedSearchService();
        SearchResultsBean resultsBean = contentBasedSearchService.searchByAttribute(attributes, systemUserRegistry);
        String errorMsg = resultsBean.getErrorMessage();
        if (errorMsg != null) {
            throw new APIPersistenceException("Error while searching " + errorMsg);
        }
        ResourceData[] resourceData = resultsBean.getResourceDataList();
        int totalLength = PaginationContext.getInstance().getLength();
        if (resourceData != null) {
            result = new DevPortalContentSearchResult();
            List<SearchContent> contentData = new ArrayList<SearchContent>();
            if (log.isDebugEnabled()) {
                log.debug("Number of records Found: " + resourceData.length);
            }
            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();
                        }
                        DocumentSearchContent docSearch = new DocumentSearchContent();
                        Resource docResource = registry.get(resourcePath);
                        String docArtifactId = docResource.getUUID();
                        GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docArtifactId);
                        Documentation doc = RegistryPersistenceDocUtil.getDocumentation(docArtifact);
                        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();
                        DevPortalAPI devAPI;
                        if (apiArtifactId != null) {
                            GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
                            devAPI = RegistryPersistenceUtil.getDevPortalAPIForSearch(apiArtifact);
                            docSearch.setApiName(devAPI.getApiName());
                            docSearch.setApiProvider(devAPI.getProviderName());
                            docSearch.setApiVersion(devAPI.getVersion());
                            docSearch.setApiUUID(devAPI.getId());
                            docSearch.setDocType(doc.getType());
                            docSearch.setId(doc.getId());
                            docSearch.setSourceType(doc.getSourceType());
                            docSearch.setVisibility(doc.getVisibility());
                            docSearch.setName(doc.getName());
                            contentData.add(docSearch);
                        } else {
                            throw new GovernanceException("artifact id is null of " + apiPath);
                        }
                    } else {
                        String apiArtifactId = resource.getUUID();
                        if (apiArtifactId != null) {
                            GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
                            DevPortalAPI devAPI = RegistryPersistenceUtil.getDevPortalAPIForSearch(apiArtifact);
                            DevPortalSearchContent content = new DevPortalSearchContent();
                            content.setContext(devAPI.getContext());
                            content.setDescription(devAPI.getDescription());
                            content.setId(devAPI.getId());
                            content.setName(devAPI.getApiName());
                            content.setProvider(RegistryPersistenceUtil.replaceEmailDomainBack(devAPI.getProviderName()));
                            content.setVersion(devAPI.getVersion());
                            content.setStatus(devAPI.getStatus());
                            content.setBusinessOwner(devAPI.getBusinessOwner());
                            content.setBusinessOwnerEmail(devAPI.getBusinessOwnerEmail());
                            contentData.add(content);
                        } else {
                            throw new GovernanceException("artifact id is null for " + resourcePath);
                        }
                    }
                }
            }
            result.setTotalCount(totalLength);
            result.setReturnedCount(contentData.size());
            result.setResults(contentData);
        }
    } catch (RegistryException | IndexerException | DocumentationPersistenceException e) {
        throw new APIPersistenceException("Error while searching for content ", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return result;
}
Also used : DevPortalSearchContent(org.wso2.carbon.apimgt.persistence.dto.DevPortalSearchContent) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) ArrayList(java.util.ArrayList) DevPortalContentSearchResult(org.wso2.carbon.apimgt.persistence.dto.DevPortalContentSearchResult) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) SearchResultsBean(org.wso2.carbon.registry.indexing.service.SearchResultsBean) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) DevPortalSearchContent(org.wso2.carbon.apimgt.persistence.dto.DevPortalSearchContent) DocumentSearchContent(org.wso2.carbon.apimgt.persistence.dto.DocumentSearchContent) PublisherSearchContent(org.wso2.carbon.apimgt.persistence.dto.PublisherSearchContent) SearchContent(org.wso2.carbon.apimgt.persistence.dto.SearchContent) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) ResourceData(org.wso2.carbon.registry.common.ResourceData) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) DocumentSearchContent(org.wso2.carbon.apimgt.persistence.dto.DocumentSearchContent) Documentation(org.wso2.carbon.apimgt.persistence.dto.Documentation) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) ContentBasedSearchService(org.wso2.carbon.registry.indexing.service.ContentBasedSearchService) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 25 with Attributes

use of org.wso2.balana.xacml3.Attributes in project carbon-apimgt by wso2.

the class RegistryPersistenceUtil method getAPIForSearch.

public static PublisherAPI getAPIForSearch(GenericArtifact apiArtifact) throws APIPersistenceException {
    PublisherAPI api = new PublisherAPI();
    try {
        api.setContext(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
        api.setDescription(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        api.setId(apiArtifact.getId());
        api.setStatus(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS));
        api.setApiName(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
        api.setProviderName(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
        ;
        api.setVersion(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
        api.setAdvertiseOnly(Boolean.parseBoolean(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
    } catch (GovernanceException e) {
        throw new APIPersistenceException("Error while extracting api attributes ", e);
    }
    return api;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException)

Aggregations

HashMap (java.util.HashMap)111 ArrayList (java.util.ArrayList)110 Test (org.testng.annotations.Test)106 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)83 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)76 SCIMResourceTypeSchema (org.wso2.charon3.core.schema.SCIMResourceTypeSchema)64 Map (java.util.Map)55 CharonException (org.wso2.charon3.core.exceptions.CharonException)54 User (org.wso2.charon3.core.objects.User)53 ComplexAttribute (org.wso2.charon3.core.attributes.ComplexAttribute)43 MultiValuedAttribute (org.wso2.charon3.core.attributes.MultiValuedAttribute)39 SimpleAttribute (org.wso2.charon3.core.attributes.SimpleAttribute)39 List (java.util.List)35 Group (org.wso2.charon3.core.objects.Group)33 JSONObject (org.json.JSONObject)32 Attribute (org.wso2.charon3.core.attributes.Attribute)32 InternalErrorException (org.wso2.charon3.core.exceptions.InternalErrorException)32 NotFoundException (org.wso2.charon3.core.exceptions.NotFoundException)30 UserStoreException (org.wso2.carbon.user.api.UserStoreException)26 NotImplementedException (org.wso2.charon3.core.exceptions.NotImplementedException)26