Search in sources :

Example 1 with Indexer

use of org.wso2.carbon.registry.indexing.indexer.Indexer in project carbon-apimgt by wso2.

the class CustomAPIIndexerTest method init.

@Before
public void init() throws RegistryException {
    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.mockStatic(IndexingManager.class);
    IndexingManager indexingManager = Mockito.mock(IndexingManager.class);
    PowerMockito.when(IndexingManager.getInstance()).thenReturn(indexingManager);
    userRegistry = Mockito.mock(UserRegistry.class);
    Mockito.doReturn(userRegistry).when(indexingManager).getRegistry(Mockito.anyInt());
    Mockito.doReturn(true).when(userRegistry).resourceExists(Mockito.anyString());
    PowerMockito.when(GovernanceUtils.getGovernanceSystemRegistry(userRegistry)).thenReturn(userRegistry);
    String path = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + "/api";
    file2Index = new AsyncIndexer.File2Index("".getBytes(), null, path, -1234, "");
    indexer = new CustomAPIIndexer();
}
Also used : IndexingManager(org.wso2.carbon.registry.indexing.IndexingManager) AsyncIndexer(org.wso2.carbon.registry.indexing.AsyncIndexer) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Before(org.junit.Before)

Example 2 with Indexer

use of org.wso2.carbon.registry.indexing.indexer.Indexer in project carbon-apimgt by wso2.

the class MSWordIndexerTest method testShouldReturnIndexedDocumentWhenParameterCorrect.

@Test
public void testShouldReturnIndexedDocumentWhenParameterCorrect() throws Exception {
    POIFSFileSystem poiFS = Mockito.mock(POIFSFileSystem.class);
    WordExtractor wordExtractor = Mockito.mock(WordExtractor.class);
    XWPFWordExtractor xwpfExtractor = Mockito.mock(XWPFWordExtractor.class);
    XWPFDocument xwpfDocument = Mockito.mock(XWPFDocument.class);
    PowerMockito.whenNew(POIFSFileSystem.class).withParameterTypes(InputStream.class).withArguments(Mockito.any(InputStream.class)).thenThrow(OfficeXmlFileException.class).thenReturn(poiFS).thenThrow(APIManagementException.class);
    PowerMockito.whenNew(WordExtractor.class).withArguments(poiFS).thenReturn(wordExtractor);
    PowerMockito.whenNew(XWPFDocument.class).withParameterTypes(InputStream.class).withArguments(Mockito.any()).thenReturn(xwpfDocument);
    PowerMockito.whenNew(XWPFWordExtractor.class).withArguments(xwpfDocument).thenReturn(xwpfExtractor);
    Mockito.when(wordExtractor.getText()).thenReturn("");
    Mockito.when(xwpfExtractor.getText()).thenReturn("");
    MSWordIndexer indexer = new MSWordIndexer();
    IndexDocument wordDoc = indexer.getIndexedDocument(file2Index);
    // should return the default media type when media type is not defined in file2Index
    if (!"application/pdf".equals(wordDoc.getFields().get(IndexingConstants.FIELD_MEDIA_TYPE).get(0))) {
        Assert.fail();
    }
    // should return the media type we have set in the file2Index
    file2Index.mediaType = "text/html";
    wordDoc = indexer.getIndexedDocument(file2Index);
    if (!"text/html".equals(wordDoc.getFields().get(IndexingConstants.FIELD_MEDIA_TYPE).get(0))) {
        Assert.fail();
    }
    // should return the media type we have set in the file2Index even if exception occurred while reading the file
    file2Index.mediaType = "text/html";
    wordDoc = indexer.getIndexedDocument(file2Index);
    if (!"text/html".equals(wordDoc.getFields().get(IndexingConstants.FIELD_MEDIA_TYPE).get(0))) {
        Assert.fail();
    }
}
Also used : IndexDocument(org.wso2.carbon.registry.indexing.solr.IndexDocument) POIFSFileSystem(org.apache.poi.poifs.filesystem.POIFSFileSystem) XWPFWordExtractor(org.apache.poi.xwpf.extractor.XWPFWordExtractor) XWPFDocument(org.apache.poi.xwpf.usermodel.XWPFDocument) WordExtractor(org.apache.poi.hwpf.extractor.WordExtractor) XWPFWordExtractor(org.apache.poi.xwpf.extractor.XWPFWordExtractor) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 3 with Indexer

use of org.wso2.carbon.registry.indexing.indexer.Indexer in project carbon-apimgt by wso2.

the class XMLIndexerTest method testShouldReturnIndexedDocumentWhenParameterCorrect.

@Test
public void testShouldReturnIndexedDocumentWhenParameterCorrect() throws RegistryException {
    String mediaType = "text/xml";
    final String MEDIA_TYPE = "mediaType";
    AsyncIndexer.File2Index file2Index = new AsyncIndexer.File2Index("".getBytes(), null, "", -1234, "");
    XMLIndexer indexer = new XMLIndexer();
    // should return the the default media type when media type is not defined in file2Index
    IndexDocument xml = indexer.getIndexedDocument(file2Index);
    if (xml.getFields().get(MEDIA_TYPE) != null) {
        Assert.fail();
    }
    // should return the media type we have set in the file2Index
    file2Index.mediaType = mediaType;
    xml = indexer.getIndexedDocument(file2Index);
    if (!mediaType.equals(xml.getFields().get(MEDIA_TYPE).get(0))) {
        Assert.fail();
    }
}
Also used : IndexDocument(org.wso2.carbon.registry.indexing.solr.IndexDocument) AsyncIndexer(org.wso2.carbon.registry.indexing.AsyncIndexer) Test(org.junit.Test)

Example 4 with Indexer

use of org.wso2.carbon.registry.indexing.indexer.Indexer in project carbon-apimgt by wso2.

the class APIUtil method notifyAPIStateChangeToAssociatedDocuments.

/**
 * Notify document artifacts if an api state change occured. This change is required to re-trigger the document
 * indexer so that the documnet indexes will be updated with the new associated api status.
 *
 * @param apiArtifact
 * @param registry
 * @throws RegistryException
 * @throws APIManagementException
 */
public static void notifyAPIStateChangeToAssociatedDocuments(GenericArtifact apiArtifact, Registry registry) throws RegistryException, APIManagementException {
    Association[] docAssociations = registry.getAssociations(apiArtifact.getPath(), APIConstants.DOCUMENTATION_ASSOCIATION);
    for (Association association : docAssociations) {
        String documentResourcePath = association.getDestinationPath();
        Resource docResource = registry.get(documentResourcePath);
        String oldStateChangeIndicatorStatus = docResource.getProperty(APIConstants.API_STATE_CHANGE_INDICATOR);
        String newStateChangeIndicatorStatus = "false";
        if (oldStateChangeIndicatorStatus != null) {
            newStateChangeIndicatorStatus = String.valueOf(!Boolean.parseBoolean(oldStateChangeIndicatorStatus));
        }
        docResource.setProperty(APIConstants.API_STATE_CHANGE_INDICATOR, "false");
        registry.put(documentResourcePath, docResource);
    }
}
Also used : Association(org.wso2.carbon.registry.core.Association) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource)

Example 5 with Indexer

use of org.wso2.carbon.registry.indexing.indexer.Indexer 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)

Aggregations

IndexDocument (org.wso2.carbon.registry.indexing.solr.IndexDocument)7 Test (org.junit.Test)5 Resource (org.wso2.carbon.registry.core.Resource)4 AsyncIndexer (org.wso2.carbon.registry.indexing.AsyncIndexer)4 HashMap (java.util.HashMap)3 POIFSFileSystem (org.apache.poi.poifs.filesystem.POIFSFileSystem)3 IOException (java.io.IOException)2 List (java.util.List)2 WordExtractor (org.apache.poi.hwpf.extractor.WordExtractor)2 XWPFWordExtractor (org.apache.poi.xwpf.extractor.XWPFWordExtractor)2 XWPFDocument (org.apache.poi.xwpf.usermodel.XWPFDocument)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)2 Association (org.wso2.carbon.registry.core.Association)2 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)2 RegistryConfigLoader (org.wso2.carbon.registry.indexing.RegistryConfigLoader)2 Indexer (org.wso2.carbon.registry.indexing.indexer.Indexer)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ArrayList (java.util.ArrayList)1 LinkedHashMap (java.util.LinkedHashMap)1