com.kingen.web.CommonController.java Source code

Java tutorial

Introduction

Here is the source code for com.kingen.web.CommonController.java

Source

/**
 * Copyright &copy; 2012-2013 <a href="https://github.com//jeesite">JeeSite</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.kingen.web;

import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.google.common.collect.Lists;
import com.kingen.bean.User;
import com.kingen.service.CommonService;
import com.kingen.service.account.AccountService;
import com.kingen.util.DateUtils;
import com.kingen.util.FastjsonFilter;
import com.kingen.util.SpringContextHolder;
import com.kingen.util.mapper.JsonMapper;
import com.kingen.vo.Comboable;

/**
 * get? Tomcat? conf/server.xml<Connector port="8080" />?<Connector port="8080" uRIEncoding="utf-8" />
 * 
 * ?
 * @author 
 * @version 2013-3-23
 */
@Controller
public abstract class CommonController {

    /**
     * 
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    //commonservicecommondao?
    //   private static CommonService service = SpringContextHolder.getBean(CommonService.class);

    @Autowired
    private AccountService service;

    /**
     * current session's user
     * @return
     */
    protected User getCurrentUser() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        return user;
    }

    /**
     * JSON
     * @param response
     * @param object
     * @return
     */
    protected String renderJsonString(HttpServletResponse response, Object object) {
        return renderString(response, JsonMapper.toJsonString(object), "application/json");
    }

    /**
     * 
     * @param response
     * @param string
     * @return
     */
    protected String renderString(HttpServletResponse response, String string, String type) {
        try {
            response.reset();
            response.setContentType(type);
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
            return null;
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * ?
     */
    @ExceptionHandler({ BindException.class, ConstraintViolationException.class, ValidationException.class })
    public String bindException() {
        return "error/400";
    }

    /**
     * ?
     */
    @ExceptionHandler({ AuthenticationException.class })
    public String authenticationException() {
        return "error/403";
    }

    /**
     * ??
     * 1. ?StringHTML?XSS
     * 2. Date?String
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // String??StringHTML?XSS
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : text.trim());
                //            setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
                //            setValue(text == null ? null : StringEscapeUtils.escapeJavaScript(text.trim()));
            }

            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        // Date ?
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {

                setValue(DateUtils.parseDate(StringUtils.trim(text)));
                logger.debug("---" + getValue());
            }
        });
    }

    public void writeJson(HttpServletResponse response, Object object) {
        writeJsonByFilter(response, object, null, null);
    }

    public void writeJson(HttpServletResponse response, Object object, String[] includesProperties,
            String[] excludesProperties) {
        writeJsonByFilter(response, object, includesProperties, excludesProperties);
    }

    public void writeJsonInclude(HttpServletResponse response, Object object, String[] includesProperties) {
        writeJsonByFilter(response, object, includesProperties, null);
    }

    public void writeJson(HttpServletResponse response, Object object, String[] excludesProperties) {
        writeJsonByFilter(response, object, null, excludesProperties);
    }

    /**
     * ??JSON???
     * 
     * @param object
     * @param includesProperties
     *            ??
     * @param excludesProperties
     *            ???
     */
    public void writeJsonByFilter(HttpServletResponse response, Object object, String[] includesProperties,
            String[] excludesProperties) {
        try {
            FastjsonFilter filter = new FastjsonFilter();// excludesincludes
            if (excludesProperties != null && excludesProperties.length > 0) {
                filter.getExcludes().addAll(Arrays.<String>asList(excludesProperties));
            }
            if (includesProperties != null && includesProperties.length > 0) {
                filter.getIncludes().addAll(Arrays.<String>asList(includesProperties));
            }
            //logger.info("JSON?[" + excludesProperties + "]??[" + includesProperties + "]");
            String json;
            String User_Agent = getRequest().getHeader("User-Agent");
            if (StringUtils.indexOfIgnoreCase(User_Agent, "MSIE 6") > -1) {
                // SerializerFeature.BrowserCompatible?\\uXXXX??IE6
                json = JSON.toJSONString(object, filter, SerializerFeature.WriteDateUseDateFormat,
                        SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.BrowserCompatible);
            } else {
                // SerializerFeature.WriteDateUseDateFormat???yyyy-MM-dd hh24:mi:ss
                // SerializerFeature.DisableCircularReferenceDetect?
                json = JSON.toJSONString(object, filter, SerializerFeature.WriteDateUseDateFormat,
                        SerializerFeature.DisableCircularReferenceDetect);
            }
            //logger.info("??JSON" + json);
            response.setContentType("text/html;charset=utf-8");

            //         response.getWriter().write(json);
            //         response.getWriter().flush();
            //         response.getWriter().close();

            //         response.getOutputStream().write(json.getBytes());
            response.getOutputStream().write(json.getBytes("UTF-8"));
            response.getOutputStream().flush();
            response.getOutputStream().close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * ??JSON???
     * 
     * @param object
     * @param includesProperties
     *            ??
     * @param excludesProperties
     *            ???
     */
    public void writeJackson(HttpServletResponse response, Object object, String[] includesProperties,
            String[] excludesProperties) {
        try {

            ObjectMapper mapper = new ObjectMapper(); //?  

            String json = serializeOnlyGivenFields(object, Arrays.asList(excludesProperties));//??json  
            response.setContentType("text/html;charset=utf-8");

            response.getOutputStream().write(json.getBytes("UTF-8"));
            response.getOutputStream().flush();
            response.getOutputStream().close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String FILTER_NAME = "fieldFilter";

    public static String serializeOnlyGivenFields(Object o, Collection<String> fields)
            throws JsonProcessingException {
        if ((fields == null) || fields.isEmpty())
            fields = new HashSet<String>();

        Set<String> properties = new HashSet<String>(fields);

        SimpleBeanPropertyFilter filter = new SimpleBeanPropertyFilter.FilterExceptFilter(properties);
        SimpleFilterProvider fProvider = new SimpleFilterProvider();
        fProvider.addFilter(FILTER_NAME, filter);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setAnnotationIntrospector(new AnnotationIntrospector());

        String json = mapper.writer(fProvider).writeValueAsString(o);
        return json;
    }

    private static class AnnotationIntrospector extends JacksonAnnotationIntrospector {
        @Override
        public Object findFilterId(Annotated a) {
            return FILTER_NAME;
        }
    }

    /**
     * request
     * 
     * @return
     */
    public HttpServletRequest getRequest() {
        //      return ServletActionContext.getRequest();
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * response
     * 
     * @return
     */

    /**
     * session
     * 
     * @return
     */
    public HttpSession getSession() {
        //      return ServletActionContext.getRequest().getSession();
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
    }

    @RequestMapping(value = "combo/{entityName}")
    protected void data(@PathVariable("entityName") String entityName, HttpServletResponse response) {
        List<Object> result = service.list(entityName);
        List<Comboable> com = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(result)) {
            for (Object o : result) {
                if (o instanceof Comboable) {
                    com.add((Comboable) o);
                }
            }
        }
        writeJson(response, com);
    }
}