Java Code Examples for org.wso2.carbon.registry.core.Resource

The following examples show how to use org.wso2.carbon.registry.core.Resource. These examples are extracted from open source projects. 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 Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetThumbnailLastUpdatedTime()
        throws APIManagementException, org.wso2.carbon.user.api.UserStoreException, RegistryException {
    APIIdentifier identifier = new APIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(true, false, true);
    ResourceDO resourceDO = new ResourceDO();
    resourceDO.setLastUpdatedOn(34579002);
    Resource resource = new ResourceImpl("test/", resourceDO);

    Mockito.when(registry.get(Mockito.anyString())).thenThrow(RegistryException.class).thenReturn(resource);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);

    try {
        abstractAPIManager.getThumbnailLastUpdatedTime(identifier);
        Assert.fail("Registry exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while loading API icon from the registry"));
    }
    Assert.assertNull(abstractAPIManager.getThumbnailLastUpdatedTime(identifier));
    Assert.assertEquals(abstractAPIManager.getThumbnailLastUpdatedTime(identifier), "34579002");
}
 
Example 2
Source Project: carbon-commons   Source File: Util.java    License: Apache License 2.0 6 votes vote down vote up
public static String getRelativeUrl() {
    BundleContext context = CarbonUIUtil.getBundleContext();
    ServiceReference reference = context.getServiceReference(RegistryService.class
            .getName());
    RegistryService registryService = (RegistryService) context.getService(reference);
    String url = null;
    try {
        Registry systemRegistry = registryService.getConfigSystemRegistry();
        Resource resource = systemRegistry.get("/carbon/connection/props");
        String servicePath = resource.getProperty("service-path");
        String contextRoot = resource.getProperty("context-root");
        contextRoot = contextRoot.equals("/") ? "" : contextRoot;
        url = contextRoot + servicePath + "/Java2WSDLService";
    } catch (Exception e) {
        log.error(e);
    }
    return url;
}
 
Example 3
@Test
public void testShouldNotLoadMessageWhenErrorOccurs() throws RegistryException {
    Resource resource = Mockito.mock(Resource.class);
    NewAPIVersionEmailNotifier emailNotifier = new NewAPIVersionEmailNotifier() {
        @Override
        protected Registry getConfigSystemRegistry(int tenantId) throws RegistryException {
            return registry;
        }
    };
    Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(true).thenThrow(RegistryException.class);
    Mockito.when(registry.get(Mockito.anyString())).thenReturn(resource);
    Mockito.when(resource.getContent()).thenReturn("".getBytes());

    try {
        NotificationDTO notification = emailNotifier.loadMessageTemplate(notificationDTO);
        Assert.assertFalse(!notification.getMessage().equals(""));

        emailNotifier.loadMessageTemplate(notificationDTO);
        Assert.fail("Should fail with an exception");
    } catch (NotificationException e) {
        // exception is expection
        return;
    }
}
 
Example 4
Source Project: carbon-identity-framework   Source File: PAPPolicyStore.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This returns given policy as Registry resource
 *
 * @param policyId   policy id
 * @param collection
 * @return policy as Registry resource
 * @throws EntitlementException throws, if fails
 */
public Resource getPolicy(String policyId, String collection) throws EntitlementException {
    String path = null;

    if (log.isDebugEnabled()) {
        log.debug("Retrieving entitlement policy");
    }

    try {
        path = collection + policyId;

        if (!registry.resourceExists(path)) {
            if (log.isDebugEnabled()) {
                log.debug("Trying to access an entitlement policy which does not exist");
            }
            return null;
        }
        return registry.get(path);
    } catch (RegistryException e) {
        log.error("Error while retrieving entitlement policy " + policyId + " PAP policy store", e);
        throw new EntitlementException("Error while retrieving entitlement policy " + policyId
                                       + " PAP policy store");
    }
}
 
Example 5
Source Project: carbon-apimgt   Source File: SequenceUtilsTestCase.java    License: Apache License 2.0 6 votes vote down vote up
public void testGetRestToSoapConvertedSequence() throws Exception {
    String provider = "admin";
    String apiName = "test-api";
    String version = "1.0.0";
    String seqType = "in";
    String resourceName = "test_get.xml";
    Resource resource = Mockito.mock(Resource.class);
    ResourceImpl resourceImpl = Mockito.mock(ResourceImpl.class);
    Collection collection = Mockito.mock(Collection.class);
    String[] paths = new String[0];
    byte[] content = new byte[1];
    PowerMockito.when(MultitenantUtils.getTenantDomain(Mockito.anyString())).thenReturn("carbon.super");
    PowerMockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(((Collection)userRegistry.get(Mockito.anyString()))).thenReturn(collection);
    Mockito.when(collection.getChildren()).thenReturn(paths);
    Mockito.when(userRegistry.get(Mockito.anyString())).thenReturn(resource);
    Mockito.when(resource.getContent()).thenReturn(content);
    Mockito.when(resourceImpl.getName()).thenReturn(resourceName);
    Mockito.when(tenantManager.getTenantId(Mockito.anyString())).thenReturn(-1);

    try {
        SequenceUtils.getRestToSoapConvertedSequence(apiName, version, provider, seqType);
    } catch (APIManagementException e) {
        Assert.fail("Failed to get the sequences from the registry");
    }
}
 
Example 6
@Override
public synchronized void addTask(TaskInfo taskInfo) throws TaskException {
    String tasksPath = this.getMyTasksPath();
    String currentTaskPath = tasksPath + "/" + taskInfo.getName();
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
                MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        getTaskMarshaller().marshal(taskInfo, out);
        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
        Resource resource = getRegistry().newResource();
        resource.setContentStream(in);
        getRegistry().put(currentTaskPath, resource);
    } catch (Exception e) {
        throw new TaskException("Error in adding task '" + taskInfo.getName()
                + "' to the repository: " + e.getMessage(), Code.CONFIG_ERROR, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 7
Source Project: carbon-apimgt   Source File: AbstractAPIManager.java    License: Apache License 2.0 6 votes vote down vote up
public Set<String> getAPIVersions(String providerName, String apiName)
        throws APIManagementException {

    Set<String> versionSet = new HashSet<String>();
    String apiPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR +
            providerName + RegistryConstants.PATH_SEPARATOR + apiName;
    try {
        Resource resource = registry.get(apiPath);
        if (resource instanceof Collection) {
            Collection collection = (Collection) resource;
            String[] versionPaths = collection.getChildren();
            if (versionPaths == null || versionPaths.length == 0) {
                return versionSet;
            }
            for (String path : versionPaths) {
                versionSet.add(path.substring(apiPath.length() + 1));
            }
        } else {
            throw new APIManagementException("API version must be a collection " + apiName);
        }
    } catch (RegistryException e) {
        String msg = "Failed to get versions for API: " + apiName;
        throw new APIManagementException(msg, e);
    }
    return versionSet;
}
 
Example 8
Source Project: carbon-apimgt   Source File: AbstractAPIManager.java    License: Apache License 2.0 6 votes vote down vote up
public API getAPI(String apiPath) throws APIManagementException {
    try {
        GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry,
                APIConstants.API_KEY);
        Resource apiResource = registry.get(apiPath);
        String artifactId = apiResource.getUUID();
        if (artifactId == null) {
            throw new APIManagementException("artifact id is null for : " + apiPath);
        }
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId);
        return getApi(apiArtifact);

    } catch (RegistryException e) {
        String msg = "Failed to get API from : " + apiPath;
        throw new APIManagementException(msg, e);
    }
}
 
Example 9
Source Project: carbon-identity   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * gets no of verified user challenges
 *
 * @param userDTO bean class that contains user and tenant Information
 * @return no of verified challenges
 * @throws IdentityException if fails
 */
public static int getVerifiedChallenges(UserDTO userDTO) throws IdentityException {

    int noOfChallenges = 0;

    try {
        UserRegistry registry = IdentityMgtServiceComponent.getRegistryService().
                getConfigSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
        String identityKeyMgtPath = IdentityMgtConstants.IDENTITY_MANAGEMENT_CHALLENGES +
                RegistryConstants.PATH_SEPARATOR + userDTO.getUserId() +
                RegistryConstants.PATH_SEPARATOR + userDTO.getUserId();

        Resource resource;
        if (registry.resourceExists(identityKeyMgtPath)) {
            resource = registry.get(identityKeyMgtPath);
            String property = resource.getProperty(IdentityMgtConstants.VERIFIED_CHALLENGES);
            if (property != null) {
                return Integer.parseInt(property);
            }
        }
    } catch (RegistryException e) {
        log.error("Error while processing userKey", e);
    }

    return noOfChallenges;
}
 
Example 10
Source Project: carbon-apimgt   Source File: AbstractAPIManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delete existing API specific mediation policy
 * @param identifier API or Product identifier
 * @param apiResourcePath   path to the API registry resource
 * @param mediationPolicyId mediation policy identifier
 */
@Override
public Boolean deleteApiSpecificMediationPolicy(Identifier identifier, String apiResourcePath,
        String mediationPolicyId) throws APIManagementException {
    Resource mediationResource =
            this.getApiSpecificMediationResourceFromUuid(identifier, mediationPolicyId, apiResourcePath);
    if (mediationResource != null) {
        //If resource exists
        String mediationPath = mediationResource.getPath();
        try {
            if (registry.resourceExists(mediationPath)) {
                registry.delete(mediationPath);
                if (!registry.resourceExists(mediationPath)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Mediation policy deleted successfully");
                    }
                    return true;
                }
            }
        } catch (RegistryException e) {
            String msg = "Failed to delete specific mediation policy ";
            throw new APIManagementException(msg, e);
        }
    }
    return false;
}
 
Example 11
@Test
public void testFailureToLoadTenantWFConfigWhenWFExecutorPropertyNameNotFound() throws Exception {
    //Workflow executor class is a singleton class with private constructor, so that IllegalAccessException will
    // be thrown while instantiation
    String invalidWFExecutor =
            "<WorkFlowExtensions>\n" +
                    "     <ApplicationCreation executor=\"org.wso2.carbon.apimgt.impl.workflow" +
                    ".ApplicationCreationWSWorkflowExecutor\">\n" +
                    "         <Property/>\n" +
                    "    </ApplicationCreation>\n" +
                    "</WorkFlowExtensions>\n";
    InputStream invalidInputStream = new ByteArrayInputStream(invalidWFExecutor.getBytes("UTF-8"));
    TenantWorkflowConfigHolder tenantWorkflowConfigHolder = new TenantWorkflowConfigHolder(tenantDomain, tenantID);
    Resource defaultWFConfigResource = new ResourceImpl();
    defaultWFConfigResource.setContentStream(invalidInputStream);
    Mockito.when(registry.get(APIConstants.WORKFLOW_EXECUTOR_LOCATION)).thenReturn(defaultWFConfigResource);
    try {
        tenantWorkflowConfigHolder.load();
        Assert.fail("Expected WorkflowException has not been thrown when workflow executor property 'name' " +
                "attribute not found");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Unable to load workflow executor class");
    }
}
 
Example 12
Source Project: carbon-apimgt   Source File: GatewayUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delete the given registry property from the given tenant registry path
 *
 * @param propertyName property name
 * @param path         resource path
 * @param tenantDomain
 * @throws AxisFault
 */
public static void deleteRegistryProperty(String propertyName, String path, String tenantDomain)
        throws AxisFault {

    try {
        UserRegistry registry = getRegistry(tenantDomain);
        PrivilegedCarbonContext.startTenantFlow();
        if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        } else {
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        }
        Resource resource = registry.get(path);
        if (resource != null && resource.getProperty(propertyName) != null) {
            resource.removeProperty(propertyName);
            registry.put(resource.getPath(), resource);
            resource.discard();
        }
    } catch (RegistryException | APIManagementException e) {
        String msg = "Failed to delete secure endpoint password alias " + e.getMessage();
        throw new AxisFault(msg, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 13
Source Project: carbon-apimgt   Source File: CustomAPIIndexerTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method checks the indexer's behaviour for new APIs which does not have the relevant properties.
 *
 * @throws RegistryException Registry Exception.
 * @throws APIManagementException API Management Exception.
 */
@Test
public void testIndexDocumentForNewAPI() throws APIManagementException, RegistryException {
    Resource resource = new ResourceImpl();
    PowerMockito.mockStatic(APIUtil.class);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(artifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(genericArtifact);
    Mockito.when(genericArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY)).thenReturn("public");
    PowerMockito.when(APIUtil.getAPI(genericArtifact, userRegistry))
            .thenReturn(Mockito.mock(API.class));
    resource.setProperty(APIConstants.ACCESS_CONTROL, APIConstants.NO_ACCESS_CONTROL);
    resource.setProperty(APIConstants.PUBLISHER_ROLES, APIConstants.NULL_USER_ROLE_LIST);
    resource.setProperty(APIConstants.STORE_VIEW_ROLES, APIConstants.NULL_USER_ROLE_LIST);
    Mockito.doReturn(resource).when(userRegistry).get(Mockito.anyString());
    indexer.getIndexedDocument(file2Index);
    Assert.assertNull(APIConstants.CUSTOM_API_INDEXER_PROPERTY + " property was set for the API which does not "
            + "require migration", resource.getProperty(APIConstants.CUSTOM_API_INDEXER_PROPERTY));
}
 
Example 14
Source Project: carbon-apimgt   Source File: SequenceUtilsTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateRestToSoapConvertedSequences() throws Exception {
    String provider = "admin";
    String apiName = "test-api";
    String version = "1.0.0";
    String seqType = "in";
    String sequence = "{\"test\":{\"method\":\"post\",\"content\":\"<header></header>\"}}";
    Resource resource = Mockito.mock(Resource.class);
    PowerMockito.when(MultitenantUtils.getTenantDomain(Mockito.anyString())).thenReturn("carbon.super");
    PowerMockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(userRegistry.resourceExists(Mockito.anyString())).thenReturn(true);
    Mockito.when(userRegistry.get(Mockito.anyString())).thenReturn(resource);
    Mockito.when(tenantManager.getTenantId(Mockito.anyString())).thenReturn(-1);

    try {
        SequenceUtils.updateRestToSoapConvertedSequences(apiName, version, provider, seqType, sequence);
    } catch (APIManagementException e) {
        Assert.fail("Failed to update the sequence in the registry");
    }
}
 
Example 15
@Test
public void testFailureToLoadTenantWFConfigWhenWFExecutorPropertySetterNotDefined() throws Exception {
    //Workflow executor class does not have setter method for 'testParam'
    String invalidWFExecutor =
            "<WorkFlowExtensions>\n" +
                    "     <ApplicationCreation executor=\"org.wso2.carbon.apimgt.impl.workflow" +
                    ".ApplicationCreationWSWorkflowExecutor\">\n" +
                    "         <Property name=\"testParam\">test</Property>\n" +
                    "    </ApplicationCreation>\n" +
                    "</WorkFlowExtensions>\n";
    InputStream invalidInputStream = new ByteArrayInputStream(invalidWFExecutor.getBytes("UTF-8"));
    TenantWorkflowConfigHolder tenantWorkflowConfigHolder = new TenantWorkflowConfigHolder(tenantDomain, tenantID);
    Resource defaultWFConfigResource = new ResourceImpl();
    defaultWFConfigResource.setContentStream(invalidInputStream);
    Mockito.when(registry.get(APIConstants.WORKFLOW_EXECUTOR_LOCATION)).thenReturn(defaultWFConfigResource);
    try {
        tenantWorkflowConfigHolder.load();
        Assert.fail("Expected WorkflowException has not been thrown when workflow executor property setter method" +
                " cannot be found");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Unable to load workflow executor class");
        Assert.assertEquals(e.getCause().getMessage(), "Error invoking setter method named : setTestParam() " +
                "that takes a single String, int, long, float, double or boolean parameter");
    }
}
 
Example 16
/**
 * This helps to find resources in a recursive manner.
 *
 * @param parentResource      parent resource Name.
 * @param serviceProviderList child resource list.
 * @throws RegistryException
 */
private void getChildResources(String parentResource, List<SAMLSSOServiceProviderDO>
        serviceProviderList) throws RegistryException {

    if (registry.resourceExists(parentResource)) {
        Resource resource = registry.get(parentResource);
        if (resource instanceof Collection) {
            Collection collection = (Collection) resource;
            String[] resources = collection.getChildren();
            for (String res : resources) {
                getChildResources(res, serviceProviderList);
            }
        } else {
            serviceProviderList.add(resourceToObject(resource));
        }
    }
}
 
Example 17
Source Project: product-es   Source File: RegistryConfiguratorTestCase.java    License: Apache License 2.0 6 votes vote down vote up
public void updateMimetypes() throws Exception {

        final String MIME_TYPE_PATH = "/_system/config/repository/components/org.wso2.carbon.governance" +
                "/media-types/index";
        WSRegistryServiceClient wsRegistry;
        RegistryProviderUtil registryProviderUtil = new RegistryProviderUtil();
        wsRegistry = registryProviderUtil.getWSRegistry(automationContext);
        Resource resource = wsRegistry.get(MIME_TYPE_PATH);
        resource.addProperty("properties", "text/properties");
        resource.addProperty("cfg", "text/config");
        resource.addProperty("rb", "text/ruby");
        resource.addProperty("drl", "xml/drool");
        resource.addProperty("xq", "xml/xquery");
        resource.addProperty("eva", "xml/evan");
        wsRegistry.put(MIME_TYPE_PATH, resource);

    }
 
Example 18
Source Project: carbon-identity   Source File: OAuthConsumerDAO.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param ppid
 * @return
 * @throws IdentityException
 */
public String getOAuthConsumerSecret(String consumerKey) throws IdentityException {
    String path = null;
    Resource resource = null;

    if (log.isDebugEnabled()) {
        log.debug("Retreiving user for OAuth consumer key  " + consumerKey);
    }

    try {
        path = RegistryConstants.PROFILES_PATH + consumerKey;
        if (registry.resourceExists(path)) {
            resource = registry.get(path);
            return resource.getProperty(IdentityRegistryResources.OAUTH_CONSUMER_PATH);
        } else {
            return null;
        }
    } catch (RegistryException e) {
        log.error("Error while retreiving user for OAuth consumer key  " + consumerKey, e);
        throw IdentityException.error("Error while retreiving user for OAuth consumer key  "
                + consumerKey, e);
    }
}
 
Example 19
Source Project: carbon-identity-framework   Source File: OpenIDAdminDAO.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve OpenID admin for a tenant.
 *
 * @return open id admin of the tenant
 * @throws IdentityException if error occurs while retrieving the OpenID admin
 */
public OpenIDAdminDO getOpenIDAdminDO() throws IdentityException {
    OpenIDAdminDO opdo = null;
    Resource resource = null;

    if (log.isDebugEnabled()) {
        log.debug("Retrieving OpenID admin for tenant");
    }
    try {
        if (registry.resourceExists(IdentityRegistryResources.OPEN_ID_ADMIN_SETTINGS)) {
            resource = registry.get(IdentityRegistryResources.OPEN_ID_ADMIN_SETTINGS);
            return resourceToObject(resource);
        }
    } catch (RegistryException e) {
        log.error("Error while retreiving openid admin", e);
        throw IdentityException.error("Error while retreiving openid admin", e);
    }
    return opdo;
}
 
Example 20
Source Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddResourceFile() throws APIManagementException, RegistryException, IOException {
    Identifier identifier = Mockito.mock(Identifier.class);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    Resource resource = new ResourceImpl();
    Mockito.when(registry.newResource()).thenReturn(resource);
    String resourcePath = "/test";
    String contentType = "sampleType";
    ResourceFile resourceFile = new ResourceFile(null, contentType);
    try {
        abstractAPIManager.addResourceFile(identifier, resourcePath, resourceFile);
        Assert.fail("Registry exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while adding the resource to the registry"));
    }
    InputStream in = IOUtils.toInputStream("sample content", "UTF-8");
    resourceFile = new ResourceFile(in, contentType);
    String returnedPath = abstractAPIManager.addResourceFile(identifier, resourcePath, resourceFile);
    Assert.assertTrue(returnedPath.contains(resourcePath) && returnedPath.contains("/t/"));
    abstractAPIManager.tenantDomain = SAMPLE_TENANT_DOMAIN;
    returnedPath = abstractAPIManager.addResourceFile(identifier, resourcePath, resourceFile);
    Assert.assertTrue(returnedPath.contains(resourcePath) && !returnedPath.contains("/t/"));

}
 
Example 21
Source Project: carbon-commons   Source File: RemoteTaskUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Object[] lookupRemoteTask(String remoteTaskId) throws TaskException {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
                MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        Registry registry = RegistryBasedTaskRepository.getRegistry();
        Resource res = registry.get(resourcePathFromRemoteTaskId(remoteTaskId));
        Object[] result = new Object[3];
        result[0] = Integer.parseInt(res.getProperty(REMOTE_TASK_TENANT_ID).toString());
        result[1] = res.getProperty(REMOTE_TASK_TASK_TYPE);
        result[2] = res.getProperty(REMOTE_TASK_TASK_NAME);
        return result;
    } catch (Exception e) {
        throw new TaskException(e.getMessage(), Code.UNKNOWN, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 22
@Before
public void init() throws RegistryException, UserStoreException {
    System.setProperty(CARBON_HOME, "");
    tenantDomain = "carbon.super";
    applicationId = "1";
    tenantID = tenantID;
    messageContext = TestUtils.getMessageContextWithAuthContext("api", "v1");
    registryServiceHolder = Mockito.mock(RegistryServiceHolder.class);
    registryService = Mockito.mock(RegistryService.class);
    registry = Mockito.mock(UserRegistry.class);
    realmService = Mockito.mock(RealmService.class);
    tenantManager = Mockito.mock(TenantManager.class);
    carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    throttleDataHolder = Mockito.mock(ThrottleDataHolder.class);
    throttlingPolicyResource = Mockito.mock(Resource.class);
    throttleContext = Mockito.mock(ThrottleContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(RegistryServiceHolder.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.when(RegistryServiceHolder.getInstance()).thenReturn(registryServiceHolder);
    PowerMockito.when(registryServiceHolder.getRegistryService()).thenReturn(registryService);
    PowerMockito.when(carbonContext.getOSGiService(RealmService.class, null)).thenReturn(realmService);
    PowerMockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
}
 
Example 23
@Test
public void testGetServiceProvider() throws Exception {
    mockStatic(IdentityTenantUtil.class);
    RealmService mockRealmService = mock(RealmService.class);
    TenantManager mockTenantManager = mock(TenantManager.class);
    when(IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService);
    when(mockRealmService.getTenantManager()).thenReturn(mockTenantManager);
    when(mockTenantManager.getDomain(anyInt())).thenReturn("test.com");

    Properties dummyResourceProperties = new Properties();
    dummyResourceProperties.putAll(dummyBasicProperties);
    Resource dummyResource = new ResourceImpl();
    dummyResource.setProperties(dummyResourceProperties);

    String path = getPath(dummyResource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER));
    when(mockRegistry.resourceExists(path)).thenReturn(true);
    when(mockRegistry.get(path)).thenReturn(dummyResource);

    SAMLSSOServiceProviderDO serviceProviderDO = objUnderTest.getServiceProvider(dummyResource.getProperty
            (IdentityRegistryResources.PROP_SAML_SSO_ISSUER));
    assertEquals(serviceProviderDO.getTenantDomain(), "test.com", "Retrieved resource's tenant domain mismatch");
}
 
Example 24
Source Project: carbon-identity-framework   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * gets no of verified user challenges
 *
 * @param userDTO bean class that contains user and tenant Information
 * @return no of verified challenges
 * @throws IdentityException if fails
 */
public static int getVerifiedChallenges(UserDTO userDTO) throws IdentityException {

    int noOfChallenges = 0;

    try {
        UserRegistry registry = IdentityMgtServiceComponent.getRegistryService().
                getConfigSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
        String identityKeyMgtPath = IdentityMgtConstants.IDENTITY_MANAGEMENT_CHALLENGES +
                RegistryConstants.PATH_SEPARATOR + userDTO.getUserId() +
                RegistryConstants.PATH_SEPARATOR + userDTO.getUserId();

        Resource resource;
        if (registry.resourceExists(identityKeyMgtPath)) {
            resource = registry.get(identityKeyMgtPath);
            String property = resource.getProperty(IdentityMgtConstants.VERIFIED_CHALLENGES);
            if (property != null) {
                return Integer.parseInt(property);
            }
        }
    } catch (RegistryException e) {
        log.error("Error while processing userKey", e);
    }

    return noOfChallenges;
}
 
Example 25
Source Project: carbon-commons   Source File: CloudServicesUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean isCloudServiceActive(String cloudServiceName,
                                           int tenantId, UserRegistry govRegistry)
                                                                                  throws Exception {
    // The cloud manager is always active
    if (StratosConstants.CLOUD_MANAGER_SERVICE.equals(cloudServiceName)) {
        return true;
    }

    String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
                                  RegistryConstants.PATH_SEPARATOR + tenantId +
                                  RegistryConstants.PATH_SEPARATOR + cloudServiceName;
    Resource cloudServiceInfoResource;
    if (govRegistry.resourceExists(cloudServiceInfoPath)) {
        cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
        String isActiveStr =
                             cloudServiceInfoResource.getProperty(
                                                     StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY);
        return "true".equals(isActiveStr);
    }
    return false;
}
 
Example 26
@Test
public void testFailureToLoadTenantWFConfigWhenXMLStreamExceptionOccurredWhileParsingConfig() throws Exception {
    TenantWorkflowConfigHolder tenantWorkflowConfigHolder = new TenantWorkflowConfigHolder(tenantDomain, tenantID);
    File defaultWFConfigFile = new File(Thread.currentThread().getContextClassLoader().
            getResource("workflow-configs/workflow-extensions.xml").getFile());
    InputStream defaultWFConfigContent = new FileInputStream(defaultWFConfigFile);
    Resource defaultWFConfigResource = Mockito.mock(Resource.class);
    Mockito.when(registry.get(APIConstants.WORKFLOW_EXECUTOR_LOCATION)).thenReturn(defaultWFConfigResource);
    Mockito.when(defaultWFConfigResource.getContentStream()).thenReturn(defaultWFConfigContent);
    //XMLStreamException will be thrown while building workflow config
    PowerMockito.whenNew(StAXOMBuilder.class).withArguments(defaultWFConfigContent).thenThrow(new
            XMLStreamException(""));
    try {
        tenantWorkflowConfigHolder.load();
        Assert.fail("Expected WorkflowException has not been thrown when XMLStreamException occurred while " +
                "processing workflow config");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error building xml from Resource at " + APIConstants
                .WORKFLOW_EXECUTOR_LOCATION);
    }
}
 
Example 27
Source Project: istio-apim   Source File: IstioExecutor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create HTTPAPISpecBinding for the API
 *
 * @param apiName  Name of the API
 * @param endPoint Endpoint of the API
 */
public void createHttpAPISpecBinding(String apiName, String endPoint) {

    NonNamespaceOperation<HTTPAPISpecBinding, HTTPAPISpecBindingList, DoneableHTTPAPISpecBinding,
            io.fabric8.kubernetes.client.dsl.Resource<HTTPAPISpecBinding, DoneableHTTPAPISpecBinding>> bindingClient
            = client.customResource(httpAPISpecBindingCRD, HTTPAPISpecBinding.class, HTTPAPISpecBindingList.class,
            DoneableHTTPAPISpecBinding.class).inNamespace(appNamespace);

    String bindingName = Strings.toLowerCase(apiName) + "-binding";
    String apiSpecName = Strings.toLowerCase(apiName) + "-apispec";

    HTTPAPISpecBinding httpapiSpecBinding = new HTTPAPISpecBinding();
    ObjectMeta metadata = new ObjectMeta();
    metadata.setName(bindingName);
    httpapiSpecBinding.setMetadata(metadata);
    HTTPAPISpecBindingSpec httpapiSpecBindingSpec = new HTTPAPISpecBindingSpec();

    APISpec apiSpec = new APISpec();
    apiSpec.setName(apiSpecName);
    apiSpec.setNamespace(appNamespace);
    ArrayList<APISpec> apiSpecsList = new ArrayList<>();
    apiSpecsList.add(apiSpec);
    httpapiSpecBindingSpec.setApi_specs(apiSpecsList);

    Service service = new Service();
    service.setName(endPoint);
    service.setNamespace(appNamespace);
    ArrayList<Service> servicesList = new ArrayList<>();
    servicesList.add(service);
    httpapiSpecBindingSpec.setServices(servicesList);
    httpapiSpecBinding.setSpec(httpapiSpecBindingSpec);

    bindingClient.createOrReplace(httpapiSpecBinding);
    log.info("[HTTPAPISpecBinding] " + bindingName + " Created in the [Namespace] " + appNamespace + " for the"
            + " [API] " + apiName);
}
 
Example 28
Source Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSubscriberAPIs() throws APIManagementException, RegistryException {
    Subscriber subscriber = new Subscriber("sub1");
    Application application = new Application("app1", subscriber);
    application.setId(1);
    SubscribedAPI subscribedAPI1 = new SubscribedAPI(subscriber,
            getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION));
    subscribedAPI1.setUUID(SAMPLE_RESOURCE_ID);
    SubscribedAPI subscribedAPI2 = new SubscribedAPI(subscriber, getAPIIdentifier("sample1", API_PROVIDER, "2.0.0"));
    Set<SubscribedAPI> subscribedAPIs = new HashSet<SubscribedAPI>();
    subscribedAPI1.setApplication(application);
    subscribedAPI2.setApplication(application);
    subscribedAPIs.add(subscribedAPI1);
    subscribedAPIs.add(subscribedAPI2);
    Mockito.when(apiMgtDAO.getSubscribedAPIs((Subscriber) Mockito.any(), Mockito.anyString()))
            .thenReturn(subscribedAPIs);
    UserRegistry registry = Mockito.mock(UserRegistry.class);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(genericArtifactManager, null, registry,
            null, apiMgtDAO);
    Resource resource = new ResourceImpl();
    resource.setUUID(SAMPLE_RESOURCE_ID);
    Mockito.when(registry.get(Mockito.anyString())).thenThrow(RegistryException.class).thenReturn(resource);
    try {
        abstractAPIManager.getSubscriberAPIs(subscriber);
        Assert.fail("Registry exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to get APIs for subscriber: "));
    }
    GenericArtifact artifact = getGenericArtifact(SAMPLE_API_NAME,API_PROVIDER,SAMPLE_API_VERSION,"sample_qname");
    Mockito.when(genericArtifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(artifact);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getAPI((GovernanceArtifact)Mockito.any(),(Registry)Mockito.any())).thenReturn(new API
            (getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION)));
    abstractAPIManager.tenantDomain = SAMPLE_TENANT_DOMAIN_1;
    Assert.assertEquals(abstractAPIManager.getSubscriberAPIs(subscriber).size(),1);

}
 
Example 29
Source Project: product-es   Source File: ProviderMigrationClient.java    License: 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 30
Source Project: carbon-identity   Source File: PAPPolicyStoreReader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param policyId
 * @param finder
 * @return
 * @throws EntitlementException
 */
public synchronized AbstractPolicy readPolicy(String policyId, PolicyFinder finder)
        throws EntitlementException {
    Resource resource = store.getPolicy(policyId, PDPConstants.ENTITLEMENT_POLICY_PAP);
    if (resource != null) {
        try {
            String policy = new String((byte[]) resource.getContent(), Charset.forName("UTF-8"));
            return PAPPolicyReader.getInstance(null).getPolicy(policy);
        } catch (RegistryException e) {
            log.error("Error while parsing entitlement policy", e);
            throw new EntitlementException("Error while loading entitlement policy");
        }
    }
    return null;
}