Search in sources :

Example 36 with Tenant

use of org.wso2.carbon.user.api.Tenant in project carbon-apimgt by wso2.

the class AbstractAPIManager method getAllDocumentation.

public List<Documentation> getAllDocumentation(APIIdentifier apiId, String loggedUsername) throws APIManagementException {
    List<Documentation> documentationList = new ArrayList<Documentation>();
    try {
        String tenantDomain = getTenantDomain(apiId);
        Registry registryType;
        /* If the API provider is a tenant, load tenant registry*/
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
            // Tenant store anonymous mode
            int tenantId = getTenantManager().getTenantId(tenantDomain);
            registryType = getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
        } else {
            registryType = registry;
        }
        String apiOrAPIProductDocPath = APIUtil.getAPIOrAPIProductDocPath(apiId);
        String pathToContent = apiOrAPIProductDocPath + APIConstants.INLINE_DOCUMENT_CONTENT_DIR;
        String pathToDocFile = apiOrAPIProductDocPath + APIConstants.DOCUMENT_FILE_DIR;
        if (registry.resourceExists(apiOrAPIProductDocPath)) {
            Resource resource = registry.get(apiOrAPIProductDocPath);
            if (resource instanceof org.wso2.carbon.registry.core.Collection) {
                String[] docsPaths = ((org.wso2.carbon.registry.core.Collection) resource).getChildren();
                for (String docPath : docsPaths) {
                    if (!(docPath.equalsIgnoreCase(pathToContent) || docPath.equalsIgnoreCase(pathToDocFile))) {
                        Resource docResource = registry.get(docPath);
                        GenericArtifactManager artifactManager = getAPIGenericArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
                        GenericArtifact docArtifact = artifactManager.getGenericArtifact(docResource.getUUID());
                        Documentation doc = APIUtil.getDocumentation(docArtifact, apiId.getProviderName());
                        Date contentLastModifiedDate;
                        Date docLastModifiedDate = docResource.getLastModified();
                        if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType())) {
                            String contentPath = APIUtil.getAPIDocContentPath(apiId, doc.getName());
                            try {
                                contentLastModifiedDate = registryType.get(contentPath).getLastModified();
                                doc.setLastUpdated((contentLastModifiedDate.after(docLastModifiedDate) ? contentLastModifiedDate : docLastModifiedDate));
                            } catch (org.wso2.carbon.registry.core.secure.AuthorizationFailedException e) {
                            // do nothing. Permission not allowed to access the doc.
                            }
                        } else if (Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
                            String contentPath = APIUtil.getAPIDocContentPath(apiId, doc.getName());
                            try {
                                contentLastModifiedDate = registryType.get(contentPath).getLastModified();
                                doc.setLastUpdated((contentLastModifiedDate.after(docLastModifiedDate) ? contentLastModifiedDate : docLastModifiedDate));
                            } catch (org.wso2.carbon.registry.core.secure.AuthorizationFailedException e) {
                            // do nothing. Permission not allowed to access the doc.
                            }
                        } else {
                            doc.setLastUpdated(docLastModifiedDate);
                        }
                        documentationList.add(doc);
                    }
                }
            }
        }
    } catch (RegistryException e) {
        String msg = "Failed to get documentations for api " + apiId.getApiName();
        throw new APIManagementException(msg, e);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String msg = "Failed to get documentations for api " + apiId.getApiName();
        throw new APIManagementException(msg, e);
    }
    return documentationList;
}
Also used : ArrayList(java.util.ArrayList) 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) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Date(java.util.Date) Collection(org.wso2.carbon.registry.core.Collection)

Example 37 with Tenant

use of org.wso2.carbon.user.api.Tenant in project carbon-apimgt by wso2.

the class AbstractAPIManager method searchPaginatedAPIProducts.

@Override
public Map<String, Object> searchPaginatedAPIProducts(String searchQuery, String requestedTenantDomain, int start, int end) throws APIManagementException {
    Map<String, Object> result = new HashMap<String, Object>();
    boolean isTenantFlowStarted = false;
    if (log.isDebugEnabled()) {
        log.debug("Original search query received : " + searchQuery);
    }
    try {
        boolean isTenantMode = (requestedTenantDomain != null);
        if (isTenantMode && !org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(requestedTenantDomain)) {
            isTenantFlowStarted = true;
            startTenantFlow(requestedTenantDomain);
        } else {
            requestedTenantDomain = org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
            isTenantFlowStarted = true;
            startTenantFlow(requestedTenantDomain);
        }
        Registry userRegistry;
        int tenantIDLocal = 0;
        String userNameLocal = this.username;
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(requestedTenantDomain))) {
            // Tenant store anonymous mode
            tenantIDLocal = getTenantManager().getTenantId(requestedTenantDomain);
            userRegistry = getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantIDLocal);
            userNameLocal = CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME;
        } else {
            userRegistry = this.registry;
            tenantIDLocal = tenantId;
        }
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userNameLocal);
        result = searchPaginatedAPIProducts(userRegistry, getSearchQuery(searchQuery), start, end);
    } catch (Exception e) {
        String msg = "Failed to Search APIs";
        throw new APIManagementException(msg, e);
    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
    return result;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) JSONObject(org.json.simple.JSONObject) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) JSONException(org.json.JSONException) XMLStreamException(javax.xml.stream.XMLStreamException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) BlockConditionNotFoundException(org.wso2.carbon.apimgt.api.BlockConditionNotFoundException) PolicyNotFoundException(org.wso2.carbon.apimgt.api.PolicyNotFoundException) IOException(java.io.IOException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationNameWhiteSpaceValidationException(org.wso2.carbon.apimgt.api.ApplicationNameWhiteSpaceValidationException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) ParseException(org.json.simple.parser.ParseException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) ApplicationNameWithInvalidCharactersException(org.wso2.carbon.apimgt.api.ApplicationNameWithInvalidCharactersException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)

Example 38 with Tenant

use of org.wso2.carbon.user.api.Tenant in project carbon-apimgt by wso2.

the class DefaultGroupIDExtractorImpl method getGroupingIdentifiers.

public String getGroupingIdentifiers(String loginResponse) {
    JSONObject obj;
    String username = null;
    Boolean isSuperTenant;
    int tenantId = MultitenantConstants.SUPER_TENANT_ID;
    String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI);
    if (StringUtils.isBlank(claim)) {
        claim = "http://wso2.org/claims/organization";
    }
    String organization = null;
    try {
        obj = new JSONObject(loginResponse);
        username = (String) obj.get("user");
        isSuperTenant = (Boolean) obj.get("isSuperTenant");
        RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
        // if the user is not in the super tenant domain then find the domain name and tenant id.
        if (!isSuperTenant) {
            tenantDomain = MultitenantUtils.getTenantDomain(username);
            tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        }
        UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId);
        UserStoreManager manager = realm.getUserStoreManager();
        organization = manager.getUserClaimValue(MultitenantUtils.getTenantAwareUsername(username), claim, null);
        if (organization != null) {
            organization = tenantDomain + "/" + organization.trim();
        }
    } catch (JSONException e) {
        log.error("Exception occured while trying to get group Identifier from login response", e);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        log.error("Error while checking user existence for " + username, e);
    }
    return organization;
}
Also used : JSONException(org.json.JSONException) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) JSONObject(org.json.JSONObject) UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService)

Example 39 with Tenant

use of org.wso2.carbon.user.api.Tenant in project carbon-apimgt by wso2.

the class CacheInvalidationServiceImpl method invalidateResourceCache.

@Override
public void invalidateResourceCache(String apiContext, String apiVersion, ResourceCacheInvalidationDto[] uriTemplates) {
    boolean isTenantFlowStarted = false;
    int tenantDomainIndex = apiContext.indexOf("/t/");
    String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    if (tenantDomainIndex != -1) {
        String temp = apiContext.substring(tenantDomainIndex + 3, apiContext.length());
        tenantDomain = temp.substring(0, temp.indexOf('/'));
    }
    try {
        isTenantFlowStarted = startTenantFlow(tenantDomain);
        Cache cache = CacheProvider.getResourceCache();
        if (apiContext.contains(APIConstants.POLICY_CACHE_CONTEXT)) {
            if (log.isDebugEnabled()) {
                log.debug("Cleaning cache for policy update for tenant " + tenantDomain);
            }
            cache.removeAll();
        } else {
            String apiCacheKey = APIUtil.getAPIInfoDTOCacheKey(apiContext, apiVersion);
            if (cache.containsKey(apiCacheKey)) {
                cache.remove(apiCacheKey);
            }
            for (ResourceCacheInvalidationDto uriTemplate : uriTemplates) {
                String resourceVerbCacheKey = APIUtil.getResourceInfoDTOCacheKey(apiContext, apiVersion, uriTemplate.getResourceURLContext(), uriTemplate.getHttpVerb());
                if (cache.containsKey(resourceVerbCacheKey)) {
                    cache.remove(resourceVerbCacheKey);
                }
            }
        }
    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
}
Also used : ResourceCacheInvalidationDto(org.wso2.carbon.apimgt.api.dto.ResourceCacheInvalidationDto) Cache(javax.cache.Cache)

Example 40 with Tenant

use of org.wso2.carbon.user.api.Tenant in project carbon-apimgt by wso2.

the class APIStateChangeWSWorkflowExecutor method complete.

/**
 * Complete the API state change workflow process.
 */
@Override
public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Completing API State change Workflow..");
        log.debug("response: " + workflowDTO.toString());
    }
    workflowDTO.setUpdatedTime(System.currentTimeMillis());
    super.complete(workflowDTO);
    String action = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_API_LC_ACTION);
    String apiName = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_APINAME);
    String providerName = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_APIPROVIDER);
    String version = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_APIVERSION);
    String invoker = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_INVOKER);
    String currentStatus = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_APISTATE);
    int tenantId = workflowDTO.getTenantId();
    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    try {
        // tenant flow is already started from the rest api service impl. no need to start from here
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(invoker);
        Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(invoker, tenantId);
        APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, version);
        GenericArtifact apiArtifact = APIUtil.getAPIArtifact(apiIdentifier, registry);
        if (WorkflowStatus.APPROVED.equals(workflowDTO.getStatus())) {
            String targetStatus;
            apiArtifact.invokeAction(action, APIConstants.API_LIFE_CYCLE);
            targetStatus = apiArtifact.getLifecycleState();
            if (!currentStatus.equals(targetStatus)) {
                apiMgtDAO.recordAPILifeCycleEvent(apiArtifact.getId(), currentStatus.toUpperCase(), targetStatus.toUpperCase(), invoker, tenantId);
            }
            if (log.isDebugEnabled()) {
                String logMessage = "API Status changed successfully. API Name: " + apiIdentifier.getApiName() + ", API Version " + apiIdentifier.getVersion() + ", New Status : " + targetStatus;
                log.debug(logMessage);
            }
        }
    } catch (RegistryException e) {
        String errorMsg = "Could not complete api state change workflow";
        log.error(errorMsg, e);
        throw new WorkflowException(errorMsg, e);
    } catch (APIManagementException e) {
        String errorMsg = "Could not complete api state change workflow";
        log.error(errorMsg, e);
        throw new WorkflowException(errorMsg, e);
    }
    return new GeneralWorkflowResponse();
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)180 UserStoreException (org.wso2.carbon.user.api.UserStoreException)88 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)83 ArrayList (java.util.ArrayList)79 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)70 PreparedStatement (java.sql.PreparedStatement)51 SQLException (java.sql.SQLException)50 IOException (java.io.IOException)49 Connection (java.sql.Connection)49 HashMap (java.util.HashMap)44 ResultSet (java.sql.ResultSet)43 JSONObject (org.json.simple.JSONObject)41 Resource (org.wso2.carbon.registry.core.Resource)40 Registry (org.wso2.carbon.registry.core.Registry)38 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)34 API (org.wso2.carbon.apimgt.api.model.API)34 Test (org.junit.Test)33 File (java.io.File)32 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)32 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)30