org.wso2.carbon.registry.core.utils.RegistryUtils Java Examples

The following examples show how to use org.wso2.carbon.registry.core.utils.RegistryUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RegistryCacheInvalidationServiceTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidateCacheWhenRegistryUnmountedAndCached() throws APIManagementException {

    List<RemoteConfiguration> remoteConfigurationList = new ArrayList<RemoteConfiguration>();
    Mockito.when(registryContext.getRemoteInstances()).thenReturn(remoteConfigurationList);
    DataBaseConfiguration dbConfiguration = Mockito.mock(DataBaseConfiguration.class);
    Mockito.when(registryContext.getDefaultDataBaseConfiguration()).thenReturn(dbConfiguration);
    PowerMockito.when(RegistryUtils.getResourceCache(RegistryConstants.REGISTRY_CACHE_BACKED_ID)).thenReturn(cache);
    Mockito.when(dbConfiguration.getUserName()).thenReturn("[email protected]");
    Mockito.when(dbConfiguration.getDbUrl()).thenReturn("xyz.com/db");
    RegistryCacheKey registryCacheKey = Mockito.mock(RegistryCacheKey.class);
    PowerMockito.when(RegistryUtils.buildRegistryCacheKey("[email protected]/db", 6543, path)).thenReturn(registryCacheKey);
    Mockito.when(cache.containsKey(registryCacheKey)).thenReturn(true);

    RegistryCacheInvalidationService registryCacheInvalidationService = new RegistryCacheInvalidationService();
    registryCacheInvalidationService.invalidateCache(path,tenantDomain);
    Mockito.verify(cache, Mockito.times(1)).remove(Matchers.any());
}
 
Example #2
Source File: RegistryCacheInvalidationServiceTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(6543);

    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(6543)).thenReturn(userRegistry);
    PowerMockito.mockStatic(RegistryUtils.class);
    Mockito.when(userRegistry.getRegistryContext()).thenReturn(registryContext);

    System.setProperty(CARBON_HOME, "");
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
}
 
Example #3
Source File: PlainTextIndexer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public IndexDocument getIndexedDocument(File2Index fileData) throws SolrException,
           RegistryException {
			
	IndexDocument indexDoc = new IndexDocument(fileData.path, RegistryUtils.decodeBytes(fileData.data), null);
			
	Map<String, List<String>> fields = new HashMap<String, List<String>>();
	fields.put("path", Arrays.asList(fileData.path));
			
	if (fileData.mediaType != null) {
		fields.put(IndexingConstants.FIELD_MEDIA_TYPE, Arrays.asList(fileData.mediaType));
	} else {
		fields.put(IndexingConstants.FIELD_MEDIA_TYPE, Arrays.asList("text/(.)"));
	}
	
	indexDoc.setFields(fields);
	
	return indexDoc;
}
 
Example #4
Source File: XMLIndexer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public IndexDocument getIndexedDocument(File2Index fileData) throws SolrException, RegistryException {
       // we register both the content as it is and only text content
       String xmlAsStr = RegistryUtils.decodeBytes(fileData.data);

       final StringBuilder contentOnly = new StringBuilder();
       
       IndexDocument indexDocument = new IndexDocument(fileData.path, xmlAsStr,
               contentOnly.toString());
       Map<String, List<String>> attributes = new HashMap<String, List<String>>();
       attributes.put("path", Arrays.asList(fileData.path));
       if (fileData.mediaType != null) {
           attributes.put(IndexingConstants.FIELD_MEDIA_TYPE, Arrays.asList(fileData.mediaType));
       }
       indexDocument.setFields(attributes);
       return indexDocument;
}
 
Example #5
Source File: WSDLIndexer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public IndexDocument getIndexedDocument(File2Index fileData)
		throws SolrException, RegistryException {
	
	if(log.isDebugEnabled()){
		log.debug("Indexing wsdl");
	}
	
	String xmlAsStr = RegistryUtils.decodeBytes(fileData.data);
	
	if(log.isDebugEnabled()){
		log.debug("Indexing string " + xmlAsStr);
	}
	final StringBuilder contentOnly = new StringBuilder();
       
       IndexDocument indexDocument = new IndexDocument(fileData.path, xmlAsStr,
               contentOnly.toString());
       Map<String, List<String>> attributes = new HashMap<String, List<String>>();
       attributes.put("path", Arrays.asList(fileData.path));
       if (fileData.mediaType != null) {
           attributes.put(IndexingConstants.FIELD_MEDIA_TYPE, Arrays.asList(fileData.mediaType));
       }
       indexDocument.setFields(attributes);
       return indexDocument;
}
 
Example #6
Source File: SequenceUtilsTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws UserStoreException, RegistryException {
    userRegistry = Mockito.mock(UserRegistry.class);
    serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    registryService = Mockito.mock(RegistryService.class);
    realmService = Mockito.mock(RealmService.class);
    tenantManager = Mockito.mock(TenantManager.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    PowerMockito.mockStatic(RegistryUtils.class);

    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
}
 
Example #7
Source File: SequenceUtilsTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSequenceTemplateConfigContext() throws Exception {
    String seqType = "in_sequences";
    String content = "<header description=\"SOAPAction\" name=\"SOAPAction\" scope=\"transport\""
            + " value=\"http://ws.cdyne.com/PhoneVerify/query/CheckPhoneNumber\"/>";
    Collection collection = new CollectionImpl();
    ResourceImpl resource = new ResourceImpl();
    resource.setName("checkPhoneNumber_post.xml");
    collection.setChildren(new String[] { INSEQUENCE_RESOURCES + "checkPhoneNumber_post.xml" });
    Mockito.when(userRegistry.resourceExists(INSEQUENCE_RESOURCES)).thenReturn(true);
    ConfigContext configContext = Mockito.mock(ConfigContext.class);
    Mockito.when(userRegistry.get(INSEQUENCE_RESOURCES)).thenReturn(collection);
    Mockito.when(userRegistry.get(INSEQUENCE_RESOURCES + "checkPhoneNumber_post.xml")).thenReturn(resource);
    PowerMockito.when(RegistryUtils.decodeBytes(Mockito.any(byte[].class))).thenReturn(content);
    try {
        ConfigContext context = SequenceUtils
                .getSequenceTemplateConfigContext(userRegistry, INSEQUENCE_RESOURCES, seqType, configContext);
        Assert.assertNotNull(context);
    } catch (RegistryException e) {
        Assert.fail("Failed to get the sequences from the registry");
    }
}
 
Example #8
Source File: CommonUtil.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
/**
 * @param templateName name of the report
 * @param registry     Registry
 * @throws ReportingException if failed to delete report template
 */
public static void deleteReportTemplate(String templateName, Registry registry) throws ReportingException {
    try {
        String resourcePath = RegistryUtils.getRelativePathToOriginal(ReportConstants.JRXML_PATH,
                RegistryConstants.CONFIG_REGISTRY_BASE_PATH);
        if (registry.resourceExists(resourcePath)) {
            registry.delete(resourcePath + RegistryConstants.PATH_SEPARATOR + templateName + ".jrxml");
        } else {
            if (log.isDebugEnabled()) {
                log.info("no any report templates called " + templateName + " , to delete");
            }
        }
    } catch (RegistryException e) {
        throw new ReportingException("Error occurred deleting the report template : " + templateName, e);
    }


}
 
Example #9
Source File: ProviderMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
private String getMediaType(String rxtPath, Registry registry)
        throws RegistryException, IOException, SAXException, ParserConfigurationException {
    Resource artifactRxt = registry.get(rxtPath);
    byte[] rxtContent = (byte[]) artifactRxt.getContent();
    String rxtContentString = RegistryUtils.decodeBytes(rxtContent);
    Document dom = stringToDocument(rxtContentString);
    Element domElement = (Element) dom.getElementsByTagName(Constants.ARTIFACT_TYPE).item(0);
    return domElement.getAttribute(Constants.TYPE);
}
 
Example #10
Source File: APIManagerComponentImagePermissionTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(CarbonContext.class);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.mockStatic(APIMgtDBUtil.class);
    authManager = Mockito.mock(AuthorizationManager.class);
    serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    realmService = Mockito.mock(RealmService.class);
    componentContext = Mockito.mock(ComponentContext.class);
    BundleContext bundleContext = Mockito.mock(BundleContext.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    Registry registry = Mockito.mock(Registry.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    APIManagerConfiguration configuration = Mockito.mock(APIManagerConfiguration.class);

    Mockito.when(componentContext.getBundleContext()).thenReturn(bundleContext);
    Mockito.when(realmService.getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID)).thenReturn(userRealm);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authManager);
    Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(true);
    Mockito.when(carbonContext.getRegistry(RegistryType.USER_GOVERNANCE)).thenReturn(registry);
    Mockito.doNothing().when(configuration).load(Mockito.anyString());
    Mockito.when(configuration.getFirstProperty(Mockito.anyString())).thenReturn("");
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(APIUtil.getMountedPath(null, "")).thenReturn("");
    PowerMockito.when(RegistryUtils.getAbsolutePath(null, null)).thenReturn("");
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.when(APIUtil.getMountedPath(Mockito.any(RegistryContext.class), Mockito.anyString()))
            .thenReturn("");
    PowerMockito.doThrow(new IndexOutOfBoundsException()).when(APIMgtDBUtil.class, "initialize");
    PowerMockito.whenNew(APIManagerConfiguration.class).withAnyArguments().thenReturn(configuration);
}
 
Example #11
Source File: CommonUtil.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * @param registry Registry
 * @return report name list
 * @throws ReportingException if failed to get report name list
 */
public static List<String> getAllReports(Registry registry) throws ReportingException {
    Resource resource;
    List<String> reportNames = null;
    try {

        String relativePath = RegistryUtils.getRelativePathToOriginal(ReportConstants.JRXML_PATH,
                RegistryConstants.CONFIG_REGISTRY_BASE_PATH);
        if (registry.resourceExists(relativePath)) {
            resource = registry.get(relativePath);
            if (resource instanceof Collection) {
                reportNames = new ArrayList<String>();
                String[] paths = ((Collection) resource).getChildren();
                for (String resourcePath : paths) {
                    Resource childResource = registry.get(resourcePath);

                    if (!(childResource instanceof Collection)) {
                        String name = ((ResourceImpl) childResource).getName();
                        reportNames.add(name.split(".jrxml")[0]);
                    }

                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.info("no any report templates available to generate reports");
            }
        }
    } catch (RegistryException e) {
        throw new ReportingException("Error occurred getting all the reports names", e);
    }
    return reportNames;

}
 
Example #12
Source File: ProviderMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
private boolean isContentArtifact(String rxtPath, Registry registry)
        throws RegistryException, IOException, SAXException, ParserConfigurationException {
    Resource artifactRxt = registry.get(rxtPath);
    byte[] rxtContent = (byte[]) artifactRxt.getContent();
    String rxtContentString = RegistryUtils.decodeBytes(rxtContent);
    Document dom = stringToDocument(rxtContentString);
    Element domElement = (Element) dom.getElementsByTagName(Constants.ARTIFACT_TYPE).item(0);
    return domElement.hasAttribute(Constants.FILE_EXTENSION);
}
 
Example #13
Source File: RegistryCacheInvalidationServiceTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidateCacheWhenRegistryUnmountedAndNotCached() throws APIManagementException {

    List<RemoteConfiguration> remoteConfigurationList = new ArrayList<RemoteConfiguration>();
    Mockito.when(registryContext.getRemoteInstances()).thenReturn(remoteConfigurationList);
    DataBaseConfiguration dbConfiguration = Mockito.mock(DataBaseConfiguration.class);
    Mockito.when(registryContext.getDefaultDataBaseConfiguration()).thenReturn(dbConfiguration);
    PowerMockito.when(RegistryUtils.getResourceCache(RegistryConstants.REGISTRY_CACHE_BACKED_ID)).thenReturn(cache);

    RegistryCacheInvalidationService registryCacheInvalidationService = new RegistryCacheInvalidationService();
    registryCacheInvalidationService.invalidateCache(path,tenantDomain);
    Mockito.verify(cache, Mockito.times(0)).remove(Matchers.any());
}
 
Example #14
Source File: ProviderMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
private String getStoragePath(String rxtPath, Registry registry)
        throws RegistryException, IOException, SAXException, ParserConfigurationException {
    Resource artifactRxt = registry.get(rxtPath);
    byte[] rxtContent = (byte[]) artifactRxt.getContent();
    String rxtContentString = RegistryUtils.decodeBytes(rxtContent);
    Document dom = stringToDocument(rxtContentString);
    Node storagePath = dom.getElementsByTagName(Constants.STORAGE_PATH).item(0);
    return storagePath.getFirstChild().getNodeValue();
}
 
Example #15
Source File: ProviderMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * This method checks whether there is a provider in the overview table.
 * @param rxtPath path of the rxt file
 * @param registry registry instance
 * @return boolean
 * @throws RegistryException
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws XMLStreamException
 */
private boolean hasOverviewProviderElement(String rxtPath, Registry registry)
        throws RegistryException, IOException, SAXException, ParserConfigurationException, XMLStreamException {
    Resource artifactRxt = registry.get(rxtPath);
    byte[] rxtContent = (byte[]) artifactRxt.getContent();
    String rxtContentString = RegistryUtils.decodeBytes(rxtContent);
    OMElement rxtContentOM = AXIOMUtil.stringToOM(rxtContentString);
    OMElement contentElement = rxtContentOM.getFirstChildWithName(new QName(Constants.CONTENT));
    Iterator tableNodes = contentElement.getChildrenWithLocalName(Constants.TABLE);
    while (tableNodes.hasNext()) {
        OMElement tableOMElement = (OMElement) tableNodes.next();
        if ("Overview".equals(tableOMElement.getAttributeValue(new QName(Constants.NAME)))) {
            Iterator fieldNodes = tableOMElement.getChildrenWithLocalName(Constants.FIELD);
            while (fieldNodes.hasNext()) {
                OMElement fieldElement = (OMElement) fieldNodes.next();
                OMElement nameElement = fieldElement.getFirstChildWithName(new QName(Constants.NAME));
                if (nameElement != null) {
                    if ("Provider".equals(nameElement.getText())) {
                        return true;
                    }
                }
            }
        }
    }

    return false;
}
 
Example #16
Source File: ProviderMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
private void migrateProvider(Collection root, Registry registry)
        throws RegistryException, SAXException, TransformerException, ParserConfigurationException, IOException {
    String[] childrenPaths = root.getChildren();
    for (String child : childrenPaths) {
        Resource childResource = registry.get(child);
        if (childResource instanceof Collection) {
            migrateProvider((Collection) childResource, registry);
        } else {
            String path = childResource.getPath();
            byte[] configContent = (byte[]) childResource.getContent();
            String contentString = RegistryUtils.decodeBytes(configContent);
            Document dom = stringToDocument(contentString);
            if (dom.getElementsByTagName(Constants.OVERVIEW).getLength() > 0) {
                Node overview = dom.getElementsByTagName(Constants.OVERVIEW).item(0);
                NodeList childrenList = overview.getChildNodes();
                for (int j = 0; j < childrenList.getLength(); j++) {
                    Node node = childrenList.item(j);
                    if (Constants.PROVIDER.equals(node.getNodeName())) {
                        overview.removeChild(node);
                    }
                }
                String newContentString = documentToString(dom);
                byte[] newContentObject = RegistryUtils.encodeString(newContentString);
                childResource.setContent(newContentObject);
                registry.put(path, childResource);
            }
        }
    }
}
 
Example #17
Source File: EmailUserNameMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * This method replaces artifacts containing email username with ':' to '-at-'.
 * This will replace the storage path and resource content which contains overview_provider attribute with emailusername.
 *
 * @param artifacts artifacts of a particular rxt type. with overview-provider attribute in the storage path.
 * @param registry registry instance
 * @throws RegistryException
 * @throws javax.xml.stream.XMLStreamException
 */
private static void migrateArtifactsWithEmailUserName(GenericArtifact[] artifacts, Registry registry)
        throws RegistryException, XMLStreamException {
    for (GenericArtifact artifact : artifacts) {
        boolean isProviderMetadataUpdated = false;
        String relativePath = artifact.getPath();
        if (registry.resourceExists(relativePath)) {
            Resource resource = registry.get(relativePath);
            String metadataString = RegistryUtils.decodeBytes((byte[]) resource.getContent());
            OMElement metadataOM = AXIOMUtil.stringToOM(metadataString);
            OMElement overview = metadataOM.getFirstChildWithName(new QName(Constants.METADATA_NAMESPACE,
                                                                            Constants.OVERVIEW));
            OMElement providerElement = overview.getFirstChildWithName(new QName(Constants.METADATA_NAMESPACE,
                                                                                 Constants.PROVIDER));
            if (providerElement != null && providerElement.getText().contains(Constants.OLD_EMAIL_AT_SIGN)) {
                String oldProviderName = providerElement.getText();
                String newProviderName = oldProviderName.replace(Constants.OLD_EMAIL_AT_SIGN,
                                                                 Constants.NEW_EMAIL_AT_SIGN);
                providerElement.setText(newProviderName);
                resource.setContent(metadataOM.toStringWithConsume());
                isProviderMetadataUpdated = true;
            }
            String newPath = null;
            if (relativePath.contains(Constants.OLD_EMAIL_AT_SIGN)) {
                newPath = relativePath.replace(Constants.OLD_EMAIL_AT_SIGN,
                                               Constants.NEW_EMAIL_AT_SIGN);//TODO:replaceALL
                registry.move(relativePath, newPath);
                registry.put(newPath, resource);
            } else if (relativePath.contains(Constants.NEW_EMAIL_AT_SIGN)) {
                newPath = relativePath;
                if(isProviderMetadataUpdated==true) {
                    registry.put(newPath, resource);
                }
            }
        }
    }
}
 
Example #18
Source File: RegistryCacheInvalidationServiceTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidateCacheWhenRegistryMountedAndCached() throws APIManagementException {

    List<RemoteConfiguration> remoteConfigurationList = new ArrayList<RemoteConfiguration>();
    RemoteConfiguration remoteConfiguration = new RemoteConfiguration();
    remoteConfiguration.setDbConfig("");
    remoteConfigurationList.add(remoteConfiguration);
    List<Mount> mountList = new ArrayList<Mount>();
    Mount mount = new Mount();
    mount.setPath("/_system/config");
    mountList.add(mount);
    DataBaseConfiguration dataBaseConfiguration = Mockito.mock(DataBaseConfiguration.class);
    Mockito.when(registryContext.getMounts()).thenReturn(mountList);
    Mockito.when(registryContext.getDBConfig(remoteConfiguration.getDbConfig())).thenReturn(dataBaseConfiguration);

    Mockito.when(registryContext.getRemoteInstances()).thenReturn(remoteConfigurationList);
    Mockito.when(registryContext.getDefaultDataBaseConfiguration()).thenReturn(dataBaseConfiguration);
    PowerMockito.when(RegistryUtils.getResourceCache(RegistryConstants.REGISTRY_CACHE_BACKED_ID)).thenReturn(cache);
    Mockito.when(dataBaseConfiguration.getUserName()).thenReturn("[email protected]");
    Mockito.when(dataBaseConfiguration.getDbUrl()).thenReturn("xyz.com/db");
    RegistryCacheKey registryCacheKey = Mockito.mock(RegistryCacheKey.class);
    PowerMockito.when(RegistryUtils.buildRegistryCacheKey("[email protected]/db", 6543, path)).thenReturn(registryCacheKey);
    Mockito.when(cache.containsKey(registryCacheKey)).thenReturn(true);

    RegistryCacheInvalidationService registryCacheInvalidationService = new RegistryCacheInvalidationService();
    registryCacheInvalidationService.invalidateCache(path,tenantDomain);
    Mockito.verify(cache, Mockito.times(1)).remove(Matchers.any());
}
 
Example #19
Source File: PermissionAuthorizationListener.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public boolean isAuthorized(String resourceId,
                            AuthorizationManager authorizationManager) throws
        UserStoreException {
    int tenantId = authorizationManager.getTenantId();
    if (tenantId == CarbonConstants.SUPER_TENANT_ID) {
        // no restrictions for the super tenant
        return true;
    }
    // so don't allow the rest of the tenants to set any permission to protected nodes
    String protectedPermissionPath = RegistryUtils.getAbsolutePath(null,
            RegistryConstants.CONFIG_REGISTRY_BASE_PATH +
                    CarbonConstants.UI_PROTECTED_PERMISSION_COLLECTION);

    return !(resourceId.startsWith(protectedPermissionPath));
}
 
Example #20
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructor() throws Exception {

    ServiceReferenceHolderMockCreator holderMockCreator = new ServiceReferenceHolderMockCreator(1);
    ServiceReferenceHolderMockCreator.initContextService();
    holderMockCreator.initRegistryServiceMockCreator(false, new Object());
    RegistryAuthorizationManager registryAuthorizationManager = Mockito.mock(RegistryAuthorizationManager.class);
    Mockito.doThrow(UserStoreException.class).doNothing().when(registryAuthorizationManager)
            .authorizeRole(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    PowerMockito.whenNew(RegistryAuthorizationManager.class).withAnyArguments()
            .thenReturn(registryAuthorizationManager);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.when(RegistryUtils.getAbsolutePath((RegistryContext) Mockito.any(), Mockito.anyString()))
            .thenReturn("/test");
    try {
        new AbstractAPIManager(null) {
            @Override
            public String getGraphqlSchema(APIIdentifier apiId) throws APIManagementException {
                return null;
            }
        };
        Assert.fail("User store exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while setting the permissions"));
    }

    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    PowerMockito.mockStatic(MultitenantUtils.class);
    PowerMockito.when(MultitenantUtils.getTenantDomain(Mockito.anyString())).thenReturn(SAMPLE_TENANT_DOMAIN_1);
    String userName = "admin";

    Mockito.verify(
            holderMockCreator.getRegistryServiceMockCreator().getMock().getConfigSystemRegistry(Mockito.anyInt()),
            Mockito.atLeastOnce());
}
 
Example #21
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws UserStoreException, RegistryException {
    apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    userRealm = Mockito.mock(UserRealm.class);
    serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    realmService = Mockito.mock(RealmService.class);
    tenantManager = Mockito.mock(TenantManager.class);
    userStoreManager = Mockito.mock(UserStoreManager.class);
    keyManager = Mockito.mock(KeyManager.class);
    cacheInvalidator = Mockito.mock(CacheInvalidator.class);
    registryService = Mockito.mock(RegistryService.class);
    genericArtifactManager = Mockito.mock(GenericArtifactManager.class);
    registry = Mockito.mock(Registry.class);
    userRegistry = Mockito.mock(UserRegistry.class);
    authorizationManager = Mockito.mock(AuthorizationManager.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(ApplicationUtils.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    PowerMockito.mockStatic(KeyManagerHolder.class);
    PowerMockito.mockStatic(CacheInvalidator.class);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(CacheInvalidator.getInstance()).thenReturn(cacheInvalidator);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authorizationManager);
    Mockito.when(KeyManagerHolder.getKeyManagerInstance(Mockito.anyString(),Mockito.anyString())).thenReturn(keyManager);
    PowerMockito.when(APIUtil.replaceSystemProperty(anyString())).thenAnswer((Answer<String>) invocation -> {
        Object[] args = invocation.getArguments();
        return (String) args[0];
    });
}
 
Example #22
Source File: SequenceUtils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the velocity template config context with sequence data populated
 *
 * @param registry      user registry reference
 * @param resourcePath  registry resource path
 * @param seqType       sequence type whether in or out sequence
 * @param configContext velocity template config context
 * @return {@link ConfigContext} sequences populated velocity template config context
 * @throws org.wso2.carbon.registry.api.RegistryException throws when getting registry resource content
 */
public static ConfigContext getSequenceTemplateConfigContext(UserRegistry registry, String resourcePath,
        String seqType, ConfigContext configContext) throws org.wso2.carbon.registry.api.RegistryException {
    Resource regResource;
    if (registry.resourceExists(resourcePath)) {
        regResource = registry.get(resourcePath);
        String[] resources = ((Collection) regResource).getChildren();
        JSONObject pathObj = new JSONObject();
        if (resources != null) {
            for (String path : resources) {
                Resource resource = registry.get(path);
                String method = resource.getProperty(SOAPToRESTConstants.METHOD);
                String registryResourceProp = resource.getProperty(SOAPToRESTConstants.Template.RESOURCE_PATH);
                String resourceName;
                if (registryResourceProp != null) {
                    resourceName = SOAPToRESTConstants.SequenceGen.PATH_SEPARATOR + registryResourceProp;
                } else {
                    resourceName  = ((ResourceImpl) resource).getName();
                    resourceName = resourceName.replaceAll(SOAPToRESTConstants.SequenceGen.XML_FILE_RESOURCE_PREFIX,
                            SOAPToRESTConstants.EMPTY_STRING);
                    resourceName = resourceName
                            .replaceAll(SOAPToRESTConstants.SequenceGen.RESOURCE_METHOD_SEPERATOR + method,
                                    SOAPToRESTConstants.EMPTY_STRING);
                    resourceName = SOAPToRESTConstants.SequenceGen.PATH_SEPARATOR + resourceName;
                }
                String content = RegistryUtils.decodeBytes((byte[]) resource.getContent());
                JSONObject contentObj = new JSONObject();
                contentObj.put(method, content);
                pathObj.put(resourceName, contentObj);
            }
        } else {
            log.error("No sequences were found on the resource path: " + resourcePath);
        }
        configContext = new SOAPToRESTAPIConfigContext(configContext, pathObj, seqType);
    }
    return configContext;
}
 
Example #23
Source File: GAConfigMediaTypeHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public void put(RequestContext requestContext) throws RegistryException {
    ResourceImpl resource = (ResourceImpl) requestContext.getResource();
    if (! resource.isContentModified()) {
        return;
    }

    // Local entry is updated only if the content of ga-config is updated
    Object content = resource.getContent();
    String resourceContent;
    if (content instanceof String) {
        resourceContent = (String) content;
    } else if (content instanceof byte[]) {
        resourceContent = RegistryUtils.decodeBytes((byte[]) content);
    } else {
        log.warn("The resource content is not of expected type");
        return;
    }

    APIManagerConfiguration config = getAPIManagerConfig();
    if (config == null) {
        return;
    }

    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    Map<String, Environment> environments = config.getApiGatewayEnvironments();

    for (String environmentName : environments.keySet()) {
        Environment environment = environments.get(environmentName);

        try {
            LocalEntryAdminClient localEntryAdminClient = new LocalEntryAdminClient(environment, tenantDomain);
            localEntryAdminClient.deleteEntry(APIConstants.GA_CONF_KEY);
            localEntryAdminClient.addLocalEntry("<localEntry key=\"" + APIConstants.GA_CONF_KEY + "\">"
                    + resourceContent + "</localEntry>");
        } catch (AxisFault e) {
            log.error("Error occurred while adding local entry(GA-config) to gateway " + environmentName, e);
        }
    }
}
 
Example #24
Source File: APIEndpointPasswordRegistryHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method is called for a registry get operation
 *
 * @param requestContext - The request context
 * @return - returns the modified resource
 * @throws RegistryException
 */
public Resource get(RequestContext requestContext) throws RegistryException {
    Resource resource = requestContext.getResource();
    if (resource != null) {
        String resourceContent = RegistryUtils.decodeBytes((byte[]) resource.getContent());
        try {
            OMElement omElement = AXIOMUtil.stringToOM(resourceContent);
            Iterator mainChildIt = omElement.getChildren();
            while (mainChildIt.hasNext()) {
                Object childObj = mainChildIt.next();
                if ((childObj instanceof OMElement) && ((APIConstants.OVERVIEW_ELEMENT)
                        .equals(((OMElement) childObj).getLocalName()))) {
                    Iterator childIt = ((OMElement) childObj)
                            .getChildrenWithLocalName(APIConstants.ENDPOINT_PASSWORD_ELEMENT);
                    //There is only one ep-password, hence no iteration
                    if (childIt.hasNext()) {
                        OMElement child = (OMElement) childIt.next();
                        String actualPassword = child.getText();
                        //Store the password in a hidden property to access in the PUT method.
                        if (!actualPassword.isEmpty()) {
                            resource.setProperty(APIConstants.REGISTRY_HIDDEN_ENDPOINT_PROPERTY, actualPassword);
                            child.setText(APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD);
                        }
                    }
                }
            }
            resource.setContent(RegistryUtils.encodeString(omElement.toString()));
            log.debug("Modified API resource content with default password before get operation");
        } catch (XMLStreamException e) {
            log.error("There was an error in reading XML Stream during API get.");
            throw new RegistryException("There was an error reading the API resource.", e);
        }
    }
    return resource;
}
 
Example #25
Source File: PermissionAuthorizationListener.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public boolean isAuthorized(String resourceId,
                            AuthorizationManager authorizationManager) throws
        UserStoreException {
    int tenantId = authorizationManager.getTenantId();
    if (tenantId == CarbonConstants.SUPER_TENANT_ID) {
        // no restrictions for the super tenant
        return true;
    }
    // so don't allow the rest of the tenants to set any permission to protected nodes
    String protectedPermissionPath = RegistryUtils.getAbsolutePath(null,
            RegistryConstants.CONFIG_REGISTRY_BASE_PATH +
                    CarbonConstants.UI_PROTECTED_PERMISSION_COLLECTION);

    return !(resourceId.startsWith(protectedPermissionPath));
}
 
Example #26
Source File: SecureVaultPasswordMigrationClient.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * update passwords in registry
 *
 * @param encryptedPasswords encrypted passwords map
 */
private void updatePasswords(Map<String, String> encryptedPasswords) {
    log.info("Initiating password migration");
    if (RegistryUtils.isRegistryReadOnly(userRegistry.getRegistryContext())) {
        return;
    }
    for (Map.Entry<String, String> entry : encryptedPasswords.entrySet()) {
        removeProperty(entry.getKey());
        updateProperty(entry.getKey(), entry.getValue());
    }
}
 
Example #27
Source File: UserAwareAPIProviderTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Before
public void init() throws Exception {
    System.setProperty("carbon.home", "");
    apiIdentifier = new APIIdentifier("admin_identifier1_v1.0");
    PowerMockito.mockStatic(ApiMgtDAO.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    userRegistry = Mockito.mock(UserRegistry.class);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    APIManagerConfigurationService apiManagerConfigurationService = Mockito
            .mock(APIManagerConfigurationService.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    resource = Mockito.mock(Resource.class, Mockito.CALLS_REAL_METHODS);
    Mockito.doReturn(apiManagerConfiguration).when(apiManagerConfigurationService).getAPIManagerConfiguration();
    Mockito.doReturn(APIConstants.API_GATEWAY_TYPE_SYNAPSE).when(apiManagerConfiguration)
            .getFirstProperty(APIConstants.API_GATEWAY_TYPE);
    Mockito.doReturn("true").when(apiManagerConfiguration)
            .getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_ACCESS_CONTROL_LEVELS);
    Mockito.doReturn(userRegistry).when(registryService)
            .getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt());
    Mockito.doReturn(userRegistry).when(registryService).getConfigSystemRegistry(Mockito.anyInt());
    Mockito.doReturn(userRegistry).when(registryService).getConfigSystemRegistry();
    Mockito.doReturn(resource).when(userRegistry).newResource();
    Mockito.doReturn(null).when(userRegistry).getUserRealm();
    PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(APIUtil.getAPIPath(Mockito.any(APIIdentifier.class))).thenReturn("test");
    PowerMockito.when(APIUtil.getArtifactManager(Mockito.any(Registry.class), Mockito.anyString()))
            .thenReturn(artifactManager);
    PowerMockito.doNothing().when(ServiceReferenceHolder.class, "setUserRealm", Mockito.any());
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    PowerMockito.when(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName())).
            thenReturn(apiIdentifier.getProviderName());
    Mockito.doReturn(realmService).when(serviceReferenceHolder).getRealmService();
    Mockito.doReturn(tenantManager).when(realmService).getTenantManager();
    Mockito.doReturn(registryService).when(serviceReferenceHolder).getRegistryService();
    Mockito.doReturn(apiManagerConfigurationService).when(serviceReferenceHolder)
            .getAPIManagerConfigurationService();
    PowerMockito.when(APIUtil.compareRoleList(Mockito.any(String[].class), Mockito.anyString()))
            .thenCallRealMethod();
    ConfigurationContextService configurationContextService = TestUtils.initConfigurationContextService(true);
    PowerMockito.when(ServiceReferenceHolder.getContextService()).thenReturn(configurationContextService);
    userAwareAPIProvider = new UserAwareAPIProvider(ADMIN_ROLE_NAME);
    PrivilegedCarbonContext prcontext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(prcontext);
}
 
Example #28
Source File: APIManagerComponentTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testShouldActivateWhenAllPrerequisitesMet() throws Exception {
    PowerMockito.mockStatic(APIMgtDBUtil.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(AuthorizationUtils.class);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(SQLConstantManagerFactory.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    ComponentContext componentContext = Mockito.mock(ComponentContext.class);
    BundleContext bundleContext = Mockito.mock(BundleContext.class);
    APIManagerConfiguration configuration = Mockito.mock(APIManagerConfiguration.class);
    APIManagerConfigurationService configurationService = Mockito.mock(APIManagerConfigurationService.class);
    AuthorizationManager authManager = Mockito.mock(AuthorizationManager.class);
    Registry registry = Mockito.mock(Registry.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    OutputEventAdapterService adapterService = Mockito.mock(OutputEventAdapterService.class);
    ThrottleProperties throttleProperties = new ThrottleProperties();

    Mockito.doNothing().when(configuration).load(Mockito.anyString());
    Mockito.doNothing().when(authManager)
            .authorizeRole(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    Mockito.doNothing().when(adapterService).create(null);
    Mockito.when(componentContext.getBundleContext()).thenReturn(bundleContext);
    Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(true);
    Mockito.when(configuration.getFirstProperty(Mockito.anyString())).thenReturn("").thenReturn(null);
    Mockito.when(bundleContext.registerService("", CommonConfigDeployer.class, null)).thenReturn(null);
    Mockito.when(authManager.isRoleAuthorized(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))
            .thenReturn(true);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(configurationService);
    Mockito.when(serviceReferenceHolder.getOutputEventAdapterService()).thenReturn(adapterService);
    Mockito.when(configurationService.getAPIManagerConfiguration()).thenReturn(configuration);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authManager);
    Mockito.when(configuration.getThrottleProperties()).thenReturn(throttleProperties);
    PowerMockito.doNothing().when(APIMgtDBUtil.class, "initialize");
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantExternalStoreConfig", Mockito.anyInt());
    PowerMockito.doNothing().when(AuthorizationUtils.class ,"addAuthorizeRoleListener",
            Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    PowerMockito.doNothing().when(SQLConstantManagerFactory.class, "initializeSQLConstantManager");
    PowerMockito.when(APIUtil.getMountedPath(null, "")).thenReturn("");
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(RegistryUtils.getAbsolutePath(null, null)).thenReturn("");
    PowerMockito.whenNew(APIManagerConfiguration.class).withAnyArguments().thenReturn(configuration);

    PowerMockito.mockStatic(ApiMgtDAO.class);
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);

    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration();
    APIManagerComponent apiManagerComponent = new APIManagerComponentWrapper(registry);
    GatewayArtifactSynchronizerProperties synchronizerProperties = new GatewayArtifactSynchronizerProperties();
    Mockito.when(config.getGatewayArtifactSynchronizerProperties()).thenReturn(synchronizerProperties);
    EventHubConfigurationDto eventHubConfigurationDto = new EventHubConfigurationDto();
    eventHubConfigurationDto.setEnabled(true);
    eventHubConfigurationDto.setInitDelay(0);
    eventHubConfigurationDto.setUsername("a");
    eventHubConfigurationDto.setPassword("sss".toCharArray());
    eventHubConfigurationDto.setServiceUrl("https://localhost");
    EventHubConfigurationDto.EventHubPublisherConfiguration eventHubPublisherConfiguration =
            new EventHubConfigurationDto.EventHubPublisherConfiguration();
    eventHubConfigurationDto.setEventHubPublisherConfiguration(eventHubPublisherConfiguration);
    Mockito.when(config.getEventHubConfigurationDto()).thenReturn(eventHubConfigurationDto);
    try {
        apiManagerComponent.activate(componentContext);
    } catch (FileNotFoundException f) {
        // Exception thrown here means that method was continued without the configuration file
        Assert.fail("Should not throw an exception");
    }
}
 
Example #29
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetPublishedAPIsByProvider1()
        throws APIManagementException, RegistryException, org.wso2.carbon.user.core.UserStoreException {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    String providerId = "1";
    API api = new API(new APIIdentifier(API_PROVIDER, SAMPLE_API_NAME, SAMPLE_API_VERSION));
    API api1 = new API(new APIIdentifier(API_PROVIDER, "pizza_api", "2.0.0"));
    PowerMockito.when(APIUtil.isAllowDisplayMultipleVersions()).thenReturn(true, false);
    PowerMockito.when(APIUtil.isAllowDisplayAPIsWithMultipleStatus()).thenReturn(true, false);
    PowerMockito.when(APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY))
            .thenReturn(genericArtifactManager);
    PowerMockito.when(APIUtil.getMountedPath(Mockito.any(), Mockito.anyString())).thenReturn("system/governance");
    PowerMockito.when(APIUtil.getAPI(Mockito.any())).thenReturn(api);
    PowerMockito.when(APIUtil.replaceEmailDomainBack(Mockito.anyString())).thenReturn(providerId);
    PowerMockito.when(APIUtil.getLcStateFromArtifact((GovernanceArtifact) Mockito.any()))
            .thenReturn(APIConstants.PUBLISHED);
    GenericArtifact genericArtifact1 = new GenericArtifactImpl(new QName("local"), "artifact1");
    GenericArtifact genericArtifact2 = new GenericArtifactImpl(new QName("local"), "artifact2");
    GenericArtifact[] genericArtifacts = new GenericArtifact[] { genericArtifact1, genericArtifact2 };
    Mockito.when(genericArtifactManager.findGenericArtifacts((Map<String, List<String>>) Mockito.any()))
            .thenThrow(GovernanceException.class).thenReturn(genericArtifacts);
    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.when(GovernanceUtils.getArtifactPath(Mockito.any(), Mockito.anyString())).thenReturn("/path1");
    PowerMockito.when(RegistryUtils.getAbsolutePath(Mockito.any(), Mockito.anyString())).thenReturn("/path1");
    Assert.assertNull(apiConsumer.getPublishedAPIsByProvider("1", "test_user", 5, API_PROVIDER, "John"));
    Assert.assertEquals(0,
            apiConsumer.getPublishedAPIsByProvider("1", "test_user", 5, API_PROVIDER, "John").size());
    Mockito.when(
            authorizationManager.isUserAuthorized(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))
            .thenReturn(true);
    Resource resource = new ResourceImpl();
    resource.setUUID(UUID.randomUUID().toString());
    Mockito.when(userRegistry.get(Mockito.anyString())).thenReturn(resource);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifactImpl.class);
    Mockito.when(genericArtifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(genericArtifact);
    Assert.assertEquals(1,
            apiConsumer.getPublishedAPIsByProvider("1", "test_user", 1, API_PROVIDER, "John").size());
    api.setVisibility("specific_to_roles");
    PowerMockito.when(MultitenantUtils.getTenantDomain(Mockito.anyString()))
            .thenReturn("carbon.super", "carbon.super", SAMPLE_TENANT_DOMAIN_1);
    PowerMockito.when(APIUtil.getAPI((GenericArtifact) Mockito.any())).thenReturn(api, api1);
    Assert.assertEquals(1,
            apiConsumer.getPublishedAPIsByProvider("1", "test_user", 5, API_PROVIDER, "John").size());
    Mockito.when(
            authorizationManager.isRoleAuthorized(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))
            .thenReturn(true);
    Assert.assertEquals(1, apiConsumer.getPublishedAPIsByProvider("1", "", 5, API_PROVIDER, "John").size());

}
 
Example #30
Source File: APIEndpointPasswordRegistryHandler.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method is called for a registry put operation
 *
 * @param requestContext - The request context
 * @throws RegistryException
 */
public void put(RequestContext requestContext) throws RegistryException {
    Resource resource = requestContext.getResource();
    Object content = resource.getContent();
    String resourceContent;
    if (content instanceof String) {
        resourceContent = (String) resource.getContent();
    } else if (content instanceof byte[]) {
        resourceContent = RegistryUtils.decodeBytes((byte[]) resource.getContent());
    } else {
        log.warn("The resource content is not of expected type");
        return;
    }
    try {
        OMElement omElement = AXIOMUtil.stringToOM(resourceContent);
        Iterator mainChildIt = omElement.getChildren();
        while (mainChildIt.hasNext()) {
            Object childObj = mainChildIt.next();
            if ((childObj instanceof OMElement) && ((APIConstants.OVERVIEW_ELEMENT)
                    .equals(((OMElement) childObj).getLocalName()))) {
                Iterator childIt = ((OMElement) childObj)
                        .getChildrenWithLocalName(APIConstants.ENDPOINT_PASSWORD_ELEMENT);
                //There is only one ep-password, hence no iteration
                if (childIt.hasNext()) {
                    OMElement child = (OMElement) childIt.next();
                    String pswd = child.getText();
                    //Password has been edited on put
                    if (!"".equals(pswd) && !((APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD).equals(pswd))) {
                        resource.setProperty(APIConstants.REGISTRY_HIDDEN_ENDPOINT_PROPERTY, pswd);
                        child.setText(pswd);
                    } else if ((APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD)
                            .equals(pswd)) { //Password not being changed
                        String actualPassword = resource
                                .getProperty(APIConstants.REGISTRY_HIDDEN_ENDPOINT_PROPERTY);
                        child.setText(actualPassword);
                    }
                }
            }
        }
        resource.setContent(RegistryUtils.encodeString(omElement.toString()));
        requestContext.setResource(resource);
        log.debug("Modified API resource content with actual password before put operation");
    } catch (XMLStreamException e) {
        log.error("There was an error in reading XML Stream during API update.");
        throw new RegistryException("There was an error updating the API resource.", e);
    }
}