/**
   * 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();
    }
  }
Example #2
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;
      }
    }
  }
  /*
  public final void testDropResourceRoot() throws Exception {

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

      author.removeResource(author.getResource("author.3.hjb.xml"));
  }

  public final void testDropResourceSub() throws Exception {

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

      article.removeResource(article.getResource("article.patent.1.xml"));
  }
  */
  public final void testStoreResourceRoot() throws Exception {

    Collection author = this.dbColl.getChildCollection("vcl-data/author");
    Collection vcoll = this.dbColl.getChildCollection("vcl-data/myvc");

    int size = vcoll.getResourceCount();

    SixdmlResource res =
        (SixdmlResource) author.createResource("author.4.manuel.xml", SixdmlResource.RESOURCE_TYPE);
    res.setContentAsDOM(
        DocumentBuilderFactoryImpl.newInstance()
            .newDocumentBuilder()
            .parse("data/vcl-data/author.4.manuel.xml"));

    author.storeResource(res);
  }
  /**
   * 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();
    }
  }
  public final void testStoreResourceSubset() throws Exception {

    Collection article = this.dbColl.getChildCollection("vcl-data/article");
    Collection vcoll = this.dbColl.getChildCollection("vcl-data/myvc");

    int size = vcoll.getResourceCount();

    SixdmlResource res =
        (SixdmlResource)
            article.createResource("article.from.manuel.xml", SixdmlResource.RESOURCE_TYPE);
    res.setContentAsDOM(
        DocumentBuilderFactoryImpl.newInstance()
            .newDocumentBuilder()
            .parse("data/vcl-data/article.from.manuel.xml"));

    article.storeResource(res);

    assertEquals(size, vcoll.getResourceCount());
  }
Example #6
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();
   }
 }
Example #7
0
 private void addXMLDocument(Collection c, String doc, String id) throws XMLDBException {
   Resource r = c.createResource(id, XMLResource.RESOURCE_TYPE);
   r.setContent(doc);
   ((EXistResource) r).setMimeType("application/xml");
   c.storeResource(r);
 }
  /**
   * Processes a compressed entry from an archive
   *
   * @param name The name of the entry
   * @param isDirectory true if the entry is a directory, false otherwise
   * @param is an InputStream for reading the uncompressed data of the entry
   * @param filterParam is an additional param for entry filtering function
   * @param storeParam is an additional param for entry storing function
   * @throws XMLDBException
   */
  protected Sequence processCompressedEntry(
      String name, boolean isDirectory, InputStream is, Sequence filterParam, Sequence storeParam)
      throws IOException, XPathException, XMLDBException {
    String dataType = isDirectory ? "folder" : "resource";

    // call the entry-filter function
    Sequence filterParams[] = new Sequence[3];
    filterParams[0] = new StringValue(name);
    filterParams[1] = new StringValue(dataType);
    filterParams[2] = filterParam;
    Sequence entryFilterFunctionResult =
        entryFilterFunction.evalFunction(contextSequence, null, filterParams);

    if (BooleanValue.FALSE == entryFilterFunctionResult.itemAt(0)) {
      return Sequence.EMPTY_SEQUENCE;
    } else {
      Sequence entryDataFunctionResult;
      Sequence uncompressedData = Sequence.EMPTY_SEQUENCE;

      // copy the input data
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      byte buf[] = new byte[1024];
      int read = -1;
      while ((read = is.read(buf)) != -1) {
        baos.write(buf, 0, read);
      }
      byte[] entryData = baos.toByteArray();

      if (entryDataFunction.getSignature().getArgumentCount() == 3) {

        Sequence dataParams[] = new Sequence[3];
        System.arraycopy(filterParams, 0, dataParams, 0, 2);
        dataParams[2] = storeParam;
        entryDataFunctionResult = entryDataFunction.evalFunction(contextSequence, null, dataParams);

        String path = entryDataFunctionResult.itemAt(0).getStringValue();

        Collection root =
            new LocalCollection(
                context.getUser(),
                context.getBroker().getBrokerPool(),
                new AnyURIValue("/db").toXmldbURI(),
                context.getAccessContext());

        if (isDirectory) {

          XMLDBAbstractCollectionManipulator.createCollection(root, path);

        } else {

          Resource resource;

          File file = new File(path);
          name = file.getName();
          path = file.getParent();

          Collection target =
              (path == null)
                  ? root
                  : XMLDBAbstractCollectionManipulator.createCollection(root, path);

          MimeType mime = MimeTable.getInstance().getContentTypeFor(name);

          try {
            NodeValue content =
                ModuleUtils.streamToXML(context, new ByteArrayInputStream(baos.toByteArray()));
            resource = target.createResource(name, "XMLResource");
            ContentHandler handler = ((XMLResource) resource).setContentAsSAX();
            handler.startDocument();
            content.toSAX(context.getBroker(), handler, null);
            handler.endDocument();
          } catch (SAXException e) {
            resource = target.createResource(name, "BinaryResource");
            resource.setContent(baos.toByteArray());
          }

          if (resource != null) {
            if (mime != null) {
              ((EXistResource) resource).setMimeType(mime.getName());
            }
            target.storeResource(resource);
          }
        }

      } else {

        // try and parse as xml, fall back to binary
        try {
          uncompressedData = ModuleUtils.streamToXML(context, new ByteArrayInputStream(entryData));
        } catch (SAXException saxe) {
          if (entryData.length > 0)
            uncompressedData =
                BinaryValueFromInputStream.getInstance(
                    context, new Base64BinaryValueType(), new ByteArrayInputStream(entryData));
        }

        // call the entry-data function
        Sequence dataParams[] = new Sequence[4];
        System.arraycopy(filterParams, 0, dataParams, 0, 2);
        dataParams[2] = uncompressedData;
        dataParams[3] = storeParam;
        entryDataFunctionResult = entryDataFunction.evalFunction(contextSequence, null, dataParams);
      }

      return entryDataFunctionResult;
    }
  }