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

The following examples show how to use org.wso2.carbon.registry.core.ResourceImpl. 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
@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 2
@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 3
Source Project: carbon-apimgt   Source File: APIConsumerImplTest.java    License: 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 4
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 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 5
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 6
Source Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: 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 7
Source Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: 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 8
Source Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: 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 9
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 10
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 11
@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 12
@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 13
@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 14
@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 15
@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 16
@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 17
@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 18
@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 19
Source Project: carbon-apimgt   Source File: CustomAPIIndexHandlerTest.java    License: 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 20
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 21
Source Project: carbon-apimgt   Source File: SequenceUtilsTestCase.java    License: 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 22
@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 23
@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 24
@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 25
Source Project: carbon-apimgt   Source File: GAConfigMediaTypeHandler.java    License: 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 26
Source Project: carbon-apimgt   Source File: SequenceUtils.java    License: 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 27
Source Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: 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 28
Source Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetGlobalMediationPolicy()
        throws RegistryException, APIManagementException, XMLStreamException, IOException {
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    String resourceUUID = SAMPLE_RESOURCE_ID;
    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)).thenThrow(RegistryException.class).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(resourcePath, new ResourceDO());
    resource.setUUID(resourceUUID);

    Mockito.when(registry.get(resourcePath)).thenReturn(resource);
    try {
        abstractAPIManager.getGlobalMediationPolicy(resourceUUID);
        Assert.fail("Registry Exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while accessing registry objects"));
    }
    abstractAPIManager.getGlobalMediationPolicy(resourceUUID); // test for registry exception
    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);
    Mediation policy = abstractAPIManager.getGlobalMediationPolicy(resourceUUID);
    Assert.assertNotNull(policy);
    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.getGlobalMediationPolicy(resourceUUID); // cover the logged only exceptions
    abstractAPIManager.getGlobalMediationPolicy(resourceUUID); // cover the logged only exceptions

}
 
Example 29
Source Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetWsdlById() throws RegistryException, APIManagementException, IOException {
    String resourceId = SAMPLE_RESOURCE_ID;
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    Collection parentCollection = new CollectionImpl();
    String wsdlResourcepath = APIConstants.API_WSDL_RESOURCE;
    String resourcePath = wsdlResourcepath + "/wsdl1";
    parentCollection.setChildren(new String[] { resourcePath });
    Mockito.when(registry.get(wsdlResourcepath)).thenReturn(parentCollection);
    Resource resource = new ResourceImpl(resourcePath, new ResourceDO());
    Mockito.when(registry.get(resourcePath)).thenThrow(RegistryException.class).thenReturn(resource);
    Mockito.when(registry.resourceExists(wsdlResourcepath)).thenReturn(false, true);
    Assert.assertNull(abstractAPIManager.getWsdlById(resourceId));
    resource.setUUID(resourceId);
    try {
        abstractAPIManager.getWsdlById(resourceId);
        Assert.fail("Exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while accessing registry objects"));
    }
    String wsdlContent = "sample wsdl";
    resource.setContent(wsdlContent);
    Wsdl wsdl = abstractAPIManager.getWsdlById(resourceId);
    Assert.assertNotNull(wsdl);
    PowerMockito.mockStatic(IOUtils.class);
    PowerMockito.when(IOUtils.toString((InputStream) Mockito.any(), Mockito.anyString()))
            .thenThrow(IOException.class);
    abstractAPIManager.getWsdlById(resourceId);// covers logged only exception;

}
 
Example 30
Source Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: 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()));
}