idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
34,500
public Attribute addAttribute ( QuotedID id , int type , String typeName , boolean canNull ) { Attribute att = new Attribute ( this , new QualifiedAttributeID ( getID ( ) , id ) , attributes . size ( ) + 1 , type , typeName , canNull , typeMapper . getTermType ( type , typeName ) ) ; Attribute prev = attributeMap . put ( id , att ) ; if ( prev != null ) throw new IllegalArgumentException ( "Duplicate attribute names" ) ; attributes . add ( att ) ; return att ; }
creates a new attribute
34,501
public Attribute getAttribute ( int index ) { Attribute attribute = attributes . get ( index - 1 ) ; return attribute ; }
gets attribute with the specified position
34,502
public static boolean isIndempotent ( Map < Variable , Variable > substitutionMap ) { if ( substitutionMap . isEmpty ( ) ) return true ; Set < Variable > valueSet = new HashSet < > ( substitutionMap . values ( ) ) ; valueSet . retainAll ( substitutionMap . entrySet ( ) ) ; return valueSet . isEmpty ( ) ; }
Returns true if there is common variables in the domain and the range of the substitution map .
34,503
public InternalSparqlQuery translate ( ParsedQuery pq ) throws OntopUnsupportedInputQueryException , OntopInvalidInputQueryException { if ( predicateIdx != 0 || ! program . getRules ( ) . isEmpty ( ) ) throw new IllegalStateException ( "SparqlAlgebraToDatalogTranslator.translate can only be called once." ) ; TupleExpr te = pq . getTupleExpr ( ) ; log . debug ( "SPARQL algebra: \n{}" , te ) ; TranslationResult body = translate ( te ) ; List < Variable > answerVariables ; if ( pq instanceof ParsedTupleQuery || pq instanceof ParsedGraphQuery ) { answerVariables = new ArrayList < > ( body . variables ) ; } else { answerVariables = Collections . emptyList ( ) ; } AtomPredicate pred = atomFactory . getRDFAnswerPredicate ( answerVariables . size ( ) ) ; Function head = termFactory . getFunction ( pred , ( List < Term > ) ( List < ? > ) answerVariables ) ; appendRule ( head , body . atoms ) ; return new InternalSparqlQuery ( program , ImmutableList . copyOf ( answerVariables ) ) ; }
Translate a given SPARQL query object to datalog program .
34,504
public QueryTreeElement removeQuery ( String query_id ) { for ( QueryTreeElement query : queries ) { if ( query . getID ( ) . equals ( query_id ) ) { queries . remove ( query ) ; return query ; } } return null ; }
Removes a query from the group and returns the removed query or null if the query was not found in this group .
34,505
public QueryTreeElement getQuery ( String id ) { for ( QueryTreeElement query : queries ) { if ( query . getID ( ) . equals ( id ) ) { return query ; } } return null ; }
Searches a specific query and returns the object query else returns null .
34,506
private TreeNode getParentTreeNode ( TreeNode child ) { TreeNode parentTreeNode = parentIndex . get ( child ) ; if ( parentTreeNode == null ) return null ; else if ( contains ( parentTreeNode . getQueryNode ( ) ) ) return parentTreeNode ; else throw new RuntimeException ( "Internal error: points to a parent that is not (anymore) in the tree" ) ; }
The returned value might be null .
34,507
protected String getQueryString ( ) { if ( bindings . size ( ) == 0 ) return queryString ; String qry = queryString ; int b = qry . indexOf ( '{' ) ; String select = qry . substring ( 0 , b ) ; String where = qry . substring ( b ) ; for ( String name : bindings . getBindingNames ( ) ) { String replacement = getReplacement ( bindings . getValue ( name ) ) ; if ( replacement != null ) { String pattern = "[\\?\\$]" + name + "(?=\\W)" ; select = select . replaceAll ( pattern , "" ) ; where = where . replaceAll ( pattern , replacement ) ; } } return select + where ; }
all code below is copy - pasted from org . eclipse . rdf4j . repository . sparql . query . SPARQLOperation
34,508
private Set < String > getBooleanConditions ( List < Function > atoms , AliasIndex index ) { Set < String > conditions = new LinkedHashSet < > ( ) ; for ( Function atom : atoms ) { if ( atom . isOperation ( ) ) { if ( atom . getFunctionSymbol ( ) == ExpressionOperation . AND ) { for ( Term t : atom . getTerms ( ) ) { Set < String > arg = getBooleanConditions ( ImmutableList . of ( ( Function ) t ) , index ) ; conditions . addAll ( arg ) ; } } else { String condition = getSQLCondition ( atom , index ) ; conditions . add ( condition ) ; } } else if ( atom . isDataTypeFunction ( ) ) { String condition = getSQLString ( atom , index , false ) ; conditions . add ( condition ) ; } } return conditions ; }
Returns a string with boolean conditions formed with the boolean atoms found in the atoms list .
34,509
private String getTableDefinitions ( List < Function > atoms , AliasIndex index , String JOIN_KEYWORD , boolean parenthesis , String indent ) { List < String > tables = getTableDefs ( atoms , index , INDENT + indent ) ; switch ( tables . size ( ) ) { case 0 : throw new RuntimeException ( "Cannot generate definition for empty data" ) ; case 1 : return tables . get ( 0 ) ; default : String JOIN = "%s\n" + indent + JOIN_KEYWORD + "\n" + INDENT + indent + "%s" ; int size = tables . size ( ) ; String currentJoin = tables . get ( size - 1 ) ; currentJoin = String . format ( JOIN , tables . get ( size - 2 ) , parenthesis ? inBrackets ( currentJoin ) : currentJoin ) ; for ( int i = size - 3 ; i >= 0 ; i -- ) { currentJoin = String . format ( JOIN , tables . get ( i ) , inBrackets ( currentJoin ) ) ; } Set < String > on = getConditionsSet ( atoms , index , true ) ; if ( on . isEmpty ( ) ) return currentJoin ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( currentJoin ) . append ( "\n" ) . append ( indent ) . append ( "ON " ) ; Joiner . on ( " AND\n" + indent ) . appendTo ( sb , on ) ; return sb . toString ( ) ; } }
Returns the table definition for these atoms . By default a list of atoms represents JOIN or LEFT JOIN of all the atoms left to right . All boolean atoms in the list are considered conditions in the ON clause of the JOIN .
34,510
private String getTableDefinition ( Function atom , AliasIndex index , String indent ) { if ( atom . isAlgebraFunction ( ) ) { Predicate functionSymbol = atom . getFunctionSymbol ( ) ; ImmutableList < Function > joinAtoms = convert ( atom . getTerms ( ) ) ; if ( functionSymbol . equals ( datalogFactory . getSparqlJoinPredicate ( ) ) ) { boolean parenthesis = joinAtoms . get ( 0 ) . isAlgebraFunction ( ) || joinAtoms . get ( 1 ) . isAlgebraFunction ( ) ; return getTableDefinitions ( joinAtoms , index , "JOIN" , parenthesis , indent + INDENT ) ; } else if ( functionSymbol . equals ( datalogFactory . getSparqlLeftJoinPredicate ( ) ) ) { boolean parenthesis = joinAtoms . get ( 1 ) . isAlgebraFunction ( ) ; return getTableDefinitions ( joinAtoms , index , "LEFT OUTER JOIN" , parenthesis , indent + INDENT ) ; } } else if ( ! atom . isOperation ( ) && ! atom . isDataTypeFunction ( ) ) { return index . getViewDefinition ( atom ) ; } return null ; }
Returns the table definition for the given atom . If the atom is a simple table or view then it returns the value as defined by the AliasIndex . If the atom is a Join or Left Join it will call getTableDefinitions on the nested term list .
34,511
private int getDataType ( Term term ) { if ( term instanceof Function ) { Function f = ( Function ) term ; Predicate p = f . getFunctionSymbol ( ) ; if ( p instanceof DatatypePredicate ) { RDFDatatype type = ( ( DatatypePredicate ) p ) . getReturnedType ( ) ; return jdbcTypeMapper . getSQLType ( type ) ; } return Types . VARCHAR ; } else if ( term instanceof Variable ) { throw new RuntimeException ( "Cannot return the SQL type for: " + term ) ; } else if ( term . equals ( termFactory . getBooleanConstant ( false ) ) || term . equals ( termFactory . getBooleanConstant ( true ) ) ) { return Types . BOOLEAN ; } return Types . VARCHAR ; }
return the SQL data type
34,512
private String getSelectClauseFragment ( SignatureVariable var , Term term , Optional < TermType > termType , AliasIndex index ) { String typeColumn = getTypeColumnForSELECT ( term , index , termType ) ; String langColumn = getLangColumnForSELECT ( term , index , termType ) ; String mainColumn = getMainColumnForSELECT ( term , index , var . castType ) ; return new StringBuffer ( ) . append ( "\n " ) . append ( typeColumn ) . append ( " AS " ) . append ( var . columnAliases . get ( 0 ) ) . append ( ", " ) . append ( langColumn ) . append ( " AS " ) . append ( var . columnAliases . get ( 1 ) ) . append ( ", " ) . append ( mainColumn ) . append ( " AS " ) . append ( var . columnAliases . get ( 2 ) ) . toString ( ) ; }
produces the select clause of the sql query for the given CQIE
34,513
private String getTypeColumnForSELECT ( Term ht , AliasIndex index , Optional < TermType > optionalTermType ) { if ( ht instanceof Variable ) { return index . getTypeColumn ( ( Variable ) ht ) . map ( QualifiedAttributeID :: getSQLRendering ) . orElseGet ( ( ) -> String . valueOf ( OBJECT . getQuestCode ( ) ) ) ; } else { COL_TYPE colType = optionalTermType . flatMap ( this :: extractColType ) . orElse ( STRING ) ; return String . valueOf ( colType . getQuestCode ( ) ) ; } }
Infers the type of a projected term .
34,514
protected < T extends RelationDefinition > void add ( T td , Map < RelationID , T > schema ) { if ( ! isStillMutable ) { throw new IllegalStateException ( "Too late, cannot add a schema" ) ; } schema . put ( td . getID ( ) , td ) ; if ( td . getID ( ) . hasSchema ( ) ) { RelationID noSchemaID = td . getID ( ) . getSchemalessID ( ) ; if ( ! schema . containsKey ( noSchemaID ) ) { schema . put ( noSchemaID , td ) ; } else { LOGGER . warn ( "DUPLICATE TABLE NAMES, USE QUALIFIED NAMES:\n" + td + "\nAND\n" + schema . get ( noSchemaID ) ) ; } } }
Inserts a new data definition to this metadata object .
34,515
private List < ImmutableTerm > addToTermsList ( String str ) { ArrayList < ImmutableTerm > terms = new ArrayList < > ( ) ; int i , j ; String st ; str = str . substring ( 1 , str . length ( ) - 1 ) ; while ( str . contains ( "{" ) ) { i = getIndexOfCurlyB ( str ) ; if ( i > 0 ) { st = str . substring ( 0 , i ) ; st = st . replace ( "\\\\" , "" ) ; terms . add ( termFactory . getConstantLiteral ( st ) ) ; str = str . substring ( str . indexOf ( "{" , i ) , str . length ( ) ) ; } else if ( i == 0 ) { j = str . indexOf ( "}" ) ; terms . add ( termFactory . getVariable ( str . substring ( 1 , j ) ) ) ; str = str . substring ( j + 1 , str . length ( ) ) ; } else { break ; } } if ( ! str . equals ( "" ) ) { str = str . replace ( "\\\\" , "" ) ; terms . add ( termFactory . getConstantLiteral ( str ) ) ; } return terms ; }
and adds parsed constant literals and template literal to terms list
34,516
private ImmutableTerm getNestedConcat ( String str ) { List < ImmutableTerm > terms ; terms = addToTermsList ( str ) ; if ( terms . size ( ) == 1 ) { return terms . get ( 0 ) ; } ImmutableFunctionalTerm f = termFactory . getImmutableFunctionalTerm ( ExpressionOperation . CONCAT , terms . get ( 0 ) , terms . get ( 1 ) ) ; for ( int j = 2 ; j < terms . size ( ) ; j ++ ) { f = termFactory . getImmutableFunctionalTerm ( ExpressionOperation . CONCAT , f , terms . get ( j ) ) ; } return f ; }
in case of more than two terms need to be concatted
34,517
private RDBMetadata extractDBMetadata ( SQLPPMapping ppMapping , Optional < RDBMetadata > optionalDBMetadata , OBDASpecInput specInput ) throws DBMetadataExtractionException { boolean isDBMetadataProvided = optionalDBMetadata . isPresent ( ) ; if ( isDBMetadataProvided && ( ! settings . isProvidedDBMetadataCompletionEnabled ( ) ) ) return optionalDBMetadata . get ( ) ; try ( Connection localConnection = LocalJDBCConnectionUtils . createConnection ( settings ) ) { return isDBMetadataProvided ? dbMetadataExtractor . extract ( ppMapping , localConnection , optionalDBMetadata . get ( ) , specInput . getConstraintFile ( ) ) : dbMetadataExtractor . extract ( ppMapping , localConnection , specInput . getConstraintFile ( ) ) ; } catch ( SQLException e ) { throw new DBMetadataExtractionException ( e . getMessage ( ) ) ; } }
Makes use of the DB connection
34,518
private ImmutableMap < Predicate , ImmutableList < TermType > > extractCastTypeMap ( Multimap < Predicate , CQIE > ruleIndex , List < Predicate > predicatesInBottomUp , ImmutableMap < CQIE , ImmutableList < Optional < TermType > > > termTypeMap , DBMetadata metadata ) { Map < Predicate , ImmutableList < TermType > > mutableCastMap = Maps . newHashMap ( ) ; for ( Predicate predicate : predicatesInBottomUp ) { ImmutableList < TermType > castTypes = inferCastTypes ( predicate , ruleIndex . get ( predicate ) , termTypeMap , mutableCastMap , metadata ) ; mutableCastMap . put ( predicate , castTypes ) ; } return ImmutableMap . copyOf ( mutableCastMap ) ; }
Infers cast types for each predicate in the bottom up order
34,519
private ImmutableList < TermType > inferCastTypes ( Predicate predicate , Collection < CQIE > samePredicateRules , ImmutableMap < CQIE , ImmutableList < Optional < TermType > > > termTypeMap , Map < Predicate , ImmutableList < TermType > > alreadyKnownCastTypes , DBMetadata metadata ) { if ( samePredicateRules . isEmpty ( ) ) { ImmutableList . Builder < TermType > defaultTypeBuilder = ImmutableList . builder ( ) ; RelationID tableId = relation2Predicate . createRelationFromPredicateName ( metadata . getQuotedIDFactory ( ) , predicate ) ; Optional < RelationDefinition > td = Optional . ofNullable ( metadata . getRelation ( tableId ) ) ; IntStream . range ( 0 , predicate . getArity ( ) ) . forEach ( i -> { if ( td . isPresent ( ) ) { Attribute attribute = td . get ( ) . getAttribute ( i + 1 ) ; defaultTypeBuilder . add ( attribute . getTermType ( ) ) ; } else { defaultTypeBuilder . add ( literalType ) ; } } ) ; return defaultTypeBuilder . build ( ) ; } ImmutableMultimap < Integer , TermType > collectedProposedCastTypes = collectProposedCastTypes ( samePredicateRules , termTypeMap , alreadyKnownCastTypes ) ; return collectedProposedCastTypes . keySet ( ) . stream ( ) . sorted ( ) . map ( i -> collectedProposedCastTypes . get ( i ) . stream ( ) . reduce ( null , ( type1 , type2 ) -> type1 == null ? type2 : unifyCastTypes ( type1 , type2 ) ) ) . map ( type -> { if ( type != null ) { return type ; } throw new IllegalStateException ( "Every argument is expected to have a COL_TYPE" ) ; } ) . collect ( ImmutableCollectors . toList ( ) ) ; }
Infers the cast types for one intensional predicate
34,520
private ImmutableMultimap < Integer , TermType > collectProposedCastTypes ( Collection < CQIE > samePredicateRules , ImmutableMap < CQIE , ImmutableList < Optional < TermType > > > termTypeMap , Map < Predicate , ImmutableList < TermType > > alreadyKnownCastTypes ) { ImmutableMultimap . Builder < Integer , TermType > indexedCastTypeBuilder = ImmutableMultimap . builder ( ) ; int arity = samePredicateRules . iterator ( ) . next ( ) . getHead ( ) . getTerms ( ) . size ( ) ; samePredicateRules . forEach ( rule -> { List < Term > headArguments = rule . getHead ( ) . getTerms ( ) ; ImmutableList < Optional < TermType > > termTypes = termTypeMap . get ( rule ) ; IntStream . range ( 0 , arity ) . forEach ( i -> { TermType type = termTypes . get ( i ) . orElseGet ( ( ) -> getCastTypeFromSubRule ( immutabilityTools . convertIntoImmutableTerm ( headArguments . get ( i ) ) , extractDataAtoms ( rule . getBody ( ) ) . collect ( ImmutableCollectors . toList ( ) ) , alreadyKnownCastTypes ) ) ; indexedCastTypeBuilder . put ( i , type ) ; } ) ; } ) ; return indexedCastTypeBuilder . build ( ) ; }
Collects the proposed cast types by the definitions of the current predicate
34,521
private TermType getCastTypeFromSubRule ( ImmutableTerm term , ImmutableList < Function > bodyDataAtoms , Map < Predicate , ImmutableList < TermType > > alreadyKnownCastTypes ) { if ( term instanceof Variable ) { Variable variable = ( Variable ) term ; for ( Function bodyDataAtom : bodyDataAtoms ) { List < Term > arguments = bodyDataAtom . getTerms ( ) ; for ( int i = 0 ; i < arguments . size ( ) ; i ++ ) { if ( arguments . get ( i ) . equals ( variable ) ) { final int index = i ; return Optional . ofNullable ( alreadyKnownCastTypes . get ( bodyDataAtom . getFunctionSymbol ( ) ) ) . map ( types -> types . get ( index ) ) . orElseThrow ( ( ) -> new IllegalStateException ( "No type could be inferred for " + term ) ) ; } } } throw new IllegalStateException ( "Unbounded variable: " + variable ) ; } else if ( term instanceof ImmutableExpression ) { ImmutableExpression expression = ( ImmutableExpression ) term ; ImmutableList < Optional < TermType > > argumentTypes = expression . getTerms ( ) . stream ( ) . map ( t -> getCastTypeFromSubRule ( t , bodyDataAtoms , alreadyKnownCastTypes ) ) . map ( Optional :: of ) . collect ( ImmutableCollectors . toList ( ) ) ; return expression . getOptionalTermType ( argumentTypes ) . orElseThrow ( ( ) -> new IllegalStateException ( "No type could be inferred for " + term ) ) ; } else if ( term instanceof Constant ) { return ( ( Constant ) term ) . getType ( ) ; } else if ( term instanceof ImmutableFunctionalTerm ) { Predicate functionSymbol = ( ( ImmutableFunctionalTerm ) term ) . getFunctionSymbol ( ) ; if ( functionSymbol instanceof DatatypePredicate ) return functionSymbol . getExpectedBaseType ( 0 ) ; } throw new IllegalStateException ( "Could not determine the type of " + term ) ; }
Extracts the cast type of one projected variable from the body atom that provides it .
34,522
public static ForeignKeyConstraint of ( String name , Attribute attribute , Attribute reference ) { return new Builder ( ( DatabaseRelationDefinition ) attribute . getRelation ( ) , ( DatabaseRelationDefinition ) reference . getRelation ( ) ) . add ( attribute , reference ) . build ( name ) ; }
creates a single - attribute foreign key
34,523
private InputQuery parseQueryString ( String queryString ) throws OntopOWLException { try { return inputQueryFactory . createSPARQLQuery ( queryString ) ; } catch ( OntopInvalidInputQueryException | OntopUnsupportedInputQueryException e ) { throw new OntopOWLException ( e ) ; } }
In contexts where we don t know the precise type
34,524
public RepositoryConnection getConnection ( ) throws RepositoryException { try { return new OntopRepositoryConnection ( this , getOntopConnection ( ) , inputQueryFactory ) ; } catch ( Exception e ) { logger . error ( "Error creating repo connection: " + e . getMessage ( ) ) ; throw new RepositoryException ( e ) ; } }
Returns a new RepositoryConnection .
34,525
private static String getProperPrefixURI ( String prefixUri ) { if ( ! prefixUri . endsWith ( "#" ) ) { if ( ! prefixUri . endsWith ( "/" ) ) { String defaultSeparator = EntityCreationPreferences . getDefaultSeparator ( ) ; if ( ! prefixUri . endsWith ( defaultSeparator ) ) { prefixUri += defaultSeparator ; } } } return prefixUri ; }
A utility method to ensure a proper naming for prefix URI
34,526
private void fireMappingDeleted ( URI srcuri , String mapping_id ) { for ( OBDAMappingListener listener : mappingListeners ) { listener . mappingDeleted ( srcuri ) ; } }
Announces to the listeners that a mapping was deleted .
34,527
private void updateRuleIndexes ( CQIE rule ) { Function head = rule . getHead ( ) ; ruleIndex . put ( head . getFunctionSymbol ( ) , rule ) ; updateRuleIndexByBodyPredicate ( rule ) ; }
This method takes a rule and populates the ruleIndex field .
34,528
public boolean contains ( String prefix ) { Set < String > prefixes = prefixToURIMap . keySet ( ) ; return prefixes . contains ( prefix ) ; }
Checks if the prefix manager stores the prefix name .
34,529
public void intersectWith ( Intersection < T > arg ) { if ( arg . elements != null ) { if ( arg . elements . isEmpty ( ) ) elements = Collections . emptySet ( ) ; else { if ( elements == null ) elements = new HashSet < > ( arg . elements ) ; else elements . retainAll ( arg . elements ) ; } } }
modifies by intersecting with another intersection
34,530
public List < String [ ] > getTabularData ( ) throws OWLException , InterruptedException { if ( tabularData == null ) { tabularData = new ArrayList < > ( ) ; String [ ] columnName = results . getSignature ( ) . toArray ( new String [ numcols ] ) ; tabularData . add ( columnName ) ; while ( this . isFetching ) { Thread . sleep ( 10 ) ; } if ( stopFetching ) return null ; tabularData . addAll ( resultsTable ) ; while ( ! stopFetching && results . hasNext ( ) ) { final OWLBindingSet bindingSet = results . next ( ) ; String [ ] crow = new String [ numcols ] ; for ( int j = 0 ; j < numcols ; j ++ ) { OWLPropertyAssertionObject constant = bindingSet . getOWLPropertyAssertionObject ( j + 1 ) ; if ( constant != null ) { crow [ j ] = constant . toString ( ) ; } else { crow [ j ] = "" ; } } tabularData . add ( crow ) ; } } return tabularData ; }
Fetch all the tuples returned by the result set .
34,531
private void validateFields ( ) throws RepositoryConfigException { try { if ( owlFile . filter ( f -> ! f . exists ( ) ) . isPresent ( ) ) { throw new RepositoryConfigException ( String . format ( "The OWL file %s does not exist!" , owlFile . get ( ) . getAbsolutePath ( ) ) ) ; } if ( owlFile . filter ( f -> ! f . canRead ( ) ) . isPresent ( ) ) { throw new RepositoryConfigException ( String . format ( "The OWL file %s is not accessible!" , owlFile . get ( ) . getAbsolutePath ( ) ) ) ; } if ( obdaFile == null ) { throw new RepositoryConfigException ( String . format ( "No mapping file specified for repository creation " ) ) ; } if ( ! obdaFile . exists ( ) ) { throw new RepositoryConfigException ( String . format ( "The mapping file %s does not exist!" , obdaFile . getAbsolutePath ( ) ) ) ; } if ( ! obdaFile . canRead ( ) ) { throw new RepositoryConfigException ( String . format ( "The mapping file %s is not accessible!" , obdaFile . getAbsolutePath ( ) ) ) ; } if ( propertiesFile == null ) { throw new RepositoryConfigException ( String . format ( "No properties file specified for repository creation " ) ) ; } if ( ! propertiesFile . exists ( ) ) { throw new RepositoryConfigException ( String . format ( "The properties file %s does not exist!" , propertiesFile . getAbsolutePath ( ) ) ) ; } if ( ! propertiesFile . canRead ( ) ) { throw new RepositoryConfigException ( String . format ( "The properties file %s is not accessible!" , propertiesFile . getAbsolutePath ( ) ) ) ; } if ( constraintFile . isPresent ( ) ) { File file = constraintFile . get ( ) ; if ( ! file . exists ( ) ) { throw new RepositoryConfigException ( String . format ( "The implicit key file %s does not exist!" , file . getAbsolutePath ( ) ) ) ; } if ( ! file . canRead ( ) ) { throw new RepositoryConfigException ( String . format ( "The implicit key file %s is not accessible!" , file . getAbsolutePath ( ) ) ) ; } } } catch ( SecurityException e ) { throw new RepositoryConfigException ( e . getMessage ( ) ) ; } }
Checks that the fields are not missing and that files exist and are accessible .
34,532
public NodeCentricOptimizationResults < UnionNode > apply ( FlattenUnionProposal proposal , IntermediateQuery query , QueryTreeComponent treeComponent ) throws InvalidQueryOptimizationProposalException , EmptyQueryException { UnionNode focusNode = proposal . getFocusNode ( ) ; IntermediateQuery snapShot = query . createSnapshot ( ) ; query . getChildren ( focusNode ) . stream ( ) . forEach ( n -> treeComponent . removeSubTree ( n ) ) ; ImmutableSet < QueryNode > subqueryRoots = proposal . getSubqueryRoots ( ) ; subqueryRoots . forEach ( n -> treeComponent . addChild ( focusNode , n , Optional . empty ( ) , false ) ) ; subqueryRoots . forEach ( n -> treeComponent . addSubTree ( snapShot , n , n ) ) ; return new NodeCentricOptimizationResultsImpl < > ( query , focusNode ) ; }
Replace the child subtrees of the focus node
34,533
public boolean getValue ( ) throws OntopConnectionException { if ( hasRead ) throw new IllegalStateException ( "getValue() can only called once!" ) ; hasRead = true ; try { return set . next ( ) ; } catch ( SQLException e ) { throw new OntopConnectionException ( e ) ; } }
Returns true if there is at least one result
34,534
private void validateNode ( ) throws InvalidQueryNodeException { ImmutableSet < Variable > substitutionDomain = substitution . getDomain ( ) ; if ( ! projectedVariables . containsAll ( substitutionDomain ) ) { throw new InvalidQueryNodeException ( "ConstructionNode: all the domain variables " + "of the substitution must be projected.\n" + toString ( ) ) ; } if ( substitutionDomain . stream ( ) . anyMatch ( childVariables :: contains ) ) { throw new InvalidQueryNodeException ( "ConstructionNode: variables defined by the substitution cannot " + "be used for defining other variables.\n" + toString ( ) ) ; } if ( substitution . getImmutableMap ( ) . values ( ) . stream ( ) . filter ( v -> v instanceof Variable ) . map ( v -> ( Variable ) v ) . anyMatch ( v -> ! projectedVariables . contains ( v ) ) ) { throw new InvalidQueryNodeException ( "ConstructionNode: substituting a variable " + "by a non-projected variable is incorrect.\n" + toString ( ) ) ; } }
Validates the node independently of its child
34,535
private void insertVariableDataTyping ( Term term , Function atom , int position , Map < String , List < IndexedPosition > > termOccurenceIndex ) throws UnknownDatatypeException { if ( term instanceof Function ) { Function function = ( Function ) term ; Predicate functionSymbol = function . getFunctionSymbol ( ) ; if ( function . isDataTypeFunction ( ) || ( functionSymbol instanceof URITemplatePredicate ) || ( functionSymbol instanceof BNodePredicate ) ) { } else if ( function . isOperation ( ) ) { for ( int i = 0 ; i < function . getArity ( ) ; i ++ ) { insertVariableDataTyping ( function . getTerm ( i ) , function , i , termOccurenceIndex ) ; } } else { throw new IllegalArgumentException ( "Unsupported subtype of: " + Function . class . getSimpleName ( ) ) ; } } else if ( term instanceof Variable ) { Variable variable = ( Variable ) term ; Term newTerm ; RDFDatatype type = getDataType ( termOccurenceIndex , variable ) ; newTerm = termFactory . getTypedTerm ( variable , type ) ; log . info ( "Datatype " + type + " for the value " + variable + " of the property " + atom + " has been " + "inferred " + "from the database" ) ; atom . setTerm ( position , newTerm ) ; } else if ( term instanceof ValueConstant ) { Term newTerm = termFactory . getTypedTerm ( term , ( ( ValueConstant ) term ) . getType ( ) ) ; atom . setTerm ( position , newTerm ) ; } else { throw new IllegalArgumentException ( "Unsupported subtype of: " + Term . class . getSimpleName ( ) ) ; } }
This method wraps the variable that holds data property values with a data type predicate . It will replace the variable with a new function symbol and update the rule atom . However if the users already defined the data - type in the mapping this method simply accepts the function symbol .
34,536
private void insertOperationDatatyping ( Term term , Function atom , int position ) throws UnknownDatatypeException { ImmutableTerm immutableTerm = immutabilityTools . convertIntoImmutableTerm ( term ) ; if ( immutableTerm instanceof ImmutableFunctionalTerm ) { ImmutableFunctionalTerm castTerm = ( ImmutableFunctionalTerm ) immutableTerm ; Predicate functionSymbol = castTerm . getFunctionSymbol ( ) ; if ( functionSymbol instanceof OperationPredicate ) { Optional < TermType > inferredType = termTypeInferenceTools . inferType ( castTerm ) ; if ( inferredType . isPresent ( ) ) { deleteExplicitTypes ( term , atom , position ) ; atom . setTerm ( position , termFactory . getTypedTerm ( term , ( RDFDatatype ) inferredType . get ( ) ) ) ; } else { if ( defaultDatatypeInferred ) { atom . setTerm ( position , termFactory . getTypedTerm ( term , typeFactory . getXsdStringDatatype ( ) ) ) ; } else { throw new UnknownDatatypeException ( "Impossible to determine the expected datatype for the operation " + castTerm + "\n" + "Possible solutions: \n" + "- Add an explicit datatype in the mapping \n" + "- Add in the .properties file the setting: ontop.inferDefaultDatatype = true\n" + " and we will infer the default datatype (xsd:string)" ) ; } } } } }
Following r2rml standard we do not infer the datatype for operation but we return the default value string
34,537
private RDFDatatype getDataType ( Map < String , List < IndexedPosition > > termOccurenceIndex , Variable variable ) throws UnknownDatatypeException { List < IndexedPosition > list = termOccurenceIndex . get ( variable . getName ( ) ) ; if ( list == null ) throw new UnboundTargetVariableException ( variable ) ; IndexedPosition ip = list . get ( 0 ) ; RelationID tableId = relation2Predicate . createRelationFromPredicateName ( metadata . getQuotedIDFactory ( ) , ip . atom . getFunctionSymbol ( ) ) ; RelationDefinition td = metadata . getRelation ( tableId ) ; Attribute attribute = td . getAttribute ( ip . pos ) ; Optional < RDFDatatype > type ; if ( attribute . getType ( ) == 0 ) { type = Optional . empty ( ) ; } else { type = Optional . of ( ( RDFDatatype ) attribute . getTermType ( ) ) ; } if ( defaultDatatypeInferred ) return type . orElseGet ( typeFactory :: getXsdStringDatatype ) ; else { return type . orElseThrow ( ( ) -> new UnknownDatatypeException ( "Impossible to determine the expected datatype for the column " + variable + "\n" + "Possible solutions: \n" + "- Add an explicit datatype in the mapping \n" + "- Add in the .properties file the setting: ontop.inferDefaultDatatype = true\n" + " and we will infer the default datatype (xsd:string)" ) ) ; } }
returns COL_TYPE for one of the datatype ids
34,538
private Optional < InjectiveVar2VarSubstitution > computeRenamingSubstitution ( DistinctVariableOnlyDataAtom sourceProjectionAtom , DistinctVariableOnlyDataAtom targetProjectionAtom ) { int arity = sourceProjectionAtom . getEffectiveArity ( ) ; if ( ! sourceProjectionAtom . getPredicate ( ) . equals ( targetProjectionAtom . getPredicate ( ) ) || ( arity != targetProjectionAtom . getEffectiveArity ( ) ) ) { return Optional . empty ( ) ; } else { ImmutableMap < Variable , Variable > newMap = FunctionalTools . zip ( sourceProjectionAtom . getArguments ( ) , targetProjectionAtom . getArguments ( ) ) . stream ( ) . distinct ( ) . filter ( e -> ! e . getKey ( ) . equals ( e . getValue ( ) ) ) . collect ( ImmutableCollectors . toMap ( ) ) ; return Optional . of ( substitutionFactory . getInjectiveVar2VarSubstitution ( newMap ) ) ; } }
When such substitution DO NOT EXIST returns an EMPTY OPTIONAL . When NO renaming is NEEDED returns an EMPTY SUBSTITUTION .
34,539
public int getTupleCount ( InputQuery inputQuery ) throws OntopReformulationException , OntopQueryEvaluationException { SQLExecutableQuery targetQuery = checkAndConvertTargetQuery ( getExecutableQuery ( inputQuery ) ) ; String sql = targetQuery . getSQL ( ) ; String newsql = "SELECT count(*) FROM (" + sql + ") t1" ; if ( ! isCanceled ( ) ) { try { java . sql . ResultSet set = sqlStatement . executeQuery ( newsql ) ; if ( set . next ( ) ) { return set . getInt ( 1 ) ; } else { return 0 ; } } catch ( SQLException e ) { throw new OntopQueryEvaluationException ( e ) ; } } else { throw new OntopQueryEvaluationException ( "Action canceled." ) ; } }
Returns the number of tuples returned by the query
34,540
private void nestedEQSubstitutions ( Function atom , Substitution mgu ) { List < Term > terms = atom . getTerms ( ) ; for ( int i = 0 ; i < terms . size ( ) ; i ++ ) { Term t = terms . get ( i ) ; if ( t instanceof Function ) { Function t2 = ( Function ) t ; substitutionUtilities . applySubstitution ( t2 , mgu ) ; if ( t2 . getFunctionSymbol ( ) == ExpressionOperation . EQ && ! ( ( atom . getTerm ( 0 ) instanceof Function ) && ( atom . getTerm ( 1 ) instanceof Function ) ) ) { if ( ! mgu . composeTerms ( t2 . getTerm ( 0 ) , t2 . getTerm ( 1 ) ) ) continue ; terms . remove ( i ) ; i -= 1 ; } else { if ( t2 . getFunctionSymbol ( ) == ExpressionOperation . AND ) { nestedEQSubstitutions ( t2 , mgu ) ; if ( t2 . getTerms ( ) . isEmpty ( ) ) { terms . remove ( i ) ; i -- ; } else { if ( t2 . getTerms ( ) . size ( ) == 1 ) { atom . setTerm ( i , t2 . getTerm ( 0 ) ) ; } } } } } } }
We search for equalities in conjunctions . This recursive methods explore AND functions and removes EQ functions substituting the values using the class
34,541
public < T extends ImmutableTerm > Optional < ImmutableSubstitution < T > > applyToSubstitution ( ImmutableSubstitution < T > substitution ) { return Optional . of ( applyRenaming ( substitution ) ) ; }
More efficient implementation
34,542
private static ImmutableList < Function > getJoinOnFilter ( RAExpressionAttributes re1 , RAExpressionAttributes re2 , ImmutableSet < QuotedID > using , TermFactory termFactory ) { return using . stream ( ) . map ( id -> new QualifiedAttributeID ( null , id ) ) . map ( id -> { Term v1 = re1 . getAttributes ( ) . get ( id ) ; if ( v1 == null ) throw new IllegalArgumentException ( "Term " + id + " not found in " + re1 ) ; Term v2 = re2 . getAttributes ( ) . get ( id ) ; if ( v2 == null ) throw new IllegalArgumentException ( "Term " + id + " not found in " + re2 ) ; return termFactory . getFunctionEQ ( v1 , v2 ) ; } ) . collect ( ImmutableCollectors . toList ( ) ) ; }
internal implementation of JOIN USING and NATURAL JOIN
34,543
public ImmutableTerm convertIntoImmutableTerm ( Term term ) { if ( term instanceof Function ) { if ( term instanceof Expression ) { Expression expression = ( Expression ) term ; return termFactory . getImmutableExpression ( expression ) ; } else { Function functionalTerm = ( Function ) term ; if ( functionalTerm . getFunctionSymbol ( ) instanceof FunctionSymbol ) return termFactory . getImmutableFunctionalTerm ( ( FunctionSymbol ) functionalTerm . getFunctionSymbol ( ) , convertTerms ( functionalTerm ) ) ; else throw new NotAFunctionSymbolException ( term + " is not using a FunctionSymbol but a " + functionalTerm . getFunctionSymbol ( ) . getClass ( ) ) ; } } return ( ImmutableTerm ) term ; }
In case the term is functional creates an immutable copy of it .
34,544
public Expression convertToMutableBooleanExpression ( ImmutableExpression booleanExpression ) { OperationPredicate pred = booleanExpression . getFunctionSymbol ( ) ; return termFactory . getExpression ( pred , convertToMutableTerms ( booleanExpression . getTerms ( ) ) ) ; }
This method takes a immutable boolean term and convert it into an old mutable boolean function .
34,545
private static List < RelationID > getTableList ( String defaultTableSchema , Set < RelationID > realTables , QuotedIDFactory idfac ) throws SQLException { List < RelationID > fks = new LinkedList < > ( ) ; for ( RelationID table : realTables ) { if ( table . hasSchema ( ) || ( defaultTableSchema == null ) || table . getTableName ( ) . equals ( "DUAL" ) ) fks . add ( table ) ; else { RelationID qualifiedTableId = idfac . createRelationID ( defaultTableSchema , table . getTableNameSQLRendering ( ) ) ; fks . add ( qualifiedTableId ) ; } } return fks ; }
Retrieve the normalized list of tables from a given list of RelationIDs
34,546
private static List < RelationID > getTableList ( Connection conn , RelationListProvider relationListProvider , QuotedIDFactory idfac ) throws SQLException { List < RelationID > relationIds = new LinkedList < > ( ) ; try ( Statement stmt = conn . createStatement ( ) ; ResultSet rs = stmt . executeQuery ( relationListProvider . getQuery ( ) ) ) { while ( rs . next ( ) ) relationIds . add ( relationListProvider . getTableID ( rs ) ) ; } return relationIds ; }
Retrieve metadata for a specific database engine
34,547
private static void getPrimaryKey ( DatabaseMetaData md , DatabaseRelationDefinition relation , QuotedIDFactory idfac ) throws SQLException { RelationID id = relation . getID ( ) ; try ( ResultSet rs = md . getPrimaryKeys ( null , id . getSchemaName ( ) , id . getTableName ( ) ) ) { extractPrimaryKey ( relation , idfac , id , rs ) ; } catch ( SQLSyntaxErrorException e ) { try ( ResultSet rs = md . getPrimaryKeys ( id . getSchemaName ( ) , null , id . getTableName ( ) ) ) { extractPrimaryKey ( relation , idfac , id , rs ) ; } } }
Retrieves the primary key for the table
34,548
private static void getForeignKeys ( DatabaseMetaData md , DatabaseRelationDefinition relation , DBMetadata metadata ) throws SQLException { QuotedIDFactory idfac = metadata . getQuotedIDFactory ( ) ; RelationID relationId = relation . getID ( ) ; try ( ResultSet rs = md . getImportedKeys ( null , relationId . getSchemaName ( ) , relationId . getTableName ( ) ) ) { extractForeignKeys ( relation , metadata , idfac , rs ) ; } catch ( Exception ex ) { try ( ResultSet rs = md . getImportedKeys ( relationId . getSchemaName ( ) , null , relationId . getTableName ( ) ) ) { extractForeignKeys ( relation , metadata , idfac , rs ) ; } } }
Retrieves the foreign keys for the table
34,549
protected PredicateLevelProposal proposeForGroupingMap ( ImmutableMultimap < ImmutableList < VariableOrGroundTerm > , ExtensionalDataNode > groupingMap ) throws AtomUnificationException { ImmutableCollection < Collection < ExtensionalDataNode > > dataNodeGroups = groupingMap . asMap ( ) . values ( ) ; try { ImmutableSet < ImmutableSubstitution < VariableOrGroundTerm > > unifyingSubstitutions = dataNodeGroups . stream ( ) . filter ( g -> g . size ( ) > 1 ) . map ( redundantNodes -> { try { return unifyRedundantNodes ( redundantNodes ) ; } catch ( AtomUnificationException e ) { throw new AtomUnificationRuntimeException ( e ) ; } } ) . filter ( s -> ! s . isEmpty ( ) ) . collect ( ImmutableCollectors . toSet ( ) ) ; ImmutableSet < ExtensionalDataNode > removableNodes = ImmutableSet . copyOf ( dataNodeGroups . stream ( ) . filter ( sameRowDataNodes -> sameRowDataNodes . size ( ) > 1 ) . reduce ( new Dominance ( ) , Dominance :: update , ( dom1 , dom2 ) -> { throw new IllegalStateException ( "Cannot be run in parallel" ) ; } ) . getRemovalNodes ( ) ) ; return new PredicateLevelProposal ( unifyingSubstitutions , removableNodes ) ; } catch ( AtomUnificationRuntimeException e ) { throw e . checkedException ; } }
groupingMap groups data nodes that are being joined on the unique constraints
34,550
private static < T extends QueryNode > NodeCentricOptimizationResults < T > propagateSubstitution ( IntermediateQuery query , Optional < ImmutableSubstitution < VariableOrGroundTerm > > optionalSubstitution , T topNode ) throws EmptyQueryException { if ( optionalSubstitution . isPresent ( ) ) { SubstitutionPropagationProposal < T > propagationProposal = new SubstitutionPropagationProposalImpl < > ( topNode , optionalSubstitution . get ( ) , false ) ; return query . applyProposal ( propagationProposal , true ) ; } else { return new NodeCentricOptimizationResultsImpl < > ( query , topNode ) ; } }
Applies the substitution from the topNode .
34,551
private synchronized void removeResultTable ( ) { OWLResultSetTableModel tm = getTableModel ( ) ; if ( tm != null ) { tm . close ( ) ; } resultTablePanel . setTableModel ( new DefaultTableModel ( ) ) ; }
removes the result table . Could be called at data query execution or at cancelling Not necessary when replacing with a new result just to remove old results that are outdated
34,552
public void setupListeners ( ) { QueryInterfaceViewsList queryInterfaceViews = ( QueryInterfaceViewsList ) this . getOWLEditorKit ( ) . get ( QueryInterfaceViewsList . class . getName ( ) ) ; if ( ( queryInterfaceViews == null ) ) { queryInterfaceViews = new QueryInterfaceViewsList ( ) ; getOWLEditorKit ( ) . put ( QueryInterfaceViewsList . class . getName ( ) , queryInterfaceViews ) ; } queryInterfaceViews . add ( this ) ; QueryManagerViewsList queryManagerViews = ( QueryManagerViewsList ) this . getOWLEditorKit ( ) . get ( QueryManagerViewsList . class . getName ( ) ) ; if ( ( queryManagerViews != null ) && ( ! queryManagerViews . isEmpty ( ) ) ) { for ( QueryManagerView queryInterfaceView : queryManagerViews ) { queryInterfaceView . addListener ( this ) ; } } }
On creation of a new view we register it globally and make sure that its selector is listened by all other instances of query view in this editor kit . Also we make this new instance listen to the selection of all other query selectors in the views .
34,553
private List < Assertion > processResults ( OntopBindingSet bindingSet ) throws OntopResultConversionException , OntopConnectionException { List < Assertion > tripleAssertions = new ArrayList < > ( ) ; ABoxAssertionSupplier builder = OntologyBuilderImpl . assertionSupplier ( rdfFactory ) ; for ( ProjectionElemList peList : constructTemplate . getProjectionElemList ( ) ) { int size = peList . getElements ( ) . size ( ) ; for ( int i = 0 ; i < size / 3 ; i ++ ) { ObjectConstant subjectConstant = ( ObjectConstant ) getConstant ( peList . getElements ( ) . get ( i * 3 ) , bindingSet ) ; Constant predicateConstant = getConstant ( peList . getElements ( ) . get ( i * 3 + 1 ) , bindingSet ) ; Constant objectConstant = getConstant ( peList . getElements ( ) . get ( i * 3 + 2 ) , bindingSet ) ; if ( subjectConstant == null || predicateConstant == null || objectConstant == null ) { continue ; } String predicateName = predicateConstant . getValue ( ) ; try { Assertion assertion ; if ( predicateName . equals ( RDF . TYPE . getIRIString ( ) ) ) { assertion = builder . createClassAssertion ( objectConstant . getValue ( ) , subjectConstant ) ; } else { if ( ( objectConstant instanceof IRIConstant ) || ( objectConstant instanceof BNode ) ) { assertion = builder . createObjectPropertyAssertion ( predicateName , subjectConstant , ( ObjectConstant ) objectConstant ) ; } else { assertion = builder . createDataPropertyAssertion ( predicateName , subjectConstant , ( ValueConstant ) objectConstant ) ; } } if ( assertion != null ) tripleAssertions . add ( assertion ) ; } catch ( InconsistentOntologyException e ) { throw new OntopResultConversionException ( "InconsistentOntologyException: " + predicateName + " " + subjectConstant + " " + objectConstant ) ; } } } return tripleAssertions ; }
The method to actually process the current result set Row . Construct a list of assertions from the current result set row . In case of describe it is called to process and store all the results from a resultset . In case of construct it is called upon next to process the only current result set .
34,554
public QuestOWLEmptyEntitiesChecker getEmptyEntitiesChecker ( ) throws Exception { OWLOntology rootOntology = getRootOntology ( ) ; Ontology mergeOntology = owlapiTranslator . translateAndClassify ( rootOntology ) ; ClassifiedTBox tBox = mergeOntology . tbox ( ) ; return new QuestOWLEmptyEntitiesChecker ( tBox , owlConnection ) ; }
Methods to get the empty concepts and roles in the ontology using the given mappings . It generates SPARQL queries to check for entities .
34,555
public OWLConnection replaceConnection ( ) throws OntopConnectionException { OWLConnection oldconn = this . owlConnection ; owlConnection = reasoner . getConnection ( ) ; return oldconn ; }
Replaces the owl connection with a new one Called when the user cancels a query . Easier to get a new connection than waiting for the cancel
34,556
private DistinctVariableOnlyDataAtom transformProjectionAtom ( DistinctVariableOnlyDataAtom atom ) { ImmutableList < Variable > newArguments = atom . getArguments ( ) . stream ( ) . map ( renamingSubstitution :: applyToVariable ) . collect ( ImmutableCollectors . toList ( ) ) ; return atomFactory . getDistinctVariableOnlyDataAtom ( atom . getPredicate ( ) , newArguments ) ; }
Renames the projected variables
34,557
public ImmutableList < SQLPPTriplesMap > getMappings ( Graph myModel ) throws InvalidR2RMLMappingException { List < SQLPPTriplesMap > mappings = new ArrayList < SQLPPTriplesMap > ( ) ; Collection < TriplesMap > tripleMaps = r2rmlParser . getMappingNodes ( myModel ) ; for ( TriplesMap tm : tripleMaps ) { SQLPPTriplesMap mapping ; try { mapping = getMapping ( tm ) ; if ( mapping != null ) { mappings . add ( mapping ) ; } List < SQLPPTriplesMap > joinMappings = getJoinMappings ( tripleMaps , tm ) ; if ( joinMappings != null ) { mappings . addAll ( joinMappings ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } } return ImmutableList . copyOf ( mappings ) ; }
This method return the list of mappings from the Model main method to be called assembles everything
34,558
private SQLPPTriplesMap getMapping ( TriplesMap tm ) throws Exception { String sourceQuery = r2rmlParser . getSQLQuery ( tm ) . trim ( ) ; ImmutableList < TargetAtom > body = getMappingTripleAtoms ( tm ) ; SQLPPTriplesMap mapping = new OntopNativeSQLPPTriplesMap ( "mapping-" + tm . hashCode ( ) , MAPPING_FACTORY . getSQLQuery ( sourceQuery ) , body ) ; if ( body . isEmpty ( ) ) { System . out . println ( "WARNING a mapping without target query will not be introduced : " + mapping . toString ( ) ) ; return null ; } return mapping ; }
Get OBDA mapping axiom from R2RML TriplesMap
34,559
private List < SQLPPTriplesMap > getJoinMappings ( Collection < TriplesMap > tripleMaps , TriplesMap tm ) throws Exception { String sourceQuery = "" ; List < SQLPPTriplesMap > joinMappings = new ArrayList < SQLPPTriplesMap > ( ) ; for ( PredicateObjectMap pobm : tm . getPredicateObjectMaps ( ) ) { for ( RefObjectMap robm : pobm . getRefObjectMaps ( ) ) { sourceQuery = robm . getJointQuery ( ) ; ImmutableList . Builder < TargetAtom > bodyBuilder = ImmutableList . builder ( ) ; ImmutableTerm joinSubject1 = r2rmlParser . getSubjectAtom ( tm ) ; TriplesMap parent = robm . getParentMap ( ) ; TriplesMap parentTriple = null ; Iterator < TriplesMap > it = tripleMaps . iterator ( ) ; while ( it . hasNext ( ) ) { TriplesMap current = it . next ( ) ; if ( current . equals ( parent ) ) { parentTriple = current ; break ; } } ImmutableTerm joinSubject2 = r2rmlParser . getSubjectAtom ( parentTriple ) ; List < ImmutableFunctionalTerm > joinPredicates = r2rmlParser . getBodyURIPredicates ( pobm ) ; for ( ImmutableFunctionalTerm pred : joinPredicates ) { bodyBuilder . add ( targetAtomFactory . getTripleTargetAtom ( joinSubject1 , pred , joinSubject2 ) ) ; } if ( sourceQuery . isEmpty ( ) ) { throw new Exception ( "Could not create source query for join in " + tm ) ; } SQLPPTriplesMap mapping = new OntopNativeSQLPPTriplesMap ( "mapping-join-" + robm . hashCode ( ) , MAPPING_FACTORY . getSQLQuery ( sourceQuery ) , bodyBuilder . build ( ) ) ; System . out . println ( "WARNING joinMapping introduced : " + mapping ) ; joinMappings . add ( mapping ) ; } } return joinMappings ; }
Get join OBDA mapping axiom from R2RML TriplesMap
34,560
private ImmutableList < TargetAtom > getMappingTripleAtoms ( TriplesMap tm ) throws Exception { ImmutableList . Builder < TargetAtom > bodyBuilder = ImmutableList . builder ( ) ; ImmutableTerm subjectAtom = r2rmlParser . getSubjectAtom ( tm ) ; List < ImmutableFunctionalTerm > classPredicates = r2rmlParser . getClassPredicates ( ) ; for ( ImmutableFunctionalTerm classPred : classPredicates ) { ImmutableTerm predFunction = termFactory . getImmutableUriTemplate ( termFactory . getConstantLiteral ( RDF . TYPE . toString ( ) ) ) ; ; bodyBuilder . add ( targetAtomFactory . getTripleTargetAtom ( subjectAtom , predFunction , classPred ) ) ; } for ( PredicateObjectMap pom : tm . getPredicateObjectMaps ( ) ) { List < ImmutableFunctionalTerm > bodyURIPredicates = r2rmlParser . getBodyURIPredicates ( pom ) ; ImmutableTerm objectAtom = r2rmlParser . getObjectAtom ( pom ) ; if ( objectAtom == null ) { continue ; } for ( ImmutableFunctionalTerm predFunction : bodyURIPredicates ) { bodyBuilder . add ( targetAtomFactory . getTripleTargetAtom ( subjectAtom , predFunction , objectAtom ) ) ; } } return bodyBuilder . build ( ) ; }
Get OBDA mapping body terms from R2RML TriplesMap
34,561
public Connection createConnection ( String url , String username , String password ) throws SQLException { if ( connection != null && ! connection . isClosed ( ) ) return connection ; connection = DriverManager . getConnection ( url , username , password ) ; return connection ; }
Constructs a new database connection object and retrieves it .
34,562
public Connection getConnection ( String url , String username , String password ) throws SQLException { boolean alive = isConnectionAlive ( ) ; if ( ! alive ) { createConnection ( url , username , password ) ; } return connection ; }
Retrieves the connection object . If the connection doesnt exist or is dead it will attempt to create a new connection .
34,563
static ClassifiedTBox classify ( OntologyImpl . UnclassifiedOntologyTBox onto ) { DefaultDirectedGraph < ObjectPropertyExpression , DefaultEdge > objectPropertyGraph = getObjectPropertyGraph ( onto ) ; EquivalencesDAGImpl < ObjectPropertyExpression > objectPropertyDAG = EquivalencesDAGImpl . getEquivalencesDAG ( objectPropertyGraph ) ; DefaultDirectedGraph < DataPropertyExpression , DefaultEdge > dataPropertyGraph = getDataPropertyGraph ( onto ) ; EquivalencesDAGImpl < DataPropertyExpression > dataPropertyDAG = EquivalencesDAGImpl . getEquivalencesDAG ( dataPropertyGraph ) ; EquivalencesDAGImpl < ClassExpression > classDAG = EquivalencesDAGImpl . getEquivalencesDAG ( getClassGraph ( onto , objectPropertyGraph , dataPropertyGraph ) ) ; EquivalencesDAGImpl < DataRangeExpression > dataRangeDAG = EquivalencesDAGImpl . getEquivalencesDAG ( getDataRangeGraph ( onto , dataPropertyGraph ) ) ; chooseObjectPropertyRepresentatives ( objectPropertyDAG ) ; chooseDataPropertyRepresentatives ( dataPropertyDAG ) ; chooseClassRepresentatives ( classDAG , objectPropertyDAG , dataPropertyDAG ) ; chooseDataRangeRepresentatives ( dataRangeDAG , dataPropertyDAG ) ; ClassifiedTBoxImpl r = new ClassifiedTBoxImpl ( onto . classes ( ) , onto . objectProperties ( ) , onto . dataProperties ( ) , onto . annotationProperties ( ) , classDAG , objectPropertyDAG , dataPropertyDAG , dataRangeDAG , onto . getDisjointClassesAxioms ( ) , onto . getDisjointObjectPropertiesAxioms ( ) , onto . getDisjointDataPropertiesAxioms ( ) , onto . getReflexiveObjectPropertyAxioms ( ) , onto . getIrreflexiveObjectPropertyAxioms ( ) , onto . getFunctionalObjectProperties ( ) , onto . getFunctionalDataProperties ( ) ) ; return r ; }
constructs a TBox reasoner from an ontology
34,564
private static DefaultDirectedGraph < ObjectPropertyExpression , DefaultEdge > getObjectPropertyGraph ( OntologyImpl . UnclassifiedOntologyTBox ontology ) { DefaultDirectedGraph < ObjectPropertyExpression , DefaultEdge > graph = new DefaultDirectedGraph < > ( DefaultEdge . class ) ; for ( ObjectPropertyExpression role : ontology . objectProperties ( ) ) { if ( ! role . isBottom ( ) && ! role . isTop ( ) ) { graph . addVertex ( role ) ; graph . addVertex ( role . getInverse ( ) ) ; } } for ( ObjectPropertyExpression role : ontology . getAuxiliaryObjectProperties ( ) ) { graph . addVertex ( role ) ; graph . addVertex ( role . getInverse ( ) ) ; } ObjectPropertyExpression top = null ; for ( BinaryAxiom < ObjectPropertyExpression > roleIncl : ontology . getSubObjectPropertyAxioms ( ) ) { if ( roleIncl . getSub ( ) . isBottom ( ) || roleIncl . getSuper ( ) . isTop ( ) ) continue ; if ( roleIncl . getSuper ( ) . isBottom ( ) ) { throw new RuntimeException ( "BOT cannot occur on the LHS - replaced by DISJ" ) ; } if ( roleIncl . getSub ( ) . isTop ( ) ) { top = roleIncl . getSub ( ) ; graph . addVertex ( top ) ; } graph . addEdge ( roleIncl . getSub ( ) , roleIncl . getSuper ( ) ) ; graph . addEdge ( roleIncl . getSub ( ) . getInverse ( ) , roleIncl . getSuper ( ) . getInverse ( ) ) ; } if ( top != null ) { for ( ObjectPropertyExpression ope : graph . vertexSet ( ) ) graph . addEdge ( ope , top ) ; } return graph ; }
graph representation of object property inclusions in the ontology
34,565
private static DefaultDirectedGraph < DataPropertyExpression , DefaultEdge > getDataPropertyGraph ( OntologyImpl . UnclassifiedOntologyTBox ontology ) { DefaultDirectedGraph < DataPropertyExpression , DefaultEdge > graph = new DefaultDirectedGraph < > ( DefaultEdge . class ) ; for ( DataPropertyExpression role : ontology . dataProperties ( ) ) if ( ! role . isBottom ( ) && ! role . isTop ( ) ) graph . addVertex ( role ) ; DataPropertyExpression top = null ; for ( BinaryAxiom < DataPropertyExpression > roleIncl : ontology . getSubDataPropertyAxioms ( ) ) { if ( roleIncl . getSub ( ) . isBottom ( ) || roleIncl . getSuper ( ) . isTop ( ) ) continue ; if ( roleIncl . getSuper ( ) . isBottom ( ) ) { throw new RuntimeException ( "BOT cannot occur on the LHS - replaced by DISJ" ) ; } if ( roleIncl . getSub ( ) . isTop ( ) ) { top = roleIncl . getSub ( ) ; graph . addVertex ( top ) ; } graph . addEdge ( roleIncl . getSub ( ) , roleIncl . getSuper ( ) ) ; } if ( top != null ) { for ( DataPropertyExpression dpe : graph . vertexSet ( ) ) graph . addEdge ( dpe , top ) ; } return graph ; }
graph representation of data property inclusions in the ontology
34,566
private static DefaultDirectedGraph < ClassExpression , DefaultEdge > getClassGraph ( OntologyImpl . UnclassifiedOntologyTBox ontology , DefaultDirectedGraph < ObjectPropertyExpression , DefaultEdge > objectPropertyGraph , DefaultDirectedGraph < DataPropertyExpression , DefaultEdge > dataPropertyGraph ) { DefaultDirectedGraph < ClassExpression , DefaultEdge > graph = new DefaultDirectedGraph < > ( DefaultEdge . class ) ; for ( OClass concept : ontology . classes ( ) ) if ( ! concept . isBottom ( ) && ! concept . isTop ( ) ) graph . addVertex ( concept ) ; for ( ObjectPropertyExpression role : objectPropertyGraph . vertexSet ( ) ) graph . addVertex ( role . getDomain ( ) ) ; for ( DefaultEdge edge : objectPropertyGraph . edgeSet ( ) ) { ObjectPropertyExpression child = objectPropertyGraph . getEdgeSource ( edge ) ; ObjectPropertyExpression parent = objectPropertyGraph . getEdgeTarget ( edge ) ; graph . addEdge ( child . getDomain ( ) , parent . getDomain ( ) ) ; } for ( DataPropertyExpression role : dataPropertyGraph . vertexSet ( ) ) for ( DataSomeValuesFrom dom : role . getAllDomainRestrictions ( ) ) graph . addVertex ( dom ) ; for ( DefaultEdge edge : dataPropertyGraph . edgeSet ( ) ) { DataPropertyExpression child = dataPropertyGraph . getEdgeSource ( edge ) ; DataPropertyExpression parent = dataPropertyGraph . getEdgeTarget ( edge ) ; graph . addEdge ( child . getDomainRestriction ( DatatypeImpl . rdfsLiteral ) , parent . getDomainRestriction ( DatatypeImpl . rdfsLiteral ) ) ; } ClassExpression top = null ; for ( BinaryAxiom < ClassExpression > clsIncl : ontology . getSubClassAxioms ( ) ) { if ( clsIncl . getSub ( ) . isBottom ( ) || clsIncl . getSuper ( ) . isTop ( ) ) continue ; if ( clsIncl . getSuper ( ) . isBottom ( ) ) { throw new RuntimeException ( "BOT cannot occur on the LHS - replaced by DISJ" ) ; } if ( clsIncl . getSub ( ) . isTop ( ) ) { top = clsIncl . getSub ( ) ; graph . addVertex ( top ) ; } graph . addEdge ( clsIncl . getSub ( ) , clsIncl . getSuper ( ) ) ; } if ( top != null ) { for ( ClassExpression c : graph . vertexSet ( ) ) graph . addEdge ( c , top ) ; } return graph ; }
graph representation of the class inclusions in the ontology
34,567
protected boolean moveCursor ( ) throws SQLException , OntopConnectionException { boolean foundFreshRow ; List < Object > currentKey ; do { foundFreshRow = rs . next ( ) ; if ( ! foundFreshRow ) { break ; } currentKey = computeRowKey ( rs ) ; } while ( ! rowKeys . add ( currentKey ) ) ; return foundFreshRow ; }
Moves cursor until we get a fresh row
34,568
public List < ImmutableFunctionalTerm > getClassPredicates ( ) { List < ImmutableFunctionalTerm > classes = new ArrayList < > ( ) ; for ( ImmutableFunctionalTerm p : classPredicates ) classes . add ( p ) ; classPredicates . clear ( ) ; return classes ; }
Get classes They can be retrieved only once after retrieving everything is cleared .
34,569
public List < ImmutableFunctionalTerm > getBodyURIPredicates ( PredicateObjectMap pom ) { List < ImmutableFunctionalTerm > predicateAtoms = new ArrayList < > ( ) ; for ( PredicateMap pm : pom . getPredicateMaps ( ) ) { String pmConstant = pm . getConstant ( ) . toString ( ) ; if ( pmConstant != null ) { ImmutableFunctionalTerm bodyPredicate = termFactory . getImmutableUriTemplate ( termFactory . getConstantLiteral ( pmConstant ) ) ; predicateAtoms . add ( bodyPredicate ) ; } Template t = pm . getTemplate ( ) ; if ( t != null ) { ImmutableFunctionalTerm predicateAtom = getURIFunction ( t . toString ( ) ) ; predicateAtoms . add ( predicateAtom ) ; } String c = pm . getColumn ( ) ; if ( c != null ) { ImmutableFunctionalTerm predicateAtom = getURIFunction ( c ) ; predicateAtoms . add ( predicateAtom ) ; } } return predicateAtoms ; }
Get body predicates with templates
34,570
private ImmutableFunctionalTerm getTermTypeAtom ( String string , Object type , String joinCond ) { if ( type . equals ( R2RMLVocabulary . iri ) ) { return getURIFunction ( string , joinCond ) ; } else if ( type . equals ( R2RMLVocabulary . blankNode ) ) { return getTypedFunction ( string , 2 , joinCond ) ; } else if ( type . equals ( R2RMLVocabulary . literal ) ) { return getTypedFunction ( trim ( string ) , 3 , joinCond ) ; } return null ; }
get a typed atom of a specific type
34,571
private String trim ( String string ) { while ( string . startsWith ( "\"" ) && string . endsWith ( "\"" ) ) { string = string . substring ( 1 , string . length ( ) - 1 ) ; } return string ; }
method that trims a string of all its double apostrophes from beginning and end
34,572
private String trimTo1 ( String string ) { while ( string . startsWith ( "\"\"" ) && string . endsWith ( "\"\"" ) ) { string = string . substring ( 1 , string . length ( ) - 1 ) ; } return string ; }
method to trim a string of its leading or trailing quotes but one
34,573
private IntermediateQuery pushDownExpressions ( final IntermediateQuery initialQuery ) { Optional < QueryNode > optionalCurrentNode = initialQuery . getFirstChild ( initialQuery . getRootNode ( ) ) ; IntermediateQuery currentQuery = initialQuery ; while ( optionalCurrentNode . isPresent ( ) ) { final QueryNode currentNode = optionalCurrentNode . get ( ) ; if ( currentNode instanceof JoinOrFilterNode ) { NextNodeAndQuery nextNodeAndQuery = optimizeJoinOrFilter ( currentQuery , ( JoinOrFilterNode ) currentNode ) ; optionalCurrentNode = nextNodeAndQuery . getOptionalNextNode ( ) ; currentQuery = nextNodeAndQuery . getNextQuery ( ) ; } else { optionalCurrentNode = getDepthFirstNextNode ( currentQuery , currentNode ) ; } } return currentQuery ; }
Tries to optimize all the JoinOrFilterNodes ONE BY ONE . Navigates in a top - down fashion .
34,574
private NextNodeAndQuery optimizeJoinOrFilter ( IntermediateQuery currentQuery , JoinOrFilterNode currentNode ) { Optional < PushDownBooleanExpressionProposal > optionalProposal = makeProposal ( currentQuery , currentNode ) ; if ( optionalProposal . isPresent ( ) ) { PushDownBooleanExpressionProposal proposal = optionalProposal . get ( ) ; NodeCentricOptimizationResults < JoinOrFilterNode > results ; try { results = currentQuery . applyProposal ( proposal ) ; } catch ( EmptyQueryException e ) { throw new IllegalStateException ( "Unexpected empty query exception while pushing down boolean expressions" ) ; } return getNextNodeAndQuery ( currentQuery , results ) ; } else { return new NextNodeAndQuery ( getDepthFirstNextNode ( currentQuery , currentNode ) , currentQuery ) ; } }
Tries to optimize one JoinOrFilterNode . Returns information for the continuing the navigation in the possibly new IntermediateQuery .
34,575
private Optional < PushDownBooleanExpressionProposal > buildProposal ( JoinOrFilterNode providerNode , ImmutableMultimap < Recipient , ImmutableExpression > recipientMap ) { ImmutableCollection < Map . Entry < Recipient , ImmutableExpression > > recipientEntries = recipientMap . entries ( ) ; ImmutableMultimap < CommutativeJoinOrFilterNode , ImmutableExpression > directRecipientNodes = recipientEntries . stream ( ) . filter ( e -> e . getKey ( ) . directRecipientNode . isPresent ( ) ) . filter ( e -> e . getKey ( ) . directRecipientNode . get ( ) != providerNode ) . map ( e -> new AbstractMap . SimpleEntry < > ( ( CommutativeJoinOrFilterNode ) e . getKey ( ) . directRecipientNode . get ( ) , e . getValue ( ) ) ) . collect ( ImmutableCollectors . toMultimap ( ) ) ; ImmutableMultimap < QueryNode , ImmutableExpression > indirectRecipientNodes = recipientEntries . stream ( ) . filter ( e -> e . getKey ( ) . indirectRecipientNode . isPresent ( ) ) . map ( e -> new AbstractMap . SimpleEntry < > ( e . getKey ( ) . indirectRecipientNode . get ( ) , e . getValue ( ) ) ) . collect ( ImmutableCollectors . toMultimap ( ) ) ; if ( directRecipientNodes . isEmpty ( ) && indirectRecipientNodes . isEmpty ( ) ) { return Optional . empty ( ) ; } else { ImmutableList < ImmutableExpression > expressionsToKeep = recipientEntries . stream ( ) . filter ( e -> e . getKey ( ) . directRecipientNode . isPresent ( ) ) . filter ( e -> e . getKey ( ) . directRecipientNode . get ( ) == providerNode ) . map ( Map . Entry :: getValue ) . collect ( ImmutableCollectors . toList ( ) ) ; return Optional . of ( new PushDownBooleanExpressionProposalImpl ( providerNode , directRecipientNodes , indirectRecipientNodes , expressionsToKeep ) ) ; } }
Builds the PushDownBooleanExpressionProposal .
34,576
public void updateStatus ( long result ) { if ( result != - 1 ) { Double time = execTime / 1000 ; String s = String . format ( "Execution time: %s sec - Number of rows retrieved: %,d " , time , result ) ; Runnable time_setter = new ExecTimeSetter ( s ) ; SwingUtilities . invokeLater ( time_setter ) ; } }
get and update the info box with the actual time in seconds of the execution of the query
34,577
public void showBooleanActionResultInTextInfo ( String title , BooleanOWLResultSet result ) throws OWLException { AskQueryInfoSetter alter_result_panel = new AskQueryInfoSetter ( title , result ) ; SwingUtilities . invokeLater ( alter_result_panel ) ; }
show the result for ask query
34,578
public void tableChanged ( TableModelEvent e ) { int rows = ( ( TableModel ) e . getSource ( ) ) . getRowCount ( ) ; updateStatus ( rows ) ; }
update the number of rows when the table change
34,579
public boolean containsTerm ( Term t ) { List < Term > terms = getTerms ( ) ; for ( int i = 0 ; i < terms . size ( ) ; i ++ ) { Term t2 = terms . get ( i ) ; if ( t2 . equals ( t ) ) return true ; } return false ; }
Check whether the function contains a particular term argument or not .
34,580
private ImmutableList < UnaryOperatorNode > extractModifierNodes ( IntermediateQueryFactory iqFactory ) { long correctedOffset = offset > 0 ? offset : 0 ; Optional < SliceNode > sliceNode = Optional . of ( limit ) . filter ( l -> l >= 0 ) . map ( l -> Optional . of ( iqFactory . createSliceNode ( correctedOffset , l ) ) ) . orElseGet ( ( ) -> Optional . of ( correctedOffset ) . filter ( o -> o > 0 ) . map ( iqFactory :: createSliceNode ) ) ; Optional < UnaryOperatorNode > distinctNode = isDistinct ( ) ? Optional . of ( iqFactory . createDistinctNode ( ) ) : Optional . empty ( ) ; ImmutableList < OrderByNode . OrderComparator > orderComparators = getSortConditions ( ) . stream ( ) . map ( o -> iqFactory . createOrderComparator ( o . getVariable ( ) , o . getDirection ( ) == OrderCondition . ORDER_ASCENDING ) ) . collect ( ImmutableCollectors . toList ( ) ) ; Optional < UnaryOperatorNode > orderByNode = orderComparators . isEmpty ( ) ? Optional . empty ( ) : Optional . of ( iqFactory . createOrderByNode ( orderComparators ) ) ; return Stream . of ( sliceNode , distinctNode , orderByNode ) . filter ( Optional :: isPresent ) . map ( Optional :: get ) . collect ( ImmutableCollectors . toList ( ) ) ; }
Top - down order
34,581
private LiftingStepResults liftChildBinding ( ImmutableList < IQTree > initialChildren , Optional < ImmutableExpression > initialJoiningCondition , VariableGenerator variableGenerator ) throws EmptyIQException { ImmutableList < IQTree > liftedChildren = initialChildren . stream ( ) . map ( c -> c . liftBinding ( variableGenerator ) ) . filter ( c -> ! ( c . getRootNode ( ) instanceof TrueNode ) ) . collect ( ImmutableCollectors . toList ( ) ) ; if ( liftedChildren . stream ( ) . anyMatch ( IQTree :: isDeclaredAsEmpty ) ) throw new EmptyIQException ( ) ; OptionalInt optionalSelectedLiftedChildPosition = IntStream . range ( 0 , liftedChildren . size ( ) ) . filter ( i -> liftedChildren . get ( i ) . getRootNode ( ) instanceof ConstructionNode ) . findFirst ( ) ; if ( ! optionalSelectedLiftedChildPosition . isPresent ( ) ) return new InnerJoinNodeImpl . LiftingStepResults ( substitutionFactory . getSubstitution ( ) , liftedChildren , initialJoiningCondition , true ) ; int selectedChildPosition = optionalSelectedLiftedChildPosition . getAsInt ( ) ; UnaryIQTree selectedLiftedChild = ( UnaryIQTree ) liftedChildren . get ( selectedChildPosition ) ; ConstructionNode selectedChildConstructionNode = ( ConstructionNode ) selectedLiftedChild . getRootNode ( ) ; IQTree selectedGrandChild = selectedLiftedChild . getChild ( ) ; try { return liftRegularChildBinding ( selectedChildConstructionNode , selectedChildPosition , selectedGrandChild , liftedChildren , ImmutableSet . of ( ) , initialJoiningCondition , variableGenerator , this :: convertIntoLiftingStepResults ) ; } catch ( UnsatisfiableConditionException e ) { throw new EmptyIQException ( ) ; } }
Lifts the binding OF AT MOST ONE child
34,582
public void synchronize ( List < QueryControllerEntity > queryEntities ) { if ( queryEntities . size ( ) > 0 ) { for ( QueryControllerEntity queryEntity : queryEntities ) { if ( queryEntity instanceof QueryControllerGroup ) { QueryControllerGroup group = ( QueryControllerGroup ) queryEntity ; QueryGroupTreeElement queryGroupEle = new QueryGroupTreeElement ( group . getID ( ) ) ; Vector < QueryControllerQuery > queries = group . getQueries ( ) ; for ( QueryControllerQuery query : queries ) { QueryTreeElement queryTreeEle = new QueryTreeElement ( query . getID ( ) , query . getQuery ( ) ) ; insertNodeInto ( queryTreeEle , queryGroupEle , queryGroupEle . getChildCount ( ) ) ; } insertNodeInto ( queryGroupEle , ( DefaultMutableTreeNode ) root , root . getChildCount ( ) ) ; } else { QueryControllerQuery query = ( QueryControllerQuery ) queryEntity ; QueryTreeElement queryTreeEle = new QueryTreeElement ( query . getID ( ) , query . getQuery ( ) ) ; insertNodeInto ( queryTreeEle , ( DefaultMutableTreeNode ) root , root . getChildCount ( ) ) ; } } } }
Takes all the existing nodes and constructs the tree .
34,583
public void reset ( ) { Enumeration < TreeNode > children = root . children ( ) ; while ( children . hasMoreElements ( ) ) { removeNodeFromParent ( ( MutableTreeNode ) children . nextElement ( ) ) ; children = root . children ( ) ; } }
Remove all the nodes from the Tree
34,584
public void elementAdded ( QueryControllerEntity element ) { if ( element instanceof QueryControllerGroup ) { QueryControllerGroup group = ( QueryControllerGroup ) element ; QueryGroupTreeElement ele = new QueryGroupTreeElement ( group . getID ( ) ) ; insertNodeInto ( ele , ( DefaultMutableTreeNode ) root , root . getChildCount ( ) ) ; nodeStructureChanged ( root ) ; } else if ( element instanceof QueryControllerQuery ) { QueryControllerQuery query = ( QueryControllerQuery ) element ; QueryTreeElement ele = new QueryTreeElement ( query . getID ( ) , query . getQuery ( ) ) ; insertNodeInto ( ele , ( DefaultMutableTreeNode ) root , root . getChildCount ( ) ) ; nodeStructureChanged ( root ) ; } }
Inserts a new node group or query into the Tree
34,585
public void elementRemoved ( QueryControllerEntity element ) { if ( element instanceof QueryControllerGroup ) { QueryControllerGroup group = ( QueryControllerGroup ) element ; QueryGroupTreeElement ele = new QueryGroupTreeElement ( group . getID ( ) ) ; Enumeration < TreeNode > groups = root . children ( ) ; while ( groups . hasMoreElements ( ) ) { Object temporal = groups . nextElement ( ) ; if ( ! ( temporal instanceof QueryGroupTreeElement ) ) { continue ; } QueryGroupTreeElement groupTElement = ( QueryGroupTreeElement ) temporal ; if ( groupTElement . getID ( ) . equals ( ele . getID ( ) ) ) { removeNodeFromParent ( groupTElement ) ; nodeStructureChanged ( root ) ; break ; } } } else if ( element instanceof QueryControllerQuery ) { QueryControllerQuery query = ( QueryControllerQuery ) element ; QueryTreeElement elementQuery = new QueryTreeElement ( query . getID ( ) , query . getQuery ( ) ) ; Enumeration < TreeNode > elements = root . children ( ) ; while ( elements . hasMoreElements ( ) ) { TreeNode currentElement = elements . nextElement ( ) ; if ( currentElement instanceof QueryGroupTreeElement ) { continue ; } if ( currentElement instanceof QueryTreeElement ) { QueryTreeElement deleteQuery = ( QueryTreeElement ) currentElement ; if ( deleteQuery . getID ( ) . equals ( elementQuery . getID ( ) ) ) { removeNodeFromParent ( deleteQuery ) ; nodeStructureChanged ( root ) ; break ; } } } } }
Removes a TreeNode group or query from the Tree
34,586
public TreeElement getNode ( String element ) { TreeElement node = null ; Enumeration < TreeNode > elements = root . children ( ) ; while ( elements . hasMoreElements ( ) ) { TreeElement currentNode = ( TreeElement ) elements . nextElement ( ) ; if ( currentNode instanceof QueryGroupTreeElement ) { QueryGroupTreeElement groupTElement = ( QueryGroupTreeElement ) currentNode ; if ( groupTElement . getID ( ) . equals ( element ) ) { node = groupTElement ; break ; } } if ( currentNode instanceof QueryTreeElement ) { QueryTreeElement queryTreeElement = ( QueryTreeElement ) currentNode ; if ( queryTreeElement . getID ( ) . equals ( element ) ) { node = queryTreeElement ; break ; } } } return node ; }
Search a TreeElement node group or query and returns the object else returns null .
34,587
public QueryTreeElement getElementQuery ( String element , String group ) { QueryTreeElement node = null ; Enumeration < TreeNode > elements = root . children ( ) ; while ( elements . hasMoreElements ( ) ) { TreeElement currentNode = ( TreeElement ) elements . nextElement ( ) ; if ( currentNode instanceof QueryGroupTreeElement && currentNode . getID ( ) . equals ( group ) ) { QueryGroupTreeElement groupTElement = ( QueryGroupTreeElement ) currentNode ; Enumeration < TreeNode > queries = groupTElement . children ( ) ; while ( queries . hasMoreElements ( ) ) { QueryTreeElement queryTElement = ( QueryTreeElement ) queries . nextElement ( ) ; if ( queryTElement . getID ( ) . equals ( element ) ) { node = queryTElement ; break ; } } } else { continue ; } } return node ; }
Search a query node in a group and returns the object else returns null .
34,588
public static Optional < QueryNode > getDepthFirstNextNode ( IntermediateQuery query , QueryNode currentNode ) { return getDepthFirstNextNode ( query , currentNode , false ) ; }
Depth - first exploration
34,589
public static NextNodeAndQuery getNextNodeAndQuery ( IntermediateQuery query , NodeCentricOptimizationResults < ? extends QueryNode > results ) { Optional < ? extends QueryNode > optionalNewNode = results . getOptionalNewNode ( ) ; if ( optionalNewNode . isPresent ( ) ) { Optional < QueryNode > optionalNextNode = getDepthFirstNextNode ( query , optionalNewNode . get ( ) ) ; return new NextNodeAndQuery ( optionalNextNode , query ) ; } Optional < QueryNode > optionalReplacingChild = results . getOptionalReplacingChild ( ) ; if ( optionalReplacingChild . isPresent ( ) ) { return new NextNodeAndQuery ( optionalReplacingChild , query ) ; } Optional < QueryNode > optionalNextSibling = results . getOptionalNextSibling ( ) ; if ( optionalNextSibling . isPresent ( ) ) { return new NextNodeAndQuery ( optionalNextSibling , query ) ; } Optional < QueryNode > optionalClosestAncestor = results . getOptionalClosestAncestor ( ) ; if ( optionalClosestAncestor . isPresent ( ) ) { Optional < QueryNode > optionalNextNode = getDepthFirstNextNode ( query , optionalClosestAncestor . get ( ) , true ) ; return new NextNodeAndQuery ( optionalNextNode , query ) ; } else { return new NextNodeAndQuery ( Optional . < QueryNode > empty ( ) , query ) ; } }
Finds the next node to visit in a new intermediate query
34,590
private String stringifySubTree ( IntermediateQuery query , QueryNode subTreeRoot , String rootOffsetString ) { StringBuilder strBuilder = new StringBuilder ( ) ; strBuilder . append ( rootOffsetString + subTreeRoot + "\n" ) ; for ( QueryNode child : query . getChildren ( subTreeRoot ) ) { strBuilder . append ( stringifySubTree ( query , child , rootOffsetString + TAB_STR ) ) ; } return strBuilder . toString ( ) ; }
Recursive method .
34,591
public < T extends ImmutableTerm > ImmutableSubstitution < T > prioritizeRenaming ( ImmutableSubstitution < T > substitution , ImmutableSet < Variable > priorityVariables ) { ImmutableMultimap < Variable , Variable > renamingMultimap = substitution . getImmutableMap ( ) . entrySet ( ) . stream ( ) . filter ( e -> priorityVariables . contains ( e . getKey ( ) ) && ( e . getValue ( ) instanceof Variable ) && ( ! priorityVariables . contains ( e . getValue ( ) ) ) ) . collect ( ImmutableCollectors . toMultimap ( e -> ( Variable ) e . getValue ( ) , Map . Entry :: getKey ) ) ; if ( renamingMultimap . isEmpty ( ) ) return substitution ; ImmutableMap < Variable , Variable > renamingMap = renamingMultimap . asMap ( ) . entrySet ( ) . stream ( ) . collect ( ImmutableCollectors . toMap ( Map . Entry :: getKey , e -> e . getValue ( ) . iterator ( ) . next ( ) ) ) ; InjectiveVar2VarSubstitution renamingSubstitution = substitutionFactory . getInjectiveVar2VarSubstitution ( renamingMap ) ; return ( ImmutableSubstitution < T > ) renamingSubstitution . composeWith ( substitution ) ; }
Prevents priority variables to be renamed into non - priority variables .
34,592
public Optional < ImmutableSubstitution < ImmutableTerm > > computeDirectedMGU ( ImmutableTerm sourceTerm , ImmutableTerm targetTerm ) { if ( sourceTerm instanceof Variable ) { Variable sourceVariable = ( Variable ) sourceTerm ; if ( ( targetTerm instanceof ImmutableFunctionalTerm ) && ( ( ImmutableFunctionalTerm ) targetTerm ) . getVariables ( ) . contains ( sourceVariable ) ) { return Optional . empty ( ) ; } ImmutableSubstitution < ImmutableTerm > substitution = sourceVariable . equals ( targetTerm ) ? substitutionFactory . getSubstitution ( ) : substitutionFactory . getSubstitution ( ImmutableMap . of ( sourceVariable , targetTerm ) ) ; return Optional . of ( substitution ) ; } else if ( sourceTerm instanceof ImmutableFunctionalTerm ) { ImmutableFunctionalTerm sourceFunctionalTerm = ( ImmutableFunctionalTerm ) sourceTerm ; if ( targetTerm instanceof Variable ) { Variable targetVariable = ( Variable ) targetTerm ; if ( sourceFunctionalTerm . getVariables ( ) . contains ( targetVariable ) ) { return Optional . empty ( ) ; } else { ImmutableSubstitution < ImmutableTerm > substitution = substitutionFactory . getSubstitution ( ImmutableMap . of ( targetVariable , sourceTerm ) ) ; return Optional . of ( substitution ) ; } } else if ( targetTerm instanceof ImmutableFunctionalTerm ) { return computeDirectedMGUOfTwoFunctionalTerms ( ( ImmutableFunctionalTerm ) sourceTerm , ( ImmutableFunctionalTerm ) targetTerm ) ; } else { return Optional . empty ( ) ; } } else if ( sourceTerm instanceof Constant ) { if ( targetTerm instanceof Variable ) { Variable targetVariable = ( Variable ) targetTerm ; ImmutableSubstitution < ImmutableTerm > substitution = substitutionFactory . getSubstitution ( ImmutableMap . of ( targetVariable , sourceTerm ) ) ; return Optional . of ( substitution ) ; } else if ( sourceTerm . equals ( targetTerm ) ) { return Optional . of ( substitutionFactory . getSubstitution ( ) ) ; } else { return Optional . empty ( ) ; } } else { throw new RuntimeException ( "Unexpected term: " + sourceTerm + " (" + sourceTerm . getClass ( ) + ")" ) ; } }
Computes a MGU that reuses as much as possible the variables from the target part .
34,593
private void readSourceDeclaration ( LineNumberReader reader ) throws IOException { String line ; dataSourceProperties = new Properties ( ) ; while ( ! ( line = reader . readLine ( ) ) . isEmpty ( ) ) { int lineNumber = reader . getLineNumber ( ) ; String [ ] tokens = line . split ( "[\t| ]+" , 2 ) ; final String parameter = tokens [ 0 ] . trim ( ) ; final String inputParameter = tokens [ 1 ] . trim ( ) ; if ( parameter . equals ( Label . sourceUri . name ( ) ) ) { dataSourceProperties . put ( OntopSQLCoreSettings . JDBC_NAME , inputParameter ) ; } else if ( parameter . equals ( Label . connectionUrl . name ( ) ) ) { dataSourceProperties . put ( OntopSQLCoreSettings . JDBC_URL , inputParameter ) ; } else if ( parameter . equals ( Label . username . name ( ) ) ) { dataSourceProperties . put ( OntopSQLCredentialSettings . JDBC_USER , inputParameter ) ; } else if ( parameter . equals ( Label . password . name ( ) ) ) { dataSourceProperties . put ( OntopSQLCredentialSettings . JDBC_PASSWORD , inputParameter ) ; } else if ( parameter . equals ( Label . driverClass . name ( ) ) ) { dataSourceProperties . put ( OntopSQLCoreSettings . JDBC_DRIVER , inputParameter ) ; } else { String msg = String . format ( "Unknown parameter name \"%s\" at line: %d." , parameter , lineNumber ) ; throw new IOException ( msg ) ; } } }
read and store datasource information
34,594
public DatalogProgram createDatalog ( OWLOntology onto ) { for ( OWLAxiom axiom : onto . getAxioms ( ) ) { if ( axiom . getAxiomType ( ) . equals ( AxiomType . SWRL_RULE ) ) { SWRLRule rule = ( SWRLRule ) axiom ; rule . accept ( this ) ; if ( notSupported ) { log . warn ( "Not Supported Translation of: " + errors ) ; errors . clear ( ) ; } } } DatalogProgram dp = datalogFactory . getDatalogProgram ( ) ; dp . appendRule ( facts ) ; return dp ; }
Translate the swrl_rules contained in the ontology Return a datalog program containing the supported datalog facts
34,595
public DatalogProgram createDatalog ( SWRLRule rule ) { rule . accept ( this ) ; if ( notSupported ) { log . warn ( "Not Supported Translation of: " + errors ) ; errors . clear ( ) ; } DatalogProgram dp = datalogFactory . getDatalogProgram ( ) ; dp . appendRule ( facts ) ; return dp ; }
Translate the swrl_rule Return a datalog program containing the supported datalog facts
34,596
public void visit ( SWRLDataRangeAtom node ) { notSupported = true ; errors . add ( node . toString ( ) ) ; }
Data range is not supported
34,597
private ImmutableSet < ExtensionalDataNode > selectNodesToRemove ( ImmutableSet < Variable > requiredAndCooccuringVariables , ImmutableMap < FunctionalDependency , ImmutableCollection < Collection < ExtensionalDataNode > > > constraintNodeMap , AtomPredicate predicate ) { if ( settings . getCardinalityPreservationMode ( ) != LOOSE ) { return ImmutableSet . of ( ) ; } return constraintNodeMap . entrySet ( ) . stream ( ) . flatMap ( e -> selectNodesToRemovePerConstraint ( requiredAndCooccuringVariables , e . getKey ( ) , e . getValue ( ) , predicate ) ) . collect ( ImmutableCollectors . toSet ( ) ) ; }
Does not look for redundant joins if not in the LOOSE preservation mode
34,598
private Stream < ImmutableExpression > extractEqualities ( ImmutableSubstitution < ImmutableTerm > substitution , ImmutableSet < Variable > leftVariables ) { return substitution . getImmutableMap ( ) . entrySet ( ) . stream ( ) . filter ( e -> leftVariables . contains ( e . getKey ( ) ) || leftVariables . contains ( e . getValue ( ) ) ) . map ( e -> termFactory . getImmutableExpression ( EQ , e . getKey ( ) , e . getValue ( ) ) ) ; }
Extracts equalities involving a left variable from the substitution
34,599
private LeftJoinNode liftSubstitution ( LeftJoinNode normalizedLeftJoin , ImmutableSubstitution < ImmutableTerm > remainingRightSubstitution , IntermediateQuery query ) { SubstitutionPropagationProposal < LeftJoinNode > proposal = new SubstitutionPropagationProposalImpl < > ( normalizedLeftJoin , remainingRightSubstitution ) ; try { NodeCentricOptimizationResults < LeftJoinNode > results = query . applyProposal ( proposal , true ) ; return results . getNewNodeOrReplacingChild ( ) . flatMap ( query :: getFirstChild ) . filter ( n -> n instanceof LeftJoinNode ) . map ( n -> ( LeftJoinNode ) n ) . orElseThrow ( ( ) -> new MinorOntopInternalBugException ( "Was expected to insert a construction node " + "followed by a LJ" ) ) ; } catch ( EmptyQueryException e ) { throw new MinorOntopInternalBugException ( "This substitution propagation was not expected " + "to make the query be empty" ) ; } }
Lifts the substitution in the absence of a LJ condition