Package org.exist.dom

Examples of org.exist.dom.ElementImpl


     * @param  currentPath  DOCUMENT ME!
     */
    private void endNode( int nodeNr, NodePath currentPath )
    {
        if( doc.nodeKind[nodeNr] == Node.ELEMENT_NODE ) {
            final ElementImpl last = stack.pop();
            broker.endElement( last, currentPath, null );
            currentPath.removeLastComponent();
            setPrevious( last );
        }
    }
View Full Code Here


                final StoredNode ql[] = selectAndLock(transaction, inSeq);
                final IndexListener listener = new IndexListener(ql);
                TextImpl text;
                AttrImpl attribute;
                ElementImpl parent;
                for (int i = 0; i < ql.length; i++) {
                    final StoredNode node = ql[i];
                    final DocumentImpl doc = (DocumentImpl)node.getOwnerDocument();
                    if (!doc.getPermissions().validate(context.getUser(),
                            Permission.WRITE)){
                            throw new XPathException(this, "User '" + context.getSubject().getName() + "' does not have permission to write to the document '" + doc.getDocumentURI() + "'!");
                    }
                    doc.getMetadata().setIndexListener(listener);
                                       
                    //update the document
                    switch (node.getNodeType())
                    {
                        case Node.ELEMENT_NODE:
                final NodeListImpl content = new NodeListImpl();
                for (final SequenceIterator j = contentSeq.iterate(); j.hasNext(); ) {
                  final Item next = j.nextItem();
                  if (Type.subTypeOf(next.getType(), Type.NODE))
                    {content.add(((NodeValue)next).getNode());}
                  else {
                    text = new TextImpl(next.getStringValue());
                    content.add(text);
                  }
                }
                            ((ElementImpl) node).update(transaction, content);
                            break;
                        case Node.TEXT_NODE:
                            parent = (ElementImpl) node.getParentNode();
                          text = new TextImpl(contentSeq.getStringValue());
                            text.setOwnerDocument(doc);
                            parent.updateChild(transaction, node, text);
                            break;
                        case Node.ATTRIBUTE_NODE:
                            parent = (ElementImpl) node.getParentNode();
                            if (parent == null) {
                                LOG.warn("parent node not found for "
                                        + node.getNodeId());
                                break;
                            }
                            final AttrImpl attr = (AttrImpl) node;
                            attribute = new AttrImpl(attr.getQName(), contentSeq.getStringValue(), context.getBroker().getBrokerPool().getSymbols());
                            attribute.setOwnerDocument(doc);
                            parent.updateChild(transaction, node, attribute);
                            break;
                        default:
                            throw new XPathException(this, "unsupported node-type");
                    }
                    doc.getMetadata().clearIndexListener();
View Full Code Here

            final IndexListener listener = new IndexListener(ql);
            final NotificationService notifier = context.getBroker().getBrokerPool().getNotificationService();
            Item temp;
            TextImpl text;
            AttrImpl attribute;
            ElementImpl parent;
            for (int i = 0; i < ql.length; i++) {
                final StoredNode node = ql[i];
                final DocumentImpl doc = (DocumentImpl)node.getOwnerDocument();
                if (!doc.getPermissions().validate(context.getUser(), Permission.WRITE)) {
                        throw new PermissionDeniedException("User '" + context.getSubject().getName() + "' does not have permission to write to the document '" + doc.getDocumentURI() + "'!");
                }
                doc.getMetadata().setIndexListener(listener);
               
                //update the document
                parent = (ElementImpl) node.getParentStoredNode();
                if (parent == null)
                    {throw new XPathException(this, "The root element of a document can not be replaced with 'update replace'. " +
                            "Please consider removing the document or use 'update value' to just replace the children of the root.");}
                switch (node.getNodeType()) {
                    case Node.ELEMENT_NODE:
                        temp = contentSeq.itemAt(0);
            if (!Type.subTypeOf(temp.getType(), Type.NODE))
              {throw new XPathException(this,
                  Messages.getMessage(Error.UPDATE_REPLACE_ELEM_TYPE,
                      Type.getTypeName(temp.getType())));}
                        parent.replaceChild(transaction, ((NodeValue)temp).getNode(), node);
                        break;
                    case Node.TEXT_NODE:
                        text = new TextImpl(contentSeq.getStringValue());
                        text.setOwnerDocument(doc);
                        parent.updateChild(transaction, node, text);
                        break;
                    case Node.ATTRIBUTE_NODE:
                        final AttrImpl attr = (AttrImpl) node;
                        attribute = new AttrImpl(attr.getQName(), contentSeq.getStringValue(), context.getBroker().getBrokerPool().getSymbols());
                        attribute.setOwnerDocument(doc);
                        parent.updateChild(transaction, node, attribute);
                        break;
                    default:
                        throw new EXistException("unsupported node-type");
                }
                doc.getMetadata().clearIndexListener();
View Full Code Here

                   
                    //update the document
                    parent = (NodeImpl) node.getParentNode();
                    switch (node.getNodeType()) {
                        case Node.ELEMENT_NODE:
                            final ElementImpl newElem = new ElementImpl((ElementImpl) node);
                            newElem.setNodeName(newQName, context.getBroker().getBrokerPool().getSymbols());
                            parent.updateChild(transaction, node, newElem);
                            break;
                        case Node.ATTRIBUTE_NODE:
                            final AttrImpl newAttr = new AttrImpl((AttrImpl) node);
                            newAttr.setNodeName(newQName, context.getBroker().getBrokerPool().getSymbols());
View Full Code Here

        }
        index.updateStats(perDocGuide);
    }

    private void updateDocument(DBBroker broker, DocumentImpl doc) {
        final ElementImpl root = (ElementImpl) doc.getDocumentElement();
        try {
            final NodePath path = new NodePath();
            final Stack<NodeStats> stack = new Stack<NodeStats>();
            QName qname;
            final EmbeddedXMLStreamReader reader = broker.getXMLStreamReader(root, false);
View Full Code Here

        }

        try {
          // get the feed
          LOG.debug("Acquiring lock on feed document...");
          final ElementImpl feedRoot = (ElementImpl) feedDoc.getDocumentElement();

          // Lock the feed
          feedDoc.getUpdateLock().acquire(Lock.WRITE_LOCK);

          // Append the entry
          collection = broker.getOrCreateCollection(transaction, pathUri.append(ENTRY_COLLECTION_URI));
          setPermissions(broker, root, collection);
          broker.saveCollection(transaction, collection);
          final XmldbURI entryURI = entryURI(uuid);
          final DocumentImpl entryDoc = collection.getDocument(broker, entryURI);
          if (entryDoc != null) {
            throw new PermissionDeniedException("Entry with " + id
                + " already exists.");
          }
          final IndexInfo info = collection.validateXMLResource(transaction, broker, entryURI, doc);
          setPermissions(broker, root, info.getDocument());
          // TODO : We should probably unlock the collection here
          collection.store(transaction, broker, info, doc, false);

          // Update the updated element
          DOMDB.replaceTextElement(transaction, feedRoot,
              Atom.NAMESPACE_STRING, "updated", currentDateTime,
              true);

          // Store the changes
          LOG.debug("Storing change...");
          broker.storeXMLResource(transaction, feedDoc);
          transact.commit(transaction);

          LOG.debug("Done!");

          //XXX: response outside of try-block
          response.setStatusCode(201);
          response.setHeader("Location", request.getModuleBase()
              + request.getPath() + "?id=" + id);
          getEntryById(broker, request.getPath(), id, response);
          /*
           * response.setContentType(Atom.MIME_TYPE+"; charset="+charset
           * ); OutputStreamWriter w = new
           * OutputStreamWriter(response.getOutputStream(),charset);
           * Transformer identity =
           * TransformerFactory.newInstance().newTransformer();
           * identity.transform(new DOMSource(doc),new
           * StreamResult(w)); w.flush(); w.close();
           */
        } catch (final IOException ex) {
          transact.abort(transaction);
          throw new EXistException("IO error: " + ex.getMessage(), ex);
        } catch (final TriggerException ex) {
          transact.abort(transaction);
          throw new EXistException("Trigger failed: "
              + ex.getMessage(), ex);
        } catch (final SAXException ex) {
          transact.abort(transaction);
          throw new EXistException("SAX error: " + ex.getMessage(),
              ex);
        } catch (final LockException ex) {
          transact.abort(transaction);
          throw new EXistException("Cannot acquire write lock.", ex);
          /*
           * } catch (IOException ex) { throw new
           * EXistException("Internal error while serializing result."
           * ,ex); } catch (TransformerException ex) { throw new
           * EXistException("Serialization error.",ex);
           */
        } finally {
                    transact.close(transaction);
          if (feedDoc != null)
            {feedDoc.getUpdateLock().release(Lock.WRITE_LOCK);}
        }
      } else {
        throw new BadRequestException(
            "Unexpected element: {http://www.w3.org/2005/Atom}" + root.getLocalName());
      }

    } else {
      if (collection == null)
        {throw new BadRequestException("Collection " + request.getPath() + " does not exist.");}

      final DocumentImpl feedDoc = collection.getDocument(broker, FEED_DOCUMENT_URI);
      if (feedDoc == null)
        {throw new BadRequestException("Feed at " + request.getPath() + " does not exist.");}

      if (!feedDoc.getPermissions().validate(broker.getSubject(), Permission.WRITE))
        {throw new PermissionDeniedException(
            "Permission denied to update feed " + collection.getURI());}

      String filename = request.getHeader("Slug");
      if (filename == null) {
        final String ext = MimeTable.getInstance().getPreferredExtension(mime);
        int count = 1;
        while (filename == null) {
          filename = "resource" + count + ext;
         
          if (collection.getDocument(broker, XmldbURI.create(filename)) != null)
            {filename = null;}

          count++;
        }
      }

      final TransactionManager transact = broker.getBrokerPool().getTransactionManager();
      final Txn transaction = transact.beginTransaction();
      try {
        final XmldbURI docUri = XmldbURI.create(filename);
        if (collection.getDocument(broker, docUri) != null) {
          transact.abort(transaction);
          throw new BadRequestException("Resource " + docUri + " already exists in collection " + pathUri);
        }

        final File tempFile = storeInTemporaryFile(request.getInputStream(), request.getContentLength());

        if (mime.isXMLType()) {
          InputStream is = new FileInputStream(tempFile);
         
          final IndexInfo info = collection.validateXMLResource(
              transaction, broker, docUri,
              new InputSource(new InputStreamReader(is, charset)));
         
          is.close();
          info.getDocument().getMetadata().setMimeType(contentType);
          is = new FileInputStream(tempFile);
         
          collection.store(transaction, broker, info,
              new InputSource(new InputStreamReader(is, charset)), false);
         
          is.close();
        } else {
          final FileInputStream is = new FileInputStream(tempFile);
          collection.addBinaryResource(transaction, broker, docUri, is, contentType, tempFile.length());
          is.close();
        }

        try {
          LOG.debug("Acquiring lock on feed document...");
          feedDoc.getUpdateLock().acquire(Lock.WRITE_LOCK);
         
          String title = request.getHeader("Title");
          if (title == null)
            {title = filename;}

          final String created = DateFormatter.toXSDDateTime(new Date());
          final ElementImpl feedRoot = (ElementImpl) feedDoc.getDocumentElement();
          DOMDB.replaceTextElement(transaction, feedRoot, Atom.NAMESPACE_STRING, "updated", created, true);
          final String uuid = UUIDGenerator.getUUID();
          final String id = "urn:uuid:" + uuid;
          final Element mediaEntry = generateMediaEntry(id, created, title, filename, mime.getName());

View Full Code Here

        final TransactionManager transact = broker.getBrokerPool().getTransactionManager();
        final Txn transaction = transact.beginTransaction();
        try {
          feedDoc.getUpdateLock().acquire(Lock.WRITE_LOCK);
          final ElementImpl feedRoot = (ElementImpl) feedDoc.getDocumentElement();

          // Modify the feed by merging the new feed-level elements
          mergeFeed(broker, transaction, feedRoot, root, DateFormatter.toXSDDateTime(new Date()));

          // Store the feed
View Full Code Here

      // Remove the entry
      entryCollection.removeXMLResource(transaction, broker, entryURI);

      // Update the feed time
      final ElementImpl feedRoot = (ElementImpl) feedDoc.getDocumentElement();
      DOMDB.replaceTextElement(transaction, feedRoot,
          Atom.NAMESPACE_STRING, "updated", currentDateTime, true);

      // Store the change on the feed
      LOG.debug("Storing change...");
View Full Code Here

   /** Creates a new instance of DOM */
   private DOMDB() {
   }
  
   public static Element replaceTextElement(Txn txn,ElementImpl parent,String namespaceName,String localName,String value,boolean firstChild) {
      ElementImpl textE = (ElementImpl)DOM.findChild(parent,namespaceName,localName);
      if (textE==null) {
         textE = (ElementImpl)parent.getOwnerDocument().createElementNS(namespaceName,localName);
         final NodeListImpl nl = new NodeListImpl(1);
         nl.add(textE);
         if (firstChild) {
            parent.insertAfter(txn,nl,parent.getFirstChild());
         } else {
            parent.appendChildren(txn,nl,-1);
         }
      }
      DOMDB.removeChildren(txn,textE);
      textE.appendChild(parent.getOwnerDocument().createTextNode(value));
      return textE;
   }
View Full Code Here

TOP

Related Classes of org.exist.dom.ElementImpl

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.