DocumentImpl feedDoc = null;
   public void doPost(DBBroker broker,IncomingMessage request,OutgoingMessage response)      throws BadRequestException,PermissionDeniedException,NotFoundException,EXistException   {      XmldbURI pathUri = XmldbURI.create(request.getPath());      String contentType = request.getHeader("Content-Type");      String charset = getContext().getDefaultCharset();            MimeType mime = MimeType.BINARY_TYPE;      if (contentType != null) {         int semicolon = contentType.indexOf(';');         if (semicolon>0) {            contentType = contentType.substring(0,semicolon).trim();         }         mime = MimeTable.getInstance().getContentType(contentType);         int equals = contentType.indexOf('=',semicolon);         if (equals>0) {            String param = contentType.substring(semicolon+1,equals).trim();            if (param.compareToIgnoreCase("charset=")==0) {               charset = param.substring(equals+1).trim();            }         }         if (mime==null) {            mime = MimeType.BINARY_TYPE;         }      }            Collection collection = broker.getCollection(pathUri);            if (mime.getName().equals(Atom.MIME_TYPE)) {         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();         docFactory.setNamespaceAware(true);         DocumentBuilder docBuilder = null;         Document doc = null;         try {            InputSource src = new InputSource(new InputStreamReader(request.getInputStream(),charset));            docBuilder = docFactory.newDocumentBuilder();            doc = docBuilder.parse(src);         } catch (IOException e) {            LOG.warn(e);            throw new BadRequestException(e.getMessage());         } catch (SAXException e) {            LOG.warn(e);            throw new BadRequestException(e.getMessage());         } catch (ParserConfigurationException e) {            LOG.warn(e);            throw new BadRequestException(e.getMessage());         }         Element root = doc.getDocumentElement();         String ns = root.getNamespaceURI();         if (ns==null || !ns.equals(Atom.NAMESPACE_STRING)) {            throw new BadRequestException("Any content posted with the Atom mime type must be in the Atom namespace.");         }         if (root.getLocalName().equals("entry")) {            if (collection == null) {               throw new BadRequestException("Collection "+request.getPath()+" does not exist.");            }            LOG.debug("Adding entry to "+request.getPath());            DocumentImpl feedDoc = null;            TransactionManager transact = broker.getBrokerPool().getTransactionManager();            Txn transaction = transact.beginTransaction();            String id = "urn:uuid:"+UUIDGenerator.getInstance().generateRandomBasedUUID();            String currentDateTime = toXSDDateTime(new Date());            Element publishedE = DOM.replaceTextElement(root,Atom.NAMESPACE_STRING,"published",currentDateTime,true,true);            DOM.replaceTextElement(root,Atom.NAMESPACE_STRING,"updated",currentDateTime,true,true);            DOM.replaceTextElement(root,Atom.NAMESPACE_STRING,"id",id,true,true);            Element editLink = findLink(root,"edit");            Element editLinkSrc = findLink(root,"edit-media");            if (editLink!=null || editLinkSrc!=null) {               throw new BadRequestException("An edit link relation cannot be specified in the entry.");            }            editLink = doc.createElementNS(Atom.NAMESPACE_STRING,"link");            editLink.setAttribute("rel","edit");            editLink.setAttribute("type",Atom.MIME_TYPE);            editLink.setAttribute("href","?id="+id);            Node next = publishedE.getNextSibling();            if (next==null) {               root.appendChild(editLink);            } else {               root.insertBefore(editLink,next);            }            try {               // get the feed               LOG.debug("Acquiring lock on feed document...");               feedDoc = collection.getDocument(broker,FEED_DOCUMENT_URI);               ElementImpl feedRoot = (ElementImpl)feedDoc.getDocumentElement();                              // Lock the feed               feedDoc.getUpdateLock().acquire(Lock.WRITE_LOCK);                              // Append the entry               NodeListImpl nl = new NodeListImpl(1);               nl.add(root);               feedRoot.appendChildren(transaction,nl,-1);                              // 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!");                              response.setStatusCode(201);               response.setHeader("Location",request.getModuleBase()+request.getPath()+"?id="+id);               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 (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 {               if (feedDoc!=null) {                  feedDoc.getUpdateLock().release(Lock.WRITE_LOCK);               }            }         } else if (root.getLocalName().equals("feed")) {            DocumentImpl feedDoc = null;            TransactionManager transact = broker.getBrokerPool().getTransactionManager();            Txn transaction = transact.beginTransaction();            try {               if (collection != null) {                  feedDoc = collection.getDocument(broker,FEED_DOCUMENT_URI);                  if (feedDoc!=null) {                     throw new PermissionDeniedException("Collection at "+request.getPath()+" already exists.");                  }               } else {                  collection = broker.getOrCreateCollection(transaction,pathUri);                  broker.saveCollection(transaction, collection);               }               UUID id = UUIDGenerator.getInstance().generateRandomBasedUUID();               String currentDateTime = toXSDDateTime(new Date());               DOM.replaceTextElement(root,Atom.NAMESPACE_STRING,"updated",currentDateTime,true);               DOM.replaceTextElement(root,Atom.NAMESPACE_STRING,"id","urn:uuid:"+id,true);               Element editLink = findLink(root,"edit");               if (editLink!=null) {                  throw new BadRequestException("An edit link relation cannot be specified in the entry.");               }               editLink = doc.createElementNS(Atom.NAMESPACE_STRING,"link");               editLink.setAttribute("rel","edit");               editLink.setAttribute("type",Atom.MIME_TYPE);               editLink.setAttribute("href","#");               IndexInfo info = collection.validateXMLResource(transaction,broker,FEED_DOCUMENT_URI,doc);               collection.store(transaction,broker,info,doc,false);               transact.commit(transaction);               response.setStatusCode(204);               response.setHeader("Location",request.getModuleBase()+request.getPath());            } catch (SAXException ex) {               transact.abort(transaction);               throw new EXistException("SAX error: "+ex.getMessage(),ex);            } catch (TriggerException ex) {               transact.abort(transaction);               throw new EXistException("Trigger failed: "+ex.getMessage(),ex);            } catch (LockException ex) {               transact.abort(transaction);               throw new EXistException("Cannot acquire write lock.",ex);            }         } 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.");         }         String filename = request.getHeader("Slug");         if (filename==null) {            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++;            }         }         TransactionManager transact = broker.getBrokerPool().getTransactionManager();         Txn transaction = transact.beginTransaction();         try {            XmldbURI docUri = XmldbURI.create(filename);            if (collection.getDocument(broker,docUri)!=null) {               transact.abort(transaction);               throw new BadRequestException("Resource "+docUri+" already exists in collection "+pathUri);            }                        File tempFile = storeInTemporaryFile(request.getInputStream(),request.getContentLength());                        if (mime.isXMLType()) {               InputStream is = new FileInputStream(tempFile);               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 {               FileInputStream is = new FileInputStream(tempFile);               collection.addBinaryResource(transaction, broker, docUri, is, contentType, (int) tempFile.length());               is.close();            }            DocumentImpl feedDoc = null;            try {               LOG.debug("Acquiring lock on feed document...");               feedDoc = collection.getDocument(broker,FEED_DOCUMENT_URI);               feedDoc.getUpdateLock().acquire(Lock.WRITE_LOCK);               String title = request.getHeader("Title");               if (title==null) {                  title = filename;               }               String created = toXSDDateTime(new Date());               ElementImpl feedRoot = (ElementImpl)feedDoc.getDocumentElement();               DOMDB.replaceTextElement(transaction,feedRoot,Atom.NAMESPACE_STRING,"updated",created,true);               String id = "urn:uuid:"+UUIDGenerator.getInstance().generateRandomBasedUUID();               Element mediaEntry = generateMediaEntry(id,created,title,filename,mime.getName());               DOMDB.appendChild(transaction,feedRoot,mediaEntry);               LOG.debug("Storing change...");               broker.storeXMLResource(transaction, feedDoc);               transact.commit(transaction);               LOG.debug("Done!");               response.setStatusCode(201);               response.setHeader("Location",request.getModuleBase()+request.getPath()+"?id="+id);               response.setContentType(Atom.MIME_TYPE+"; charset="+charset);               OutputStreamWriter w = new OutputStreamWriter(response.getOutputStream(),charset);               Transformer identity = TransformerFactory.newInstance().newTransformer();               identity.transform(new DOMSource(mediaEntry),new StreamResult(w));               w.flush();               w.close();            } catch (ParserConfigurationException ex) {               transact.abort(transaction);               throw new EXistException("DOM implementation is misconfigured.",ex);            } catch (TransformerException ex) {               throw new EXistException("Serialization error.",ex);            } catch (LockException ex) {               transact.abort(transaction);               throw new EXistException("Cannot acquire write lock.",ex);            } finally {               if (feedDoc!=null) {                  feedDoc.getUpdateLock().release(Lock.WRITE_LOCK);               }            }         } catch (IOException ex) {            transact.abort(transaction);            throw new EXistException("I/O error while handling temporary files.",ex);         } catch (SAXParseException e) {            transact.abort(transaction);            throw new BadRequestException("Parsing exception at "                    + e.getLineNumber() + "/" + e.getColumnNumber() + ": "                    + e.toString());         } catch (SAXException e) {            transact.abort(transaction);            Exception o = e.getException();            if (o == null)               o = e;            throw new BadRequestException("Parsing exception: "                    + o.getMessage());         } catch (TriggerException e) {            transact.abort(transaction);            throw new PermissionDeniedException(e.getMessage());         } catch (LockException e) {            transact.abort(transaction);            throw new PermissionDeniedException(e.getMessage());         }      }   }