bing.li před 5 roky
rodič
revize
4c01188741

+ 107 - 68
src/main/java/cn/efunbox/audio/aop/AllowOriginIntercepter.java

@@ -1,68 +1,107 @@
-package cn.efunbox.audio.aop;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.util.StringUtils;
-import org.springframework.web.servlet.HandlerInterceptor;
-import org.springframework.web.servlet.ModelAndView;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * Created by libin on 2015/5/13.
- */
-@Component
-public class  AllowOriginIntercepter implements HandlerInterceptor {
-    private static final Logger logger = LoggerFactory.getLogger(AllowOriginIntercepter.class);
-    private String allowValue = "precms.api.ai160.com,precms.ai160.com,cms.api.ai160.com,cms.ai160.com,efunbox.cn,cms.api.efunbox.cn,*";
-
-    @Override
-    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
-
-        String origin = request.getHeader("Origin");
-        //logger.info("进入AllowOriginIntercepter 拦截 origin={}",origin);
-        String headers = request.getHeader("Access-Control-Request-Headers");
-        if (!StringUtils.isEmpty(headers)) {
-            headers = ", " + headers;
-        } else {
-            headers = "";
-        }
-        if (!StringUtils.isEmpty(origin)) {
-            if (originIsAllow(origin, allowValue)) {
-                response.setHeader("Access-Control-Allow-Origin", origin);
-                response.setHeader("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE, PATCH");
-                response.setHeader("Access-Control-Allow-Headers", "Origin, X-Token, Authentication, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization, Cache-control, id, token "+headers);
-                response.setHeader("Access-Control-Allow-Credentials", "true");
-            }
-        }
-        return true;
-    }
-
-    @Override
-    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
-
-    }
-
-    @Override
-    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
-
-    }
-
-    private boolean originIsAllow(String origin, String value) {
-        if (StringUtils.isEmpty(value)) {
-            return false;
-        }
-        if (value.contains("*")) {
-            return true;
-        }
-        String[] values = value.split(",");
-        for (String s : values) {
-            if (origin.indexOf(s) > -1) {
-                return true;
-            }
-        }
-        return false;
-    }
-}
+package cn.efunbox.audio.aop;
+
+import cn.efunbox.audio.utils.ApiResult;
+import com.alibaba.fastjson.JSON;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+import org.springframework.web.servlet.HandlerInterceptor;
+import org.springframework.web.servlet.ModelAndView;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.PrintWriter;
+
+/**
+ * Created by libin on 2015/5/13.
+ */
+@Component
+public class  AllowOriginIntercepter implements HandlerInterceptor {
+    private static final Logger logger = LoggerFactory.getLogger(AllowOriginIntercepter.class);
+    private String allowValue = "precms.api.ai160.com,precms.ai160.com,cms.api.ai160.com,cms.ai160.com,efunbox.cn,cms.api.efunbox.cn,*";
+
+    @Override
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+
+        String origin = request.getHeader("Origin");
+        //logger.info("进入AllowOriginIntercepter 拦截 origin={}",origin);
+        String headers = request.getHeader("Access-Control-Request-Headers");
+
+        //忽略 OPTIONS 请求
+        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
+            logger.info("OPTIONS 请求 忽略 返回200");
+            //将实体对象转换为JSON Object转换
+            response.setCharacterEncoding("UTF-8");
+            response.setStatus(HttpStatus.OK.value());
+            if (null!=origin){
+                response.setHeader("Access-Control-Allow-Origin", origin);
+            }else {
+                response.setHeader("Access-Co..." +
+                        "ntrol-Allow-Origin", "*");
+            }
+            response.setContentType("application/json; charset=utf-8");
+            response.setHeader("Access-Control-Allow-Credentials", "true");
+            response.setHeader("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE, PATCH");
+            response.setHeader("Access-Control-Max-Age", "3600");
+            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Token,Authentication, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization, Cache-control, "+headers);
+            response.setHeader("X-Frame-Options","SAMEORIGIN");
+            PrintWriter out = null;
+            try {
+                out = response.getWriter();
+                out.append(JSON.toJSONString(ApiResult.ok()));
+            } catch (IOException e) {
+                logger.error("request ={} 返回 失败 e={}" ,request.getRequestURI(),e);
+            } finally {
+                if (out != null) {
+                    out.close();
+                }
+            }
+            return false;
+        }
+
+        if (!StringUtils.isEmpty(headers)) {
+            headers = ", " + headers;
+        } else {
+            headers = "";
+        }
+        if (!StringUtils.isEmpty(origin)) {
+            if (originIsAllow(origin, allowValue)) {
+                response.setHeader("Access-Control-Allow-Origin", origin);
+                response.setHeader("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE, PATCH");
+                response.setHeader("Access-Control-Allow-Headers", "Origin, X-Token, Authentication, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization, Cache-control, id, token "+headers);
+                response.setHeader("Access-Control-Allow-Credentials", "true");
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
+
+    }
+
+    @Override
+    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
+
+    }
+
+    private boolean originIsAllow(String origin, String value) {
+        if (StringUtils.isEmpty(value)) {
+            return false;
+        }
+        if (value.contains("*")) {
+            return true;
+        }
+        String[] values = value.split(",");
+        for (String s : values) {
+            if (origin.indexOf(s) > -1) {
+                return true;
+            }
+        }
+        return false;
+    }
+}

+ 44 - 0
src/main/java/cn/efunbox/audio/aop/ResLogInterceptor.java

@@ -0,0 +1,44 @@
+package cn.efunbox.audio.aop;
+
+import cn.efunbox.audio.entity.res.ResUserEvent;
+import cn.efunbox.audio.service.res.ResUserEventService;
+import cn.efunbox.audio.utils.SnowflakeIdUtil;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.servlet.HandlerInterceptor;
+import org.springframework.web.servlet.ModelAndView;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+public class ResLogInterceptor implements HandlerInterceptor {
+
+    @Autowired
+    ResUserEventService resUserEventService;
+
+    @Override
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+        //System.out.println(request.getServletPath());
+        //System.out.println(request.getHeader("USERID"));
+        //记入日志
+        String userId = request.getHeader("USERID");
+        if(StringUtils.isNotBlank(userId)) {
+            ResUserEvent resUserEvent = new ResUserEvent();
+            resUserEvent.setId(SnowflakeIdUtil.getSnowflakeIdUtil().nextId());
+            resUserEvent.setInterfaceName(request.getServletPath());
+            resUserEvent.setUserId(userId);
+            resUserEventService.recordLog(resUserEvent);
+        }
+        return true;
+    }
+
+    @Override
+    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
+
+    }
+
+    @Override
+    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
+
+    }
+}

+ 29 - 15
src/main/java/cn/efunbox/audio/config/Config.java

@@ -1,9 +1,6 @@
 package cn.efunbox.audio.config;
 
-import cn.efunbox.audio.aop.AdminInterceptor;
-import cn.efunbox.audio.aop.AllowOriginIntercepter;
-import cn.efunbox.audio.aop.AuthInterceptor;
-import cn.efunbox.audio.aop.IgnoreOptionsInterceptor;
+import cn.efunbox.audio.aop.*;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@@ -16,48 +13,65 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
  */
 @Configuration
 @EnableWebMvc
-public class Config extends WebMvcConfigurerAdapter{
+public class Config extends WebMvcConfigurerAdapter {
 
     /**
      * 直接采用new interceptor或Autowired注入拦截器会导致dao为null的错误
+     *
      * @return
      */
     @Bean
-    AuthInterceptor authInterceptor(){
+    AuthInterceptor authInterceptor() {
         return new AuthInterceptor();
     }
 
     @Bean
-    AdminInterceptor adminInterceptor(){
+    AdminInterceptor adminInterceptor() {
         return new AdminInterceptor();
     }
 
     @Bean
-    AllowOriginIntercepter allowOriginIntercepter(){
+    AllowOriginIntercepter allowOriginIntercepter() {
         return new AllowOriginIntercepter();
     }
 
     @Bean
-    IgnoreOptionsInterceptor ignoreOptionsInterceptor(){
+    IgnoreOptionsInterceptor ignoreOptionsInterceptor() {
         return new IgnoreOptionsInterceptor();
     }
 
+    @Bean
+    ResLogInterceptor resLogInterceptor() {
+        return new ResLogInterceptor();
+    }
+
     @Override
     public void addInterceptors(InterceptorRegistry registry) {
         registry.addInterceptor(authInterceptor())
-                .addPathPatterns("/audio/search","/audio/searchList","/audio/info/{audioId}","/album","/album/{albumId}")
-                .excludePathPatterns("/device/**", "/error","/audio/*");
+                .addPathPatterns("/audio/search", "/audio/searchList", "/audio/info/{audioId}", "/album", "/album/{albumId}")
+                .excludePathPatterns("/device/**", "/error", "/audio/*");
 
         registry.addInterceptor(adminInterceptor())
                 .addPathPatterns("/**", "/device/update", "/device/delete")
-                .excludePathPatterns("/device/**","/audio/info/{audioId}", "/error", "/admin/login", "/audio/search","/file/**","/audio/searchList","/statistics","/album","/album/{albumId}")
-                .excludePathPatterns("/getTypeList","/getTypeContentList","/getContentDetail","/getContentChapterList","/getChapterDetail","/test/**","/getTypeUpdateList/**","/getContentUpdateList/**","/getChapterUpdateList/**");
+                .excludePathPatterns("/device/**", "/audio/info/{audioId}", "/error", "/admin/login", "/audio/search", "/file/**", "/audio/searchList", "/statistics", "/album", "/album/{albumId}")
+
+                .excludePathPatterns("/getTypeList", "/getTypeContentList", "/getContentDetail", "/getContentChapterList", "/getChapterDetail", "/getTypeUpdateList", "/getContentUpdateList", "/getChapterUpdateList", "/getTypeUpdateList/**", "/getContentUpdateList/**", "/getChapterUpdateList/**");
+
+        //杭研开放接口
+        //.excludePathPatterns("/getTypeList","/getTypeContentList","/getContentDetail","/getContentChapterList","/getChapterDetail","/getTypeUpdateList","/getContentUpdateList","/getChapterUpdateList");
+
 
         registry.addInterceptor(ignoreOptionsInterceptor())
+                .addPathPatterns("/**")
+                //杭研开放接口
+                .excludePathPatterns("/getTypeList", "/getTypeContentList", "/getContentDetail", "/getContentChapterList", "/getChapterDetail", "/getTypeUpdateList", "/getContentUpdateList", "/getChapterUpdateList");
+
+        registry.addInterceptor(allowOriginIntercepter())
                 .addPathPatterns("/**");
 
-//        registry.addInterceptor(allowOriginIntercepter())
-//                .addPathPatterns("/**");
+        //杭研接口日志拦截器
+        registry.addInterceptor(resLogInterceptor())
+                .addPathPatterns("/getTypeList", "/getTypeContentList", "/getContentDetail", "/getContentChapterList", "/getChapterDetail", "/getTypeUpdateList", "/getContentUpdateList", "/getChapterUpdateList");
     }
 
 //    /**

+ 2 - 2
src/main/java/cn/efunbox/audio/entity/res/ResCategory.java

@@ -31,8 +31,8 @@ public class ResCategory {
     @Column(name = "sort")
     private String sort;
 
-    @Column(name = "type_update_time")
-    private String typeUpdateTime;
+    @Column(name = "type_updatetime")
+    private String typeUpdatetime;
 
     @Column(name = "is_del")
     private String isDel;

+ 36 - 0
src/main/java/cn/efunbox/audio/entity/res/ResUserEvent.java

@@ -0,0 +1,36 @@
+package cn.efunbox.audio.entity.res;
+
+import lombok.Data;
+import lombok.ToString;
+import org.hibernate.annotations.DynamicInsert;
+import org.hibernate.annotations.DynamicUpdate;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import java.util.Date;
+
+@ToString
+@Entity
+@DynamicInsert
+@DynamicUpdate
+@Data
+@Table(name = "res_user_event")
+public class ResUserEvent {
+
+    @Id
+    private Long id;
+
+    @Column(name = "user_id")
+    private String userId;
+
+    @Column(name = "interface_name")
+    private String interfaceName;
+
+    @Column(name = "gmt_created")
+    private Date gmtCreated;
+
+    @Column(name = "gmt_modified")
+    private Date gmtModified;
+}

+ 34 - 0
src/main/java/cn/efunbox/audio/impl/res/ResUserEventServiceImpl.java

@@ -0,0 +1,34 @@
+package cn.efunbox.audio.impl.res;
+
+import cn.efunbox.audio.entity.res.ResUserEvent;
+import cn.efunbox.audio.repository.res.ResUserEventRepository;
+import cn.efunbox.audio.service.res.ResUserEventService;
+import cn.efunbox.audio.utils.ResApiCode;
+import cn.efunbox.audio.utils.ResApiResult;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+@Service
+@Slf4j
+public class ResUserEventServiceImpl implements ResUserEventService {
+
+    @Autowired
+    ResUserEventRepository resUserEventRepository;
+
+    /**
+     * 记录日志
+     * @param resUserEvent
+     */
+    @Override
+    public ResApiResult recordLog(ResUserEvent resUserEvent) {
+
+        try {
+            resUserEventRepository.save(resUserEvent);
+        } catch (Exception e) {
+            log.info("日志记录发生异常:{}",e.getMessage());
+            ResApiResult.error(ResApiCode.UNKNOWN_ERROR);
+        }
+        return ResApiResult.ok();
+    }
+}

+ 7 - 7
src/main/java/cn/efunbox/audio/repository/AudioRepoImpl.java

@@ -27,7 +27,7 @@ public class AudioRepoImpl {
 
     public List<Audio> findAudio(SearchVO searchVO, Integer pageStart, int pageSize) {
 
-        StringBuilder sb = new StringBuilder("select * from audio where 1=1 ");
+        StringBuilder sb = new StringBuilder("select * from audio where 1=1");
 
         fillSql(searchVO,sb);
 
@@ -41,7 +41,7 @@ public class AudioRepoImpl {
 
     public Long count(SearchVO searchVO) {
 
-        StringBuilder sb = new StringBuilder("select count(*) from audio where 1=1 ");
+        StringBuilder sb = new StringBuilder("select count(*) from audio where 1=1");
 
         fillSql(searchVO,sb);
         Query query = entityManager.createNativeQuery(sb.toString());
@@ -53,16 +53,16 @@ public class AudioRepoImpl {
     private void fillSql(SearchVO searchVO, StringBuilder sb) {
 
         if (StringUtils.isNotBlank(searchVO.getName())) {
-            sb.append("and name like '%").append(searchVO.getName()).append("%'");
+            sb.append(" and name like \"%").append(searchVO.getName()).append("%\"");
         }
 
         if (StringUtils.isNotBlank(searchVO.getKeyword())) {
-            sb.append("and name like '%").append(searchVO.getKeyword()).append("%'");
+            sb.append(" and name like \"%").append(searchVO.getKeyword()).append("%\"");
         }
 
         List<BigInteger> idAlbums = searchVO.getIdAlbums();
         if (!CollectionUtils.isEmpty(idAlbums)) {
-            sb.append("and album_id in (");
+            sb.append(" and album_id in (");
             for (int i = 0; i < idAlbums.size();i++) {
                 if (i > 0) {
                     sb.append(",");
@@ -74,7 +74,7 @@ public class AudioRepoImpl {
 
         List<Long> idGroups = searchVO.getIdGroups();
         if (!CollectionUtils.isEmpty(idGroups)) {
-            sb.append("and id_group in (");
+            sb.append(" and id_group in (");
             for (int i = 0; i < idGroups.size();i++) {
                 if (i > 0) {
                     sb.append(",");
@@ -85,7 +85,7 @@ public class AudioRepoImpl {
         }
 
         if (Objects.nonNull(searchVO.getMediaType()) && searchVO.getMediaType() > 0) {
-            sb.append("and media_type = ");
+            sb.append(" and media_type = ");
             sb.append( searchVO.getMediaType() );
         }
 

+ 8 - 0
src/main/java/cn/efunbox/audio/repository/res/ResUserEventRepository.java

@@ -0,0 +1,8 @@
+package cn.efunbox.audio.repository.res;
+
+import cn.efunbox.audio.entity.res.ResUserEvent;
+import cn.efunbox.audio.repository.base.BasicRepository;
+
+public interface ResUserEventRepository extends BasicRepository<ResUserEvent> {
+
+}

+ 9 - 0
src/main/java/cn/efunbox/audio/service/res/ResUserEventService.java

@@ -0,0 +1,9 @@
+package cn.efunbox.audio.service.res;
+
+import cn.efunbox.audio.entity.res.ResUserEvent;
+import cn.efunbox.audio.utils.ResApiResult;
+
+public interface ResUserEventService {
+
+    public ResApiResult recordLog(ResUserEvent resUserEvent);
+}