package com.wn.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wn.dao.BaseSystemDao;
import com.wn.dao.ChatDao;
import com.wn.model.BaseResult;
import com.wn.model.BaseSystemBean;
import com.wn.model.ChatBean;
import com.wn.util.Base64Utils;
import com.wn.util.BaseUtils;
import com.wn.util.CommonUtils;
import com.wn.util.DbUtils;
import com.wn.util.ErrorUtils;
import com.wn.util.MD5Utils;
import com.wn.util.PrintWriterUtils;
import com.wn.util.TimeUtils;
import com.wn.util.VideoUtils;

/**
* Author : wangning
* Date :  2022年4月28日 上午1:10:48
* Email : maoning20080809@163.com
* Description : 聊天信息, (java.lang.IllegalArgumentException: 请求头太大,使用base64加解密)
*/
@WebServlet("/chat")
public class ChatServlet extends BaseServlet {
    
    private ChatDao chatDao = new ChatDao();
    private BaseSystemDao baseSystemDao = new BaseSystemDao();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doPost(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        System.out.println("ChatServlet 方法名:" + method);
        if("insertChatList".equals(method)) {
            processInsertChatList(request, response);
        } else if("getChatList".equals(method)) {
            processGetChatList(request, response);
        } else if("uploadChatImages".equals(method)) {
            processUploadImages(request, response);
        } else if("uploadChatVideo".equals(method)) {
            processUploadVideo(request, response);
        } else if("uploadChatVoice".equals(method)) {
            processUploadVoice(request, response);
        } else if("deleteChatFile".equals(method)) {
            deleteChatFile(request, response);
        }
        super.doPost(request, response);
    }
    
    //获取聊天信息列表
    private void processGetChatList(HttpServletRequest request, HttpServletResponse response) throws IOException  {
        Connection con = null;
        BaseResult<String> baseResult = new BaseResult<String>();
        try {
            con = DbUtils.getInstance().getConnection();
            String fromAccount = request.getParameter("fromAccount");
            System.out.println("processGetChatList 参数:" + fromAccount);
            ArrayList<ChatBean> contactsList = chatDao.getChatList(con, fromAccount);
            //System.out.println("processGetChatList 返回值:" + contactsList);            
        
            if(contactsList == null) {
                baseResult.setSuccess(false);
            } else {
                String contactsListGson = new Gson().toJson(contactsList);
                System.out.println("processGetChatList 返回值:" + contactsListGson);
                baseResult.setSuccess(true);
                baseResult.setData(contactsListGson);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            baseResult.setSuccess(false);
            
        } finally {
            PrintWriterUtils.basePrintWriterObject(response, baseResult);
            DbUtils.getInstance().close(con);
        }
    }    
    
    //插入两天信息列表
    private void processInsertChatList(HttpServletRequest request, HttpServletResponse response) throws IOException  {
        Connection con = null;
        BaseResult<String> baseResult = new BaseResult<String>();
        try {
            con = DbUtils.getInstance().getConnection();

            String chatListJson = request.getParameter("chatList");
            //System.out.println("插入聊天md5:" + md5ChatList);
            //String chatListJson = Base64Utils.decode(md5ChatList);
            //System.out.println("插入聊天j解密:" + chatListJson);
            ArrayList<ChatBean> contactsList = new Gson().fromJson(chatListJson, new TypeToken<ArrayList<ChatBean>>(){}.getType());
            System.out.println("插入聊天json:" + contactsList);
            boolean isSuccess = chatDao.insertChatList(con, contactsList);
            System.out.println("插入聊天返回值:" + isSuccess);
            baseResult.setSuccess(true);
            
        } catch (Exception e) {
            e.printStackTrace();
            baseResult.setSuccess(false);
            
        } finally {
            PrintWriterUtils.basePrintWriterObject(response, baseResult);
            DbUtils.getInstance().close(con);
        }
    }
    
    //删除聊天文件
    private void deleteChatFile(HttpServletRequest request, HttpServletResponse response) throws IOException  {
        BaseResult<String> baseResult = new BaseResult<String>();
        try {
            
            String fileName = request.getParameter("fileName");
            System.out.println("删除聊天文件:" + fileName);
            String resultPath = BaseUtils.getUploadPath(request);
            String reallyFileName = resultPath + fileName;
            new File(reallyFileName).delete();
            baseResult.setSuccess(true);
            System.out.println("删除聊天文件成功:");
        } catch (Exception e) {
            System.out.println("删除聊天文件失败:");
            e.printStackTrace();
            baseResult.setSuccess(false);
            
        } finally {
            PrintWriterUtils.basePrintWriterObject(response, baseResult);
        
        }
    }    
    
    
    //上传聊天图片
    private void processUploadImages(HttpServletRequest request, HttpServletResponse response) throws IOException {
        
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        
        factory.setSizeThreshold(1024 * 1024);
        List items = null;
        String filename = "";
        ArrayList<String> paramList = new ArrayList<String>();
        BaseResult<String> baseResult = new BaseResult<String>();
        Connection con = null;

        try {
            con = DbUtils.getInstance().getConnection();
            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while(iter.hasNext()) {
                FileItem item = (FileItem)iter.next();
                                
                if(!item.isFormField()) {
                    filename = System.currentTimeMillis() + ".jpg";
                    String resultPath = BaseUtils.getUploadPath(request);
                    File f = new File(resultPath);
                    if(!f.exists()) {
                        f.mkdirs();
                    }
                    String imgsrc = resultPath + filename;
                    InputStream is = item.getInputStream();
                    FileOutputStream fos = new FileOutputStream(imgsrc);
                    byte b[] = new byte[1024 * 1024];
                    int length = 0;
                    while(-1 != (length = is.read(b))) {
                        fos.write(b, 0, length);
                    }
                    fos.flush();
                    fos.close();
                    System.out.println("上传朋友圈图片路径:" + filename);
                } else {
                    //获取其他参数
                    String value = item.getString("UTF-8");
                    paramList.add(value);
                }
            }
            
            ChatBean chatBean = getChatBean(paramList, filename, "");

            boolean isSuccess = true;
            if(isSync(con)) {
                isSuccess =  chatDao.insertChat(con,chatBean);    
            }
        
            if(isSuccess) {
                String chatBeanGson =  new Gson().toJson(chatBean);                
                baseResult.setSuccess(true);
                baseResult.setData(chatBeanGson);
                    
            } else {
                baseResult.setSuccess(false);
                
            }
            
        } catch(Exception e) {
            e.printStackTrace();
            baseResult.setSuccess(false);
            
        } finally {
            DbUtils.getInstance().close(con);
            PrintWriterUtils.basePrintWriterObject(response, baseResult);
        }
    }

    //上传小视频
    private void processUploadVideo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        
        factory.setSizeThreshold(1024 * 1024);
        List items = null;
        //小视频文件
        String filename = "";
        ArrayList<String> paramList = new ArrayList<String>();
        //小视频缩略图
        String videoFrame = "";
        BaseResult<String> baseResult = new BaseResult<String>();
        Connection con = null;

        try {
            con = DbUtils.getInstance().getConnection();

            String videoFrameFileName = "";
            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while(iter.hasNext()) {
                FileItem item = (FileItem)iter.next();
                                
                if(!item.isFormField()) {
                    filename = System.currentTimeMillis() + ".mp4";
                    String resultPath = BaseUtils.getUploadPath(request);
                    File f = new File(resultPath);
                    if(!f.exists()) {
                        f.mkdirs();
                    }
                    String videosrc = resultPath + filename;
                    InputStream is = item.getInputStream();
                    FileOutputStream fos = new FileOutputStream(videosrc);
                    byte b[] = new byte[1024 * 1024];
                    int length = 0;
                    while(-1 != (length = is.read(b))) {
                        fos.write(b, 0, length);
                    }
                    fos.flush();
                    fos.close();
                    
                    //生成小视频对应的缩略图
                    videoFrameFileName = System.currentTimeMillis() + ".jpg";
                    videoFrame = resultPath + videoFrameFileName;
                    File videoFrameFile = new File(videoFrame);
                    if(!videoFrameFile.exists()) {
                        videoFrameFile.createNewFile();
                    }
                    
                    VideoUtils.fetchImage(videosrc, videoFrame);
                    
                    System.out.println("上传聊天小视频路径:" + filename +" , 缩略图路径: " + videoFrameFileName);
                } else {
                    //获取其他参数
                    String value = item.getString("UTF-8");
                    paramList.add(value);
                }
            }
            
            ChatBean chatBean = getChatBean(paramList, filename, videoFrameFileName);
            //boolean isSuccess =  chatDao.insertChat(con,chatBean);
            boolean isSuccess = true;
            if(isSync(con)) {
                isSuccess =  chatDao.insertChat(con,chatBean);    
            }
            
            if(isSuccess) {
                String chatBeanGson =  new Gson().toJson(chatBean);                
                baseResult.setSuccess(true);
                baseResult.setData(chatBeanGson);    
            } else {
                baseResult.setSuccess(false);
            }
            
        } catch(Exception e) {
            e.printStackTrace();
            baseResult.setSuccess(false);
        } finally {
            PrintWriterUtils.basePrintWriterObject(response, baseResult);
            DbUtils.getInstance().close(con);
        }
    }
    
    //上传语音
    private void processUploadVoice(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("上传聊天语音");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        
        factory.setSizeThreshold(1024 * 1024);
        List items = null;
        //语音文件
        String filename = "";
        ArrayList<String> paramList = new ArrayList<String>();
        BaseResult<String> baseResult = new BaseResult<String>();
        Connection con = null;

        try {
            con = DbUtils.getInstance().getConnection();

            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while(iter.hasNext()) {
                FileItem item = (FileItem)iter.next();
                                
                if(!item.isFormField()) {
                    filename = System.currentTimeMillis() + ".mp3";
                    String resultPath = BaseUtils.getUploadPath(request);
                    File f = new File(resultPath);
                    if(!f.exists()) {
                        f.mkdirs();
                    }
                    String videosrc = resultPath + filename;
                    InputStream is = item.getInputStream();
                    FileOutputStream fos = new FileOutputStream(videosrc);
                    byte b[] = new byte[1024 * 1024];
                    int length = 0;
                    while(-1 != (length = is.read(b))) {
                        fos.write(b, 0, length);
                    }
                    fos.flush();
                    fos.close();
                    
                    System.out.println("上传聊天语音频路径:" + filename);
                } else {
                    //获取其他参数
                    String value = item.getString("UTF-8");
                    paramList.add(value);
                }
            }
            
            ChatBean chatBean = getChatBean(paramList, filename, "");
            //boolean isSuccess =  chatDao.insertChat(con,chatBean);
            boolean isSuccess = true;
            if(isSync(con)) {
                isSuccess =  chatDao.insertChat(con,chatBean);    
            }
            if(isSuccess) {
                String chatBeanGson =  new Gson().toJson(chatBean);                
                baseResult.setSuccess(true);
                baseResult.setData(chatBeanGson);
            } else {
                baseResult.setSuccess(false);
            }
            
            
        } catch(Exception e) {
            e.printStackTrace();
            baseResult.setSuccess(false);
        } finally {
            PrintWriterUtils.basePrintWriterObject(response, baseResult);
            DbUtils.getInstance().close(con);
        }
    }

    
    /**
     * 获取聊天对象
     * @param paramList
     * @param filePath 文件路径
     * @param videoFrame 小视频缩略图
     * @return
     */
    private ChatBean getChatBean(ArrayList<String> paramList, String filePath,String videoFrame){
        ChatBean chatBean = new ChatBean();
        String fromAccount = paramList.get(0);
        String toAccount = paramList.get(1);
        int contentType = Integer.parseInt(paramList.get(2));
        int userType = Integer.parseInt(paramList.get(3));
        String messageId = paramList.get(4);
        int second = Integer.parseInt(paramList.get(5));
        
        chatBean.setFromAccount(fromAccount);
        chatBean.setToAccount(toAccount);
        chatBean.setContent("");
        chatBean.setContentType(contentType);
        chatBean.setUserType(userType);
        chatBean.setMessageId(messageId);
        chatBean.setAddTime(TimeUtils.getAddTime());
        chatBean.setLatitude(0.0);
        chatBean.setLongitude(0.0);
        chatBean.setVideo("");
        chatBean.setVideoLocal("");
        chatBean.setVoice("");
        chatBean.setVoiceLocal("");
        chatBean.setImgPathLocal("");
        chatBean.setSecond(second);
        
        
        if(contentType == CommonUtils.Chat.CONTENT_TYPE_IMG) {
            chatBean.setImgPath(filePath);
            
        } else if(contentType == CommonUtils.Chat.CONTENT_TYPE_VIDEO) {
            chatBean.setVideo(filePath);
            //缩略图
            chatBean.setImgPath(videoFrame);
        } else if(contentType == CommonUtils.Chat.CONTENT_TYPE_VOICE) {
            chatBean.setVoice(filePath);
            chatBean.setImgPath("");
        }
        
        return chatBean;
            
    }
    
    private Boolean isSync(Connection con) throws Exception {
        BaseSystemBean baseSystemBean =  baseSystemDao.getBaseSystem(con, "com.wn.wechatclientdemo");
        return baseSystemBean.getSync() == 1;
    }
    

}
 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐