Search in sources :

Example 46 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.

the class APIUtil method addDefinedAllSequencesToRegistry.

/**
 * Add all the custom sequences of given type to registry
 *
 * @param registry           Registry instance
 * @param customSequenceType Custom sequence type which is in/out or fault
 * @throws APIManagementException
 */
public static void addDefinedAllSequencesToRegistry(UserRegistry registry, String customSequenceType) throws APIManagementException {
    InputStream inSeqStream = null;
    String seqFolderLocation = CarbonUtils.getCarbonHome() + File.separator + APIConstants.API_CUSTOM_SEQUENCES_FOLDER_LOCATION + File.separator + customSequenceType;
    try {
        File inSequenceDir = new File(seqFolderLocation);
        File[] sequences;
        sequences = inSequenceDir.listFiles();
        if (sequences != null) {
            for (File sequenceFile : sequences) {
                String sequenceFileName = sequenceFile.getName();
                String regResourcePath = APIConstants.API_CUSTOM_SEQUENCE_LOCATION + '/' + customSequenceType + '/' + sequenceFileName;
                if (registry.resourceExists(regResourcePath)) {
                    if (log.isDebugEnabled()) {
                        log.debug("The sequence file with the name " + sequenceFileName + " already exists in the registry path " + regResourcePath);
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Adding sequence file with the name " + sequenceFileName + " to the registry path " + regResourcePath);
                    }
                    inSeqStream = new FileInputStream(sequenceFile);
                    byte[] inSeqData = IOUtils.toByteArray(inSeqStream);
                    Resource inSeqResource = registry.newResource();
                    inSeqResource.setContent(inSeqData);
                    registry.put(regResourcePath, inSeqResource);
                }
            }
        } else {
            log.error("Custom sequence template location unavailable for custom sequence type " + customSequenceType + " : " + seqFolderLocation);
        }
    } catch (RegistryException e) {
        throw new APIManagementException("Error while saving defined sequences to the registry ", e);
    } catch (IOException e) {
        throw new APIManagementException("Error while reading defined sequence ", e);
    } finally {
        IOUtils.closeQuietly(inSeqStream);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) IOException(java.io.IOException) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) FileInputStream(java.io.FileInputStream)

Example 47 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.

the class APIUtil method isPerAPISequence.

/**
 * Returns true if the sequence is a per API one
 *
 * @param sequenceName
 * @param tenantId
 * @param identifier   API identifier
 * @param sequenceType in/out/fault
 * @return true/false
 * @throws APIManagementException
 */
public static boolean isPerAPISequence(String sequenceName, int tenantId, APIIdentifier identifier, String sequenceType) throws APIManagementException {
    org.wso2.carbon.registry.api.Collection seqCollection = null;
    try {
        UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);
        if (registry.resourceExists(getSequencePath(identifier, sequenceType))) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier, sequenceType));
            if (seqCollection != null) {
                String[] childPaths = seqCollection.getChildren();
                for (String childPath : childPaths) {
                    Resource sequence = registry.get(childPath);
                    OMElement seqElment = APIUtil.buildOMElement(sequence.getContentStream());
                    if (sequenceName.equals(seqElment.getAttributeValue(new QName("name")))) {
                        return true;
                    }
                }
            }
        }
    } catch (RegistryException e) {
        String msg = "Error while retrieving registry for tenant " + tenantId;
        log.error(msg);
        throw new APIManagementException(msg, e);
    } catch (org.wso2.carbon.registry.api.RegistryException e) {
        String msg = "Error while processing the " + sequenceType + " sequences of " + identifier + " in the registry";
        log.error(msg);
        throw new APIManagementException(msg, e);
    } catch (Exception e) {
        throw new APIManagementException(e.getMessage(), e);
    }
    return false;
}
Also used : QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) OMElement(org.apache.axiom.om.OMElement) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) KeyStoreException(java.security.KeyStoreException) JSONException(org.json.JSONException) XMLStreamException(javax.xml.stream.XMLStreamException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ExceptionException(org.wso2.carbon.core.commons.stub.loggeduserinfo.ExceptionException) APIMgtInternalException(org.wso2.carbon.apimgt.api.APIMgtInternalException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URISyntaxException(java.net.URISyntaxException) SignatureException(java.security.SignatureException) RemoteException(java.rmi.RemoteException) CertificateEncodingException(javax.security.cert.CertificateEncodingException) AuthorizationFailedException(org.wso2.carbon.registry.core.secure.AuthorizationFailedException) EventPublisherException(org.wso2.carbon.apimgt.eventing.EventPublisherException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) ValidationException(org.everit.json.schema.ValidationException) CryptoException(org.wso2.carbon.core.util.CryptoException) NotifierException(org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SocketException(java.net.SocketException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) CertificateException(java.security.cert.CertificateException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException)

Example 48 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.

the class APIUtil method getMediationPolicyAttributes.

/**
 * Returns attributes correspond to the given mediation policy name and direction
 *
 * @param policyName name of the  sequence
 * @param tenantId   logged in user's tenantId
 * @param direction  in/out/fault
 * @param identifier API identifier
 * @return attributes(path, uuid) of the given mediation sequence or null
 * @throws APIManagementException If failed to get the uuid of the mediation sequence
 */
public static Map<String, String> getMediationPolicyAttributes(String policyName, int tenantId, String direction, APIIdentifier identifier) throws APIManagementException {
    org.wso2.carbon.registry.api.Collection seqCollection = null;
    String seqCollectionPath = "";
    Map<String, String> mediationPolicyAttributes = new HashMap<>(3);
    try {
        UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);
        if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN.equals(direction)) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + "/" + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN);
        } else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT.equals(direction)) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + "/" + APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT);
        } else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT.equals(direction)) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + "/" + APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT);
        }
        if (seqCollection == null) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier, direction));
        }
        if (seqCollection != null) {
            String[] childPaths = seqCollection.getChildren();
            for (String childPath : childPaths) {
                Resource mediationPolicy = registry.get(childPath);
                OMElement seqElment = APIUtil.buildOMElement(mediationPolicy.getContentStream());
                String seqElmentName = seqElment.getAttributeValue(new QName("name"));
                if (policyName.equals(seqElmentName)) {
                    mediationPolicyAttributes.put("path", childPath);
                    mediationPolicyAttributes.put("uuid", mediationPolicy.getUUID());
                    mediationPolicyAttributes.put("name", policyName);
                    return mediationPolicyAttributes;
                }
            }
        }
        // If the sequence not found the default sequences, check in custom sequences
        seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier, direction));
        if (seqCollection != null) {
            String[] childPaths = seqCollection.getChildren();
            for (String childPath : childPaths) {
                Resource mediationPolicy = registry.get(childPath);
                OMElement seqElment = APIUtil.buildOMElement(mediationPolicy.getContentStream());
                if (policyName.equals(seqElment.getAttributeValue(new QName("name")))) {
                    mediationPolicyAttributes.put("path", childPath);
                    mediationPolicyAttributes.put("uuid", mediationPolicy.getUUID());
                    mediationPolicyAttributes.put("name", policyName);
                    return mediationPolicyAttributes;
                }
            }
        }
    } catch (Exception e) {
        String msg = "Issue is in accessing the Registry";
        log.error(msg);
        throw new APIManagementException(msg, e);
    }
    return mediationPolicyAttributes;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) OMElement(org.apache.axiom.om.OMElement) KeyStoreException(java.security.KeyStoreException) JSONException(org.json.JSONException) XMLStreamException(javax.xml.stream.XMLStreamException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ExceptionException(org.wso2.carbon.core.commons.stub.loggeduserinfo.ExceptionException) APIMgtInternalException(org.wso2.carbon.apimgt.api.APIMgtInternalException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URISyntaxException(java.net.URISyntaxException) SignatureException(java.security.SignatureException) RemoteException(java.rmi.RemoteException) CertificateEncodingException(javax.security.cert.CertificateEncodingException) AuthorizationFailedException(org.wso2.carbon.registry.core.secure.AuthorizationFailedException) EventPublisherException(org.wso2.carbon.apimgt.eventing.EventPublisherException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) ValidationException(org.everit.json.schema.ValidationException) CryptoException(org.wso2.carbon.core.util.CryptoException) NotifierException(org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SocketException(java.net.SocketException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) CertificateException(java.security.cert.CertificateException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Collection(java.util.Collection)

Example 49 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.

the class APIProviderImplTest method testUpdateAPIforStateChange_ToPublished.

@Test
public void testUpdateAPIforStateChange_ToPublished() throws RegistryException, UserStoreException, APIManagementException, FaultGatewaysException, APIPersistenceException, XMLStreamException {
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.0");
    Set<String> environments = new HashSet<String>();
    environments.add("Production");
    environments.add("Sandbox");
    API api = new API(apiId);
    api.setContext("/test");
    api.setStatus(APIConstants.CREATED);
    api.setAsDefaultVersion(true);
    api.setEnvironments(environments);
    api.setOrganization("carbon.super");
    Mockito.when(apimgtDAO.getPublishedDefaultVersion(apiId)).thenReturn("1.0.0");
    Map<String, String> failedGWEnv = new HashMap<String, String>();
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, null, null);
    Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
    Mockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
    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);
    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);
    PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
    PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
    apiProvider.addAPI(api);
    // Mock Updating API
    Resource apiSourceArtifact = Mockito.mock(Resource.class);
    Mockito.when(apiSourceArtifact.getUUID()).thenReturn("12640983654");
    String apiSourcePath = "path";
    PowerMockito.when(APIUtil.getAPIPath(api.getId())).thenReturn(apiSourcePath);
    PowerMockito.when(apiProvider.registry.get(apiSourcePath)).thenReturn(apiSourceArtifact);
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)).thenReturn("CREATED");
    Mockito.when(artifactManager.getGenericArtifact(apiSourceArtifact.getUUID())).thenReturn(artifact);
    PowerMockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
    Mockito.when(artifact.getId()).thenReturn("12640983654");
    PowerMockito.when(GovernanceUtils.getArtifactPath(apiProvider.registry, "12640983654")).thenReturn(apiSourcePath);
    Mockito.doNothing().when(artifactManager).updateGenericArtifact(artifact);
    apiProvider.updateAPIforStateChange(api, APIConstants.CREATED, APIConstants.PUBLISHED);
    // From the 2 environments, only 1 was successful
    Assert.assertEquals(2, api.getEnvironments().size());
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) RealmService(org.wso2.carbon.user.core.service.RealmService) 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) HashSet(java.util.HashSet) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 50 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.

the class APIProviderImplTest method testGetCustomApiFaultSequences.

@Test
public void testGetCustomApiFaultSequences() throws Exception {
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.1");
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    mockSequences(APIConstants.API_CUSTOM_FAULTSEQUENCE_LOCATION, APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT, apiId);
    List<String> sequenceList = apiProvider.getCustomApiFaultSequences(apiId);
    Assert.assertNotNull(sequenceList);
    Assert.assertEquals(1, sequenceList.size());
    // OMException when building OMElement
    PowerMockito.when(APIUtil.buildOMElement(any(InputStream.class))).thenThrow(new OMException());
    apiProvider.getCustomApiFaultSequences(apiId);
    // org.wso2.carbon.registry.api.RegistryException
    ServiceReferenceHolder sh = PowerMockito.mock(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(sh);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    PowerMockito.when(sh.getRegistryService()).thenReturn(registryService);
    UserRegistry registry = Mockito.mock(UserRegistry.class);
    PowerMockito.when(registryService.getGovernanceSystemRegistry(Matchers.anyInt())).thenReturn(registry);
    Mockito.when(registry.resourceExists(APIUtil.getSequencePath(apiId, APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT))).thenThrow(org.wso2.carbon.registry.api.RegistryException.class);
    String msg = "Error while processing the " + APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT + " sequences of " + apiId + " in the registry";
    try {
        apiProvider.getCustomApiFaultSequences(apiId);
    } catch (APIManagementException e) {
        Assert.assertEquals(msg, e.getMessage());
    }
    // Registry Exception
    PowerMockito.when(registryService.getGovernanceSystemRegistry(Matchers.anyInt())).thenThrow(RegistryException.class);
    String msg1 = "Error while retrieving registry for tenant -1";
    try {
        apiProvider.getCustomApiFaultSequences(apiId);
    } catch (APIManagementException e) {
        Assert.assertEquals(msg1, e.getMessage());
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) InputStream(java.io.InputStream) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) OMException(org.apache.axiom.om.OMException) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)147 Resource (org.wso2.carbon.registry.core.Resource)96 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)86 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)84 Test (org.junit.Test)75 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)75 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)66 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)65 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)53 API (org.wso2.carbon.apimgt.api.model.API)47 UserStoreException (org.wso2.carbon.user.api.UserStoreException)44 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)43 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)41 Registry (org.wso2.carbon.registry.core.Registry)39 IOException (java.io.IOException)38 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)37 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)34 ArrayList (java.util.ArrayList)33 QName (javax.xml.namespace.QName)32 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)32