/**
   * Test sending of HTTP GET requests.
   *
   * @throws Exception exception
   */
  @Test
  public void testPOSTGet() throws Exception {
    // GET1 - just send a GET request
    final Command get1 =
        new XQuery(
            "http:send-request("
                + "<http:request method='get' "
                + "href='http://localhost:8984/basex/jax-rx/books'/>)");
    get1.execute(context);
    checkResponse(get1, HttpURLConnection.HTTP_OK, 2);
    assertTrue(((ItemIter) get1.result()).item[1].type == Type.DOC);

    // GET2 - with override-media-type='text/plain'
    final Command get2 =
        new XQuery(
            "http:send-request("
                + "<http:request method='get' override-media-type='text/plain'/>,"
                + "'http://localhost:8984/basex/jax-rx/books')");
    get2.execute(context);
    checkResponse(get2, HttpURLConnection.HTTP_OK, 2);
    assertTrue(((ItemIter) get2.result()).item[1].type == Type.STR);

    // Get3 - with status-only='true'
    final Command get3 =
        new XQuery(
            "http:send-request("
                + "<http:request method='get' status-only='true'/>,"
                + "'http://localhost:8984/basex/jax-rx/books')");
    get3.execute(context);
    checkResponse(get3, HttpURLConnection.HTTP_OK, 1);
  }
Exemple #2
0
 /**
  * Queries empty content.
  *
  * @throws IOException I/O exception
  */
 @Test
 public void queryEmptyString() throws IOException {
   final Query q = session.query("'',1");
   assertTrue(q.more());
   assertEqual("", q.next());
   assertTrue(q.more());
   assertEqual("1", q.next());
   assertNull(q.next());
 }
 /**
  * Checks the response to an HTTP request.
  *
  * @param c command
  * @param expStatus expected status
  * @param itemsCount expected number of items
  * @throws QueryException query exception
  */
 private void checkResponse(final Command c, final int expStatus, final int itemsCount)
     throws QueryException {
   assertTrue(c.result() instanceof ItemIter);
   final ItemIter res = (ItemIter) c.result();
   assertEquals(itemsCount, res.size());
   assertTrue(res.item[0] instanceof FElem);
   final FElem response = (FElem) res.item[0];
   assertNotNull(response.attr());
   final NodeIter resAttr = response.attr();
   Nod attr = null;
   while ((attr = resAttr.next()) != null) {
     if (Token.eq(attr.nname(), STATUS)) assertTrue(eq(attr.atom(), token(expStatus)));
   }
 }
Exemple #4
0
 /** Command test. */
 @Test
 public final void replace() {
   // query to count number of documents
   final String count = "count(db:open('" + NAME + "'))";
   // database must be opened to replace resources
   no(new Replace(FILE, "xxx"));
   ok(new CreateDB(NAME, FILE));
   assertEquals("1", ok(new XQuery(count)));
   // replace existing document
   ok(new Replace(FN, "<a/>"));
   assertEquals("1", ok(new XQuery(count)));
   // replace existing document (again)
   ok(new Replace(FN, "<a/>"));
   assertEquals("1", ok(new XQuery(count)));
   // invalid content
   no(new Replace(FN, ""));
   assertEquals("1", ok(new XQuery(count)));
   // create and replace binary file
   ok(new XQuery("db:store('" + NAME + "', 'a', 'a')"));
   ok(new Replace("a", "<b/>"));
   assertTrue(ok(new XQuery("db:open('" + NAME + "')")).length() != 0);
   ok(new XQuery("db:retrieve('" + NAME + "', 'a')"));
   // a failing replace should not remove existing documents
   no(new Replace(FN, "<a>"));
   assertEquals("1", ok(new XQuery(count)));
 }
Exemple #5
0
  /**
   * Checks the contents of the specified zip entry.
   *
   * @param file file to be checked
   * @param data expected file contents
   * @throws IOException I/O exception
   */
  private static void checkEntry(final String file, final byte[] data) throws IOException {

    ZipFile zf = null;
    try {
      zf = new ZipFile(TMPZIP);
      final ZipEntry ze = zf.getEntry(file);
      assertNotNull("File not found: " + file, ze);
      final DataInputStream is = new DataInputStream(zf.getInputStream(ze));
      final byte[] dt = new byte[(int) ze.getSize()];
      is.readFully(dt);
      assertTrue(
          "Wrong contents in file \""
              + file
              + "\":"
              + Prop.NL
              + "Expected: "
              + string(data)
              + Prop.NL
              + "Found: "
              + string(dt),
          eq(data, dt));
    } finally {
      if (zf != null) zf.close();
    }
  }
Exemple #6
0
  /**
   * Runs a query and checks the updating flag.
   *
   * @throws IOException I/O exception
   */
  @Test
  public void queryUpdating() throws IOException {
    // test non-updating query
    Query query = session.query("12345678");
    assertFalse(query.updating());
    assertEqual("12345678", query.execute());
    assertFalse(query.updating());
    query.close();

    // test updating query
    query = session.query("insert node <a/> into <b/>");
    assertTrue(query.updating());
    assertEqual("", query.execute());
    assertTrue(query.updating());
    query.close();
  }
Exemple #7
0
 /**
  * Test sending of HTTP request without any attributes - error shall be thrown that mandatory
  * attributes are missing.
  */
 @Test
 public void sendEmptyReq() {
   try {
     new XQuery(_HTTP_SEND_REQUEST.args("<http:request/>")).execute(ctx);
   } catch (final BaseXException ex) {
     assertTrue(ex.getMessage().contains(ErrType.HC.toString()));
   }
 }
Exemple #8
0
 /**
  * Runs a query with additional serialization parameters.
  *
  * @throws IOException I/O exception
  */
 @Test
 public void querySerial1() throws IOException {
   session.execute("set serializer wrap-prefix=db,wrap-uri=ns");
   final Query query = session.query(WRAPPER + "()");
   assertTrue("Result expected.", query.more());
   assertEqual("<db:results xmlns:db=\"ns\"/>", query.next());
   assertFalse("No result expected.", query.more());
 }
Exemple #9
0
 /**
  * Deletes the document node and checks if namespace nodes of descendants are deleted as well.
  * F.i. adding a document via REST/PUT deletes a document node if the given document/name is
  * already stored in the target collection. If the test fails, this may lead to superfluous
  * namespace nodes.
  *
  * @throws IOException I/O exception
  */
 @Test
 public void deleteDocumentNode() throws IOException {
   create(2);
   context.data().startUpdate(context.options);
   context.data().delete(0);
   context.data().finishUpdate(context.options);
   final byte[] ns = context.data().nspaces.globalUri();
   assertTrue(ns != null && ns.length == 0);
 }
Exemple #10
0
 /**
  * Runs a query with additional serialization parameters.
  *
  * @throws IOException I/O exception
  */
 @Test
 public void querySerial2() throws IOException {
   final Query query = session.query(WRAPPER + "1 to 2");
   assertTrue("Result expected.", query.more());
   assertEqual(
       "<db:results xmlns:db=\"ns\">  <db:result>1</db:result>"
           + "  <db:result>2</db:result></db:results>",
       query.next());
 }
Exemple #11
0
 /** Tests http:send-request((),()). */
 @Test
 public void sendReqNoParams() {
   final Command cmd = new XQuery(_HTTP_SEND_REQUEST.args("()"));
   try {
     cmd.execute(ctx);
   } catch (final BaseXException ex) {
     assertTrue(ex.getMessage().contains(ErrType.HC.toString()));
   }
 }
Exemple #12
0
 /**
  * Checks the response to an HTTP request.
  *
  * @param v query result
  * @param itemsCount expected number of items
  * @param expStatus expected status
  */
 private static void checkResponse(final Value v, final int itemsCount, final int expStatus) {
   assertEquals(itemsCount, v.size());
   assertTrue(v.itemAt(0) instanceof FElem);
   final FElem response = (FElem) v.itemAt(0);
   assertNotNull(response.attributes());
   if (!eq(response.attribute(STATUS), token(expStatus))) {
     fail("Expected: " + expStatus + "\nFound: " + response);
   }
 }
Exemple #13
0
 /**
  * Queries empty content.
  *
  * @throws IOException I/O exception
  */
 @Test
 public void queryEmptyBinary() throws IOException {
   session.execute("create db " + NAME);
   session.store("X", new ArrayInput(""));
   assertEqual("", session.execute("xquery " + RAW + _DB_RETRIEVE.args(NAME, "X")));
   assertEqual("", session.query(RAW + _DB_RETRIEVE.args(NAME, "X")).execute());
   final Query q = session.query(RAW + _DB_RETRIEVE.args(NAME, "X"));
   assertTrue(q.more());
   assertEqual("", q.next());
   assertNull(q.next());
 }
Exemple #14
0
  /**
   * Tests RequestParser.parse() with multipart request.
   *
   * @throws IOException I/O Exception
   * @throws QueryException query exception
   */
  @Test
  public void parseMultipartReq() throws IOException, QueryException {
    final String multiReq =
        "<http:request "
            + "xmlns:http='http://expath.org/ns/http-client' "
            + "method='POST' href='"
            + REST_ROOT
            + "'>"
            + "<http:header name='hdr1' value='hdr1val'/>"
            + "<http:header name='hdr2' value='hdr2val'/>"
            + "<http:multipart media-type='multipart/mixed' boundary='xxxx'>"
            + "<http:header name='p1hdr1' value='p1hdr1val'/>"
            + "<http:header name='p1hdr2' value='p1hdr2val'/>"
            + "<http:body media-type='text/plain'>"
            + "Part1"
            + "</http:body>"
            + "<http:header name='p2hdr1' value='p2hdr1val'/>"
            + "<http:body media-type='text/plain'>"
            + "Part2"
            + "</http:body>"
            + "<http:body media-type='text/plain'>"
            + "Part3"
            + "</http:body>"
            + "</http:multipart>"
            + "</http:request>";

    final DBNode dbNode1 = new DBNode(new IOContent(multiReq));
    final HttpRequestParser rp = new HttpRequestParser(null);
    final HttpRequest r = rp.parse(dbNode1.children().next(), null);

    assertEquals(2, r.attributes.size());
    assertEquals(2, r.headers.size());
    assertTrue(r.isMultipart);
    assertEquals(3, r.parts.size());

    // check parts
    final Iterator<Part> i = r.parts.iterator();
    Part part = i.next();
    assertEquals(2, part.headers.size());
    assertEquals(1, part.bodyContent.size());
    assertEquals(1, part.bodyAttrs.size());

    part = i.next();
    assertEquals(1, part.headers.size());
    assertEquals(1, part.bodyContent.size());
    assertEquals(1, part.bodyAttrs.size());

    part = i.next();
    assertEquals(0, part.headers.size());
    assertEquals(1, part.bodyContent.size());
    assertEquals(1, part.bodyAttrs.size());
  }
Exemple #15
0
 /**
  * Queries binary content (works only if output stream is specified).
  *
  * @throws IOException I/O exception
  */
 @Test
 public void queryBinary() throws IOException {
   if (out == null) return;
   session.execute("create db " + NAME);
   final byte[] tmp = {0, 1, 2, 127, 0, -1, -2, -128};
   session.store("X", new ArrayInput(tmp));
   final String retr = _DB_RETRIEVE.args(NAME, "X");
   // check command
   session.execute("xquery " + RAW + retr + ',' + retr);
   assertTrue(eq(out.toArray(), concat(tmp, tmp)));
   out.reset();
   // check query execution
   session.query(RAW + retr + ',' + retr).execute();
   assertTrue(eq(out.toArray(), concat(tmp, tmp)));
   out.reset();
   // check iterator
   final Query q = session.query(RAW + retr + ',' + retr);
   q.next();
   assertTrue(eq(out.toArray(), tmp));
   out.reset();
   q.next();
   assertTrue(eq(out.toArray(), tmp));
   assertNull(q.next());
 }
  /**
   * Test wild-card matching.
   *
   * @throws QueryException wild-card expression is not parsed
   */
  @Test
  public void testMatch() throws QueryException {
    for (int i = 0; i < VALIDWC.length; i++) {

      final String q = VALIDWC[i];
      final FTWildcard wc = new FTWildcard(token(q), null);

      final String[] good = TEXTS_GOOD[i];
      for (final String element : good) {
        assertTrue('"' + q + "\" did NOT match \"" + element + '"', wc.match(token(element)));
      }

      final String[] bad = TEXTS_BAD[i];
      for (final String element : bad) {
        assertFalse('"' + q + "\" matched \"" + element + '"', wc.match(token(element)));
      }
    }
  }
Exemple #17
0
  /**
   * Tests RequestParser.parse() with normal (not multipart) request.
   *
   * @throws IOException I/O Exception
   * @throws QueryException query exception
   */
  @Test
  public void parseRequest() throws IOException, QueryException {
    // Simple HTTP request with no errors
    final String req =
        "<http:request "
            + "xmlns:http='http://expath.org/ns/http-client' "
            + "method='POST' href='"
            + REST_ROOT
            + "'>"
            + "<http:header name='hdr1' value='hdr1val'/>"
            + "<http:header name='hdr2' value='hdr2val'/>"
            + "<http:body media-type='text/xml'>"
            + "Test body content"
            + "</http:body>"
            + "</http:request>";
    final DBNode dbNode = new DBNode(new IOContent(req));
    final HttpRequestParser rp = new HttpRequestParser(null);
    final HttpRequest r = rp.parse(dbNode.children().next(), null);

    assertEquals(2, r.attributes.size());
    assertEquals(2, r.headers.size());
    assertTrue(r.bodyContent.size() != 0);
    assertEquals(1, r.payloadAttrs.size());
  }
Exemple #18
0
  /**
   * Tests if errors are thrown when some mandatory attributes are missing in a <http:request/>,
   * <http:body/> or <http:multipart/>.
   *
   * @throws IOException I/O Exception
   */
  @Test
  public void errors() throws IOException {

    // Incorrect requests
    final List<byte[]> falseReqs = new ArrayList<>();

    // Request without method
    final byte[] falseReq1 =
        token(
            "<http:request "
                + "xmlns:http='http://expath.org/ns/http-client' "
                + "href='"
                + REST_ROOT
                + "'/>");
    falseReqs.add(falseReq1);

    // Request with send-authorization and no credentials
    final byte[] falseReq2 =
        token(
            "<http:request "
                + "xmlns:http='http://expath.org/ns/http-client' "
                + "method='GET' href='"
                + REST_ROOT
                + "' "
                + "send-authorization='true'/>");
    falseReqs.add(falseReq2);

    // Request with send-authorization and only username
    final byte[] falseReq3 =
        token(
            "<http:request "
                + "xmlns:http='http://expath.org/ns/http-client' "
                + "method='GET' href='"
                + REST_ROOT
                + "' "
                + "send-authorization='true' username='******'/>");
    falseReqs.add(falseReq3);

    // Request with body that has no media-type
    final byte[] falseReq4 =
        token(
            "<http:request "
                + "xmlns:http='http://expath.org/ns/http-client' "
                + "method='POST' href='"
                + REST_ROOT
                + "'>"
                + "<http:body>"
                + "</http:body>"
                + "</http:request>");
    falseReqs.add(falseReq4);

    // Request with multipart that has no media-type
    final byte[] falseReq5 =
        token(
            "<http:request method='POST' "
                + "xmlns:http='http://expath.org/ns/http-client' "
                + "href='"
                + REST_ROOT
                + "'>"
                + "<http:multipart boundary='xxx'>"
                + "</http:multipart>"
                + "</http:request>");
    falseReqs.add(falseReq5);

    // Request with multipart with part that has a body without media-type
    final byte[] falseReq6 =
        token(
            "<http:request method='POST' "
                + "xmlns:http='http://expath.org/ns/http-client' "
                + "href='"
                + REST_ROOT
                + "'>"
                + "<http:multipart boundary='xxx'>"
                + "<http:header name='hdr1' value-='val1'/>"
                + "<http:body media-type='text/plain'>"
                + "Part1"
                + "</http:body>"
                + "<http:header name='hdr1' value-='val1'/>"
                + "<http:body>"
                + "Part1"
                + "</http:body>"
                + "</http:multipart>"
                + "</http:request>");
    falseReqs.add(falseReq6);

    // Request with schema different from http
    final byte[] falseReq7 =
        token(
            "<http:request "
                + "xmlns:http='http://expath.org/ns/http-client' "
                + "href='ftp://basex.org'/>");
    falseReqs.add(falseReq7);

    // Request with content and method which must be empty
    final byte[] falseReq8 =
        token(
            "<http:request "
                + "xmlns:http='http://expath.org/ns/http-client' "
                + "method='DELETE' href='"
                + REST_ROOT
                + "'>"
                + "<http:body media-type='text/plain'>"
                + "</http:body>"
                + "</http:request>");
    falseReqs.add(falseReq8);

    for (final byte[] falseReq : falseReqs) {
      final DBNode dbNode = new DBNode(new IOContent(falseReq));
      try {
        final HttpRequestParser rp = new HttpRequestParser(null);
        rp.parse(dbNode.children().next(), null);
        fail("Exception not thrown");
      } catch (final QueryException ex) {
        assertTrue(ex.getMessage().contains(ErrType.HC.toString()));
      }
    }
  }
Exemple #19
0
 /**
  * Checks if namespace hierarchy structure is updated correctly on the descendant axis after a
  * NSNode has been deleted.
  */
 @Test
 public void deleteShiftPreValues4() {
   create(16);
   query("delete node doc('d16')/a/b");
   assertTrue(context.data().nspaces.toString().isEmpty());
 }
Exemple #20
0
 /**
  * Assumes that the specified flag is successful.
  *
  * @param flag flag
  */
 private static void ok(final boolean flag) {
   assertTrue(flag);
 }