Search in sources :

Example 16 with LOCAL

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.LOCAL in project carbon-apimgt by wso2.

the class GAConfigMediaTypeHandler method put.

public void put(RequestContext requestContext) throws RegistryException {
    ResourceImpl resource = (ResourceImpl) requestContext.getResource();
    if (!resource.isContentModified()) {
        return;
    }
    // Local entry is updated only if the content of ga-config is updated
    Object content = resource.getContent();
    if (!(content instanceof String)) {
        if (!(content instanceof byte[])) {
            log.warn("The resource content is not of expected type");
            return;
        }
    }
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
    GoogleAnalyticsConfigEvent googleAnalyticsConfigEvent = new GoogleAnalyticsConfigEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.GA_CONFIG_UPDATE.toString(), tenantId, tenantDomain);
    APIUtil.sendNotification(googleAnalyticsConfigEvent, APIConstants.NotifierType.GA_CONFIG.name());
}
Also used : ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) GoogleAnalyticsConfigEvent(org.wso2.carbon.apimgt.impl.notifier.events.GoogleAnalyticsConfigEvent)

Example 17 with LOCAL

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.LOCAL in project carbon-apimgt by wso2.

the class APIConsumerImpl method isCandidateAPI.

private boolean isCandidateAPI(String apiPath, String loggedUsername, GenericArtifactManager artifactManager, int tenantId, boolean showAllAPIs, boolean allowMultipleVersions, String apiOwner, String providerId, Registry registry, Map<String, API> apiCollection) throws UserStoreException, RegistryException, APIManagementException {
    AuthorizationManager manager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
    Comparator<API> versionComparator = new APIVersionComparator();
    Resource resource;
    String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + apiPath);
    boolean checkAuthorized;
    String userNameWithoutDomain = loggedUsername;
    if (!loggedUsername.isEmpty() && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(super.tenantDomain)) {
        String[] nameParts = loggedUsername.split("@");
        userNameWithoutDomain = nameParts[0];
    }
    int loggedInUserTenantDomain = -1;
    if (!StringUtils.isEmpty(loggedUsername)) {
        loggedInUserTenantDomain = APIUtil.getTenantId(loggedUsername);
    }
    if (loggedUsername.isEmpty()) {
        // Anonymous user is viewing.
        checkAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
    } else if (tenantId != loggedInUserTenantDomain) {
        // Cross tenant scenario
        providerId = APIUtil.replaceEmailDomainBack(providerId);
        String[] nameParts = providerId.split("@");
        String provideNameWithoutDomain = nameParts[0];
        checkAuthorized = manager.isUserAuthorized(provideNameWithoutDomain, path, ActionConstants.GET);
    } else {
        // Some user is logged in also user and api provider tenant domain are same.
        checkAuthorized = manager.isUserAuthorized(userNameWithoutDomain, path, ActionConstants.GET);
    }
    String apiArtifactId = null;
    if (checkAuthorized) {
        resource = registry.get(apiPath);
        apiArtifactId = resource.getUUID();
    }
    if (apiArtifactId != null) {
        GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
        // check the API status
        String status = APIUtil.getLcStateFromArtifact(artifact);
        API api = null;
        // Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
        if (!showAllAPIs) {
            // then we are only interested in published APIs here...
            if (APIConstants.PUBLISHED.equals(status)) {
                api = APIUtil.getAPI(artifact);
            }
        } else {
            // else we are interested in both deprecated/published APIs here...
            if (APIConstants.PUBLISHED.equals(status) || APIConstants.DEPRECATED.equals(status)) {
                api = APIUtil.getAPI(artifact);
            }
        }
        if (api != null) {
            String apiVisibility = api.getVisibility();
            if (!StringUtils.isEmpty(apiVisibility) && !APIConstants.API_GLOBAL_VISIBILITY.equalsIgnoreCase(apiVisibility)) {
                String providerDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerId));
                String loginUserDomain = MultitenantUtils.getTenantDomain(loggedUsername);
                if (!StringUtils.isEmpty(providerDomain) && !StringUtils.isEmpty(loginUserDomain) && !providerDomain.equals(loginUserDomain)) {
                    return false;
                }
            }
            // apiOwner is the value coming from front end and compared against the API instance
            if (apiOwner != null && !apiOwner.isEmpty()) {
                if (APIUtil.replaceEmailDomainBack(providerId).equals(APIUtil.replaceEmailDomainBack(apiOwner)) && api.getApiOwner() != null && !api.getApiOwner().isEmpty() && !APIUtil.replaceEmailDomainBack(apiOwner).equals(APIUtil.replaceEmailDomainBack(api.getApiOwner()))) {
                    // reject remote APIs when local admin user's API selected
                    return false;
                } else if (!APIUtil.replaceEmailDomainBack(providerId).equals(APIUtil.replaceEmailDomainBack(apiOwner)) && !APIUtil.replaceEmailDomainBack(apiOwner).equals(APIUtil.replaceEmailDomainBack(api.getApiOwner()))) {
                    // reject local admin's APIs when remote API selected
                    return false;
                }
            }
            String key;
            // Check the configuration to allow showing multiple versions of an API true/false
            if (!allowMultipleVersions) {
                // If allow only showing the latest version of an API
                key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                API existingAPI = apiCollection.get(key);
                if (existingAPI != null) {
                    // this one has a higher version number
                    if (versionComparator.compare(api, existingAPI) > 0) {
                        apiCollection.put(key, api);
                        return true;
                    }
                } else {
                    // We haven't seen this API before
                    apiCollection.put(key, api);
                    return true;
                }
            } else {
                // If allow showing multiple versions of an API
                key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName() + COLON_CHAR + api.getId().getVersion();
                // we're not really interested in the key, so generate one for the sake of adding this element to
                // the map.
                key = key + '_' + apiCollection.size();
                apiCollection.put(key, api);
                return true;
            }
        }
    }
    return false;
}
Also used : APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) Resource(org.wso2.carbon.registry.core.Resource) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager)

Example 18 with LOCAL

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.LOCAL in project carbon-apimgt by wso2.

the class APIGatewayAdmin method unDeployAPI.

private void unDeployAPI(CertificateManager certificateManager, SequenceAdminServiceProxy sequenceAdminServiceProxy, RESTAPIAdminServiceProxy restapiAdminServiceProxy, LocalEntryServiceProxy localEntryServiceProxy, EndpointAdminServiceProxy endpointAdminServiceProxy, GatewayAPIDTO gatewayAPIDTO, MediationSecurityAdminServiceProxy mediationSecurityAdminServiceProxy) throws AxisFault {
    if (log.isDebugEnabled()) {
        log.debug("Start to undeploy default api " + gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion());
    }
    // Delete Default API
    String qualifiedDefaultApiName = GatewayUtils.getQualifiedDefaultApiName(gatewayAPIDTO.getName());
    if (restapiAdminServiceProxy.getApi(qualifiedDefaultApiName) != null) {
        restapiAdminServiceProxy.deleteApi(qualifiedDefaultApiName);
    }
    if (log.isDebugEnabled()) {
        log.debug(gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion() + " Default API Definition " + "undeployed successfully");
        log.debug("Start to undeploy API Definition" + gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion());
    }
    // Delete API
    String qualifiedName = GatewayUtils.getQualifiedApiName(gatewayAPIDTO.getName(), gatewayAPIDTO.getVersion());
    if (restapiAdminServiceProxy.getApi(qualifiedName) != null) {
        restapiAdminServiceProxy.deleteApi(qualifiedName);
    }
    if (log.isDebugEnabled()) {
        log.debug(gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion() + " API Definition undeployed " + "successfully");
        log.debug("Start to undeploy custom sequences" + gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion());
    }
    // Remove Sequences to be remove.
    if (gatewayAPIDTO.getSequencesToBeRemove() != null) {
        for (String sequenceName : gatewayAPIDTO.getSequencesToBeRemove()) {
            if (sequenceAdminServiceProxy.isExistingSequence(sequenceName)) {
                sequenceAdminServiceProxy.deleteSequence(sequenceName);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion() + " custom sequences undeployed " + "successfully");
        log.debug("Start to undeploy endpoints" + gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion());
    }
    // Remove endpoints
    if (gatewayAPIDTO.getEndpointEntriesToBeRemove() != null) {
        for (String endpoint : gatewayAPIDTO.getEndpointEntriesToBeRemove()) {
            if (endpointAdminServiceProxy.isEndpointExist(endpoint)) {
                endpointAdminServiceProxy.deleteEndpoint(endpoint);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion() + " endpoints undeployed " + "successfully");
        log.debug("Start to undeploy client certificates" + gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion());
    }
    // Remove clientCertificates
    if (gatewayAPIDTO.getClientCertificatesToBeRemove() != null) {
        for (String alias : gatewayAPIDTO.getClientCertificatesToBeRemove()) {
            certificateManager.deleteClientCertificateFromGateway(alias);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion() + " client certificates undeployed " + "successfully");
        log.debug("Start to undeploy local entries" + gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion());
    }
    // Remove Local Entries if Exist
    if (gatewayAPIDTO.getLocalEntriesToBeRemove() != null) {
        for (String localEntryKey : gatewayAPIDTO.getLocalEntriesToBeRemove()) {
            if (localEntryServiceProxy.isEntryExists(localEntryKey)) {
                localEntryServiceProxy.deleteEntry(localEntryKey);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion() + " Local entries undeployed " + "successfully");
        log.debug("Start to remove vault entries" + gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion());
    }
    if (gatewayAPIDTO.getCredentialsToBeRemove() != null) {
        for (String alias : gatewayAPIDTO.getCredentialsToBeRemove()) {
            try {
                if (mediationSecurityAdminServiceProxy.isAliasExist(alias)) {
                    GatewayUtils.deleteRegistryProperty(alias, APIConstants.API_SYSTEM_CONFIG_SECURE_VAULT_LOCATION, gatewayAPIDTO.getTenantDomain());
                }
            } catch (APIManagementException e) {
                String msg = "Error while checking existence of vault entry";
                log.error(msg, e);
                throw new AxisFault(msg, e);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion() + " Vault entries removed " + "successfully");
        log.debug(gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion() + "undeployed successfully");
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException)

Example 19 with LOCAL

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.LOCAL in project carbon-apimgt by wso2.

the class APIUtil method loadAndSyncTenantConf.

/**
 * Loads tenant-conf.json (tenant config) to registry from the tenant-conf.json available in the file system.
 * If any REST API scopes are added to the local tenant-conf.json, they will be updated in the registry.
 *
 * @param organization organization.
 * @throws APIManagementException when error occurred while loading the tenant-conf to registry
 */
public static void loadAndSyncTenantConf(String organization) throws APIManagementException {
    try {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonElement jsonElement = getFileBaseTenantConfig();
        String currentConfig = ServiceReferenceHolder.getInstance().getApimConfigService().getTenantConfig(organization);
        if (currentConfig == null) {
            ServiceReferenceHolder.getInstance().getApimConfigService().addTenantConfig(organization, gson.toJson(jsonElement));
        }
    } catch (APIManagementException e) {
        throw new APIManagementException("Error while saving tenant conf to the registry of tenant " + organization, e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GsonBuilder(com.google.gson.GsonBuilder) JsonElement(com.google.gson.JsonElement) Gson(com.google.gson.Gson)

Example 20 with LOCAL

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.LOCAL in project carbon-apimgt by wso2.

the class SubscriberRegistrationInterceptor method handleMessage.

/**
 * Handles the incoming message after post authentication. Only used in Store REST API, to register a newly
 * signed up store user who hasn't logged in to Store for the first time either via REST API or Store UI.
 * This method will register the user as a subscriber
 * (register in AM_SUBSCRIBER table, add the default application for subscriber etc.).
 *
 * @param message cxf message
 */
@Override
@MethodStats
public void handleMessage(Message message) {
    String username = RestApiCommonUtil.getLoggedInUsername();
    // by-passes the interceptor if user is an annonymous user
    if (username.equalsIgnoreCase(APIConstants.WSO2_ANONYMOUS_USER)) {
        return;
    }
    // checking if the subscriber exists in the subscriber cache
    Cache<String, Subscriber> subscriberCache = Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.API_SUBSCRIBER_CACHE);
    if (subscriberCache.get(username) != null) {
        return;
    }
    // check the existence in the database
    String groupId = RestApiUtil.getLoggedInUserGroupId();
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    try {
        // takes a consumer object using the user set in thread local carbon context
        APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
        Subscriber subscriber = apiConsumer.getSubscriber(username);
        if (subscriber == null) {
            synchronized ((username + LOCK_POSTFIX).intern()) {
                subscriber = apiConsumer.getSubscriber(username);
                if (subscriber == null) {
                    message.getExchange().get(RestApiConstants.USER_REST_API_SCOPES);
                    if (!hasSubscribeScope(message)) {
                        // permission. It should be allowed.
                        if (logger.isDebugEnabled()) {
                            logger.debug("User " + username + " does not have subscribe scope " + "(" + APIM_SUBSCRIBE_SCOPE + ")");
                        }
                        return;
                    }
                    if (!APIConstants.SUPER_TENANT_DOMAIN.equalsIgnoreCase(tenantDomain)) {
                        loadTenantRegistry();
                    }
                    apiConsumer.addSubscriber(username, groupId);
                    // The subscriber object added here is not a complete subscriber object. It will only contain
                    // username
                    subscriberCache.put(username, new Subscriber(username));
                    if (logger.isDebugEnabled()) {
                        logger.debug("Subscriber " + username + " added to AM_SUBSCRIBER database");
                    }
                }
            }
        } else {
            subscriberCache.put(username, subscriber);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Unable to add the subscriber " + username, e, logger);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Aggregations

RestVariable (org.wso2.carbon.bpmn.rest.engine.variable.RestVariable)14 RestResponseFactory (org.wso2.carbon.bpmn.rest.common.RestResponseFactory)12 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)10 Map (java.util.Map)6 HashMap (java.util.HashMap)5 ActivitiObjectNotFoundException (org.activiti.engine.ActivitiObjectNotFoundException)5 RuntimeService (org.activiti.engine.RuntimeService)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 TreeMap (java.util.TreeMap)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 Response (javax.ws.rs.core.Response)3 JAXBContext (javax.xml.bind.JAXBContext)3 JAXBException (javax.xml.bind.JAXBException)3 Unmarshaller (javax.xml.bind.Unmarshaller)3 XMLStreamException (javax.xml.stream.XMLStreamException)3 ActivitiIllegalArgumentException (org.activiti.engine.ActivitiIllegalArgumentException)3 RegIndex (org.wso2.ballerinalang.programfile.Instruction.RegIndex)3 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)3