一、编写PathUtil.java对路径进行封装
package com.lzx.o2o.util;
public class PathUtil {
private static String separator = System.getProperty("file.separator");
public static String getImgBasePath() {
String os = System.getProperty("os.name");
String basePath = "";
if (os.toLowerCase().startsWith("win")) {
basePath = "D:/project/image";
} else {
basePath = "/home/project/image";
}
return basePath.replace("/", separator);
}
public static String getShopImagePath(Long shopId) {
String imagePath = "/upload/item/shop/" + shopId + "/";
return imagePath.replace("/", separator);
}
}
二、编写ImageUtil.java对图片操作进行封装
package com.lzx.o2o.util;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
public class ImageUtil {
private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
private static final Random r = new Random();
private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);
public static File transferCommonsMultipartFileToFile(CommonsMultipartFile cFile) {
File newFile = new File(cFile.getOriginalFilename());
try {
cFile.transferTo(newFile);
} catch (IllegalStateException e) {
logger.error(e.toString());
e.printStackTrace();
} catch (IOException e) {
logger.error(e.toString());
e.printStackTrace();
}
return newFile;
}
public static String generateThumnail(File file, String targetAddr) {
String realFileName = getRandomFileName();
String extension = getExtension(file);
makeDirPath(targetAddr);
String realtiveAddr = targetAddr + realFileName + extension;
logger.debug("Current realtive addr is:" + realtiveAddr);
File dest = new File(PathUtil.getImgBasePath() + realtiveAddr);
logger.debug("Current complete addr is:" + PathUtil.getImgBasePath() + realtiveAddr);
try {
Thumbnails.of(file).size(200, 200)
.watermark(Positions.CENTER, ImageIO.read(new File(basePath + "/watermark.jpg")), 0.25f)
.outputQuality(0.85f).toFile(dest);
} catch (IOException e) {
logger.error(e.toString());
e.printStackTrace();
}
return realtiveAddr;
}
private static void makeDirPath(String targetAddr) {
String realFileParentPath = PathUtil.getImgBasePath() + targetAddr;
File dirPath = new File(realFileParentPath);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
}
private static String getExtension(File cFile) {
String FileName = cFile.getName();
String extension = FileName.substring(FileName.lastIndexOf("."));
return extension;
}
private static String getRandomFileName() {
int rannum = r.nextInt(89999) + 10000;
String nowTimeStr = sDateFormat.format(new Date());
return nowTimeStr + rannum;
}
public static void main(String args[]) throws IOException {
Thumbnails.of(new File("D:/image/xiaohuangren.jpg")).size(200, 200)
.watermark(Positions.CENTER, ImageIO.read(new File(basePath + "/watermark.jpg")), 0.25f)
.outputQuality(0.85f).toFile("D:/image/xiaohuangrennews.jpg");
}
}
三、编写枚举类 ShopStateEnum.java
package com.lzx.o2o.enums;
public enum ShopStateEnum {
CHECK(0, "审核中"), OFFLINE(-1, "非法店铺"), SUCCESS(1, "操作成功"), PASS(2, "通过认证"), INNER_ERROR(-1001, "内部系统错误"),
NULL_SHOPID(-1002, "ShopId为空"), NULL_SHOP(-1003, "Shop为空");
private int state;
private String stateInfo;
private ShopStateEnum(int state, String stateInfo) {
this.state = state;
this.stateInfo = stateInfo;
}
public static ShopStateEnum stateOf(int state) {
for (ShopStateEnum stateEnum : values()) {
if (stateEnum.getState() == state) {
return stateEnum;
}
}
return null;
}
public int getState() {
return state;
}
public String getStateInfo() {
return stateInfo;
}
}
四、dto层在操作完成后并返回处理结构 ShopExecution.java
package com.lzx.o2o.dto;
import java.util.List;
import com.lzx.o2o.entity.Shop;
import com.lzx.o2o.enums.ShopStateEnum;
public class ShopExecution {
private int state;
private String stateInfo;
private int count;
private Shop shop;
private List<Shop> shopList;
public ShopExecution() {
}
public ShopExecution(ShopStateEnum shopStateEnum) {
this.state = shopStateEnum.getState();
this.stateInfo = shopStateEnum.getStateInfo();
}
public ShopExecution(ShopStateEnum shopStateEnum, Shop shop) {
this.state = shopStateEnum.getState();
this.stateInfo = shopStateEnum.getStateInfo();
this.shop = shop;
}
public ShopExecution(ShopStateEnum shopStateEnum, List<Shop> shopList) {
this.state = shopStateEnum.getState();
this.stateInfo = shopStateEnum.getStateInfo();
this.shopList = shopList;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getStateInfo() {
return stateInfo;
}
public void setStateInfo(String stateInfo) {
this.stateInfo = stateInfo;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public Shop getShop() {
return shop;
}
public void setShop(Shop shop) {
this.shop = shop;
}
public List<Shop> getShopList() {
return shopList;
}
public void setShopList(List<Shop> shopList) {
this.shopList = shopList;
}
}
五、编写 ShopOperationException.java 对RuntimeException进行简单封装
package com.lzx.o2o.exceptions;
public class ShopOperationException extends RuntimeException {
private static final long serialVersionUID = 2408494200829456621L;
public ShopOperationException(String msg) {
super(msg);
}
}
六、编写 ShopService.java 接口
package com.lzx.o2o.service;
import java.io.File;
import com.lzx.o2o.dto.ShopExecution;
import com.lzx.o2o.entity.Shop;
public interface ShopService {
ShopExecution addShop(Shop shop, File shopImage);
}
七、编写ShopServiceImpl.java实现类
package com.lzx.o2o.service.impl;
import java.io.File;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lzx.o2o.dao.ShopDao;
import com.lzx.o2o.dto.ShopExecution;
import com.lzx.o2o.entity.Shop;
import com.lzx.o2o.enums.ShopStateEnum;
import com.lzx.o2o.exceptions.ShopOperationException;
import com.lzx.o2o.service.ShopService;
import com.lzx.o2o.util.ImageUtil;
import com.lzx.o2o.util.PathUtil;
@Service
public class ShopServiceImpl implements ShopService {
@Autowired
private ShopDao shopDao;
@Override
@Transactional
public ShopExecution addShop(Shop shop, File shopImg) {
if (shop == null) {
return new ShopExecution(ShopStateEnum.NULL_SHOP);
}
try {
shop.setEnableStatus(0);
shop.setCreateTime(new Date());
shop.setLastEditTime(new Date());
int effectedNum = shopDao.insertShop(shop);
if (effectedNum <= 0) {
throw new ShopOperationException("店铺创建失败");
} else {
if (shopImg != null) {
try {
addShopImg(shop, shopImg);
} catch (Exception e) {
throw new ShopOperationException("addShopImg error:" + e.getMessage());
}
effectedNum = shopDao.updateShop(shop);
if (effectedNum <= 0) {
throw new ShopOperationException("更新图片地址失败");
}
}
}
} catch (Exception e) {
throw new ShopOperationException("addShop error:" + e.getMessage());
}
return new ShopExecution(ShopStateEnum.CHECK);
}
private void addShopImg(Shop shop, File shopImg) {
String dest = PathUtil.getShopImagePath(shop.getShopId());
String shopImgAddr = ImageUtil.generateThumnail(shopImg, dest);
shop.setShopImg(shopImgAddr);
}
}
八、编写ShopServiceTest.java进行junit测试
package com.lzx.o2o.service;
import static org.junit.Assert.assertEquals;
import java.io.File;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.lzx.o2o.BaseTest;
import com.lzx.o2o.dto.ShopExecution;
import com.lzx.o2o.entity.Area;
import com.lzx.o2o.entity.PersonInfo;
import com.lzx.o2o.entity.Shop;
import com.lzx.o2o.entity.ShopCategory;
import com.lzx.o2o.enums.ShopStateEnum;
public class ShopServiceTest extends BaseTest {
@Autowired
private ShopService shopService;
@Test
public void testAddShop() {
Shop shop = new Shop();
PersonInfo owner = new PersonInfo();
owner.setUserId(1L);
Area area = new Area();
area.setAreaId(2);
ShopCategory shopCategory = new ShopCategory();
shopCategory.setShopCategoryId(10L);
shop.setOwner(owner);
shop.setArea(area);
shop.setShopCategory(shopCategory);
shop.setShopName("李泽旭22");
shop.setShopDesc("大帅哥一枚");
shop.setShopAddr("济南长清区");
shop.setPhone("17854167728");
shop.setPriority(100);
shop.setEnableStatus(ShopStateEnum.CHECK.getState());
shop.setAdvice("审核中");
File imageFile = new File("D:/image/jingse.jpg");
ShopExecution se = shopService.addShop(shop, imageFile);
assertEquals(ShopStateEnum.CHECK.getState(), se.getState());
}
}