Ejemplo n.º 1
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("");
  }
Ejemplo n.º 2
0
  /* (non-Javadoc)
   * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
   */
  public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    final String userName = args[0].getStringValue();

    Collection collection = null;
    try {
      collection =
          new LocalCollection(
              context.getSubject(),
              context.getBroker().getBrokerPool(),
              XmldbURI.ROOT_COLLECTION_URI,
              context.getAccessContext());
      final UserManagementService ums =
          (UserManagementService) collection.getService("UserManagementService", "1.0");
      final Account user = ums.getAccount(userName);

      if (user == null)
      // todo - why not just return false()? /ljo
      {
        return Sequence.EMPTY_SEQUENCE;
      }
      return user.hasDbaRole() ? BooleanValue.TRUE : BooleanValue.FALSE;
    } catch (final XMLDBException xe) {
      logger.error("Failed to access user " + userName);
      throw new XPathException(this, "Failed to access user " + userName, xe);
    } finally {
      if (null != collection)
        try {
          collection.close();
        } catch (final XMLDBException e) {
          /* ignore */
        }
    }
  }
Ejemplo n.º 3
0
  public void execute(Connection connection) throws XMLDBException, EXistException {
    Collection collection = connection.getCollection("/db");
    XQueryService service = (XQueryService) collection.getService("XQueryService", "1.0");
    service.declareVariable("filename", "");
    service.declareVariable("count", "0");
    String query = IMPORT + xqueryContent;
    System.out.println("query: " + query);
    CompiledExpression compiled = service.compile(query);
    try {
      for (int i = 0; i < count; i++) {
        File nextFile = new File(directory, prefix + i + ".xml");

        service.declareVariable("filename", nextFile.getName());
        service.declareVariable("count", new IntegerValue(i));
        ResourceSet results = service.execute(compiled);

        Writer out = new OutputStreamWriter(new FileOutputStream(nextFile), "UTF-8");
        for (ResourceIterator iter = results.getIterator(); iter.hasMoreResources(); ) {
          Resource r = iter.nextResource();
          out.write(r.getContent().toString());
        }
        out.close();
      }
    } catch (IOException e) {
      throw new EXistException("exception while storing generated data: " + e.getMessage(), e);
    }
  }
Ejemplo n.º 4
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();
    }
  }
Ejemplo n.º 5
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();
 }
Ejemplo n.º 6
0
  /* (non-Javadoc)
   * @see org.apache.tools.ant.Task#execute()
   */
  public void execute() throws BuildException {
    if (uri == null) throw new BuildException("You have to specify an XMLDB collection URI");
    if (resource == null && collection == null)
      throw new BuildException(
          "Missing parameter: either resource or collection should be specified");

    registerDatabase();
    try {
      log("Get base collection: " + uri, Project.MSG_DEBUG);
      Collection base = DatabaseManager.getCollection(uri, user, password);

      if (base == null) {
        throw new BuildException("Collection " + uri + " could not be found.");
      }

      log(
          "Create collection management service for collection " + base.getName(),
          Project.MSG_DEBUG);
      CollectionManagementServiceImpl service =
          (CollectionManagementServiceImpl) base.getService("CollectionManagementService", "1.0");
      if (resource != null) {
        log("Copying resource: " + resource, Project.MSG_INFO);
        Resource res = base.getResource(resource);
        if (res == null) throw new BuildException("Resource " + resource + " not found.");
        service.copyResource(resource, destination, name);
      } else {
        log("Copying collection: " + collection, Project.MSG_INFO);
        service.copy(collection, destination, name);
      }
    } catch (XMLDBException e) {
      throw new BuildException("XMLDB exception during remove: " + e.getMessage(), e);
    }
  }
Ejemplo n.º 7
0
  /*
   * @see TestCase#tearDown()
   */
  protected void tearDown() {
    try {
      Collection root = DatabaseManager.getCollection(XmldbURI.LOCAL_DB, "admin", "");
      CollectionManagementService service =
          (CollectionManagementService) root.getService("CollectionManagementService", "1.0");
      service.removeCollection(TEST_COLLECTION_NAME);

      DatabaseManager.deregisterDatabase(database);
      DatabaseInstanceManager dim =
          (DatabaseInstanceManager) testCollection.getService("DatabaseInstanceManager", "1.0");
      dim.shutdown();
      database = null;
      testCollection = null;
      System.out.println("tearDown PASSED");
    } catch (XMLDBException e) {
      fail(e.getMessage());
    }
  }
Ejemplo n.º 8
0
 private static void shutdown(Collection collection) {
   try {
     //		shutdown the database gracefully
     DatabaseInstanceManager manager =
         (DatabaseInstanceManager) collection.getService("DatabaseInstanceManager", "1.0");
     manager.shutdown();
   } catch (XMLDBException e) {
     fail(e.getMessage());
   }
 }
Ejemplo n.º 9
0
 private XUpdateQueryService createXQueryUpdateService(String collectionPath) {
   XUpdateQueryService service;
   Collection collection;
   try {
     collection = this.getOrCreateCollection(collectionPath);
     service = (XUpdateQueryService) collection.getService("XUpdateQueryService", "1.0");
     service.setCollection(collection);
   } catch (XMLDBException e) {
     throw new Cts2RuntimeException(e);
   }
   return service;
 }
Ejemplo n.º 10
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());
  }
  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 final void testDropVirtualCollectionSuccess() throws Exception {
    Collection testColl = this.db.getCollection("/db/vc-colls", "sa", "");

    VirtualCollectionManagementService vcms =
        (VirtualCollectionManagementService)
            testColl.getService("VirtualCollectionManagementService", "1.0");

    int size = testColl.getChildCollectionCount();

    vcms.removeVirtualCollection("test-vc");

    assertEquals(
        "Why is the virtual collection not removed?", size - 1, testColl.getChildCollectionCount());
  }
Ejemplo n.º 13
0
 /**
  * @param xquery
  * @param mess
  * @return TODO
  */
 private ResourceSet querySingleLine(String xquery, String mess) throws XMLDBException {
   // query a single line:
   XPathQueryService service = (XPathQueryService) root.getService("XPathQueryService", "1.0");
   ResourceSet result = null;
   if (xquery != "") {
     // xquery = "/*/*[2]";
     System.out.println("Querying \"" + xquery + "\" ...");
     long t0 = System.currentTimeMillis();
     result = service.queryResource("big.xml", xquery);
     // assertEquals(1, result.getSize());
     long t1 = System.currentTimeMillis();
     System.out.println(
         "Time for query \"" + xquery + "\" on " + mess + ": " + (t1 - t0) + " ms.");
   }
   return result;
 }
Ejemplo n.º 14
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());
    }
  }
Ejemplo n.º 15
0
  private void removeTags() throws Exception {
    XUpdateQueryService service =
        (XUpdateQueryService) testCol.getService("XUpdateQueryService", "1.0");
    int start = rand.nextInt(RUNS / 4);
    for (int i = start; i < RUNS; i++) {
      String xupdate =
          "<xupdate:modifications version=\"1.0\" xmlns:xupdate=\"http://www.xmldb.org/xupdate\">"
              + "<xupdate:remove select=\"//"
              + tags[i]
              + "\"/>"
              + "</xupdate:modifications>";

      @SuppressWarnings("unused")
      long mods = service.updateResource("test.xml", xupdate);
      System.out.println("Removed: " + tags[i]);

      i += rand.nextInt(3);
    }
  }
  public final void testVCLSchemaVisitor() throws Exception {

    if (true) return;

    Collection vcl = this.dbColl.getChildCollection("vcl-data");

    VirtualCollectionManagementService vcms =
        (VirtualCollectionManagementService)
            vcl.getService("VirtualCollectionManagementService", "1.0");

    File f = new File("data/vcl-schema/author-articles.vcs");
    URL url = new URL("file://" + f.getAbsolutePath());

    long start = System.currentTimeMillis();
    vcms.createVirtualCollection("myvc", url);
    long end = System.currentTimeMillis();

    System.out.println("Time: " + (end - start) + " msec");
  }
Ejemplo n.º 17
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();
    }
  }
Ejemplo n.º 18
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();
   }
 }
Ejemplo n.º 19
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;
  }
Ejemplo n.º 20
0
  private XQueryService createXQueryService(String collectionPath) {
    XQueryService service;
    Collection collection;
    try {
      collection = this.getOrCreateCollection(collectionPath);

      service = (XQueryService) collection.getService("XPathQueryService", "1.0");

      service.setCollection(collection);
    } catch (XMLDBException e) {
      throw new Cts2RuntimeException(e);
    }

    try {
      for (Entry<Object, Object> entry : namespaceMappingProperties.entrySet()) {
        service.setNamespace((String) entry.getKey(), (String) entry.getValue());
      }
    } catch (XMLDBException e) {
      throw new Cts2RuntimeException(e);
    }

    return service;
  }
  public final void testCreateVirtualCollectionSuccess() throws Exception {
    Collection testColl = this.db.getCollection("/db/vc-colls", "sa", "");

    VirtualCollectionManagementService vcms =
        (VirtualCollectionManagementService)
            testColl.getService("VirtualCollectionManagementService", "1.0");

    int size = testColl.getChildCollectionCount();

    VirtualCollection vc =
        vcms.createVirtualCollection(
            "test-vc", new File("data/vcl-schema/author-articles.no.dtd.vcs").toURL());

    assertNotNull("Expected that an instance of VirtualCollection is returned and not null", vc);
    assertTrue(
        "Expected the returns instance is an instance of VirtualCollection and not "
            + vc.getClass(),
        vc instanceof VirtualCollection);

    assertEquals(
        "Why is the virtual collection not inserted but returned?",
        size + 1,
        testColl.getChildCollectionCount());
  }
Ejemplo n.º 22
0
  /*
   * (non-Javadoc)
   *
   * @see org.exist.xquery.Expression#eval(org.exist.dom.DocumentSet,
   * org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
   */
  public Sequence eval(Sequence args[], Sequence contextSequence) throws XPathException {

    if (!context.getSubject().hasDbaRole()) {
      final XPathException xPathException =
          new XPathException(
              this,
              "Permission denied, calling user '"
                  + context.getSubject().getName()
                  + "' must be a DBA to call this function.");
      logger.error("Invalid user", xPathException);
      throw xPathException;
    }

    final String user = args[0].getStringValue();
    final String pass = args[1].getStringValue();

    logger.info("Attempting to create user " + user);

    final UserAider userObj = new UserAider(user);
    userObj.setPassword(pass);

    // changed by wolf: the first group is always the primary group, so we
    // don't need
    // an additional argument
    final Sequence groups = args[2];
    final int len = groups.getItemCount();
    for (int x = 0; x < len; x++) {
      userObj.addGroup(groups.itemAt(x).getStringValue());
    }

    Collection collection = null;
    try {
      collection =
          new LocalCollection(
              context.getSubject(),
              context.getBroker().getBrokerPool(),
              XmldbURI.ROOT_COLLECTION_URI,
              context.getAccessContext());
      final UserManagementService ums =
          (UserManagementService) collection.getService("UserManagementService", "1.0");
      ums.addAccount(userObj);

    } catch (final XMLDBException xe) {
      logger.error("Failed to create user: "******"Failed to create user: "******"Failed to create new user '" + user + "' by " + context.getSubject().getName(),
          xe);
    } finally {
      if (null != collection)
        try {
          collection.close();
        } catch (final XMLDBException e) {
          /* ignore */
        }
    }
    return Sequence.EMPTY_SEQUENCE;
  }
Ejemplo n.º 23
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);
    }
  }
Ejemplo n.º 24
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();
    }
  }
Ejemplo n.º 25
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();
    }
  }