添加店铺之ShopService的实现(包括对上传图片的处理)

一、编写PathUtil.java对路径进行封装

package com.lzx.o2o.util;

public class PathUtil {
	/*
	 * 获取当前系统文件路径的分隔符
	 */
	private static String separator = System.getProperty("file.separator");

	/**
	 * 创建用来存储图片的根目录(绝对地址路径)
	 * 
	 * @return
	 */
	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);
	}

	/**
	 * 创建用来存储图片的相对地址路径
	 * 
	 * @param shopId
	 * @return
	 */
	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 {

	// 通过当前执行的线程获取项目的resources路径
	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);

	/**
	 * 将CommonsMultipartFile转换成File类
	 * 
	 * @param cFile
	 * @return
	 */
	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;
	}

	/**
	 * 处理缩略图,并返回新生成图片的相对值路径
	 * 
	 * @param file
	 * @param targetAddr
	 * @return
	 */
	public static String generateThumnail(File file, String targetAddr) {
		// 获取不重复的随机名
		String realFileName = getRandomFileName();
		// 获取文件的扩展名如 png,jpg等
		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);
		// 调用Thumbnails生成带有水印的图片
		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;
	}

	/**
	 * 创建目标路径所涉及到的目录,即/home/work/lzx/xxx.jpg,那么 home work lzx 这三个文件夹都得自动创建
	 * 
	 * @param targetAddr
	 */
	private static void makeDirPath(String targetAddr) {
		String realFileParentPath = PathUtil.getImgBasePath() + targetAddr;
		File dirPath = new File(realFileParentPath);
		if (!dirPath.exists()) {
			dirPath.mkdirs();
		}
	}

	/**
	 * 获取输入文件流的扩展名
	 * 
	 * @param cFile
	 * @return
	 */
	private static String getExtension(File cFile) {
		String FileName = cFile.getName();
		String extension = FileName.substring(FileName.lastIndexOf("."));
		return extension;
	}

	/**
	 * 生成随机文件名,当前年月日小时分钟秒钟+五位随机数
	 * 
	 * @return
	 */
	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 不希望第三方程序访问Enum值如:CHECK(0,"审核书中")
	 */
	private ShopStateEnum(int state, String stateInfo) {
		this.state = state;
		this.stateInfo = stateInfo;
	}

	/**
	 * 依据传入的state返回相应的Enum值
	 * 
	 * @param state
	 * @return
	 */
	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;
	// 操作的shop(增删改店铺的时候用到)
	private Shop 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 {
	/**
	 * 注册店铺信息
	 * 
	 * @param shop
	 * @param imageFile
	 * @return
	 */
	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) {
		// 获取shop图片目录的相对值路径
		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());
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值