org.wso2.carbon.registry.core.ResourceImpl Java Examples

The following examples show how to use org.wso2.carbon.registry.core.ResourceImpl. 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: TenantWorkflowConfigHolderTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureToLoadTenantWFConfigWhenWFExecutorClassCannotBeInstantiated() throws Exception {
    //Workflow executor is an abstract class so that InstantiationException will be thrown
    String invalidWFExecutor =
                    "<WorkFlowExtensions>\n" +
                    "    <ApplicationCreation executor=\"org.wso2.carbon.apimgt.impl.workflow" +
                    ".WorkflowExecutor\"/></WorkFlowExtensions>";
    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 class cannot be " +
                "instantiate");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Unable to instantiate class");
    }
}
 
Example #2
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAllWsdls() throws RegistryException, APIManagementException {
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    Collection parentCollection = new CollectionImpl();
    String wsdlResourcepath = APIConstants.API_WSDL_RESOURCE;
    String resourcePath = wsdlResourcepath + "/wsdl1";
    parentCollection.setChildren(new String[] { resourcePath });
    Mockito.when(registry.get(wsdlResourcepath)).thenReturn(parentCollection);
    Resource resource = new ResourceImpl();
    Mockito.when(registry.get(resourcePath)).thenThrow(RegistryException.class).thenReturn(resource);
    Mockito.when(registry.resourceExists(wsdlResourcepath)).thenReturn(true);
    try {
        abstractAPIManager.getAllWsdls();
        Assert.fail("Exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to get wsdl list"));
    }
    resource.setUUID(SAMPLE_RESOURCE_ID);

    List<Wsdl> wsdls = abstractAPIManager.getAllWsdls();
    Assert.assertNotNull(wsdls);
    Assert.assertEquals(wsdls.size(), 1);

}
 
Example #3
Source File: SAMLSSOServiceProviderDAOTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "ResourceToObjectData")
public void testAddServiceProvider(Object paramMapObj) throws Exception {
    Properties properties = new Properties();
    properties.putAll((Map<?, ?>) paramMapObj);
    Resource dummyResource = new ResourceImpl();
    dummyResource.setProperties(properties);
    SAMLSSOServiceProviderDO serviceProviderDO = objUnderTest.resourceToObject(dummyResource);
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    String expectedPath = getPath(dummyResource
            .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER));
    if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) {
        expectedPath = getPath(dummyResource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER)
                + IdentityRegistryResources.QUALIFIER_ID + dummyResource.getProperty(IdentityRegistryResources.
                PROP_SAML_SSO_ISSUER_QUALIFIER));
    }
    objUnderTest.addServiceProvider(serviceProviderDO);
    verify(mockRegistry).put(captor.capture(), any(Resource.class));
    assertEquals(captor.getValue(), expectedPath, "Resource is not added at correct path");
}
 
Example #4
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testUploadWsdl() throws RegistryException, APIManagementException {
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    Resource resource = new ResourceImpl();
    String resourcePath = "/test/wsdl";
    String wsdlContent = "sample wsdl";
    Resource resourceMock = Mockito.mock(Resource.class);
    resourceMock.setContent(wsdlContent);
    resourceMock.setMediaType(String.valueOf(ContentType.APPLICATION_XML));
    Mockito.when(registry.newResource()).thenReturn(resource);
    Mockito.doThrow(RegistryException.class).doReturn(resourcePath).when(registry).put(resourcePath, resource);
    try {
        abstractAPIManager.uploadWsdl(resourcePath, wsdlContent);
        Assert.fail("Exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while uploading wsdl to from the registry"));
    }
    abstractAPIManager.uploadWsdl(resourcePath, wsdlContent);
    Mockito.verify(registry, Mockito.atLeastOnce()).put(resourcePath, resource);
}
 
Example #5
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with 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 #6
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with 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 #7
Source File: TenantWorkflowConfigHolderTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadingDefaultTenantWorkflowConfig() throws FileNotFoundException, XMLStreamException,
        RegistryException {
    TenantWorkflowConfigHolder tenantWorkflowConfigHolder = new TenantWorkflowConfigHolder(tenantDomain, tenantID);
    File defaultWFConfigFile = new File(Thread.currentThread().getContextClassLoader().
            getResource("workflow-configs/default-workflow-extensions.xml").getFile());
    InputStream defaultWFConfigContent = new FileInputStream(defaultWFConfigFile);
    Resource defaultWFConfigResource = new ResourceImpl();
    defaultWFConfigResource.setContentStream(defaultWFConfigContent);
    Mockito.when(registry.get(APIConstants.WORKFLOW_EXECUTOR_LOCATION)).thenReturn(defaultWFConfigResource);
    try {
        tenantWorkflowConfigHolder.load();
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor("AM_APPLICATION_CREATION"));
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor
                ("AM_APPLICATION_REGISTRATION_PRODUCTION"));
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor
                ("AM_APPLICATION_REGISTRATION_SANDBOX"));
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor("AM_USER_SIGNUP"));
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor("AM_SUBSCRIPTION_CREATION"));
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor("AM_SUBSCRIPTION_DELETION"));
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor("AM_API_STATE"));

    } catch (WorkflowException e) {
        Assert.fail("Unexpected WorkflowException occurred while loading default tenant workflow configuration");
    }
}
 
Example #8
Source File: TenantWorkflowConfigHolderTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadingExtendedTenantWorkflowConfig() throws FileNotFoundException, XMLStreamException,
        RegistryException {
    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 = new ResourceImpl();
    defaultWFConfigResource.setContentStream(defaultWFConfigContent);
    Mockito.when(registry.get(APIConstants.WORKFLOW_EXECUTOR_LOCATION)).thenReturn(defaultWFConfigResource);
    try {
        tenantWorkflowConfigHolder.load();
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor("AM_APPLICATION_CREATION"));
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor
                ("AM_APPLICATION_REGISTRATION_PRODUCTION"));
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor
                ("AM_APPLICATION_REGISTRATION_SANDBOX"));
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor("AM_USER_SIGNUP"));
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor("AM_SUBSCRIPTION_CREATION"));
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor("AM_SUBSCRIPTION_DELETION"));
        Assert.assertNotNull(tenantWorkflowConfigHolder.getWorkflowExecutor("AM_API_STATE"));
    } catch (WorkflowException e) {
        Assert.fail("Unexpected WorkflowException occurred while loading extended tenant workflow configuration");
    }
}
 
Example #9
Source File: TenantWorkflowConfigHolderTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureToLoadTenantWFConfigWhenWFExecutorClassNotFound() throws Exception {
    //Workflow executor is an non existing class so that ClassNotFoundException will be thrown
    String invalidWFExecutor =
            "<WorkFlowExtensions>\n" +
                    "    <ApplicationCreation executor=\"org.wso2.carbon.apimgt.impl.workflow" +
                    ".TestExecutor\"/></WorkFlowExtensions>";
    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 class not found");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Unable to find class");
    }
}
 
Example #10
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetWsdl() throws APIManagementException, RegistryException, IOException {
    Resource resourceMock = Mockito.mock(Resource.class);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    String wsdlName =
            identifier.getProviderName() + "--" + identifier.getApiName() + identifier.getVersion() + ".wsdl";
    String wsdlResourcePath = APIConstants.API_WSDL_RESOURCE_LOCATION + wsdlName;
    Resource resource = new ResourceImpl(wsdlResourcePath, new ResourceDO());
    Mockito.when(registry.get(wsdlResourcePath)).thenThrow(RegistryException.class).thenReturn(resource);
    Mockito.when(registry.resourceExists(wsdlResourcePath)).thenReturn(true);
    try {
        abstractAPIManager.getWSDL(identifier);
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while getting wsdl file from the registry"));
    }
    String wsdlContent = "sample wsdl";
    resource.setContent(wsdlContent);
    InputStream inputStream = new ArrayInputStream();
    Mockito.when(resourceMock.getContentStream()).thenReturn(inputStream);
    Assert.assertEquals(wsdlContent, IOUtils.toString(abstractAPIManager.getWSDL(identifier).getContent()));
    PowerMockito.mockStatic(IOUtils.class);
}
 
Example #11
Source File: TenantWorkflowConfigHolderTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureToLoadTenantWFConfigWhenWFExecutorClassCannotAccessible() 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" +
                    ".InvalidWorkFlowExecutor1\"/></WorkFlowExtensions>";
    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 class cannot be " +
                "accessible");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Illegal attempt to invoke class methods");
    }
}
 
Example #12
Source File: TenantWorkflowConfigHolderTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: TenantWorkflowConfigHolderTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@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 #14
Source File: TenantWorkflowConfigHolderTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureToLoadTenantWFConfigWhenWFExecutorPropertySetterInInvalid() throws Exception {
    //Workflow executor class setter method is invalid since it has multiple parameter types
    String invalidWFExecutor =
            "<WorkFlowExtensions>\n" +
                    "     <ApplicationCreation executor=\"org.wso2.carbon.apimgt.impl.workflow" +
                    ".InvalidWorkFlowExecutor2\">\n" +
                    "         <Property name=\"username\">admin</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" +
                " is invalid");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Unable to load workflow executor class");
        Assert.assertEquals(e.getCause().getMessage(), "Error invoking setter method named : setUsername() " +
                "that takes a single String, int, long, float, double or boolean parameter");
    }
}
 
Example #15
Source File: CustomAPIIndexHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method tests whether the CustomAPIIndexer works correctly under different circumstances without throwing
 * Exception.
 *
 * @throws RegistryException Registry Exception.
 */
@Test
public void testPut() throws RegistryException {
    // Resource without property.
    Resource resource = new ResourceImpl();
    RequestContext requestContext = Mockito.mock(RequestContext.class);
    Mockito.doReturn(Mockito.mock(Registry.class)).when(requestContext).getRegistry();
    ResourcePath resourcePath = Mockito.mock(ResourcePath.class);
    Mockito.doReturn(resource).when(requestContext).getResource();
    Mockito.doReturn(resourcePath).when(requestContext).getResourcePath();
    CustomAPIIndexHandler customAPIIndexHandler = new CustomAPIIndexHandler();
    customAPIIndexHandler.put(requestContext);

    // Resource with property.
    resource.setProperty(APIConstants.CUSTOM_API_INDEXER_PROPERTY, "true");
    Mockito.doReturn(resource).when(requestContext).getResource();
    customAPIIndexHandler.put(requestContext);
}
 
Example #16
Source File: SequenceUtilsTestCase.java    From carbon-apimgt with 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 #17
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 #18
Source File: SAMLSSOServiceProviderDAOTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@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 #19
Source File: CustomAPIIndexerTest.java    From carbon-apimgt with 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 #20
Source File: CustomAPIIndexerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method checks the indexer's behaviour for APIs which does not have the relevant custom properties.
 *
 * @throws RegistryException Registry Exception.
 * @throws APIManagementException API Management Exception.
 */
@Test
public void testIndexingCustomProperties() throws RegistryException, APIManagementException {
    Resource resource = new ResourceImpl();
    PowerMockito.mockStatic(APIUtil.class);
    Mockito.doReturn(resource).when(userRegistry).get(Mockito.anyString());
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    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.API_RELATED_CUSTOM_PROPERTIES_PREFIX + APIConstants.
            CUSTOM_API_INDEXER_PROPERTY, APIConstants.CUSTOM_API_INDEXER_PROPERTY);
    Assert.assertEquals(APIConstants.OVERVIEW_PREFIX + APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX +
            APIConstants.CUSTOM_API_INDEXER_PROPERTY, indexer.getIndexedDocument(file2Index).getFields().keySet().
            toArray()[0].toString());
}
 
Example #21
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTagsWithAttributes() throws Exception {
    Registry userRegistry = Mockito.mock(Registry.class);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    System.setProperty(CARBON_HOME, "");
    PowerMockito.mockStatic(GovernanceUtils.class);
    UserRegistry userRegistry1 = Mockito.mock(UserRegistry.class);
    Mockito.when(registryService.getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt())).
            thenReturn(userRegistry1);
    Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry1);
    List<TermData> list = new ArrayList<TermData>();
    TermData termData = new TermData("testTerm", 10);
    list.add(termData);
    Mockito.when(GovernanceUtils.getTermDataList(Mockito.anyMap(), Mockito.anyString(), Mockito.anyString(),
            Mockito.anyBoolean())).thenReturn(list);
    ResourceDO resourceDO = Mockito.mock(ResourceDO.class);
    Resource resource = new ResourceImpl("dw", resourceDO);
    resource.setContent("testContent");
    Mockito.when(userRegistry1.resourceExists(Mockito.anyString())).thenReturn(true);
    Mockito.when(userRegistry1.get(Mockito.anyString())).thenReturn(resource);
    assertNotNull(apiConsumer.getTagsWithAttributes("testDomain"));
}
 
Example #22
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAllGlobalMediationPolicies()
        throws RegistryException, APIManagementException, IOException, XMLStreamException {
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    Collection parentCollection = new CollectionImpl();
    String mediationResourcePath = APIConstants.API_CUSTOM_SEQUENCE_LOCATION;
    String childCollectionPath = mediationResourcePath + "/testMediation";
    parentCollection.setChildren(new String[] { childCollectionPath });
    Mockito.when(registry.get(mediationResourcePath)).thenReturn(parentCollection);
    Collection childCollection = new CollectionImpl();
    String resourcePath = childCollectionPath + "/policy1";
    childCollection.setChildren(new String[] { resourcePath });
    Mockito.when(registry.get(childCollectionPath)).thenReturn(childCollection);
    Resource resource = new ResourceImpl();
    resource.setUUID(SAMPLE_RESOURCE_ID);

    Mockito.when(registry.get(resourcePath)).thenReturn(resource);
    try {
        abstractAPIManager.getAllGlobalMediationPolicies();
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to get global mediation policies"));
    }
    String mediationPolicyContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<sequence xmlns=\"http://ws.apache.org/ns/synapse\" name=\"default-endpoint\">\n</sequence>";
    resource.setContent(mediationPolicyContent);

    List<Mediation> policies = abstractAPIManager.getAllGlobalMediationPolicies();
    Assert.assertNotNull(policies);
    Assert.assertEquals(policies.size(), 1);
    PowerMockito.mockStatic(IOUtils.class);
    PowerMockito.mockStatic(AXIOMUtil.class);
    PowerMockito.when(IOUtils.toString((InputStream) Mockito.any(), Mockito.anyString()))
            .thenThrow(IOException.class).thenReturn(mediationPolicyContent);
    PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())).thenThrow(XMLStreamException.class);
    abstractAPIManager.getAllGlobalMediationPolicies(); // cover the logged only exceptions
    abstractAPIManager.getAllGlobalMediationPolicies(); // cover the logged only exceptions

}
 
Example #23
Source File: SAMLSSOServiceProviderDAOTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetServiceProviders() throws Exception {
    when(mockRegistry.resourceExists(IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS)).thenReturn(true);
    Resource collection = new CollectionImpl();
    String[] paths = new String[]{
            getPath("DummyIssuer"), getPath("DummyAdvIssuer"), getPath("https://example.com/url?abc")
    };
    Properties dummyResourceProperties = new Properties();
    dummyResourceProperties.putAll(dummyBasicProperties);
    Resource dummyResource = new ResourceImpl();
    dummyResource.setProperties(dummyResourceProperties);

    Properties dummyAdvProperties = new Properties();
    dummyAdvProperties.putAll((Map<?, ?>) dummyAdvProperties);
    Resource dummyAdvResource = new ResourceImpl();
    dummyAdvResource.setProperties(dummyAdvProperties);

    Properties urlBasedIssuerResourceProperties = new Properties();
    urlBasedIssuerResourceProperties.putAll((Map<?, ?>) urlBasedIssuerResourceProperties);
    Resource urlBasedIssuerResource = new ResourceImpl();
    urlBasedIssuerResource.setProperties(urlBasedIssuerResourceProperties);
    Resource[] spResources = new Resource[]{dummyResource, dummyAdvResource, urlBasedIssuerResource};
    collection.setContent(paths);
    when(mockRegistry.get(IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS)).thenReturn(collection);
    when(mockRegistry.get(paths[0])).thenReturn(spResources[0]);
    when(mockRegistry.get(paths[1])).thenReturn(spResources[1]);
    when(mockRegistry.get(paths[2])).thenReturn(spResources[2]);
    when(mockRegistry.resourceExists(paths[0])).thenReturn(true);
    when(mockRegistry.resourceExists(paths[1])).thenReturn(true);
    when(mockRegistry.resourceExists(paths[2])).thenReturn(true);
    SAMLSSOServiceProviderDO[] serviceProviders = objUnderTest.getServiceProviders();
    assertEquals(serviceProviders.length, 3, "Should have returned 3 service providers.");
}
 
Example #24
Source File: SAMLSSOServiceProviderDAOTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testUploadServiceProvider() throws Exception {
    setUpResources();
    Properties properties = new Properties();
    properties.putAll(dummyBasicProperties);
    Resource dummyResource = new ResourceImpl();
    dummyResource.setProperties(properties);
    String expectedPath = getPath(dummyResource
            .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER));
    when(mockRegistry.resourceExists(expectedPath)).thenReturn(false);
    SAMLSSOServiceProviderDO serviceProviderDO = objUnderTest.resourceToObject(dummyResource);
    assertEquals(objUnderTest.uploadServiceProvider(serviceProviderDO), serviceProviderDO, "Same resource should" +
            " have returned after successful upload.");
}
 
Example #25
Source File: SAMLSSOServiceProviderDAOTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = IdentityException.class)
public void testUploadExistingServiceProvider() throws Exception {
    setUpResources();
    Properties properties = new Properties();
    properties.putAll(dummyAdvProperties);
    Resource dummyResource = new ResourceImpl();
    dummyResource.setProperties(properties);
    String expectedPath = getPath(dummyResource
            .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER));
    when(mockRegistry.resourceExists(expectedPath)).thenReturn(true);
    SAMLSSOServiceProviderDO serviceProviderDO = objUnderTest.resourceToObject(dummyResource);
    objUnderTest.uploadServiceProvider(serviceProviderDO);
    fail("Uploading an existing SP should have failed");
}
 
Example #26
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 #27
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 #28
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetCreatedResourceUuid() throws RegistryException, APIManagementException {
    Resource resource = new ResourceImpl();
    resource.setUUID(SAMPLE_RESOURCE_ID);
    Mockito.when(registry.get(Mockito.anyString())).thenThrow(RegistryException.class).thenReturn(resource);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    Assert.assertNull(abstractAPIManager.getCreatedResourceUuid("/test/path"));
    Assert.assertEquals(abstractAPIManager.getCreatedResourceUuid("/test/path"), SAMPLE_RESOURCE_ID);
}
 
Example #29
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with 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 #30
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDocumentation() throws APIManagementException, RegistryException {
    Registry registry = Mockito.mock(UserRegistry.class);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(genericArtifactManager, registry, null);
    APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    String documentationName = "doc1";
    String contentPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName()
            + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR
            + identifier.getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.DOC_DIR
            + RegistryConstants.PATH_SEPARATOR + documentationName;
    GenericArtifact genericArtifact = getGenericArtifact(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION,
            "sample");
    String docType = "other";
    genericArtifact.setAttribute(APIConstants.DOC_TYPE, docType);
    genericArtifact.setAttribute(APIConstants.DOC_SOURCE_TYPE, "URL");
    Resource resource = new ResourceImpl();
    resource.setUUID(SAMPLE_RESOURCE_ID);
    Mockito.when(registry.get(contentPath)).thenThrow(RegistryException.class).thenReturn(resource);
    Mockito.when(genericArtifactManager.getGenericArtifact(SAMPLE_RESOURCE_ID)).thenReturn(genericArtifact);
    try {
        abstractAPIManager.getDocumentation(identifier, DocumentationType.OTHER, documentationName);
        Assert.fail("Registry exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to get documentation details"));
    }
    Assert.assertTrue(
            abstractAPIManager.getDocumentation(identifier, DocumentationType.OTHER, documentationName).getId()
                    .equals(genericArtifact.getId()));
}