idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
0
public Object eval ( Bindings bindings , String expression ) throws ScriptException { CompiledScript compiledExpression = requireNonNull ( expressions . get ( expression ) ) ; Object returnValue = compiledExpression . eval ( bindings ) ; return convertNashornValue ( returnValue ) ; }
Evaluates an expression using the given bindings .
1
public void addFileRepositoryCollectionClass ( Class < ? extends FileRepositoryCollection > clazz , Set < String > fileExtensions ) { for ( String extension : fileExtensions ) { fileRepositoryCollections . put ( extension . toLowerCase ( ) , clazz ) ; } }
Add a FileRepositorySource so it can be used by the createFileRepositySource factory method
2
public FileRepositoryCollection createFileRepositoryCollection ( File file ) { Class < ? extends FileRepositoryCollection > clazz ; String extension = FileExtensionUtils . findExtensionFromPossibilities ( file . getName ( ) , fileRepositoryCollections . keySet ( ) ) ; clazz = fileRepositoryCollections . get ( extension ) ; if ( clazz == null ) { throw new MolgenisDataException ( "Unknown extension for file '" + file . getName ( ) + "'" ) ; } Constructor < ? extends FileRepositoryCollection > ctor ; try { ctor = clazz . getConstructor ( File . class ) ; } catch ( Exception e ) { throw new MolgenisDataException ( "Exception creating [" + clazz + "] missing constructor FileRepositorySource(File file)" ) ; } FileRepositoryCollection fileRepositoryCollection = BeanUtils . instantiateClass ( ctor , file ) ; autowireCapableBeanFactory . autowireBeanProperties ( fileRepositoryCollection , AutowireCapableBeanFactory . AUTOWIRE_BY_TYPE , false ) ; try { fileRepositoryCollection . init ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } return fileRepositoryCollection ; }
Factory method for creating a new FileRepositorySource
3
private static boolean hasNewMappedByAttrs ( EntityType entityType , EntityType existingEntityType ) { Set < String > mappedByAttrs = entityType . getOwnMappedByAttributes ( ) . map ( Attribute :: getName ) . collect ( toSet ( ) ) ; Set < String > existingMappedByAttrs = existingEntityType . getOwnMappedByAttributes ( ) . map ( Attribute :: getName ) . collect ( toSet ( ) ) ; return ! mappedByAttrs . equals ( existingMappedByAttrs ) ; }
Returns true if entity meta contains mapped by attributes that do not exist in the existing entity meta .
4
private void upsertAttributes ( EntityType entityType , EntityType existingEntityType ) { Map < String , Attribute > attrsMap = stream ( entityType . getOwnAllAttributes ( ) ) . collect ( toMap ( Attribute :: getName , Function . identity ( ) ) ) ; Map < String , Attribute > existingAttrsMap = stream ( existingEntityType . getOwnAllAttributes ( ) ) . collect ( toMap ( Attribute :: getName , Function . identity ( ) ) ) ; Set < String > addedAttrNames = Sets . difference ( attrsMap . keySet ( ) , existingAttrsMap . keySet ( ) ) ; Set < String > sharedAttrNames = Sets . intersection ( attrsMap . keySet ( ) , existingAttrsMap . keySet ( ) ) ; Set < String > deletedAttrNames = Sets . difference ( existingAttrsMap . keySet ( ) , attrsMap . keySet ( ) ) ; if ( ! addedAttrNames . isEmpty ( ) ) { dataService . add ( ATTRIBUTE_META_DATA , addedAttrNames . stream ( ) . map ( attrsMap :: get ) ) ; } List < String > updatedAttrNames = sharedAttrNames . stream ( ) . filter ( attrName -> ! EntityUtils . equals ( attrsMap . get ( attrName ) , existingAttrsMap . get ( attrName ) ) ) . collect ( toList ( ) ) ; if ( ! updatedAttrNames . isEmpty ( ) ) { dataService . update ( ATTRIBUTE_META_DATA , updatedAttrNames . stream ( ) . map ( attrsMap :: get ) ) ; } if ( ! deletedAttrNames . isEmpty ( ) ) { dataService . delete ( ATTRIBUTE_META_DATA , deletedAttrNames . stream ( ) . map ( existingAttrsMap :: get ) ) ; } }
Add and update entity attributes
5
public EntityImportReport doImport ( EmxImportJob job ) { try { return writer . doImport ( job ) ; } catch ( Exception e ) { LOG . error ( "Error handling EmxImportJob" , e ) ; throw e ; } }
Does the import in a transaction . Manually rolls back schema changes if something goes wrong . Refreshes the metadata .
6
private Optional < String > tryGetEntityTypeName ( String tableName ) { EntityTypeDescription entityTypeDescription = entityTypeRegistry . getEntityTypeDescription ( tableName ) ; String entityTypeId = entityTypeDescription != null ? entityTypeDescription . getId ( ) : null ; return Optional . ofNullable ( entityTypeId ) ; }
Tries to determine the entity type identifier for this table name
7
private Optional < String > tryGetAttributeName ( String tableName , String colName ) { String attributeName ; EntityTypeDescription entityTypeDescription = entityTypeRegistry . getEntityTypeDescription ( tableName ) ; if ( entityTypeDescription != null ) { AttributeDescription attrDescription = entityTypeDescription . getAttributeDescriptionMap ( ) . get ( colName ) ; if ( attrDescription != null ) { attributeName = attrDescription . getName ( ) ; } else { attributeName = null ; } } else { attributeName = null ; } return Optional . ofNullable ( attributeName ) ; }
Tries to determine the attribute name for this table column name
8
private void assignUniqueLabel ( Package pack , Package targetPackage ) { Set < String > existingLabels ; if ( targetPackage != null ) { existingLabels = stream ( targetPackage . getChildren ( ) ) . map ( Package :: getLabel ) . collect ( toSet ( ) ) ; } else { existingLabels = dataService . query ( PACKAGE , Package . class ) . eq ( PackageMetadata . PARENT , null ) . findAll ( ) . map ( Package :: getLabel ) . collect ( toSet ( ) ) ; } pack . setLabel ( generateUniqueLabel ( pack . getLabel ( ) , existingLabels ) ) ; }
Checks if there s a Package in the target location with the same label . If so keeps adding a postfix until the label is unique .
9
public Map < String , Object > dehydrate ( Entity entity ) { LOG . trace ( "Dehydrating entity {}" , entity ) ; Map < String , Object > dehydratedEntity = newHashMap ( ) ; EntityType entityType = entity . getEntityType ( ) ; entityType . getAtomicAttributes ( ) . forEach ( attribute -> { if ( ! attribute . hasExpression ( ) ) { String name = attribute . getName ( ) ; AttributeType type = attribute . getDataType ( ) ; dehydratedEntity . put ( name , getValueBasedOnType ( entity , name , type ) ) ; } } ) ; return dehydratedEntity ; }
Creates a Map containing the values required to rebuild this entity . For references to other entities only stores the ids .
10
public void move ( String sourceDir , String targetDir ) throws IOException { validatePathname ( sourceDir ) ; validatePathname ( targetDir ) ; Files . move ( Paths . get ( getStorageDir ( ) + File . separator + sourceDir ) , Paths . get ( getStorageDir ( ) + File . separator + targetDir ) ) ; }
Move directories in FileStore Pleae provide the path from the relative root of the fileStore
11
private boolean hasAttributeThatReferences ( EntityType candidate , String entityTypeId ) { Iterable < Attribute > attributes = candidate . getOwnAtomicAttributes ( ) ; return stream ( attributes ) . filter ( Attribute :: hasRefEntity ) . map ( attribute -> attribute . getRefEntity ( ) . getId ( ) ) . anyMatch ( entityTypeId :: equals ) ; }
Determines if an entityType has an attribute that references another entity
12
public QueryRule createDisMaxQueryRuleForAttribute ( Set < String > searchTerms , Collection < OntologyTerm > ontologyTerms ) { List < String > queryTerms = new ArrayList < > ( ) ; if ( searchTerms != null ) { queryTerms . addAll ( searchTerms . stream ( ) . filter ( StringUtils :: isNotBlank ) . map ( this :: processQueryString ) . collect ( Collectors . toList ( ) ) ) ; } ontologyTerms . stream ( ) . filter ( ontologyTerm -> ! ontologyTerm . getIRI ( ) . contains ( COMMA_CHAR ) ) . forEach ( ot -> queryTerms . addAll ( parseOntologyTermQueries ( ot ) ) ) ; QueryRule disMaxQueryRule = createDisMaxQueryRuleForTerms ( queryTerms ) ; ontologyTerms . stream ( ) . filter ( ontologyTerm -> ontologyTerm . getIRI ( ) . contains ( COMMA_CHAR ) ) . forEach ( ot -> disMaxQueryRule . getNestedRules ( ) . add ( createShouldQueryRule ( ot . getIRI ( ) ) ) ) ; return disMaxQueryRule ; }
Create a disMaxJunc query rule based on the given search terms as well as the information from given ontology terms
13
public QueryRule createDisMaxQueryRuleForTerms ( List < String > queryTerms ) { List < QueryRule > rules = new ArrayList < > ( ) ; queryTerms . stream ( ) . filter ( StringUtils :: isNotEmpty ) . map ( this :: escapeCharsExcludingCaretChar ) . forEach ( query -> { rules . add ( new QueryRule ( AttributeMetadata . LABEL , Operator . FUZZY_MATCH , query ) ) ; rules . add ( new QueryRule ( AttributeMetadata . DESCRIPTION , Operator . FUZZY_MATCH , query ) ) ; } ) ; QueryRule finalDisMaxQuery = new QueryRule ( rules ) ; finalDisMaxQuery . setOperator ( Operator . DIS_MAX ) ; return finalDisMaxQuery ; }
Create disMaxJunc query rule based a list of queryTerm . All queryTerms are lower cased and stop words are removed
14
public QueryRule createBoostedDisMaxQueryRuleForTerms ( List < String > queryTerms , Double boostValue ) { QueryRule finalDisMaxQuery = createDisMaxQueryRuleForTerms ( queryTerms ) ; if ( boostValue != null && boostValue . intValue ( ) != 0 ) { finalDisMaxQuery . setValue ( boostValue ) ; } return finalDisMaxQuery ; }
Create a disMaxQueryRule with corresponding boosted value
15
public QueryRule createShouldQueryRule ( String multiOntologyTermIri ) { QueryRule shouldQueryRule = new QueryRule ( new ArrayList < > ( ) ) ; shouldQueryRule . setOperator ( Operator . SHOULD ) ; for ( String ontologyTermIri : multiOntologyTermIri . split ( COMMA_CHAR ) ) { OntologyTerm ontologyTerm = ontologyService . getOntologyTerm ( ontologyTermIri ) ; List < String > queryTerms = parseOntologyTermQueries ( ontologyTerm ) ; Double termFrequency = getBestInverseDocumentFrequency ( queryTerms ) ; shouldQueryRule . getNestedRules ( ) . add ( createBoostedDisMaxQueryRuleForTerms ( queryTerms , termFrequency ) ) ; } return shouldQueryRule ; }
Create a boolean should query for composite tags containing multiple ontology terms
16
public List < String > parseOntologyTermQueries ( OntologyTerm ontologyTerm ) { List < String > queryTerms = getOtLabelAndSynonyms ( ontologyTerm ) . stream ( ) . map ( this :: processQueryString ) . collect ( Collectors . toList ( ) ) ; for ( OntologyTerm childOt : ontologyService . getChildren ( ontologyTerm ) ) { double boostedNumber = Math . pow ( 0.5 , ontologyService . getOntologyTermDistance ( ontologyTerm , childOt ) ) ; getOtLabelAndSynonyms ( childOt ) . forEach ( synonym -> queryTerms . add ( parseBoostQueryString ( synonym , boostedNumber ) ) ) ; } return queryTerms ; }
Create a list of string queries based on the information collected from current ontologyterm including label synonyms and child ontologyterms
17
public Set < String > getOtLabelAndSynonyms ( OntologyTerm ontologyTerm ) { Set < String > allTerms = Sets . newLinkedHashSet ( ontologyTerm . getSynonyms ( ) ) ; allTerms . add ( ontologyTerm . getLabel ( ) ) ; return allTerms ; }
A helper function to collect synonyms as well as label of ontologyterm
18
public List < String > getAttributeIdentifiers ( EntityType sourceEntityType ) { Entity entityTypeEntity = dataService . findOne ( ENTITY_TYPE_META_DATA , new QueryImpl < > ( ) . eq ( EntityTypeMetadata . ID , sourceEntityType . getId ( ) ) ) ; if ( entityTypeEntity == null ) throw new MolgenisDataAccessException ( "Could not find EntityTypeEntity by the name of " + sourceEntityType . getId ( ) ) ; List < String > attributeIdentifiers = new ArrayList < > ( ) ; recursivelyCollectAttributeIdentifiers ( entityTypeEntity . getEntities ( EntityTypeMetadata . ATTRIBUTES ) , attributeIdentifiers ) ; return attributeIdentifiers ; }
A helper function that gets identifiers of all the attributes from one EntityType
19
private Entity toEntity ( EntityType entityType , Entity emxEntity ) { Entity entity = entityManager . create ( entityType , POPULATE ) ; for ( Attribute attr : entityType . getAtomicAttributes ( ) ) { if ( attr . getExpression ( ) == null && ! attr . isMappedBy ( ) ) { String attrName = attr . getName ( ) ; Object emxValue = emxEntity . get ( attrName ) ; AttributeType attrType = attr . getDataType ( ) ; switch ( attrType ) { case BOOL : case DATE : case DATE_TIME : case DECIMAL : case EMAIL : case ENUM : case HTML : case HYPERLINK : case INT : case LONG : case SCRIPT : case STRING : case TEXT : Object value = emxValue != null ? DataConverter . convert ( emxValue , attr ) : null ; if ( ( ! attr . isAuto ( ) || value != null ) && ( ! attr . hasDefaultValue ( ) || value != null ) ) { entity . set ( attrName , value ) ; } break ; case CATEGORICAL : case FILE : case XREF : Entity refEntity = toRefEntity ( attr , emxValue ) ; if ( ( ! attr . isAuto ( ) || refEntity != null ) && ( ! attr . hasDefaultValue ( ) || refEntity != null ) ) { entity . set ( attrName , refEntity ) ; } break ; case CATEGORICAL_MREF : case MREF : List < Entity > refEntities = toRefEntities ( attr , emxValue ) ; if ( ! refEntities . isEmpty ( ) ) { entity . set ( attrName , refEntities ) ; } break ; case COMPOUND : throw new IllegalAttributeTypeException ( attrType ) ; default : throw new UnexpectedEnumException ( attrType ) ; } } } return entity ; }
Create an entity from the EMX entity
20
private Column createColumnFromCell ( Sheet sheet , Cell cell ) { if ( cell . getCellTypeEnum ( ) == CellType . STRING ) { return Column . create ( cell . getStringCellValue ( ) , cell . getColumnIndex ( ) , getColumnDataFromSheet ( sheet , cell . getColumnIndex ( ) ) ) ; } else { throw new MolgenisDataException ( String . format ( "Celltype [%s] is not supported for columnheaders" , cell . getCellTypeEnum ( ) ) ) ; } }
Specific columntypes are permitted in the import . The supported columntypes are specified in the method .
21
private Object getCellValue ( Cell cell ) { Object value ; if ( cell == null ) { return null ; } switch ( cell . getCellTypeEnum ( ) ) { case STRING : value = cell . getStringCellValue ( ) ; break ; case NUMERIC : if ( isCellDateFormatted ( cell ) ) { try { setUserTimeZone ( LocaleUtil . TIMEZONE_UTC ) ; Date dateCellValue = cell . getDateCellValue ( ) ; value = formatUTCDateAsLocalDateTime ( dateCellValue ) ; } finally { resetUserTimeZone ( ) ; } } else { value = cell . getNumericCellValue ( ) ; } break ; case BOOLEAN : value = cell . getBooleanCellValue ( ) ; break ; case FORMULA : value = getTypedFormulaValue ( cell ) ; break ; default : value = null ; break ; } return value ; }
Retrieves the proper Java type instance based on the Excel CellTypeEnum
22
public void validate ( EntityType entityType ) { validateEntityId ( entityType ) ; validateEntityLabel ( entityType ) ; validatePackage ( entityType ) ; validateExtends ( entityType ) ; validateOwnAttributes ( entityType ) ; Map < String , Attribute > ownAllAttrMap = stream ( entityType . getOwnAllAttributes ( ) ) . collect ( toLinkedMap ( Attribute :: getIdentifier , Function . identity ( ) ) ) ; validateOwnIdAttribute ( entityType , ownAllAttrMap ) ; validateOwnLabelAttribute ( entityType , ownAllAttrMap ) ; validateOwnLookupAttributes ( entityType , ownAllAttrMap ) ; validateLabelAttribute ( entityType ) ; validateBackend ( entityType ) ; }
Validates entity meta data
23
void validateBackend ( EntityType entityType ) { String backendName = entityType . getBackend ( ) ; if ( ! dataService . getMeta ( ) . hasBackend ( backendName ) ) { throw new MolgenisValidationException ( new ConstraintViolation ( format ( "Unknown backend [%s]" , backendName ) ) ) ; } }
Validate that the entity meta data backend exists
24
static void validateOwnLookupAttributes ( EntityType entityType , Map < String , Attribute > ownAllAttrMap ) { entityType . getOwnLookupAttributes ( ) . forEach ( ownLookupAttr -> { Attribute ownAttr = ownAllAttrMap . get ( ownLookupAttr . getIdentifier ( ) ) ; if ( ownAttr == null ) { throw new MolgenisValidationException ( new ConstraintViolation ( format ( "Lookup attribute [%s] is not one of the attributes of entity [%s]" , ownLookupAttr . getName ( ) , entityType . getId ( ) ) ) ) ; } if ( ! ownLookupAttr . isVisible ( ) ) { throw new MolgenisValidationException ( new ConstraintViolation ( format ( "Lookup attribute [%s] of entity type [%s] must be visible" , ownLookupAttr . getName ( ) , entityType . getId ( ) ) ) ) ; } } ) ; }
Validate that the lookup attributes owned by this entity are part of the owned attributes .
25
static void validateOwnLabelAttribute ( EntityType entityType , Map < String , Attribute > ownAllAttrMap ) { Attribute ownLabelAttr = entityType . getOwnLabelAttribute ( ) ; if ( ownLabelAttr != null ) { Attribute ownAttr = ownAllAttrMap . get ( ownLabelAttr . getIdentifier ( ) ) ; if ( ownAttr == null ) { throw new MolgenisValidationException ( new ConstraintViolation ( format ( "Label attribute [%s] is not one of the attributes of entity [%s]" , ownLabelAttr . getName ( ) , entityType . getId ( ) ) ) ) ; } if ( ownAttr . isNillable ( ) ) { throw new MolgenisValidationException ( new ConstraintViolation ( format ( "Label attribute [%s] of entity type [%s] cannot be nillable" , ownLabelAttr . getName ( ) , entityType . getId ( ) ) ) ) ; } } }
Validate that the label attribute owned by this entity is part of the owned attributes .
26
static void validateOwnIdAttribute ( EntityType entityType , Map < String , Attribute > ownAllAttrMap ) { Attribute ownIdAttr = entityType . getOwnIdAttribute ( ) ; if ( ownIdAttr != null ) { Attribute ownAttr = ownAllAttrMap . get ( ownIdAttr . getIdentifier ( ) ) ; if ( ownAttr == null ) { throw new MolgenisValidationException ( new ConstraintViolation ( format ( "EntityType [%s] ID attribute [%s] is not part of the entity attributes" , entityType . getId ( ) , ownIdAttr . getName ( ) ) ) ) ; } if ( ! AttributeUtils . isIdAttributeTypeAllowed ( ownIdAttr ) ) { throw new MolgenisValidationException ( new ConstraintViolation ( format ( "EntityType [%s] ID attribute [%s] type [%s] is not allowed" , entityType . getId ( ) , ownIdAttr . getName ( ) , ownIdAttr . getDataType ( ) . toString ( ) ) ) ) ; } if ( ! ownIdAttr . isUnique ( ) ) { throw new MolgenisValidationException ( new ConstraintViolation ( format ( "EntityType [%s] ID attribute [%s] is not a unique attribute" , entityType . getId ( ) , ownIdAttr . getName ( ) ) ) ) ; } if ( ownIdAttr . isNillable ( ) ) { throw new MolgenisValidationException ( new ConstraintViolation ( format ( "EntityType [%s] ID attribute [%s] cannot be nillable" , entityType . getId ( ) , ownIdAttr . getName ( ) ) ) ) ; } } else { if ( ! entityType . isAbstract ( ) && entityType . getIdAttribute ( ) == null ) { throw new MolgenisValidationException ( new ConstraintViolation ( format ( "EntityType [%s] is missing required ID attribute" , entityType . getId ( ) ) ) ) ; } } }
Validate that the ID attribute owned by this entity is part of the owned attributes .
27
static void validateExtends ( EntityType entityType ) { EntityType entityTypeExtends = entityType . getExtends ( ) ; if ( entityTypeExtends != null && ! entityTypeExtends . isAbstract ( ) ) { throw new MolgenisValidationException ( new ConstraintViolation ( format ( "EntityType [%s] is not abstract; EntityType [%s] can't extend it" , entityTypeExtends . getId ( ) , entityType . getId ( ) ) ) ) ; } }
Validates if this entityType extends another entityType . If so checks whether that parent entityType is abstract .
28
void validatePackage ( EntityType entityType ) { Package pack = entityType . getPackage ( ) ; if ( pack != null && isSystemPackage ( pack ) && ! systemEntityTypeRegistry . hasSystemEntityType ( entityType . getId ( ) ) ) { throw new MolgenisValidationException ( new ConstraintViolation ( format ( "Adding entity [%s] to system package [%s] is not allowed" , entityType . getId ( ) , pack . getId ( ) ) ) ) ; } }
Validate that non - system entities are not assigned to a system package
29
void register ( String repoFullName ) { lock . writeLock ( ) . lock ( ) ; try { if ( ! entityListenersByRepo . containsKey ( requireNonNull ( repoFullName ) ) ) { entityListenersByRepo . put ( repoFullName , HashMultimap . create ( ) ) ; } } finally { lock . writeLock ( ) . unlock ( ) ; } }
Register a repository to the entity listeners service once
30
Stream < Entity > updateEntities ( String repoFullName , Stream < Entity > entities ) { lock . readLock ( ) . lock ( ) ; try { verifyRepoRegistered ( repoFullName ) ; SetMultimap < Object , EntityListener > entityListeners = this . entityListenersByRepo . get ( repoFullName ) ; return entities . filter ( entity -> { Set < EntityListener > entityEntityListeners = entityListeners . get ( entity . getIdValue ( ) ) ; entityEntityListeners . forEach ( entityListener -> entityListener . postUpdate ( entity ) ) ; return true ; } ) ; } finally { lock . readLock ( ) . unlock ( ) ; } }
Update all registered listeners of the entities
31
void updateEntity ( String repoFullName , Entity entity ) { lock . readLock ( ) . lock ( ) ; try { verifyRepoRegistered ( repoFullName ) ; SetMultimap < Object , EntityListener > entityListeners = this . entityListenersByRepo . get ( repoFullName ) ; Set < EntityListener > entityEntityListeners = entityListeners . get ( entity . getIdValue ( ) ) ; entityEntityListeners . forEach ( entityListener -> entityListener . postUpdate ( entity ) ) ; } finally { lock . readLock ( ) . unlock ( ) ; } }
Update all registered listeners of an entity
32
public void addEntityListener ( String repoFullName , EntityListener entityListener ) { lock . writeLock ( ) . lock ( ) ; try { verifyRepoRegistered ( repoFullName ) ; SetMultimap < Object , EntityListener > entityListeners = this . entityListenersByRepo . get ( repoFullName ) ; entityListeners . put ( entityListener . getEntityId ( ) , entityListener ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } }
Adds an entity listener for a entity of the given class that listens to entity changes
33
public boolean removeEntityListener ( String repoFullName , EntityListener entityListener ) { lock . writeLock ( ) . lock ( ) ; try { verifyRepoRegistered ( repoFullName ) ; SetMultimap < Object , EntityListener > entityListeners = this . entityListenersByRepo . get ( repoFullName ) ; if ( entityListeners . containsKey ( entityListener . getEntityId ( ) ) ) { entityListeners . remove ( entityListener . getEntityId ( ) , entityListener ) ; return true ; } return false ; } finally { lock . writeLock ( ) . unlock ( ) ; } }
Removes an entity listener for a entity of the given class
34
boolean isEmpty ( String repoFullName ) { lock . readLock ( ) . lock ( ) ; try { verifyRepoRegistered ( repoFullName ) ; return entityListenersByRepo . get ( repoFullName ) . isEmpty ( ) ; } finally { lock . readLock ( ) . unlock ( ) ; } }
Check if a repository has no listeners Repository must be registered
35
private void verifyRepoRegistered ( String repoFullName ) { lock . readLock ( ) . lock ( ) ; try { if ( ! entityListenersByRepo . containsKey ( requireNonNull ( repoFullName ) ) ) { LOG . error ( "Repository [{}] is not registered in the entity listeners service" , repoFullName ) ; throw new MolgenisDataException ( "Repository [" + repoFullName + "] is not registered, please contact your administrator" ) ; } } finally { lock . readLock ( ) . unlock ( ) ; } }
Verify that the repository is registered
36
public void populateLocalizationStrings ( AllPropertiesMessageSource source ) { source . getAllMessageIds ( ) . asMap ( ) . forEach ( ( namespace , messageIds ) -> updateNamespace ( source , namespace , ImmutableSet . copyOf ( messageIds ) ) ) ; }
Adds all values in all namespaces from those specified in the property files for that namespace .
37
@ SuppressWarnings ( "squid:S3752" ) @ RequestMapping ( method = { RequestMethod . GET , RequestMethod . POST } ) public String forwardDefaultMenuDefaultPlugin ( Model model ) { Menu menu = menuReaderService . getMenu ( ) . orElseThrow ( ( ) -> new RuntimeException ( "main menu does not exist" ) ) ; String menuId = menu . getId ( ) ; model . addAttribute ( KEY_MENU_ID , menuId ) ; Optional < MenuItem > optionalActiveItem = menu . firstItem ( ) ; if ( ! optionalActiveItem . isPresent ( ) ) { LOG . warn ( "main menu does not contain any (accessible) items" ) ; return "forward:/login" ; } MenuItem activeItem = optionalActiveItem . get ( ) ; String pluginId = activeItem . getId ( ) ; String contextUri = URI + '/' + menuId + '/' + pluginId ; addModelAttributes ( model , contextUri ) ; return getForwardPluginUri ( activeItem . getId ( ) , null , getQueryString ( activeItem ) ) ; }
Forwards to the first plugin of the first menu that the user can read since no menu path is provided .
38
private EntityPermission getPermission ( Action operation ) { EntityPermission result ; switch ( operation ) { case COUNT : case READ : result = EntityPermission . READ ; break ; case UPDATE : result = EntityPermission . UPDATE ; break ; case DELETE : result = EntityPermission . DELETE ; break ; case CREATE : throw new UnexpectedEnumException ( Action . CREATE ) ; default : throw new IllegalArgumentException ( "Illegal operation" ) ; } return result ; }
Finds out what permission to check for an operation that is being performed on this repository .
39
public JobFactory < MappingJobExecution > mappingJobFactory ( ) { return new JobFactory < MappingJobExecution > ( ) { public Job createJob ( MappingJobExecution mappingJobExecution ) { final String mappingProjectId = mappingJobExecution . getMappingProjectId ( ) ; final String targetEntityTypeId = mappingJobExecution . getTargetEntityTypeId ( ) ; final String packageId = mappingJobExecution . getPackageId ( ) ; final String label = mappingJobExecution . getLabel ( ) ; final Boolean addSourceAttribute = mappingJobExecution . isAddSourceAttribute ( ) ; final String resultUrl = menuReaderService . findMenuItemPath ( DataExplorerController . ID ) + "?entity=" + targetEntityTypeId ; mappingJobExecution . setResultUrl ( resultUrl ) ; return progress -> mappingService . applyMappings ( mappingProjectId , targetEntityTypeId , addSourceAttribute , packageId , label , progress ) ; } } ; }
The MappingJob Factory bean .
40
public static Object convert ( Object source , Attribute attr ) { try { return convert ( source , attr . getDataType ( ) ) ; } catch ( DataConversionException e ) { throw new AttributeValueConversionException ( format ( "Conversion failure in entity type [%s] attribute [%s]; %s" , attr . getEntity ( ) . getId ( ) , attr . getName ( ) , e . getMessage ( ) ) , e ) ; } }
Convert value to the type based on the given attribute .
41
@ GetMapping ( value = "/{entityTypeId}/exist" , produces = APPLICATION_JSON_VALUE ) public boolean entityExists ( @ PathVariable ( "entityTypeId" ) String entityTypeId ) { return dataService . hasRepository ( entityTypeId ) ; }
Checks if an entity exists .
42
@ GetMapping ( value = "/{entityTypeId}/meta" , produces = APPLICATION_JSON_VALUE ) public EntityTypeResponse retrieveEntityType ( @ PathVariable ( "entityTypeId" ) String entityTypeId , @ RequestParam ( value = "attributes" , required = false ) String [ ] attributes , @ RequestParam ( value = "expand" , required = false ) String [ ] attributeExpands ) { Set < String > attributeSet = toAttributeSet ( attributes ) ; Map < String , Set < String > > attributeExpandSet = toExpandMap ( attributeExpands ) ; EntityType meta = dataService . getEntityType ( entityTypeId ) ; return new EntityTypeResponse ( meta , attributeSet , attributeExpandSet , permissionService , dataService ) ; }
Gets the metadata for an entity
43
@ GetMapping ( value = "/{entityTypeId}/{id}" , produces = APPLICATION_JSON_VALUE ) public Map < String , Object > retrieveEntity ( @ PathVariable ( "entityTypeId" ) String entityTypeId , @ PathVariable ( "id" ) String untypedId , @ RequestParam ( value = "attributes" , required = false ) String [ ] attributes , @ RequestParam ( value = "expand" , required = false ) String [ ] attributeExpands ) { Set < String > attributesSet = toAttributeSet ( attributes ) ; Map < String , Set < String > > attributeExpandSet = toExpandMap ( attributeExpands ) ; EntityType meta = dataService . getEntityType ( entityTypeId ) ; Object id = getTypedValue ( untypedId , meta . getIdAttribute ( ) ) ; Entity entity = dataService . findOneById ( entityTypeId , id ) ; if ( entity == null ) { throw new UnknownEntityException ( meta , id ) ; } return getEntityAsMap ( entity , meta , attributesSet , attributeExpandSet ) ; }
Get s an entity by it s id
44
@ DeleteMapping ( "/{entityTypeId}/{id}" ) @ ResponseStatus ( NO_CONTENT ) public void deleteDelete ( @ PathVariable ( "entityTypeId" ) String entityTypeId , @ PathVariable ( "id" ) String untypedId ) { delete ( entityTypeId , untypedId ) ; }
Deletes an entity by it s id
45
@ PostMapping ( value = "/{entityTypeId}/{id}" , params = "_method=DELETE" ) @ ResponseStatus ( NO_CONTENT ) public void deletePost ( @ PathVariable ( "entityTypeId" ) String entityTypeId , @ PathVariable ( "id" ) String untypedId ) { delete ( entityTypeId , untypedId ) ; }
Deletes an entity by it s id but tunnels DELETE through POST
46
@ DeleteMapping ( "/{entityTypeId}" ) @ ResponseStatus ( NO_CONTENT ) public void deleteAll ( @ PathVariable ( "entityTypeId" ) String entityTypeId ) { dataService . deleteAll ( entityTypeId ) ; }
Deletes all entities for the given entity name
47
@ PostMapping ( value = "/{entityTypeId}" , params = "_method=DELETE" ) @ ResponseStatus ( NO_CONTENT ) public void deleteAllPost ( @ PathVariable ( "entityTypeId" ) String entityTypeId ) { dataService . deleteAll ( entityTypeId ) ; }
Deletes all entities for the given entity name but tunnels DELETE through POST
48
@ DeleteMapping ( value = "/{entityTypeId}/meta" ) @ ResponseStatus ( NO_CONTENT ) public void deleteMeta ( @ PathVariable ( "entityTypeId" ) String entityTypeId ) { deleteMetaInternal ( entityTypeId ) ; }
Deletes all entities and entity meta data for the given entity name
49
@ PostMapping ( value = "/{entityTypeId}/meta" , params = "_method=DELETE" ) @ ResponseStatus ( NO_CONTENT ) public void deleteMetaPost ( @ PathVariable ( "entityTypeId" ) String entityTypeId ) { deleteMetaInternal ( entityTypeId ) ; }
Deletes all entities and entity meta data for the given entity name but tunnels DELETE through POST
50
@ SuppressWarnings ( "deprecation" ) private EntityCollectionResponse retrieveEntityCollectionInternal ( String entityTypeId , EntityCollectionRequest request , Set < String > attributesSet , Map < String , Set < String > > attributeExpandsSet ) { EntityType meta = dataService . getEntityType ( entityTypeId ) ; Repository < Entity > repository = dataService . getRepository ( entityTypeId ) ; Sort sort ; SortV1 sortV1 = request . getSort ( ) ; if ( sortV1 != null ) { sort = new Sort ( ) ; for ( SortV1 . OrderV1 orderV1 : sortV1 ) { sort . on ( orderV1 . getProperty ( ) , orderV1 . getDirection ( ) == SortV1 . DirectionV1 . ASC ? Sort . Direction . ASC : Sort . Direction . DESC ) ; } } else { sort = null ; } List < QueryRule > queryRules = request . getQ ( ) == null ? Collections . emptyList ( ) : request . getQ ( ) ; Query < Entity > q = new QueryImpl < > ( queryRules ) . pageSize ( request . getNum ( ) ) . offset ( request . getStart ( ) ) . sort ( sort ) ; Iterable < Entity > it = ( ) -> dataService . findAll ( entityTypeId , q ) . iterator ( ) ; Long count = repository . count ( new QueryImpl < > ( q ) . setOffset ( 0 ) . setPageSize ( 0 ) ) ; EntityPager pager = new EntityPager ( request . getStart ( ) , request . getNum ( ) , count , it ) ; List < Map < String , Object > > entities = new ArrayList < > ( ) ; for ( Entity entity : it ) { entities . add ( getEntityAsMap ( entity , meta , attributesSet , attributeExpandsSet ) ) ; } return new EntityCollectionResponse ( pager , entities , UriUtils . createEntityCollectionUriPath ( entityTypeId ) , meta , permissionService , dataService ) ; }
Handles a Query
51
public JobFactory < FileIngestJobExecution > fileIngestJobFactory ( ) { return new JobFactory < FileIngestJobExecution > ( ) { public Job createJob ( FileIngestJobExecution fileIngestJobExecution ) { final String targetEntityId = fileIngestJobExecution . getTargetEntityId ( ) ; final String url = fileIngestJobExecution . getUrl ( ) ; final String loader = fileIngestJobExecution . getLoader ( ) ; String dataExplorerURL = menuReaderService . findMenuItemPath ( "dataexplorer" ) ; fileIngestJobExecution . setResultUrl ( format ( "{0}?entity={1}" , dataExplorerURL , targetEntityId ) ) ; return progress -> fileIngester . ingest ( targetEntityId , url , loader , fileIngestJobExecution . getIdentifier ( ) , progress ) ; } } ; }
The FileIngestJob Factory bean .
52
public static Iterable < String > getAttributeNames ( Iterable < Attribute > attrs ) { return ( ) -> stream ( attrs ) . map ( Attribute :: getName ) . iterator ( ) ; }
Returns attribute names for the given attributes
53
public static String buildFullName ( Package aPackage , String simpleName ) { String fullName ; if ( aPackage != null ) { fullName = aPackage . getId ( ) + PACKAGE_SEPARATOR + simpleName ; } else { fullName = simpleName ; } return fullName ; }
Builds and returns an entity full name based on a package and a simpleName
54
private static void checkForKeyword ( String name ) { if ( KEYWORDS . contains ( name ) || KEYWORDS . contains ( name . toUpperCase ( ) ) ) { throw new MolgenisDataException ( "Name [" + name + "] is not allowed because it is a reserved keyword." ) ; } }
Checks if a name is a reserved keyword .
55
< E extends Entity > void registerStaticEntityFactory ( EntityFactory < E , ? > staticEntityFactory ) { String entityTypeId = staticEntityFactory . getEntityTypeId ( ) ; staticEntityFactoryMap . put ( entityTypeId , staticEntityFactory ) ; }
Registers a static entity factory
56
private void validateCsvFile ( List < String [ ] > content , String fileName ) { if ( content . isEmpty ( ) ) { throw new MolgenisDataException ( format ( "CSV-file: [{0}] is empty" , fileName ) ) ; } if ( content . size ( ) == 1 ) { throw new MolgenisDataException ( format ( "Header was found, but no data is present in file [{0}]" , fileName ) ) ; } int headerLength = content . get ( 0 ) . length ; content . forEach ( row -> { if ( row . length != headerLength ) { throw new MolgenisDataException ( format ( "Column count in CSV-file: [{0}] is not consistent" , fileName ) ) ; } } ) ; }
Validates CSV file content .
57
public Object eval ( String expression , Entity entity , int depth ) { return eval ( createBindings ( entity , depth ) , expression ) ; }
Evaluate a expression for a given entity .
58
private Object eval ( Bindings bindings , String expression ) { try { return jsScriptEngine . eval ( bindings , expression ) ; } catch ( javax . script . ScriptException t ) { return new ScriptException ( t . getCause ( ) . getMessage ( ) , t . getCause ( ) ) ; } catch ( Exception t ) { return new ScriptException ( t ) ; } }
Evaluates an expression with the given bindings .
59
private Bindings createBindings ( Entity entity , int depth ) { Bindings bindings = new SimpleBindings ( ) ; JSObject global = ( JSObject ) magmaBindings . get ( "nashorn.global" ) ; JSObject magmaScript = ( JSObject ) global . getMember ( KEY_MAGMA_SCRIPT ) ; JSObject dollarFunction = ( JSObject ) magmaScript . getMember ( KEY_DOLLAR ) ; JSObject bindFunction = ( JSObject ) dollarFunction . getMember ( BIND ) ; Object boundDollar = bindFunction . call ( dollarFunction , toScriptEngineValueMap ( entity , depth ) ) ; bindings . put ( KEY_DOLLAR , boundDollar ) ; bindings . put ( KEY_NEW_VALUE , magmaScript . getMember ( KEY_NEW_VALUE ) ) ; bindings . put ( KEY_IS_NULL , magmaScript . getMember ( KEY_IS_NULL ) ) ; return bindings ; }
Creates magmascript bindings for a given Entity .
60
private Object toScriptEngineValueMap ( Entity entity , int depth ) { if ( entity != null ) { Object idValue = toScriptEngineValue ( entity , entity . getEntityType ( ) . getIdAttribute ( ) , 0 ) ; if ( depth == 0 ) { return idValue ; } else { Map < String , Object > map = Maps . newHashMap ( ) ; entity . getEntityType ( ) . getAtomicAttributes ( ) . forEach ( attr -> map . put ( attr . getName ( ) , toScriptEngineValue ( entity , attr , depth ) ) ) ; map . put ( KEY_ID_VALUE , idValue ) ; return map ; } } else { return null ; } }
Convert entity to a JavaScript object . Adds _idValue as a special key to every level for quick access to the id value of an entity .
61
private boolean isBroader ( AttributeType enrichedTypeGuess , AttributeType columnTypeGuess ) { if ( columnTypeGuess == null && enrichedTypeGuess != null || columnTypeGuess == null ) { return true ; } switch ( columnTypeGuess ) { case INT : return enrichedTypeGuess . equals ( INT ) || enrichedTypeGuess . equals ( LONG ) || enrichedTypeGuess . equals ( DECIMAL ) || enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; case DECIMAL : return enrichedTypeGuess . equals ( DECIMAL ) || enrichedTypeGuess . equals ( DATE ) || enrichedTypeGuess . equals ( DATE_TIME ) || enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; case LONG : return enrichedTypeGuess . equals ( LONG ) || enrichedTypeGuess . equals ( DECIMAL ) || enrichedTypeGuess . equals ( DATE ) || enrichedTypeGuess . equals ( DATE_TIME ) || enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; case BOOL : return enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; case STRING : return enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; case DATE_TIME : return enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; case DATE : return enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; default : return false ; } }
Check if the new enriched type is broader the the previously found type
62
private AttributeType getEnrichedType ( AttributeType guess , Object value ) { if ( guess == null || value == null ) { return guess ; } if ( guess . equals ( STRING ) ) { String stringValue = value . toString ( ) ; if ( stringValue . length ( ) > MAX_STRING_LENGTH ) { return TEXT ; } if ( canValueBeUsedAsDate ( value ) ) { return DATE ; } } else if ( guess . equals ( DECIMAL ) ) { if ( value instanceof Integer ) { return INT ; } else if ( value instanceof Long ) { Long longValue = ( Long ) value ; return longValue > Integer . MIN_VALUE && longValue < Integer . MAX_VALUE ? INT : LONG ; } else if ( value instanceof Double ) { Double doubleValue = ( Double ) value ; if ( doubleValue != Math . rint ( doubleValue ) ) { return DECIMAL ; } if ( doubleValue > Integer . MIN_VALUE && doubleValue < Integer . MAX_VALUE ) { return INT ; } if ( doubleValue > Long . MIN_VALUE && doubleValue < Long . MAX_VALUE ) { return LONG ; } } } return guess ; }
Returns an enriched AttributeType for when the value meets certain criteria i . e . if a string value is longer dan 255 characters the type should be TEXT
63
private AttributeType getCommonType ( AttributeType existingGuess , AttributeType newGuess ) { if ( existingGuess == null && newGuess == null ) { return null ; } if ( existingGuess == null ) { return newGuess ; } if ( newGuess == null ) { return existingGuess ; } if ( existingGuess . equals ( newGuess ) ) { return existingGuess ; } switch ( existingGuess ) { case INT : if ( newGuess . equals ( DECIMAL ) ) { return DECIMAL ; } else if ( newGuess . equals ( LONG ) ) { return LONG ; } else { return STRING ; } case DECIMAL : if ( newGuess . equals ( INT ) || newGuess . equals ( LONG ) ) { return DECIMAL ; } else { return STRING ; } case LONG : if ( newGuess . equals ( INT ) ) { return LONG ; } else if ( newGuess . equals ( DECIMAL ) ) { return DECIMAL ; } else { return STRING ; } default : return STRING ; } }
Returns the AttributeType shared by both types
64
private AttributeType getBasicAttributeType ( Object value ) { if ( value == null ) { return null ; } if ( value instanceof Integer ) { return INT ; } else if ( value instanceof Double || value instanceof Float ) { return DECIMAL ; } else if ( value instanceof Long ) { return LONG ; } else if ( value instanceof Boolean ) { return BOOL ; } else { return STRING ; } }
Sets the basic type based on instance of the value Object
65
private void validateDeleteAllowed ( Attribute attr ) { String attrIdentifier = attr . getIdentifier ( ) ; if ( systemEntityTypeRegistry . hasSystemAttribute ( attrIdentifier ) ) { throw new SystemMetadataModificationException ( ) ; } }
Deleting attribute meta data is allowed for non - system attributes .
66
public String init ( @ RequestParam ( value = "entity" , required = false ) String selectedEntityName , @ RequestParam ( value = "entityId" , required = false ) String selectedEntityId , Model model ) { StringBuilder message = new StringBuilder ( "" ) ; final boolean currentUserIsSu = SecurityUtils . currentUserIsSu ( ) ; Map < String , EntityType > entitiesMeta = dataService . getMeta ( ) . getEntityTypes ( ) . filter ( entityType -> ! entityType . isAbstract ( ) ) . filter ( entityType -> currentUserIsSu || ! EntityTypeUtils . isSystemEntity ( entityType ) ) . sorted ( Comparator . comparing ( EntityType :: getLabel ) ) . collect ( toLinkedMap ( EntityType :: getId , Function . identity ( ) ) ) ; model . addAttribute ( "entitiesMeta" , entitiesMeta ) ; if ( selectedEntityId != null && selectedEntityName == null ) { EntityType entityType = dataService . getMeta ( ) . getEntityType ( selectedEntityId ) . orElse ( null ) ; if ( entityType == null ) { message . append ( "Entity does not exist or you do not have permission on this entity" ) ; } else { selectedEntityName = entityType . getId ( ) ; } if ( selectedEntityName != null ) { checkExistsAndPermission ( selectedEntityName , message ) ; } } if ( StringUtils . isNotEmpty ( message . toString ( ) ) ) { model . addAttribute ( "warningMessage" , message . toString ( ) ) ; } model . addAttribute ( "selectedEntityName" , selectedEntityName ) ; boolean navigatorAvailable = menuReaderService . findMenuItemPath ( NAVIGATOR ) != null ; model . addAttribute ( "showNavigatorLink" , dataExplorerSettings . isShowNavigatorLink ( ) && navigatorAvailable ) ; model . addAttribute ( "hasTrackingId" , null != appSettings . getGoogleAnalyticsTrackingId ( ) ) ; model . addAttribute ( "hasMolgenisTrackingId" , null != appSettings . getGoogleAnalyticsTrackingIdMolgenis ( ) ) ; return "view-dataexplorer" ; }
Show the explorer page
67
private EntityType assignUniqueLabel ( EntityType entityType , CopyState state ) { Set < String > existingLabels ; Package targetPackage = state . targetPackage ( ) ; if ( targetPackage != null ) { existingLabels = stream ( targetPackage . getEntityTypes ( ) ) . map ( EntityType :: getLabel ) . collect ( toSet ( ) ) ; } else { existingLabels = dataService . query ( ENTITY_TYPE_META_DATA , EntityType . class ) . eq ( EntityTypeMetadata . PACKAGE , null ) . findAll ( ) . map ( EntityType :: getLabel ) . collect ( toSet ( ) ) ; } entityType . setLabel ( LabelGenerator . generateUniqueLabel ( entityType . getLabel ( ) , existingLabels ) ) ; return entityType ; }
Checks if there s an EntityType in the target location with the same label . If so keeps adding a postfix until the label is unique .
68
public static String getJunctionTableName ( EntityType entityType , Attribute attr , boolean quotedIdentifier ) { int nrAdditionalChars = 1 ; String entityPart = generateId ( entityType , ( MAX_IDENTIFIER_BYTE_LENGTH - nrAdditionalChars ) / 2 ) ; String attrPart = generateId ( attr , ( MAX_IDENTIFIER_BYTE_LENGTH - nrAdditionalChars ) / 2 ) ; return quotedIdentifier ? getQuotedIdentifier ( entityPart + '_' + attrPart ) : entityPart + '_' + attrPart ; }
Returns the junction table name for the given attribute of the given entity
69
static String getJunctionTableIndexName ( EntityType entityType , Attribute attr , Attribute idxAttr ) { String indexNamePostfix = "_idx" ; int nrAdditionalChars = 1 + indexNamePostfix . length ( ) ; String entityPart = generateId ( entityType , ( MAX_IDENTIFIER_BYTE_LENGTH - nrAdditionalChars ) / 3 ) ; String attrPart = generateId ( attr , ( MAX_IDENTIFIER_BYTE_LENGTH - nrAdditionalChars ) / 3 ) ; String idxAttrPart = generateId ( idxAttr , ( MAX_IDENTIFIER_BYTE_LENGTH - nrAdditionalChars ) / 3 ) ; return getQuotedIdentifier ( entityPart + '_' + attrPart + '_' + idxAttrPart + indexNamePostfix ) ; }
Returns the junction table index name for the given indexed attribute in a junction table
70
public String viewTagWizard ( @ RequestParam ( required = false , value = "selectedTarget" ) String target , Model model ) { List < String > entityTypeIds = dataService . findAll ( ENTITY_TYPE_META_DATA , EntityType . class ) . filter ( entityType -> ! EntityTypeUtils . isSystemEntity ( entityType ) ) . map ( EntityType :: getId ) . collect ( toList ( ) ) ; if ( StringUtils . isEmpty ( target ) ) { Optional < String > findFirst = entityTypeIds . stream ( ) . findFirst ( ) ; if ( findFirst . isPresent ( ) ) { target = findFirst . get ( ) ; } } if ( StringUtils . isEmpty ( target ) ) { throw new IllegalStateException ( "There are no entities available!" ) ; } List < Ontology > ontologies = ontologyService . getOntologies ( ) ; EntityType emd = dataService . getEntityType ( target ) ; List < Attribute > attributes = newArrayList ( emd . getAttributes ( ) ) ; Map < String , Multimap < Relation , OntologyTerm > > taggedAttributes = attributes . stream ( ) . collect ( toMap ( ( Attribute :: getName ) , ( x -> ontologyTagService . getTagsForAttribute ( emd , x ) ) ) ) ; model . addAttribute ( "entity" , emd ) ; model . addAttribute ( "entityTypeIds" , entityTypeIds ) ; model . addAttribute ( "attributes" , attributes ) ; model . addAttribute ( "ontologies" , ontologies ) ; model . addAttribute ( "taggedAttributes" , taggedAttributes ) ; model . addAttribute ( "relations" , Relation . values ( ) ) ; return VIEW_TAG_WIZARD ; }
Displays on tag wizard button press
71
public Language create ( String code , String name , boolean active ) { Language language = super . create ( code ) ; language . setName ( name ) ; language . setActive ( active ) ; return language ; }
Creates a language with the given code and name
72
static String getSqlAddColumn ( EntityType entityType , Attribute attr , ColumnMode columnMode ) { StringBuilder sql = new StringBuilder ( "ALTER TABLE " ) ; String columnSql = getSqlColumn ( entityType , attr , columnMode ) ; sql . append ( getTableName ( entityType ) ) . append ( " ADD " ) . append ( columnSql ) ; List < String > sqlTableConstraints = getSqlTableConstraints ( entityType , attr ) ; if ( ! sqlTableConstraints . isEmpty ( ) ) { sqlTableConstraints . forEach ( sqlTableConstraint -> sql . append ( ",ADD " ) . append ( sqlTableConstraint ) ) ; } return sql . toString ( ) ; }
Returns SQL string to add a column to an existing table .
73
static String getSqlDropColumnDefault ( EntityType entityType , Attribute attr ) { return "ALTER TABLE " + getTableName ( entityType ) + " ALTER COLUMN " + getColumnName ( attr ) + " DROP DEFAULT" ; }
Returns SQL string to remove the default value from an existing column .
74
private static boolean isPersistedInOtherTable ( Attribute attr ) { boolean bidirectionalOneToMany = attr . getDataType ( ) == ONE_TO_MANY && attr . isMappedBy ( ) ; return isMultipleReferenceType ( attr ) || bidirectionalOneToMany ; }
Returns whether this attribute is stored in the entity table or another table such as a junction table or referenced entity table .
75
private static < E extends Entity > boolean isDistinctSelectRequired ( EntityType entityType , Query < E > q ) { return isDistinctSelectRequiredRec ( entityType , q . getRules ( ) ) ; }
Determines whether a distinct select is required based on a given query .
76
static < E extends Entity > String getSqlCount ( EntityType entityType , Query < E > q , List < Object > parameters ) { StringBuilder sqlBuilder = new StringBuilder ( "SELECT COUNT" ) ; String idAttribute = getColumnName ( entityType . getIdAttribute ( ) ) ; List < QueryRule > queryRules = q . getRules ( ) ; if ( queryRules == null || queryRules . isEmpty ( ) ) { sqlBuilder . append ( "(*) FROM " ) . append ( getTableName ( entityType ) ) ; } else { boolean distinctSelectRequired = isDistinctSelectRequired ( entityType , q ) ; if ( distinctSelectRequired ) { sqlBuilder . append ( "(DISTINCT this." ) . append ( idAttribute ) . append ( ')' ) ; } else { sqlBuilder . append ( "(*)" ) ; } String from = getSqlFrom ( entityType , q ) ; String where = getSqlWhere ( entityType , q , parameters , new AtomicInteger ( ) ) ; sqlBuilder . append ( from ) . append ( " WHERE " ) . append ( where ) ; } return sqlBuilder . toString ( ) ; }
Produces SQL to count the number of entities that match the given query . Ignores query offset and pagesize .
77
public Group getGroup ( String groupName ) { Fetch roleFetch = new Fetch ( ) . field ( RoleMetadata . NAME ) . field ( RoleMetadata . LABEL ) ; Fetch fetch = new Fetch ( ) . field ( GroupMetadata . ROLES , roleFetch ) . field ( GroupMetadata . NAME ) . field ( GroupMetadata . LABEL ) . field ( GroupMetadata . DESCRIPTION ) . field ( GroupMetadata . ID ) . field ( GroupMetadata . PUBLIC ) . field ( GroupMetadata . ROOT_PACKAGE ) ; Group group = dataService . query ( GroupMetadata . GROUP , Group . class ) . eq ( GroupMetadata . NAME , groupName ) . fetch ( fetch ) . findOne ( ) ; if ( group == null ) { throw new UnknownEntityException ( groupMetadata , groupMetadata . getAttribute ( GroupMetadata . NAME ) , groupName ) ; } return group ; }
Get the group entity by its unique name .
78
public void addMember ( final Group group , final User user , final Role role ) { ArrayList < Role > groupRoles = newArrayList ( group . getRoles ( ) ) ; Collection < RoleMembership > memberships = roleMembershipService . getMemberships ( groupRoles ) ; boolean isGroupRole = groupRoles . stream ( ) . anyMatch ( gr -> gr . getName ( ) . equals ( role . getName ( ) ) ) ; if ( ! isGroupRole ) { throw new NotAValidGroupRoleException ( role , group ) ; } boolean isMember = memberships . stream ( ) . parallel ( ) . anyMatch ( m -> m . getUser ( ) . equals ( user ) ) ; if ( isMember ) { throw new IsAlreadyMemberException ( user , group ) ; } roleMembershipService . addUserToRole ( user , role ) ; }
Add member to group . User can only be added to a role that belongs to the group . The user can only have a single role within the group
79
@ GetMapping ( "/logo/{name}.{extension}" ) public void getLogo ( OutputStream out , @ PathVariable ( "name" ) String name , @ PathVariable ( "extension" ) String extension , HttpServletResponse response ) throws IOException { File f = fileStore . getFileUnchecked ( "/logo/" + name + "." + extension ) ; if ( ! f . exists ( ) ) { response . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return ; } String contentType = URLConnection . guessContentTypeFromName ( f . getName ( ) ) ; if ( contentType != null ) { response . setContentType ( contentType ) ; } FileCopyUtils . copy ( new FileInputStream ( f ) , out ) ; }
Get a file from the logo subdirectory of the filestore
80
static boolean isPersistedInPostgreSql ( EntityType entityType ) { String backend = entityType . getBackend ( ) ; if ( backend == null ) { if ( null != getApplicationContext ( ) ) { DataService dataService = getApplicationContext ( ) . getBean ( DataService . class ) ; backend = dataService . getMeta ( ) . getDefaultBackend ( ) . getName ( ) ; } else { return true ; } } return backend . equals ( PostgreSqlRepositoryCollection . POSTGRESQL ) ; }
Returns whether the given entity is persisted in PostgreSQL
81
public String generateId ( Attribute attribute ) { String idPart = generateHashcode ( attribute . getEntity ( ) . getId ( ) + attribute . getIdentifier ( ) ) ; String namePart = truncateName ( cleanName ( attribute . getName ( ) ) ) ; return namePart + SEPARATOR + idPart ; }
Generates a field name for the given entity type
82
@ SuppressWarnings ( "WeakerAccess" ) public Entity getPluginSettings ( ) { String entityTypeId = DefaultSettingsEntityType . getSettingsEntityName ( getId ( ) ) ; return RunAsSystemAspect . runAsSystem ( ( ) -> getPluginSettings ( entityTypeId ) ) ; }
Returns an entity containing settings for a plugin or null if no settings exist .
83
DecoratorConfiguration removeReferencesOrDeleteIfEmpty ( List < Object > decoratorParametersToRemove , DecoratorConfiguration configuration ) { List < DecoratorParameters > decoratorParameters = stream ( configuration . getEntities ( PARAMETERS , DecoratorParameters . class ) . spliterator ( ) , false ) . filter ( parameters -> ! decoratorParametersToRemove . contains ( parameters . getId ( ) ) ) . collect ( toList ( ) ) ; if ( decoratorParameters . isEmpty ( ) ) { dataService . deleteById ( DECORATOR_CONFIGURATION , configuration . getIdValue ( ) ) ; return null ; } else { configuration . setDecoratorParameters ( decoratorParameters . stream ( ) ) ; return configuration ; } }
Removes references to DecoratorParameters that will be deleted . If this results in a DecoratorConfiguration without any parameters then the row is deleted .
84
@ Scheduled ( fixedRate = 60000 ) public void logStatistics ( ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Cache stats:" ) ; for ( Map . Entry < String , LoadingCache < Query < Entity > , List < Object > > > cacheEntry : caches . entrySet ( ) ) { LOG . debug ( "{}:{}" , cacheEntry . getKey ( ) , cacheEntry . getValue ( ) . stats ( ) ) ; } } }
Logs cumulative cache statistics for all known caches .
85
static Object getPostgreSqlValue ( Entity entity , Attribute attr ) { String attrName = attr . getName ( ) ; AttributeType attrType = attr . getDataType ( ) ; switch ( attrType ) { case BOOL : return entity . getBoolean ( attrName ) ; case CATEGORICAL : case XREF : Entity xrefEntity = entity . getEntity ( attrName ) ; return xrefEntity != null ? getPostgreSqlValue ( xrefEntity , xrefEntity . getEntityType ( ) . getIdAttribute ( ) ) : null ; case CATEGORICAL_MREF : case MREF : case ONE_TO_MANY : Iterable < Entity > entities = entity . getEntities ( attrName ) ; return stream ( entities ) . map ( mrefEntity -> getPostgreSqlValue ( mrefEntity , mrefEntity . getEntityType ( ) . getIdAttribute ( ) ) ) . collect ( toList ( ) ) ; case DATE : return entity . getLocalDate ( attrName ) ; case DATE_TIME : Instant instant = entity . getInstant ( attrName ) ; return instant != null ? instant . truncatedTo ( ChronoUnit . SECONDS ) . atOffset ( UTC ) : null ; case DECIMAL : return entity . getDouble ( attrName ) ; case EMAIL : case ENUM : case HTML : case HYPERLINK : case SCRIPT : case STRING : case TEXT : return entity . getString ( attrName ) ; case FILE : FileMeta fileEntity = entity . getEntity ( attrName , FileMeta . class ) ; return fileEntity != null ? getPostgreSqlValue ( fileEntity , fileEntity . getEntityType ( ) . getIdAttribute ( ) ) : null ; case INT : return entity . getInt ( attrName ) ; case LONG : return entity . getLong ( attrName ) ; case COMPOUND : throw new IllegalAttributeTypeException ( attrType ) ; default : throw new UnexpectedEnumException ( attrType ) ; } }
Returns the PostgreSQL value for the given entity attribute
86
private void performIndexActions ( Progress progress , String transactionId ) { List < IndexAction > indexActions = dataService . findAll ( INDEX_ACTION , createQueryGetAllIndexActions ( transactionId ) , IndexAction . class ) . collect ( toList ( ) ) ; try { boolean success = true ; int count = 0 ; for ( IndexAction indexAction : indexActions ) { success &= performAction ( progress , count ++ , indexAction ) ; } if ( success ) { progress . progress ( count , "Executed all index actions, cleaning up the actions..." ) ; dataService . delete ( INDEX_ACTION , indexActions . stream ( ) ) ; dataService . deleteById ( INDEX_ACTION_GROUP , transactionId ) ; progress . progress ( count , "Cleaned up the actions." ) ; } } catch ( Exception ex ) { LOG . error ( "Error performing index actions" , ex ) ; throw ex ; } finally { progress . status ( "Refresh index start" ) ; indexService . refreshIndex ( ) ; progress . status ( "Refresh index done" ) ; } }
Performs the IndexActions .
87
private boolean performAction ( Progress progress , int progressCount , IndexAction indexAction ) { requireNonNull ( indexAction ) ; String entityTypeId = indexAction . getEntityTypeId ( ) ; updateIndexActionStatus ( indexAction , IndexActionMetadata . IndexStatus . STARTED ) ; try { if ( dataService . hasEntityType ( entityTypeId ) ) { EntityType entityType = dataService . getEntityType ( entityTypeId ) ; if ( indexAction . getEntityId ( ) != null ) { progress . progress ( progressCount , format ( "Indexing {0}.{1}" , entityType . getId ( ) , indexAction . getEntityId ( ) ) ) ; rebuildIndexOneEntity ( entityTypeId , indexAction . getEntityId ( ) ) ; } else { progress . progress ( progressCount , format ( "Indexing {0}" , entityType . getId ( ) ) ) ; final Repository < Entity > repository = dataService . getRepository ( entityType . getId ( ) ) ; indexService . rebuildIndex ( repository ) ; } } else { EntityType entityType = getEntityType ( indexAction ) ; if ( indexService . hasIndex ( entityType ) ) { progress . progress ( progressCount , format ( "Dropping entityType with id: {0}" , entityType . getId ( ) ) ) ; indexService . deleteIndex ( entityType ) ; } else { progress . progress ( progressCount , format ( "Skip index entity {0}.{1}" , entityType . getId ( ) , indexAction . getEntityId ( ) ) ) ; } } updateIndexActionStatus ( indexAction , IndexActionMetadata . IndexStatus . FINISHED ) ; return true ; } catch ( Exception ex ) { LOG . error ( "Index job failed" , ex ) ; updateIndexActionStatus ( indexAction , IndexActionMetadata . IndexStatus . FAILED ) ; return false ; } }
Performs a single IndexAction
88
private void rebuildIndexOneEntity ( String entityTypeId , String untypedEntityId ) { LOG . trace ( "Indexing [{}].[{}]... " , entityTypeId , untypedEntityId ) ; EntityType entityType = dataService . getEntityType ( entityTypeId ) ; if ( null != entityType ) { Object entityId = getTypedValue ( untypedEntityId , entityType . getIdAttribute ( ) ) ; String entityFullName = entityType . getId ( ) ; Entity actualEntity = dataService . findOneById ( entityFullName , entityId ) ; if ( null == actualEntity ) { LOG . debug ( "Index delete [{}].[{}]." , entityFullName , entityId ) ; indexService . deleteById ( entityType , entityId ) ; return ; } boolean indexEntityExists = indexService . hasIndex ( entityType ) ; if ( ! indexEntityExists ) { LOG . debug ( "Create mapping of repository [{}] because it was not exist yet" , entityTypeId ) ; indexService . createIndex ( entityType ) ; } LOG . debug ( "Index [{}].[{}]." , entityTypeId , entityId ) ; indexService . index ( actualEntity . getEntityType ( ) , actualEntity ) ; } else { throw new MolgenisDataException ( "Unknown EntityType for entityTypeId: " + entityTypeId ) ; } }
Indexes one single entity instance .
89
static Query < IndexAction > createQueryGetAllIndexActions ( String transactionId ) { QueryRule rule = new QueryRule ( INDEX_ACTION_GROUP_ATTR , EQUALS , transactionId ) ; QueryImpl < IndexAction > q = new QueryImpl < > ( rule ) ; q . setSort ( new Sort ( ACTION_ORDER ) ) ; return q ; }
Retrieves the query to get all index actions sorted
90
private IntermediateParseResults getEntityTypeFromSource ( RepositoryCollection source ) { IntermediateParseResults intermediateResults = parseTagsSheet ( source . getRepository ( EMX_TAGS ) ) ; parsePackagesSheet ( source . getRepository ( EMX_PACKAGES ) , intermediateResults ) ; parseEntitiesSheet ( source . getRepository ( EMX_ENTITIES ) , intermediateResults ) ; parseAttributesSheet ( source . getRepository ( EMX_ATTRIBUTES ) , intermediateResults ) ; reiterateToMapRefEntity ( source . getRepository ( EMX_ATTRIBUTES ) , intermediateResults ) ; if ( source . hasRepository ( EMX_LANGUAGES ) ) parseLanguages ( source . getRepository ( EMX_LANGUAGES ) , intermediateResults ) ; if ( source . hasRepository ( EMX_I18NSTRINGS ) ) parseI18nStrings ( source . getRepository ( EMX_I18NSTRINGS ) , intermediateResults ) ; postProcessMetadata ( intermediateResults ) ; return intermediateResults ; }
Parses metadata from a collection of repositories .
91
IntermediateParseResults parseTagsSheet ( Repository < Entity > tagRepository ) { IntermediateParseResults intermediateParseResults = new IntermediateParseResults ( entityTypeFactory ) ; if ( tagRepository != null ) { for ( Entity tagEntity : tagRepository ) { String id = tagEntity . getString ( EMX_TAG_IDENTIFIER ) ; if ( id != null ) { intermediateParseResults . addTag ( id , entityToTag ( id , tagEntity ) ) ; } } } return intermediateParseResults ; }
Parses all tags defined in the tags repository .
92
private void parsePackagesSheet ( Repository < Entity > repo , IntermediateParseResults intermediateResults ) { if ( repo == null ) return ; int rowIndex = 1 ; for ( Entity packageEntity : resolvePackages ( repo ) ) { rowIndex ++ ; parseSinglePackage ( intermediateResults , rowIndex , packageEntity ) ; } }
Parses the packages sheet
93
private static List < Tag > toTags ( IntermediateParseResults intermediateResults , List < String > tagIdentifiers ) { if ( tagIdentifiers . isEmpty ( ) ) { return emptyList ( ) ; } List < Tag > tags = new ArrayList < > ( tagIdentifiers . size ( ) ) ; for ( String tagIdentifier : tagIdentifiers ) { Tag tag = intermediateResults . getTag ( tagIdentifier ) ; if ( tag == null ) { throw new UnknownTagException ( tagIdentifier ) ; } tags . add ( tag ) ; } return tags ; }
Convert tag identifiers to tags
94
List < EntityType > putEntitiesInDefaultPackage ( IntermediateParseResults intermediateResults , String defaultPackageId ) { Package p = getPackage ( intermediateResults , defaultPackageId ) ; if ( p == null ) { throw new UnknownPackageException ( defaultPackageId ) ; } List < EntityType > entities = newArrayList ( ) ; for ( EntityType entityType : intermediateResults . getEntityTypes ( ) ) { if ( entityType . getPackage ( ) == null ) { entityType . setId ( defaultPackageId + PACKAGE_SEPARATOR + entityType . getId ( ) ) ; entityType . setPackage ( p ) ; } entities . add ( entityType ) ; } return entities ; }
Put the entities that are not in a package in the selected package
95
static boolean parseBoolean ( String booleanString , int rowIndex , String columnName ) { if ( booleanString . equalsIgnoreCase ( TRUE . toString ( ) ) ) return true ; else if ( booleanString . equalsIgnoreCase ( FALSE . toString ( ) ) ) return false ; else throw new InvalidValueException ( booleanString , columnName , "TRUE, FALSE" , EMX_ATTRIBUTES , rowIndex ) ; }
Validates whether an EMX value for a boolean attribute is valid and returns the parsed boolean value .
96
private Language toLanguage ( Entity emxLanguageEntity ) { Language language = languageFactory . create ( ) ; language . setCode ( emxLanguageEntity . getString ( EMX_LANGUAGE_CODE ) ) ; language . setName ( emxLanguageEntity . getString ( EMX_LANGUAGE_NAME ) ) ; return language ; }
Creates a language entity from a EMX entity describing a language
97
public < A > Set < A > getAllDependants ( A item , Function < A , Integer > getDepth , Function < A , Set < A > > getDependants ) { Set < A > currentGeneration = singleton ( item ) ; Set < A > result = newHashSet ( ) ; Set < A > visited = newHashSet ( ) ; for ( int depth = 0 ; ! currentGeneration . isEmpty ( ) ; depth ++ ) { currentGeneration = copyOf ( difference ( getDirectDependants ( currentGeneration , getDependants ) , visited ) ) ; result . addAll ( currentGeneration . stream ( ) . filter ( getDepthFilter ( depth , getDepth ) ) . collect ( toSet ( ) ) ) ; visited . addAll ( currentGeneration ) ; } return result ; }
Retrieves all items that depend on a given item .
98
private Integer getLookupAttributeIndex ( EditorAttribute editorAttribute , EditorEntityType editorEntityType ) { String editorAttributeId = editorAttribute . getId ( ) ; int index = editorEntityType . getLookupAttributes ( ) . stream ( ) . map ( EditorAttributeIdentifier :: getId ) . collect ( toList ( ) ) . indexOf ( editorAttributeId ) ; return index != - 1 ? index : null ; }
Find index of editorAttribute in editorEntityType lookupAttributes or return null
99
public AttributeMapping addAttributeMapping ( String targetAttributeName ) { if ( attributeMappings . containsKey ( targetAttributeName ) ) { throw new IllegalStateException ( "AttributeMapping already exists for target attribute " + targetAttributeName ) ; } Attribute targetAttribute = targetEntityType . getAttribute ( targetAttributeName ) ; AttributeMapping attributeMapping = new AttributeMapping ( targetAttribute ) ; attributeMappings . put ( targetAttributeName , attributeMapping ) ; return attributeMapping ; }
Adds a new empty attribute mapping to a target attribute

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
59
Add dataset card