예제 #1
0
  /**
   * 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;
  }
예제 #2
0
  /**
   * 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();
    }
  }
예제 #3
0
  /**
   * 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();
    }
  }
예제 #4
0
  /**
   * 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("=== XMLDBQuery ===\n");

    System.out.println("* Run query via XML:DB:");

    // Collection instance
    Collection coll = null;

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

      // Receive the database
      coll = DatabaseManager.getCollection(DBNAME);

      // Receive the XPath query service
      XPathQueryService service = (XPathQueryService) coll.getService("XPathQueryService", "1.0");

      // Execute the query and receives all results
      ResourceSet set = service.query(QUERY);

      // Create a result iterator
      ResourceIterator iter = set.getIterator();

      // Loop through all result items
      while (iter.hasMoreResources()) {
        // Receive the next results
        Resource res = iter.nextResource();

        // Write the result to the console
        System.out.println(res.getContent());
      }
    } catch (final XMLDBException ex) {
      // Handle exceptions
      System.err.println("XML:DB Exception occured " + ex.errorCode);
    } finally {
      // Close the collection
      if (coll != null) coll.close();
    }
  }
예제 #5
0
  /**
   * This method performs an XPath query to the database and returns the results as a Vector of
   * Strings.
   *
   * @param collection The name of the collection to look for the document.
   * @param query A string containing an XPath expression which shall act as a query against the
   *     database.
   * @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 A Vector containing the answers to the query as Strings.
   */
  public Vector query(String collection, String query, String username, String password) {
    Vector response = new Vector();
    try {
      Class cl = Class.forName(_driver);
      Database database = (Database) cl.newInstance();
      DatabaseManager.registerDatabase(database);

      Collection col = DatabaseManager.getCollection(_URI + collection, username, password);
      XPathQueryService service = (XPathQueryService) col.getService("XPathQueryService", "1.0");
      service.setProperty("indent", "yes");

      ResourceSet result = service.query(query);
      ResourceIterator i = result.getIterator();
      while (i.hasMoreResources()) {
        Resource r = i.nextResource();
        response.add((String) r.getContent());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return response;
  }
예제 #6
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();
    }
  }