예제 #1
0
 /* (non-Javadoc)
  * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
  */
 public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
   NodeValue docNode = (NodeValue) args[0].itemAt(0);
   if (docNode.getImplementationType() == NodeValue.IN_MEMORY_NODE)
     throw new XPathException(
         getASTNode(),
         "First argument to function node-by-id "
             + "should be a persistent node, not an in-memory node.");
   DocumentImpl doc = ((NodeProxy) docNode).getDocument();
   String id = args[1].itemAt(0).getStringValue();
   NodeId nodeId = context.getBroker().getBrokerPool().getNodeFactory().createFromString(id);
   NodeProxy node = new NodeProxy(doc, nodeId);
   return node;
 }
예제 #2
0
  /* (non-Javadoc)
   * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
   */
  public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if (context.getProfiler().isEnabled()) {
      context.getProfiler().start(this);
      context
          .getProfiler()
          .message(
              this,
              Profiler.DEPENDENCIES,
              "DEPENDENCIES",
              Dependency.getDependenciesName(this.getDependencies()));
      if (contextSequence != null)
        context
            .getProfiler()
            .message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
    }

    Sequence result;
    // return 0 if the argument sequence is empty
    // TODO : return empty sequence ?
    if (args[0].isEmpty()) result = IntegerValue.ZERO;
    else {
      int count = 0;
      for (SequenceIterator i = args[0].iterate(); i.hasNext(); ) {
        Item next = i.nextItem();
        if (Type.subTypeOf(next.getType(), Type.NODE)) {
          NodeValue nv = (NodeValue) next;
          if (nv.getImplementationType() != NodeValue.PERSISTENT_NODE)
            throw new XPathException(
                getASTNode(), getName() + " cannot be applied to in-memory nodes.");
          NodeProxy np = (NodeProxy) nv;
          Match match = np.getMatches();
          while (match != null) {
            if (match.getNodeId().isDescendantOrSelfOf(np.getNodeId())) {
              count += match.getFrequency();
            }
            match = match.getNextMatch();
          }
        }
      }
      result = new IntegerValue(count);
    }

    if (context.getProfiler().isEnabled()) context.getProfiler().end(this, "", result);

    return result;
  }
  /**
   * Processes a compressed entry from an archive
   *
   * @param name The name of the entry
   * @param isDirectory true if the entry is a directory, false otherwise
   * @param is an InputStream for reading the uncompressed data of the entry
   * @param filterParam is an additional param for entry filtering function
   * @param storeParam is an additional param for entry storing function
   * @throws XMLDBException
   */
  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);
      }

      return entryDataFunctionResult;
    }
  }
예제 #4
0
  private boolean deepEquals(Item a, Item b, Collator collator) {
    try {
      final boolean aAtomic = Type.subTypeOf(a.getType(), Type.ATOMIC);
      final boolean bAtomic = Type.subTypeOf(b.getType(), Type.ATOMIC);
      if (aAtomic || bAtomic) {
        if (!aAtomic || !bAtomic) return false;
        try {
          AtomicValue av = (AtomicValue) a;
          AtomicValue bv = (AtomicValue) b;
          if (Type.subTypeOf(av.getType(), Type.NUMBER)
              && Type.subTypeOf(bv.getType(), Type.NUMBER)) {
            // or if both values are NaN
            if (((NumericValue) a).isNaN() && ((NumericValue) b).isNaN()) return true;
          }
          return ValueComparison.compareAtomic(
              collator, av, bv, Constants.TRUNC_NONE, Constants.EQ);
        } catch (XPathException e) {
          return false;
        }
      }
      //		assert Type.subTypeOf(a.getType(), Type.NODE);
      //		assert Type.subTypeOf(b.getType(), Type.NODE);
      if (a.getType() != b.getType()) return false;
      NodeValue nva = (NodeValue) a, nvb = (NodeValue) b;
      if (nva == nvb) return true;
      try {
        // Don't use this shortcut for in-memory nodes since the symbol table is ignored.
        if (nva.getImplementationType() != NodeValue.IN_MEMORY_NODE && nva.equals(nvb))
          return true; // shortcut!
      } catch (XPathException e) {
        // apparently incompatible values, do manual comparison
      }
      Node na, nb;
      switch (a.getType()) {
        case Type.DOCUMENT:
          // NodeValue.getNode() doesn't seem to work for document nodes
          na = nva instanceof Node ? (Node) nva : ((NodeProxy) nva).getDocument();
          nb = nvb instanceof Node ? (Node) nvb : ((NodeProxy) nvb).getDocument();
          return compareContents(na, nb);
        case Type.ELEMENT:
          na = nva.getNode();
          nb = nvb.getNode();
          return compareElements(na, nb);
        case Type.ATTRIBUTE:
          na = nva.getNode();
          nb = nvb.getNode();
          return compareNames(na, nb) && safeEquals(na.getNodeValue(), nb.getNodeValue());
        case Type.PROCESSING_INSTRUCTION:
        case Type.NAMESPACE:
          na = nva.getNode();
          nb = nvb.getNode();
          return safeEquals(na.getNodeName(), nb.getNodeName())
              && safeEquals(nva.getStringValue(), nvb.getStringValue());
        case Type.TEXT:
        case Type.COMMENT:
          return safeEquals(nva.getStringValue(), nvb.getStringValue());

        default:
          {
            logger.error("unexpected item type " + Type.getTypeName(a.getType()));
            throw new RuntimeException("unexpected item type " + Type.getTypeName(a.getType()));
          }
      }
    } catch (XPathException e) {
      logger.error(e.getMessage());
      e.printStackTrace();
      return false;
    }
  }