Search in sources :

Example 46 with ResourcePath

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

the class AbstractAPIManagerTestCase method testDeleteWsdl.

@Test
public void testDeleteWsdl() throws APIManagementException, RegistryException {
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    Collection parentCollection = new CollectionImpl();
    String wsdlResourcePath = APIConstants.API_WSDL_RESOURCE;
    String resourcePath = wsdlResourcePath + "/wsdl1";
    parentCollection.setChildren(new String[] { resourcePath });
    Mockito.when(registry.get(wsdlResourcePath)).thenReturn(parentCollection);
    Resource resource = new ResourceImpl(resourcePath, new ResourceDO());
    Mockito.when(registry.get(resourcePath)).thenThrow(RegistryException.class).thenReturn(resource);
    Mockito.when(registry.resourceExists(wsdlResourcePath)).thenReturn(true);
    try {
        abstractAPIManager.deleteWsdl(SAMPLE_RESOURCE_ID);
        Assert.fail("Exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while accessing registry objects"));
    }
    Mockito.when(registry.resourceExists(resourcePath)).thenReturn(true, true, true, true, false);
    resource.setUUID(SAMPLE_RESOURCE_ID);
    Mockito.doThrow(RegistryException.class).doNothing().when(registry).delete(resourcePath);
    try {
        abstractAPIManager.deleteWsdl(SAMPLE_RESOURCE_ID);
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to delete wsdl"));
    }
    Assert.assertFalse(abstractAPIManager.deleteWsdl(SAMPLE_RESOURCE_ID));
    Assert.assertTrue(abstractAPIManager.deleteWsdl(SAMPLE_RESOURCE_ID));
}
Also used : ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) CollectionImpl(org.wso2.carbon.registry.core.CollectionImpl) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ResourceDO(org.wso2.carbon.registry.core.jdbc.dataobjects.ResourceDO) Resource(org.wso2.carbon.registry.core.Resource) Collection(org.wso2.carbon.registry.core.Collection) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 47 with ResourcePath

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

the class APIManagerComponent method addRxtConfigs.

private void addRxtConfigs() throws APIManagementException {
    String rxtDir = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "rxts";
    File file = new File(rxtDir);
    // create a FilenameFilter
    FilenameFilter filenameFilter = new FilenameFilter() {

        public boolean accept(File dir, String name) {
            // if the file extension is .rxt return true, else false
            return name.endsWith(".rxt");
        }
    };
    String[] rxtFilePaths = file.list(filenameFilter);
    if (rxtFilePaths == null || rxtFilePaths.length == 0) {
        log.info("No RXTs Found.");
        return;
    }
    RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
    UserRegistry systemRegistry;
    try {
        systemRegistry = registryService.getRegistry(CarbonConstants.REGISTRY_SYSTEM_USERNAME);
    } catch (RegistryException e) {
        throw new APIManagementException("Failed to get registry", e);
    }
    for (String rxtPath : rxtFilePaths) {
        String resourcePath = GovernanceConstants.RXT_CONFIGS_PATH + RegistryConstants.PATH_SEPARATOR + rxtPath;
        try {
            if (systemRegistry.resourceExists(resourcePath)) {
                // Adding Authorization header to the template if not exist
                if (API_RXT.equals(rxtPath)) {
                    // get Registry resource
                    Resource resource = systemRegistry.get(resourcePath);
                    if (resource.getContent() != null) {
                        // check whether the resource contains a field called authorization header.
                        if (!RegistryUtils.decodeBytes((byte[]) resource.getContent()).contains(AUTHORIZATION_HEADER)) {
                            updateRegistryResourceContent(resource, systemRegistry, rxtDir, rxtPath, resourcePath);
                        }
                        // check whether the resource contains a section called 'Labels' and add it
                        if (!RegistryUtils.decodeBytes((byte[]) resource.getContent()).contains(LABELS)) {
                            updateRegistryResourceContent(resource, systemRegistry, rxtDir, rxtPath, resourcePath);
                        }
                        // check whether the resource contains a section called 'API Security' and add it
                        if (!RegistryUtils.decodeBytes((byte[]) resource.getContent()).contains(API_SECURITY)) {
                            updateRegistryResourceContent(resource, systemRegistry, rxtDir, rxtPath, resourcePath);
                        }
                        // check whether the resource contains a section called 'Type' and add it
                        if (!RegistryUtils.decodeBytes((byte[]) resource.getContent()).contains(TYPE_ELEMENT)) {
                            updateRegistryResourceContent(resource, systemRegistry, rxtDir, rxtPath, resourcePath);
                        }
                        // check whether the resource contains a section called 'enable Schema Validation' and
                        // add it
                        Object enableValidation = resource.getContent();
                        if (!RegistryUtils.decodeBytes((byte[]) enableValidation).contains(ENABLE_SCHEMA_VALIDATION)) {
                            updateRegistryResourceContent(resource, systemRegistry, rxtDir, rxtPath, resourcePath);
                        }
                    }
                }
                continue;
            }
            String rxt = FileUtil.readFileToString(rxtDir + File.separator + rxtPath);
            Resource resource = systemRegistry.newResource();
            resource.setContent(rxt.getBytes(Charset.defaultCharset()));
            resource.setMediaType(APIConstants.RXT_MEDIA_TYPE);
            systemRegistry.put(resourcePath, resource);
        } catch (IOException e) {
            String msg = "Failed to read rxt files";
            throw new APIManagementException(msg, e);
        } catch (RegistryException e) {
            String msg = "Failed to add rxt to registry ";
            throw new APIManagementException(msg, e);
        }
    }
}
Also used : FilenameFilter(java.io.FilenameFilter) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) IOException(java.io.IOException) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) File(java.io.File) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 48 with ResourcePath

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

the class CustomAPIIndexer method getIndexedDocument.

public IndexDocument getIndexedDocument(AsyncIndexer.File2Index fileData) throws SolrException, RegistryException {
    Registry registry = GovernanceUtils.getGovernanceSystemRegistry(IndexingManager.getInstance().getRegistry(fileData.tenantId));
    String resourcePath = fileData.path.substring(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH.length());
    Resource resource = null;
    if (resourcePath.contains("/apimgt/applicationdata/apis/")) {
        return null;
    }
    if (registry.resourceExists(resourcePath)) {
        resource = registry.get(resourcePath);
    }
    if (log.isDebugEnabled()) {
        log.debug("CustomAPIIndexer is currently indexing the api at path " + resourcePath);
    }
    // Here we are adding properties as fields, so that we can search the properties as we do for attributes.
    IndexDocument indexDocument = super.getIndexedDocument(fileData);
    Map<String, List<String>> fields = indexDocument.getFields();
    if (resource != null) {
        Properties properties = resource.getProperties();
        Enumeration propertyNames = properties.propertyNames();
        while (propertyNames.hasMoreElements()) {
            String property = (String) propertyNames.nextElement();
            if (log.isDebugEnabled()) {
                log.debug("API at " + resourcePath + " has " + property + " property");
            }
            if (property.startsWith(APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX)) {
                fields.put((OVERVIEW_PREFIX + property), getLowerCaseList(resource.getPropertyValues(property)));
                if (log.isDebugEnabled()) {
                    log.debug(property + " is added as " + (OVERVIEW_PREFIX + property) + " field for indexing");
                }
            }
        }
        indexDocument.setFields(fields);
    }
    return indexDocument;
}
Also used : IndexDocument(org.wso2.carbon.registry.indexing.solr.IndexDocument) Enumeration(java.util.Enumeration) Resource(org.wso2.carbon.registry.core.Resource) ArrayList(java.util.ArrayList) List(java.util.List) Registry(org.wso2.carbon.registry.core.Registry) Properties(java.util.Properties)

Example 49 with ResourcePath

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

the class CustomAPIIndexHandlerTest method testPut.

/**
 * This method tests whether the CustomAPIIndexer works correctly under different circumstances without throwing
 * Exception.
 *
 * @throws RegistryException Registry Exception.
 */
@Test
public void testPut() throws RegistryException {
    // Resource without property.
    Resource resource = new ResourceImpl();
    RequestContext requestContext = Mockito.mock(RequestContext.class);
    Mockito.doReturn(Mockito.mock(Registry.class)).when(requestContext).getRegistry();
    ResourcePath resourcePath = Mockito.mock(ResourcePath.class);
    Mockito.doReturn(resource).when(requestContext).getResource();
    Mockito.doReturn(resourcePath).when(requestContext).getResourcePath();
    CustomAPIIndexHandler customAPIIndexHandler = new CustomAPIIndexHandler();
    customAPIIndexHandler.put(requestContext);
    // Resource with property.
    resource.setProperty(APIConstants.CUSTOM_API_INDEXER_PROPERTY, "true");
    Mockito.doReturn(resource).when(requestContext).getResource();
    customAPIIndexHandler.put(requestContext);
}
Also used : ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) ResourcePath(org.wso2.carbon.registry.core.ResourcePath) Resource(org.wso2.carbon.registry.core.Resource) RequestContext(org.wso2.carbon.registry.core.jdbc.handlers.RequestContext) Registry(org.wso2.carbon.registry.core.Registry) Test(org.junit.Test)

Example 50 with ResourcePath

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

the class RegistryPersistenceImpl method searchContentForPublisher.

@Override
public PublisherContentSearchResult searchContentForPublisher(Organization org, String searchQuery, int start, int offset, UserContext ctx) throws APIPersistenceException {
    log.debug("Requested query for publisher content search: " + searchQuery);
    Map<String, String> attributes = RegistrySearchUtil.getPublisherSearchAttributes(searchQuery, ctx);
    if (log.isDebugEnabled()) {
        log.debug("Search attributes : " + attributes);
    }
    boolean isTenantFlowStarted = false;
    PublisherContentSearchResult result = null;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        String requestedTenantDomain = org.getName();
        String tenantAwareUsername = getTenantAwareUsername(RegistryPersistenceUtil.getTenantAdminUserName(requestedTenantDomain));
        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 PublisherContentSearchResult();
            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);
                        // 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();
                        PublisherAPI pubAPI;
                        if (apiArtifactId != null) {
                            GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
                            String accociatedType;
                            if (apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE).equals(APIConstants.AuditLogConstants.API_PRODUCT)) {
                                // associatedAPIProduct = APIUtil.getAPIProduct(apiArtifact, registry);
                                accociatedType = APIConstants.API_PRODUCT;
                            } else {
                                // associatedAPI = APIUtil.getAPI(apiArtifact, registry);
                                accociatedType = APIConstants.API;
                            }
                            pubAPI = RegistryPersistenceUtil.getAPIForSearch(apiArtifact);
                            docSearch.setApiName(pubAPI.getApiName());
                            docSearch.setApiProvider(pubAPI.getProviderName());
                            docSearch.setApiVersion(pubAPI.getVersion());
                            docSearch.setApiUUID(pubAPI.getId());
                            docSearch.setAssociatedType(accociatedType);
                            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();
                        // API api;
                        // APIProduct apiProduct;
                        String type;
                        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);
                                type = APIConstants.API_PRODUCT;
                            } else {
                                // api = APIUtil.getAPI(apiArtifact, registry);
                                // apiSet.add(api);
                                type = APIConstants.API;
                            }
                            PublisherAPI pubAPI = RegistryPersistenceUtil.getAPIForSearch(apiArtifact);
                            PublisherSearchContent content = new PublisherSearchContent();
                            content.setContext(pubAPI.getContext());
                            content.setDescription(pubAPI.getDescription());
                            content.setId(pubAPI.getId());
                            content.setName(pubAPI.getApiName());
                            content.setProvider(RegistryPersistenceUtil.replaceEmailDomainBack(pubAPI.getProviderName()));
                            content.setType(type);
                            content.setVersion(pubAPI.getVersion());
                            content.setStatus(pubAPI.getStatus());
                            content.setAdvertiseOnly(pubAPI.isAdvertiseOnly());
                            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 | APIManagementException e) {
        throw new APIPersistenceException("Error while searching for content ", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return result;
}
Also used : DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) ArrayList(java.util.ArrayList) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) 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) PublisherSearchContent(org.wso2.carbon.apimgt.persistence.dto.PublisherSearchContent) 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) PublisherContentSearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherContentSearchResult)

Aggregations

Resource (org.wso2.carbon.registry.core.Resource)51 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)48 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)44 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)28 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)25 IOException (java.io.IOException)18 Registry (org.wso2.carbon.registry.core.Registry)16 Collection (org.wso2.carbon.registry.core.Collection)15 UserStoreException (org.wso2.carbon.user.api.UserStoreException)14 Test (org.junit.Test)13 Resource (org.wso2.carbon.registry.api.Resource)13 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)12 ArrayList (java.util.ArrayList)11 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)11 RegistryException (org.wso2.carbon.registry.api.RegistryException)11 ResourceImpl (org.wso2.carbon.registry.core.ResourceImpl)11 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)11 JSONParser (org.json.simple.parser.JSONParser)10 ParseException (org.json.simple.parser.ParseException)10 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)10