Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (c) 2009 Mysema Ltd.
   * All rights reserved.
   * 
   */
  package com.mysema.rdfbean.sesame.query;
  
  import java.io.Closeable;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import  javax.annotation.Nullable;
 
 import  org.openrdf.model.BNode;
 import  org.openrdf.model.Literal;
 import  org.openrdf.model.Resource;
 import  org.openrdf.model.Statement;
 import  org.openrdf.model.URI;
 import  org.openrdf.model.Value;
 import  org.openrdf.model.ValueFactory;
 import  org.openrdf.model.vocabulary.XMLSchema;
 import  org.openrdf.query.BindingSet;
 import  org.openrdf.query.algebra.*;
 import  org.openrdf.query.algebra.StatementPattern.Scope;
 import  org.openrdf.query.parser.TupleQueryModel;
 import  org.openrdf.repository.RepositoryConnection;
 import  org.openrdf.result.TupleResult;
 import  org.openrdf.store.StoreException;
 
SesameQuery provides a query implementation for Sesame Repository

Author(s):
tiwe
Version:
$Id$
 
 public class SesameQuery 
     extends AbstractProjectingQuery<SesameQuery, Value, Resource, BNode, URI, Literal, Statement>  
     implements TransformerContextBeanQueryCloseable{
    
     private static final Logger logger = LoggerFactory.getLogger(SesameQuery.class);
     
     private static final Logger queryTreeLogger = LoggerFactory.getLogger("com.mysema.rdfbean.sesame.queryTree");
    
     private static final URI RDF_TYPE = org.openrdf.model.vocabulary.RDF.TYPE;
     
     private static final Map<Operator<?>,OperationTransformertransformers = new HashMap<Operator<?>,OperationTransformer>();
     
     static{
         register(new FunctionTransformer());
         
         register(new BetweenTransformer());
         register(new BooleanTransformer());
        register(new CastTransformer());
        register(new ColIsEmptyTransformer());
        register(new CompareTransformer());
        register(new ContainsKeyValueTransformer());
        register(new EqualsTransformer());
        register(new ExistsTransformer());
        register(new InstanceOfTransformer());
        register(new InTransformer());
        register(new IsNullTransformer());
        register(new MapIsEmptyTransformer());
        register(new MathTransformer());
        register(new RegexTransformer());
        register(new StringContainsTransformer());
    }
    
    private final Configuration conf;
    
    private final RepositoryConnection connection;
    
    private final Map<Object,Var> constToVar = new HashMap<Object,Var>();
    private final VarNameIterator extNames = new VarNameIterator("_ext_");
    
    private ValueExpr filterConditions;
    
    private final boolean includeInferred = true;
    
    private final Inference inference;
    
    private JoinBuilder joinBuilder;
    
    private final Ontology ontology
    private final Stack<Operator<?>> operatorStack = new Stack<Operator<?>>();
    private Map<Path<?>,Var> allPaths = new HashMap<Path<?>,Var>();
    
    private Map<Path<?>, Var> pathToMatchedVar = new HashMap<Path<?>,Var>();
    
    private Map<Path<?>, Var> pathToVar = new HashMap<Path<?>, Var>();
    
    private final StatementPattern.Scope patternScope;
    
    private TupleResult queryResult;
    
    private final Map<UID, Var> resToVar = new HashMap<UID, Var>();
    
    private final Transformer<StatementPattern,TupleExpr> stmtTransformer = new Transformer<StatementPattern,TupleExpr>(){
        @Override
        public TupleExpr transform(StatementPattern pattern) {
            if (.untypedAsString()){
                Var object = pattern.getObjectVar();
                if (object.getValue() != null && object.getValue() instanceof Literal){
                    return transformLiteralPattern(patternobject);                    
                }            
            }        
            
            if (.subClassOf()){
                Value predicate = pattern.getPredicateVar().getValue();
                Var object = pattern.getObjectVar();
                if (predicate != null && predicate.equals() && object.getValue() != null){
                    return transformTypePattern(patternobject);
                }
            }
            
            return pattern;
        }
        
    };
    
    private final ValueFactory valueFactory;
    
    private final VarNameIterator varNames = new VarNameIterator("_var_");
    
    public SesameQuery(Session session
            SesameDialect dialect,
            RepositoryConnection connection
            StatementPattern.Scope patternScope,
            Ontology ontology,
            Inference inference) {
        super(dialectsession);        
        this. = Assert.notNull(connection);
        this. = session.getConfiguration();
        this. = Assert.notNull(ontology);
        this. = Assert.notNull(inference);
        this. = patternScope;
        this. = dialect.getValueFactory();
        this. = new JoinBuilder();
    }
    
    private static void register(OperationTransformer transformer){
        for (Operator<?> operator : transformer.getSupportedOperations()){
            .put(operatortransformer);
        }
    }
    
    private void addFilterCondition(ValueExpr filterCondition) {
        if ( == null) {
             = filterCondition;
        } else if (filterCondition != null){
             = new And(filterCondition);
        }
    }
    
    @SuppressWarnings("unchecked")
    private void addProjection(Expr<?> expr, ProjectionElemList projectionList<ExtensionElem> extensions){
        if (expr instanceof Path){
            projection.addElement(new ProjectionElem(toVar((Path<?>) expr).getName()));    
        }else if (expr instanceof EConstructor){    
            EConstructor<?> constructor = (EConstructor<?>)expr;
            for (Expr<?> arg : constructor.getArgs()){
                addProjection(argprojectionextensions);
            }
        }else{
            ValueExpr val = toValue(expr);
            if (val instanceof Var){
                projection.addElement(new ProjectionElem(((Var)val).getName()));
            }else{
                String extLabel = .next();
                projection.addElement(new ProjectionElem(extLabel));
                extensions.add(new ExtensionElem(valextLabel));
            }
        }  
    }
            
    public void close() throws IOException {
        if ( != null){
            try {
                .close();
            } catch (StoreException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
    protected <RT> RT convert(Class<RT> rt, Literal literal) {
        return .getConverterRegistry().fromString(literal.getLabel(), rt);
    }
    
    @Override
    public long count() {
        // TODO : use aggregate function
        long total = 0l;
        Iterator<?> it = getInnerResults();
        while (it.hasNext()){
            total++;
            it.next();
        }
        return total;
    }
    
    @Override
    public JoinBuilder createJoinBuilder() {
        return new JoinBuilder();
    }
        
    private StatementPattern createPattern(Var sUID p, Var o){
        return new StatementPattern(
                Assert.notNull(s"subject is null"), 
                toVar(Assert.notNull(p"predicate is null")), 
                Assert.notNull(o"object is null"));
    }
    private TupleExpr createTupleExpr(TupleExpr tupleExpr
            ValueExpr filterConditions
            List<OrderElem> orderElements,
            List<ExtensionElem> extensions,
            ProjectionElemList projection,
            QueryModifiers modifiers){
        
        if (filterConditions != null){
            tupleExpr = new Filter(tupleExprfilterConditions);
        }        
        // order
        if(!orderElements.isEmpty()){
            tupleExpr = new Order(tupleExprorderElements); 
        }        
        // projection
        if (!extensions.isEmpty()){
            tupleExpr = new Extension(tupleExprextensions);
        }        
        
        if (!projection.getElements().isEmpty()){
            tupleExpr = new Projection(tupleExprprojection);    
        }                
        // limit / offset
        if (modifiers.isRestricting()){
            Long limit = modifiers.getLimit();
            Long offset = modifiers.getOffset();            
            tupleExpr = new Slice(tupleExpr
                    offset != null ? offset.intValue() : 0,
                    limit != null ? limit.intValue() : -1);
        }
        
        return tupleExpr;
    }
    
    @Override
    public Var createVar() {
       return new Var(.next());
    }
    
    @Override
    public Locale getLocale() {
        return .getCurrentLocale();
    }
    
    @Override
    protected Iterator<Value[]> getInnerResults() {
        QueryMetadata metadata = .getMetadata();
        List<OrderElem> orderElements = new ArrayList<OrderElem>();
        ProjectionElemList projection = new ProjectionElemList();
        List<ExtensionElem> extensions = new ArrayList<ExtensionElem>();
        
        // from
        for (JoinExpression join : metadata.getJoins()){            
            handleRootPath((Path<?>) join.getTarget());
        }        
        // where
        if (metadata.getWhere() != null){
            addFilterCondition(toValue(metadata.getWhere()));
        }        
        // order by (optional paths)
        .setOptional();
        for (OrderSpecifier<?> os : metadata.getOrderBy()){
            orderElements.add(new OrderElem(toValue(os.getTarget()), os.isAscending()));
        }        
        
        .putAll();
         = ;
        // select (optional paths)
        for (Expr<?> expr : metadata.getProjection()){
            addProjection(exprprojectionextensions);
        }
        .setMandatory();
        
        TupleExpr tupleExpr = createTupleExpr(
                .getTupleExpr(),   // from
                ,             // where
                orderElements,                // order
                extensions,                   // select
                projection,
                getMetadata().getModifiers());// paging
        
        
        // evaluate it
        try {
            TupleQueryModel query;
            if (getMetadata().isDistinct()){
                query = new TupleQueryModel(new Distinct(tupleExpr));
            }else{
                query = new TupleQueryModel(tupleExpr);
            }
            
            logQuery(query);            
             = DirectQuery.query(query);
            
            return new Iterator<Value[]>(){
                public boolean hasNext() {
                    try {                        
                        return .hasNext();
                    } catch (StoreException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
                public Value[] next() {
                    try {
                        BindingSet bindingSet = .next();
                        List<StringbindingNames = .getBindingNames();
                        Value[] values = new Value[bindingNames.size()];
                        for (int i = 0; i < bindingNames.size(); i++){
                            values[i] = bindingSet.getValue(bindingNames.get(i));
                        }
                        return values;
                    } catch (StoreException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
                public void remove() {
                    // do nothing
                }                
            };
        } catch (StoreException e) {
            throw new RuntimeException(e.getMessage(), e);
        }        
    }
    
    @Override
    public MappedPath getMappedPath(Path<?> path) {
        return this.getMappedPathForPropertyPath(path);
    }
    
    @Override
    public Scope getPatternScope() {
        return ;
    }
        
    @SuppressWarnings("unchecked")
    public ID getResourceForLID(Expr<?> arg) {
        String lid = ((Constant<String>)arg).getConstant();
        ID id = .getIdentityService().getID(new LID(lid));
        return id;
    }
    @Override
    public ValueFactory getValueFactory() {
        return ;
    }
    private void handleRootPath(Path<?> path) {
        Var var = new Var(path.getMetadata().getExpression().toString());
        .disallow(var.getName());
        .put(pathvar);
        MappedClass mappedClass = MappedClass.getMappedClass(path.getType());
        UID rdfType = mappedClass.getUID();
        if (rdfType != null){
            match(var.toVar(rdfType));
        } else {
            throw new IllegalArgumentException("No types mapped against " + path.getType().getName());
        }
    }
    public boolean inNegation(){
        int notIndex = .lastIndexOf(.);
        if (notIndex > -1){
            int existsIndex = .lastIndexOf(.);
            return notIndex > existsIndex;
        }
        return false;
    }
    
    public boolean inOptionalPath(){
        return .contains(.) || 
            (.contains(.) && .peek() != .);
    }
    
    @Override
    public boolean isRegistered(Path<?> path) {
        return .containsKey(path);
    }
  
    protected void logQuery(TupleQueryModel query) {
        if (.isDebugEnabled()){
            .debug(query.toString());                    
        }                        
        if (.isDebugEnabled()){
            .debug(new QuerySerializer(query,false).toString());
        }
    }
            
    public void match(JoinBuilder builder, Var subUID pred, Var obj){
        builder.add(createPattern(subpredobj));
    }
    
    public void match(Var subUID pred, Var obj) {
        .add(createPattern(subpredobj));
    }
    
    @Override
    public void register(Path<?> path, Var var) {
        .put(pathvar);
    }
    private StatementPattern replaceObject(StatementPattern pattern, Var obj){
        return new StatementPattern(pattern.getScope(), 
                pattern.getSubjectVar(), 
                pattern.getPredicateVar(),
                obj,
                pattern.getContextVar());
    }
        
    public TupleExpr toTuples(SubQuery subQuery){
        EBoolean where = subQuery.getMetadata().getWhere();
        
        JoinBuilder normalJoins = ;
         = createJoinBuilder();
        for (JoinExpression join : subQuery.getMetadata().getJoins()){            
            handleRootPath((Path<?>) join.getTarget());
        }
       
        // list
        ProjectionElemList projection = new ProjectionElemList();            
        List<ExtensionElem> extensions = new ArrayList<ExtensionElem>();
        for (Expr<?> expr : subQuery.getMetadata().getProjection()){
            addProjection(exprprojectionextensions);
        }        
        
        ValueExpr filterConditions = toValue(where);
        
        // from
        TupleExpr tupleExpr = createTupleExpr(
                .getTupleExpr(),             // from
                filterConditions,                       // where
                Collections.<OrderElem>emptyList(),     // order
                extensions,                             // select
                projection,
                subQuery.getMetadata().getModifiers()); // paging
                
         = normalJoins;
        return tupleExpr;
    }
    
    @SuppressWarnings("unchecked")
    @Nullable
    public ValueExpr toValue(Expr<?> expr) {
        if (expr instanceof BooleanBuilder){
            return toValue(((BooleanBuilder)expr).getValue());            
        }else if (expr instanceof Path) {
            return toVar((Path<?>) expr);            
        } else if (expr instanceof Operation) {
            return  toValue((Operation<?,?>)expr);            
        } else if (expr instanceof Constant) {
            return toVar((Constant<?>)expr);            
        } else {
            throw new IllegalArgumentException(expr.toString());
        }
    }
    @Override
    public Value toValue(ID id) {
        return .getResource(id);
    }
    @Nullable
    private ValueExpr toValue(Operation<?,?> operation) {
        boolean outerOptional = inOptionalPath();
        boolean innerOptional = false;
        Map<Path<?>,Var> _pathToVar = null;
        Map<Path<?>,Var> _pathToMatchedVar = null;
        .push(operation.getOperator());        
        if (!outerOptional && inOptionalPath()){
            .setOptional();
            innerOptional = true;
            
            _pathToVar = ;
            _pathToMatchedVar = ;
             = new HashMap<Path<?>,Var>(_pathToVar);
             = new HashMap<Path<?>,Var>(_pathToMatchedVar);
        }                  
        try{
            OperationTransformer transformer = .get(operation.getOperator());
            if (transformer != null) {             
                return transformer.transform(operationthis);
            } else {
                throw new IllegalArgumentException(operation.toString());
            }    
        }finally{
            .pop();
            if (!outerOptional && innerOptional){
                .setMandatory();
                
                .putAll();
                 = _pathToVar;
                 = _pathToMatchedVar;
            }
        }
        
    }
    @SuppressWarnings("unchecked")
    public Var toVar(Constant<?> constant) {
        Object javaValue = constant.getConstant();
        if (.containsKey(javaValue)){
            return .get(javaValue);
        }else{
            Value rdfValue;
            ConverterRegistry converter = .getConverterRegistry();
            if (javaValue instanceof Class){
                UID datatype = converter.getDatatype((Class<?>)javaValue);
                if (datatype != null){
                    return toVar(datatype);
                }else{
                    rdfValue = getTypeForDomainClass((Class<?>)javaValue);
                }
            }else if (converter.supports(javaValue.getClass())){
                String label = converter.toString(javaValue);
                UID datatype = converter.getDatatype(javaValue.getClass());
                rdfValue = .createLiteral(label.getURI(datatype));
            }else{
                ID id = .getId(javaValue);                
                rdfValue =  .getResource(Assert.notNull(id"id is null"));
            }        
            Var var = new Var(.next(), rdfValue);
            var.setAnonymous(true);
            .put(javaValuevar);
            return var;
        }        
    }
    public Var toVar(Path<?> path) {
        if (.containsKey(path)) {
            return .get(path);
            
        } else if (path.getMetadata().getParent() != null) {
            PathMetadata<?> md = path.getMetadata();
            PathType pathType = md.getPathType();            
            Var parentNode = toVar(md.getParent());
            Var pathNode = null;
            Var matchedVar = .get(path);
            
            if (pathType.equals(.)) {
                MappedPath mappedPath = getMappedPathForPropertyPath(path); 
                List<MappedPredicatepredPath = mappedPath.getPredicatePath();
                if (predPath.size() > 0){
                    for (int i = 0; i < predPath.size(); i++){
                        MappedPredicate pred = predPath.get(i);
                        if (matchedVar != null && i == predPath.size() -1){
                            pathNode = matchedVar;
                        }else if (i == predPath.size() - 1){    
                            pathNode = new Var(path.toString().replace('.''_'));
                            .disallow(pathNode.getName());
                        }else{
                            pathNode = new Var(.next());    
                        }                        
                        if (!pred.inv()) {
                            match(parentNodepred.getUID(), pathNode);
                        } else {
                            match(pathNodepred.getUID(), parentNode);
                        }
                        parentNode = pathNode;
                    }
                     
                }else{
//                    idPropertyInOperation = true;
                    // id property
                    pathNode =  parentNode;
                }
            } else if (pathType.equals(.) || pathType.equals(.)) {
                // ?!? 
                throw new UnsupportedOperationException(pathType + " not supported!");
                
            } else if (pathType.equals(.) || pathType.equals(.)) {
                @SuppressWarnings("unchecked")
                int index = getIntValue((Constant<Integer>)md.getExpression());                
                for (int i = 0; i < indexi++){
                    pathNode = new Var(.next());
                    match(parentNode.pathNode);
                    parentNode = pathNode;
                }
                pathNode = new Var(.next());
                match(parentNode.pathNode);
            } else if (pathType.equals(.) || pathType.equals(.)) {     
                MappedPath mappedPath = getMappedPathForPropertyPath(md.getParent()); 
                MappedProperty<?> mappedProperty = mappedPath.getMappedProperty();
                if (!mappedProperty.isLocalized()){
                    match(parentNodemappedProperty.getKeyPredicate(), 
                        ((Var)toValue(path.getMetadata().getExpression())));
                        
                    if (mappedProperty.getValuePredicate() != null){
                        pathNode = new Var(.next());
                        match(parentNodemappedProperty.getValuePredicate(), pathNode);
                    }else{
                        pathNode = parentNode;
                    }
                }else{  
                    pathNode = parentNode;            
                }
                
            } else {
                throw new UnsupportedOperationException(pathType + " not supported!");
            }
            .put(pathpathNode);
            return pathNode;
        } else {
            throw new IllegalArgumentException("Undeclared path " + path);
        }
    }
    public Var toVar(UID id) {
        if (.containsKey(id)) {
            return .get(id);
        } else {
            Var var = new Var(.next(), .getResource(id));
            var.setAnonymous(true);
            .put(idvar);
            return var;
        }
    }
    public Var toVar(Value value){
        if (.containsKey(value)){
            return .get(value);
        }else{
            Var var = new Var(.next(), value);
            var.setAnonymous(true);
            .put(valuevar);
            return var;
        }
    }
    private TupleExpr transformLiteralPattern(StatementPattern pattern, Var object) {
        Literal lit = (Literal) pattern.getObjectVar().getValue();
        if (lit.getDatatype() != null && lit.getDatatype().equals(XMLSchema.STRING)){
            // match untyped literal for xsd:string vars
            Var obj2 = new Var(object.getName()+"_untyped".createLiteral(lit.getLabel()));
            StatementPattern pattern2 = replaceObject(patternobj2);
            return new Union(patternpattern2);
        }else{
            return pattern;
        }
    }
    private TupleExpr transformTypePattern(StatementPattern pattern, Var object) {
        if (object.getValue() instanceof URI){
            Set<UIDsubtypes = .getSubtypes(.getUID((URI) object.getValue()));
            if (subtypes.size() > 1){
                List<StatementPattern> patterns = new ArrayList<StatementPattern>(subtypes.size());
                int counter = 1;
                for (UID type : subtypes){
                    Var subtypeVar = new Var(object.getName() + "_" + (counter++));
                    subtypeVar.setValue(.getURI(type));
                    patterns.add(replaceObject(patternsubtypeVar));
                }
                return new Union(patterns);
            }else{
                return pattern;
            }
            
        }else{
            return pattern;
        }        
    }
    
New to GrepCode? Check out our FAQ X