Search in sources :

Example 1 with ResourceData

use of org.wso2.carbon.registry.common.ResourceData 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 2 with ResourceData

use of org.wso2.carbon.registry.common.ResourceData 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 3 with ResourceData

use of org.wso2.carbon.registry.common.ResourceData in project jaggery by wso2.

the class RegistryHostObject method jsFunction_search.

public static Scriptable jsFunction_search(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException {
    String functionName = "search";
    int argsCount = args.length;
    if (argsCount != 1) {
        HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
    }
    if (!(args[0] instanceof NativeObject)) {
        HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "json", args[0], false);
    }
    NativeObject options = (NativeObject) args[0];
    CustomSearchParameterBean parameters = new CustomSearchParameterBean();
    String path = null;
    List<String[]> values = new ArrayList<String[]>();
    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    String val;
    for (Object idObj : options.getIds()) {
        String id = (String) idObj;
        Object value = options.get(id, options);
        if (value == null || value instanceof Undefined) {
            continue;
        }
        if ("path".equals(id)) {
            path = (String) value;
            continue;
        }
        if ("createdBefore".equals(id) || "createdAfter".equals(id) || "updatedBefore".equals(id) || "updatedAfter".equals(id)) {
            long t;
            if (value instanceof Number) {
                t = ((Number) value).longValue();
            } else {
                t = Long.parseLong(HostObjectUtil.serializeObject(value));
            }
            val = new String(dateFormat.format(new Date(t)).getBytes());
        } else {
            val = HostObjectUtil.serializeObject(value);
        }
        values.add(new String[] { id, val });
    }
    parameters.setParameterValues(values.toArray(new String[0][0]));
    RegistryHostObject registryHostObject = (RegistryHostObject) thisObj;
    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        UserRegistry userRegistry = RegistryHostObjectContext.getRegistryService().getRegistry(registryHostObject.registry.getUserName(), tenantId);
        Registry configRegistry = RegistryHostObjectContext.getRegistryService().getConfigSystemRegistry(tenantId);
        AdvancedSearchResultsBean resultsBean = registryHostObject.search(configRegistry, userRegistry, parameters);
        if (resultsBean.getResourceDataList() == null) {
            ScriptableObject error = (ScriptableObject) cx.newObject(thisObj);
            error.put("error", error, true);
            error.put("description", error, resultsBean.getErrorMessage());
            return error;
        }
        List<ScriptableObject> results = new ArrayList<ScriptableObject>();
        for (ResourceData resourceData : resultsBean.getResourceDataList()) {
            String resourcePath = resourceData.getResourcePath();
            if (path != null && !resourcePath.startsWith(path)) {
                continue;
            }
            ScriptableObject result = (ScriptableObject) cx.newObject(thisObj);
            result.put("author", result, resourceData.getAuthorUserName());
            result.put("rating", result, resourceData.getAverageRating());
            result.put("created", result, resourceData.getCreatedOn().getTime().getTime());
            result.put("description", result, resourceData.getDescription());
            result.put("name", result, resourceData.getName());
            result.put("path", result, resourceData.getResourcePath());
            List<ScriptableObject> tags = new ArrayList<ScriptableObject>();
            if (resourceData.getTagCounts() != null) {
                for (TagCount tagCount : resourceData.getTagCounts()) {
                    ScriptableObject tag = (ScriptableObject) cx.newObject(thisObj);
                    tag.put("name", tag, tagCount.getKey());
                    tag.put("count", tag, tagCount.getValue());
                    tags.add(tag);
                }
            }
            result.put("tags", result, cx.newArray(thisObj, tags.toArray()));
            results.add(result);
        }
        return cx.newArray(thisObj, results.toArray());
    } catch (RegistryException e) {
        throw new ScriptException(e);
    } catch (CarbonException e) {
        throw new ScriptException(e);
    }
}
Also used : CustomSearchParameterBean(org.wso2.carbon.registry.search.beans.CustomSearchParameterBean) ResourceData(org.wso2.carbon.registry.common.ResourceData) CarbonException(org.wso2.carbon.CarbonException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) RegistryException(org.wso2.carbon.registry.api.RegistryException) AdvancedSearchResultsBean(org.wso2.carbon.registry.search.beans.AdvancedSearchResultsBean) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) TagCount(org.wso2.carbon.registry.common.TagCount) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat)

Example 4 with ResourceData

use of org.wso2.carbon.registry.common.ResourceData in project jaggery by wso2.

the class RegistryHostObject method search.

private ResourceData[] search(UserRegistry registry, String searchQuery) throws IndexerException, RegistryException {
    SolrClient client = SolrClient.getInstance();
    SolrDocumentList results = client.query(searchQuery, registry.getTenantId());
    if (log.isDebugEnabled())
        log.debug("result received " + results);
    List<ResourceData> filteredResults = new ArrayList<ResourceData>();
    for (int i = 0; i < results.getNumFound(); i++) {
        SolrDocument solrDocument = results.get(i);
        String path = getPathFromId((String) solrDocument.getFirstValue("id"));
        // if (AuthorizationUtils.authorize(path, ActionConstants.GET)){
        if ((registry.resourceExists(path)) && (isAuthorized(registry, path, ActionConstants.GET))) {
            filteredResults.add(loadResourceByPath(registry, path));
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("filtered results " + filteredResults + " for user " + registry.getUserName());
    }
    return filteredResults.toArray(new ResourceData[0]);
}
Also used : ResourceData(org.wso2.carbon.registry.common.ResourceData) SolrDocument(org.apache.solr.common.SolrDocument) SolrClient(org.wso2.carbon.registry.indexing.solr.SolrClient) SolrDocumentList(org.apache.solr.common.SolrDocumentList)

Example 5 with ResourceData

use of org.wso2.carbon.registry.common.ResourceData in project jaggery by wso2.

the class RegistryHostObject method loadResourceByPath.

private ResourceData loadResourceByPath(UserRegistry registry, String path) throws RegistryException {
    ResourceData resourceData = new ResourceData();
    resourceData.setResourcePath(path);
    if (path != null) {
        if (RegistryConstants.ROOT_PATH.equals(path)) {
            resourceData.setName("root");
        } else {
            String[] parts = path.split(RegistryConstants.PATH_SEPARATOR);
            resourceData.setName(parts[parts.length - 1]);
        }
    }
    Resource child = registry.get(path);
    resourceData.setResourceType(child instanceof Collection ? "collection" : "resource");
    resourceData.setAuthorUserName(child.getAuthorUserName());
    resourceData.setDescription(child.getDescription());
    resourceData.setAverageRating(registry.getAverageRating(child.getPath()));
    Calendar createdDateTime = Calendar.getInstance();
    createdDateTime.setTime(child.getCreatedTime());
    resourceData.setCreatedOn(createdDateTime);
    CommonUtil.populateAverageStars(resourceData);
    child.discard();
    return resourceData;
}
Also used : ResourceData(org.wso2.carbon.registry.common.ResourceData) Collection(org.wso2.carbon.registry.core.Collection)

Aggregations

ResourceData (org.wso2.carbon.registry.common.ResourceData)7 ArrayList (java.util.ArrayList)4 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)4 IndexerException (org.wso2.carbon.registry.indexing.indexer.IndexerException)4 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)3 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)3 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)3 Resource (org.wso2.carbon.registry.core.Resource)3 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)3 ContentBasedSearchService (org.wso2.carbon.registry.indexing.service.ContentBasedSearchService)3 SearchResultsBean (org.wso2.carbon.registry.indexing.service.SearchResultsBean)3 ScriptException (org.jaggeryjs.scriptengine.exceptions.ScriptException)2 CarbonException (org.wso2.carbon.CarbonException)2 DevPortalSearchContent (org.wso2.carbon.apimgt.persistence.dto.DevPortalSearchContent)2 DocumentSearchContent (org.wso2.carbon.apimgt.persistence.dto.DocumentSearchContent)2 Documentation (org.wso2.carbon.apimgt.persistence.dto.Documentation)2 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)2 PublisherSearchContent (org.wso2.carbon.apimgt.persistence.dto.PublisherSearchContent)2 SearchContent (org.wso2.carbon.apimgt.persistence.dto.SearchContent)2 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)2