Example #1
0
 private void startup(Configuration configuration) throws ServletException {
   if (configuration == null) {
     throw new ServletException("database has not been configured");
   }
   LOG.info("configuring eXist instance");
   try {
     if (!BrokerPool.isConfigured()) {
       BrokerPool.configure(1, 5, configuration);
     }
   } catch (EXistException e) {
     throw new ServletException(e.getMessage());
   } catch (DatabaseConfigurationException e) {
     throw new ServletException(e.getMessage());
   }
   try {
     LOG.info("registering XMLDB driver");
     Class clazz = Class.forName("org.exist.xmldb.DatabaseImpl");
     Database database = (Database) clazz.newInstance();
     DatabaseManager.registerDatabase(database);
   } catch (ClassNotFoundException e) {
     LOG.info("ERROR", e);
   } catch (InstantiationException e) {
     LOG.info("ERROR", e);
   } catch (IllegalAccessException e) {
     LOG.info("ERROR", e);
   } catch (XMLDBException e) {
     LOG.info("ERROR", e);
   }
 }
  /**
   * 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;
  }
Example #3
0
  @Override
  public void afterPropertiesSet() throws Exception {

    if (StringUtils.isNotBlank(this.existHome)) {
      System.setProperty(ExistServiceConstants.EXIST_HOME_PROP, this.existHome);
      System.setProperty("exist.initdb", "true");
    }

    final String driver = "org.exist.xmldb.DatabaseImpl";

    // initialize database driver
    Class<?> cl = Class.forName(driver);
    Database database = (Database) cl.newInstance();
    database.setProperty("create-database", "true");
    DatabaseManager.registerDatabase(database);

    Collection root = this.getOrCreateCollection("");

    xQueryService = (XQueryService) root.getService("XPathQueryService", "1.0");
    collectionManagementService =
        (CollectionManagementService) root.getService("CollectionManagementService", "1.0");
    databaseInstanceManager =
        (DatabaseInstanceManager) root.getService("DatabaseInstanceManager", "1.0");
    indexQueryService = (IndexQueryService) root.getService("IndexQueryService", "1.0");
    xUpdateQueryService = (XUpdateQueryService) root.getService("XUpdateQueryService", "1.0");
    // This doesn't exist in existDB 2.1.  ValidationModule now maybe?  Not sure.  possibly an
    // extension not loaded...
    //		validationService = (ValidationService) root.getService("ValidationService", "1.0");

    this.namespaceMappingProperties = this.cts2Marshaller.getNamespaceMappingProperties();

    this.xQueryService = this.createXQueryService("");
  }
  /**
   * 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();
    }
  }
  /** @see TestCase#setUp() */
  protected void setUp() throws Exception {
    super.setUp();

    String name = "de.xplib.nexd.engine.xapi.DatabaseImpl";
    Class clazz = Class.forName(name);

    this.db = (SixdmlDatabase) clazz.newInstance();
    DatabaseManager.registerDatabase(this.db);

    this.coll = (SixdmlCollection) this.db.getCollection("nexd://localhost./db/docs", "sa", "");

    this.vcoll =
        (VirtualCollection) this.db.getCollection("nexd://localhost./db/vcl-data/myvc", "sa", "");

    this.dbColl = (SixdmlCollection) this.db.getCollection("nexd://localhost./db", "sa", "");
  }
  /**
   * 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();
    }
  }
  /**
   * 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();
    }
  }
Example #8
0
 protected void setUp() {
   try {
     // initialize driver
     Class<?> cl = Class.forName("org.exist.xmldb.DatabaseImpl");
     Database database = (Database) cl.newInstance();
     database.setProperty("create-database", "true");
     DatabaseManager.registerDatabase(database);
     root = DatabaseManager.getCollection(XmldbURI.LOCAL_DB, "admin", "");
     CollectionManagementService service =
         (CollectionManagementService) root.getService("CollectionManagementService", "1.0");
     root = service.createCollection("test");
     FILE_STORED = "big.xml";
     doc = (XMLResource) root.createResource(FILE_STORED, "XMLResource");
   } catch (ClassNotFoundException e) {
   } catch (InstantiationException e) {
   } catch (IllegalAccessException e) {
   } catch (XMLDBException e) {
     e.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  /**
   * 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;
  }
  public static void main(String args[]) throws Exception {
    String driver = "org.exist.xmldb.DatabaseImpl";
    Class cl = Class.forName(driver);
    Database database = (Database) cl.newInstance();
    DatabaseManager.registerDatabase(database);

    Collection col = DatabaseManager.getCollection("xmldb:exist:///db", "admin", "");
    XPathQueryService service = (XPathQueryService) col.getService("XPathQueryService", "1.0");
    service.setProperty("indent", "yes");

    ResourceSet result =
        service.query(
            "for $s in //intervention/(speaker|writer)/affiliation[@EPparty ='PSE'] return data($s/../../(speech|writing)/@ref)");
    ResourceIterator i = result.getIterator();
    while (i.hasMoreResources()) {
      Resource r = i.nextResource();
      System.out.println((String) r.getContent());
    }
    // shut down the database
    DatabaseInstanceManager manager =
        (DatabaseInstanceManager) col.getService("DatabaseInstanceManager", "1.0");
    manager.shutdown();
  }
  public void init(ServletConfig config) throws ServletException {
    super.init(config);

    query = config.getInitParameter("xquery");
    if (query == null) {
      throw new ServletException("RedirectorServlet requires a parameter 'xquery'.");
    }
    user = config.getInitParameter("user");
    if (user == null) {
      user = DEFAULT_USER;
    }
    password = config.getInitParameter("password");
    if (password == null) {
      password = DEFAULT_PASS;
    }
    final String confCollectionURI = config.getInitParameter("uri");
    if (confCollectionURI == null) {
      collectionURI = DEFAULT_URI;
    } else {
      try {
        collectionURI = XmldbURI.xmldbUriFor(confCollectionURI);
      } catch (final URISyntaxException e) {
        throw new ServletException("Invalid XmldbURI for parameter 'uri': " + e.getMessage(), e);
      }
    }

    try {
      final Class<?> driver = Class.forName(DRIVER);
      final Database database = (Database) driver.newInstance();
      database.setProperty("create-database", "true");
      DatabaseManager.registerDatabase(database);
    } catch (final Exception e) {
      final String errorMessage = "Failed to initialize database driver";
      LOG.error(errorMessage, e);
      throw new ServletException(errorMessage + ": " + e.getMessage(), e);
    }
  }
  /**
   * 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 #13
0
  protected void setUp() {
    try {
      // initialize driver
      Class<?> cl = Class.forName("org.exist.xmldb.DatabaseImpl");
      database = (Database) cl.newInstance();
      database.setProperty("create-database", "true");
      DatabaseManager.registerDatabase(database);

      Collection root = DatabaseManager.getCollection(XmldbURI.LOCAL_DB, "admin", "");
      CollectionManagementService service =
          (CollectionManagementService) root.getService("CollectionManagementService", "1.0");
      testCollection = service.createCollection(TEST_COLLECTION_NAME);
      assertNotNull(testCollection);

      service =
          (CollectionManagementService)
              testCollection.getService("CollectionManagementService", "1.0");

      Collection xsl1 = service.createCollection("xsl1");
      assertNotNull(xsl1);

      Collection xsl3 = service.createCollection("xsl3");
      assertNotNull(xsl3);

      service = (CollectionManagementService) xsl1.getService("CollectionManagementService", "1.0");

      Collection xsl2 = service.createCollection("xsl2");
      assertNotNull(xsl2);

      String doc1 =
          "<?xml version='1.0' encoding='UTF-8'?>\n"
              + "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\n"
              + "<xsl:import href='xsl2/2.xsl' />\n"
              + "<xsl:template match='/'>\n"
              + "<doc>"
              + "<p>Start Template 1</p>"
              + "<xsl:call-template name='template-2' />"
              + "<xsl:call-template name='template-3' />"
              + "<p>End Template 1</p>"
              + "</doc>"
              + "</xsl:template>"
              + "</xsl:stylesheet>";

      String doc2 =
          "<?xml version='1.0' encoding='UTF-8'?>\n"
              + "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\n"
              + "<xsl:import href='../../xsl3/3.xsl' />\n"
              + "<xsl:template name='template-2'>\n"
              + "<p>Start Template 2</p>"
              + "<xsl:call-template name='template-3' />"
              + "<p>End Template 2</p>"
              + "</xsl:template>"
              + "</xsl:stylesheet>";

      String doc3 =
          "<?xml version='1.0' encoding='UTF-8'?>\n"
              + "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\n"
              + "<xsl:template name='template-3'>\n"
              + "<p>Template 3</p>"
              + "</xsl:template>"
              + "</xsl:stylesheet>";

      addXMLDocument(xsl1, doc1, "1.xsl");
      addXMLDocument(xsl2, doc2, "2.xsl");
      addXMLDocument(xsl3, doc3, "3.xsl");
    } catch (ClassNotFoundException e) {
    } catch (InstantiationException e) {
    } catch (IllegalAccessException e) {
    } catch (XMLDBException e) {
      e.printStackTrace();
    }
  }
Example #14
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();
    }
  }