Package org.exist.util

Examples of org.exist.util.MimeType


   
    final XmldbURI pathUri = XmldbURI.create(request.getPath());
    String contentType = request.getHeader("Content-Type");
    String charset = getContext().getDefaultCharset();

    MimeType mime = MimeType.BINARY_TYPE;
    if (contentType != null) {
      final int semicolon = contentType.indexOf(';');
      if (semicolon > 0) {
        contentType = contentType.substring(0, semicolon).trim();
      }
      mime = MimeTable.getInstance().getContentType(contentType);
      if (mime == null) {
        mime = MimeType.BINARY_TYPE;
      }
      final int equals = contentType.indexOf('=', semicolon);
      if (equals > 0) {
        final String param = contentType.substring(semicolon + 1, equals)
            .trim();
        if (param.compareToIgnoreCase("charset=") == 0) {
          charset = param.substring(equals + 1).trim();
        }
      }
    }

    final String currentDateTime = DateFormatter.toXSDDateTime(new Date());

    Collection collection = broker.getCollection(pathUri);

    if (mime.getName().equals(Atom.MIME_TYPE)) {
      final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      docFactory.setNamespaceAware(true);
      DocumentBuilder docBuilder = null;
      Document doc = null;
      try {
        final InputSource src = new InputSource(
            new InputStreamReader(request.getInputStream(), charset)
        );
        docBuilder = docFactory.newDocumentBuilder();
        doc = docBuilder.parse(src);
      } catch (final IOException e) {
        LOG.warn(e);
        throw new BadRequestException(e.getMessage());
      } catch (final SAXException e) {
        LOG.warn(e);
        throw new BadRequestException(e.getMessage());
      } catch (final ParserConfigurationException e) {
        LOG.warn(e);
        throw new BadRequestException(e.getMessage());
      }

      final Element root = doc.getDocumentElement();
      final 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 ("feed".equals(root.getLocalName())) {
        DocumentImpl feedDoc = null;
        final TransactionManager transact = broker.getBrokerPool().getTransactionManager();
        final 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);
            setPermissions(broker, root, collection);
            broker.saveCollection(transaction, collection);
          }

          final String id = UUIDGenerator.getUUID();
          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 feed.");
          }
          editLink = doc.createElementNS(Atom.NAMESPACE_STRING, "link");
          editLink.setAttribute("rel", "edit");
          editLink.setAttribute("type", Atom.MIME_TYPE);
          editLink.setAttribute("href", "#");
          root.appendChild(editLink);

          Element selfLink = findLink(root, "self");
          if (selfLink != null) {
            throw new BadRequestException(
                "A self link relation cannot be specified in the feed.");
          }
          selfLink = doc.createElementNS(Atom.NAMESPACE_STRING, "link");
          selfLink.setAttribute("rel", "self");
          selfLink.setAttribute("type", Atom.MIME_TYPE);
          selfLink.setAttribute("href", "#");
          root.appendChild(selfLink);

          final IndexInfo info = collection.validateXMLResource(transaction, broker, FEED_DOCUMENT_URI, doc);
          setPermissions(broker, root, info.getDocument());
          // TODO : We should probably unlock the collection here
          collection.store(transaction, broker, info, doc, false);
          transact.commit(transaction);
          response.setStatusCode(204);
          response.setHeader("Location", request.getModuleBase() + request.getPath());

        } 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);
        } finally {
                    transact.close(transaction);
                }
      } else if ("entry".equals(root.getLocalName())) {

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

        LOG.debug("Adding entry to " + request.getPath());
        DocumentImpl feedDoc = null;
        feedDoc = collection.getDocument(broker, FEED_DOCUMENT_URI);

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

        final TransactionManager transact = broker.getBrokerPool().getTransactionManager();
        final Txn transaction = transact.beginTransaction();
        final String uuid = UUIDGenerator.getUUID();
        final String id = "urn:uuid:" + uuid;
        final 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");
        final 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);
        final 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...");
          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());

          collection = broker.getOrCreateCollection(transaction, pathUri.append(ENTRY_COLLECTION_URI));
          broker.saveCollection(transaction, collection);
          final XmldbURI entryURI = entryURI(uuid);

View Full Code Here


   
    final XmldbURI pathUri = XmldbURI.create(request.getPath());
    String contentType = request.getHeader("Content-Type");
    String charset = getContext().getDefaultCharset();

    MimeType mime = MimeType.BINARY_TYPE;
    if (contentType != null) {
      final int semicolon = contentType.indexOf(';');
      if (semicolon > 0) {
        contentType = contentType.substring(0, semicolon).trim();
      }

      mime = MimeTable.getInstance().getContentType(contentType);
      if (mime == null) {
        mime = MimeType.BINARY_TYPE;
      }

      final int equals = contentType.indexOf('=', semicolon);
      if (equals > 0) {
        final String param = contentType.substring(semicolon + 1, equals)
            .trim();
        if (param.compareToIgnoreCase("charset=") == 0) {
          charset = param.substring(equals + 1).trim();
        }
      }
    }

    final String currentDateTime = DateFormatter.toXSDDateTime(new Date());

    Collection collection = broker.getCollection(pathUri);

    if (mime.getName().equals(Atom.MIME_TYPE)) {
      final DocumentBuilderFactory docFactory = DocumentBuilderFactory
          .newInstance();
      docFactory.setNamespaceAware(true);
      DocumentBuilder docBuilder = null;
      Document doc = null;
      try {
        final InputSource src = new InputSource(
            new InputStreamReader(request.getInputStream(), charset));
       
        docBuilder = docFactory.newDocumentBuilder();
        doc = docBuilder.parse(src);
      } catch (final IOException e) {
        LOG.warn(e);
        throw new BadRequestException(e.getMessage());
      } catch (final SAXException e) {
        LOG.warn(e);
        throw new BadRequestException(e.getMessage());
      } catch (final ParserConfigurationException e) {
        LOG.warn(e);
        throw new BadRequestException(e.getMessage());
      }

      final Element root = doc.getDocumentElement();
      final 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 ("feed".equals(root.getLocalName())) {
        DocumentImpl feedDoc = collection.getDocument(broker, FEED_DOCUMENT_URI);
        if (feedDoc == null)
          {throw new BadRequestException("Collection at "
              + request.getPath() + " does not exist.");}

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

        if (DOM.findChild(root, Atom.NAMESPACE_STRING, "title") == null)
          {throw new BadRequestException(
              "The feed metadata sent does not contain a title.");}

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

        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
          broker.storeXMLResource(transaction, feedDoc);
          transact.commit(transaction);
          response.setStatusCode(204);

        } catch (final LockException ex) {
          transact.abort(transaction);
          throw new EXistException("Cannot acquire write lock.", ex);
        } catch (final RuntimeException ex) {
          transact.abort(transaction);
          throw ex;
        } finally {
                    transact.close(transaction);
          if (feedDoc != null)
            {feedDoc.getUpdateLock().release(Lock.WRITE_LOCK);}
        }

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

        final String id = request.getParameter("id");
        if (id == null)
          {throw new BadRequestException(
              "The 'id' parameter for the entry is missing.");}

        LOG.debug("Updating entry " + id + " in collection " + request.getPath());
        DocumentImpl feedDoc = null;
        DocumentImpl entryDoc = null;
        final TransactionManager transact = broker.getBrokerPool().getTransactionManager();
        final Txn transaction = transact.beginTransaction();

        try {
          // Get the feed
          LOG.debug("Acquiring lock on feed document...");
          feedDoc = collection.getDocument(broker, FEED_DOCUMENT_URI);
          if (!feedDoc.getPermissions().validate(broker.getSubject(), Permission.WRITE))
            {throw new PermissionDeniedException(
                "Permission denied to update feed "
                    + collection.getURI());}
         
          feedDoc.getUpdateLock().acquire(Lock.WRITE_LOCK);

          // Find the entry
          final String uuid = id.substring(9);
          collection = broker.getCollection(pathUri.append(ENTRY_COLLECTION_URI));
          final XmldbURI entryURI = entryURI(uuid);
          entryDoc = collection.getDocument(broker, entryURI);
          if (entryDoc == null)
            {throw new BadRequestException(
                "Cannot find entry with id " + id);}

          // Lock the entry
          entryDoc.getUpdateLock().acquire(Lock.WRITE_LOCK);

          final Element entry = entryDoc.getDocumentElement();

          mergeEntry(transaction, (ElementImpl) entry, root, currentDateTime);

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

          // Store the feed
          broker.storeXMLResource(transaction, feedDoc);
          broker.storeXMLResource(transaction, entryDoc);
          transact.commit(transaction);

          // Send back the changed entry
          response.setStatusCode(200);
          getEntryById(broker, request.getPath(), id, response);
          /*
           * response.setStatusCode(200);
           * response.setContentType(Atom.
           * MIME_TYPE+"; charset="+charset); OutputStreamWriter w =
           * new
           * OutputStreamWriter(response.getOutputStream(),charset);
           * Transformer identity =
           * TransformerFactory.newInstance().newTransformer();
           * identity.transform(new DOMSource(entry),new
           * StreamResult(w)); w.flush(); w.close();
           */
        } catch (final LockException ex) {
          transact.abort(transaction);
          throw new EXistException("Cannot acquire write lock.", ex);
          /*
           * } catch (IOException ex) { throw new EXistException(
           * "I/O exception during serialization of entry response."
           * ,ex); } catch (TransformerException ex) { throw new
           * EXistException("Serialization error.",ex);
           */
        } finally {
                    transact.close(transaction);
          if (feedDoc != null)
            {feedDoc.getUpdateLock().release(Lock.WRITE_LOCK);}

          if (entryDoc != null)
            {entryDoc.getUpdateLock().release(Lock.WRITE_LOCK);}
        }

      } else {
        throw new BadRequestException(
            "Unexpected element: {http://www.w3.org/2005/Atom}"
                + root.getLocalName());
      }

    } else {
      final TransactionManager transact = broker.getBrokerPool().getTransactionManager();
      final Txn transaction = transact.beginTransaction();
      try {
        final XmldbURI docUri = pathUri.lastSegment();
        final XmldbURI collUri = pathUri.removeLastSegment();

        if (docUri == null || collUri == null) {
          transact.abort(transaction);
          throw new BadRequestException("The path is not valid: "
              + request.getPath());
        }

        collection = broker.getCollection(collUri);
        if (collection == null) {
          transact.abort(transaction);
          throw new BadRequestException(
              "The collection does not exist: " + collUri);
        }

        if (collection.getDocument(broker, docUri) == null) {
          transact.abort(transaction);
          throw new BadRequestException("Resource " + docUri
              + " does not exist in collection " + collUri);
        }

        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)));
View Full Code Here

        throws XPathException {
        final File baseDir = new File(args[1].getStringValue());
        logger.debug("Loading files from directory: " + baseDir);

        //determine resource type - xml or binary?
        MimeType mimeTypeFromArgs = null;
        if(getSignature().getArgumentCount() > 3 && args[3].hasOne()) {
            final String mimeTypeParam = args[3].getStringValue();
            mimeTypeFromArgs = MimeTable.getInstance().getContentType(mimeTypeParam);
            if (mimeTypeFromArgs == null) {
              throw new XPathException(this, "Unknown mime type specified: " + mimeTypeParam);
            }
        }

        //keep the directory structure?
        boolean keepDirStructure = false;
        if(getSignature().getArgumentCount() >= 5)
            {keepDirStructure = args[4].effectiveBooleanValue();}
       
        final List<String> excludes = new ArrayList<String>();
        if (getSignature().getArgumentCount() == 6) {
          for (final SequenceIterator i = args[5].iterate(); i.hasNext(); ) {
            excludes.add(i.nextItem().getStringValue());
          }
        }
       
        final ValueSequence stored = new ValueSequence();

        //store according to each pattern
        final Sequence patterns = args[2];
        for(final SequenceIterator i = patterns.iterate(); i.hasNext(); )
        {
            //get the files to store
            final String pattern = i.nextItem().getStringValue();
            final File[] files = DirectoryScanner.scanDir(baseDir, pattern);
            logger.debug("Found: " + files.length);
           
            Collection col = collection;
            String relDir, prevDir = null;
           
            for(int j = 0; j < files.length; j++) {
                try {
                    logger.debug(files[j].getAbsolutePath());
                    String relPath = files[j].toString().substring(baseDir.toString().length());
                    final int p = relPath.lastIndexOf(File.separatorChar);
         
                    if (checkExcludes(excludes, relPath))
                      {continue;}
                   
                    if(p >= 0) {
                        relDir = relPath.substring(0, p);
                        relDir = relDir.replace(File.separatorChar, '/');
                    } else {
                        relDir = relPath;
                    }
         
                    if(keepDirStructure && (prevDir == null || (!relDir.equals(prevDir)))) {
                        col = createCollectionPath(collection, relDir);
                        prevDir = relDir;
                    }

                    MimeType mimeType = mimeTypeFromArgs;
                    if (mimeType == null) {
                      mimeType = MimeTable.getInstance().getContentTypeFor(files[j].getName());
                      if (mimeType == null)
                        {mimeType = MimeType.BINARY_TYPE;}
                    }
                   
                    //TODO  : these probably need to be encoded and checked for right mime type
                    final Resource resource = col.createResource(files[j].getName(), mimeType.getXMLDBType());
                    resource.setContent(files[j]);

                    ((EXistResource) resource).setMimeType(mimeType.getName());

                    col.storeResource(resource);

                    //TODO : use dedicated function in XmldbURI
                    stored.add(new StringValue(col.getName() + "/" + resource.getId()));
View Full Code Here

            logger.debug(ex.getMessage());
            throw new XPathException("Invalid path '" + pathParameter + "'");
        }

        // Verify mime-type input
        MimeType newMimeType = null;
        if (args[1].isEmpty()) {
            // No input, use default mimetype
            newMimeType = mimeTable.getContentTypeFor(pathParameter);

            if (newMimeType == null) {
                throw new XPathException("Unable to determine mimetype for '" + pathParameter + "'");
            }

        } else {
            // Mimetype is provided, check if valid
            newMimeType = mimeTable.getContentType(args[1].getStringValue());

            if (newMimeType == null) {
                throw new XPathException("mime-type '" + args[1].getStringValue() + "' is not supported.");
            }
        }

        // Get mime-type of resource
        MimeType currentMimeType = getMimeTypeStoredResource(pathUri);
        if (currentMimeType == null) {
            // stored resource has no mime-type (unexpected situation)
            // fall back to document name
            logger.debug("Resource '" + pathUri + "' has no mime-type, retrieve from document name.");
            currentMimeType = mimeTable.getContentTypeFor(pathUri);
           
            // if extension based lookup still fails
            if (currentMimeType == null) {
                throw new XPathException("Unable to determine mime-type from path '" + pathUri + "'.");
            }           
        }

        // Check if mimeType are equivalent
        // in some cases value null is set, then allow to set to new value (repair action)
        if (newMimeType.isXMLType() != currentMimeType.isXMLType() ) {
            throw new XPathException("New mime-type must be a " + currentMimeType.getXMLDBType() + " mime-type");
        }

        // At this moment it is possible to update the mimetype
        final DBBroker broker = context.getBroker();
        final BrokerPool brokerPool = broker.getBrokerPool();
View Full Code Here

    /**
     * Determine mimetype of currently stored resource. Copied from
     * get-mime-type.
     */
    private MimeType getMimeTypeStoredResource(XmldbURI pathUri) throws XPathException {
        MimeType returnValue = null;
        DocumentImpl doc = null;
        try {
            // relative collection Path: add the current base URI
            pathUri = context.getBaseURI().toXmldbURI().resolveCollectionPath(pathUri);
           
View Full Code Here

                LOG.debug("creating collection " + collUri);
                transaction = transact.beginTransaction();
                collection = broker.getOrCreateCollection(transaction, collUri);
                broker.saveCollection(transaction, collection);
            }
            MimeType mime;
            String contentType = request.getContentType();
            String charset = null;
            if (contentType != null) {
                final int semicolon = contentType.indexOf(';');
                if (semicolon > 0) {
                    contentType = contentType.substring(0, semicolon).trim();
                    final int equals = contentType.indexOf('=', semicolon);
                    if (equals > 0) {
                        final String param = contentType.substring(semicolon + 1,
                                equals).trim();
                        if (param.compareToIgnoreCase("charset=") == 0) {
                            charset = param.substring(equals + 1).trim();
                        }
                    }
                }
                mime = MimeTable.getInstance().getContentType(contentType);
            } else {
                mime = MimeTable.getInstance().getContentTypeFor(docUri);
                if (mime != null) {
                    contentType = mime.getName();
                }
            }
            if (mime == null) {
                mime = MimeType.BINARY_TYPE;
                contentType = mime.getName();
            }

            if (transaction == null) {
                transaction = transact.beginTransaction();
            }

            if (mime.isXMLType()) {
                final InputSource vtfis = new VirtualTempFileInputSource(vtempFile, charset);

                final IndexInfo info = collection.validateXMLResource(transaction, broker, docUri, vtfis);
                info.getDocument().getMetadata().setMimeType(contentType);
                collection.store(transaction, broker, info, vtfis, false);
View Full Code Here

                {throw new IOException("Resource "+collectionUri.toString()+" is not a collection.");}
           
            if(collection.hasChildCollection(broker, documentUri))
                {throw new IOException("Resource "+documentUri.toString()+" is a collection.");}
           
            MimeType mime = MimeTable.getInstance().getContentTypeFor(documentUri);
            String contentType=null;
            if (mime != null){
                contentType = mime.getName();
            } else {
                mime = MimeType.BINARY_TYPE;
            }
           
            transact = pool.getTransactionManager();
            txn = transact.beginTransaction();
           
            if(mime.isXMLType()) {
                LOG.debug("storing XML resource");
                final InputSource inputsource = new InputSource(tmp.toURI().toASCIIString());
                final IndexInfo info = collection.validateXMLResource(txn, broker, documentUri, inputsource);
                final DocumentImpl doc = info.getDocument();
                doc.getMetadata().setMimeType(contentType);
View Full Code Here

                config.setBasicPassword(xmldbURL.getPassword());
            }
            client.setConfig(config);

            String contentType=MimeType.BINARY_TYPE.getName();
            final MimeType mime
                    = MimeTable.getInstance().getContentTypeFor(xmldbURL.getDocumentName());
            if (mime != null){
                contentType = mime.getName();
            }
           
            // Initialize xmlrpc parameters
            final List<Object> params = new ArrayList<Object>(5);
            String handle=null;
View Full Code Here

      context.setModuleLoadPath(getContext().getModuleLoadPath());

      String contentType = request.getHeader("Content-Type");
      String charset = getContext().getDefaultCharset();

      MimeType mime = MimeType.XML_TYPE;
      if (contentType != null) {
        final int semicolon = contentType.indexOf(';');
        if (semicolon > 0) {
          contentType = contentType.substring(0, semicolon).trim();
        }
        mime = MimeTable.getInstance().getContentType(contentType);
        final int equals = contentType.indexOf('=', semicolon);
        if (equals > 0) {
          final String param = contentType.substring(semicolon + 1, equals).trim();
          if (param.compareToIgnoreCase("charset=") == 0) {
            charset = param.substring(equals + 1).trim();
          }
        }
      }

      if (!mime.isXMLType() && !mime.equals(xqueryMimeType)) {
        throw new BadRequestException(
            "The xquery mime type is not an XML mime type nor application/xquery");
      }

      CompiledXQuery compiledQuery = null;
View Full Code Here

TOP

Related Classes of org.exist.util.MimeType

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.