idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
41,100
@ PostMapping ( "/removeMappingProject" ) public String deleteMappingProject ( @ RequestParam ( ) String mappingProjectId ) { MappingProject project = mappingService . getMappingProject ( mappingProjectId ) ; LOG . info ( "Deleting mappingProject {}" , project . getName ( ) ) ; mappingService . deleteMappingProject ( mappingProjectId ) ; return "redirect:" + getMappingServiceMenuUrl ( ) ; }
Removes a mapping project
41,101
@ PostMapping ( "/removeAttributeMapping" ) public String removeAttributeMapping ( @ RequestParam ( ) String mappingProjectId , @ RequestParam ( ) String target , @ RequestParam ( ) String source , @ RequestParam ( ) String attribute ) { MappingProject project = mappingService . getMappingProject ( mappingProjectId ) ; project . getMappingTarget ( target ) . getMappingForSource ( source ) . deleteAttributeMapping ( attribute ) ; mappingService . updateMappingProject ( project ) ; return "redirect:" + getMappingServiceMenuUrl ( ) + "/mappingproject/" + project . getIdentifier ( ) ; }
Removes a attribute mapping
41,102
@ GetMapping ( "/mappingproject/{id}" ) public String viewMappingProject ( @ PathVariable ( "id" ) String identifier , Model model ) { MappingProject project = mappingService . getMappingProject ( identifier ) ; MappingTarget mappingTarget = project . getMappingTargets ( ) . get ( 0 ) ; String target = mappingTarget . getName ( ) ; model . addAttribute ( "entityTypes" , getNewSources ( mappingTarget ) ) ; model . addAttribute ( "compatibleTargetEntities" , mappingService . getCompatibleEntityTypes ( mappingTarget . getTarget ( ) ) . collect ( toList ( ) ) ) ; model . addAttribute ( "selectedTarget" , target ) ; model . addAttribute ( "mappingProject" , project ) ; model . addAttribute ( "attributeTagMap" , getTagsForAttribute ( target , project ) ) ; model . addAttribute ( "packages" , dataService . getMeta ( ) . getPackages ( ) . stream ( ) . filter ( p -> ! isSystemPackage ( p ) ) . collect ( toList ( ) ) ) ; return VIEW_SINGLE_MAPPING_PROJECT ; }
Displays a mapping project .
41,103
void autoGenerateAlgorithms ( EntityMapping mapping , EntityType sourceEntityType , EntityType targetEntityType , MappingProject project ) { algorithmService . autoGenerateAlgorithm ( sourceEntityType , targetEntityType , mapping ) ; mappingService . updateMappingProject ( project ) ; }
Generate algorithms based on semantic matches between attribute tags and descriptions
41,104
private List < EntityType > getNewSources ( MappingTarget target ) { return dataService . getEntityTypeIds ( ) . filter ( name -> isValidSource ( target , name ) ) . map ( dataService :: getEntityType ) . collect ( toList ( ) ) ; }
Lists the entities that may be added as new sources to this mapping project s selected target
41,105
public String init ( Model model ) { final UriComponents uriComponents = ServletUriComponentsBuilder . fromCurrentContextPath ( ) . build ( ) ; model . addAttribute ( "molgenisUrl" , uriComponents . toUriString ( ) + URI + "/swagger.yml" ) ; model . addAttribute ( "baseUrl" , uriComponents . toUriString ( ) ) ; final String currentUsername = SecurityUtils . getCurrentUsername ( ) ; if ( currentUsername != null ) { model . addAttribute ( "token" , tokenService . generateAndStoreToken ( currentUsername , "For Swagger UI" ) ) ; } return "view-swagger-ui" ; }
Serves the Swagger UI which allows you to try out the documented endpoints . Sets the url parameter to the swagger yaml that describes the REST API . Creates an apiKey token for the current user .
41,106
@ GetMapping ( value = "/swagger.yml" , produces = "text/yaml" ) public String swagger ( Model model , HttpServletResponse response ) { response . setContentType ( "text/yaml" ) ; response . setCharacterEncoding ( "UTF-8" ) ; final UriComponents uriComponents = ServletUriComponentsBuilder . fromCurrentContextPath ( ) . build ( ) ; model . addAttribute ( "scheme" , uriComponents . getScheme ( ) ) ; String host = uriComponents . getHost ( ) ; if ( uriComponents . getPort ( ) >= 0 ) { host += ":" + uriComponents . getPort ( ) ; } model . addAttribute ( "host" , host ) ; model . addAttribute ( "entityTypes" , metaDataService . getEntityTypes ( ) . filter ( e -> ! e . isAbstract ( ) ) . map ( EntityType :: getId ) . sorted ( ) . collect ( toList ( ) ) ) ; model . addAttribute ( "attributeTypes" , AttributeType . getOptionsLowercase ( ) ) ; model . addAttribute ( "languageCodes" , getLanguageCodes ( ) . collect ( toList ( ) ) ) ; return "view-swagger" ; }
Serves the Swagger description of the REST API . As host fills in the host where the controller lives . As options for the entity names contains only those entity names that the user can actually see .
41,107
public static String getLanguageCode ( String name ) { if ( ! isI18n ( name ) ) return null ; return name . substring ( name . indexOf ( '-' ) + 1 , name . length ( ) ) ; }
Get the language code of a new with language suffix .
41,108
public void executeScript ( String pythonScript , PythonOutputHandler outputHandler ) { File file = new File ( pythonScriptExecutable ) ; if ( ! file . exists ( ) ) { throw new MolgenisPythonException ( "File [" + pythonScriptExecutable + "] does not exist" ) ; } if ( ! file . canExecute ( ) ) { throw new MolgenisPythonException ( "Can not execute [" + pythonScriptExecutable + "]. Does it have executable permissions?" ) ; } Path tempFile = null ; try { tempFile = Files . createTempFile ( null , ".py" ) ; Files . write ( tempFile , pythonScript . getBytes ( UTF_8 ) , StandardOpenOption . WRITE ) ; String tempScriptFilePath = tempFile . toAbsolutePath ( ) . toString ( ) ; LOG . info ( "Running python script [{}]" , tempScriptFilePath ) ; Process process = Runtime . getRuntime ( ) . exec ( getCommand ( pythonScriptExecutable , tempScriptFilePath ) ) ; final StringBuilder sb = new StringBuilder ( ) ; PythonStreamHandler errorHandler = new PythonStreamHandler ( process . getErrorStream ( ) , output -> sb . append ( output ) . append ( "\n" ) ) ; errorHandler . start ( ) ; if ( outputHandler != null ) { PythonStreamHandler streamHandler = new PythonStreamHandler ( process . getInputStream ( ) , outputHandler ) ; streamHandler . start ( ) ; } process . waitFor ( ) ; if ( process . exitValue ( ) > 0 ) { throw new MolgenisPythonException ( "Error running [" + tempScriptFilePath + "]." + sb . toString ( ) ) ; } LOG . info ( "Script [{}] done" , tempScriptFilePath ) ; } catch ( IOException e ) { throw new MolgenisPythonException ( "Exception executing PythonScipt." , e ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new MolgenisPythonException ( "Exception waiting for PythonScipt to finish" , e ) ; } finally { if ( tempFile != null ) { try { Files . delete ( tempFile ) ; } catch ( IOException e ) { LOG . error ( "" , e ) ; } } } }
Execute a python script and wait for it to finish
41,109
public Entity toEntity ( final EntityType meta , final Map < String , Object > request ) { final Entity entity = entityManager . create ( meta , POPULATE ) ; for ( Attribute attr : meta . getAtomicAttributes ( ) ) { if ( attr . getExpression ( ) == null ) { String paramName = attr . getName ( ) ; if ( request . containsKey ( paramName ) ) { final Object paramValue = request . get ( paramName ) ; Attribute idAttribute = meta . getIdAttribute ( ) ; Object idValue = request . get ( idAttribute . getName ( ) ) ; final Object value = this . toEntityValue ( attr , paramValue , idValue ) ; entity . set ( attr . getName ( ) , value ) ; } } } return entity ; }
Creates a new entity based from a HttpServletRequest . For file attributes persists the file in the file store and persist a file meta data entity .
41,110
public Object toEntityValue ( Attribute attr , Object paramValue , Object id ) { if ( ( paramValue instanceof String ) && ( ( String ) paramValue ) . isEmpty ( ) ) { paramValue = null ; } Object value ; AttributeType attrType = attr . getDataType ( ) ; switch ( attrType ) { case BOOL : value = convertBool ( attr , paramValue ) ; break ; case EMAIL : case ENUM : case HTML : case HYPERLINK : case SCRIPT : case STRING : case TEXT : value = convertString ( attr , paramValue ) ; break ; case CATEGORICAL : case XREF : value = convertRef ( attr , paramValue ) ; break ; case CATEGORICAL_MREF : case MREF : case ONE_TO_MANY : value = convertMref ( attr , paramValue ) ; break ; case DATE : value = convertDate ( attr , paramValue ) ; break ; case DATE_TIME : value = convertDateTime ( attr , paramValue ) ; break ; case DECIMAL : value = convertDecimal ( attr , paramValue ) ; break ; case FILE : value = convertFile ( attr , paramValue , id ) ; break ; case INT : value = convertInt ( attr , paramValue ) ; break ; case LONG : value = convertLong ( attr , paramValue ) ; break ; case COMPOUND : throw new IllegalAttributeTypeException ( attrType ) ; default : throw new UnexpectedEnumException ( attrType ) ; } return value ; }
Converts a HTTP request parameter to a entity value of which the type is defined by the attribute . For file attributes persists the file in the file store and persist a file meta data entity .
41,111
public Schema loadSchema ( String schema ) { try { JSONObject rawSchema = new JSONObject ( new JSONTokener ( schema ) ) ; return SchemaLoader . load ( rawSchema ) ; } catch ( JSONException | SchemaException e ) { throw new InvalidJsonSchemaException ( e ) ; } }
Loads JSON schema . The schema may contain remote references .
41,112
public void validate ( String json , String schemaJson ) { Schema schema = loadSchema ( schemaJson ) ; validate ( json , schema ) ; }
Validates that a JSON string conforms to a JSON schema .
41,113
private QueryBuilder nestedQueryBuilder ( List < Attribute > attributePath , QueryBuilder queryBuilder ) { if ( attributePath . size ( ) == 1 ) { return queryBuilder ; } else if ( attributePath . size ( ) == 2 ) { return QueryBuilders . nestedQuery ( getQueryFieldName ( attributePath . get ( 0 ) ) , queryBuilder , ScoreMode . Avg ) ; } else { throw new UnsupportedOperationException ( CANNOT_FILTER_DEEP_REFERENCE_MSG ) ; } }
Wraps the query in a nested query when a query is done on a reference entity . Returns the original query when it is applied to the current entity .
41,114
public static String concatAttributeHref ( String baseUri , String qualifiedEntityName , Object entityIdValue , String attributeName ) { return String . format ( "%s/%s/%s/%s" , baseUri , encodePathSegment ( qualifiedEntityName ) , encodePathSegment ( DataConverter . toString ( entityIdValue ) ) , encodePathSegment ( attributeName ) ) ; }
Create an encoded href for an attribute
41,115
public static String concatMetaAttributeHref ( String baseUri , String entityParentName , String attributeName ) { return String . format ( "%s/%s/meta/%s" , baseUri , encodePathSegment ( entityParentName ) , encodePathSegment ( attributeName ) ) ; }
Create an encoded href for an attribute meta
41,116
public static String concatEntityHref ( String baseUri , String qualifiedEntityName , Object entityIdValue ) { if ( null == qualifiedEntityName ) { qualifiedEntityName = "" ; } return String . format ( "%s/%s/%s" , baseUri , encodePathSegment ( qualifiedEntityName ) , encodePathSegment ( DataConverter . toString ( entityIdValue ) ) ) ; }
Create an encoded href for an entity
41,117
public static String concatMetaEntityHref ( String baseUri , String qualifiedEntityName ) { return String . format ( "%s/%s/meta" , baseUri , encodePathSegment ( qualifiedEntityName ) ) ; }
Create an encoded href for an entity meta
41,118
public static String concatEntityCollectionHref ( String baseUri , String qualifiedEntityName , String qualifiedIdAttributeName , List < String > entitiesIds ) { String ids ; ids = entitiesIds . stream ( ) . map ( Href :: encodeIdToRSQL ) . collect ( Collectors . joining ( "," ) ) ; return String . format ( "%s/%s?q=%s=in=(%s)" , baseUri , encodePathSegment ( qualifiedEntityName ) , encodePathSegment ( qualifiedIdAttributeName ) , ids ) ; }
Create an encoded href for an entity collection
41,119
@ Transactional ( readOnly = true , isolation = Isolation . SERIALIZABLE ) public void export ( List < EntityType > entityTypes , List < Package > packages , Path downloadFilePath , Progress progress ) { requireNonNull ( progress ) ; if ( ! ( entityTypes . isEmpty ( ) && packages . isEmpty ( ) ) ) { try ( XlsxWriter writer = XlsxWriterFactory . create ( downloadFilePath , timeZoneProvider . getSystemTimeZone ( ) ) ) { exportEmx ( entityTypes , packages , writer , progress ) ; } catch ( CodedRuntimeException e ) { throw e ; } catch ( IOException | RuntimeException e ) { throw new EmxExportException ( e ) ; } } else { throw new EmptyExportRequestException ( ) ; } }
Isolation level needs to be SERIALIZABLE in case IndexActions are being downloaded . The entities have their own transaction and can change during the download when executed with a default isolation level .
41,120
void writeEntityTypes ( Collection < EntityType > entityTypes , XlsxWriter writer ) { LinkedList < EntityType > sortedEntityTypes = sortEntityTypesAbstractFirst ( entityTypes ) ; if ( ! writer . hasSheet ( EMX_ENTITIES ) ) { writer . createSheet ( EMX_ENTITIES , newArrayList ( ENTITIES_ATTRS . keySet ( ) ) ) ; } writer . writeRows ( sortedEntityTypes . stream ( ) . map ( EntityTypeMapper :: map ) , EMX_ENTITIES ) ; }
package private for test
41,121
public static Attribute getQueryRuleAttribute ( QueryRule queryRule , EntityType entityType ) { String queryRuleField = queryRule . getField ( ) ; if ( queryRuleField == null ) { return null ; } Attribute attr = null ; String [ ] queryRuleFieldTokens = StringUtils . split ( queryRuleField , NESTED_ATTRIBUTE_SEPARATOR ) ; EntityType entityTypeAtCurrentDepth = entityType ; for ( int depth = 0 ; depth < queryRuleFieldTokens . length ; ++ depth ) { String attrName = queryRuleFieldTokens [ depth ] ; attr = entityTypeAtCurrentDepth . getAttribute ( attrName ) ; if ( attr == null ) { throw new UnknownAttributeException ( entityTypeAtCurrentDepth , attrName ) ; } if ( depth + 1 < queryRuleFieldTokens . length ) { entityTypeAtCurrentDepth = attr . getRefEntity ( ) ; } } return attr ; }
Returns the attribute for a query rule field .
41,122
private static Function < EntityTypeNode , Set < EntityTypeNode > > getDependencies ( ) { return entityTypeNode -> { EntityType entityType = entityTypeNode . getEntityType ( ) ; Set < EntityTypeNode > refEntityMetaSet = stream ( entityType . getOwnAllAttributes ( ) ) . filter ( attribute -> isProcessableAttribute ( attribute , entityType ) ) . map ( attr -> new EntityTypeNode ( attr . getRefEntity ( ) ) ) . collect ( toCollection ( HashSet :: new ) ) ; EntityType extendsEntityMeta = entityType . getExtends ( ) ; if ( extendsEntityMeta != null ) { refEntityMetaSet . add ( new EntityTypeNode ( extendsEntityMeta ) ) ; } return refEntityMetaSet ; } ; }
Returns dependencies of the given entity meta data .
41,123
private static Set < EntityTypeNode > expandEntityTypeDependencies ( EntityTypeNode entityTypeNode ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "expandEntityTypeDependencies(EntityTypeNode entityTypeNode) --- entity: [{}], skip: [{}]" , entityTypeNode . getEntityType ( ) . getId ( ) , entityTypeNode . isSkip ( ) ) ; } if ( ! entityTypeNode . isSkip ( ) ) { EntityType entityType = entityTypeNode . getEntityType ( ) ; Set < EntityTypeNode > refEntityMetaSet = stream ( entityType . getOwnAllAttributes ( ) ) . filter ( attribute -> isProcessableAttribute ( attribute , entityType ) ) . flatMap ( attr -> { EntityTypeNode nodeRef = new EntityTypeNode ( attr . getRefEntity ( ) , entityTypeNode . getStack ( ) ) ; Set < EntityTypeNode > dependenciesRef = expandEntityTypeDependencies ( nodeRef ) ; dependenciesRef . add ( nodeRef ) ; return dependenciesRef . stream ( ) ; } ) . collect ( toCollection ( HashSet :: new ) ) ; EntityType extendsEntityMeta = entityType . getExtends ( ) ; if ( extendsEntityMeta != null ) { EntityTypeNode nodeRef = new EntityTypeNode ( extendsEntityMeta , entityTypeNode . getStack ( ) ) ; refEntityMetaSet . add ( nodeRef ) ; Set < EntityTypeNode > dependenciesRef = expandEntityTypeDependencies ( nodeRef ) ; refEntityMetaSet . addAll ( dependenciesRef ) ; } return refEntityMetaSet ; } else { return Sets . newHashSet ( ) ; } }
Returns whole tree dependencies of the given entity meta data .
41,124
private boolean hasAuthenticatedMolgenisToken ( ) { boolean hasAuthenticatedMolgenisToken = false ; Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( authentication instanceof RestAuthenticationToken ) { hasAuthenticatedMolgenisToken = authentication . isAuthenticated ( ) ; } return hasAuthenticatedMolgenisToken ; }
Check on authenticated RestAuthenticationToken
41,125
public static Map < String , Attribute > deepCopyAttributes ( EntityType entityType , EntityType entityTypeCopy , AttributeFactory attrFactory ) { Map < String , Attribute > copiedAttributes = new LinkedHashMap < > ( ) ; Map < String , Attribute > ownAttrMap = stream ( entityType . getOwnAllAttributes ( ) ) . map ( attr -> { Attribute attrCopy = Attribute . newInstance ( attr , DEEP_COPY_ATTRS , attrFactory ) ; copiedAttributes . put ( attr . getIdentifier ( ) , attrCopy ) ; return attrCopy ; } ) . map ( attrCopy -> attrCopy . setEntity ( entityTypeCopy ) ) . collect ( toLinkedMap ( Attribute :: getName , Function . identity ( ) ) ) ; ownAttrMap . forEach ( ( attrName , ownAttr ) -> { Attribute ownAttrParent = ownAttr . getParent ( ) ; if ( ownAttrParent != null ) { ownAttr . setParent ( ownAttrMap . get ( ownAttrParent . getName ( ) ) ) ; } } ) ; entityTypeCopy . setOwnAllAttributes ( ownAttrMap . values ( ) ) ; return copiedAttributes ; }
Deep copy all attributes of an EntityType to its copy . Returns a LinkedMap of the old attribute IDs to the newly copied Attributes .
41,126
public String getLabel ( String languageCode ) { String i18nLabel = getString ( getI18nAttributeName ( LABEL , languageCode ) ) ; return i18nLabel != null ? i18nLabel : getLabel ( ) ; }
Label of the entity in the requested language
41,127
public String getDescription ( String languageCode ) { String i18nDescription = getString ( getI18nAttributeName ( DESCRIPTION , languageCode ) ) ; return i18nDescription != null ? i18nDescription : getDescription ( ) ; }
Description of the entity in the requested language
41,128
public Attribute getIdAttribute ( ) { Attribute idAttr = getOwnIdAttribute ( ) ; if ( idAttr == null ) { EntityType extend = getExtends ( ) ; if ( extend != null ) { idAttr = extend . getIdAttribute ( ) ; } } return idAttr ; }
Attribute that is used as unique Id . Id attribute should always be provided .
41,129
public Attribute getLabelAttribute ( ) { Attribute labelAttr = getOwnLabelAttribute ( ) ; if ( labelAttr == null ) { EntityType extend = getExtends ( ) ; if ( extend != null ) { labelAttr = extend . getLabelAttribute ( ) ; } } return labelAttr ; }
Attribute that is used as unique label . If no label exist returns null .
41,130
public Attribute getLabelAttribute ( String langCode ) { Attribute labelAttr = getLabelAttribute ( ) ; Attribute i18nLabelAttr = labelAttr != null ? getAttribute ( labelAttr . getName ( ) + '-' + langCode ) : null ; return i18nLabelAttr != null ? i18nLabelAttr : labelAttr ; }
Gets the correct label attribute for the given language or the default if not found
41,131
public Attribute getAttribute ( String attrName ) { Attribute attr = getCachedOwnAttrs ( ) . get ( attrName ) ; if ( attr == null ) { EntityType extendsEntityType = getExtends ( ) ; if ( extendsEntityType != null ) { attr = extendsEntityType . getAttribute ( attrName ) ; } } return attr ; }
Get attribute by name
41,132
static void addSequenceNumber ( Attribute attr , Iterable < Attribute > attrs ) { Integer sequenceNumber = attr . getSequenceNumber ( ) ; if ( null == sequenceNumber ) { int i = stream ( attrs ) . filter ( a -> null != a . getSequenceNumber ( ) ) . mapToInt ( Attribute :: getSequenceNumber ) . max ( ) . orElse ( - 1 ) ; if ( i == - 1 ) attr . setSequenceNumber ( 0 ) ; else attr . setSequenceNumber ( ++ i ) ; } }
Add a sequence number to the attribute . If the sequence number exists add it ot the attribute . If the sequence number does not exists then find the highest sequence number . If Entity has not attributes with sequence numbers put 0 .
41,133
public void initialize ( ContextRefreshedEvent event ) { ApplicationContext ctx = event . getApplicationContext ( ) ; Stream < String > languageCodes = LanguageService . getLanguageCodes ( ) ; EntityTypeMetadata entityTypeMeta = ctx . getBean ( EntityTypeMetadata . class ) ; AttributeMetadata attrMetaMeta = ctx . getBean ( AttributeMetadata . class ) ; L10nStringMetadata l10nStringMeta = ctx . getBean ( L10nStringMetadata . class ) ; languageCodes . forEach ( languageCode -> { entityTypeMeta . addAttribute ( getI18nAttributeName ( EntityTypeMetadata . LABEL , languageCode ) ) . setNillable ( true ) . setLabel ( "Label (" + languageCode + ')' ) ; entityTypeMeta . addAttribute ( getI18nAttributeName ( EntityTypeMetadata . DESCRIPTION , languageCode ) ) . setNillable ( true ) . setLabel ( "Description (" + languageCode + ')' ) . setDataType ( TEXT ) ; attrMetaMeta . addAttribute ( getI18nAttributeName ( AttributeMetadata . LABEL , languageCode ) ) . setNillable ( true ) . setLabel ( "Label (" + languageCode + ')' ) ; attrMetaMeta . addAttribute ( getI18nAttributeName ( AttributeMetadata . DESCRIPTION , languageCode ) ) . setNillable ( true ) . setLabel ( "Description (" + languageCode + ')' ) . setDataType ( TEXT ) ; l10nStringMeta . addAttribute ( languageCode ) . setNillable ( true ) . setDataType ( TEXT ) ; } ) ; }
Initialize internationalization attributes
41,134
public void populate ( Entity entity ) { generateAutoDateOrDateTime ( singletonList ( entity ) , entity . getEntityType ( ) . getAttributes ( ) ) ; Attribute idAttr = entity . getEntityType ( ) . getIdAttribute ( ) ; if ( idAttr != null && idAttr . isAuto ( ) && entity . getIdValue ( ) == null && ( idAttr . getDataType ( ) == STRING ) ) { entity . set ( idAttr . getName ( ) , idGenerator . generateId ( ) ) ; } }
Populates an entity with auto values
41,135
public void populateL10nStrings ( ) { AllPropertiesMessageSource allPropertiesMessageSource = new AllPropertiesMessageSource ( ) ; String [ ] namespaces = localizationMessageSources . stream ( ) . map ( PropertiesMessageSource :: getNamespace ) . toArray ( String [ ] :: new ) ; allPropertiesMessageSource . addMolgenisNamespaces ( namespaces ) ; localizationPopulator . populateLocalizationStrings ( allPropertiesMessageSource ) ; }
Populates dataService with localization strings from property files on the classpath .
41,136
public void populateLanguages ( ) { dataService . add ( LANGUAGE , languageFactory . create ( LanguageService . DEFAULT_LANGUAGE_CODE , LanguageService . DEFAULT_LANGUAGE_NAME , true ) ) ; dataService . add ( LANGUAGE , languageFactory . create ( "nl" , new Locale ( "nl" ) . getDisplayName ( new Locale ( "nl" ) ) , false ) ) ; dataService . add ( LANGUAGE , languageFactory . create ( "pt" , new Locale ( "pt" ) . getDisplayName ( new Locale ( "pt" ) ) , false ) ) ; dataService . add ( LANGUAGE , languageFactory . create ( "es" , new Locale ( "es" ) . getDisplayName ( new Locale ( "es" ) ) , false ) ) ; dataService . add ( LANGUAGE , languageFactory . create ( "de" , new Locale ( "de" ) . getDisplayName ( new Locale ( "de" ) ) , false ) ) ; dataService . add ( LANGUAGE , languageFactory . create ( "it" , new Locale ( "it" ) . getDisplayName ( new Locale ( "it" ) ) , false ) ) ; dataService . add ( LANGUAGE , languageFactory . create ( "fr" , new Locale ( "fr" ) . getDisplayName ( new Locale ( "fr" ) ) , false ) ) ; dataService . add ( LANGUAGE , languageFactory . create ( "xx" , "My language" , false ) ) ; }
Populate data store with default languages
41,137
List < Boolean > resolveBooleanExpressions ( List < String > expressions , Entity entity ) { if ( expressions . isEmpty ( ) ) { return Collections . emptyList ( ) ; } return jsMagmaScriptEvaluator . eval ( expressions , entity ) . stream ( ) . map ( this :: convertToBoolean ) . collect ( toList ( ) ) ; }
Resolved boolean expressions
41,138
@ PreAuthorize ( "hasAnyRole('ROLE_SU')" ) @ PostMapping ( value = "/add-bootstrap-theme" ) public Style addBootstrapTheme ( @ RequestParam ( value = "bootstrap3-style" ) MultipartFile bootstrap3Style , @ RequestParam ( value = "bootstrap4-style" , required = false ) MultipartFile bootstrap4Style ) throws MolgenisStyleException { String styleIdentifier = bootstrap3Style . getOriginalFilename ( ) ; try { String bs4FileName = null ; InputStream bs3InputStream = null ; InputStream bs4InputStream = null ; try { bs3InputStream = bootstrap3Style . getInputStream ( ) ; if ( bootstrap4Style != null ) { bs4FileName = bootstrap4Style . getOriginalFilename ( ) ; bs4InputStream = bootstrap4Style . getInputStream ( ) ; } return styleService . addStyle ( styleIdentifier , bootstrap3Style . getOriginalFilename ( ) , bs3InputStream , bs4FileName , bs4InputStream ) ; } finally { if ( bs3InputStream != null ) { bs3InputStream . close ( ) ; } if ( bs4InputStream != null ) { bs4InputStream . close ( ) ; } } } catch ( IOException e ) { throw new MolgenisStyleException ( "unable to add style: " + styleIdentifier , e ) ; } }
Add a new bootstrap theme theme is passed as a bootstrap css file . It is mandatory to pass a bootstrap3 style file but optional to pass a bootstrap 4 style file
41,139
private static List < File > unzip ( File file , NameMapper nameMapper ) { try { File parentFile = file . getParentFile ( ) ; TrackingNameMapper trackingNameMapper = new TrackingNameMapper ( parentFile , nameMapper ) ; ZipUtil . unpack ( file , parentFile , trackingNameMapper ) ; return trackingNameMapper . getFiles ( ) ; } catch ( Exception ex ) { throw new UnzipException ( ex ) ; } }
Unzips a zipfile into the directory it resides in .
41,140
public static Map < String , Integer > createNGrams ( String inputQuery , boolean removeStopWords ) { List < String > wordsInString = Lists . newArrayList ( Stemmer . replaceIllegalCharacter ( inputQuery ) . split ( " " ) ) ; if ( removeStopWords ) wordsInString . removeAll ( STOPWORDSLIST ) ; List < String > stemmedWordsInString = wordsInString . stream ( ) . map ( Stemmer :: stem ) . collect ( Collectors . toList ( ) ) ; Map < String , Integer > tokens = new HashMap < > ( ) ; for ( String singleWord : stemmedWordsInString ) { if ( ! StringUtils . isEmpty ( singleWord ) ) { StringBuilder singleString = new StringBuilder ( singleWord . length ( ) + 2 ) ; singleString . append ( '^' ) . append ( singleWord . toLowerCase ( ) ) . append ( '$' ) ; int length = singleString . length ( ) ; for ( int i = 0 ; i < length - 1 ; i ++ ) { String token = null ; if ( i + N_GRAMS < length ) { token = singleString . substring ( i , i + N_GRAMS ) ; } else { token = singleString . substring ( length - 2 ) ; } if ( ! tokens . containsKey ( token ) ) { tokens . put ( token , 1 ) ; } else { tokens . put ( token , ( tokens . get ( token ) + 1 ) ) ; } } } } return tokens ; }
create n - grams tokens of the string .
41,141
private static double calculateScore ( Map < String , Integer > inputStringTokens , Map < String , Integer > ontologyTermTokens ) { if ( inputStringTokens . size ( ) == 0 || ontologyTermTokens . size ( ) == 0 ) return ( double ) 0 ; int totalToken = getTotalNumTokens ( inputStringTokens ) + getTotalNumTokens ( ontologyTermTokens ) ; int numMatchedToken = 0 ; for ( Entry < String , Integer > token : inputStringTokens . entrySet ( ) ) { if ( ontologyTermTokens . containsKey ( token . getKey ( ) ) ) { numMatchedToken += Math . min ( token . getValue ( ) , ontologyTermTokens . get ( token . getKey ( ) ) ) ; } } if ( totalToken == 0 ) { return 0 ; } else { return 2.0 * numMatchedToken / totalToken * 100 ; } }
Calculate the ngram distance
41,142
public void addListener ( SettingsEntityListener settingsEntityListener ) { RunAsSystemAspect . runAsSystem ( ( ) -> entityListenersService . addEntityListener ( entityTypeId , new EntityListener ( ) { public void postUpdate ( Entity entity ) { settingsEntityListener . postUpdate ( entity ) ; } public Object getEntityId ( ) { return getEntityType ( ) . getId ( ) ; } } ) ) ; }
Adds a listener for this settings entity that fires on entity updates
41,143
public void removeListener ( SettingsEntityListener settingsEntityListener ) { RunAsSystemAspect . runAsSystem ( ( ) -> entityListenersService . removeEntityListener ( entityTypeId , new EntityListener ( ) { public void postUpdate ( Entity entity ) { settingsEntityListener . postUpdate ( entity ) ; } public Object getEntityId ( ) { return getEntityType ( ) . getId ( ) ; } } ) ) ; }
Removes a listener for this settings entity that fires on entity updates
41,144
public void add ( Entity entity ) { if ( entity == null ) throw new IllegalArgumentException ( "Entity cannot be null" ) ; if ( cachedAttributes == null ) throw new MolgenisDataException ( "The attribute names are not defined, call writeAttributeNames first" ) ; int i = 0 ; Row poiRow = sheet . createRow ( row ++ ) ; for ( Attribute attribute : cachedAttributes ) { Cell cell = poiRow . createCell ( i ++ , CellType . STRING ) ; cell . setCellValue ( toValue ( entity . get ( attribute . getName ( ) ) ) ) ; } entity . getIdValue ( ) ; }
Add a new row to the sheet
41,145
public void writeAttributeHeaders ( Iterable < Attribute > attributes , AttributeWriteMode attributeWriteMode ) { if ( attributes == null ) throw new IllegalArgumentException ( "Attributes cannot be null" ) ; if ( attributeWriteMode == null ) throw new IllegalArgumentException ( "AttributeWriteMode cannot be null" ) ; if ( cachedAttributes == null ) { Row poiRow = sheet . createRow ( row ++ ) ; int i = 0 ; for ( Attribute attribute : attributes ) { Cell cell = poiRow . createCell ( i ++ , CellType . STRING ) ; switch ( attributeWriteMode ) { case ATTRIBUTE_LABELS : cell . setCellValue ( AbstractCellProcessor . processCell ( attribute . getLabel ( ) , true , cellProcessors ) ) ; break ; case ATTRIBUTE_NAMES : cell . setCellValue ( AbstractCellProcessor . processCell ( attribute . getName ( ) , true , cellProcessors ) ) ; break ; default : throw new UnexpectedEnumException ( attributeWriteMode ) ; } } this . cachedAttributes = attributes ; } }
Write sheet column headers
41,146
public Tag getTagEntity ( String objectIRI , String label , Relation relation , String codeSystemIRI ) { Tag tag = dataService . query ( TAG , Tag . class ) . eq ( OBJECT_IRI , objectIRI ) . and ( ) . eq ( RELATION_IRI , relation . getIRI ( ) ) . and ( ) . eq ( CODE_SYSTEM , codeSystemIRI ) . findOne ( ) ; if ( tag == null ) { tag = tagFactory . create ( ) ; tag . setId ( idGenerator . generateId ( ) ) ; tag . setObjectIri ( objectIRI ) ; tag . setLabel ( label ) ; tag . setRelationIri ( relation . getIRI ( ) ) ; tag . setRelationLabel ( relation . getLabel ( ) ) ; tag . setCodeSystem ( codeSystemIRI ) ; dataService . add ( TAG , tag ) ; } return tag ; }
Fetches a tag from the repository . Creates a new one if it does not yet exist .
41,147
public boolean populate ( ContextRefreshedEvent event ) { boolean databasePopulated = isDatabasePopulated ( ) ; if ( ! databasePopulated ) { LOG . trace ( "Populating database with I18N strings ..." ) ; i18nPopulator . populateLanguages ( ) ; LOG . trace ( "Populated database with I18N strings" ) ; } LOG . trace ( "Populating plugin entities ..." ) ; pluginPopulator . populate ( event . getApplicationContext ( ) ) ; LOG . trace ( "Populated plugin entities" ) ; LOG . trace ( "Populating settings entities ..." ) ; settingsPopulator . initialize ( event ) ; LOG . trace ( "Populated settings entities" ) ; LOG . trace ( "Populating default genome browser attributes ..." ) ; genomeBrowserAttributesPopulator . populate ( ) ; LOG . trace ( "Populated default genome browser attributes" ) ; LOG . trace ( "Populating database with I18N strings ..." ) ; i18nPopulator . populateL10nStrings ( ) ; LOG . trace ( "Populated database with I18N strings" ) ; LOG . trace ( "Populating script type entities ..." ) ; scriptTypePopulator . populate ( ) ; LOG . trace ( "Populated script type entities" ) ; if ( ! databasePopulated ) { LOG . trace ( "Populating database with users, groups and authorities ..." ) ; usersGroupsAuthoritiesPopulator . populate ( ) ; LOG . trace ( "Populated database with users, groups and authorities" ) ; LOG . trace ( "Populating database with application entities ..." ) ; systemEntityPopulator . populate ( event ) ; LOG . trace ( "Populated database with application entities" ) ; } LOG . trace ( "Populating dynamic decorator entities ..." ) ; dynamicDecoratorPopulator . populate ( ) ; LOG . trace ( "Populated dynamic decorator entities" ) ; return databasePopulated ; }
Returns whether the database was populated previously .
41,148
public void validate ( Query < ? extends Entity > query , EntityType entityType ) { query . getRules ( ) . forEach ( queryRule -> validateQueryRule ( queryRule , entityType ) ) ; }
Validates query based on the given entity type converts query values to the expected type if necessary .
41,149
public void setValue ( Object value ) { if ( value instanceof Iterable < ? > ) { this . value = stream ( ( Iterable < ? > ) value ) . map ( this :: toValue ) . collect ( toList ( ) ) ; } else { this . value = toValue ( value ) ; } }
Sets a new value for this rule .
41,150
Set < String > findMatchedWords ( Explanation explanation ) { Set < String > words = new HashSet < > ( ) ; String description = explanation . getDescription ( ) ; if ( description . startsWith ( Options . SUM_OF . toString ( ) ) || description . startsWith ( Options . PRODUCT_OF . toString ( ) ) ) { if ( newArrayList ( explanation . getDetails ( ) ) . stream ( ) . allMatch ( this :: reachLastLevel ) ) { words . add ( extractMatchedWords ( explanation . getDetails ( ) ) ) ; } else { for ( Explanation subExplanation : explanation . getDetails ( ) ) { words . addAll ( findMatchedWords ( subExplanation ) ) ; } } } else if ( description . startsWith ( Options . MAX_OF . toString ( ) ) ) { Explanation maxExplanation = newArrayList ( explanation . getDetails ( ) ) . stream ( ) . max ( ( explanation1 , explanation2 ) -> Float . compare ( explanation1 . getValue ( ) , explanation2 . getValue ( ) ) ) . orElseThrow ( ( ) -> new IllegalStateException ( "explanation.getDetails() shouldn't return an empty array" ) ) ; words . addAll ( findMatchedWords ( maxExplanation ) ) ; } else if ( description . startsWith ( Options . WEIGHT . toString ( ) ) ) { words . add ( getMatchedWord ( description ) ) ; } return words ; }
This method is able to recursively collect all the matched words from Elasticsearch Explanation document
41,151
Map < String , Double > findMatchQueries ( String matchedWordsString , Map < String , String > collectExpandedQueryMap ) { Map < String , Double > qualifiedQueries = new HashMap < > ( ) ; Set < String > matchedWords = splitIntoTerms ( matchedWordsString ) ; for ( Entry < String , String > entry : collectExpandedQueryMap . entrySet ( ) ) { Set < String > wordsInQuery = splitIntoTerms ( entry . getKey ( ) ) ; if ( wordsInQuery . containsAll ( matchedWords ) ) { qualifiedQueries . put ( entry . getKey ( ) , NGramDistanceAlgorithm . stringMatching ( matchedWordsString , entry . getKey ( ) ) ) ; } } return qualifiedQueries ; }
This method is able to find the queries that are used in the matching . Only queries that contain all matched words are potential queries .
41,152
public String init ( final Model model ) { super . init ( model ) ; model . addAttribute ( "adminEmails" , userService . getSuEmailAddresses ( ) ) ; if ( SecurityUtils . currentUserIsAuthenticated ( ) ) { User currentUser = userService . getUser ( SecurityUtils . getCurrentUsername ( ) ) ; if ( currentUser != null ) { model . addAttribute ( "userName" , getFormattedName ( currentUser ) ) ; model . addAttribute ( "userEmail" , currentUser . getEmail ( ) ) ; } } model . addAttribute ( "isRecaptchaEnabled" , appSettings . getRecaptchaIsEnabled ( ) ) ; model . addAttribute ( "recaptchaPublicKey" , appSettings . getRecaptchaPublicKey ( ) ) ; return VIEW_FEEDBACK ; }
Serves feedback form .
41,153
@ SuppressWarnings ( "squid:S3457" ) private SimpleMailMessage createFeedbackMessage ( FeedbackForm form ) { SimpleMailMessage message = new SimpleMailMessage ( ) ; message . setTo ( userService . getSuEmailAddresses ( ) . toArray ( new String [ ] { } ) ) ; if ( form . hasEmail ( ) ) { message . setCc ( form . getEmail ( ) ) ; message . setReplyTo ( form . getEmail ( ) ) ; } else { message . setReplyTo ( "no-reply@molgenis.org" ) ; } String appName = appSettings . getTitle ( ) ; message . setSubject ( String . format ( "[feedback-%s] %s" , appName , form . getSubject ( ) ) ) ; message . setText ( String . format ( "Feedback from %s:\n\n%s" , form . getFrom ( ) , form . getFeedback ( ) ) ) ; return message ; }
Creates a MimeMessage based on a FeedbackForm .
41,154
private static String getFormattedName ( User user ) { List < String > parts = new ArrayList < > ( ) ; if ( user . getTitle ( ) != null ) { parts . add ( user . getTitle ( ) ) ; } if ( user . getFirstName ( ) != null ) { parts . add ( user . getFirstName ( ) ) ; } if ( user . getMiddleNames ( ) != null ) { parts . add ( user . getMiddleNames ( ) ) ; } if ( user . getLastName ( ) != null ) { parts . add ( user . getLastName ( ) ) ; } if ( parts . isEmpty ( ) ) { return null ; } else { return StringUtils . collectionToDelimitedString ( parts , " " ) ; } }
Formats a MolgenisUser s name .
41,155
private byte [ ] generateRandomBytes ( int nBytes , Random random ) { byte [ ] randomBytes = new byte [ nBytes ] ; random . nextBytes ( randomBytes ) ; return randomBytes ; }
Generates a number of random bytes .
41,156
synchronized void unschedule ( String scheduledJobId ) { try { quartzScheduler . deleteJob ( new JobKey ( scheduledJobId , SCHEDULED_JOB_GROUP ) ) ; } catch ( SchedulerException e ) { String message = format ( "Error deleting ScheduledJob ''{0}''" , scheduledJobId ) ; LOG . error ( message , e ) ; throw new ScheduledJobException ( message , e ) ; } }
Remove a job from the quartzScheduler
41,157
private static void validateMappedBy ( Attribute attr , Attribute mappedByAttr ) { if ( mappedByAttr != null ) { if ( ! isSingleReferenceType ( mappedByAttr ) ) { throw new MolgenisDataException ( format ( "Invalid mappedBy attribute [%s] data type [%s]." , mappedByAttr . getName ( ) , mappedByAttr . getDataType ( ) ) ) ; } Attribute refAttr = attr . getRefEntity ( ) . getAttribute ( mappedByAttr . getName ( ) ) ; if ( refAttr == null ) { throw new MolgenisDataException ( format ( "mappedBy attribute [%s] is not part of entity [%s]." , mappedByAttr . getName ( ) , attr . getRefEntity ( ) . getId ( ) ) ) ; } } }
Validate whether the mappedBy attribute is part of the referenced entity .
41,158
private static void validateOrderBy ( Attribute attr , Sort orderBy ) { if ( orderBy != null ) { EntityType refEntity = attr . getRefEntity ( ) ; if ( refEntity != null ) { for ( Sort . Order orderClause : orderBy ) { String refAttrName = orderClause . getAttr ( ) ; if ( refEntity . getAttribute ( refAttrName ) == null ) { throw new MolgenisDataException ( format ( "Unknown entity [%s] attribute [%s] referred to by entity [%s] attribute [%s] sortBy [%s]" , refEntity . getId ( ) , refAttrName , attr . getEntityType ( ) . getId ( ) , attr . getName ( ) , orderBy . toSortString ( ) ) ) ; } } } } }
Validate whether the attribute names defined by the orderBy attribute point to existing attributes in the referenced entity .
41,159
public ImportService getImportService ( File file , RepositoryCollection source ) { final Map < String , ImportService > importServicesMappedToExtensions = Maps . newHashMap ( ) ; importServices . stream ( ) . filter ( importService -> importService . canImport ( file , source ) ) . forEach ( importService -> { for ( String extension : importService . getSupportedFileExtensions ( ) ) { importServicesMappedToExtensions . put ( extension . toLowerCase ( ) , importService ) ; } } ) ; String extension = FileExtensionUtils . findExtensionFromPossibilities ( file . getName ( ) , importServicesMappedToExtensions . keySet ( ) ) ; final ImportService importService = importServicesMappedToExtensions . get ( extension ) ; if ( importService == null ) throw new MolgenisDataException ( "Can not import file. No suitable importer found" ) ; return importService ; }
Finds a suitable ImportService for a FileRepositoryCollection .
41,160
public static String cleanStemPhrase ( String phrase ) { StringBuilder stringBuilder = new StringBuilder ( ) ; for ( String word : replaceIllegalCharacter ( phrase ) . split ( " " ) ) { String stemmedWord = stem ( word ) ; if ( StringUtils . isNotEmpty ( stemmedWord ) ) { if ( stringBuilder . length ( ) > 0 ) { stringBuilder . append ( ' ' ) ; } stringBuilder . append ( stemmedWord ) ; } } return stringBuilder . toString ( ) ; }
Remove illegal characters from the string and stem each single word
41,161
private String constructNodePath ( String parentNodePath , int currentPosition ) { StringBuilder nodePathStringBuilder = new StringBuilder ( ) ; if ( ! StringUtils . isEmpty ( parentNodePath ) ) nodePathStringBuilder . append ( parentNodePath ) . append ( '.' ) ; nodePathStringBuilder . append ( currentPosition ) . append ( '[' ) . append ( nodePathStringBuilder . toString ( ) . split ( "\\." ) . length - 1 ) . append ( ']' ) ; return nodePathStringBuilder . toString ( ) ; }
Constructs the node path string for a child node
41,162
public static Object getTypedValue ( String valueStr , Attribute attr ) { if ( EntityTypeUtils . isReferenceType ( attr ) ) { throw new MolgenisDataException ( "getTypedValue(String, AttributeMetadata) can't be used for attributes referencing entities" ) ; } return getTypedValue ( valueStr , attr , null ) ; }
Convert a string value to a typed value based on a non - entity - referencing attribute data type .
41,163
public static Object getTypedValue ( String valueStr , Attribute attr , EntityManager entityManager ) { if ( valueStr == null ) return null ; switch ( attr . getDataType ( ) ) { case BOOL : return Boolean . valueOf ( valueStr ) ; case CATEGORICAL : case FILE : case XREF : EntityType xrefEntity = attr . getRefEntity ( ) ; Object xrefIdValue = getTypedValue ( valueStr , xrefEntity . getIdAttribute ( ) , entityManager ) ; return entityManager . getReference ( xrefEntity , xrefIdValue ) ; case CATEGORICAL_MREF : case MREF : case ONE_TO_MANY : EntityType mrefEntity = attr . getRefEntity ( ) ; List < String > mrefIdStrValues = ListEscapeUtils . toList ( valueStr ) ; return mrefIdStrValues . stream ( ) . map ( mrefIdStrValue -> getTypedValue ( mrefIdStrValue , mrefEntity . getIdAttribute ( ) , entityManager ) ) . map ( mrefIdValue -> entityManager . getReference ( mrefEntity , mrefIdValue ) ) . collect ( toList ( ) ) ; case COMPOUND : throw new IllegalArgumentException ( "Compound attribute has no value" ) ; case DATE : try { return parseLocalDate ( valueStr ) ; } catch ( DateTimeParseException e ) { throw new MolgenisDataException ( format ( FAILED_TO_PARSE_ATTRIBUTE_AS_DATE_MESSAGE , attr . getName ( ) , valueStr ) , e ) ; } case DATE_TIME : try { return parseInstant ( valueStr ) ; } catch ( DateTimeParseException e ) { throw new MolgenisDataException ( format ( FAILED_TO_PARSE_ATTRIBUTE_AS_DATETIME_MESSAGE , attr . getName ( ) , valueStr ) , e ) ; } case DECIMAL : return Double . valueOf ( valueStr ) ; case EMAIL : case ENUM : case HTML : case HYPERLINK : case SCRIPT : case STRING : case TEXT : return valueStr ; case INT : return Integer . valueOf ( valueStr ) ; case LONG : return Long . valueOf ( valueStr ) ; default : throw new UnexpectedEnumException ( attr . getDataType ( ) ) ; } }
Convert a string value to a typed value based on the attribute data type .
41,164
public static boolean equalsEntities ( Iterable < Entity > entityIterable , Iterable < Entity > otherEntityIterable ) { List < Entity > attrs = newArrayList ( entityIterable ) ; List < Entity > otherAttrs = newArrayList ( otherEntityIterable ) ; if ( attrs . size ( ) != otherAttrs . size ( ) ) return false ; for ( int i = 0 ; i < attrs . size ( ) ; ++ i ) { if ( ! equals ( attrs . get ( i ) , otherAttrs . get ( i ) ) ) return false ; } return true ; }
Returns true if an Iterable equals another Iterable .
41,165
public List < String > getEnumOptions ( ) { String enumOptionsStr = getString ( ENUM_OPTIONS ) ; return enumOptionsStr != null ? asList ( enumOptionsStr . split ( "," ) ) : emptyList ( ) ; }
For enum fields returns the possible enum values
41,166
public Attribute getInversedBy ( ) { if ( hasRefEntity ( ) ) { return Streams . stream ( getRefEntity ( ) . getAtomicAttributes ( ) ) . filter ( Attribute :: isMappedBy ) . filter ( attr -> getName ( ) . equals ( attr . getMappedBy ( ) . getName ( ) ) ) . findFirst ( ) . orElse ( null ) ; } else { return null ; } }
For a reference type attribute searches the referenced entity for its inversed attribute . This is the one - to - many attribute that has mappedBy set to this attribute . Returns null if this is not a reference type attribute or no inverse attribute exists .
41,167
public void grantDefaultPermissions ( GroupValue groupValue ) { PackageIdentity packageIdentity = new PackageIdentity ( groupValue . getRootPackage ( ) . getName ( ) ) ; GroupIdentity groupIdentity = new GroupIdentity ( groupValue . getName ( ) ) ; aclService . createAcl ( groupIdentity ) ; groupValue . getRoles ( ) . forEach ( roleValue -> { PermissionSet permissionSet = PERMISSION_SETS_PER_ROLE . get ( roleValue . getLabel ( ) ) ; Sid roleSid = createRoleSid ( roleValue . getName ( ) ) ; permissionService . grant ( packageIdentity , permissionSet , roleSid ) ; permissionService . grant ( groupIdentity , permissionSet , roleSid ) ; } ) ; if ( groupValue . isPublic ( ) ) { permissionService . grant ( groupIdentity , READ , createAuthoritySid ( AUTHORITY_USER ) ) ; } }
Grants default permissions on the root package and group to the roles of the group
41,168
public Fetch field ( String field , Fetch fetch ) { attrFetchMap . put ( field , fetch ) ; return this ; }
Updates this fetch adding a single field . If the field is a reference the reference will be fetched with the Fetch that is provided .
41,169
public List < String > getTracksString ( Map < String , GenomeBrowserTrack > entityTracks ) { List < String > results = new ArrayList < > ( ) ; if ( hasPermission ( ) ) { Map < String , GenomeBrowserTrack > allTracks = new HashMap < > ( entityTracks ) ; for ( GenomeBrowserTrack track : entityTracks . values ( ) ) { allTracks . putAll ( getReferenceTracks ( track ) ) ; } results = allTracks . values ( ) . stream ( ) . map ( GenomeBrowserTrack :: toTrackString ) . collect ( Collectors . toList ( ) ) ; } return results ; }
Get readable genome entities
41,170
public Entity get ( Repository < Entity > repository , Object id ) { LoadingCache < Object , Optional < Map < String , Object > > > cache = getEntityCache ( repository ) ; EntityType entityType = repository . getEntityType ( ) ; return cache . getUnchecked ( id ) . map ( e -> entityHydration . hydrate ( e , entityType ) ) . orElse ( null ) ; }
Retrieves an entity from the cache or the underlying repository .
41,171
public List < Entity > getBatch ( Repository < Entity > repository , Iterable < Object > ids ) { try { return getEntityCache ( repository ) . getAll ( ids ) . values ( ) . stream ( ) . filter ( Optional :: isPresent ) . map ( Optional :: get ) . map ( e -> entityHydration . hydrate ( e , repository . getEntityType ( ) ) ) . collect ( Collectors . toList ( ) ) ; } catch ( ExecutionException exception ) { if ( exception . getCause ( ) instanceof RuntimeException ) { throw ( RuntimeException ) exception . getCause ( ) ; } throw new MolgenisDataException ( exception ) ; } }
Retrieves a list of entities from the cache . If the cache doesn t yet exist will create the cache .
41,172
private LoadingCache < Object , Optional < Map < String , Object > > > createEntityCache ( Repository < Entity > repository ) { Caffeine < Object , Object > cacheBuilder = Caffeine . newBuilder ( ) . recordStats ( ) . expireAfterAccess ( 10 , MINUTES ) ; if ( ! MetaDataService . isMetaEntityType ( repository . getEntityType ( ) ) ) { cacheBuilder . maximumSize ( MAX_CACHE_SIZE_PER_ENTITY ) ; } LoadingCache < Object , Optional < Map < String , Object > > > cache = CaffeinatedGuava . build ( cacheBuilder , createCacheLoader ( repository ) ) ; GuavaCacheMetrics . monitor ( meterRegistry , cache , "l2." + repository . getEntityType ( ) . getId ( ) ) ; return cache ; }
Creates a new Entity cache
41,173
private void removeMappedByAttributes ( Map < String , EntityType > resolvedEntityTypes ) { resolvedEntityTypes . values ( ) . stream ( ) . flatMap ( EntityType :: getMappedByAttributes ) . filter ( attribute -> resolvedEntityTypes . containsKey ( attribute . getEntity ( ) . getId ( ) ) ) . forEach ( attribute -> dataService . delete ( ATTRIBUTE_META_DATA , attribute ) ) ; }
Removes the mappedBy attributes of each OneToMany pair in the supplied map of EntityTypes
41,174
< T > T call ( Job < T > job , Progress progress , JobExecutionContext jobExecutionContext ) { return runWithContext ( jobExecutionContext , ( ) -> tryCall ( job , progress ) ) ; }
Executes a job in the calling thread .
41,175
private Entity findSynonymWithHighestNgramScore ( String ontologyIri , String queryString , Entity ontologyTermEntity ) { Iterable < Entity > entities = ontologyTermEntity . getEntities ( OntologyTermMetadata . ONTOLOGY_TERM_SYNONYM ) ; if ( Iterables . size ( entities ) > 0 ) { String cleanedQueryString = removeIllegalCharWithSingleWhiteSpace ( queryString ) ; List < Entity > synonymEntities = FluentIterable . from ( entities ) . transform ( ontologyTermSynonymEntity -> { Entity mapEntity = ontologyTermSynonymFactory . create ( ) ; mapEntity . set ( ontologyTermSynonymEntity ) ; String ontologyTermSynonym = removeIllegalCharWithSingleWhiteSpace ( ontologyTermSynonymEntity . getString ( OntologyTermSynonymMetadata . ONTOLOGY_TERM_SYNONYM_ATTR ) ) ; mapEntity . set ( SCORE , NGramDistanceAlgorithm . stringMatching ( cleanedQueryString , ontologyTermSynonym ) ) ; return mapEntity ; } ) . toSortedList ( ( entity1 , entity2 ) -> entity2 . getDouble ( SCORE ) . compareTo ( entity1 . getDouble ( SCORE ) ) ) ; Entity firstMatchedSynonymEntity = Iterables . getFirst ( synonymEntities , ontologyTermSynonymFactory . create ( ) ) ; double topNgramScore = firstMatchedSynonymEntity . getDouble ( SCORE ) ; String topMatchedSynonym = firstMatchedSynonymEntity . getString ( OntologyTermSynonymMetadata . ONTOLOGY_TERM_SYNONYM_ATTR ) ; for ( Entity nextMatchedSynonymEntity : Iterables . skip ( synonymEntities , 1 ) ) { String nextMatchedSynonym = nextMatchedSynonymEntity . getString ( OntologyTermSynonymMetadata . ONTOLOGY_TERM_SYNONYM_ATTR ) ; StringBuilder tempCombinedSynonym = new StringBuilder ( ) ; tempCombinedSynonym . append ( topMatchedSynonym ) . append ( SINGLE_WHITESPACE ) . append ( nextMatchedSynonym ) ; double newScore = NGramDistanceAlgorithm . stringMatching ( cleanedQueryString , removeIllegalCharWithSingleWhiteSpace ( tempCombinedSynonym . toString ( ) ) ) ; if ( newScore > topNgramScore ) { topNgramScore = newScore ; topMatchedSynonym = tempCombinedSynonym . toString ( ) ; } } firstMatchedSynonymEntity . set ( OntologyTermSynonymMetadata . ONTOLOGY_TERM_SYNONYM_ATTR , topMatchedSynonym ) ; firstMatchedSynonymEntity . set ( SCORE , topNgramScore ) ; firstMatchedSynonymEntity . set ( COMBINED_SCORE , topNgramScore ) ; Map < String , Double > weightedWordSimilarity = informationContentService . redistributedNGramScore ( cleanedQueryString , ontologyIri ) ; Set < String > synonymStemmedWords = informationContentService . createStemmedWordSet ( topMatchedSynonym ) ; Set < String > createStemmedWordSet = informationContentService . createStemmedWordSet ( cleanedQueryString ) ; createStemmedWordSet . stream ( ) . filter ( originalWord -> Iterables . contains ( synonymStemmedWords , originalWord ) && weightedWordSimilarity . containsKey ( originalWord ) ) . forEach ( word -> firstMatchedSynonymEntity . set ( COMBINED_SCORE , ( firstMatchedSynonymEntity . getDouble ( COMBINED_SCORE ) + weightedWordSimilarity . get ( word ) ) ) ) ; return firstMatchedSynonymEntity ; } return null ; }
A helper function to calculate the best NGram score from a list ontologyTerm synonyms
41,176
private static String generateBase64Authentication ( String username , String password ) { requireNonNull ( username , password ) ; String userPass = username + ":" + password ; String userPassBase64 = Base64 . getEncoder ( ) . encodeToString ( userPass . getBytes ( UTF_8 ) ) ; return "Basic " + userPassBase64 ; }
Generate base64 authentication based on username and password .
41,177
private String executeScriptExecuteRequest ( String rScript ) throws IOException { URI uri = getScriptExecutionUri ( ) ; HttpPost httpPost = new HttpPost ( uri ) ; NameValuePair nameValuePair = new BasicNameValuePair ( "x" , rScript ) ; httpPost . setEntity ( new UrlEncodedFormEntity ( singletonList ( nameValuePair ) ) ) ; String openCpuSessionKey ; try ( CloseableHttpResponse response = httpClient . execute ( httpPost ) ) { int statusCode = response . getStatusLine ( ) . getStatusCode ( ) ; if ( statusCode >= 200 && statusCode < 300 ) { Header openCpuSessionKeyHeader = response . getFirstHeader ( "X-ocpu-session" ) ; if ( openCpuSessionKeyHeader == null ) { throw new IOException ( "Missing 'X-ocpu-session' header" ) ; } openCpuSessionKey = openCpuSessionKeyHeader . getValue ( ) ; EntityUtils . consume ( response . getEntity ( ) ) ; } else if ( statusCode == 400 ) { HttpEntity entity = response . getEntity ( ) ; String rErrorMessage = EntityUtils . toString ( entity ) ; EntityUtils . consume ( entity ) ; throw new ScriptException ( rErrorMessage ) ; } else { throw new ClientProtocolException ( format ( FORMAT_UNEXPECTED_RESPONSE_STATUS , statusCode ) ) ; } } return openCpuSessionKey ; }
Execute R script using OpenCPU
41,178
private String executeScriptGetResponseRequest ( String openCpuSessionKey , String scriptOutputFilename , String outputPathname ) throws IOException { String responseValue ; if ( scriptOutputFilename != null ) { executeScriptGetFileRequest ( openCpuSessionKey , scriptOutputFilename , outputPathname ) ; responseValue = null ; } else { responseValue = executeScriptGetValueRequest ( openCpuSessionKey ) ; } return responseValue ; }
Retrieve R script response using OpenCPU
41,179
private void executeScriptGetFileRequest ( String openCpuSessionKey , String scriptOutputFilename , String outputPathname ) throws IOException { URI scriptGetValueResponseUri = getScriptGetFileResponseUri ( openCpuSessionKey , scriptOutputFilename ) ; HttpGet httpGet = new HttpGet ( scriptGetValueResponseUri ) ; try ( CloseableHttpResponse response = httpClient . execute ( httpGet ) ) { int statusCode = response . getStatusLine ( ) . getStatusCode ( ) ; if ( statusCode >= 200 && statusCode < 300 ) { HttpEntity entity = response . getEntity ( ) ; Files . copy ( entity . getContent ( ) , Paths . get ( outputPathname ) ) ; EntityUtils . consume ( entity ) ; } else { throw new ClientProtocolException ( format ( FORMAT_UNEXPECTED_RESPONSE_STATUS , statusCode ) ) ; } } }
Retrieve R script file response using OpenCPU and write to file
41,180
private String executeScriptGetValueRequest ( String openCpuSessionKey ) throws IOException { URI scriptGetValueResponseUri = getScriptGetValueResponseUri ( openCpuSessionKey ) ; HttpGet httpGet = new HttpGet ( scriptGetValueResponseUri ) ; String responseValue ; try ( CloseableHttpResponse response = httpClient . execute ( httpGet ) ) { int statusCode = response . getStatusLine ( ) . getStatusCode ( ) ; if ( statusCode >= 200 && statusCode < 300 ) { HttpEntity entity = response . getEntity ( ) ; responseValue = EntityUtils . toString ( entity ) ; EntityUtils . consume ( entity ) ; } else { throw new ClientProtocolException ( format ( FORMAT_UNEXPECTED_RESPONSE_STATUS , statusCode ) ) ; } } return responseValue ; }
Retrieve and return R script STDOUT response using OpenCPU
41,181
public ViewResolver viewResolver ( ) { FreeMarkerViewResolver resolver = new FreeMarkerViewResolver ( ) ; resolver . setCache ( true ) ; resolver . setSuffix ( ".ftl" ) ; resolver . setContentType ( "text/html;charset=UTF-8" ) ; return resolver ; }
Enable spring freemarker viewresolver . All freemarker template names should end with . ftl
41,182
public FreeMarkerConfigurer freeMarkerConfigurer ( ) { FreeMarkerConfigurer result = new FreeMarkerConfigurer ( ) { protected void postProcessConfiguration ( Configuration config ) { config . setObjectWrapper ( new MolgenisFreemarkerObjectWrapper ( VERSION_2_3_23 ) ) ; } protected void postProcessTemplateLoaders ( List < TemplateLoader > templateLoaders ) { templateLoaders . add ( new ClassTemplateLoader ( FreeMarkerConfigurer . class , "" ) ) ; } } ; result . setPreferFileSystemAccess ( false ) ; result . setTemplateLoaderPath ( "classpath:/templates/" ) ; result . setDefaultEncoding ( "UTF-8" ) ; Properties freemarkerSettings = new Properties ( ) ; freemarkerSettings . setProperty ( Configuration . LOCALIZED_LOOKUP_KEY , Boolean . FALSE . toString ( ) ) ; freemarkerSettings . setProperty ( Configuration . NUMBER_FORMAT_KEY , "computer" ) ; result . setFreemarkerSettings ( freemarkerSettings ) ; Map < String , Object > freemarkerVariables = Maps . newHashMap ( ) ; freemarkerVariables . put ( "hasPermission" , new HasPermissionDirective ( permissionService ) ) ; freemarkerVariables . put ( "notHasPermission" , new NotHasPermissionDirective ( permissionService ) ) ; addFreemarkerVariables ( freemarkerVariables ) ; result . setFreemarkerVariables ( freemarkerVariables ) ; return result ; }
Configure freemarker . All freemarker templates should be on the classpath in a package called freemarker
41,183
private String toAttributeName ( String vcfInfoFieldKey ) { String attrName = infoFieldKeyToAttrNameMap . get ( vcfInfoFieldKey ) ; if ( attrName == null ) { throw new RuntimeException ( format ( "Missing attribute for VCF info field [%s]" , vcfInfoFieldKey ) ) ; } return attrName ; }
Returns the corresponding attribute name for a VCF info field key
41,184
private static Set < String > determineVcfInfoFlagFields ( VcfMeta vcfMeta ) { return stream ( vcfMeta . getInfoMeta ( ) ) . filter ( vcfInfoMeta -> vcfInfoMeta . getType ( ) . equals ( VcfMetaInfo . Type . FLAG ) ) . map ( VcfMetaInfo :: getId ) . collect ( toSet ( ) ) ; }
Returns a set of all possible VCF info fields of type Flag
41,185
private static Map < String , String > createInfoFieldKeyToAttrNameMap ( VcfMeta vcfMeta , String entityTypeId ) { Map < String , String > infoFieldIdToAttrNameMap = newHashMapWithExpectedSize ( size ( vcfMeta . getInfoMeta ( ) ) ) ; for ( VcfMetaInfo info : vcfMeta . getInfoMeta ( ) ) { String postFix = "" ; switch ( info . getId ( ) ) { case INTERNAL_ID : case CHROM : case ALT : case POS : case REF : case FILTER : case QUAL : case ID : postFix = '_' + entityTypeId ; break ; default : break ; } String name = info . getId ( ) ; if ( NameValidator . KEYWORDS . contains ( name ) || NameValidator . KEYWORDS . contains ( name . toUpperCase ( ) ) ) { name = name + '_' ; } infoFieldIdToAttrNameMap . put ( info . getId ( ) , name + postFix ) ; } return infoFieldIdToAttrNameMap ; }
Returns a mapping of VCF info field keys to MOLGENIS attribute names
41,186
public Optional < CacheHit < Entity > > get ( String entityTypeId , Object id , EntityType entityType ) { CombinedEntityCache cache = caches . get ( ) ; if ( cache == null ) { return Optional . empty ( ) ; } Optional < CacheHit < Entity > > result = cache . getIfPresent ( entityType , id ) ; if ( result . isPresent ( ) ) { LOG . debug ( "Retrieved entity [{}] from L1 cache that belongs to {}" , id , entityTypeId ) ; } else { LOG . trace ( "No entity with id [{}] present in L1 cache that belongs to {}" , id , entityTypeId ) ; } return result ; }
Retrieves an entity from the L1 cache based on a combination of entity name and entity id .
41,187
public void put ( String entityTypeId , Entity entity ) { CombinedEntityCache entityCache = caches . get ( ) ; if ( entityCache != null ) { entityCache . put ( entity ) ; LOG . trace ( "Added dehydrated row [{}] from entity {} to the L1 cache" , entity . getIdValue ( ) , entityTypeId ) ; } }
Puts an entity into the L1 cache if the cache exists for the current thread .
41,188
private List < Entity > findAllBatch ( List < Object > batch ) { String entityId = getEntityType ( ) . getId ( ) ; EntityType entityType = getEntityType ( ) ; List < Object > missingIds = batch . stream ( ) . filter ( id -> ! l1Cache . get ( entityId , id , entityType ) . isPresent ( ) ) . collect ( toList ( ) ) ; Map < Object , Entity > missingEntities = delegate ( ) . findAll ( missingIds . stream ( ) ) . collect ( toMap ( Entity :: getIdValue , e -> e ) ) ; return batch . stream ( ) . map ( id -> l1Cache . get ( entityId , id , getEntityType ( ) ) . map ( CacheHit :: getValue ) . orElse ( missingEntities . get ( id ) ) ) . collect ( toList ( ) ) ; }
Looks up the Entities for a List of entity IDs . Those present in the cache are returned from cache . The missing ones are retrieved from the decoratedRepository .
41,189
private void evictBiDiReferencedEntityTypes ( ) { getEntityType ( ) . getMappedByAttributes ( ) . map ( Attribute :: getRefEntity ) . forEach ( l1Cache :: evictAll ) ; getEntityType ( ) . getInversedByAttributes ( ) . map ( Attribute :: getRefEntity ) . forEach ( l1Cache :: evictAll ) ; }
Evict all entries for entity types referred to by this entity type through a bidirectional relation .
41,190
private void evictBiDiReferencedEntities ( Entity entity ) { Stream < EntityKey > backreffingEntities = getEntityType ( ) . getMappedByAttributes ( ) . flatMap ( mappedByAttr -> Streams . stream ( entity . getEntities ( mappedByAttr . getName ( ) ) ) ) . map ( EntityKey :: create ) ; Stream < EntityKey > manyToOneEntities = getEntityType ( ) . getInversedByAttributes ( ) . map ( inversedByAttr -> entity . getEntity ( inversedByAttr . getName ( ) ) ) . filter ( Objects :: nonNull ) . map ( EntityKey :: create ) ; l1Cache . evict ( Stream . concat ( backreffingEntities , manyToOneEntities ) ) ; }
Evict all entity instances referenced by this entity instance through a bidirectional relation .
41,191
public Hits < ExplainedAttribute > findAttributes ( EntityType sourceEntityType , Set < String > queryTerms , Collection < OntologyTerm > ontologyTerms ) { Iterable < String > attributeIdentifiers = semanticSearchServiceHelper . getAttributeIdentifiers ( sourceEntityType ) ; QueryRule disMaxQueryRule = semanticSearchServiceHelper . createDisMaxQueryRuleForAttribute ( queryTerms , ontologyTerms ) ; List < QueryRule > finalQueryRules = Lists . newArrayList ( new QueryRule ( AttributeMetadata . ID , Operator . IN , attributeIdentifiers ) ) ; if ( ! disMaxQueryRule . getNestedRules ( ) . isEmpty ( ) ) { finalQueryRules . addAll ( Arrays . asList ( new QueryRule ( Operator . AND ) , disMaxQueryRule ) ) ; } Stream < Entity > attributeEntities = dataService . findAll ( ATTRIBUTE_META_DATA , new QueryImpl < > ( finalQueryRules ) ) ; Map < String , String > collectExpanedQueryMap = semanticSearchServiceHelper . collectExpandedQueryMap ( queryTerms , ontologyTerms ) ; List < ExplainedAttribute > attributeSearchHits = new ArrayList < > ( ) ; AtomicInteger count = new AtomicInteger ( 0 ) ; attributeEntities . forEach ( attributeEntity -> { Attribute attribute = sourceEntityType . getAttribute ( attributeEntity . getString ( AttributeMetadata . NAME ) ) ; Set < ExplainedQueryString > explainedQueryStrings ; boolean isHighQuality ; if ( count . get ( ) < MAX_NUMBER_EXPLAINED_ATTRIBUTES ) { explainedQueryStrings = convertAttributeToExplainedAttribute ( attribute , collectExpanedQueryMap , new QueryImpl < > ( finalQueryRules ) ) ; isHighQuality = isSingleMatchHighQuality ( queryTerms , Sets . newHashSet ( collectExpanedQueryMap . values ( ) ) , explainedQueryStrings ) ; } else { explainedQueryStrings = emptySet ( ) ; isHighQuality = false ; } attributeSearchHits . add ( ExplainedAttribute . create ( attribute , explainedQueryStrings , isHighQuality ) ) ; count . incrementAndGet ( ) ; } ) ; return Hits . create ( attributeSearchHits . stream ( ) . map ( explainedAttribute -> Hit . create ( explainedAttribute , 1f ) ) . collect ( toList ( ) ) ) ; }
public for testability
41,192
public Set < String > createLexicalSearchQueryTerms ( Attribute targetAttribute , Set < String > searchTerms ) { Set < String > queryTerms = new HashSet < > ( ) ; if ( searchTerms != null && ! searchTerms . isEmpty ( ) ) { queryTerms . addAll ( searchTerms ) ; } if ( queryTerms . isEmpty ( ) ) { if ( StringUtils . isNotBlank ( targetAttribute . getLabel ( ) ) ) { queryTerms . add ( targetAttribute . getLabel ( ) ) ; } if ( StringUtils . isNotBlank ( targetAttribute . getDescription ( ) ) ) { queryTerms . add ( targetAttribute . getDescription ( ) ) ; } } return queryTerms ; }
A helper function to create a list of queryTerms based on the information from the targetAttribute as well as user defined searchTerms . If the user defined searchTerms exist the targetAttribute information will not be used .
41,193
public Set < ExplainedQueryString > convertAttributeToExplainedAttribute ( Attribute attribute , Map < String , String > collectExpandedQueryMap , Query < Entity > query ) { EntityType attributeMetaData = dataService . getEntityType ( ATTRIBUTE_META_DATA ) ; String attributeID = attribute . getIdentifier ( ) ; Explanation explanation = elasticSearchExplainService . explain ( query , attributeMetaData , attributeID ) ; return elasticSearchExplainService . findQueriesFromExplanation ( collectExpandedQueryMap , explanation ) ; }
A helper function to explain each of the matched attributes returned by the explain - API
41,194
public static List < Entity > resolvePackages ( Iterable < Entity > packageRepo ) { List < Entity > resolved = new LinkedList < > ( ) ; if ( ( packageRepo == null ) || Iterables . isEmpty ( packageRepo ) ) return resolved ; List < Entity > unresolved = new ArrayList < > ( ) ; Map < String , Entity > resolvedByName = new HashMap < > ( ) ; for ( Entity pack : packageRepo ) { String name = pack . getString ( EMX_PACKAGE_NAME ) ; String parentName = pack . getString ( EMX_PACKAGE_PARENT ) ; if ( Strings . isNullOrEmpty ( parentName ) ) { resolved . add ( pack ) ; resolvedByName . put ( name , pack ) ; } else { unresolved . add ( pack ) ; } } if ( resolved . isEmpty ( ) ) { throw new MissingRootPackageException ( ) ; } List < Entity > ready = new ArrayList < > ( ) ; while ( ! unresolved . isEmpty ( ) ) { for ( Entity pack : unresolved ) { Entity parent = resolvedByName . get ( pack . getString ( EMX_PACKAGE_PARENT ) ) ; if ( parent != null ) { String name = pack . getString ( EMX_PACKAGE_NAME ) ; ready . add ( pack ) ; resolvedByName . put ( name , pack ) ; } } if ( ready . isEmpty ( ) ) { throw new PackageResolveException ( ) ; } resolved . addAll ( ready ) ; unresolved . removeAll ( ready ) ; ready . clear ( ) ; } return resolved ; }
Resolves package fullNames by looping through all the packages and their parents
41,195
public int getOntologyTermDistance ( OntologyTerm ontologyTerm1 , OntologyTerm ontologyTerm2 ) { String nodePath1 = getOntologyTermNodePath ( ontologyTerm1 ) ; String nodePath2 = getOntologyTermNodePath ( ontologyTerm2 ) ; if ( StringUtils . isEmpty ( nodePath1 ) ) { throw new MolgenisDataAccessException ( "The nodePath cannot be null : " + ontologyTerm1 . toString ( ) ) ; } if ( StringUtils . isEmpty ( nodePath2 ) ) { throw new MolgenisDataAccessException ( "The nodePath cannot be null : " + ontologyTerm2 . toString ( ) ) ; } return calculateNodePathDistance ( nodePath1 , nodePath2 ) ; }
Calculate the distance between any two ontology terms in the ontology tree structure by calculating the difference in nodePaths .
41,196
public List < OntologyTerm > getChildren ( OntologyTerm ontologyTerm ) { Iterable < org . molgenis . ontology . core . meta . OntologyTerm > ontologyTermEntities = ( ) -> dataService . query ( ONTOLOGY_TERM , org . molgenis . ontology . core . meta . OntologyTerm . class ) . eq ( ONTOLOGY_TERM_IRI , ontologyTerm . getIRI ( ) ) . findAll ( ) . iterator ( ) ; List < OntologyTerm > children = new ArrayList < > ( ) ; for ( Entity ontologyTermEntity : ontologyTermEntities ) { Entity ontologyEntity = ontologyTermEntity . getEntity ( OntologyTermMetadata . ONTOLOGY ) ; ontologyTermEntity . getEntities ( OntologyTermMetadata . ONTOLOGY_TERM_NODE_PATH ) . forEach ( ontologyTermNodePathEntity -> children . addAll ( getChildOntologyTermsByNodePath ( ontologyEntity , ontologyTermNodePathEntity ) ) ) ; } return children ; }
Retrieve all descendant ontology terms
41,197
static String toValue ( Cell cell , List < CellProcessor > cellProcessors ) { String value ; switch ( cell . getCellTypeEnum ( ) ) { case BLANK : value = null ; break ; case STRING : value = cell . getStringCellValue ( ) ; break ; case NUMERIC : if ( DateUtil . isCellDateFormatted ( cell ) ) { try { LocaleUtil . setUserTimeZone ( LocaleUtil . TIMEZONE_UTC ) ; Date dateCellValue = cell . getDateCellValue ( ) ; value = formatUTCDateAsLocalDateTime ( dateCellValue ) ; } finally { LocaleUtil . resetUserTimeZone ( ) ; } } else { double x = cell . getNumericCellValue ( ) ; if ( x == Math . rint ( x ) && ! Double . isNaN ( x ) && ! Double . isInfinite ( x ) ) value = String . valueOf ( ( long ) x ) ; else value = String . valueOf ( x ) ; } break ; case BOOLEAN : value = String . valueOf ( cell . getBooleanCellValue ( ) ) ; break ; case FORMULA : FormulaEvaluator evaluator = cell . getSheet ( ) . getWorkbook ( ) . getCreationHelper ( ) . createFormulaEvaluator ( ) ; CellValue cellValue ; try { cellValue = evaluator . evaluate ( cell ) ; } catch ( StackOverflowError e ) { LOG . error ( "StackOverflowError evaluating formula" , e ) ; throw new RuntimeException ( "Error evaluating formula, possibly due to deep formula nesting." ) ; } switch ( cellValue . getCellTypeEnum ( ) ) { case BOOLEAN : value = String . valueOf ( cellValue . getBooleanValue ( ) ) ; break ; case NUMERIC : if ( DateUtil . isCellDateFormatted ( cell ) ) { try { LocaleUtil . setUserTimeZone ( LocaleUtil . TIMEZONE_UTC ) ; Date javaDate = DateUtil . getJavaDate ( cellValue . getNumberValue ( ) , false ) ; value = formatUTCDateAsLocalDateTime ( javaDate ) ; } finally { LocaleUtil . resetUserTimeZone ( ) ; } } else { double x = cellValue . getNumberValue ( ) ; if ( x == Math . rint ( x ) && ! Double . isNaN ( x ) && ! Double . isInfinite ( x ) ) value = String . valueOf ( ( long ) x ) ; else value = String . valueOf ( x ) ; } break ; case STRING : value = cellValue . getStringValue ( ) ; break ; case BLANK : value = null ; break ; default : throw new MolgenisDataException ( "unsupported cell type: " + cellValue . getCellTypeEnum ( ) ) ; } break ; default : throw new MolgenisDataException ( "unsupported cell type: " + cell . getCellTypeEnum ( ) ) ; } return AbstractCellProcessor . processCell ( value , false , cellProcessors ) ; }
Gets a cell value as String and process the value with the given cellProcessors
41,198
private static String formatUTCDateAsLocalDateTime ( Date javaDate ) { LocalDateTime localDateTime = javaDate . toInstant ( ) . atZone ( UTC ) . toLocalDateTime ( ) ; return localDateTime . toString ( ) ; }
Formats parsed Date as LocalDateTime string at zone UTC to express that we don t know the timezone .
41,199
public static String getCurrentUri ( ) { HttpServletRequest request = ( ( ServletRequestAttributes ) RequestContextHolder . currentRequestAttributes ( ) ) . getRequest ( ) ; StringBuilder uri = new StringBuilder ( ) ; uri . append ( request . getAttribute ( "javax.servlet.forward.request_uri" ) ) ; if ( StringUtils . isNotBlank ( request . getQueryString ( ) ) ) { uri . append ( "?" ) . append ( request . getQueryString ( ) ) ; } return uri . toString ( ) ; }
Gets the uri which is currently visible in the browser .