Package org.exist.xquery.value

Examples of org.exist.xquery.value.Sequence


            }
        }
        // Check if we can speed up the processing of the "order by" clause.
        boolean fastOrderBy = false;
        LocalVariable var;
        Sequence in;
        // Save the local variable stack
        LocalVariable mark = context.markLocalVariables(false);
        try {
            // Evaluate the "in" expression
            in = inputSequence.eval(contextSequence, null);
            clearContext(getExpressionId(), in);
            // Declare the iteration variable
            var = new LocalVariable(QName.parse(context, varName, null));
            var.setSequenceType(sequenceType);
            context.declareVariableBinding(var);
            registerUpdateListener(in);
            // Declare positional variable
            LocalVariable at = null;
            if (positionalVariable != null) {
                at = new LocalVariable(QName.parse(context, positionalVariable, null));
                at.setSequenceType(POSITIONAL_VAR_TYPE);
                context.declareVariableBinding(at);
            }
            // Assign the whole input sequence to the bound variable.
            // This is required if we process the "where" or "order by" clause
            // in one step.
            var.setValue(in);
            // Save the current context document set to the variable as a hint
            // for path expressions occurring in the "return" clause.
            if (in instanceof NodeSet) {
                var.setContextDocs(in.getDocumentSet());
            } else {
                var.setContextDocs(null);
            }
            // See if we can process the "where" clause in a single step (instead of
            // calling the where expression for each item in the input sequence)
            // This is possible if the input sequence is a node set and has no
            // dependencies on the current context item.
            boolean fastExec =
                whereExpr != null && at == null &&
                !Dependency.dependsOn(whereExpr, Dependency.CONTEXT_ITEM) &&
                in.isPersistentSet() &&
                Type.subTypeOf(in.getItemType(), Type.NODE);
            // If possible, apply the where expression ahead of the iteration
            if (fastExec) {
                if (!in.isCached()) {
                    setContext(getExpressionId(), in);
                    if (whereExpr != null)
                        {whereExpr.setContextId(getExpressionId());}
                }
                in = applyWhereExpression(in);
                if (!in.isCached())
                    {clearContext(getExpressionId(), in);}
            }
            // PreorderedValueSequence applies the order specs to all items
            // in one single processing step
            if (fastOrderBy) {
                in = new PreorderedValueSequence(orderSpecs, in, getExpressionId());
            }
            // Otherwise, if there's an order by clause, wrap the result into
            // an OrderedValueSequence. OrderedValueSequence will compute
            // order expressions for every item when it is added to the result sequence.
            if (resultSequence == null) {
                if (orderSpecs != null && !fastOrderBy) {
                    resultSequence = new OrderedValueSequence(orderSpecs, in.getItemCount());
                } else {
                    resultSequence = new ValueSequence();
                    ((ValueSequence)resultSequence).keepUnOrdered(unordered);
                }
            }
            Sequence val = null;
            int p = 1;
            final IntegerValue atVal = new IntegerValue(1);
            if(positionalVariable != null)
                {at.setValue(atVal);}
            //Type.EMPTY is *not* a subtype of other types ;
            //the tests below would fail without this prior cardinality check
            if (in.isEmpty() && sequenceType != null &&
                    !Cardinality.checkCardinality(sequenceType.getCardinality(),
                    Cardinality.EMPTY)) {
                throw new XPathException(this, ErrorCodes.XPTY0004,
                    "Invalid cardinality for variable $" + varName +
                    ". Expected " + Cardinality.getDescription(sequenceType.getCardinality()) +
                    ", got " + Cardinality.getDescription(in.getCardinality()));
            }
            // Loop through each variable binding
            p = 0;
            for (final SequenceIterator i = in.iterate(); i.hasNext(); p++) {
                context.proceed(this);
                contextItem = i.nextItem();
                context.setContextSequencePosition(p, in);
                if (positionalVariable != null)
                    {at.setValue(new IntegerValue(p + 1));}
                contextSequence = contextItem.toSequence();
                // set variable value to current item
                var.setValue(contextSequence);
                if (sequenceType == null)
                    {var.checkType();} //because it makes some conversions !
                val = contextSequence;
                // check optional where clause
                if (whereExpr != null && (!fastExec)) {
                    if (contextItem instanceof NodeProxy)
                        {((NodeProxy)contextItem).addContextNode(getExpressionId(), (NodeProxy)contextItem);}
                    final Sequence bool = applyWhereExpression(null);
                    if (contextItem instanceof NodeProxy)
                        {((NodeProxy)contextItem).clearContext(getExpressionId());}
                    // if where returned false, continue
                    if (!bool.effectiveBooleanValue())
                        {continue;}
                } else {
                    val = contextItem.toSequence();
                }
                //Reset the context position
                context.setContextSequencePosition(0, null);
                if (groupedSequence==null) {
                    if (returnExpr instanceof BindingExpression) {
                        ((BindingExpression)returnExpr).eval(null, null, resultSequence, null);
                    // otherwise call the return expression and add results to resultSequence
                    } else {
                        val = returnExpr.eval(null);
                        resultSequence.addAll(val);
                    }
                } else {
                    /* bv : special processing for groupby :
                    if returnExpr is a Binding expression, pass the groupedSequence. 
                    Else, add item to groupedSequence and don't evaluate here ! 
                     */
                    if (returnExpr instanceof BindingExpression){
                        ((BindingExpression)returnExpr).eval(null, null, resultSequence, groupedSequence);
                    } else {
                        final Sequence toGroupSequence = context.resolveVariable(groupedSequence.getToGroupVarName()).getValue();
                        groupedSequence.addAll(toGroupSequence);
                    }
                }
                // free resources
                var.destroy(context, resultSequence);
            }
        } finally {
            // restore the local variable stack
            context.popLocalVariables(mark, resultSequence);
        }
        // bv : Special processing for groupBy : one return per group in groupedSequence
        if (groupSpecs!=null) {
            mark = context.markLocalVariables(false);
            context.declareVariableBinding(var);

            // Declare positional variable if required
            LocalVariable at = null;
            if (positionalVariable != null) {
                at = new LocalVariable(QName.parse(context, positionalVariable, null));
                at.setSequenceType(POSITIONAL_VAR_TYPE);
                context.declareVariableBinding(at);
            }
            final IntegerValue atVal = new IntegerValue(1);
            if(positionalVariable != null) {
                at.setValue(atVal);
            }

            int p = 0;
            for (final Iterator<String> it = groupedSequence.iterate(); it.hasNext(); ) {
                final GroupedValueSequence currentGroup = groupedSequence.get(it.next());
                context.proceed(this);
                // set binding variable to current group
                var.setValue(currentGroup);
                var.checkType();
                //set value of grouping keys for the current group
                for (int i=0; i< groupKeyVar.length ; i ++) {
                    groupKeyVar[i].setValue(currentGroup.getGroupKey().itemAt(i).toSequence());
                }
                if (positionalVariable != null) {
                    final ValueSequence ps = new ValueSequence();
                    for (int i = 0; i < currentGroup.getItemCount(); i++) {
                        ps.add(new IntegerValue(p + i + 1));
                    }
                    at.setValue(ps);
                }
                //evaluate real return expression
                final Sequence val = groupReturnExpr.eval(null);
                resultSequence.addAll(val);

                p += currentGroup.getItemCount();
            }
            //Reset the context position
View Full Code Here


    protected Sequence processCompressedEntry(String name, boolean isDirectory, InputStream is, Sequence filterParam, Sequence storeParam) throws IOException, XPathException, XMLDBException
    {
        String dataType = isDirectory ? "folder" : "resource";

        //call the entry-filter function
        Sequence filterParams[] = new Sequence[3];
        filterParams[0] = new StringValue(name);
        filterParams[1] = new StringValue(dataType);
        filterParams[2] = filterParam;
        Sequence entryFilterFunctionResult = entryFilterFunction.evalFunction(contextSequence, null, filterParams);

        if(BooleanValue.FALSE == entryFilterFunctionResult.itemAt(0))
        {
            return Sequence.EMPTY_SEQUENCE;
        }
        else
        {
            Sequence entryDataFunctionResult;
            Sequence uncompressedData = Sequence.EMPTY_SEQUENCE;
           
            //copy the input data
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte buf[] = new byte[1024];
            int read = -1;
            while((read = is.read(buf)) != -1)
            {
                baos.write(buf, 0, read);
            }
            byte[] entryData = baos.toByteArray();

            if (entryDataFunction.getSignature().getArgumentCount() == 3){
             
                Sequence dataParams[] = new Sequence[3];
                System.arraycopy(filterParams, 0, dataParams, 0, 2);
                dataParams[2] = storeParam;
                entryDataFunctionResult = entryDataFunction.evalFunction(contextSequence, null, dataParams);
               
                String path = entryDataFunctionResult.itemAt(0).getStringValue();
               
                Collection root = new LocalCollection(context.getUser(), context.getBroker().getBrokerPool(), new AnyURIValue("/db").toXmldbURI(), context.getAccessContext());

          if (isDirectory){
                 
                  XMLDBAbstractCollectionManipulator.createCollection(root, path);
                 
                } else {

                    Resource resource;
                   
                File file = new File(path);
                name = file.getName();
                path = file.getParent();
               
                Collection target = (path==null) ? root : XMLDBAbstractCollectionManipulator.createCollection(root, path);
               
                  MimeType mime = MimeTable.getInstance().getContentTypeFor(name);
                 
                try{
                  NodeValue content = ModuleUtils.streamToXML(context, new ByteArrayInputStream(baos.toByteArray()));
                  resource = target.createResource(name, "XMLResource");
                  ContentHandler handler = ((XMLResource)resource).setContentAsSAX();
                  handler.startDocument();
                  content.toSAX(context.getBroker(), handler, null);
                  handler.endDocument();
                } catch(SAXException e){
                  resource = target.createResource(name, "BinaryResource");
                  resource.setContent(baos.toByteArray());
                    }
               
                if (resource != null){
                  if (mime != null){
                    ((EXistResource)resource).setMimeType(mime.getName());
                  }
                  target.storeResource(resource);
                }
                 
                }
               
            } else {
             
                //try and parse as xml, fall back to binary
                try
                {
                    uncompressedData = ModuleUtils.streamToXML(context, new ByteArrayInputStream(entryData));
                }
                catch(SAXException saxe)
                {
                    if(entryData.length > 0)
                        uncompressedData = BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), new ByteArrayInputStream(entryData));
                }

                //call the entry-data function
                Sequence dataParams[] = new Sequence[4];
                System.arraycopy(filterParams, 0, dataParams, 0, 2);
                dataParams[2] = uncompressedData;
                dataParams[3] = storeParam;
                entryDataFunctionResult = entryDataFunction.evalFunction(contextSequence, null, dataParams);
               
View Full Code Here

        super(context, signature);
    }
   
    @Override
    public Sequence eval(final Sequence[] args, final HttpRequest request) throws XPathException {
        final Sequence result;
       
        if(isCalledAs(qnCookie.getLocalName())) {
            final String cookieName = args[0].getStringValue();
           
            if(getSignature().getArgumentCount() == 1) {
                result = getCookie(request, cookieName, null);
            } else if(getSignature().getArgumentCount() == 2) {
                final Sequence defaultValues = args[1];
                result = getCookie(request, cookieName, defaultValues);
            } else {
                throw new XPathException(this, "Unknown function call: " + getSignature());
            }  
        } else {
View Full Code Here

       
        return result;
    }
   
    private Sequence getCookie(final HttpRequest request, final String cookieName, final Sequence defaultValues) throws XPathException {
        final Sequence result;
        final String cookieValue = request.getCookieValue(cookieName);
        if(cookieValue == null) {
            if(defaultValues != null) {
                result = defaultValues;
            } else {
View Full Code Here

        super(context, signature);
    }
   
    @Override
    public Sequence eval(final Sequence[] args, final HttpRequest request) throws XPathException {
        final Sequence result;
       
        if(isCalledAs(qnParameterNames.getLocalName())) {
            result = new ValueSequence();
            for(final String parameterName : request.getParameterNames()) {
                result.add(new StringValue(parameterName));
            }
        } else if(isCalledAs(qnParameter.getLocalName())) {
            final String paramName = args[0].getStringValue();
           
            if(getSignature().getArgumentCount() == 1) {
                result = getParameter(request, paramName, null);
            } else if(getSignature().getArgumentCount() == 2) {
                final Sequence defaultValues = args[1];
                result = getParameter(request, paramName, defaultValues);
            } else {
                throw new XPathException(this, "Unknown function call: " + getSignature());
            }  
        } else {
View Full Code Here

       
        return result;
    }
   
    private Sequence getParameter(final HttpRequest request, final String paramName, final Sequence defaultValues) throws XPathException {
        final Sequence result;
        final Object queryParamValues = request.getQueryParam(paramName);
        if(queryParamValues == null) {
            if(defaultValues != null) {
                result = defaultValues;
            } else {
                result = Sequence.EMPTY_SEQUENCE;
            }
        } else {
            result = new ValueSequence();
            if(queryParamValues instanceof List) {
                for(final Object value : (List)queryParamValues) {
                    result.add(new StringValue(value.toString()));
                }
            } else {
                result.add(new StringValue(queryParamValues.toString()));
            }
        }
       
        return result;
    }
View Full Code Here

                    "CONTEXT ITEM", contextItem.toSequence());}
        }
        final Variable var = getVariable();
        if (var == null)
            {throw new XPathException(this, ErrorCodes.XPDY0002, "variable '$" + qname + "' is not set.");}
        final Sequence seq = var.getValue();
        if (seq == null)
            {throw new XPathException(this, ErrorCodes.XPDY0002, "undefined value for variable '$" + qname + "'");}
        final Sequence result = seq;
        if (context.getProfiler().isEnabled())
            {context.getProfiler().end(this, "", result);}
        return result;
    }
View Full Code Here

                {context.getProfiler().message(this, Profiler.START_SEQUENCES, "RESULT SEQUENCE", resultSequence);}
        }       
       
    final LocalVariable var = new LocalVariable(QName.parse(context, varName, null));
       
    final Sequence inSeq = inputSequence.eval(contextSequence, contextItem);
        if (sequenceType != null) {
          //Type.EMPTY is *not* a subtype of other types ; the tests below would fail without this prior cardinality check
          if (!inSeq.isEmpty() && !Type.subTypeOf(inSeq.getItemType(), sequenceType.getPrimaryType()))
        {throw new XPathException(this, ErrorCodes.XPTY0004, "Invalid type for variable $" + varName +
            ". Expected " +
            Type.getTypeName(sequenceType.getPrimaryType()) +
            ", got " +Type.getTypeName(inSeq.getItemType()), inSeq);}
        } 

    boolean found = (mode == EVERY) ? true : false;
    boolean canDecide = (mode == EVERY) ? true : false;

    for (final SequenceIterator i = inSeq.iterate(); i.hasNext(); ) {
      canDecide = true;
     
      final Item item = i.nextItem();     
      // set variable value to current item
            var.setValue(item.toSequence());
            if (sequenceType == null)
                {var.checkType();} //... because is makes some conversions
     
            Sequence satisfiesSeq = null;
           
            //Binds the variable : now in scope
        final LocalVariable mark = context.markLocalVariables(false);
        try {
          context.declareVariableBinding(var);
          //Evaluate the return clause for the current value of the variable
          satisfiesSeq = returnExpr.eval(contextSequence, contextItem);
        } finally {
          //Unbind the variable until the next iteration : now out of scope
          context.popLocalVariables(mark, satisfiesSeq);
        }
           
            if (sequenceType != null) {
            //TODO : ignore nodes right now ; they are returned as xs:untypedAtomicType
            if (!Type.subTypeOf(sequenceType.getPrimaryType(), Type.NODE)) {
                if (!Type.subTypeOf(item.toSequence().getItemType(), sequenceType.getPrimaryType()))
              {throw new XPathException(this, ErrorCodes.XPTY0004, "Invalid type for variable $" + varName +
                  ". Expected " +
                  Type.getTypeName(sequenceType.getPrimaryType()) +
                  ", got " +Type.getTypeName(contextItem.toSequence().getItemType()), inSeq);}
              } else if (!Type.subTypeOf(item.getType(), Type.NODE))
            {throw new XPathException(this, ErrorCodes.XPTY0004, "Invalid type for variable $" + varName +
                ". Expected " +
                Type.getTypeName(Type.NODE) +
                " (or more specific), got " + Type.getTypeName(item.getType()), inSeq);}
            //trigger the old behaviour
            else {var.checkType();}
            } 
           
      found = satisfiesSeq.effectiveBooleanValue();
      if ((mode == SOME ) && found)
        {break;}
      if ((mode == EVERY) && !found)
        {break;}
    }
       
    final Sequence result = canDecide && found ? BooleanValue.TRUE : BooleanValue.FALSE;
       
        if (context.getProfiler().isEnabled())
            {context.getProfiler().end(this, "", result);}
       
        return result;       
View Full Code Here

        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            builder.setReplaceAttributeFlag(replaceAttribute);
            context.proceed(this, builder);

            final Sequence nameSeq = qnameExpr.eval(contextSequence, contextItem);
            if(!nameSeq.hasOne())
              {throw new XPathException(this, "The name expression should evaluate to a single value");}

            final Item qnItem = nameSeq.itemAt(0);
            QName qn;
            if (qnItem.getType() == Type.QNAME)
                {qn = ((QNameValue) qnItem).getQName();}
            else
              try {
                qn = QName.parse(context, nameSeq.getStringValue(), null);
          } catch (final IllegalArgumentException e) {
          throw new XPathException(this, ErrorCodes.XPTY0004, "'" + nameSeq.getStringValue() + "' is not a valid attribute name");
        }

            //Not in the specs but... makes sense
            if(!XMLChar.isValidName(qn.getLocalName()))
              {throw new XPathException(this, ErrorCodes.XPTY0004, "'" + qn.getLocalName() + "' is not a valid attribute name");}
           
            if ("xmlns".equals(qn.getLocalName()) && qn.getNamespaceURI().isEmpty())
              {throw new XPathException(this, ErrorCodes.XQDY0044, "'" + qn.getLocalName() + "' is not a valid attribute name");}

            String value;
            final Sequence valueSeq = valueExpr.eval(contextSequence, contextItem);
            if(valueSeq.isEmpty())
              {value = "";}
            else {
                final StringBuilder buf = new StringBuilder();
                for(final SequenceIterator i = valueSeq.iterate(); i.hasNext(); ) {
                    final Item next = i.nextItem();
                    buf.append(next.getStringValue());
                    if(i.hasNext())
                        {buf.append(' ');}
                }
View Full Code Here

                {context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);}
            if (contextItem != null)
                {context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());}
        }
       
    Sequence lval = left.eval(contextSequence, contextItem);   
    Sequence rval = right.eval(contextSequence, contextItem);
        lval.removeDuplicates();
    rval.removeDuplicates();
      
        Sequence result;
        if (lval.isEmpty() && rval.isEmpty()) {
            result = Sequence.EMPTY_SEQUENCE;
        } else if(rval.isEmpty()) {
            if(!Type.subTypeOf(lval.getItemType(), Type.NODE))
                {throw new XPathException(this, ErrorCodes.XPTY0004, "union operand is not a node sequence");}
View Full Code Here

TOP

Related Classes of org.exist.xquery.value.Sequence

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.