Example usage for com.mongodb.gridfs GridFSInputFile setContentType

List of usage examples for com.mongodb.gridfs GridFSInputFile setContentType

Introduction

In this page you can find the example usage for com.mongodb.gridfs GridFSInputFile setContentType.

Prototype

public void setContentType(final String contentType) 

Source Link

Document

Sets the content type (MIME type) on the GridFS entry.

Usage

From source file:com.trenako.images.ImagesRepositoryImpl.java

License:Apache License

@Override
public void store(UploadFile file) {
    DBObject metadata = fillMetadata(file.getMetadata());

    GridFSInputFile f = getGridFs().createFile(file.getContent());
    f.setFilename(file.getFilename());/*from   ww w . j a v  a 2 s. co  m*/
    f.setMetaData(metadata);
    f.setContentType(file.getContentType());
    f.save();
}

From source file:controllers.user.UserController.java

/**
 * ??/* w  w  w . java 2s .  c  o m*/
 * 
 * @author Poppy
 * @date 2014-9-29
 * @return
 * @since 1.0
 */
public static Result add() {
    String msg = "";
    UserForm form = new UserForm();
    User user = new User();
    try {
        // ??
        Form<UserForm> userForm = Form.form(UserForm.class);
        form = userForm.bindFromRequest().get();
        // ?cookie??
        Cookie cookie = request().cookie(IContent.VERIFYCODE_COOKIE);
        String cookieValue = (cookie == null) ? "" : cookie.value();
        String verifyCode = form.verifyCode;
        if (!verifyCode.toUpperCase().equals(cookieValue.toUpperCase())) {
            msg = "verifyWrong";
            return ok(register.render(form, msg));
        }
        // 
        FilePart pro = request().body().asMultipartFormData().getFile("productionCertificateUrl");
        FilePart food = request().body().asMultipartFormData().getFile("foodCirculationUrl");
        FilePart bus = request().body().asMultipartFormData().getFile("businessLicenseUrl");
        // ????
        if (EmptyUtil.isNotEmpty(pro)) {
            File proFile = pro.getFile();
            // ?
            String ext = "jpg";
            String proFileExt = pro.getFilename().substring(pro.getFilename().lastIndexOf(".") + 1)
                    .toLowerCase();
            if (!Arrays.<String>asList(ext.split(",")).contains(proFileExt)) {
                msg = "extWrong";
                return ok(register.render(form, msg));
            } else {
                // 
                GridFSInputFile gProFile = PlayJongo.gridfs().createFile(proFile);
                gProFile.setFilename(pro.getFilename());
                gProFile.setContentType(proFileExt);
                gProFile.save();
                user.productionCertificateUrl = "/common/download/" + gProFile.getId();
            }
        } else {
            user.productionCertificateUrl = "";
        }
        // ?????
        if (EmptyUtil.isNotEmpty(food)) {
            File foodFile = food.getFile();
            // ?
            String ext = "jpg";
            String foodFileExt = food.getFilename().substring(food.getFilename().lastIndexOf(".") + 1)
                    .toLowerCase();
            if (!Arrays.<String>asList(ext.split(",")).contains(foodFileExt)) {
                msg = "extWrong";
                return ok(register.render(form, msg));
            } else {
                // 
                GridFSInputFile gFoodFile = PlayJongo.gridfs().createFile(foodFile);
                gFoodFile.setFilename(food.getFilename());
                gFoodFile.setContentType(foodFileExt);
                gFoodFile.save();
                user.foodCirculationUrl = "/common/download/" + gFoodFile.getId();
            }
        } else {
            user.foodCirculationUrl = "";
        }
        // ??
        if (EmptyUtil.isNotEmpty(bus)) {
            File busFile = bus.getFile();
            // ?
            String ext = "jpg";
            String busFileExt = bus.getFilename().substring(bus.getFilename().lastIndexOf(".") + 1)
                    .toLowerCase();
            if (!Arrays.<String>asList(ext.split(",")).contains(busFileExt)) {
                msg = "extWrong";
                return ok(register.render(form, msg));
            } else {
                // 
                GridFSInputFile gBusFile = PlayJongo.gridfs().createFile(busFile);
                gBusFile.setFilename(bus.getFilename());
                gBusFile.setContentType(busFileExt);
                gBusFile.save();
                user.businessLicenseUrl = "/common/download/" + gBusFile.getId();
            }
        } else {
            user.businessLicenseUrl = "";
        }
        // form??
        user.addr = form.addr;
        user.businessLicenseCode = form.businessLicenseCode;
        user.city = form.city;
        user.enterpriseName = form.enterpriseName;
        user.enterprisePrincipal = form.enterprisePrincipal;
        user.enterpriseType = form.enterpriseType;
        user.executiveStandard = form.executiveStandard;
        user.legalPerson = form.legalPerson;
        user.organizationCode = form.organizationCode;
        user.postCode = form.postCode;
        user.productionAddr = form.productionAddr;
        user.province = form.province;
        user.pwd = form.pwd;
        user.qualityPrincipal = form.qualityPrincipal;
        user.qualityAuthorizer = form.qualityAuthorizer;
        user.tel = form.tel;
        user.email = form.email;
        user.productionCertificate = form.productionCertificate;
        user.variety = form.variety;
        user.enterpriseAddr = form.enterpriseAddr;
        user.busiScope = form.busiScope;
        user.busiMod = form.busiMod;
        user.foodCirculation = form.foodCirculation;
        user.approvalFlag = 0;
        user.updateFlag = 0;
        if (form.enterpriseType == 1) {
            user.userName = form.organizationCode;
            // ??
            Long checkResult = User.registerCheck(user.organizationCode);
            if (checkResult == 0) {
                // ?form??
                user.add();
                msg = "success";
            } else {
                msg = "checkWrong";
            }
        } else {
            user.userName = form.foodCirculation;
            // ?????
            Long checkResult = User.registerCheckBis(user.foodCirculation);
            if (checkResult == 0) {
                // ?form??
                user.add();
                msg = "success";
            } else {
                msg = "checkWrong";
            }
        }
    } catch (Exception e) {
        // 
        Logger.error("UserController-add:?", e);
        msg = "error";
    }
    // 
    return ok(register.render(form, msg));
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Saves a file into the current database using the specified <tt>namespace</tt> and <tt>filename</tt>. All files sharing the same 
 * <tt>namespace</tt> and <tt>filename</tt> are considered versions of the same file. So, inserting a new file with an existing 
 * <tt>namespace</tt> and <tt>filename</tt> will create a new entry in the database. The method {@link #readFile(String, String)} will 
 * retrieve the latest version of the file and the method {@link #readFile(String, String)} will remove all the versions of the file. 
 * Other possible options could be to define a unique index in the <tt>files</tt> collection to avoid duplicates (versions) to be 
 * created: <code>createIndex("filename", namespace + ".files");</code>
 * @param namespace - (optional) name space under the file is saved. When nothing specified, the default bucket is used
 * @param filename - filename to be assigned to the file in the database
 * @param file - file to be saved to the database
 * @param metadata - optional file metadata
 * @return the id associated to the file in the collection
 *//*from w w w  .ja va 2  s.c  o  m*/
public String saveFile(final @Nullable String namespace, final String filename, final File file,
        final @Nullable DBObject metadata) {
    checkArgument(isNotBlank(filename), "Uninitialized or invalid filename");
    checkArgument(file != null && file.canRead() && file.isFile(), "Uninitialized or invalid file");
    String objectId = null;
    final String namespace2 = trimToEmpty(namespace);
    final String filename2 = filename.trim();
    if (metadata != null) {
        metadata.removeField(IS_LATEST_VERSION_ATTR);
    }
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final GridFS gfsNs = isNotBlank(namespace2) ? new GridFS(db, namespace2) : new GridFS(db);
    // enforce isolation property: each namespace has its own bucket (encompassing 2 collections: files and chunks) and indexes in the database
    createSparseIndexWithUniqueConstraint(FILE_VERSION_PROP,
            gfsNs.getBucketName() + "." + GRIDFS_FILES_COLLECTION, false);
    // index open access links
    createNonUniqueIndex(FILE_OPEN_ACCESS_LINK_PROP, gfsNs.getBucketName() + "." + GRIDFS_FILES_COLLECTION,
            false);
    try {
        // insert new file/version in the database
        final GridFSInputFile gfsFile = gfsNs.createFile(file);
        gfsFile.setFilename(filename2);
        gfsFile.setContentType(mimeType(file));
        gfsFile.setMetaData(metadata);
        gfsFile.save();
        objectId = ObjectId.class.cast(gfsFile.getId()).toString();
        // unset the latest version in the database
        final GridFSDBFile latestVersion = getLatestVersion(gfsNs, filename2);
        if (latestVersion != null && latestVersion.getMetaData() != null) {
            latestVersion.getMetaData().removeField(IS_LATEST_VERSION_ATTR);
            latestVersion.save();
        }
    } catch (DuplicateKeyException dke) {
        throw new MongoDBDuplicateKeyException(dke.getMessage());
    } catch (IOException ioe) {
        throw new IllegalStateException("Failed to save file", ioe);
    } finally {
        // enforce versioning property by always restoring the latest version in the database
        restoreLatestVersion(gfsNs, filename2);
    }
    return objectId;
}

From source file:fr.wseduc.gridfs.GridFSPersistor.java

License:Apache License

private void persistFile(Message<Buffer> message, byte[] data, JsonObject header) {
    GridFS fs = new GridFS(db, bucket);
    GridFSInputFile f = fs.createFile(data);
    String id = header.getString("_id");
    if (id == null || id.trim().isEmpty()) {
        id = UUID.randomUUID().toString();
    }//from   w w  w  .  jav a2s . c  o  m
    f.setId(id);
    f.setContentType(header.getString("content-type"));
    f.setFilename(header.getString("filename"));
    f.save();
    JsonObject reply = new JsonObject();
    reply.putString("_id", id);
    replyOK(message, reply);
}

From source file:fr.wseduc.resizer.GridFsFileAccess.java

License:Apache License

private GridFSInputFile saveFile(ImageFile img, String id, GridFS fs) {
    GridFSInputFile f = fs.createFile(img.getData());
    f.setId(id);//from  w  w w. j  a va2s .  c o  m
    f.setContentType(img.getContentType());
    f.setFilename(img.getFilename());
    f.save();
    return f;
}

From source file:in.mtap.iincube.mongoapi.GridFsUpdater.java

License:Apache License

@Override
public Boolean execute() {
    GridFS gridFS = getGridFs();/*from   www . j a v a 2s .com*/
    gridFS.remove(filename);
    GridFSInputFile file = gridFS.createFile(stream);
    file.setContentType(contentType);
    file.setFilename(filename);
    file.save();
    return true;
}

From source file:in.mtap.iincube.mongoapi.GridFsWriter.java

License:Apache License

@Override
public Boolean execute() {
    GridFS gridFS = getGridFs();/*from www .j  a  v  a2 s. c o  m*/
    GridFSInputFile file = gridFS.createFile(stream);
    file.setFilename(filename);
    file.setContentType(contentType);
    file.save();
    return false;
}

From source file:io.liveoak.mongo.gridfs.GridFSBlobResource.java

License:Open Source License

private GridFSFilesPathItemResource pushToDB(RequestContext ctx, MediaType contentType, GridFSDBObject fileInfo,
        Supplier contentProvider) throws IOException {
    ObjectId currentId = fileInfo.getId();
    boolean fileExists = currentId != null;

    // update the targeted userspace - hopefully current user has rights to do that
    GridFS gridfs = getUserspace().getGridFS();

    Object content = contentProvider.get();
    GridFSInputFile blob;
    if (fileExists) {
        // here is a time gap when file doesn't exist for a while when being updated.
        // making the switch instantaneous would require another layer of indirection
        // - not using file_id as canonical id, but some other id, mapped to a file.
        // there would still remain a moment between mapping from old file to new file
        // involving two separate file items and a moment in time when during a switch
        // no file would match a filename, nor file id.
        gridfs.remove(currentId);/*from   w  ww .  j  ava 2  s.  co  m*/
    }
    if (content instanceof File) {
        blob = gridfs.createFile((File) content);
    } else if (content instanceof InputStream) {
        blob = gridfs.createFile((InputStream) content);
    } else if (content instanceof ByteBuf) {
        blob = gridfs.createFile(((ByteBuf) content).array());
    } else {
        throw new IllegalArgumentException("Unsupported value supplied: " + content.getClass());
    }

    // meta data
    if (fileExists) {
        blob.setId(currentId);
    }
    blob.setFilename(fileInfo().getString("filename"));
    blob.setContentType(contentType != null ? contentType.toString() : "application/octet-stream");
    blob.put("parent", fileInfo().getParentId());
    blob.save();

    String oid = blob.getId().toString();

    return new GridFSFilesPathItemResource(ctx, getFilesRoot(), oid, new GridFSDBObject(blob),
            GridFSResourcePath.fromContext(ctx));
}

From source file:it.marcoberri.mbfasturl.action.Commons.java

License:Apache License

/**
 * /*w  w  w.j ava 2s . co  m*/
 * @param u
 * @param dimx
 * @param dimy
 * @return
 * @throws WriterException
 * @throws IOException
 */
public static String generateQrcode(Url u, int dimx, int dimy) throws WriterException, IOException {

    final String proxy = ConfigurationHelper.getProp().getProperty("url.proxy.domain", "http://mbfu.it/");
    final GridFS fs = MongoConnectionHelper.getGridFS();

    final QRCodeWriter writer = new QRCodeWriter();
    final BitMatrix bitMatrix = writer.encode(proxy + "/" + u.getFast(), BarcodeFormat.QR_CODE, dimx, dimy);
    final File temp = File.createTempFile("tempfile" + System.currentTimeMillis(), ".tmp");
    MatrixToImageWriter.writeToFile(bitMatrix, "gif", temp);

    final GridFSInputFile gfi = fs.createFile(temp);
    gfi.setFilename(u.getFast() + ".gif");

    final BasicDBObject meta = new BasicDBObject();
    meta.put("ref_url", u.getId());
    meta.put("created", new Date());
    gfi.setMetaData(meta);

    gfi.setContentType("image/gif");
    gfi.save();

    temp.deleteOnExit();

    return gfi.getId().toString();

}

From source file:mx.org.cedn.avisosconagua.engine.processors.Init.java

License:Open Source License

/**
 * Processes an uploaded file and stores it in MongoDB.
 * @param item file item from the parsed servlet request
 * @param currentId ID for the current MongoDB object for the advice
 * @return file name/*from   w  w w .ja  va2  s .com*/
 * @throws IOException 
 */
private String processUploadedFile(FileItem item, String currentId) throws IOException {
    System.out.println("file: size=" + item.getSize() + " name:" + item.getName());
    GridFS gridfs = mi.getImagesFS();
    String filename = currentId + ":" + item.getFieldName() + "_" + item.getName();
    gridfs.remove(filename);
    GridFSInputFile gfsFile = gridfs.createFile(item.getInputStream());
    gfsFile.setFilename(filename);
    gfsFile.setContentType(item.getContentType());
    gfsFile.save();
    return filename;
}