Exemplo n.º 1
0
  /** arguments: lines , columns, XQuery string */
  public static void main(String[] args) {
    String xquery = "";
    int lines = 20;
    int columns = 20;
    if (args.length >= 2) {
      lines = Integer.parseInt(args[0]);
      columns = Integer.parseInt(args[1]);
    }
    if (args.length == 3) {
      xquery = args[2];
    }
    if (args.length < 2) {
      System.out.println("Taking default values");
    }

    SAXStorageTest tester = new SAXStorageTest(null);
    tester.setUp();
    XMLReader dataSource = new TabularXMLReader(lines, columns);
    tester.storeSAXEvents(dataSource);
    System.out.println("Stored tabular data, " + lines + " lines, " + columns + " columns");

    try {
      if (xquery != "") {
        ResourceSet result = tester.querySingleLine(xquery, "testQueryBigDocument");
        System.out.println("result size: " + result.getSize());
      }
      shutdown(tester.root);
    } catch (XMLDBException e) {
      fail(e.getMessage());
    }
  }
Exemplo n.º 2
0
 private String execQuery(String query) throws XMLDBException {
   XQueryService service = (XQueryService) testCollection.getService("XQueryService", "1.0");
   service.setProperty("indent", "no");
   ResourceSet result = service.query(query);
   assertEquals(result.getSize(), 1);
   return result.getResource(0).getContent().toString();
 }
Exemplo n.º 3
0
  private void fetchDb() throws Exception {
    XPathQueryService xquery = (XPathQueryService) testCol.getService("XPathQueryService", "1.0");
    ResourceSet result =
        xquery.query(
            "for $n in collection('"
                + XmldbURI.ROOT_COLLECTION
                + "/test')//* return local-name($n)");

    for (int i = 0; i < result.getSize(); i++) {
      Resource r = result.getResource(i);
      String tag = r.getContent().toString();
      System.out.println("Retrieving " + tag);

      ResourceSet result2 = xquery.query("//" + tag);
      assertEquals(result2.getSize(), 1);

      System.out.println(result2.getResource(0).getContent());
    }
  }
Exemplo n.º 4
0
 /**
  * Store in the new way: the XMLResource stores just a File object before storeResource() stores
  * the SAX events in the database.
  *
  * @throws XMLDBException
  */
 public void testQueryBigDocument() {
   try {
     XMLReader dataSource = new TabularXMLReader();
     storeSAXEvents(dataSource);
     ResourceSet result = querySingleLine("", "testQueryBigDocument");
     assertEquals(1, result.getSize());
   } catch (XMLDBException e) {
     fail(e.getMessage());
   }
 }
Exemplo n.º 5
0
  private void executeAndEvaluate(String query, String expectedValue) {

    LOG.info("Query=" + query);
    LOG.info("ExpectedValue=" + query);

    try {
      ResourceSet results = executeQuery(query);
      assertEquals(1, results.getSize());

      String r = (String) results.getResource(0).getContent();
      LOG.info(r);

      assertXpathEvaluatesTo(expectedValue, "//status/text()", r);

    } catch (Exception ex) {
      LOG.error(ex);
      fail(ex.getMessage());
    }
  }
Exemplo n.º 6
0
  private void insertTags() throws Exception {
    XUpdateQueryService service =
        (XUpdateQueryService) testCol.getService("XUpdateQueryService", "1.0");
    XPathQueryService xquery = (XPathQueryService) testCol.getService("XPathQueryService", "1.0");

    String[] tagsWritten = new String[RUNS];
    for (int i = 0; i < RUNS; i++) {
      String tag = tags[i];
      String parent;
      if (i > 0 && rand.nextInt(100) < 70) {
        parent = "//" + tagsWritten[rand.nextInt(i) / 2];
      } else parent = "/root";
      String xupdate =
          "<xupdate:modifications version=\"1.0\" xmlns:xupdate=\"http://www.xmldb.org/xupdate\">"
              + "<xupdate:append select=\""
              + parent
              + "\">"
              + "<xupdate:element name=\""
              + tag
              + "\"/>"
              + "</xupdate:append>"
              + "</xupdate:modifications>";

      long mods = service.updateResource("test.xml", xupdate);
      System.out.println("Inserted " + tag + ": " + mods + " ; parent = " + parent);
      assertEquals(mods, 1);

      tagsWritten[i] = tag;
      String query = "//" + tagsWritten[rand.nextInt(i + 1)];
      ResourceSet result = xquery.query(query);
      assertEquals(result.getSize(), 1);

      System.out.println(result.getResource(0).getContent());
    }

    XMLResource res = (XMLResource) testCol.getResource("test.xml");
    assertNotNull(res);
    System.out.println(res.getContent());
  }
Exemplo n.º 7
0
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (request.getCharacterEncoding() == null)
      try {
        request.setCharacterEncoding("UTF-8");
      } catch (final IllegalStateException e) {
      }
    // Try to find the XQuery
    final String qpath = getServletContext().getRealPath(query);
    final File f = new File(qpath);
    if (!(f.canRead() && f.isFile())) {
      throw new ServletException("Cannot read XQuery source from " + f.getAbsolutePath());
    }
    final FileSource source = new FileSource(f, "UTF-8", true);

    try {
      // Prepare and execute the XQuery
      final Collection collection =
          DatabaseManager.getCollection(collectionURI.toString(), user, password);
      final XQueryService service = (XQueryService) collection.getService("XQueryService", "1.0");
      if (!((CollectionImpl) collection).isRemoteCollection()) {
        service.declareVariable(
            RequestModule.PREFIX + ":request", new HttpRequestWrapper(request, "UTF-8", "UTF-8"));
        service.declareVariable(
            ResponseModule.PREFIX + ":response", new HttpResponseWrapper(response));
        service.declareVariable(
            SessionModule.PREFIX + ":session", new HttpSessionWrapper(request.getSession(false)));
      }
      final ResourceSet result = service.execute(source);

      String redirectTo = null;
      String servletName = null;
      String path = null;
      RequestWrapper modifiedRequest = null;
      // parse the query result element
      if (result.getSize() == 1) {
        final XMLResource resource = (XMLResource) result.getResource(0);
        Node node = resource.getContentAsDOM();
        if (node.getNodeType() == Node.DOCUMENT_NODE) {
          node = ((Document) node).getDocumentElement();
        }
        if (node.getNodeType() != Node.ELEMENT_NODE) {
          response.sendError(
              HttpServletResponse.SC_BAD_REQUEST,
              "Redirect XQuery should return an XML element. Received: " + resource.getContent());
          return;
        }
        Element elem = (Element) node;
        if (!(Namespaces.EXIST_NS.equals(elem.getNamespaceURI())
            && "dispatch".equals(elem.getLocalName()))) {
          response.sendError(
              HttpServletResponse.SC_BAD_REQUEST,
              "Redirect XQuery should return an element <exist:dispatch>. Received: "
                  + resource.getContent());
          return;
        }
        if (elem.hasAttribute("path")) {
          path = elem.getAttribute("path");
        } else if (elem.hasAttribute("servlet-name")) {
          servletName = elem.getAttribute("servlet-name");
        } else if (elem.hasAttribute("redirect")) {
          redirectTo = elem.getAttribute("redirect");
        } else {
          response.sendError(
              HttpServletResponse.SC_BAD_REQUEST,
              "Element <exist:dispatch> should either provide an attribute 'path' or 'servlet-name'. Received: "
                  + resource.getContent());
          return;
        }

        // Check for add-parameter elements etc.
        if (elem.hasChildNodes()) {
          node = elem.getFirstChild();
          while (node != null) {
            if (node.getNodeType() == Node.ELEMENT_NODE
                && Namespaces.EXIST_NS.equals(node.getNamespaceURI())) {
              elem = (Element) node;
              if ("add-parameter".equals(elem.getLocalName())) {
                if (modifiedRequest == null) {
                  modifiedRequest = new RequestWrapper(request);
                }
                modifiedRequest.addParameter(elem.getAttribute("name"), elem.getAttribute("value"));
              }
            }
            node = node.getNextSibling();
          }
        }
      }

      if (redirectTo != null) {
        // directly redirect to the specified URI
        response.sendRedirect(redirectTo);
        return;
      }

      // Get a RequestDispatcher, either from the servlet context or the request
      RequestDispatcher dispatcher;
      if (servletName != null && servletName.length() > 0) {
        dispatcher = getServletContext().getNamedDispatcher(servletName);
      } else {
        LOG.debug("Dispatching to " + path);
        dispatcher = getServletContext().getRequestDispatcher(path);
        if (dispatcher == null) {
          dispatcher = request.getRequestDispatcher(path);
        }
      }
      if (dispatcher == null) {
        response.sendError(
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
            "Could not create a request dispatcher. Giving up.");
        return;
      }

      if (modifiedRequest != null) {
        request = modifiedRequest;
      }
      // store the original request URI to org.exist.forward.request-uri
      request.setAttribute("org.exist.forward.request-uri", request.getRequestURI());
      request.setAttribute("org.exist.forward.servlet-path", request.getServletPath());

      // finally, execute the forward
      dispatcher.forward(request, response);
    } catch (final XMLDBException e) {
      throw new ServletException(
          "An error occurred while initializing RedirectorServlet: " + e.getMessage(), e);
    }
  }
  public final void testXPathQueryServiceSuccess() throws Exception {

    XPathQueryService s = (XPathQueryService) this.getService("XPathQueryService");

    ResourceSet rs1 = s.query("//author/@id");
    assertTrue("Expected a non empty ResourceSet.", rs1.getSize() > 0);

    ResourceSet rs2 = s.query("//foo/@bar");
    assertTrue("Expected a non empty ResourceSet.", rs2.getSize() > 0);

    int id1[] = new int[(int) rs1.getSize()];
    for (int i = 0; i < id1.length; i++) {
      Resource res = rs1.getResource(i);
      assertTrue(
          "Expected instance of VirtualResource and not " + res.getClass(),
          res instanceof VirtualResource);

      Document doc = (Document) ((VirtualResource) res).getContentAsDOM();
      Element elem = doc.getDocumentElement();

      assertEquals(
          "Expected " + NEXDEngineI.QNAME_QUERY_RESULT + " but it is " + elem.getTagName(),
          NEXDEngineI.QNAME_QUERY_RESULT,
          elem.getTagName());

      NamedNodeMap nnm = elem.getAttributes();

      String value = elem.getAttribute("id");
      id1[i] = Integer.parseInt(value);
    }

    int id2[] = new int[(int) rs2.getSize()];
    for (int i = 0; i < id2.length; i++) {
      Resource res = rs2.getResource(i);
      assertTrue(
          "Expected instance of VirtualResource and not " + res.getClass(),
          res instanceof VirtualResource);

      Document doc = (Document) ((VirtualResource) res).getContentAsDOM();
      Element elem = doc.getDocumentElement();

      assertEquals(
          "Expected " + NEXDEngineI.QNAME_QUERY_RESULT + " but it is " + elem.getTagName(),
          NEXDEngineI.QNAME_QUERY_RESULT,
          elem.getTagName());

      String value = elem.getAttribute("bar");
      id2[i] = Integer.parseInt(value);
    }

    for (int i = 0; i < id1.length; i++) {
      int id = id1[i];

      boolean in1 = false;

      for (int j = 0; j < id2.length; j++) {

        if (id == id2[j]) {
          in1 = true;
        }

        boolean in2 = false;
        for (int k = 0; k < id1.length; k++) {
          if (id2[j] == id1[k]) {
            in2 = true;
          }
        }
        assertTrue("Expected id=" + id2[j] + " is in the first array.", in2);
      }
      assertTrue("Expected id=" + id + " is in the second array.", in1);
    }
  }