Java tutorial
/* * Copyright 2010-2013, the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cloudbees.demo.beesshop.service; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.Iterables; import com.google.common.io.ByteStreams; import com.mongodb.DB; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSInputFile; import org.bson.types.ObjectId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.TimeUnit; /** * MongoDB GridFS storage for images. * * @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a> */ @Service public class MongoDbFileStorageService implements InitializingBean { protected final Logger logger = LoggerFactory.getLogger(getClass()); private final Random random = new Random(); private String cdnDomainName; private Map<String, String> contentTypeByFileExtension = new HashMap<String, String>() { { put("jpg", "image/jpeg"); put("jpeg", "image/jpeg"); put("png", "image/png"); put("gif", "image/gif"); } }; private Map<String, String> defaultFileExtensionByContentType = new HashMap<String, String>() { { put("image/jpeg", "jpg"); put("image/png", "png"); put("image/gif", "gif"); } }; private GridFS gridFS; @Autowired public MongoDbFileStorageService(DB db) { this.gridFS = new GridFS(db, "media"); } @Override public void afterPropertiesSet() throws Exception { } @Nullable public String findContentType(String fileName) { String fileExtension = Iterables.getLast(Splitter.on('.').split(fileName), null); fileExtension = Strings.nullToEmpty(fileExtension).toLowerCase(); return contentTypeByFileExtension.get(fileExtension); } @Nonnull public String storeFile(InputStream in, String contentType) { String extension = defaultFileExtensionByContentType.get(contentType); String fileName = Joiner.on(".").skipNulls().join(Math.abs(random.nextLong()), extension); GridFSInputFile file = gridFS.createFile(in, fileName); file.setContentType(contentType); file.save(); return "gridfs://" + gridFS.getBucketName() + "/" + file.getId().toString(); } public void serveFile(String photoId, String id, HttpServletResponse response) throws IOException { GridFSDBFile file = gridFS.findOne(new ObjectId(id)); response.setContentType(file.getContentType()); response.setHeader("cache-control", "public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS)); try (InputStream in = file.getInputStream()) { ByteStreams.copy(in, response.getOutputStream()); } } public String getCdnDomainName() { return cdnDomainName; } public void setCdnDomainName(String cdnDomainName) { this.cdnDomainName = cdnDomainName; } }