getUiEntities
@param {string} entityname microfrontends | clustermicrofrontends
@param {string} namespace k8s namespace name
@param {array} placements array of strings: namespace | namespace | cluster
482937
async function getUiEntities(entityname, namespace, placements) {
  if (namespace) {
    const currentNamespace = await getNamespace(namespace);
    if (
      !currentNamespace.metadata.labels ||
      currentNamespace.metadata.labels.env !== 'true'
    ) {
      return 'systemNamespace';
    }
  }
  var fetchUrl =
    k8sServerUrl +
    '/apis/ui.kyma-project.io/v1alpha1/' +
    (namespace ? 'namespaces/' + namespace + '/' : '') +
    entityname;
  const segmentPrefix = entityname === 'clustermicrofrontends' ? 'cmf-' : 'mf-';
  const cacheName = '_console_mf_cache_';
  if (!window[cacheName]) {
    window[cacheName] = {};
  }

  const cache = window[cacheName];
  const cacheKey = fetchUrl + (placements || '');
  const fromCache = cache[cacheKey];
  return (
    fromCache ||
    fetchFromKyma(fetchUrl)
      .then(result => {
        if (!result.items.length) {
          return [];
        }
        return result.items
          .filter(function (item) {
            // placement only exists in clustermicrofrontends
            return !placements || placements.includes(item.spec.placement);
          })
          .map(function (item) {
            function buildNode(node, spec) {
              var n = {
                label: node.label,
                pathSegment: node.navigationPath.split('/').pop(),
                viewUrl: spec.viewBaseUrl
                  ? spec.viewBaseUrl + node.viewUrl
                  : node.viewUrl,
                hideFromNav: node.showInNavigation === false || undefined,
                order: node.order,
                context: {
                  settings: node.settings
                    ? { ...node.settings, ...(node.context || {}) }
                    : {}
                },
                requiredPermissions: node.requiredPermissions || undefined
              };

              n.context.requiredBackendModules =
                node.requiredBackendModules || undefined;

              if (node.externalLink) {
                delete n.viewUrl;
                delete n.pathSegment;
                n.externalLink = {
                  url: node.externalLink,
                  sameWindow: false
                };
              }

              processNodeForLocalDevelopment(n);
              return n;
            }

            function processNodeForLocalDevelopment(node) {
              const isLocalDev = window.location.href.startsWith(
                'http://console-dev.kyma.local:4200'
              );
              if (!isLocalDev || !node.viewUrl) {
                return;
              }
              if (node.viewUrl.startsWith('https://console.kyma.local')) {
                node.viewUrl =
                  'http://console-dev.kyma.local:4200' +
                  node.viewUrl.substring('https://console.kyma.local'.length);
              } else if (
                node.viewUrl.startsWith('https://catalog.kyma.local')
              ) {
                node.viewUrl =
                  config.serviceCatalogModuleUrl +
                  node.viewUrl.substring('https://catalog.kyma.local'.length);
              } else if (
                node.viewUrl.startsWith('https://instances.kyma.local')
              ) {
                node.viewUrl =
                  config.serviceInstancesModuleUrl +
                  node.viewUrl.substring('https://instances.kyma.local'.length);
              } else if (
                node.viewUrl.startsWith('https://brokers.kyma.local')
              ) {
                node.viewUrl =
                  config.serviceBrokersModuleUrl +
                  node.viewUrl.substring('https://brokers.kyma.local'.length);
              } else if (
                node.viewUrl.startsWith('https://lambdas-ui.kyma.local')
              ) {
                node.viewUrl =
                  config.lambdasModuleUrl +
                  node.viewUrl.substring(
                    'https://lambdas-ui.kyma.local'.length
                  );
              } else if (node.viewUrl.startsWith('https://log-ui.kyma.local')) {
                node.viewUrl =
                  config.logsModuleUrl +
                  node.viewUrl.substring('https://log-ui.kyma.local'.length);
              } else if(node.viewUrl.startsWith('https://add-ons.kyma.local')) {
                node.viewUrl =
                  config.addOnsModuleUrl +
                  node.viewUrl.substring('https://add-ons.kyma.local'.length);
              }
              return node;
            }

            function buildNodeWithChildren(specNode, spec) {
              var parentNodeSegments = specNode.navigationPath.split('/');
              var children = getDirectChildren(parentNodeSegments, spec);
              var node = buildNode(specNode, spec);
              if (children.length) {
                node.children = children;
              }
              return node;
            }

            function getDirectChildren(parentNodeSegments, spec) {
              // process only direct children
              return spec.navigationNodes
                .filter(function (node) {
                  var currentNodeSegments = node.navigationPath.split('/');
                  var isDirectChild =
                    parentNodeSegments.length ===
                    currentNodeSegments.length - 1 &&
                    parentNodeSegments.filter(function (segment) {
                      return currentNodeSegments.includes(segment);
                    }).length > 0;
                  return isDirectChild;
                })
                .map(function mapSecondLevelNodes(node) {
                  // map direct children
                  return buildNodeWithChildren(node, spec);
                });
            }

            function buildTree(name, spec) {
              return spec.navigationNodes
                .filter(function getTopLevelNodes(node) {
                  var segments = node.navigationPath.split('/');
                  return segments.length === 1;
                })
                .map(function processTopLevelNodes(node) {
                  return buildNodeWithChildren(node, spec, name);
                })
                .map(function addSettingsForTopLevelNodes(node) {
                  if (spec.category) {
                    node.category = spec.category;
                  }
                  if (!node.externalLink) {
                    if (!node.pathSegment.startsWith(segmentPrefix)) {
                      node.pathSegment = segmentPrefix + node.pathSegment;
                    }
                    node.navigationContext = spec.appName ? spec.appName : name;
                    node.viewGroup = node.navigationContext;
                    node.keepSelectedForChildren = true;
                  }

                  return node;
                });
            }
            if (item.spec.navigationNodes) {
              var tree = buildTree(item.metadata.name, item.spec);
              return tree;
            }
            return [];
          });
      })
      .catch(err => {
        console.error('Error fetching UiEntity ' + name, err);
        return [];
      })
      .then(result => {
        cache[cacheKey] = new Promise(function (resolve) {
          resolve(result);
        });
        return result;
      })
  );
}
369761
private static String initFindEntityQueryWithEmbeddedEndNode(EntityKeyMetadata entityKeyMetadata) {
		StringBuilder queryBuilder = new StringBuilder();
		appendMatchOwnerEntityNode( queryBuilder, entityKeyMetadata );
		appendGetEmbeddedNodesIfNeeded( true, queryBuilder );
		return queryBuilder.toString();
	}
1106202
async function getNamespace(namespaceName) {
  const cacheName = '_console_namespace_promise_cache_';
  if (!window[cacheName]) {
    window[cacheName] = {};
  }
  const cache = window[cacheName];
  if (!cache[namespaceName]) {
    cache[namespaceName] = fetchFromKyma(
      `${k8sServerUrl}/api/v1/namespaces/${namespaceName}`
    );
  }
  return await cache[namespaceName];
}
547827
private Entities toEntities(final JsonNode node, String text) throws IOException {
		if (null == node || node.isNull() || node.isMissingNode()) {
			return null;
		}
		final ObjectMapper mapper = this.createMapper();
		Entities entities = mapper.readerFor(Entities.class).readValue(node);
		extractTickerSymbolEntitiesFromText(text, entities);
		return entities;
	}
169284
function entitiesToDatastore(entities, options) {
    const multiple = is.array(entities);
    entities = arrify(entities);

    if (entities[0].className !== 'Entity') {
        // Not an entity instance, nothing to do here...
        return entities;
    }

    const result = entities.map(e => toDatastore(e, options));

    return multiple ? result : result[0];
}
827120
public FSArray getEntity_mentions() {
    if (Entity_Type.featOkTst && ((Entity_Type)jcasType).casFeat_entity_mentions == null)
      jcasType.jcas.throwFeatMissing("entity_mentions", "de.julielab.jules.types.ace.Entity");
    return (FSArray)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((Entity_Type)jcasType).casFeatCode_entity_mentions)));}
587254
function Model(namespace) {
    var self = this;
    this.i = 0;
    var local = {
        modelPath: null,
        entitiesPath: null,
        connection: null,
        files: {},
        toReload: [],
        trying: 0
    };

    var _configuration = null;
    var _connector = null;

    var cacheless = (process.env.IS_CACHELESS == 'false') ? false : true;
    var standalone = config.Host.isStandalone();


    var setup = function(namespace) {
        if ( typeof(namespace) == 'undefined' || namespace == '') {
            console.error('gina', 'MODEL:ERR:1', 'EEMPTY: Model namespace', __stack);
        }

        var model, namespace = namespace.split(/\//g);
        _connector = namespace[1];//Has to be writtien the same for the connetors.json decalration or for the model folder
        var bundle = namespace[0];
        namespace.shift();
        //Capitalize - Normalize
        if (namespace.length > 1) {
            //            for (var i; i<namespace.length; ++i) {
            //                namespace[i] = namespace[i].substring(0, 1).toUpperCase() + namespace[i].substring(1);
            //            }

            model = namespace.join(".");
        } else {
            //Dir name.
            model = namespace[0];
        }


        console.debug("\nBundle: ", bundle);
        console.debug("Model: ", model);
        self.name       = _connector;
        self.bundle     = bundle;
        self.model      = model;
        self.modelDirName = model;
        var modelConnectors = getContext('modelConnectors');
        if (modelConnectors) {
            self.connectors = getContext('modelConnectors')[self.name];
            self.database = self.connectors.database;
        } else {
            self.connectors = {};
        }

    }

    /**
     * Init
     *
     * @param {string} namesapce
     *
     * @private
     * */
    var init = function(reload) {

        var bundle          = self.bundle;
        var model           = self.model;
        var modelDirName    = self.modelDirName;

        // this is supposed to happen on load or for dev env; on reload, with a checksum
        var conf        = getConfigSync(bundle);
        local.locals    = conf.locals;

        if (conf) {
            _configuration = conf.connectors;

            console.debug("CONF READY ", model, conf.path);
            //TODO - More controls...

            //For now, I just need the F..ing entity name.
            var modelPath       = local.modelPath = _(conf.path + '/' + modelDirName);
            var entitiesPath    = local.entitiesPath = _(modelPath + '/entities');
            console.debug('models scaning... ', entitiesPath, fs.existsSync(entitiesPath));
            if (!fs.existsSync(entitiesPath)) {
                fs.mkdirSync(entitiesPath) // creating empty path
            }

            var connectorPath   = _(modelPath + '/lib/connector.js');
            //Getting Entities Manager.
            var exists = fs.existsSync(connectorPath);
            if (exists) {
                if (cacheless)
                    delete require.cache[_(connectorPath, true)];

                var Connector = require(_(connectorPath, true));

                self.connect(
                    Connector,
                    function onConnect(err, conn) {
                        if (err) {
                            console.error(err.stack);
                            self.emit('model#ready', err, self.bundle, self.name, null)

                        } else {
                            local.connection = conn;
                            self.emit('model#ready', false, self.bundle, self.name, conn)
                        }
                    }
                )
            } else {//Means that no connector was found in models.

                //finished.
                self.emit('model#ready', new Error('[ '+self.name+' ] No connector found'), self.bundle, self.name, conn)
            }

        } else {
            console.debug("no configuration found...");
            self.emit('model#ready', new Error('no configuration found for your model: ' + model), self.bundle, self.name, null)
        }

        return self
    }


    this.connect = function(Connector, callback) {
        if ( typeof(self.connectors[_connector]) == 'undefined' ) {
            self.connectors[_connector] = {};
            var connector = new Connector( self.getConfig(_connector) );

            connector.onReady( function(err, conn){
                self.connectors[_connector].err = err;
                self.connectors[_connector].conn = conn;

                callback(err, conn);
            });

        } else {
            callback(self.connectors[_connector].err, self.connectors[_connector].conn);
        }
    }

    this.reload = function(conf, cb) {
        setup(namespace);
        init(cb)
    }

    /**
     * Get Model configuration
     *
     * @param {string} bundle
     *
     * @callback callback
     * @param {boolean|string} err - Error Status response
     * @param {object} conf - Configuration response
     *
     * @private
     * */
    var getConfigSync = function(bundle, i) {
        var i = i || 0;
        var configuration = config.getInstance(bundle);

        try {

            var locals = _locals = utilsConfig.getSync('gina', 'locals.json')
        } catch (err) {
            console.emerg('Error while calling `Model::getConfigSync()` '+ err.stack||err.message);
            if ( i < 10) {
                console.debug('about to retry to load locals.json');
                setTimeout(function(){

                    i = i+1;
                    console.debug('retry ('+i+') ...');
                    return getConfigSync(bundle, i)
                }, 300)

            } else {
                throw new Error('Config could not be loaded');
                process.exit(1)
            }
            return false
        }

        if ( typeof(configuration) != 'undefined' && locals) {

            var env = configuration.Env.current;
            var conf = configuration.Env.getConf(bundle, env);

            // configuration object.
            var confObj = {
                connectors  : conf.content.connectors,
                path        : conf.modelsPath,
                locals      : locals
            };

            return confObj
        } else {
            throw new Error('Config not instantiated');
            return undefined
        }
    }

    /**
     * Get Model Configuration
     *
     * @return {object|undefined} configuration
     * */
    this.getConfig = function(connector){
        var connector = ( typeof(connector) == 'undefined' ) ?  _connector : connector;

        if (_configuration) {
            return ( typeof(connector) != 'undefined' ) ? _configuration[connector] : undefined
        } else {
            return undefined
        }
    }


    this.onReady = function(callback) {
        self.once('model#ready', function(err, bundle, model, conn) {
            // entities == null when the database server has not started.
            if ( err ) {
                console.error(err.stack||err.message)
                //console.log('No entities found for [ '+ self.name +':'+ entityName +'].\n 1) Check if the database is started.\n2) Check if exists: /models/entities/'+ entityName);
            }
            callback(err, bundle, model, conn)
        });
        setup(namespace);
        return init()
    };

    return this
}
156021
@Override
    public EntityIdentifier[] searchForEntities(String query, SearchMethod method)
            throws GroupsException {
        boolean allowPartial = true;

        switch (method) {
            case DISCRETE:
                allowPartial = false;
                break;
            case STARTS_WITH:
                query = query + "%";
                break;
            case ENDS_WITH:
                query = "%" + query;
                break;
            case CONTAINS:
                query = "%" + query + "%";
                break;
            default:
                throw new GroupsException("Unknown search type");
        }

        // get the list of matching portlet definitions
        final List<IPortletDefinition> definitions =
                this.portletDefinitionRegistry.searchForPortlets(query, allowPartial);
        if (log.isDebugEnabled()) {
            log.debug("Found " + definitions.size() + " matching definitions for query " + query);
        }

        // initialize an appropriately-sized array of EntityIdentifiers
        final EntityIdentifier[] identifiers = new EntityIdentifier[definitions.size()];

        // add an identifier for each matching portlet
        for (final ListIterator<IPortletDefinition> defIter = definitions.listIterator();
                defIter.hasNext(); ) {
            final IPortletDefinition definition = defIter.next();
            identifiers[defIter.previousIndex()] =
                    new EntityIdentifier(
                            definition.getPortletDefinitionId().getStringId(), this.getType());
        }

        return identifiers;
    }
238932
private Entity lookupEntity(String sid) {
        for (Integer i = 0; i < getEntities().size(); i++) {
            Entity e = getEntities().get(i);
            if (e != null && sid.compareTo(EntityContainer.buildId(e.getId())) == 0) {
                return getEntity(e.getId());
            }
        }
        return null;
    }
1159321
public FSArray getEntities() {
    if (Document_Type.featOkTst && ((Document_Type)jcasType).casFeat_entities == null)
      jcasType.jcas.throwFeatMissing("entities", "de.julielab.jules.types.ace.Document");
    return (FSArray)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((Document_Type)jcasType).casFeatCode_entities)));}
1327941
function find(name, namespace) {
	// If there are no replicants for that namespace, return undefined
	if (!{}.hasOwnProperty.call(declaredReplicants, namespace)) {
		return undefined;
	}

	// If that replicant doesn't exist for that namespace, return undefined
	if (!{}.hasOwnProperty.call(declaredReplicants[namespace], name)) {
		return undefined;
	}

	// Return the replicant.
	return declaredReplicants[namespace][name];
}
938823
@Override
    public IEntity getEntity(String key, Class type, String svcName) throws GroupsException {
        IIndividualGroupService svc = null;
        if (svcName == null) {
            svc = getDefaultService();
        } else {
            try {
                Name n = GroupService.parseServiceName(svcName);
                svc = getComponentService(n);
            } catch (InvalidNameException ine) {
                throw new GroupsException("Invalid service name.");
            }
        }
        return (svc == null) ? null : svc.getEntity(key, type);
    }
984243
private Map<Resourcepart, Presence> getPresencesInternal(BareJid entity) {
        Map<Resourcepart, Presence> entityPresences = presenceMap.get(entity);
        if (entityPresences == null) {
            entityPresences = nonRosterPresenceMap.lookup(entity);
        }
        return entityPresences;
    }
221433
private Object getEntityWithAssociationFromNode(EntityMetadata m, Node node)
    {
        Map<String, Object> relationMap = new HashMap<String, Object>();

        /**
         * Map containing Node ID as key and Entity object as value. Helps cache
         * entity objects found earlier for faster lookup and prevents repeated
         * processing
         */
        Map<Long, Object> nodeIdToEntityMap = new HashMap<Long, Object>();

        Object entity = mapper.getEntityFromNode(node, m);

        nodeIdToEntityMap.put(node.getId(), entity);
        populateRelations(m, entity, relationMap, node, nodeIdToEntityMap);

        nodeIdToEntityMap.clear();

        if (!relationMap.isEmpty() && entity != null)
        {
            return new EnhanceEntity(entity, PropertyAccessorHelper.getId(entity, m), relationMap);
        }
        else
        {
            return entity;
        }

    }
1332581
private void setEntitiesInResult(EntityMetadata m, List results, JsonArray array)
    {
        for (JsonElement element : array)
        {

            String id = element.getAsJsonObject().get("value").getAsJsonObject()
                    .get(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName()).getAsString();
            Object entityFromJson = CouchDBObjectMapper.getEntityFromJson(m.getEntityClazz(), m, element
                    .getAsJsonObject().get("value").getAsJsonObject(), m.getRelationNames(), kunderaMetadata);
            if (entityFromJson != null
                    && (m.getTableName().concat(id)).equals(element.getAsJsonObject().get("id").getAsString()))
            {
                results.add(entityFromJson);
            }

        }
    }
958962
func (s *PresenceService) GetNamespaces() ([]services.Namespace, error) {
	result, err := s.GetRange(context.TODO(), backend.Key(namespacesPrefix), backend.RangeEnd(backend.Key(namespacesPrefix)), backend.NoLimit)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	out := make([]services.Namespace, 0, len(result.Items))
	for _, item := range result.Items {
		if !bytes.HasSuffix(item.Key, []byte(paramsPrefix)) {
			continue
		}
		ns, err := services.UnmarshalNamespace(
			item.Value, services.WithResourceID(item.ID), services.WithExpires(item.Expires))
		if err != nil {
			return nil, trace.Wrap(err)
		}
		out = append(out, *ns)
	}
	sort.Sort(services.SortedNamespaces(out))
	return out, nil
}
438536
function findOne(repository, options) {
    const entityPrimaryKeyColumn = lodash_1.find(repository.metadata.columns, (columnMetadata) => columnMetadata.isPrimary).propertyName;
    const entityColumns = repository.metadata.columns.map((columnMetadata) => columnMetadata.propertyName);
    const entityManyToOneOrOneToOneRelationColumns = repository
        .metadata
        .relations
        .filter((relationMetadata) => relationMetadata.relationType === 'many-to-one' || relationMetadata.relationType === 'one-to-one')
        .map((relationMetadata) => relationMetadata.propertyName);
    const entityUniqueColumns = repository
        .metadata
        .columns
        .filter((columnMetadata) => columnMetadata.isUnique)
        .map((columnMetadata) => columnMetadata.propertyName);
    return function (source, args, context, info) {
        return __awaiter(this, void 0, void 0, function* () {
            const selectedColumns = Object.keys(graphqlFields(info));
            const selectQueryBuilder = repository.createQueryBuilder(repository.metadata.name.toLowerCase());
            /** Select **/
            const selectFactory = new select_factory_1.SelectFactory(selectQueryBuilder);
            selectFactory
                .select(selectedColumns.filter((select) => entityColumns.includes(select)));
            /** Where **/
            const filter = Object
                .keys(args)
                .filter((argName) => entityUniqueColumns.includes(argName) || argName === entityPrimaryKeyColumn)
                .reduce((filteredArgs, argName) => {
                filteredArgs[argName] = args[argName];
                return filteredArgs;
            }, {});
            const whereFactory = new where_factory_1.WhereFactory(selectQueryBuilder, entityManyToOneOrOneToOneRelationColumns);
            whereFactory
                .where(filter);
            /** Joins **/
            const joinsFactory = new joins_factory_1.JoinsFactory(selectQueryBuilder);
            joinsFactory
                .join(selectedColumns
                .filter((select) => entityManyToOneOrOneToOneRelationColumns.includes(select))
                .reduce((selectedRelationColumns, selectedRelationColumn) => {
                selectedRelationColumns[selectQueryBuilder.alias] = selectedRelationColumn;
                return selectedRelationColumns;
            }, {}))
                .join(whereFactory.selectedManyToOneOrOneToOneRelationColumns);
            /** Extend **/
            if (lodash_1.get(options, 'extend')) {
                yield options.extend(selectQueryBuilder);
            }
            /** Execute get many method **/
            return yield selectQueryBuilder.getOne();
        });
    };
}