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); } }
/** * 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; }
/** * 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(); } }
/* (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 */ } } }
/* (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); } }
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; } } }
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; }
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()); }
public final void testDropResourceSubset() throws Exception { Collection article = this.dbColl.getChildCollection("vcl-data/article"); int size = article.getResourceCount(); Resource r = article.getResource("article.from.manuel.xml"); // Just do it if the resource exists. if (r != null) { article.removeResource(r); assertEquals(size - 1, article.getResourceCount()); } }
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(); }
@Override public void setPermissions(final Collection child, final Permission perm) throws XMLDBException { final XmldbURI childUri = XmldbURI.create(child.getName()); try { executeWithBroker( new BrokerOperation<Void>() { @Override public Void withBroker(final DBBroker broker) throws XMLDBException, LockException, PermissionDeniedException, IOException, EXistException, TriggerException, SyntaxException { return modifyCollection( broker, childUri, new DatabaseItemModifier<org.exist.collections.Collection, Void>() { @Override public Void modify(org.exist.collections.Collection collection) throws PermissionDeniedException, LockException { collection.setPermissions(perm); return null; } }); } }); } catch (final Exception e) { throw new XMLDBException( ErrorCodes.VENDOR_ERROR, "Failed to modify permission on Collection '" + childUri.toString() + "'", e); } }
/* 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(); } }
/* * @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()); } }
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"); }
/** * 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(); } }
/** * Store in the "classical" eXist way: the XMLResource stores an XML string before storeResource() * stores it in the database. */ public void testQueryStoreContentAsSAX() { try { ContentHandler databaseInserter = doc.setContentAsSAX(); (new TabularXMLReader()).writeDocument(databaseInserter); root.storeResource(doc); querySingleLine("", "testQueryStoreContentAsSAX"); } catch (Exception e) { fail(e.getMessage()); } }
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()); } }
public final void testDropVirtualResourceFail() throws Exception { Collection vcoll = this.dbColl.getChildCollection("vcl-data/myvc"); String[] names = vcoll.listResources(); for (int i = 0; i < names.length; i++) { Resource res = vcoll.getResource(names[i]); assertTrue( "Expected instance of VirtualResource and not " + res.getClass(), res instanceof VirtualResource); try { vcoll.removeResource(res); assertTrue("Cannot delete a VirtualResource.", false); } catch (XMLDBException e) { assertTrue( "Expected errorCode.INVALID_COLLECTION", e.errorCode == ErrorCodes.INVALID_COLLECTION); } } }
@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(""); }
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; }
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()); }
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 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(); }
@Override public void setPermissions( Collection child, final String owner, final String group, final int mode, final List<ACEAider> aces) throws XMLDBException { final XmldbURI childUri = XmldbURI.create(child.getName()); try { executeWithBroker( new BrokerOperation<Void>() { @Override public Void withBroker(final DBBroker broker) throws XMLDBException, LockException, PermissionDeniedException, IOException, EXistException, TriggerException, SyntaxException { return modifyCollection( broker, childUri, new DatabaseItemModifier<org.exist.collections.Collection, Void>() { @Override public Void modify(org.exist.collections.Collection collection) throws PermissionDeniedException, LockException { final Permission permission = collection.getPermissions(); permission.setOwner(owner); permission.setGroup(group); permission.setMode(mode); if (permission instanceof ACLPermission) { final ACLPermission aclPermission = (ACLPermission) permission; aclPermission.clear(); for (final ACEAider ace : aces) { aclPermission.addACE( ace.getAccessType(), ace.getTarget(), ace.getWho(), ace.getMode()); } } return null; } }); } }); } catch (final Exception e) { throw new XMLDBException( ErrorCodes.VENDOR_ERROR, "Failed to modify permission on Collection '" + childUri.toString() + "'", e); } }
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()); }
/** * @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; }
public final void testDropResourceRoot() throws Exception { Collection author = this.dbColl.getChildCollection("vcl-data/author"); Collection vcoll = this.dbColl.getChildCollection("vcl-data/myvc"); int size = vcoll.getResourceCount(); Resource res = author.getResource("author.4.manuel.xml"); author.removeResource(res); assertEquals(size - 1, vcoll.getResourceCount()); }
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()); } }