Search in sources :

Example 21 with ResourcePath

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

the class SequenceUtils method updateRestToSoapConvertedSequences.

/**
 * Updates the api sequences where user will be able to edits the generated sequences
 * <p>
 * Note: this method is directly invoked from the jaggery layer
 *
 * @param name     api name
 * @param version  api version
 * @param provider api provider
 * @param seqType  to identify the sequence is whether in/out sequence
 * @param content  sequence content
 * @throws APIManagementException throws exceptions on unsuccessful persistence in registry or json parsing of the content
 */
public static void updateRestToSoapConvertedSequences(String name, String version, String provider, String seqType, String content) throws APIManagementException {
    if (provider != null) {
        provider = APIUtil.replaceEmailDomain(provider);
    }
    provider = (provider != null ? provider.trim() : null);
    name = (name != null ? name.trim() : null);
    version = (version != null ? version.trim() : null);
    boolean isTenantFlowStarted = false;
    JSONParser jsonParser = new JSONParser();
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(provider));
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
        int tenantId;
        UserRegistry registry;
        tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        APIUtil.loadTenantRegistry(tenantId);
        registry = registryService.getGovernanceSystemRegistry(tenantId);
        JSONObject sequences = (JSONObject) jsonParser.parse(content);
        for (Object sequence : sequences.keySet()) {
            String sequenceContent = (String) ((JSONObject) sequences.get(sequence)).get("content");
            String resourcePath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + APIUtil.replaceEmailDomain(provider) + RegistryConstants.PATH_SEPARATOR + name + RegistryConstants.PATH_SEPARATOR + version + RegistryConstants.PATH_SEPARATOR + SOAPToRESTConstants.SOAP_TO_REST_RESOURCE + RegistryConstants.PATH_SEPARATOR + seqType + RegistryConstants.PATH_SEPARATOR + sequence + ".xml";
            Resource regResource;
            if (registry.resourceExists(resourcePath)) {
                regResource = registry.get(resourcePath);
                regResource.setContent(sequenceContent);
                if (log.isDebugEnabled()) {
                    log.debug("Api sequence content for " + resourcePath + " is: " + sequenceContent);
                }
                regResource.setMediaType("text/xml");
                registry.put(resourcePath, regResource);
            }
        }
    } catch (ParseException e) {
        handleException("Error occurred while parsing the sequence json", e);
    } catch (UserStoreException e) {
        handleException("Error while reading tenant information", e);
    } catch (RegistryException e) {
        handleException("Error when create registry instance", e);
    } catch (org.wso2.carbon.registry.api.RegistryException e) {
        handleException("Error while creating registry resource", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
Also used : Resource(org.wso2.carbon.registry.api.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) JSONObject(org.json.simple.JSONObject) UserStoreException(org.wso2.carbon.user.api.UserStoreException) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException) RegistryService(org.wso2.carbon.registry.core.service.RegistryService)

Example 22 with ResourcePath

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

the class SequenceUtils method saveRestToSoapConvertedSequence.

/**
 * Saves the converted api sequence in the registry for the given resource path
 *
 * @param registry     user registry reference
 * @param sequence     sequence to be saved
 * @param method       http method of the operation
 * @param resourcePath registry resource path
 * @throws APIManagementException throws errors on if the resource persistence gets unsuccessful
 */
public static void saveRestToSoapConvertedSequence(UserRegistry registry, String sequence, String method, String resourcePath, String apiResourceName) throws APIManagementException {
    try {
        Resource regResource;
        if (apiResourceName.startsWith(SOAPToRESTConstants.SequenceGen.PATH_SEPARATOR)) {
            apiResourceName = apiResourceName.substring(1);
        }
        if (!registry.resourceExists(resourcePath)) {
            regResource = registry.newResource();
        } else {
            regResource = registry.get(resourcePath);
        }
        regResource.setContent(sequence);
        regResource.addProperty(SOAPToRESTConstants.METHOD, method);
        if (regResource.getProperty(SOAPToRESTConstants.Template.RESOURCE_PATH) != null) {
            regResource.removeProperty(SOAPToRESTConstants.Template.RESOURCE_PATH);
        }
        regResource.addProperty(SOAPToRESTConstants.Template.RESOURCE_PATH, apiResourceName);
        regResource.setMediaType("text/xml");
        registry.put(resourcePath, regResource);
    } catch (RegistryException e) {
        handleException("Error occurred while accessing the registry to save api sequence", e);
    } catch (org.wso2.carbon.registry.api.RegistryException e) {
        handleException("Error occurred while saving api sequence", e);
    }
}
Also used : Resource(org.wso2.carbon.registry.api.Resource) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 23 with ResourcePath

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

the class APIProviderImplTest method testCreateNewAPIVersion.

@Test
public void testCreateNewAPIVersion() throws Exception {
    // Create Original API
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId);
    api.setContext("/test");
    api.setVisibility("Public");
    api.setStatus(APIConstants.CREATED);
    api.setWsdlUrl("https://localhost:9443/services/echo?wsdl");
    api.setOrganization("carbon.super");
    long time = System.currentTimeMillis();
    String newVersion = "1.0.1";
    // Create new API object
    APIIdentifier newApiId = new APIIdentifier("admin", "API1", "1.0.1");
    final API newApi = new API(newApiId);
    newApi.setStatus(APIConstants.CREATED);
    newApi.setContext("/test");
    newApi.setWsdlUrl("/registry/resource/_system/governance/apimgt/applicationdata/wsdls/admin--API11.0.0.wsdl");
    // Create Documentation List
    List<Documentation> documentationList = getDocumentationList();
    final APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, documentationList, null);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
    ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
    Mockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getConfigSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    GenericArtifact artifactNew = Mockito.mock(GenericArtifact.class);
    Mockito.when(APIUtil.createAPIArtifactContent(artifact, newApi)).thenReturn(artifactNew);
    PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
    Mockito.when(publisherAPI.getVersionTimestamp()).thenReturn(String.valueOf(time));
    PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
    API returnedAPI = apiProvider.addAPI(api);
    Assert.assertTrue(StringUtils.isNotEmpty(returnedAPI.getVersionTimestamp()));
    String targetPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + api.getId().getProviderName() + RegistryConstants.PATH_SEPARATOR + api.getId().getApiName() + RegistryConstants.PATH_SEPARATOR + newVersion + APIConstants.API_RESOURCE_NAME;
    String apiSourcePath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + apiId.getProviderName() + RegistryConstants.PATH_SEPARATOR + apiId.getApiName() + RegistryConstants.PATH_SEPARATOR + apiId.getVersion() + APIConstants.API_RESOURCE_NAME;
    PowerMockito.when(APIUtil.getAPIPath(apiId)).thenReturn(apiSourcePath);
    String apiSourceUUID = "87ty543-899hyt";
    Mockito.when(apiProvider.registry.resourceExists(targetPath)).thenReturn(false);
    Mockito.doNothing().when(apiProvider.registry).beginTransaction();
    Mockito.doNothing().when(apiProvider.registry).commitTransaction();
    Resource apiSourceArtifact = Mockito.mock(Resource.class);
    Mockito.when(apiProvider.registry.get(apiSourcePath)).thenReturn(apiSourceArtifact);
    // Mocking Old API retrieval
    Mockito.when(apiSourceArtifact.getUUID()).thenReturn(apiSourceUUID);
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)).thenReturn("PUBLISHED");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT)).thenReturn("test");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE)).thenReturn("test/{version}");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_WEBSOCKET)).thenReturn("false");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES)).thenReturn("admin, subscriber");
    Mockito.when(artifactManager.getGenericArtifact(apiSourceUUID)).thenReturn(artifact);
    // Mocking thumbnail
    String thumbUrl = APIConstants.API_IMAGE_LOCATION + RegistryConstants.PATH_SEPARATOR + api.getId().getProviderName() + RegistryConstants.PATH_SEPARATOR + api.getId().getApiName() + RegistryConstants.PATH_SEPARATOR + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ICON_IMAGE;
    Resource image = Mockito.mock(Resource.class);
    Mockito.when(apiProvider.registry.get(thumbUrl)).thenReturn(image);
    Mockito.when(apiProvider.registry.resourceExists(thumbUrl)).thenReturn(true);
    // Mocking In sequence retrieval
    String inSeqFilePath = "API1/1.0.0/in";
    PowerMockito.when(APIUtil.getSequencePath(api.getId(), "in")).thenReturn(inSeqFilePath);
    Mockito.when(apiProvider.registry.resourceExists(inSeqFilePath)).thenReturn(true);
    Collection inSeqCollection = Mockito.mock(Collection.class);
    Mockito.when(apiProvider.registry.get(inSeqFilePath)).thenReturn(inSeqCollection);
    String[] inSeqChildPaths = { "path1" };
    Mockito.when(inSeqCollection.getChildren()).thenReturn(inSeqChildPaths);
    Mockito.when(apiProvider.registry.get(inSeqChildPaths[0])).thenReturn(apiSourceArtifact);
    InputStream responseStream = IOUtils.toInputStream("<sequence name=\"in-seq\"></sequence>", "UTF-8");
    OMElement seqElment = buildOMElement(responseStream);
    PowerMockito.when(APIUtil.buildOMElement(responseStream)).thenReturn(seqElment);
    Mockito.when(apiSourceArtifact.getContentStream()).thenReturn(responseStream);
    // Mocking Out sequence retrieval
    Resource apiSourceArtifact1 = Mockito.mock(Resource.class);
    String outSeqFilePath = "API1/1.0.0/out";
    PowerMockito.when(APIUtil.getSequencePath(api.getId(), "out")).thenReturn(outSeqFilePath);
    Mockito.when(apiProvider.registry.resourceExists(outSeqFilePath)).thenReturn(true);
    Collection outSeqCollection = Mockito.mock(Collection.class);
    Mockito.when(apiProvider.registry.get(outSeqFilePath)).thenReturn(outSeqCollection);
    String[] outSeqChildPaths = { "path2" };
    Mockito.when(outSeqCollection.getChildren()).thenReturn(outSeqChildPaths);
    Mockito.when(apiProvider.registry.get(outSeqChildPaths[0])).thenReturn(apiSourceArtifact1);
    InputStream responseStream2 = IOUtils.toInputStream("<sequence name=\"in-seq\"></sequence>", "UTF-8");
    OMElement seqElment2 = buildOMElement(responseStream2);
    PowerMockito.when(APIUtil.buildOMElement(responseStream2)).thenReturn(seqElment2);
    Mockito.when(apiSourceArtifact1.getContentStream()).thenReturn(responseStream2);
    // Mock Adding new API artifact with new version
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            apiProvider.createAPI(newApi);
            return null;
        }
    }).when(artifactManager).addGenericArtifact(artifact);
    Mockito.doNothing().when(artifact).attachLifecycle(APIConstants.API_LIFE_CYCLE);
    PowerMockito.when(APIUtil.getAPIProviderPath(api.getId())).thenReturn("/dummy/provider/path");
    Mockito.doNothing().when(apiProvider.registry).addAssociation("/dummy/provider/path", targetPath, APIConstants.PROVIDER_ASSOCIATION);
    PowerMockito.when(GovernanceUtils.getArtifactPath(apiProvider.registry, artifact.getId())).thenReturn(artifactPath);
    PowerMockito.doNothing().when(APIUtil.class);
    String[] roles = { "admin", "subscriber" };
    APIUtil.setResourcePermissions("admin", "Public", roles, artifactPath);
    // Mock no tags case
    Mockito.when(apiProvider.registry.getTags(apiSourcePath)).thenReturn(null);
    // Mock WSDL retrieval
    String wsdlUrl = APIUtil.getWSDLDefinitionFilePath(api.getId().getApiName(), api.getId().getVersion(), api.getId().getProviderName());
    PowerMockito.when(apiProvider.registry.resourceExists(wsdlUrl)).thenReturn(true);
    // Mock new API retrieval
    String newApiPath = "API1/1.0.1/";
    PowerMockito.when(APIUtil.getAPIPath(newApi.getId())).thenReturn(newApiPath);
    String newApiUUID = "87ty543-899hy23";
    GenericArtifact newArtifact = Mockito.mock(GenericArtifact.class);
    Resource newApiResource = Mockito.mock(Resource.class);
    Mockito.when(newApiResource.getUUID()).thenReturn(newApiUUID);
    Mockito.when(apiProvider.registry.get(newApiPath)).thenReturn(newApiResource);
    Mockito.when(artifactManager.getGenericArtifact(newApiUUID)).thenReturn(newArtifact);
    PowerMockito.when(APIUtil.getAPI(newArtifact, apiProvider.registry, api.getId(), "test")).thenReturn(newApi);
    // Swagger resource
    String resourcePath = APIUtil.getOpenAPIDefinitionFilePath(api.getId().getApiName(), api.getId().getVersion(), api.getId().getProviderName());
    Mockito.when(apiProvider.registry.resourceExists(resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME)).thenReturn(true);
    PowerMockito.mockStatic(OASParserUtil.class);
    Mockito.when(OASParserUtil.getAPIDefinition(apiId, apiProvider.registry)).thenReturn("{\"info\": {\"swagger\":\"data\"}}");
    Mockito.doNothing().when(artifactManager).updateGenericArtifact(artifact);
    // WSDL
    String newWsdlResourcePath = APIUtil.getWSDLDefinitionFilePath(newApi.getId().getApiName(), newApi.getId().getVersion(), newApi.getId().getProviderName());
    PowerMockito.when(apiProvider.registry.copy(resourcePath, newWsdlResourcePath)).thenReturn(newWsdlResourcePath);
    // Mock Config system registry
    PowerMockito.when(tenantManager.getTenantId(Matchers.anyString())).thenReturn(-1234);
    AuthorizationManager authManager = Mockito.mock(AuthorizationManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    PowerMockito.when(realmService.getTenantUserRealm(-1234)).thenReturn(userRealm);
    PowerMockito.when(userRealm.getAuthorizationManager()).thenReturn(authManager);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) OMElement(org.apache.axiom.om.OMElement) UserRealm(org.wso2.carbon.user.api.UserRealm) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) QName(javax.xml.namespace.QName) InputStream(java.io.InputStream) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) RealmService(org.wso2.carbon.user.core.service.RealmService) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Collection(org.wso2.carbon.registry.core.Collection) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 24 with ResourcePath

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

the class APIProviderImplTest method testCreateNewAPIVersion_ForDefaultVersion.

@Ignore
@Test
public void testCreateNewAPIVersion_ForDefaultVersion() throws Exception {
    // Create Original API
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId);
    api.setContext("/test");
    api.setVisibility("Public");
    api.setStatus(APIConstants.CREATED);
    api.setAsDefaultVersion(true);
    String newVersion = "1.0.1";
    // Create new API object
    APIIdentifier newApiId = new APIIdentifier("admin", "API1", "1.0.1");
    final API newApi = new API(newApiId);
    newApi.setStatus(APIConstants.CREATED);
    newApi.setContext("/test");
    // Mock API as a default version
    Mockito.when(apimgtDAO.getDefaultVersion(apiId)).thenReturn("1.0.0");
    final APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, new ArrayList<Documentation>(), null);
    Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
    Mockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
    GenericArtifact artifactNew = Mockito.mock(GenericArtifact.class);
    Mockito.when(APIUtil.createAPIArtifactContent(artifact, newApi)).thenReturn(artifactNew);
    RegistryService rs = Mockito.mock(RegistryService.class);
    UserRegistry ur = Mockito.mock(UserRegistry.class);
    ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(rs);
    Mockito.when(rs.getConfigSystemRegistry(Mockito.anyInt())).thenReturn(ur);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
    PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
    apiProvider.addAPI(api);
    String targetPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + api.getId().getProviderName() + RegistryConstants.PATH_SEPARATOR + api.getId().getApiName() + RegistryConstants.PATH_SEPARATOR + newVersion + APIConstants.API_RESOURCE_NAME;
    String apiSourcePath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + apiId.getProviderName() + RegistryConstants.PATH_SEPARATOR + apiId.getApiName() + RegistryConstants.PATH_SEPARATOR + apiId.getVersion() + APIConstants.API_RESOURCE_NAME;
    PowerMockito.when(APIUtil.getAPIPath(apiId)).thenReturn(apiSourcePath);
    String apiSourceUUID = "87ty543-899hyt";
    Mockito.when(apiProvider.registry.resourceExists(targetPath)).thenReturn(false);
    Resource apiSourceArtifact = Mockito.mock(Resource.class);
    Mockito.when(apiProvider.registry.get(apiSourcePath)).thenReturn(apiSourceArtifact);
    // Mock API as a default version
    Mockito.when(apimgtDAO.getDefaultVersion(apiId)).thenReturn("1.0.0");
    Mockito.when(apiSourceArtifact.getUUID()).thenReturn(apiSourceUUID);
    Mockito.doNothing().when(artifactManager).updateGenericArtifact(artifact);
    // Mocking Old API retrieval
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)).thenReturn("PUBLISHED");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT)).thenReturn("test");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE)).thenReturn("test/{version}");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_WEBSOCKET)).thenReturn("false");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES)).thenReturn("admin, subscriber");
    Mockito.when(artifactManager.getGenericArtifact(apiSourceUUID)).thenReturn(artifact);
    // Mocking no thumbnail case
    String thumbUrl = APIConstants.API_IMAGE_LOCATION + RegistryConstants.PATH_SEPARATOR + api.getId().getProviderName() + RegistryConstants.PATH_SEPARATOR + api.getId().getApiName() + RegistryConstants.PATH_SEPARATOR + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ICON_IMAGE;
    Mockito.when(apiProvider.registry.resourceExists(thumbUrl)).thenReturn(false);
    // Mocking In sequence retrieval
    String inSeqFilePath = "API1/1.0.0/in";
    PowerMockito.when(APIUtil.getSequencePath(api.getId(), "in")).thenReturn(inSeqFilePath);
    Mockito.when(apiProvider.registry.resourceExists(inSeqFilePath)).thenReturn(false);
    // Mocking Out sequence retrieval
    String outSeqFilePath = "API1/1.0.0/out";
    PowerMockito.when(APIUtil.getSequencePath(api.getId(), "out")).thenReturn(outSeqFilePath);
    Mockito.when(apiProvider.registry.resourceExists(outSeqFilePath)).thenReturn(false);
    // Mock Adding new API artifact with new version
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            apiProvider.createAPI(newApi);
            return null;
        }
    }).when(artifactManager).addGenericArtifact(artifact);
    Mockito.doNothing().when(artifact).attachLifecycle(APIConstants.API_LIFE_CYCLE);
    PowerMockito.when(APIUtil.getAPIProviderPath(api.getId())).thenReturn("/dummy/provider/path");
    Mockito.doNothing().when(apiProvider.registry).addAssociation("/dummy/provider/path", targetPath, APIConstants.PROVIDER_ASSOCIATION);
    PowerMockito.when(GovernanceUtils.getArtifactPath(apiProvider.registry, artifact.getId())).thenReturn(artifactPath);
    PowerMockito.doNothing().when(APIUtil.class);
    String[] roles = { "admin", "subscriber" };
    APIUtil.setResourcePermissions("admin", "Public", roles, artifactPath);
    // Mock no tags case
    Mockito.when(apiProvider.registry.getTags(apiSourcePath)).thenReturn(null);
    // Mock new API retrieval
    String newApiPath = "API1/1.0.1/";
    PowerMockito.when(APIUtil.getAPIPath(newApi.getId())).thenReturn(newApiPath);
    String newApiUUID = "87ty543-899hy23";
    GenericArtifact newArtifact = Mockito.mock(GenericArtifact.class);
    Resource newApiResource = Mockito.mock(Resource.class);
    Mockito.when(newApiResource.getUUID()).thenReturn(newApiUUID);
    Mockito.when(apiProvider.registry.get(newApiPath)).thenReturn(newApiResource);
    Mockito.when(artifactManager.getGenericArtifact(newApiUUID)).thenReturn(newArtifact);
    PowerMockito.when(APIUtil.getAPI(newArtifact, apiProvider.registry, api.getId(), "test")).thenReturn(newApi);
    String resourcePath = APIUtil.getOpenAPIDefinitionFilePath(api.getId().getApiName(), api.getId().getVersion(), api.getId().getProviderName());
    Mockito.when(apiProvider.registry.resourceExists(resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME)).thenReturn(false);
    // Mock Config system registry
    ServiceReferenceHolder sh = TestUtils.getServiceReferenceHolder();
    RegistryService registryService = Mockito.mock(RegistryService.class);
    PowerMockito.when(sh.getRegistryService()).thenReturn(registryService);
    PowerMockito.when(apiPersistenceInstance.getPublisherAPI(any(Organization.class), any(String.class))).thenReturn(publisherAPI);
    // apiProvider.createNewAPIVersion(api, newVersion);
    apiProvider.createNewAPIVersion(apiSourceUUID, newVersion, true, superTenantDomain);
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) QName(javax.xml.namespace.QName) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) RealmService(org.wso2.carbon.user.core.service.RealmService) InvocationOnMock(org.mockito.invocation.InvocationOnMock) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) Ignore(org.junit.Ignore) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 25 with ResourcePath

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

the class AbstractAPIManagerTestCase method testGetGlobalMediationPolicy.

@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"));
    }
    // test for registry exception
    abstractAPIManager.getGlobalMediationPolicy(resourceUUID);
    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);
    // cover the logged only exceptions
    abstractAPIManager.getGlobalMediationPolicy(resourceUUID);
    // cover the logged only exceptions
    abstractAPIManager.getGlobalMediationPolicy(resourceUUID);
}
Also used : ResourceDO(org.wso2.carbon.registry.core.jdbc.dataobjects.ResourceDO) ArrayInputStream(org.apache.derby.iapi.services.io.ArrayInputStream) InputStream(java.io.InputStream) Resource(org.wso2.carbon.registry.core.Resource) IOException(java.io.IOException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Mediation(org.wso2.carbon.apimgt.api.model.Mediation) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) CollectionImpl(org.wso2.carbon.registry.core.CollectionImpl) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Collection(org.wso2.carbon.registry.core.Collection) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

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