/**
   * This method retrieves an xml document from the database based on its resource identifier. The
   * document is returned as an org.w3c.dom.Document.
   *
   * @param collection The name of the collection to look for the document.
   * @param resourceId The resource identifier of the document to be retrieved.
   * @param username The identifier of the user calling the method used for authentication.
   * @param password The password of the user calling the method used for authentication.
   * @return The xml document retrieved as an org.w3c.dom.Document.
   */
  public Document retrieveDocument(
      String collection, String resourceId, String username, String password) {
    Document doc = null;

    try {
      // initialize database driver
      Class cl = Class.forName(_driver);
      Database database = (Database) cl.newInstance();
      DatabaseManager.registerDatabase(database);

      // get the collection
      Collection col = DatabaseManager.getCollection(_URI + collection, username, password);
      col.setProperty(OutputKeys.INDENT, "no");
      XMLResource res = (XMLResource) col.getResource(resourceId);
      if (res == null) System.out.println("document not found!");
      else {
        doc = (Document) (res.getContentAsDOM()).getOwnerDocument();
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return doc;
  }
  /**
   * This method stores an xml document given as an org.w3c.dom.Document to the database giving it
   * an indentifier. If the identifier provided is null, then the database generates a unique
   * identifier on its own.
   *
   * @param doc The dom represntation of the document to be stored as an org.w3c.dom.Document.
   * @param resourceId The resourceId to give to the document as a unique identifier within the
   *     database. If null a unique identifier is automatically generated.
   * @param collection The name of the collection to store the document under. If it does not exist,
   *     it is created.
   * @param username The identifier of the user calling the method used for authentication.
   * @param password The password of the user calling the method used for authentication.
   */
  public void storeDomDocument(
      Document doc, String resourceId, String collection, String username, String password) {

    try {
      // initialize driver
      Class cl = Class.forName(_driver);
      Database database = (Database) cl.newInstance();
      DatabaseManager.registerDatabase(database);

      // try to get collection
      Collection col = DatabaseManager.getCollection(_URI + collection, username, password);
      if (col == null) {
        // collection does not exist: get root collection and create
        // for simplicity, we assume that the new collection is a
        // direct child of the root collection, e.g. /db/test.
        // the example will fail otherwise.
        Collection root = DatabaseManager.getCollection(_URI + "/db");
        CollectionManagementService mgtService =
            (CollectionManagementService) root.getService("CollectionManagementService", "1.0");
        col = mgtService.createCollection(collection.substring("/db".length()));
      }
      // create new XMLResource; an id will be assigned to the new resource
      XMLResource document = (XMLResource) col.createResource(resourceId, "XMLResource");
      document.setContentAsDOM(doc.getDocumentElement());
      col.storeResource(document);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * Main method of the example class.
   *
   * @param args (ignored) command-line arguments
   * @throws Exception exception
   */
  public static void main(final String[] args) throws Exception {

    System.out.println("=== XMLDBInsert ===");

    // Collection instance
    Collection col = null;

    try {
      // Register the database
      Class<?> c = Class.forName(DRIVER);
      Database db = (Database) c.newInstance();
      DatabaseManager.registerDatabase(db);

      System.out.println("\n* Get collection.");

      // Receive the collection
      col = DatabaseManager.getCollection(DBNAME);

      // ID for the new document
      String id = "world";

      // Content of the new document
      String doc = "<xml>Hello World!</xml>";

      System.out.println("\n* Create new resource.");

      // Create a new XML resource with the specified ID
      XMLResource res = (XMLResource) col.createResource(id, XMLResource.RESOURCE_TYPE);

      // Set the content of the XML resource as the document
      res.setContent(doc);

      System.out.println("\n* Store new resource.");

      // Store the resource into the database
      col.storeResource(res);

    } catch (final XMLDBException ex) {
      // Handle exceptions
      System.err.println("XML:DB Exception occurred " + ex.errorCode);
      ex.printStackTrace();
    } finally {
      // Close the collection
      if (col != null) col.close();
    }
  }
Example #4
0
 /**
  * Store in the "classical" eXist way: the XMLResource stores an XML string before storeResource()
  * stores it in the database.
  */
 public void testQueryStoreContentAsSAX() {
   try {
     ContentHandler databaseInserter = doc.setContentAsSAX();
     (new TabularXMLReader()).writeDocument(databaseInserter);
     root.storeResource(doc);
     querySingleLine("", "testQueryStoreContentAsSAX");
   } catch (Exception e) {
     fail(e.getMessage());
   }
 }
Example #5
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());
  }
Example #6
0
 /**
  * @param dataSource
  * @throws XMLDBException
  */
 private void storeSAXEvents(XMLReader dataSource) {
   try {
     if (root instanceof LocalCollection) {
       long t0 = System.currentTimeMillis();
       LocalCollection coll = (LocalCollection) root;
       coll.setReader(dataSource);
       String existHome = System.getProperty("exist.home");
       File existDir = existHome == null ? new File(".") : new File(existHome);
       doc.setContent(new File(existDir, FILE_STORED));
       coll.storeResource(doc);
       long t1 = System.currentTimeMillis();
       System.out.println("Time for storing:  " + (t1 - t0) + " ms.");
     }
   } catch (XMLDBException e) {
     fail(e.getMessage());
   }
 }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {

      // Identify Sources
      String path = getServletContext().getRealPath("/WEB-INF/");
      String XMLFileName = path + "/Home.xml";
      String XSLFileName = path + "/Home.xsl";

      StreamSource XMLSource = new StreamSource(XMLFileName);
      StreamSource XSLSource = new StreamSource(XSLFileName);

      String URI = "xmldb:exist://localhost:8444/exist/xmlrpc";
      String driver = "org.exist.xmldb.DatabaseImpl";

      XMLResource res = null;
      Node resNode = null;
      Document doc = null;

      try {
        Class cl = Class.forName(driver);
        Database database = (Database) cl.newInstance();
        DatabaseManager.registerDatabase(database);

        // get the collection
        Collection col =
            DatabaseManager.getCollection(URI + "/db/AnswerQuest", "admin", "password");

        col.setProperty(OutputKeys.INDENT, "no");
        res = (XMLResource) col.getResource("Home.xml");

        resNode = res.getContentAsDOM();

        doc = (Document) resNode;

      } catch (Exception e) {
        System.err.println("Error Document: " + e.getMessage());
      }

      DOMSource origDocSource = new DOMSource(doc);

      // Identify Result
      StreamResult homeOutput = new StreamResult(out);

      // Create TransformerFactory
      TransformerFactory xFactory = TransformerFactory.newInstance();

      // Create Transformer
      Transformer optimusPrime = xFactory.newTransformer(XSLSource);

      // Apply transform
      optimusPrime.transform(XMLSource, homeOutput);

    } catch (TransformerConfigurationException ex) {

      System.out.println("Encountered TransformerConfiguration Error: " + ex.getMessage());

    } catch (TransformerException ex) {

      System.out.println("Encountered Transformer Error: " + ex.getMessage());

    } finally {
      out.close();
    }
  }
Example #8
0
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    String URI = "xmldb:exist://localhost:8444/exist/xmlrpc";
    String driver = "org.exist.xmldb.DatabaseImpl";

    XMLResource res = null;
    Node resNode = null;
    Document doc = null;

    String path = getServletContext().getRealPath("/");
    String XSLFileName = path + "/Slideshow.xsl";
    File XslFile = new File(XSLFileName);

    String name;
    String rating;

    try {
      name = request.getParameter("name");
      rating = request.getParameter("rating");

      if (name == null) {
        name = "";
      }
      if (rating == null) {
        rating = "";
      }

    } catch (Exception e) {
      name = "";
      rating = "";
    }

    try {
      Class cl = Class.forName(driver);
      Database database = (Database) cl.newInstance();
      DatabaseManager.registerDatabase(database);

      // get the collection
      Collection col = DatabaseManager.getCollection(URI + "/db/Project", "admin", "password");

      XQueryService service = (XQueryService) col.getService("XQueryService", "1.0");
      XQueryService another = (XQueryService) col.getService("XQueryService", "1.0");
      service.setProperty("indent", "yes");
      another.setProperty("indent", "yes");
      String queryString = "";
      if (!(rating.equals(""))) {
        service.declareVariable("rating", "");
        queryString =
            "for $rating in //app//name[text()='"
                + name
                + "']/../rating "
                + "return update replace $rating with <rating>"
                + rating
                + "</rating>";
        service.query(queryString);
      }

      col.setProperty(OutputKeys.INDENT, "no");

      res = (XMLResource) col.getResource("Review.xml");

      resNode = res.getContentAsDOM();

      doc = (Document) resNode;

    } catch (Exception e) {
      System.err.println("Error Document: " + e.getMessage());
    }
    DOMSource origDocSource = new DOMSource(doc);

    try {
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      StreamSource stylesheet = new StreamSource(XslFile);

      Transformer transformer = transformerFactory.newTransformer(stylesheet);

      NodeList appNodes = doc.getElementsByTagName("name");
      int numEvent = appNodes.getLength();
      String prev;
      String next;

      for (int i = 0; i < numEvent; i++) {

        Node eventNode = appNodes.item(i);

        NodeList eventNodeListChildren = eventNode.getChildNodes();
        Node eventTextNode = eventNodeListChildren.item(0);
        String appname = eventTextNode.getNodeValue();
        if (name.equals(appname)) {

          if (i != 0) {
            prev = appNodes.item(i - 1).getChildNodes().item(0).getNodeValue();
          } else {
            prev = appNodes.item(numEvent - 1).getChildNodes().item(0).getNodeValue();
          }

          if (i != (numEvent - 1)) {
            next = appNodes.item(i + 1).getChildNodes().item(0).getNodeValue();
          } else {
            next = appNodes.item(0).getChildNodes().item(0).getNodeValue();
          }

          transformer.setParameter("app_name", appname);
          transformer.setParameter("prev_name", prev);
          transformer.setParameter("next_name", next);

          transformer.transform(origDocSource, new StreamResult(out));
        }
      }
    } catch (Exception e) {
      out.println("Exception transformation :" + e.getMessage());
      e.printStackTrace(out);
    } finally {
      out.close();
    }
  }
  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);
    }
  }