Package org.exist

Examples of org.exist.Database


      throw new PermissionDeniedException(e);
    }

    inst = this;
   
    Database db = manager.getDatabase();
   
    inject(db, md);

        db.registerDocumentTrigger(DocumentEvents.class);
        db.registerCollectionTrigger(CollectionEvents.class);
   
    Map<String, Class<?>> map = (Map<String, Class<?>>) db.getConfiguration().getProperty(XQueryContext.PROPERTY_BUILT_IN_MODULES);
        map.put(
        NAMESPACE_URI,
        MetadataModule.class);
  }
View Full Code Here


              uri = fileURI.substring(5);
              is = new FileInputStream(new File(uri));
            } else {
              XmldbURI pathUri = XmldbURI.create( URLDecoder.decode( fileURI.substring(15) , "UTF-8" ) );
 
              Database db = getJoint().getContext().getDatabase();
              DBBroker broker = null;
              try {
                broker = db.getBroker();
              DocumentImpl resource = broker.getXMLResource(pathUri, Lock.READ_LOCK);
   
              if (resource.getResourceType() == DocumentImpl.BINARY_FILE) {
                is = broker.getBinaryResource((BinaryDocument) resource);
              } else {
                //TODO: xml source???
                return;
              }
              } catch (EXistException e) {
                      exception = e;
          } finally {
                db.release(broker);
              }
            }
          } else {
            URL url = new URL(fileURI);
            URLConnection conn = url.openConnection();
View Full Code Here

  }

  @Override
  public String evalution(String script) throws Exception {
   
    Database db = compiledXQuery.getContext().getDatabase();
    DBBroker broker = null;
    try {
      broker = db.getBroker(); //TODO: account required

      XQueryContext context = compiledXQuery.getContext().copyContext();
      context.setDebuggeeJoint(null);
      context.undeclareGlobalVariable(Debuggee.SESSION);
      context.undeclareGlobalVariable(Debuggee.IDEKEY);
     
      XQuery service = broker.getXQueryService();
      CompiledXQuery compiled = service.compile(context, script);
     
      Sequence resultSequence = service.execute(compiled, null);
 
          SAXSerializer sax = null;
          Serializer serializer = broker.getSerializer();
      serializer.reset();
          try {
              sax = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
              Properties outputProps = new Properties();
              StringWriter writer = new StringWriter();
              sax.setOutput(writer, outputProps);
              serializer.setSAXHandlers(sax, sax);
              for (SequenceIterator i = resultSequence.iterate(); i.hasNext();) {
                  Item next = i.nextItem();
                  if (Type.subTypeOf(next.getType(), Type.NODE))
                      serializer.toSAX((NodeValue) next);
                  else
                      writer.write(next.getStringValue());
              }
              return writer.toString();
          } finally {
              if (sax != null) {
                  SerializerPool.getInstance().returnObject(sax);
              }
          }
    } finally {
      db.release(broker);
    }
  }
View Full Code Here

     */
    private void storeXMLInternal(final Txn transaction, final DBBroker broker, final IndexInfo info, final boolean privileged, final StoreBlock doParse) throws EXistException, SAXException, PermissionDeniedException {
       
        final DocumentImpl document = info.getIndexer().getDocument();
       
        final Database db = broker.getBrokerPool();
       
        try {
            /* TODO
             *
             * These security checks are temporarily disabled because throwing an exception
             * here may cause the database to corrupt.
             * Why would the database corrupt? Because validateXMLInternal that is typically
             * called before this method actually modifies the database and this collection,
             * so throwing an exception here leaves the database in an inconsistent state
             * with data 1/2 added/updated.
             *
             * The downside of disabling these checks here is that: this collection is not locked
             * between the call to validateXmlInternal and storeXMLInternal, which means that if
             * UserA in ThreadA calls validateXmlInternal and is permitted access to store a resource,
             * and then UserB in ThreadB modifies the permissions of this collection to prevent UserA
             * from storing the document, when UserA reaches here (storeXMLInternal) they will still
             * be allowed to store their document. However the next document that UserA attempts to store
             * will be forbidden by validateXmlInternal and so the security transgression whilst not ideal
             * is short-lived.
             *
             * To fix the issue we need to refactor validateXMLInternal and move any document/database/collection
             * modification code into storeXMLInternal after the commented out permissions checks below.
             *
             * Noted by Adam Retter 2012-02-01T19:18
             */
           
            /*
            if(info.isCreating()) {
                // create
                *
                if(!getPermissionsNoLock().validate(broker.getSubject(), Permission.WRITE)) {
                    throw new PermissionDeniedException("Permission denied to write collection: " + path);
                }
            } else {
                // update

                final Permission oldDocPermissions = info.getOldDocPermissions();
                if(!((oldDocPermissions.getOwner().getId() != broker.getSubject().getId()) | (oldDocPermissions.validate(broker.getSubject(), Permission.WRITE)))) {
                    throw new PermissionDeniedException("A resource with the same name already exists in the target collection '" + path + "', and you do not have write access on that resource.");
                }
            }
            */

            if(LOG.isDebugEnabled()) {
                LOG.debug("storing document " + document.getDocId() + " ...");
            }

            //Sanity check
            if(!document.getUpdateLock().isLockedForWrite()) {
                LOG.warn("document is not locked for write !");
            }
           
            db.getProcessMonitor().startJob(ProcessMonitor.ACTION_STORE_DOC, document.getFileURI());
            doParse.run();
            broker.storeXMLResource(transaction, document);
            broker.flush();
            broker.closeDocument();
            //broker.checkTree(document);
            LOG.debug("document stored.");
        } finally {
            //This lock has been acquired in validateXMLResourceInternal()
            document.getUpdateLock().release(Lock.WRITE_LOCK);
            broker.getBrokerPool().getProcessMonitor().endJob();
        }
        setCollectionConfigEnabled(true);
        broker.deleteObservers();
       
        if(info.isCreating()) {
            info.getTriggers().afterCreateDocument(broker, transaction, document);
        } else {
            info.getTriggers().afterUpdateDocument(broker, transaction, document);
        }
       
        db.getNotificationService().notifyUpdate(document, (info.isCreating() ? UpdateListener.ADD : UpdateListener.UPDATE));
        //Is it a collection configuration file ?
        final XmldbURI docName = document.getFileURI();
        //WARNING : there is no reason to lock the collection since setPath() is normally called in a safe way
        //TODO: *resolve* URI against CollectionConfigurationManager.CONFIG_COLLECTION_URI
        if (getURI().startsWith(XmldbURI.CONFIG_COLLECTION_URI)
View Full Code Here

     */
    private IndexInfo validateXMLResourceInternal(final Txn transaction, final DBBroker broker, final XmldbURI docUri, final CollectionConfiguration config, final ValidateBlock doValidate) throws EXistException, PermissionDeniedException, TriggerException, SAXException, LockException, IOException {
        //Make the necessary operations if we process a collection configuration document
        checkConfigurationDocument(transaction, broker, docUri);
       
        final Database db = broker.getBrokerPool();
       
        if (db.isReadOnly()) {
            throw new PermissionDeniedException("Database is read-only");
        }
       
        DocumentImpl oldDoc = null;
        boolean oldDocLocked = false;
        try {
            db.getProcessMonitor().startJob(ProcessMonitor.ACTION_VALIDATE_DOC, docUri);
            getLock().acquire(Lock.WRITE_LOCK);  
           
            DocumentImpl document = new DocumentImpl((BrokerPool) db, this, docUri);
            oldDoc = documents.get(docUri.getRawCollectionPath());
            checkPermissionsForAddDocument(broker, oldDoc);
            checkCollectionConflict(docUri);
            manageDocumentInformation(oldDoc, document);
            final Indexer indexer = new Indexer(broker, transaction);
           
            final IndexInfo info = new IndexInfo(indexer, config);
            info.setCreating(oldDoc == null);
            info.setOldDocPermissions(oldDoc != null ? oldDoc.getPermissions() : null);
            indexer.setDocument(document, config);
            addObserversToIndexer(broker, indexer);
            indexer.setValidating(true);
           
            if(CollectionConfiguration.DEFAULT_COLLECTION_CONFIG_FILE_URI.equals(docUri)) {
                // we are updating collection.xconf. Notify configuration manager
                //CollectionConfigurationManager confMgr = broker.getBrokerPool().getConfigurationManager();
                //confMgr.invalidateAll(getURI());
                setCollectionConfigEnabled(false);
            }
           
            final DocumentTriggers trigger = new DocumentTriggers(broker, indexer, this, isTriggersEnabled() ? config : null);
            trigger.setValidating(true);
           
            info.setTriggers(trigger);

            if(oldDoc == null) {
                trigger.beforeCreateDocument(broker, transaction, getURI().append(docUri));
            } else {
                trigger.beforeUpdateDocument(broker, transaction, oldDoc);
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Scanning document " + getURI().append(docUri));
            }
           
            doValidate.run(info);
            // new document is valid: remove old document
            if (oldDoc != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("removing old document " + oldDoc.getFileURI());
                }
                oldDoc.getUpdateLock().acquire(Lock.WRITE_LOCK);
                oldDocLocked = true;
                if (oldDoc.getResourceType() == DocumentImpl.BINARY_FILE) {
                    //TODO : use a more elaborated method ? No triggers...
                    broker.removeBinaryResource(transaction, (BinaryDocument) oldDoc);
                    documents.remove(oldDoc.getFileURI().getRawCollectionPath());
                    //This lock is released in storeXMLInternal()
                    //TODO : check that we go until there to ensure the lock is released
//                    if (transaction != null)
//                      transaction.acquireLock(document.getUpdateLock(), Lock.WRITE_LOCK);
//                  else
                    document.getUpdateLock().acquire(Lock.WRITE_LOCK);
                   
                    document.setDocId(broker.getNextResourceId(transaction, this));
                    addDocument(transaction, broker, document);
                } else {
                    //TODO : use a more elaborated method ? No triggers...
                    broker.removeXMLResource(transaction, oldDoc, false);
                    oldDoc.copyOf(document, true);
                    indexer.setDocumentObject(oldDoc);
                    //old has become new at this point
                    document = oldDoc;
                    oldDocLocked = false;   
                }
                if (LOG.isDebugEnabled()) {
                    LOG.debug("removed old document " + oldDoc.getFileURI());
                }
            } else {
                //This lock is released in storeXMLInternal()
                //TODO : check that we go until there to ensure the lock is released
//              if (transaction != null)
//                  transaction.acquireLock(document.getUpdateLock(), Lock.WRITE_LOCK);
//              else
                document.getUpdateLock().acquire(Lock.WRITE_LOCK);
             
                document.setDocId(broker.getNextResourceId(transaction, this));
                addDocument(transaction, broker, document);
            }
           
            trigger.setValidating(false);

            return info;
        } finally {
            if (oldDoc != null && oldDocLocked) {
                oldDoc.getUpdateLock().release(Lock.WRITE_LOCK);
            }
            getLock().release(Lock.WRITE_LOCK);
           
            db.getProcessMonitor().endJob();
        }
    }
View Full Code Here

        return new BinaryDocument(broker.getBrokerPool(), this, docUri);
    }

    // Streaming
    public BinaryDocument addBinaryResource(final Txn transaction, final DBBroker broker, final BinaryDocument blob, final InputStream is, final String mimeType, final long size, final Date created, final Date modified) throws EXistException, PermissionDeniedException, LockException, TriggerException, IOException {
        final Database db = broker.getBrokerPool();
        if (db.isReadOnly()) {
            throw new PermissionDeniedException("Database is read-only");
        }
        final XmldbURI docUri = blob.getFileURI();
        //TODO : move later, i.e. after the collection lock is acquired ?
        final DocumentImpl oldDoc = getDocument(broker, docUri);
        try {
            db.getProcessMonitor().startJob(ProcessMonitor.ACTION_STORE_BINARY, docUri);
            getLock().acquire(Lock.WRITE_LOCK);
            checkPermissionsForAddDocument(broker, oldDoc);
            checkCollectionConflict(docUri);
            manageDocumentInformation(oldDoc, blob);
            final DocumentMetadata metadata = blob.getMetadata();
View Full Code Here

  protected static StringBuilder getPropertyString(Variable variable, XQueryContext context) {
        Sequence value = variable.getValue();
       
        DBBroker broker = null;

        Database db = context.getDatabase();
        try {
          broker = db.getBroker();
          Serializer serializer = broker.getSerializer();
          serializer.reset();
 
          try {
            StringBuilder property = new StringBuilder();
              if (value.hasOne()) {
                  String strVal = getPropertyValue(value.itemAt(0), serializer);
                  String type = Type.subTypeOf(value.getItemType(), Type.NODE) ? "node" :
                      Type.getTypeName(value.getItemType());
                  property.append("<property name=\"");
                  property.append(variable.getQName().toString());
                  property.append("\" fullname=\"");
                  property.append(variable.getQName().toString());
                  property.append("\" type=\"");
                  property.append(type);
                  property.append("\" size=\"");
                  property.append(strVal.length());
                  property.append("\" encoding=\"none\">");
                  property.append(strVal);
                  property.append("</property>");
              } else {
                property.append("<property name=\"");
                property.append(variable.getQName().toString());
                property.append("\" fullname=\"");
                property.append(variable.getQName().toString());
                property.append("\" type=\"array\" children=\"true\" numchildren=\"");
                property.append(value.getItemCount());
                property.append("\">");
                  int idx = 0;
                  for (SequenceIterator si = value.iterate(); si.hasNext(); idx++) {
                      Item item = si.nextItem();
                      String strVal = getPropertyValue(item, serializer);
                      String type = Type.subTypeOf(value.getItemType(), Type.NODE) ? "xs:string" :
                          Type.getTypeName(value.getItemType());
                      property.append("<property name=\"");
                      property.append(idx);
                      property.append("\" type=\"");
                      property.append(type);
                      property.append("\" size=\"");
                      property.append(strVal.length());
                      property.append("\" encoding=\"none\">");
                      property.append(strVal);
                      property.append("</property>");
                  }
                  property.append("</property>");
              }
              return property;
          } catch (SAXException e) {
              e.printStackTrace();
          } catch (XPathException e) {
              e.printStackTrace();
          }
        } catch (EXistException e) {
      e.printStackTrace();
    } finally {
          db.release(broker);
        }
        return null;
    }
View Full Code Here

TOP

Related Classes of org.exist.Database

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.