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());
}
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;
}
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");
}
}
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);
}
}
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);
}
}
Aggregations