Search in sources :

Example 96 with APIManagerConfiguration

use of org.wso2.carbon.apimgt.impl.APIManagerConfiguration in project carbon-apimgt by wso2.

the class TokenMgtDataHolder method initData.

public static void initData() {
    try {
        APIManagerConfiguration configuration = org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
        if (configuration == null) {
            log.error("API Manager configuration is not initialized");
        } else {
            applicationTokenScope = configuration.getFirstProperty(APIConstants.APPLICATION_TOKEN_SCOPE);
            JWTConfigurationDto jwtConfigurationDto = configuration.getJwtConfigurationDto();
            if (log.isDebugEnabled()) {
                log.debug("JWTGeneration enabled : " + jwtConfigurationDto.isEnabled());
            }
        }
    } catch (Exception e) {
        log.error("Error occur while initializing API KeyMgt Data Holder.Default configuration will be used." + e.toString());
    }
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) JWTConfigurationDto(org.wso2.carbon.apimgt.common.gateway.dto.JWTConfigurationDto)

Example 97 with APIManagerConfiguration

use of org.wso2.carbon.apimgt.impl.APIManagerConfiguration in project carbon-apimgt by wso2.

the class APIProviderImpl method getSubscriberClaims.

/**
 * Returns the claims of subscriber for the given subscriber.
 *
 * @param subscriber The name of the subscriber to be returned
 * @return The looked up claims of the subscriber or null if the requested subscriber does not exist
 * @throws APIManagementException if failed to get Subscriber
 */
@Override
public Map<String, String> getSubscriberClaims(String subscriber) throws APIManagementException {
    String tenantDomain = MultitenantUtils.getTenantDomain(subscriber);
    int tenantId = 0;
    Map<String, String> claimMap = new HashMap<>();
    Map<String, String> subscriberClaims = null;
    String configuredClaims = "";
    try {
        tenantId = getTenantId(tenantDomain);
        UserStoreManager userStoreManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getUserStoreManager();
        if (userStoreManager.isExistingUser(subscriber)) {
            subscriberClaims = APIUtil.getClaims(subscriber, tenantId, ClaimsRetriever.DEFAULT_DIALECT_URI);
            APIManagerConfiguration configuration = getAPIManagerConfiguration();
            configuredClaims = configuration.getFirstProperty(APIConstants.API_PUBLISHER_SUBSCRIBER_CLAIMS);
        }
        for (String claimURI : configuredClaims.split(",")) {
            if (subscriberClaims != null) {
                claimMap.put(claimURI, subscriberClaims.get(claimURI));
            }
        }
    } catch (UserStoreException e) {
        throw new APIManagementException("Error while retrieving tenant id for tenant domain " + tenantDomain, e);
    }
    return claimMap;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Example 98 with APIManagerConfiguration

use of org.wso2.carbon.apimgt.impl.APIManagerConfiguration in project carbon-apimgt by wso2.

the class APIProviderImpl method propergateAPIStatusChangeToGateways.

public Map<String, String> propergateAPIStatusChangeToGateways(String newStatus, API api) throws APIManagementException {
    Map<String, String> failedGateways = new HashMap<String, String>();
    APIIdentifier identifier = api.getId();
    String providerTenantMode = identifier.getProviderName();
    String name = identifier.getApiName();
    String version = identifier.getVersion();
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerTenantMode));
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        if (api != null) {
            String currentStatus = api.getStatus();
            if (APIConstants.PUBLISHED.equals(newStatus) || !currentStatus.equals(newStatus)) {
                api.setStatus(newStatus);
                APIManagerConfiguration config = getAPIManagerConfiguration();
                String gatewayType = config.getFirstProperty(APIConstants.API_GATEWAY_TYPE);
                api.setAsPublishedDefaultVersion(api.getId().getVersion().equals(apiMgtDAO.getPublishedDefaultVersion(api.getId())));
                loadMediationPoliciesToAPI(api, tenantDomain);
            }
        } else {
            handleException("Couldn't find an API with the name-" + name + "version-" + version);
        }
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return failedGateways;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 99 with APIManagerConfiguration

use of org.wso2.carbon.apimgt.impl.APIManagerConfiguration in project carbon-apimgt by wso2.

the class APIProviderImpl method updateDocumentPermissions.

private void updateDocumentPermissions(API api, API oldApi) throws APIManagementException {
    boolean updatePermissions = false;
    if (APIUtil.isAccessControlEnabled()) {
        if (!oldApi.getAccessControl().equals(api.getAccessControl()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getAccessControl()) && !api.getAccessControlRoles().equals(oldApi.getAccessControlRoles())) || !oldApi.getVisibility().equals(api.getVisibility()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getVisibility()) && !api.getVisibleRoles().equals(oldApi.getVisibleRoles()))) {
            updatePermissions = true;
        }
    } else if (!oldApi.getVisibility().equals(api.getVisibility()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getVisibility()) && !api.getVisibleRoles().equals(oldApi.getVisibleRoles()))) {
        updatePermissions = true;
    }
    String visibleRolesList = api.getVisibleRoles();
    String[] visibleRoles = new String[0];
    if (visibleRolesList != null) {
        visibleRoles = visibleRolesList.split(",");
    }
    // TODO check if registry.beginTransaction(); flow is needed
    List<Documentation> docs = getAllDocumentation(api.getId());
    if (updatePermissions) {
        APIManagerConfiguration config = getAPIManagerConfiguration();
        boolean isSetDocLevelPermissions = Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_API_DOC_VISIBILITY_LEVELS));
        String docRootPath = APIUtil.getAPIDocPath(api.getId());
        if (isSetDocLevelPermissions) {
            for (Documentation doc : docs) {
                if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
                    String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
                    APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
                    if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
                        String contentPath = APIUtil.getAPIDocContentPath(api.getId(), doc.getName());
                        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, contentPath, registry);
                    } else if (Documentation.DocumentSourceType.FILE.equals(doc.getSourceType()) && doc.getFilePath() != null) {
                        String filePath = APIUtil.getDocumentationFilePath(api.getId(), doc.getFilePath().split("files" + RegistryConstants.PATH_SEPARATOR)[1]);
                        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, filePath, registry);
                    }
                }
            }
        } else {
            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, docRootPath, registry);
        }
    } else {
        if (docs != null) {
            for (Documentation doc : docs) {
                if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
                    String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
                    APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
                }
            }
        }
    }
    // update doc visibility
    if (docs != null) {
        Iterator it = docs.iterator();
        while (it.hasNext()) {
            Object docsObject = it.next();
            Documentation doc = (Documentation) docsObject;
            updateDocVisibility(api, doc);
        }
    }
}
Also used : Documentation(org.wso2.carbon.apimgt.api.model.Documentation) Iterator(java.util.Iterator) JSONObject(org.json.simple.JSONObject)

Example 100 with APIManagerConfiguration

use of org.wso2.carbon.apimgt.impl.APIManagerConfiguration in project carbon-apimgt by wso2.

the class APIProviderImpl method updateApiArtifact.

private String updateApiArtifact(API api, boolean updateMetadata, boolean updatePermissions) throws APIManagementException {
    // Validate Transports
    validateAndSetTransports(api);
    validateAndSetAPISecurity(api);
    boolean transactionCommitted = false;
    String apiUUID = null;
    try {
        registry.beginTransaction();
        String apiArtifactId = registry.get(APIUtil.getAPIPath(api.getId())).getUUID();
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when updating API artifact ID " + api.getId();
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        String oldStatus = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
        Resource apiResource = registry.get(artifact.getPath());
        String oldAccessControlRoles = api.getAccessControlRoles();
        if (apiResource != null) {
            oldAccessControlRoles = registry.get(artifact.getPath()).getProperty(APIConstants.PUBLISHER_ROLES);
        }
        GenericArtifact updateApiArtifact = APIUtil.createAPIArtifactContent(artifact, api);
        String artifactPath = GovernanceUtils.getArtifactPath(registry, updateApiArtifact.getId());
        org.wso2.carbon.registry.core.Tag[] oldTags = registry.getTags(artifactPath);
        if (oldTags != null) {
            for (org.wso2.carbon.registry.core.Tag tag : oldTags) {
                registry.removeTag(artifactPath, tag.getTagName());
            }
        }
        Set<String> tagSet = api.getTags();
        if (tagSet != null) {
            for (String tag : tagSet) {
                registry.applyTag(artifactPath, tag);
            }
        }
        if (updateMetadata && api.getEndpointConfig() != null && !api.getEndpointConfig().isEmpty()) {
            // If WSDL URL get change only we update registry WSDL resource. If its registry resource patch we
            // will skip registry update. Only if this API created with WSDL end point type we need to update
            // wsdls for each update.
            // check for wsdl endpoint
            org.json.JSONObject response1 = new org.json.JSONObject(api.getEndpointConfig());
            boolean isWSAPI = APIConstants.APITransportType.WS.toString().equals(api.getType());
            String wsdlURL;
            if (!APIUtil.isStreamingApi(api) && "wsdl".equalsIgnoreCase(response1.get("endpoint_type").toString()) && response1.has("production_endpoints")) {
                wsdlURL = response1.getJSONObject("production_endpoints").get("url").toString();
                if (APIUtil.isValidWSDLURL(wsdlURL, true)) {
                    String path = APIUtil.createWSDL(registry, api);
                    if (path != null) {
                        // reset the wsdl path to permlink
                        updateApiArtifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
                    }
                }
            }
        }
        artifactManager.updateGenericArtifact(updateApiArtifact);
        // write API Status to a separate property. This is done to support querying APIs using custom query (SQL)
        // to gain performance
        String apiStatus = api.getStatus().toUpperCase();
        saveAPIStatus(artifactPath, apiStatus);
        String[] visibleRoles = new String[0];
        String publisherAccessControlRoles = api.getAccessControlRoles();
        updateRegistryResources(artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
        // propagate api status change and access control roles change to document artifact
        String newStatus = updateApiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
        if (!StringUtils.equals(oldStatus, newStatus) || !StringUtils.equals(oldAccessControlRoles, publisherAccessControlRoles)) {
            APIUtil.notifyAPIStateChangeToAssociatedDocuments(artifact, registry);
        }
        if (updatePermissions) {
            APIUtil.clearResourcePermissions(artifactPath, api.getId(), ((UserRegistry) registry).getTenantId());
            String visibleRolesList = api.getVisibleRoles();
            if (visibleRolesList != null) {
                visibleRoles = visibleRolesList.split(",");
            }
            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
        }
        // attaching api categories to the API
        List<APICategory> attachedApiCategories = api.getApiCategories();
        artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
        if (attachedApiCategories != null) {
            for (APICategory category : attachedApiCategories) {
                artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
            }
        }
        registry.commitTransaction();
        transactionCommitted = true;
        apiUUID = updateApiArtifact.getId();
        if (updatePermissions) {
            APIManagerConfiguration config = getAPIManagerConfiguration();
            boolean isSetDocLevelPermissions = Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_API_DOC_VISIBILITY_LEVELS));
            String docRootPath = APIUtil.getAPIDocPath(api.getId());
            if (isSetDocLevelPermissions) {
                // Retain the docs
                List<Documentation> docs = getAllDocumentation(api.getId());
                for (Documentation doc : docs) {
                    if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
                        String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
                        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
                        if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
                            String contentPath = APIUtil.getAPIDocContentPath(api.getId(), doc.getName());
                            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, contentPath, registry);
                        } else if (Documentation.DocumentSourceType.FILE.equals(doc.getSourceType()) && doc.getFilePath() != null) {
                            String filePath = APIUtil.getDocumentationFilePath(api.getId(), doc.getFilePath().split("files" + RegistryConstants.PATH_SEPARATOR)[1]);
                            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, filePath, registry);
                        }
                    }
                }
            } else {
                APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, docRootPath, registry);
            }
        } else {
            // In order to support content search feature - we need to update resource permissions of document resources
            // if their visibility is set to API level.
            List<Documentation> docs = getAllDocumentation(api.getId());
            if (docs != null) {
                for (Documentation doc : docs) {
                    if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
                        String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
                        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
                    }
                }
            }
        }
    } catch (Exception e) {
        try {
            registry.rollbackTransaction();
        } catch (RegistryException re) {
            // Throwing an error from this level will mask the original exception
            log.error("Error while rolling back the transaction for API: " + api.getId().getApiName(), re);
        }
        handleException("Error while performing registry transaction operation", e);
    } finally {
        try {
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException ex) {
            handleException("Error occurred while rolling back the transaction.", ex);
        }
    }
    return apiUUID;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) 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) JSONObject(org.json.simple.JSONObject) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Aggregations

APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)122 Test (org.junit.Test)76 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)67 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)51 HashMap (java.util.HashMap)39 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)36 RealmService (org.wso2.carbon.user.core.service.RealmService)33 APIManagerConfigurationService (org.wso2.carbon.apimgt.impl.APIManagerConfigurationService)31 ArrayList (java.util.ArrayList)26 API (org.wso2.carbon.apimgt.api.model.API)25 Before (org.junit.Before)24 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)24 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)24 ThrottleProperties (org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)23 TenantManager (org.wso2.carbon.user.core.tenant.TenantManager)23 ApiMgtDAO (org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO)22 MessageContext (org.apache.synapse.MessageContext)20 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)20 Cache (javax.cache.Cache)19 Map (java.util.Map)18