public Object getExtendedContent() throws XMLDBException {
    if (file != null) return file;
    if (inputSource != null) return inputSource;

    DBBroker broker = null;
    BinaryDocument blob = null;
    InputStream rawDataStream = null;
    try {
      broker = pool.get(user);
      blob = (BinaryDocument) getDocument(broker, Lock.READ_LOCK);
      if (!blob.getPermissions().validate(user, Permission.READ))
        throw new XMLDBException(
            ErrorCodes.PERMISSION_DENIED, "Permission denied to read resource");

      rawDataStream = broker.getBinaryResource(blob);
    } catch (EXistException e) {
      throw new XMLDBException(
          ErrorCodes.VENDOR_ERROR, "error while loading binary resource " + getId(), e);
    } catch (IOException e) {
      throw new XMLDBException(
          ErrorCodes.VENDOR_ERROR, "error while loading binary resource " + getId(), e);
    } finally {
      if (blob != null) parent.getCollection().releaseDocument(blob, Lock.READ_LOCK);
      if (broker != null) pool.release(broker);
    }

    return rawDataStream;
  }
Esempio n. 2
0
  public void getEntryById(DBBroker broker, String path, String id, OutgoingMessage response)
      throws EXistException, BadRequestException {
    XQuery xquery = broker.getXQueryService();
    CompiledXQuery feedQuery = xquery.getXQueryPool().borrowCompiledXQuery(broker, entryByIdSource);

    XQueryContext context;
    if (feedQuery == null) {
      context = xquery.newContext(AccessContext.REST);
      try {
        feedQuery = xquery.compile(context, entryByIdSource);
      } catch (XPathException ex) {
        throw new EXistException("Cannot compile xquery " + entryByIdSource.getURL(), ex);
      } catch (IOException ex) {
        throw new EXistException(
            "I/O exception while compiling xquery " + entryByIdSource.getURL(), ex);
      }
    } else {
      context = feedQuery.getContext();
    }
    context.setStaticallyKnownDocuments(
        new XmldbURI[] {XmldbURI.create(path).append(AtomProtocol.FEED_DOCUMENT_NAME)});

    try {
      context.declareVariable("id", id);
      Sequence resultSequence = xquery.execute(feedQuery, null);
      if (resultSequence.isEmpty()) {
        throw new BadRequestException("No topic was found.");
      }
      String charset = getContext().getDefaultCharset();
      response.setContentType("application/atom+xml; charset=" + charset);
      Serializer serializer = broker.getSerializer();
      serializer.reset();
      try {
        Writer w = new OutputStreamWriter(response.getOutputStream(), charset);
        SAXSerializer sax =
            (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
        Properties outputProperties = new Properties();
        sax.setOutput(w, outputProperties);
        serializer.setProperties(outputProperties);
        serializer.setSAXHandlers(sax, sax);

        serializer.toSAX(resultSequence, 1, 1, false);

        SerializerPool.getInstance().returnObject(sax);
        w.flush();
        w.close();
      } catch (IOException ex) {
        LOG.fatal("Cannot read resource " + path, ex);
        throw new EXistException("I/O error on read of resource " + path, ex);
      } catch (SAXException saxe) {
        LOG.warn(saxe);
        throw new BadRequestException("Error while serializing XML: " + saxe.getMessage());
      }
      resultSequence.itemAt(0);
    } catch (XPathException ex) {
      throw new EXistException("Cannot execute xquery " + entryByIdSource.getURL(), ex);
    } finally {
      xquery.getXQueryPool().returnCompiledXQuery(entryByIdSource, feedQuery);
    }
  }
  private <R> R modifyCollection(
      DBBroker broker,
      XmldbURI collectionURI,
      DatabaseItemModifier<org.exist.collections.Collection, R> modifier)
      throws XMLDBException, LockException, PermissionDeniedException, IOException, EXistException,
          TriggerException, SyntaxException {
    final TransactionManager transact = broker.getBrokerPool().getTransactionManager();
    final Txn transaction = transact.beginTransaction();

    org.exist.collections.Collection coll = null;

    try {
      coll = broker.openCollection(collectionURI, Lock.WRITE_LOCK);
      if (coll == null) {
        throw new XMLDBException(
            ErrorCodes.INVALID_COLLECTION, "Collection " + collectionURI.toString() + " not found");
      }

      final R result = modifier.modify(coll);

      broker.saveCollection(transaction, coll);
      transact.commit(transaction);
      broker.flush();

      return result;

    } catch (final EXistException ee) {
      transact.abort(transaction);
      throw ee;
    } catch (final XMLDBException xmldbe) {
      transact.abort(transaction);
      throw xmldbe;
    } catch (final LockException le) {
      transact.abort(transaction);
      throw le;
    } catch (final PermissionDeniedException pde) {
      transact.abort(transaction);
      throw pde;
    } catch (final IOException ioe) {
      transact.abort(transaction);
      throw ioe;
    } catch (final TriggerException te) {
      transact.abort(transaction);
      throw te;
    } catch (final SyntaxException se) {
      transact.abort(transaction);
      throw se;
    } finally {
      transact.close(transaction);
      if (coll != null) {
        coll.release(Lock.WRITE_LOCK);
      }
    }
  }
  public void configure(DBBroker broker, Collection parent, Map parameters)
      throws CollectionConfigurationException {
    super.configure(broker, parent, parameters);
    String stylesheet = (String) parameters.get("src");
    if (stylesheet == null)
      throw new CollectionConfigurationException(
          "STXTransformerTrigger requires an " + "attribute 'src'");
    String origProperty = System.getProperty("javax.xml.transform.TransformerFactory");
    System.setProperty(
        "javax.xml.transform.TransformerFactory", "net.sf.joost.trax.TransformerFactoryImpl");
    factory = (SAXTransformerFactory) TransformerFactory.newInstance();
    // reset property to previous setting
    if (origProperty != null)
      System.setProperty("javax.xml.transform.TransformerFactory", origProperty);

    getLogger().debug("compiling stylesheet " + stylesheet);
    XmldbURI stylesheetUri = null;
    try {
      stylesheetUri = XmldbURI.xmldbUriFor(stylesheet);
    } catch (URISyntaxException e) {
    }
    // TODO: allow full XmldbURIs to be used as well.
    if (stylesheetUri == null || stylesheet.indexOf(':') == Constants.STRING_NOT_FOUND) {
      stylesheetUri = parent.getURI().resolveCollectionPath(stylesheetUri);
      DocumentImpl doc;
      try {
        doc = (DocumentImpl) broker.getXMLResource(stylesheetUri);
        if (doc == null)
          throw new CollectionConfigurationException(
              "stylesheet " + stylesheetUri + " not found in database");
        Serializer serializer = broker.getSerializer();
        TemplatesHandler thandler = factory.newTemplatesHandler();
        serializer.setSAXHandlers(thandler, null);
        serializer.toSAX(doc);
        template = thandler.getTemplates();
        handler = factory.newTransformerHandler(template);
      } catch (TransformerConfigurationException e) {
        throw new CollectionConfigurationException(e.getMessage(), e);
      } catch (PermissionDeniedException e) {
        throw new CollectionConfigurationException(e.getMessage(), e);
      } catch (SAXException e) {
        throw new CollectionConfigurationException(e.getMessage(), e);
      }
    } else
      try {
        template = factory.newTemplates(new StreamSource(stylesheet));
        handler = factory.newTransformerHandler(template);
      } catch (TransformerConfigurationException e) {
        throw new CollectionConfigurationException(e.getMessage(), e);
      }
  }
Esempio n. 5
0
  @BeforeClass
  public static void setUp() throws Exception {
    TransactionManager transact = null;
    Txn transaction = null;
    try {
      pool = startDB();
      broker = pool.get(pool.getSecurityManager().getSystemSubject());
      transact = pool.getTransactionManager();
      transaction = transact.beginTransaction();

      root =
          broker.getOrCreateCollection(
              transaction, XmldbURI.create(XmldbURI.ROOT_COLLECTION + "/test"));
      broker.saveCollection(transaction, root);

      String existHome = System.getProperty("exist.home");
      File existDir = existHome == null ? new File(".") : new File(existHome);
      String directory = "samples/shakespeare";
      File dir = new File(existDir, directory);

      // store some documents.
      for (File f : dir.listFiles(new XMLFilenameFilter())) {
        IndexInfo info =
            root.validateXMLResource(
                transaction,
                broker,
                XmldbURI.create(f.getName()),
                new InputSource(f.toURI().toASCIIString()));
        root.store(transaction, broker, info, new InputSource(f.toURI().toASCIIString()), false);
      }

      IndexInfo info =
          root.validateXMLResource(transaction, broker, XmldbURI.create("nested.xml"), NESTED_XML);
      root.store(transaction, broker, info, NESTED_XML, false);
      transact.commit(transaction);

      // for the tests
      docs = root.allDocs(broker, new DefaultDocumentSet(), true);
      seqSpeech = executeQuery(broker, "//SPEECH", 2628, null);

    } catch (Exception e) {
      if (pool != null) {
        pool.release(broker);
        BrokerPool.stopAll(false);
        pool = null;
        root = null;
      }
      throw e;
    }
  }
Esempio n. 6
0
  /**
   * Statically analyze a query for various properties.
   *
   * @param query the query to analyze
   * @param params parameters for the query; if necessary parameters are left out they will be
   *     listed as required variables in the analysis
   * @return a query analysis facet
   */
  public QueryAnalysis analyze(String query, Object... params) {
    if (presub) query = presub(query, params);

    long t1 = System.currentTimeMillis(), t2 = 0, t3 = 0;
    DBBroker broker = null;
    try {
      broker = db.acquireBroker();
      prepareContext(broker);
      final org.exist.source.Source source = buildQuerySource(query, params, "analyze");
      final XQuery xquery = broker.getXQueryService();
      final XQueryPool pool = xquery.getXQueryPool();
      CompiledXQuery compiledQuery = pool.borrowCompiledXQuery(broker, source);
      try {
        AnalysisXQueryContext context;
        if (compiledQuery == null) {
          context = new AnalysisXQueryContext(broker, AccessContext.INTERNAL_PREFIX_LOOKUP);
          buildXQueryStaticContext(context, false);
          buildXQueryDynamicContext(context, params, null, false);
          t2 = System.currentTimeMillis();
          compiledQuery = xquery.compile(context, source);
          t3 = System.currentTimeMillis();
        } else {
          context = (AnalysisXQueryContext) compiledQuery.getContext();
          t2 = System.currentTimeMillis();
        }
        return new QueryAnalysis(
            compiledQuery,
            Collections.unmodifiableSet(context.requiredVariables),
            Collections.unmodifiableSet(context.requiredFunctions));
      } finally {
        if (compiledQuery != null) pool.returnCompiledXQuery(source, compiledQuery);
      }
    } catch (XPathException e) {
      LOG.warn(
          "query compilation failed --  "
              + query
              + "  -- "
              + (params == null ? "" : " with params " + Arrays.asList(params))
              + (bindings.isEmpty() ? "" : " and bindings " + bindings));
      throw new DatabaseException("failed to compile query", e);
    } catch (IOException e) {
      throw new DatabaseException("unexpected exception", e);
    } catch (PermissionDeniedException e) {
      throw new DatabaseException("permission denied", e);
    } finally {
      db.releaseBroker(broker);
      STATS.update(query, t1, t2, t3, 0, System.currentTimeMillis());
    }
  }
  private <R> R modifyResource(
      DBBroker broker, Resource resource, DatabaseItemModifier<DocumentImpl, R> modifier)
      throws XMLDBException, LockException, PermissionDeniedException, EXistException,
          SyntaxException {
    final TransactionManager transact = broker.getBrokerPool().getTransactionManager();
    final Txn transaction = transact.beginTransaction();

    DocumentImpl document = null;
    try {
      document = ((AbstractEXistResource) resource).openDocument(broker, Lock.WRITE_LOCK);
      final SecurityManager sm = broker.getBrokerPool().getSecurityManager();
      if (!document.getPermissions().validate(user, Permission.WRITE)
          && !sm.hasAdminPrivileges(user)) {
        throw new XMLDBException(
            ErrorCodes.PERMISSION_DENIED,
            "you are not the owner of this resource; owner = "
                + document.getPermissions().getOwner());
      }

      final R result = modifier.modify(document);

      broker.storeXMLResource(transaction, document);
      transact.commit(transaction);

      return result;

    } catch (final EXistException ee) {
      transact.abort(transaction);
      throw ee;
    } catch (final XMLDBException xmldbe) {
      transact.abort(transaction);
      throw xmldbe;
    } catch (final LockException le) {
      transact.abort(transaction);
      throw le;
    } catch (final PermissionDeniedException pde) {
      transact.abort(transaction);
      throw pde;
    } catch (final SyntaxException se) {
      transact.abort(transaction);
      throw se;
    } finally {
      transact.close(transaction);
      if (document != null) {
        ((AbstractEXistResource) resource).closeDocument(document, Lock.WRITE_LOCK);
      }
    }
  }
Esempio n. 8
0
  /**
   * Parse the input source into a set of modifications.
   *
   * @param is
   * @return an array of type Modification
   * @throws ParserConfigurationException
   * @throws IOException
   * @throws SAXException
   */
  public Modification[] parse(InputSource is)
      throws ParserConfigurationException, IOException, SAXException {
    final XMLReader reader = broker.getBrokerPool().getParserPool().borrowXMLReader();
    try {
      reader.setProperty(Namespaces.SAX_LEXICAL_HANDLER, this);
      reader.setFeature(Namespaces.SAX_NAMESPACES, true);
      reader.setFeature(Namespaces.SAX_NAMESPACES_PREFIXES, false);
      reader.setContentHandler(this);

      reader.parse(is);
      final Modification mods[] = new Modification[modifications.size()];
      return modifications.toArray(mods);
    } finally {
      broker.getBrokerPool().getParserPool().returnXMLReader(reader);
    }
  }
Esempio n. 9
0
 private void wipeDatabase() {
   DBBroker broker = null;
   Transaction tx = Database.requireTransaction();
   try {
     broker = db.acquireBroker();
     broker.removeCollection(tx.tx, broker.getCollection(XmldbURI.ROOT_COLLECTION_URI));
     tx.commit();
   } catch (PermissionDeniedException e) {
     throw new RuntimeException(e);
   } catch (IOException e) {
     throw new RuntimeException(e);
   } finally {
     tx.abortIfIncomplete();
     db.releaseBroker(broker);
   }
 }
Esempio n. 10
0
  @AfterClass
  public static void tearDown() {

    TransactionManager transact = null;
    Txn transaction = null;
    try {
      transact = pool.getTransactionManager();
      transaction = transact.beginTransaction();
      root =
          broker.getOrCreateCollection(
              transaction, XmldbURI.create(XmldbURI.ROOT_COLLECTION + "/test"));
      //          broker.removeCollection(transaction, root);

      transact.commit(transaction);
    } catch (Exception e) {
      if (transaction != null) {
        transact.abort(transaction);
      }
    } finally {
      if (pool != null) pool.release(broker);
    }
    BrokerPool.stopAll(false);
    pool = null;
    root = null;
  }
Esempio n. 11
0
 public FTIndexWorker(FTIndex index, DBBroker broker) throws DatabaseConfigurationException {
   this.index = index;
   try {
     this.engine = new NativeTextEngine(broker, index.getBFile(), broker.getConfiguration());
   } catch (DBException e) {
     throw new DatabaseConfigurationException(e.getMessage(), e);
   }
 }
Esempio n. 12
0
  /**
   * Create a {@link Source} object for the given URL.
   *
   * <p>As a special case, if the URL starts with "resource:", the resource will be read from the
   * current context class loader.
   *
   * @param broker broker, can be null if not asking for a database resource
   * @param contextPath
   * @param location
   * @throws MalformedURLException
   * @throws IOException
   */
  public static final Source getSource(
      DBBroker broker, String contextPath, String location, boolean checkXQEncoding)
      throws MalformedURLException, IOException, PermissionDeniedException {
    Source source = null;

    /* file:// or location without scheme is assumed to be a file */
    if (location.startsWith("file:") || location.indexOf(':') == Constants.STRING_NOT_FOUND) {
      location = location.replaceAll("^(file:)?/*(.*)$", "$2");

      File f = new File(contextPath + File.separatorChar + location);
      if (!f.canRead()) {
        File f2 = new File(location);
        if (!f2.canRead()) {
          throw new FileNotFoundException(
              "cannot read module source from file at "
                  + location
                  + ". Tried "
                  + f.getAbsolutePath()
                  + " and "
                  + f2.getAbsolutePath());
        } else {
          f = f2;
        }
      }
      location = f.toURI().toASCIIString();
      source = new FileSource(f, "UTF-8", checkXQEncoding);
    }

    /* xmldb: */
    else if (location.startsWith(XmldbURI.XMLDB_URI_PREFIX)) {
      DocumentImpl resource = null;
      try {
        XmldbURI pathUri = XmldbURI.create(location);
        resource = broker.getXMLResource(pathUri, Lock.READ_LOCK);
        source = new DBSource(broker, (BinaryDocument) resource, true);
      } finally {
        // TODO: this is nasty!!! as we are unlocking the resource whilst there
        // is still a source
        if (resource != null) resource.getUpdateLock().release(Lock.READ_LOCK);
      }
    }

    /* resource: */
    else if (location.startsWith(ClassLoaderSource.PROTOCOL)) {
      source = new ClassLoaderSource(location);
    }

    /* any other URL */
    else {
      URL url = new URL(location);
      source = new URLSource(url);
    }

    return source;
  }
Esempio n. 13
0
  private Sequence processQuery(String select) throws SAXException {
    XQueryContext context = null;
    try {
      context = new XQueryContext(broker.getBrokerPool(), accessCtx);
      context.setStaticallyKnownDocuments(documentSet);
      Map.Entry<String, String> namespaceEntry;
      for (final Iterator<Map.Entry<String, String>> i = namespaces.entrySet().iterator();
          i.hasNext(); ) {
        namespaceEntry = (Map.Entry<String, String>) i.next();
        context.declareNamespace(namespaceEntry.getKey(), namespaceEntry.getValue());
      }
      Map.Entry<String, Object> entry;
      for (final Iterator<Map.Entry<String, Object>> i = variables.entrySet().iterator();
          i.hasNext(); ) {
        entry = (Map.Entry<String, Object>) i.next();
        context.declareVariable(entry.getKey().toString(), entry.getValue());
      }
      // TODO(pkaminsk2): why replicate XQuery.compile here?
      final XQueryLexer lexer = new XQueryLexer(context, new StringReader(select));
      final XQueryParser parser = new XQueryParser(lexer);
      final XQueryTreeParser treeParser = new XQueryTreeParser(context);
      parser.xpath();
      if (parser.foundErrors()) {
        throw new SAXException(parser.getErrorMessage());
      }

      final AST ast = parser.getAST();

      if (LOG.isDebugEnabled()) {
        LOG.debug("generated AST: " + ast.toStringTree());
      }

      final PathExpr expr = new PathExpr(context);
      treeParser.xpath(ast, expr);
      if (treeParser.foundErrors()) {
        throw new SAXException(treeParser.getErrorMessage());
      }
      expr.analyze(new AnalyzeContextInfo());
      final Sequence seq = expr.eval(null, null);
      return seq;
    } catch (final RecognitionException e) {
      LOG.warn("error while creating variable", e);
      throw new SAXException(e);
    } catch (final TokenStreamException e) {
      LOG.warn("error while creating variable", e);
      throw new SAXException(e);
    } catch (final XPathException e) {
      throw new SAXException(e);
    } finally {
      if (context != null) {
        context.reset(false);
      }
    }
  }
Esempio n. 14
0
  private static String serialize(DBBroker broker, Item item) throws SAXException, XPathException {
    Serializer serializer = broker.getSerializer();

    serializer.reset();
    String value;
    if (Type.subTypeOf(item.getType(), Type.NODE)) {
      value = serializer.serialize((NodeValue) item);
    } else {
      value = item.getStringValue();
    }
    return value;
  }
Esempio n. 15
0
  @Test
  public void childSelector() throws XPathException {
    NodeSelector selector = new ChildSelector(seqSpeech.toNodeSet(), -1);
    NameTest test = new NameTest(Type.ELEMENT, new QName("LINE", ""));
    NodeSet set =
        broker
            .getStructuralIndex()
            .findElementsByTagName(
                ElementValue.ELEMENT, seqSpeech.getDocumentSet(), test.getName(), selector);

    assertEquals(9492, set.getLength());
  }
Esempio n. 16
0
  @Test
  public void ancestorSelector() throws XPathException {
    NodeSelector selector = new AncestorSelector(seqSpeech.toNodeSet(), -1, false, true);
    NameTest test = new NameTest(Type.ELEMENT, new QName("ACT", ""));
    NodeSet set =
        broker
            .getStructuralIndex()
            .findElementsByTagName(
                ElementValue.ELEMENT, seqSpeech.getDocumentSet(), test.getName(), selector);

    assertEquals(15, set.getLength());
  }
Esempio n. 17
0
  @Test
  public void descendantOrSelfSelector() throws XPathException {
    NodeSelector selector = new DescendantOrSelfSelector(seqSpeech.toNodeSet(), -1);
    NameTest test = new NameTest(Type.ELEMENT, new QName("SPEECH", ""));
    NodeSet set =
        broker
            .getStructuralIndex()
            .findElementsByTagName(
                ElementValue.ELEMENT, seqSpeech.getDocumentSet(), test.getName(), selector);

    assertEquals(2628, set.getLength());
  }
Esempio n. 18
0
  @Test
  public void descendantSelector() throws XPathException, SAXException, PermissionDeniedException {
    Sequence seq = executeQuery(broker, "//SCENE", 72, null);
    NameTest test = new NameTest(Type.ELEMENT, new QName("SPEAKER", ""));
    NodeSelector selector = new DescendantSelector(seq.toNodeSet(), -1);
    NodeSet set =
        broker
            .getStructuralIndex()
            .findElementsByTagName(
                ElementValue.ELEMENT, seq.getDocumentSet(), test.getName(), selector);

    assertEquals(2639, set.getLength());
  }
Esempio n. 19
0
  @Test
  public void extArrayNodeSet_selectParentChild_3()
      throws XPathException, SAXException, PermissionDeniedException {
    Sequence nestedSet = executeQuery(broker, "//section[@n = ('1.1', '1.1.1', '1.2')]", 3, null);
    NameTest test = new NameTest(Type.ELEMENT, new QName("para", ""));
    NodeSet children =
        broker
            .getStructuralIndex()
            .findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null);

    NodeSet result = children.selectParentChild(nestedSet.toNodeSet(), NodeSet.DESCENDANT);
    assertEquals(4, result.getLength());
  }
Esempio n. 20
0
  @Test
  public void selectAncestors() throws XPathException, SAXException, PermissionDeniedException {
    NameTest test = new NameTest(Type.ELEMENT, new QName("SCENE", ""));
    NodeSet scenes =
        broker
            .getStructuralIndex()
            .findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null);
    Sequence largeSet =
        executeQuery(broker, "//SPEECH/LINE[fn:contains(., 'love')]/ancestor::SPEECH", 187, null);

    NodeSet result = ((AbstractNodeSet) scenes).selectAncestors(largeSet.toNodeSet(), false, -1);
    assertEquals(49, result.getLength());
  }
  public InputStream getStreamContent() throws XMLDBException {
    InputStream retval = null;
    if (file != null) {
      try {
        retval = new FileInputStream(file);
      } catch (FileNotFoundException fnfe) {
        // Cannot fire it :-(
        throw new XMLDBException(ErrorCodes.VENDOR_ERROR, fnfe.getMessage(), fnfe);
      }
    } else if (inputSource != null) {
      retval = inputSource.getByteStream();
    } else if (rawData != null) {
      retval = new ByteArrayInputStream(rawData);
    } else {
      DBBroker broker = null;
      BinaryDocument blob = null;
      try {
        broker = pool.get(user);
        blob = (BinaryDocument) getDocument(broker, Lock.READ_LOCK);
        if (!blob.getPermissions().validate(user, Permission.READ))
          throw new XMLDBException(
              ErrorCodes.PERMISSION_DENIED, "Permission denied to read resource");

        retval = broker.getBinaryResource(blob);
      } catch (EXistException e) {
        throw new XMLDBException(
            ErrorCodes.VENDOR_ERROR, "error while loading binary resource " + getId(), e);
      } catch (IOException e) {
        throw new XMLDBException(
            ErrorCodes.VENDOR_ERROR, "error while loading binary resource " + getId(), e);
      } finally {
        if (blob != null) parent.getCollection().releaseDocument(blob, Lock.READ_LOCK);
        if (broker != null) pool.release(broker);
      }
    }

    return retval;
  }
Esempio n. 22
0
  private static Sequence executeQuery(
      DBBroker broker, String query, int expected, String expectedResult)
      throws XPathException, SAXException, PermissionDeniedException {
    XQuery xquery = broker.getXQueryService();
    Sequence seq = xquery.execute(query, null, AccessContext.TEST);
    assertEquals(expected, seq.getItemCount());

    if (expectedResult != null) {
      Item item = seq.itemAt(0);
      String value = serialize(broker, item);
      assertEquals(expectedResult, value);
    }
    return seq;
  }
Esempio n. 23
0
  @Test
  public void selectParentChild_2() throws XPathException, SAXException, PermissionDeniedException {
    NameTest test = new NameTest(Type.ELEMENT, new QName("SPEAKER", ""));
    NodeSet speakers =
        broker
            .getStructuralIndex()
            .findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null);
    Sequence largeSet =
        executeQuery(broker, "//SPEECH/LINE[fn:contains(., 'love')]/ancestor::SPEECH", 187, null);

    NodeSet result =
        NodeSetHelper.selectParentChild(speakers, largeSet.toNodeSet(), NodeSet.DESCENDANT, -1);
    assertEquals(187, result.getLength());
  }
Esempio n. 24
0
 public static void addToList(DBBroker broker, byte[] data, int start, int len, AttrList list) {
   int pos = start;
   byte idSizeType = (byte) (data[pos] & 0x3);
   boolean hasNamespace = (data[pos] & 0x10) == 0x10;
   int attrType = (data[pos] & 0x4) >> 0x2;
   pos += StoredNode.LENGTH_SIGNATURE_LENGTH;
   int dlnLen = ByteConversion.byteToShort(data, pos);
   pos += NodeId.LENGTH_NODE_ID_UNITS;
   NodeId dln = broker.getBrokerPool().getNodeFactory().createFromData(dlnLen, data, pos);
   pos += dln.size();
   short id = (short) Signatures.read(idSizeType, data, pos);
   pos += Signatures.getLength(idSizeType);
   String name = broker.getSymbols().getName(id);
   if (name == null) throw new RuntimeException("no symbol for id " + id);
   short nsId = 0;
   String prefix = null;
   if (hasNamespace) {
     nsId = ByteConversion.byteToShort(data, pos);
     pos += LENGTH_NS_ID;
     int prefixLen = ByteConversion.byteToShort(data, pos);
     pos += LENGTH_PREFIX_LENGTH;
     if (prefixLen > 0) prefix = UTF8.decode(data, pos, prefixLen).toString();
     pos += prefixLen;
   }
   String namespace = nsId == 0 ? "" : broker.getSymbols().getNamespace(nsId);
   String value;
   try {
     value = new String(data, pos, len - (pos - start), "UTF-8");
   } catch (UnsupportedEncodingException uee) {
     LOG.warn(uee);
     value = new String(data, pos, len - (pos - start));
   }
   list.addAttribute(
       broker.getSymbols().getQName(Node.ATTRIBUTE_NODE, namespace, name, prefix),
       value,
       attrType);
 }
  public void getContentIntoAStream(OutputStream os) throws XMLDBException {
    DBBroker broker = null;
    BinaryDocument blob = null;
    boolean doClose = false;
    try {
      broker = pool.get(user);
      blob = (BinaryDocument) getDocument(broker, Lock.READ_LOCK);
      if (!blob.getPermissions().validate(user, Permission.READ))
        throw new XMLDBException(
            ErrorCodes.PERMISSION_DENIED, "Permission denied to read resource");

      // Improving the performance a bit for files!
      if (os instanceof FileOutputStream) {
        os = new BufferedOutputStream(os, 655360);
        doClose = true;
      }

      broker.readBinaryResource(blob, os);
    } catch (EXistException e) {
      throw new XMLDBException(
          ErrorCodes.VENDOR_ERROR, "error while loading binary resource " + getId(), e);
    } catch (IOException ioe) {
      throw new XMLDBException(
          ErrorCodes.VENDOR_ERROR, "error while loading binary resource " + getId(), ioe);
    } finally {
      if (blob != null) parent.getCollection().releaseDocument(blob, Lock.READ_LOCK);
      if (broker != null) pool.release(broker);
      if (doClose) {
        try {
          os.close();
        } catch (IOException ioe) {
          // IgnoreIT(R)
        }
      }
    }
  }
Esempio n. 26
0
  @Test
  public void selectAncestorDescendant()
      throws XPathException, SAXException, PermissionDeniedException {
    NameTest test = new NameTest(Type.ELEMENT, new QName("SPEAKER", ""));
    NodeSet speakers =
        broker
            .getStructuralIndex()
            .findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null);
    Sequence outerSet =
        executeQuery(broker, "//SCENE/TITLE[fn:contains(., 'closet')]/ancestor::SCENE", 1, null);

    NodeSet result =
        speakers.selectAncestorDescendant(
            outerSet.toNodeSet(), NodeSet.DESCENDANT, false, -1, true);
    assertEquals(56, result.getLength());
  }
Esempio n. 27
0
  @Test
  public void selectParentChild() throws XPathException, SAXException, PermissionDeniedException {

    NameTest test = new NameTest(Type.ELEMENT, new QName("SPEAKER", ""));
    NodeSet speakers =
        broker
            .getStructuralIndex()
            .findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null);
    Sequence smallSet =
        executeQuery(
            broker, "//SPEECH/LINE[fn:contains(., 'perturbed spirit')]/ancestor::SPEECH", 1, null);

    NodeSet result =
        NodeSetHelper.selectParentChild(speakers, smallSet.toNodeSet(), NodeSet.DESCENDANT, -1);
    assertEquals(1, result.getLength());
    String value = serialize(broker, result.itemAt(0));
    assertEquals(value, "<SPEAKER>HAMLET</SPEAKER>");
  }
Esempio n. 28
0
  @Test
  public void nodeProxy_getParents()
      throws XPathException, SAXException, PermissionDeniedException {
    Sequence smallSet =
        executeQuery(
            broker, "//SPEECH/LINE[fn:contains(., 'perturbed spirit')]/ancestor::SPEECH", 1, null);

    NodeProxy proxy = (NodeProxy) smallSet.itemAt(0);

    NodeSet result = proxy.getParents(-1);
    assertEquals(1, result.getLength());

    NameTest test = new NameTest(Type.ELEMENT, new QName("SPEAKER", ""));
    NodeSet speakers =
        broker
            .getStructuralIndex()
            .findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null);

    result = speakers.selectParentChild(proxy, NodeSet.DESCENDANT, -1);
    assertEquals(1, result.getLength());
  }
  private <R> R readCollection(
      DBBroker broker,
      XmldbURI collectionURI,
      DatabaseItemReader<org.exist.collections.Collection, R> reader)
      throws XMLDBException, PermissionDeniedException {
    org.exist.collections.Collection coll = null;

    try {
      coll = broker.openCollection(collectionURI, Lock.READ_LOCK);
      if (coll == null) {
        throw new XMLDBException(
            ErrorCodes.INVALID_COLLECTION, "Collection " + collectionURI.toString() + " not found");
      }

      return reader.read(coll);

    } finally {
      if (coll != null) {
        coll.release(Lock.READ_LOCK);
      }
    }
  }
Esempio n. 30
0
 /** Constructor for XUpdateProcessor. */
 public XUpdateProcessor(DBBroker broker, DocumentSet docs, AccessContext accessCtx)
     throws ParserConfigurationException {
   if (accessCtx == null) {
     throw new NullAccessContextException();
   }
   this.accessCtx = accessCtx;
   final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   factory.setNamespaceAware(true);
   factory.setValidating(false);
   this.builder = factory.newDocumentBuilder();
   this.broker = broker;
   this.documentSet = docs;
   // namespaces.put("xml", Namespaces.XML_NS);
   // TODO : move this to a dedicated configure() method.
   if (broker != null) {
     final Configuration config = broker.getConfiguration();
     Boolean temp;
     if ((temp = (Boolean) config.getProperty("indexer.preserve-whitespace-mixed-content"))
         != null) {
       preserveWhitespaceTemp = temp.booleanValue();
     }
   }
 }