Skip to content

Commit

Permalink
🐛 Fix file created in wrong file bucket if bucket name contains .
Browse files Browse the repository at this point in the history
  • Loading branch information
ujibang committed Apr 21, 2021
1 parent 1f99260 commit 01efa4f
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 72 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* =========================LICENSE_END==================================
*/
package org.restheart.mongodb.handlers.files;
package org.restheart.mongodb.db;

import static org.junit.Assert.*;
import org.junit.Rule;
Expand Down Expand Up @@ -59,6 +59,15 @@ public GetFileHandlerTest() {
*/
@Test
public void testExtractBucket() {
assertEquals("mybucket", GetFileBinaryHandler.extractBucketName("mybucket.files"));
assertEquals("mybucket", GridFsDAO.extractBucketName("mybucket.files"));
}

/**
*
*/
@Test
public void testExtractBucketWithDots() {
assertEquals("mybucket.foo", GridFsDAO.extractBucketName("mybucket.foo.files"));
assertEquals("mybucket.foo.bar", GridFsDAO.extractBucketName("mybucket.foo.bar.files"));
}
}
4 changes: 2 additions & 2 deletions mongodb/src/main/java/org/restheart/mongodb/db/GridFsDAO.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ public class GridFsDAO implements GridFsRepository {

private static final String FILENAME = "filename";

private static String extractBucketName(final String collectionName) {
return collectionName.split("\\.")[0];
public static String extractBucketName(final String collectionName) {
return collectionName.substring(0, collectionName.lastIndexOf('.'));
}

private final MongoClient client;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import org.restheart.exchange.MongoResponse;
import org.restheart.handlers.PipelinedHandler;
import org.restheart.mongodb.db.DatabaseImpl;
import org.restheart.mongodb.db.GridFsDAO;
import org.restheart.mongodb.utils.RequestHelper;
import org.restheart.mongodb.utils.ResponseHelper;
import org.restheart.utils.HttpStatus;
Expand Down Expand Up @@ -91,10 +92,9 @@ public void handleRequest(HttpServerExchange exchange) throws Exception {
if (request.isDbMeta()) {
collName = META_COLLNAME;
docId = new BsonString(DB_META_DOCID);
} else if (request.isCollectionMeta()) {
} else if (request.isCollectionMeta() || request.isFilesBucketMeta() || request.isSchemaStoreMeta()) {
collName = META_COLLNAME;
docId = new BsonString(COLL_META_DOCID_PREFIX.concat(
request.getCollectionName()));
docId = new BsonString(COLL_META_DOCID_PREFIX.concat(request.getCollectionName()));
} else {
collName = request.getCollectionName();
docId = request.getDocumentId();
Expand Down Expand Up @@ -134,26 +134,16 @@ public void handleRequest(HttpServerExchange exchange) throws Exception {
}

var cs = request.getClientSession();
var coll = dbsDAO.getCollection(
request.getDBName(),
collName);

BsonDocument document = cs == null
? coll
.find(query)
.projection(fieldsToReturn)
.first()
: coll
.find(cs, query)
.projection(fieldsToReturn)
.first();
var coll = dbsDAO.getCollection(request.getDBName(), collName);

var document = cs == null
? coll.find(query).projection(fieldsToReturn).first()
: coll.find(cs, query).projection(fieldsToReturn).first();

if (document == null) {
String errMsg = request.getDocumentId() == null
? " does not exist"
: " ".concat(BsonUtils.getIdAsString(
request.getDocumentId(), true))
.concat(" does not exist");
: " ".concat(BsonUtils.getIdAsString(request.getDocumentId(), true)).concat(" does not exist");

if (null != request.getType()) {
switch (request.getType()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.restheart.mongodb.db.MongoClientSingleton;
import org.restheart.mongodb.utils.RequestHelper;
import org.restheart.mongodb.utils.ResponseHelper;
import static org.restheart.mongodb.db.GridFsDAO.extractBucketName;
import org.restheart.utils.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -48,21 +49,14 @@ public class GetFileBinaryHandler extends PipelinedHandler {
/**
*
*/
public static final String APPLICATION_OCTET_STREAM
= "application/octet-stream";
public static final String APPLICATION_OCTET_STREAM = "application/octet-stream";

/**
*
*/
public static final String CONTENT_TRANSFER_ENCODING_BINARY
= "binary";
public static final String CONTENT_TRANSFER_ENCODING_BINARY = "binary";

private static final Logger LOGGER
= LoggerFactory.getLogger(GetFileBinaryHandler.class);

static String extractBucketName(final String collectionName) {
return collectionName.split("\\.")[0];
}
private static final Logger LOGGER = LoggerFactory.getLogger(GetFileBinaryHandler.class);

/**
* Creates a new instance of GetFileBinaryHandler
Expand Down Expand Up @@ -97,15 +91,11 @@ public void handleRequest(HttpServerExchange exchange) throws Exception {
}

LOGGER.trace("GET " + exchange.getRequestURL());
final String bucket = extractBucketName(request.getCollectionName());
final var bucket = extractBucketName(request.getCollectionName());

GridFSBucket gridFSBucket = GridFSBuckets.create(MongoClientSingleton.getInstance().getClient()
.getDatabase(request.getDBName()),
bucket);
var gridFSBucket = GridFSBuckets.create(MongoClientSingleton.getInstance().getClient().getDatabase(request.getDBName()), bucket);

GridFSFile dbsfile = gridFSBucket
.find(eq("_id", request.getDocumentId()))
.limit(1).iterator().tryNext();
var dbsfile = gridFSBucket.find(eq("_id", request.getDocumentId())).limit(1).iterator().tryNext();

if (dbsfile == null) {
fileNotFound(request, exchange);
Expand All @@ -120,17 +110,16 @@ private boolean checkEtag(HttpServerExchange exchange, GridFSFile dbsfile) {
if (dbsfile != null) {
Object etag;

if (dbsfile.getMetadata() != null
&& dbsfile.getMetadata().containsKey("_etag")) {
if (dbsfile.getMetadata() != null && dbsfile.getMetadata().containsKey("_etag")) {
etag = dbsfile.getMetadata().get("_etag");
} else {
etag = null;
}

if (etag != null && etag instanceof ObjectId) {
ObjectId _etag = (ObjectId) etag;
var _etag = (ObjectId) etag;

BsonObjectId __etag = new BsonObjectId(_etag);
var __etag = new BsonObjectId(_etag);

// in case the request contains the IF_NONE_MATCH header with the current etag value,
// just return 304 NOT_MODIFIED code
Expand All @@ -151,9 +140,7 @@ private void fileNotFound(
final String errMsg = String.format(
"File with ID <%s> not found", request.getDocumentId());
LOGGER.trace(errMsg);
MongoResponse.of(exchange).setInError(
HttpStatus.SC_NOT_FOUND,
errMsg);
MongoResponse.of(exchange).setInError(HttpStatus.SC_NOT_FOUND, errMsg);
next(exchange);
}

Expand All @@ -167,45 +154,29 @@ private void sendBinaryContent(
LOGGER.trace("Filename = {}", file.getFilename());
LOGGER.trace("Content length = {}", file.getLength());

if (file.getMetadata() != null
&& file.getMetadata().get("contentType") != null) {
response.getHeaders().put(Headers.CONTENT_TYPE,
file.getMetadata().get("contentType").toString());
} else if (file.getMetadata() != null
&& file.getMetadata().get("contentType") != null) {
response.getHeaders().put(Headers.CONTENT_TYPE,
file.getMetadata().get("contentType").toString());
if (file.getMetadata() != null && file.getMetadata().get("contentType") != null) {
response.getHeaders().put(Headers.CONTENT_TYPE, file.getMetadata().get("contentType").toString());
} else if (file.getMetadata() != null && file.getMetadata().get("contentType") != null) {
response.getHeaders().put(Headers.CONTENT_TYPE, file.getMetadata().get("contentType").toString());
} else {
response.getHeaders().put(
Headers.CONTENT_TYPE,
APPLICATION_OCTET_STREAM);
response.getHeaders().put(Headers.CONTENT_TYPE, APPLICATION_OCTET_STREAM);
}

response.getHeaders().put(Headers.CONTENT_LENGTH, file.getLength());

response.getHeaders().put(
Headers.CONTENT_DISPOSITION,
String.format("inline; filename=\"%s\"",
extractFilename(file)));
response.getHeaders().put(Headers.CONTENT_DISPOSITION, String.format("inline; filename=\"%s\"", extractFilename(file)));

response.getHeaders().put(
Headers.CONTENT_TRANSFER_ENCODING,
CONTENT_TRANSFER_ENCODING_BINARY);
response.getHeaders().put(Headers.CONTENT_TRANSFER_ENCODING,CONTENT_TRANSFER_ENCODING_BINARY);

ResponseHelper.injectEtagHeader(exchange, file.getMetadata());

response.setStatusCode(HttpStatus.SC_OK);

response.setCustomerSender(() -> {
if (request.getClientSession() != null) {
gridFSBucket.downloadToStream(
request.getClientSession(),
file.getId(),
exchange.getOutputStream());
gridFSBucket.downloadToStream(request.getClientSession(), file.getId(), exchange.getOutputStream());
} else {
gridFSBucket.downloadToStream(
file.getId(),
exchange.getOutputStream());
gridFSBucket.downloadToStream(file.getId(), exchange.getOutputStream());
}
});
}
Expand Down

0 comments on commit 01efa4f

Please sign in to comment.