Search in sources :

Example 1 with Tenant

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

the class RestCallUtilImpl method rsaSignedFetchUserRequest.

/**
 * {@inheritDoc}
 */
@Override
public HttpResponse rsaSignedFetchUserRequest(URI uri, String username, String userTenantDomain, String rsaSignedToken, MediaType acceptContentType) throws APIManagementException {
    if (uri == null) {
        throw new IllegalArgumentException("The URI must not be null");
    }
    if (username == null) {
        throw new IllegalArgumentException("UserName must not be null");
    }
    if (userTenantDomain == null) {
        throw new IllegalArgumentException("User tenant domain must not be null");
    }
    if (rsaSignedToken == null) {
        throw new IllegalArgumentException("RSA signed token must not be null");
    }
    HttpURLConnection httpConnection = null;
    try {
        JSONObject loginInfoJsonObj = new JSONObject();
        loginInfoJsonObj.put(APIMgtConstants.FunctionsConstants.USERNAME, username);
        loginInfoJsonObj.put(APIMgtConstants.FunctionsConstants.USER_TENANT_DOMAIN, userTenantDomain);
        httpConnection = (HttpURLConnection) uri.toURL().openConnection();
        httpConnection.setRequestMethod(APIMgtConstants.FunctionsConstants.POST);
        httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        httpConnection.setDoOutput(true);
        httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.RSA_SIGNED_TOKEN, rsaSignedToken);
        if (acceptContentType != null) {
            httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.ACCEPT, acceptContentType.toString());
        }
        OutputStream outputStream = httpConnection.getOutputStream();
        outputStream.write(loginInfoJsonObj.toString().getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
        return getResponse(httpConnection);
    } catch (IOException e) {
        throw new APIManagementException("Connection not established properly ", e);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OutputStream(java.io.OutputStream) IOException(java.io.IOException)

Example 2 with Tenant

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

the class AbstractAPIManager method getSwaggerDefinitionTimeStamps.

/**
 * gets the swagger definition timestamps as a map
 *
 * @param apiIdentifier
 * @return
 * @throws APIManagementException
 */
public Map<String, String> getSwaggerDefinitionTimeStamps(APIIdentifier apiIdentifier) throws APIManagementException {
    String apiTenantDomain = getTenantDomain(apiIdentifier);
    try {
        Registry registryType;
        // Tenant store anonymous mode if current tenant and the required tenant is not matching
        if (this.tenantDomain == null || isTenantDomainNotMatching(apiTenantDomain)) {
            int tenantId = getTenantManager().getTenantId(apiTenantDomain);
            registryType = getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
        } else {
            registryType = registry;
        }
        return OASParserUtil.getAPIOpenAPIDefinitionTimeStamps(apiIdentifier, registryType);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        log.error("Error while getting the lastUpdated time due to " + e.getMessage(), e);
    } catch (RegistryException e) {
        log.debug("Error while getting the lastUpdated time due to " + e.getMessage(), e);
    }
    return null;
}
Also used : UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 3 with Tenant

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

the class AbstractAPIManager method searchPaginatedAPIs.

@Override
public Map<String, Object> searchPaginatedAPIs(String searchQuery, String requestedTenantDomain, int start, int end, boolean isLazyLoad, boolean isPublisherListing) throws APIManagementException {
    Map<String, Object> result = new HashMap<String, Object>();
    boolean isTenantFlowStarted = false;
    String[] searchQueries = searchQuery.split("&");
    StringBuilder filteredQuery = new StringBuilder();
    String subQuery = null;
    if (log.isDebugEnabled()) {
        log.debug("Original search query received : " + searchQuery);
    }
    // Filtering the queries related with custom properties
    for (String query : searchQueries) {
        if (searchQuery.startsWith(APIConstants.DOCUMENTATION_SEARCH_TYPE_PREFIX)) {
            subQuery = query;
            break;
        }
        // If the query does not contains "=" then it is an errornous scenario.
        if (query.contains("=")) {
            String[] searchKeys = query.split("=");
            if (searchKeys.length >= 2) {
                if (!Arrays.asList(APIConstants.API_SEARCH_PREFIXES).contains(searchKeys[0].toLowerCase())) {
                    if (log.isDebugEnabled()) {
                        log.debug(searchKeys[0] + " does not match with any of the reserved key words. Hence" + " appending " + APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX + " as prefix");
                    }
                    searchKeys[0] = (APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX + searchKeys[0]);
                }
                // category search should only return results that exactly match.
                if (searchKeys[0].equals(APIConstants.LABEL_SEARCH_TYPE_PREFIX)) {
                    searchKeys[0] = APIConstants.API_LABELS_GATEWAY_LABELS;
                    searchKeys[1] = searchKeys[1].replace("*", "");
                } else if (searchKeys[0].equals(APIConstants.CATEGORY_SEARCH_TYPE_PREFIX)) {
                    searchKeys[0] = APIConstants.API_CATEGORIES_CATEGORY_NAME;
                    searchKeys[1] = searchKeys[1].replace("*", "");
                }
                if (filteredQuery.length() == 0) {
                    filteredQuery.append(searchKeys[0]).append("=").append(searchKeys[1]);
                } else {
                    filteredQuery.append("&").append(searchKeys[0]).append("=").append(searchKeys[1]);
                }
            }
        } else {
            filteredQuery.append(query);
        }
    }
    searchQuery = filteredQuery.toString();
    if (log.isDebugEnabled()) {
        log.debug("Final search query after the post processing for the custom properties : " + 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);
            APIUtil.loadTenantRegistry(tenantIDLocal);
            userRegistry = getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantIDLocal);
            userNameLocal = CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME;
            if (!requestedTenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                APIUtil.loadTenantConfigBlockingMode(requestedTenantDomain);
            }
        } else {
            userRegistry = this.registry;
            tenantIDLocal = tenantId;
        }
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userNameLocal);
        if (subQuery != null && subQuery.startsWith(APIConstants.DOCUMENTATION_SEARCH_TYPE_PREFIX)) {
            Map<Documentation, API> apiDocMap = searchAPIDoc(userRegistry, tenantIDLocal, userNameLocal, subQuery.split("=")[1]);
            result.put("apis", apiDocMap);
            /*Pagination for Document search results is not supported yet, hence length is sent as end-start*/
            if (apiDocMap.isEmpty()) {
                result.put("length", 0);
            } else {
                result.put("length", end - start);
            }
        } else if (searchQuery != null && searchQuery.startsWith(APIConstants.CONTENT_SEARCH_TYPE_PREFIX)) {
            result = searchPaginatedAPIsByContent(userRegistry, tenantIDLocal, searchQuery, start, end, isLazyLoad);
        } else {
            result = searchPaginatedAPIs(userRegistry, tenantIDLocal, searchQuery, start, end, isLazyLoad, isPublisherListing);
        }
    } catch (Exception e) {
        String msg = "Failed to Search APIs";
        throw new APIManagementException(msg, e);
    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
    return result;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) 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) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API)

Example 4 with Tenant

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

the class AbstractAPIManager method getGraphqlSchemaDefinition.

/**
 * Returns the graphQL content in registry specified by the wsdl name
 *
 * @param apiId Api Identifier
 * @return graphQL content matching name if exist else null
 */
@Override
public String getGraphqlSchemaDefinition(APIIdentifier apiId) throws APIManagementException {
    String apiTenantDomain = getTenantDomain(apiId);
    String schema;
    try {
        Registry registryType;
        // Tenant store anonymous mode if current tenant and the required tenant is not matching
        if (this.tenantDomain == null || isTenantDomainNotMatching(apiTenantDomain)) {
            int tenantId = getTenantManager().getTenantId(apiTenantDomain);
            registryType = getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
        } else {
            registryType = registry;
        }
        schema = schemaDef.getGraphqlSchemaDefinition(apiId, registryType);
    } catch (org.wso2.carbon.user.api.UserStoreException | RegistryException e) {
        String msg = "Failed to get graphql schema definition of Graphql API : " + apiId;
        throw new APIManagementException(msg, e);
    }
    return schema;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 5 with Tenant

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

the class AbstractAPIManager method getApplicationByUUID.

/**
 * Returns the corresponding application given the uuid with keys for a specific tenant.
 *
 * @param uuid         uuid of the Application.
 * @param tenantDomain domain of the accessed store.
 * @return it will return Application corresponds to the uuid provided.
 * @throws APIManagementException
 */
public Application getApplicationByUUID(String uuid, String tenantDomain) throws APIManagementException {
    Application application = apiMgtDAO.getApplicationByUUID(uuid);
    if (application != null) {
        Set<APIKey> keys = getApplicationKeys(application.getId(), tenantDomain);
        for (APIKey key : keys) {
            if (APIConstants.JWT.equals(application.getTokenType())) {
                key.setAccessToken("");
            }
            application.addKey(key);
        }
        int subscriptionCount = apiMgtDAO.getSubscriptionCountByApplicationId(application, tenantDomain);
        application.setSubscriptionCount(subscriptionCount);
    }
    return application;
}
Also used : APIKey(org.wso2.carbon.apimgt.api.model.APIKey) Application(org.wso2.carbon.apimgt.api.model.Application)

Aggregations

UserStoreException (org.wso2.carbon.user.api.UserStoreException)194 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)180 ArrayList (java.util.ArrayList)177 SQLException (java.sql.SQLException)170 PreparedStatement (java.sql.PreparedStatement)156 Connection (java.sql.Connection)155 HashMap (java.util.HashMap)128 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)110 ResultSet (java.sql.ResultSet)107 IOException (java.io.IOException)98 Map (java.util.Map)78 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)77 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)71 RealmService (org.wso2.carbon.user.core.service.RealmService)64 IdentityProvider (org.wso2.carbon.identity.application.common.model.IdentityProvider)55 Test (org.testng.annotations.Test)54 List (java.util.List)50 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)48 PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)48 IdentityApplicationManagementException (org.wso2.carbon.identity.application.common.IdentityApplicationManagementException)48