Search in sources :

Example 86 with UserRegistry

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

the class APIProviderImpl method getCustomInSequences.

/**
 * Get stored custom inSequences from governanceSystem registry
 *
 * @throws APIManagementException
 */
public List<String> getCustomInSequences(APIIdentifier apiIdentifier) throws APIManagementException {
    List<String> sequenceList = new ArrayList<String>();
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = null;
        if (apiIdentifier.getProviderName().contains("-AT-")) {
            String provider = apiIdentifier.getProviderName().replace("-AT-", "@");
            tenantDomain = MultitenantUtils.getTenantDomain(provider);
        }
        PrivilegedCarbonContext.startTenantFlow();
        isTenantFlowStarted = true;
        if (!StringUtils.isEmpty(tenantDomain)) {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        } else {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        }
        UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);
        if (registry.resourceExists(APIConstants.API_CUSTOM_INSEQUENCE_LOCATION)) {
            org.wso2.carbon.registry.api.Collection inSeqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_INSEQUENCE_LOCATION);
            if (inSeqCollection != null) {
                String[] inSeqChildPaths = inSeqCollection.getChildren();
                Arrays.sort(inSeqChildPaths);
                for (String inSeqChildPath : inSeqChildPaths) {
                    Resource inSequence = registry.get(inSeqChildPath);
                    try {
                        OMElement seqElment = APIUtil.buildOMElement(inSequence.getContentStream());
                        sequenceList.add(seqElment.getAttributeValue(new QName("name")));
                    } catch (OMException e) {
                        log.info("Error occurred when reading the sequence '" + inSeqChildPath + "' from the registry.", e);
                    }
                }
            }
        }
        String customInSeqFileLocation = APIUtil.getSequencePath(apiIdentifier, "in");
        if (registry.resourceExists(customInSeqFileLocation)) {
            org.wso2.carbon.registry.api.Collection inSeqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(customInSeqFileLocation);
            if (inSeqCollection != null) {
                String[] inSeqChildPaths = inSeqCollection.getChildren();
                Arrays.sort(inSeqChildPaths);
                for (String inSeqChildPath : inSeqChildPaths) {
                    Resource inSequence = registry.get(inSeqChildPath);
                    try {
                        OMElement seqElment = APIUtil.buildOMElement(inSequence.getContentStream());
                        sequenceList.add(seqElment.getAttributeValue(new QName("name")));
                    } catch (OMException e) {
                        log.info("Error occurred when reading the sequence '" + inSeqChildPath + "' from the registry.", e);
                    }
                }
            }
        }
    } catch (Exception e) {
        handleException("Issue is in getting custom InSequences from the Registry", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return sequenceList;
}
Also used : QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) 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) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) XMLStreamException(javax.xml.stream.XMLStreamException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) IOException(java.io.IOException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.PersistenceException) UnsupportedPolicyTypeException(org.wso2.carbon.apimgt.api.UnsupportedPolicyTypeException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) NotificationException(org.wso2.carbon.apimgt.impl.notification.exception.NotificationException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) OMException(org.apache.axiom.om.OMException) OMException(org.apache.axiom.om.OMException)

Example 87 with UserRegistry

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

the class RegistryPersistenceUtil method loadloadTenantAPIRXT.

public static void loadloadTenantAPIRXT(String tenant, int tenantID) throws APIManagementException {
    RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
    UserRegistry registry = null;
    try {
        registry = registryService.getGovernanceSystemRegistry(tenantID);
    } catch (RegistryException e) {
        throw new APIManagementException("Error when create registry instance ", e);
    }
    String rxtDir = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "rxts";
    File file = new File(rxtDir);
    FilenameFilter filenameFilter = new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            // if the file extension is .rxt return true, else false
            return name.endsWith(".rxt");
        }
    };
    String[] rxtFilePaths = file.list(filenameFilter);
    if (rxtFilePaths == null) {
        throw new APIManagementException("rxt files not found in directory " + rxtDir);
    }
    for (String rxtPath : rxtFilePaths) {
        String resourcePath = GovernanceConstants.RXT_CONFIGS_PATH + RegistryConstants.PATH_SEPARATOR + rxtPath;
        // This is  "registry" is a governance registry instance, therefore calculate the relative path to governance.
        String govRelativePath = RegistryUtils.getRelativePathToOriginal(resourcePath, RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH));
        try {
            // calculate resource path
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
            resourcePath = authorizationManager.computePathOnMount(resourcePath);
            org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantID).getAuthorizationManager();
            if (registry.resourceExists(govRelativePath)) {
                // set anonymous user permission to RXTs
                authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
                continue;
            }
            String rxt = FileUtil.readFileToString(rxtDir + File.separator + rxtPath);
            Resource resource = registry.newResource();
            resource.setContent(rxt.getBytes(Charset.defaultCharset()));
            resource.setMediaType(APIConstants.RXT_MEDIA_TYPE);
            registry.put(govRelativePath, resource);
            authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
        } catch (UserStoreException e) {
            throw new APIManagementException("Error while adding role permissions to API", e);
        } catch (IOException e) {
            String msg = "Failed to read rxt files";
            throw new APIManagementException(msg, e);
        } catch (RegistryException e) {
            String msg = "Failed to add rxt to registry ";
            throw new APIManagementException(msg, e);
        }
    }
}
Also used : AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) IOException(java.io.IOException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) FilenameFilter(java.io.FilenameFilter) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) File(java.io.File)

Example 88 with UserRegistry

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

the class TerminationTask method invokeProtocolHandler.

private synchronized void invokeProtocolHandler(ExitProtocolMessage message) {
    OMElement payload = message.toOM();
    Options options = new Options();
    options.setTo(new EndpointReference(message.getTaskProtocolHandlerURL()));
    options.setAction(WSConstants.WS_HT_COORDINATION_PROTOCOL_EXIT_ACTION);
    options.setTransportInProtocol(org.apache.axis2.Constants.TRANSPORT_HTTPS);
    ServiceClient serviceClient = null;
    try {
        serviceClient = new ServiceClient();
        serviceClient.setOptions(options);
        // Setting basic auth headers.
        String tenantDomain = MultitenantUtils.getTenantDomainFromUrl(message.getTaskProtocolHandlerURL());
        if (message.getTaskProtocolHandlerURL().equals(tenantDomain)) {
            // this is a Super tenant registration service
            CarbonUtils.setBasicAccessSecurityHeaders(CoordinationConfiguration.getInstance().getProtocolHandlerAdminUser(), CoordinationConfiguration.getInstance().getProtocolHandlerAdminPassword(), serviceClient);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Sending exit protocol message to tenant domain: " + tenantDomain);
            }
            // Tenant's registration service
            String username = "";
            String password = "";
            try {
                UserRegistry configSystemRegistry = B4PContentHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantID);
                Resource taskCoordination = configSystemRegistry.get(REG_TASK_COORDINATION);
                if (taskCoordination != null) {
                    username = taskCoordination.getProperty(USERNAME);
                    password = taskCoordination.getProperty(PASSWORD);
                } else {
                    log.error("Task coordination is not configured for tenant : " + tenantDomain + ". Dropping Exit Coordination message. Affected Tasks ids : " + message.getTaskIDs());
                    return;
                }
            } catch (RegistryException e) {
                log.warn("Error while accessing Registry Service for tenant : " + tenantDomain + ". Dropping Exit Coordination message. Affected Tasks ids : " + message.getTaskIDs(), e);
                return;
            }
            CarbonUtils.setBasicAccessSecurityHeaders(username, password, serviceClient);
        }
        serviceClient.fireAndForget(payload);
        if (log.isDebugEnabled()) {
            log.debug("Sent exit protocol message to " + message.getTaskProtocolHandlerURL());
        }
    } catch (AxisFault axisFault) {
        log.error("Error occurred while invoking HT Protocol Handler " + message.getTaskProtocolHandlerURL() + ". Affected Tasks ids : " + message.getTaskIDs(), axisFault);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) Options(org.apache.axis2.client.Options) ServiceClient(org.apache.axis2.client.ServiceClient) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) OMElement(org.apache.axiom.om.OMElement) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 89 with UserRegistry

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

the class GraphQLSchemaDefinition method saveGraphQLSchemaDefinition.

/**
 * This method saves schema definition of GraphQL APIs in the registry
 *
 * @param api              API to be saved
 * @param schemaDefinition Graphql API definition as String
 * @param registry         user registry
 * @throws APIManagementException
 */
public void saveGraphQLSchemaDefinition(API api, String schemaDefinition, Registry registry) throws APIManagementException {
    String apiName = api.getId().getApiName();
    String apiVersion = api.getId().getVersion();
    String apiProviderName = api.getId().getProviderName();
    String resourcePath = APIUtil.getGraphqlDefinitionFilePath(apiName, apiVersion, apiProviderName);
    try {
        String saveResourcePath = resourcePath + apiProviderName + APIConstants.GRAPHQL_SCHEMA_PROVIDER_SEPERATOR + apiName + apiVersion + APIConstants.GRAPHQL_SCHEMA_FILE_EXTENSION;
        Resource resource;
        if (!registry.resourceExists(saveResourcePath)) {
            resource = registry.newResource();
        } else {
            resource = registry.get(saveResourcePath);
        }
        resource.setContent(schemaDefinition);
        resource.setMediaType(String.valueOf(ContentType.TEXT_PLAIN));
        registry.put(saveResourcePath, resource);
        if (log.isDebugEnabled()) {
            log.debug("Successfully imported the schema: " + schemaDefinition);
        }
        String[] visibleRoles = null;
        if (api.getVisibleRoles() != null) {
            visibleRoles = api.getVisibleRoles().split(",");
        }
        // Need to set anonymous if the visibility is public
        APIUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
        APIUtil.setResourcePermissions(apiProviderName, api.getVisibility(), visibleRoles, resourcePath);
    } catch (RegistryException e) {
        String errorMessage = "Error while adding Graphql Definition for " + apiName + '-' + apiVersion;
        log.error(errorMessage, e);
        handleException(errorMessage, e);
    }
}
Also used : Resource(org.wso2.carbon.registry.api.Resource) RegistryException(org.wso2.carbon.registry.api.RegistryException)

Example 90 with UserRegistry

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

the class OASParserUtil method saveAPIDefinition.

/**
 * This method saves api definition json in the registry
 *
 * @param api               API to be saved
 * @param apiDefinitionJSON API definition as JSON string
 * @param registry          user registry
 * @throws APIManagementException
 */
public static void saveAPIDefinition(API api, String apiDefinitionJSON, Registry registry) throws APIManagementException {
    String apiName = api.getId().getApiName();
    String apiVersion = api.getId().getVersion();
    String apiProviderName = api.getId().getProviderName();
    try {
        String resourcePath = APIUtil.getOpenAPIDefinitionFilePath(apiName, apiVersion, apiProviderName);
        resourcePath = resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
        Resource resource;
        if (!registry.resourceExists(resourcePath)) {
            resource = registry.newResource();
        } else {
            resource = registry.get(resourcePath);
        }
        resource.setContent(apiDefinitionJSON);
        resource.setMediaType("application/json");
        registry.put(resourcePath, resource);
        String[] visibleRoles = null;
        if (api.getVisibleRoles() != null) {
            visibleRoles = api.getVisibleRoles().split(",");
        }
        // Need to set anonymous if the visibility is public
        APIUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
        APIUtil.setResourcePermissions(apiProviderName, api.getVisibility(), visibleRoles, resourcePath);
    } catch (RegistryException e) {
        handleException("Error while adding Swagger Definition for " + apiName + '-' + apiVersion, e);
    }
}
Also used : APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) Resource(org.wso2.carbon.registry.api.Resource) RegistryException(org.wso2.carbon.registry.api.RegistryException)

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