前尘往事,如烟似梦,想来缘浅,奈何情深,岁月如潮,沁漫沙滩。
src/main/java/com.imooc.o2o.dao 目录下新建 ShopDao.java接口。
package com.imooc.o2o.dao;
import com.imooc.o2o.entity.Shop;
public interface ShopDao {
/**
* 新增店铺
* @param shop
* @return
*/
int insertShop(Shop shop);
}
src/main/resources/mapper路径下创建ShopDao.xml文件
<mapper namespace="com.imooc.o2o.dao.ShopDao">
<insert id="insertShop" useGeneratedKeys="true" keyColumn="shop_id"
keyProperty="shopId">
INSERT INTO
tb_shop(owner_id,area_id,shop_category_id,shop_name,shop_desc,shop_addr,
phone,shop_img,priority,create_time,last_edit_time,enable_status,advice)
VALUSE
(#{owner.userId},#{area.areaId},#{shopCategory.shopCategoryId},#{shopName},
#{shopDesc},#{shopAddr},#{phone},#{shopImg},#{priority},#{createTime},
#{lastEditTime},#{enableStatus},#{advice})
insert>
mapper>
数据库添加测试数据
insert into `o2o`.`tb_shop_category` ( `shop_category_name`, `shop_category_desc`, `shop_category_img`, `priority`) values ( '咖啡奶茶', '咖啡奶茶', 'test', '1')
insert into `o2o`.`tb_person_info` ( `name`, `profile_img`, `email`, `gender`, `enable_status`, `user_type`) values ( '测试', 'test', 'test', '1', '1', '2')
com.imooc.o2o.dao目录下创建ShopDaoTest.java进行单元测试
package com.imooc.o2o.dao;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.imooc.o2o.BaseTest;
import com.imooc.o2o.entity.Area;
import com.imooc.o2o.entity.PersonInfo;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.entity.ShopCategory;
public class ShopDaoTest extends BaseTest{
@Autowired
private ShopDao shopDao;
@Test
public void testInsertShop() {
Shop shop = new Shop();
PersonInfo owner = new PersonInfo();
Area area = new Area();
ShopCategory shopCategory = new ShopCategory();
owner.setUserId(1L);
area.setAreaId(2);
shopCategory.setShopCategoryId(1L);
shop.setOwner(owner);
shop.setArea(area);
shop.setShopCategory(shopCategory);
shop.setShopName("测试的店铺");
shop.setShopDesc("test");
shop.setShopAddr("test");
shop.setPhone("test");
shop.setShopImg("test");
shop.setCreateTime(new Date());
shop.setEnableStatus(1);
shop.setAdvice("审核中");
int effectedNum = shopDao.insertShop(shop);
assertEquals(1, effectedNum);
}
}
运行
src/main/java/com.imooc.o2o.dao目录下ShopDao.java新增代码
/**
* 更新店铺信息
*/
int updateShop(Shop shop);
src/main/resources/mapper目录下ShopDao.xml新增代码
"updateShop" parameterType="com.imooc.o2o.entity.Shop">
update tb_shop
<set>
<if test="shopName != null">shop_name=#{shopName},if>
<if test="shopDesc != null">shop_desc=#{shopDesc},if>
<if test="shopAddr != null">shop_addr=#{shopAddr},if>
<if test="phone != null">phone=#{phone},if>
<if test="shopImg != null">shop_img=#{shopImg},if>
<if test="priority != null">priority=#{priority},if>
<if test="lastEditTime != null">last_edit_time=#{lastEditTime},if>
<if test="enableStatus != null">enable_status=#{enableStatus},if>
<if test="advice != null">advice=#{advice},if>
<if test="area != null">area_id=#{area.areaId},if>
<if test="shopCategory != null">shop_category_id=#{shopCategory.shopCategoryId}if>
set>
where shop_id=#{shopId}
src/test/java/com.imooc.o2o.dao目录下ShopDaoTest.java添加代码
@Test
public void testUpdateShop() {
Shop shop = new Shop();
shop.setShopId(1L);
shop.setShopDesc("测试描述");
shop.setShopAddr("测试地址");
int effectedNum = shopDao.updateShop(shop);
assertEquals(1, effectedNum);
}
testInsertShop方法上面添加@Ignore标签,JUnit则不会触发testInsertShop方法了。
Run As执行测试。没发现错误就ok了。
打开链接 http://www.mvnrepository.com/search?q=Thumbnailator
<dependency>
<groupId>net.coobirdgroupId>
<artifactId>thumbnailatorartifactId>
<version>0.4.8version>
dependency>
我们在之前的pom.xml配置中也配置过.
在src/main/java/com.imooc.o2o.util路径下新建ImageUtil.java类
在src/main/resources路径下放置一张图片
在/Users/mac/Downloads/luoto.png 存入另外一张图片。为此图片添加上面图片的水印。
package com.imooc.o2o.util;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
public class ImageUtil {
public static void main(String[] args) throws IOException {
String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
Thumbnails.of(new File("/Users/mac/Downloads/luoto.png")).size(200, 200)
.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/jingyu.png")), 0.25f)
.outputQuality(0.8f).toFile("/Users/mac/Downloads/luotonew.png");
}
}
运行main函数,我们发现在/Users/mac/Downloads路径下多出一张luotonew.png的水印图片。
src/main/java/com.imooc.o2o.util路径下创建PathUtil.java类
package com.imooc.o2o.util;
public class PathUtil {
/*
* 根据不同的操作系统,设置储存图片文件不同的根目录
*/
private static String seperator = System.getProperty("file.separator");
public static String getImgBasePath() {
String os =System.getProperty("os.name");
String basePath = "";
if(os.toLowerCase().startsWith("win")) {
basePath = "D:/projectdev/image/"; //根据自己的实际路径进行设置
}else {
basePath = "/home/o2o/image/";//根据自己的实际路径进行设置
}
basePath = basePath.replace("/", seperator);
return basePath;
}
//根据不同的业务需求返回不同的子路径
public static String getShopImagePath(long shopId) {
String imagePath = "/upkoad/item/shop/"+ shopId + "/";
return imagePath.replace("/", seperator);
}
}
修改ImageUtil.java类
package com.imooc.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.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 SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
private static final Random r = new Random();
/**
* 处理缩略图,并返回新生成图片的相对值路径
* @param thumbnail
* @param targetAddr
* @return
*/
public static String generateThumbnail(File thumbnail,String targetAddr) {
String realFileName = getRandomFileName();
String extension = getFileExtension(thumbnail);
makeDirPath(targetAddr);
String relativeAddr =targetAddr +realFileName + extension;
File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
try {
Thumbnails.of(thumbnail).size(200, 200)
.watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new File(basePath + "watermark.png")),0.25f)
.outputQuality(0.8f).toFile(dest);
}catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
return relativeAddr;
}
/**
* 创建目标路径所涉及到的目录,即/home/work/o2o/xxx.jpg,
* 那么 home work o2o 这三个文件夹都得自动创建
* @param targetAddr
*/
private static void makeDirPath(String targetAddr) {
// TODO Auto-generated method stub
String realFileParentPath = PathUtil.getImgBasePath()+targetAddr;
File dirPath = new File(realFileParentPath);
if(!dirPath.exists()) {
dirPath.mkdirs();
}
}
/**
* 生成随机文件名,当前年月日小时分钟秒+五位随机数
*/
private static String getRandomFileName() {
//获取随机的五位数
int rannum = r.nextInt(89999) + 10000;
String nowTimeStr = sDateFormat.format(new Date());
return nowTimeStr+rannum;
}
/**
* 获取输入文件流的扩展名
* @param args
* @throws IOException
*/
private static String getFileExtension(File thumbnail) {
String originalFileName = thumbnail.getName();
return originalFileName.substring(originalFileName.lastIndexOf("."));
}
public static void main(String[] args) throws IOException {
Thumbnails.of(new File("/Users/mac/Downloads/luoto.png")).size(200, 200)
.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/jingyu.png")), 0.25f)
.outputQuality(0.8f).toFile("/Users/mac/Downloads/luotonew.png");
}
}
创建枚举类型文件
package com.imooc.o2o.enums;
public enum ShopStateEnum {
CHECK(0, "审核中"), OFFLINE(-1, "非法店铺"), SUCCESS(1, "操作成功"), PASS(2, "通过认证"), INNER_ERROR(-1001, "内部系统错误"),
NULL_SHOPID(-1002,"ShopId为空");
private int state;
private String stateInfo;
private ShopStateEnum(int state, String stateInfo) {
this.state = state;
this.stateInfo = stateInfo;
}
/*
*依据传入的state返回相应的enum值
*/
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;
}
}
src/main/java/com.imooc.o2o.dto路径下创建ShopExecution.java类
package com.imooc.o2o.dto;
import java.util.List;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.enums.ShopStateEnum;
public class ShopExecution {
// 结果状态
private int state;
// 状态标识
private String stateInfo;
// 店铺数量
private int count;
// 操作的shop(增删改店铺的时候用到)
private Shop shop;
// shop列表(查询店铺列表的时候使用)
private List shopList;
public ShopExecution() {
}
// 店铺操作失败的时候使用的构造器
public ShopExecution(ShopStateEnum stateEnum) {
this.state = stateEnum.getState();
this.stateInfo = stateEnum.getStateInfo();
}
// 店铺操作成功的时候使用的构造器
public ShopExecution(ShopStateEnum stateEnum, Shop shop) {
this.state = stateEnum.getState();
this.stateInfo = stateEnum.getStateInfo();
this.shop = shop;
}
// 店铺操作成功的时候使用的构造器
public ShopExecution(ShopStateEnum stateEnum, List shopList) {
this.state = stateEnum.getState();
this.stateInfo = stateEnum.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 getShopList() {
return shopList;
}
public void setShopList(List shopList) {
this.shopList = shopList;
}
}
创建com.imooc.o2o.exceptions包,ShopOperationException.java类文件
package com.imooc.o2o.exceptions;
public class ShopOperationException extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = 2361446884822298905L;
public ShopOperationException(String msg) {
super(msg);
}
}
ShopServiceImpl.java
package com.imooc.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 org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.imooc.o2o.dao.ShopDao;
import com.imooc.o2o.dto.ShopExecution;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.enums.ShopStateEnum;
import com.imooc.o2o.exceptions.ShopOperationException;
import com.imooc.o2o.service.ShopService;
import com.imooc.o2o.util.ImageUtil;
import com.imooc.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) {
// TODO: handle exception
throw new ShopOperationException("addShopImg error"+e.getMessage());
}
//更新店铺的图片地址
effectedNum = shopDao.updateShop(shop);
if(effectedNum <=0) {
throw new ShopOperationException("更新图片地址失败");
}
}
}
}catch (Exception e) {
// TODO: handle exception
throw new ShopOperationException("addShop error:"+e.getMessage());
}
return new ShopExecution(ShopStateEnum.CHECK,shop);
}
private void addShopImg(Shop shop, File shopImg) {
// 获取shop图片目录的相对值路径
String dest = PathUtil.getShopImagePath(shop.getShopId());
String shopImgAddr = ImageUtil.generateThumbnail(shopImg,dest);
shop.setShopImg(shopImgAddr);
}
}
src/test/java/com.imooc.o2o.service目录下创建ShopServiceTest.java文件
package com.imooc.o2o.service;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.util.Date;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.imooc.o2o.BaseTest;
import com.imooc.o2o.dto.ShopExecution;
import com.imooc.o2o.entity.Area;
import com.imooc.o2o.entity.PersonInfo;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.entity.ShopCategory;
import com.imooc.o2o.enums.ShopStateEnum;
public class ShopServiceTest extends BaseTest{
@Autowired
private ShopService shopService;
@Test
public void testAddShop() {
Shop shop = new Shop();
PersonInfo owner = new PersonInfo();
Area area = new Area();
ShopCategory shopCategory = new ShopCategory();
owner.setUserId(1L);
area.setAreaId(2);
shopCategory.setShopCategoryId(1L);
shop.setOwner(owner);
shop.setArea(area);
shop.setShopCategory(shopCategory);
shop.setShopName("测试的店铺1");
shop.setShopDesc("test1");
shop.setShopAddr("test1");
shop.setPhone("test1");
shop.setCreateTime(new Date());
shop.setEnableStatus(ShopStateEnum.CHECK.getState());
shop.setAdvice("审核中");
File shopImg = new File("/Users/mac/Downloads/luoto.png");
ShopExecution se = shopService.addShop(shop, shopImg);
assertEquals(ShopStateEnum.CHECK.getState(), se.getState());
}
}
运行JUnit进行测试,运行成功,但是报错了显示不能创建file
修改PathUtil.java,去掉"upkoad/item/shop/"+ shopId + "/";
upkoad前的斜杠
//根据不同的业务需求返回不同的子路径
public static String getShopImagePath(long shopId) {
String imagePath = "upkoad/item/shop/"+ shopId + "/";
return imagePath.replace("/", seperator);
}
在src/test/resources目录下添加watermark.png水印图片再进行测试,测试成功,文件也创建成功了。注意:PathUtil.java中设置的文件路径需要真实存在。