com.wonders.bud.freshmommy.web.content.controller.ChannelController.java Source code

Java tutorial

Introduction

Here is the source code for com.wonders.bud.freshmommy.web.content.controller.ChannelController.java

Source

/** 
 * 
 * Copyright (c) 1995-2012 Wonders Information Co.,Ltd. 
 * 1518 Lianhang Rd,Shanghai 201112.P.R.C.
 * All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Wonders Group.
 * (Social Security Department). You shall not disclose such
 * Confidential Information and shall use it only in accordance with 
 * the terms of the license agreement you entered into with Wonders Group. 
 *
 * Distributable under GNU LGPL license by gnu.org
 */

package com.wonders.bud.freshmommy.web.content.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.wonders.bud.framework.common.util.FileUtil;
import com.wonders.bud.framework.common.util.RestMsg;
import com.wonders.bud.freshmommy.service.content.model.po.ChannelPO;
import com.wonders.bud.freshmommy.service.content.service.ChannelService;
import com.wonders.bud.freshmommy.web.content.vo.ChannelVO;
import com.wonders.bud.freshmommy.web.utils.Constant;

/**
 * <p>
 * Title: freshmommy_[]_[??]
 * </p>
 * <p>
 * Description: [?controller]
 * </p>
 * 
 * @author Dy
 * @version $Revision$ 20141124
 * @author (lastest modification by $Author$)
 * @since 20100901
 */
@Controller
@RequestMapping("api/channel")
public class ChannelController {

    protected static Logger log = Logger.getLogger(ChannelController.class);

    private static final String CHANNAL_MIN_FILE = "tempimages/cache/titleimgs/";//
    private static final String CHANNAL_FILE = "tempimages/cache/imgs/";//
    private static final String[] TARGET_PATH = { "images/channel/titleimgs/", "images/channel/imgs/" };

    @Autowired
    private ChannelService channelService;

    /**
     * <p>
     * Description:[?]
     * </p>
     * Created by [Dy] [20141124] 
     * Midified by [] []
     * 
     * @param request
     * @return RestMsg<Object>
     */
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public RestMsg<Object> addChannel(HttpServletRequest request) {
        RestMsg<Object> rm = new RestMsg<Object>();

        // ??
        String channelName = request.getParameter("name");
        String priority = request.getParameter("priority");
        String parentId = request.getParameter("parentId");
        String isDisplay = request.getParameter("isDisplay");
        String titleImg = request.getParameter("titleImg");
        String contentImg = request.getParameter("contentImg");
        String descrition = request.getParameter("descrition");

        // 
        if (StringUtils.isBlank(channelName)) {
            rm.errorMsg("????");
        } else if (StringUtils.isBlank(parentId)) {
            rm.errorMsg("??");
        } else if (StringUtils.isBlank(priority)) {
            rm.errorMsg("??");
        } else {
            try {

                ChannelPO channel = channelService.getById(Integer.valueOf(parentId));
                if (!Integer.valueOf(parentId).equals(0) && channel == null) {
                    rm.errorMsg("???");
                } else {

                    // ????
                    Map<String, Object> check = new HashMap<String, Object>();
                    check.put("parentId", Integer.valueOf(parentId));
                    check.put("channelName", channelName);

                    if (!channelService.duplicatecheck(null, check)) {

                        ChannelPO po = new ChannelPO();
                        po.setChannelName(channelName);
                        po.setIsDisplay("on".equals(isDisplay) ? 1 : 0);
                        po.setParentId(Integer.valueOf(parentId));
                        po.setPriority(Integer.valueOf(priority));
                        po.setDescrition(descrition);

                        //?
                        if (StringUtils.isNotBlank(contentImg)) {
                            String actionPath = request.getSession().getServletContext().getRealPath("");
                            List<String> paths = moveImg(new String[] { titleImg, contentImg }, TARGET_PATH,
                                    actionPath);

                            if (paths != null && paths.size() > 0) {
                                po.setContentImg(paths.get(1));
                                po.setTitleImg(paths.get(0));
                            } else {
                                rm.errorMsg("??");
                                return rm;
                            }
                        }

                        // ?
                        channelService.save(po);
                        if (po.getChannelId() == null) {
                            rm.errorMsg("??");
                        } else {
                            rm.successMsg("??" + channelName + "??");
                        }

                    } else {
                        rm.errorMsg(
                                "?" + (Integer.valueOf(parentId).equals(0) ? "?" : channel.getChannelName())
                                        + "???" + channelName + "??");
                    }
                }
            } catch (Exception e) {
                log.error(e.getLocalizedMessage());
                rm.errorMsg("??");
            }
        }

        return rm;
    }

    /**
     * <p>
     * Description:[?]
     * </p>
     * Created by [Dy] [20141124] 
     * Midified by [] []
     * 
     * @param request
     * @param cid ?id
     * @return RestMsg<Object>
     */
    @RequestMapping(value = "/{cid}", method = RequestMethod.POST)
    @ResponseBody
    public RestMsg<Object> updateChannel(HttpServletRequest request, @PathVariable Integer cid) {
        RestMsg<Object> rm = new RestMsg<Object>();

        // ??
        String channelName = request.getParameter("name");
        String priority = request.getParameter("priority");
        String isDisplay = request.getParameter("isDisplay");
        String titleImg = request.getParameter("titleImg");
        String contentImg = request.getParameter("contentImg");
        String descrition = request.getParameter("descrition");

        // 
        if (StringUtils.isBlank(channelName)) {
            rm.errorMsg("????");
        } else if (StringUtils.isBlank(priority)) {
            rm.errorMsg("??");
        } else {
            try {

                ChannelPO channel = channelService.getById(cid);

                if (channel == null) {
                    rm.errorMsg("????");
                } else {
                    // ????
                    Map<String, Object> check = new HashMap<String, Object>();
                    check.put("parentId", channel.getParentId());
                    check.put("channelName", channelName);

                    if (!channelService.duplicatecheck(cid, check)) {

                        channel.setChannelName(channelName);
                        channel.setIsDisplay("on".equals(isDisplay) ? 1 : 0);
                        channel.setPriority(Integer.valueOf(priority));
                        channel.setDescrition(descrition);
                        //?
                        String actionPath = request.getSession().getServletContext().getRealPath("");
                        if (!contentImg.equals(channel.getContentImg())) {
                            if (StringUtils.isNotBlank(contentImg)) {
                                List<String> paths = moveImg(new String[] { titleImg, contentImg }, TARGET_PATH,
                                        actionPath);

                                if (paths != null && paths.size() > 0) {

                                    deleteImg(actionPath, channel);
                                    channel.setContentImg(paths.get(1));
                                    channel.setTitleImg(paths.get(0));
                                } else {
                                    rm.errorMsg("??");
                                    return rm;
                                }
                            } else {

                                deleteImg(actionPath, channel);
                                channel.setContentImg("");
                                channel.setTitleImg("");
                            }

                        }

                        // ?
                        channelService.update(channel);
                        rm.successMsg("??" + channelName + "??");
                    } else {
                        rm.errorMsg("?"
                                + (Integer.valueOf(channel.getParentId()).equals(0) ? "?"
                                        : channelService.getById(channel.getParentId()).getChannelName())
                                + "???" + channelName + "?");
                    }
                }
            } catch (Exception e) {
                log.error(e.getLocalizedMessage());
                rm.errorMsg("?");
            }
        }
        return rm;
    }

    /**
     * <p>
     * Description:[?]
     * </p>
     * Created by [Dy] [20141124] 
     * Midified by [] []
     * 
     * @param request
     * @param cid ?id
     * @return RestMsg<Object>
     */
    @RequestMapping(value = "/{cid}", method = RequestMethod.DELETE)
    @ResponseBody
    public RestMsg<Object> deleteChannel(HttpServletRequest request, @PathVariable Integer cid) {
        RestMsg<Object> rm = new RestMsg<Object>();
        try {
            channelService.deleteById(cid);
            rm.successMsg("??");
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            rm.errorMsg("?");
        }
        return rm;
    }

    /**
     * <p>
     * Description:[?]
     * </p>
     * Created by [Dy] [20141124] 
     * Midified by [] []
     * 
     * @param request
     * @param cid ?id
     * @return RestMsg<Object>
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public RestMsg<List<ChannelVO>> getChannels(HttpServletRequest request) {
        RestMsg<List<ChannelVO>> rm = new RestMsg<List<ChannelVO>>();

        try {

            //
            List<ChannelPO> list = channelService.getList(null);
            List<ChannelVO> data = new ArrayList<ChannelVO>();

            if (null != list && list.size() > 0) {
                for (ChannelPO po : list) {
                    ChannelVO vo = new ChannelVO();
                    BeanUtils.copyProperties(vo, po);
                    vo.setName(po.getChannelName());
                    data.add(vo);
                }
            }
            ChannelVO root = new ChannelVO();
            root.setName("?");
            root.setChannelId(0);
            root.setChannelType(Constant.CHANNEL_TYPE_DEFAULT);
            data.add(root);

            rm.setResult(data);
            rm.successMsg();
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            rm.errorMsg("?");
        }
        return rm;
    }

    /**
     * <p>
     * Description:[???]
     * </p>
     * Created by [Dy] [20141124] 
     * Midified by [] []
     * 
     * @param request
     * @param cid ?id
     * @return RestMsg<Object>
     */
    @RequestMapping(value = "/menu", method = RequestMethod.GET)
    @ResponseBody
    public RestMsg<List<ChannelVO>> getChannelsMenu(HttpServletRequest request) {
        RestMsg<List<ChannelVO>> rm = new RestMsg<List<ChannelVO>>();

        try {

            //??
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("isDisplay", Constant.CHA_I_DISPLAY);

            List<ChannelPO> list = channelService.getList(map);
            List<ChannelVO> data = new ArrayList<ChannelVO>();

            if (null != list && list.size() > 0) {
                for (ChannelPO po : list) {
                    ChannelVO vo = new ChannelVO();
                    BeanUtils.copyProperties(vo, po);
                    vo.setName(po.getChannelName());
                    data.add(vo);
                }
            }

            rm.setResult(data);
            rm.successMsg();
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            rm.errorMsg("?");
        }
        return rm;
    }

    /**
     * <p>
     * Description:[?]
     * </p>
     * 
     * Created by [Dy] [20141124]
     * Midified by [] []
     * @param request
     * @param response
     * @param session
     * @return
     * @throws Exception
     * @throws IOException
     */
    @RequestMapping(value = "/addImg", method = RequestMethod.POST)
    @ResponseBody
    public RestMsg<Map<String, String>> addImg(HttpServletRequest request, HttpServletResponse response,
            HttpSession session) throws Exception, IOException {

        RestMsg<Map<String, String>> rm = new RestMsg<Map<String, String>>();
        try {
            // MultipartHttpRequest
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            // 
            MultipartFile file = multipartRequest.getFile("imgfile");

            if (file.getContentType().toLowerCase().indexOf("image") < 0) {
                rm = rm.errorMsg("??");
            } else {

                // ??
                String actionPath = request.getSession().getServletContext().getRealPath("");
                String uuid = UUID.randomUUID().toString();
                //
                StringBuffer fileName = new StringBuffer();
                fileName.append(actionPath).append(File.separator).append(CHANNAL_FILE).append(uuid).append(".png");
                //
                StringBuffer minFileName = new StringBuffer();
                minFileName.append(actionPath).append(File.separator).append(CHANNAL_MIN_FILE).append(uuid)
                        .append(".png");

                File imgFolder = new File(fileName.toString());
                if (!imgFolder.getParentFile().exists()) { // 
                    imgFolder.getParentFile().mkdirs();
                }

                File minImgFolder = new File(minFileName.toString());
                if (!minImgFolder.getParentFile().exists()) { // 
                    minImgFolder.getParentFile().mkdirs();
                }

                //
                BufferedImage sourceImg = ImageIO.read(file.getInputStream());
                float heigth = sourceImg.getHeight();
                float width = sourceImg.getWidth();
                double scale = 1;
                double sH = heigth / 200;
                double sW = width / 200;
                scale = sH < sW ? sH : sW;
                int rheigth = new Double(scale * 200).intValue();
                int rwidth = new Double(scale * 200).intValue();

                //?

                Thumbnails.of(file.getInputStream()).scale(1).toFile(fileName.toString());
                Thumbnails.of(file.getInputStream()).sourceRegion(Positions.CENTER, rwidth, rheigth).size(200, 200)
                        .keepAspectRatio(false).toFile(minFileName.toString());

                Map<String, String> map = new HashMap<String, String>();
                map.put("minImg", CHANNAL_MIN_FILE + uuid + ".png");
                map.put("img", CHANNAL_FILE + uuid + ".png");
                rm = rm.successMsg();
                rm.setResult(map);
            }
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            rm.errorMsg("?");
        }
        return rm;
    }

    /**
     * <p>
     * Description:[]
     * </p>
     * 
     * Created by [Dy] [20141124]
     * Midified by [] []
     * @param request
     * @return
     */
    @RequestMapping(value = "/deleteImg", method = RequestMethod.POST)
    @ResponseBody
    public RestMsg<Object> deleteImg(HttpServletRequest request) {
        RestMsg<Object> rm = new RestMsg<Object>();

        String filepath = request.getParameter("filepath");
        String minFilepath = request.getParameter("minFilepath");
        try {

            String actionPath = request.getSession().getServletContext().getRealPath("");
            //
            FileUtil.deleteFiles(actionPath, filepath);
            FileUtil.deleteFiles(actionPath, minFilepath);
            rm.successMsg();
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            rm.errorMsg("?");
        }
        return rm;
    }

    /**
     * <p>
     * Description:[?]
     * </p>
     * 
     * Created by [Dy] [20141127]
     * Midified by [] []
     * @param actionPath 
     * @param channel ?
     */
    private void deleteImg(String actionPath, ChannelPO channel) {
        //?
        if (StringUtils.isNotBlank(channel.getContentImg())) {
            FileUtil.deleteFiles(actionPath, channel.getContentImg());
        }
        if (StringUtils.isNotBlank(channel.getTitleImg())) {
            FileUtil.deleteFiles(actionPath, channel.getTitleImg());
        }
    }

    /**
     * <p>
     * Description:[?]
     * </p>
     * 
     * Created by [Dy] [20141127]
     * Midified by [] []
     * @param sourcePath 
     * @param targetPath 
     * @param actionPath action
     * @return List<String> ?sourcePath?
     */
    public static List<String> moveImg(String[] sourcePath, String[] targetPath, String actionPath) {

        List<String> list = new ArrayList<String>();
        if (sourcePath.length == targetPath.length) {
            if (sourcePath.length > 0) {
                try {
                    for (int i = 0; i < sourcePath.length; i++) {
                        if (StringUtils.isNotBlank(sourcePath[i])) {
                            File cacheFile = new File(actionPath + File.separator + sourcePath[i]);

                            //
                            StringBuffer fileName = new StringBuffer();
                            fileName.append(actionPath).append(File.separator).append(targetPath[i])
                                    .append(cacheFile.getName());

                            File folder = new File(fileName.toString());
                            if (!folder.getParentFile().exists()) { // 
                                folder.getParentFile().mkdirs();
                            }

                            Thumbnails.of(cacheFile).scale(1).toFile(fileName.toString());

                            // 
                            FileUtil.deleteFiles(actionPath, sourcePath[i]);

                            list.add(targetPath[i] + cacheFile.getName());
                        }
                    }
                    return list;
                } catch (Exception e) {
                    log.error(e.getLocalizedMessage());
                    return null;
                }
            }
        }
        return null;
    }
}