Пример #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
  public Collection getOrCreateCollection(String path) throws XMLDBException {
    path = StringUtils.removeStart(path, "/");
    path = StringUtils.removeEnd(path, "/");
    path = path.replaceAll("[/]+", "/");

    String pathWithURI = uri + path;

    Collection col = DatabaseManager.getCollection(pathWithURI, userName, password);

    if (col != null) {
      return col;
    } else {
      synchronized (syncLock) {
        col = DatabaseManager.getCollection(pathWithURI, userName, password);
        if (col != null) {
          return col;
        }
        String[] paths = path.split("/");

        String[] parentPath = (String[]) ArrayUtils.remove(paths, paths.length - 1);

        this.getOrCreateCollection(StringUtils.join(parentPath, '/'));

        CollectionManagementService mgt = this.getCollectionManagementService();

        col = mgt.createCollection(StringUtils.join(paths, '/'));

        // If we are creating a new root collection, we need to set up the indexing configuration
        // for this collection,
        // which is done by placing a collection.xconf file into the config path structure.
        if (paths.length == 1 && getCollectionRoot().endsWith(paths[0])) {
          log.info("Configuring Indexes for Collection " + paths[0]);
          // Add the index configuration file for our root config
          try {
            String confFilePath = "/collection.xconf";
            String confFileXml =
                IOUtils.toString(this.getClass().getResourceAsStream(confFilePath), "UTF-8");
            Collection configCol = getOrCreateCollection("/system/config/db/" + paths[0]);
            org.xmldb.api.base.Resource r =
                configCol.createResource("collection.xconf", "XMLResource");
            r.setContent(confFileXml);
            configCol.storeResource(r);
            log.info(
                "Wrote index configuration " + r.getParentCollection().getName() + "/" + r.getId());
          } catch (Exception e) {
            log.error(
                "Failure configuring indexes for collection "
                    + paths[0]
                    + " - indexes will not be available!",
                e);
          }
        }
        return col;
      }
    }
  }
Пример #4
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("");
  }
Пример #5
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);
   }
 }
Пример #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);
    }
  }
Пример #7
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();
    }
  }
Пример #8
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());
    }
  }
Пример #9
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();
    }
  }
Пример #10
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();
   }
 }
Пример #11
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;
  }
  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();
  }
  /** @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", "");
  }
Пример #14
0
  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);
    }
  }
Пример #15
0
  /**
   * 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();
    }
  }
Пример #16
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();
    }
  }
Пример #17
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);
    }
  }
Пример #18
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();
    }
  }