Browse Source

针对saas的参数处理

yingp 7 years ago
parent
commit
42a9cde79d

+ 2 - 0
src/main/docker/Dockerfile

@@ -1,4 +1,6 @@
 FROM tomcat
 
+MKDIR /opt/report/data/DEFAULT/jrxml
+MKDIR /opt/report/data/DEFAULT/Picture
 ADD report-0.0.1.jar /usr/local/tomcat/webapps/report.jar
 ENV JAVA_OPTS="$JAVA_OPTS -server -Xmx2g -Xms1g -Duser.timezone=GMT+08 -Dfile.encoding=utf-8"

+ 10 - 0
src/main/java/com/uas/report/SpecialProperties.java

@@ -60,6 +60,9 @@ public class SpecialProperties {
 	@Value("${datasource}")
 	private String dataSourceInformation;
 
+	@Value("${defaultUserName:}")
+	private String defaultUserName;
+
 	public String getLocalBaseDir() {
 		return localBaseDir;
 	}
@@ -124,4 +127,11 @@ public class SpecialProperties {
 		this.dataSourceInformation = dataSourceInformation;
 	}
 
+	public String getDefaultUserName() {
+		return defaultUserName;
+	}
+
+	public void setDefaultUserName(String defaultUserName) {
+		this.defaultUserName = defaultUserName;
+	}
 }

+ 16 - 0
src/main/java/com/uas/report/WebAppConfiguration.java

@@ -4,7 +4,9 @@ import java.nio.charset.Charset;
 import java.util.Arrays;
 import java.util.List;
 
+import com.uas.report.web.UserNameResolver;
 import org.apache.axis.transport.http.AxisServlet;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.web.servlet.FilterRegistrationBean;
 import org.springframework.boot.web.servlet.ServletRegistrationBean;
 import org.springframework.context.annotation.Bean;
@@ -13,6 +15,7 @@ import org.springframework.context.annotation.Configuration;
 import org.springframework.http.MediaType;
 import org.springframework.http.converter.HttpMessageConverter;
 import org.springframework.http.converter.StringHttpMessageConverter;
+import org.springframework.web.method.support.HandlerMethodArgumentResolver;
 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
 import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
 import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
@@ -29,6 +32,9 @@ import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
 @ComponentScan(basePackages = "com.uas.report.controller")
 public class WebAppConfiguration extends WebMvcConfigurerAdapter {
 
+	@Autowired
+	private SpecialProperties specialProperties;
+
 	@Override
 	public void addResourceHandlers(ResourceHandlerRegistry registry) {
 		// Spring boot默认资源路径在src/main/resources下,而非/src/main/webapp
@@ -97,4 +103,14 @@ public class WebAppConfiguration extends WebMvcConfigurerAdapter {
 		return servletRegistrationBean;
 	}
 
+	@Bean
+	public UserNameResolver userNameResolver() {
+		return new UserNameResolver(specialProperties.getDefaultUserName());
+	}
+
+	@Override
+	public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
+		argumentResolvers.add(userNameResolver());
+		super.addArgumentResolvers(argumentResolvers);
+	}
 }

+ 0 - 4
src/main/java/com/uas/report/controller/FileController.java

@@ -43,7 +43,6 @@ public class FileController {
 	@ResponseBody
 	public String upload(String userName, String fileType, String filePath, Boolean isAbsolutePath,
 			@RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws IOException {
-		userName = userName == null ? null : userName.toUpperCase();
 		// 未指定上传文件路径,则按照账套名称上传
 		// 该情况下,不会上传多个文件的
 		if (StringUtils.isEmpty(filePath)) {
@@ -80,7 +79,6 @@ public class FileController {
 	@RequestMapping("/download/zip")
 	public void downloadZip(String userName, HttpServletRequest request, HttpServletResponse response)
 			throws IOException {
-		userName = userName == null ? null : userName.toUpperCase();
 		fileService.downloadZip(userName, response);
 	}
 
@@ -97,7 +95,6 @@ public class FileController {
 	@RequestMapping("/download/jrxml")
 	public void downloadJrxml(String userName, String reportName, HttpServletRequest request,
 			HttpServletResponse response) throws IOException {
-		userName = userName == null ? null : userName.toUpperCase();
 		fileService.download(fileService.getJrxmlFilePath(userName, reportName), true, response);
 	}
 
@@ -112,7 +109,6 @@ public class FileController {
 	@ResponseBody
 	public Map<String, Object> standardJrxmls(String userName, String onlyData, HttpServletRequest request,
 			HttpServletResponse response) throws IOException {
-		userName = userName == null ? null : userName.toUpperCase();
 		// onlyData为真,只返回字节数据(自动部署时只获取标准模板字节数据),否则下载标准模板zip
 		if (!StringUtils.isEmpty(onlyData) && (onlyData.equals("1") || onlyData.equals("true"))) {
 			Map<String, Object> result = new HashMap<>();

+ 4 - 16
src/main/java/com/uas/report/controller/PrintController.java

@@ -6,7 +6,6 @@ import java.io.IOException;
 import java.io.OutputStream;
 import java.net.URLEncoder;
 import java.sql.SQLException;
-import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -14,6 +13,7 @@ import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
+import com.uas.report.util.*;
 import org.dom4j.DocumentException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -24,13 +24,6 @@ import org.springframework.web.bind.annotation.ResponseBody;
 
 import com.uas.report.service.FileService;
 import com.uas.report.service.PrintService;
-import com.uas.report.util.ArrayUtils;
-import com.uas.report.util.CollectionUtils;
-import com.uas.report.util.FileUtils;
-import com.uas.report.util.Platform;
-import com.uas.report.util.ReportConstants;
-import com.uas.report.util.ReportUtils;
-import com.uas.report.util.StringUtils;
 
 import net.sf.jasperreports.engine.JRException;
 
@@ -45,7 +38,7 @@ import net.sf.jasperreports.engine.JRException;
 @RequestMapping("/print")
 public class PrintController {
 
-	private static final long timestamp = new Date().getTime();
+	private static final long timestamp = System.currentTimeMillis();
 
 	@Autowired
 	private PrintService printService;
@@ -82,11 +75,10 @@ public class PrintController {
 	 * @throws JRException
 	 * @throws ServletException
 	 */
-	@RequestMapping()
+	@RequestMapping
 	public void print(String userName, String profile, String reportName, String whereCondition, String otherParameters,
 			String printType, String title, HttpServletRequest request, HttpServletResponse response)
 			throws JRException, IOException, DocumentException, SQLException, ServletException {
-		userName = userName == null ? null : userName.toUpperCase();
 		// printType为空,默认进入预览页
 		if (StringUtils.isEmpty(printType)) {
 			printType = ReportConstants.PRINT_TYPE_PREVIEW;
@@ -149,7 +141,6 @@ public class PrintController {
 	public void export(String userName, String profile, String reportName, String whereCondition,
 			String otherParameters, String exportFileType, Boolean flush, String title, HttpServletRequest request,
 			HttpServletResponse response) throws JRException, IOException, DocumentException, SQLException {
-		userName = userName == null ? null : userName.toUpperCase();
 		ReportUtils.checkParameters(userName, reportName);
 		String masterOfJrxml = printService.getMasterOfJrxml(userName, reportName);
 		if (StringUtils.isEmpty(exportFileType)) {
@@ -232,7 +223,6 @@ public class PrintController {
 	public String getPdfPath(String userName, final String profile, final String reportName,
 			final String whereCondition, final String otherParameters, Boolean flush, HttpServletRequest request,
 			HttpServletResponse response) throws JRException, IOException, DocumentException, SQLException {
-		userName = userName == null ? null : userName.toUpperCase();
 		ReportUtils.checkParameters(userName, reportName);
 		String masterOfJrxml = printService.getMasterOfJrxml(userName, reportName);
 
@@ -286,7 +276,6 @@ public class PrintController {
 	public Map<String, Object> getPdfData(String userName, String profile, String reportName, String whereCondition,
 			String otherParameters, HttpServletRequest request, HttpServletResponse response)
 			throws JRException, IOException, DocumentException, SQLException {
-		userName = userName == null ? null : userName.toUpperCase();
 		ReportUtils.checkParameters(userName, reportName);
 		Map<String, Object> result = new HashMap<>();
 		// 判断是否过载
@@ -304,7 +293,7 @@ public class PrintController {
 	/**
 	 * 获取该模板在当前条件下的结果数目
 	 * 
-	 * @param userName不为null;当前账套用户名
+	 * @param userName 不为null;当前账套用户名
 	 * @param profile
 	 *            用于标识请求源(B2C、B2B)是正式、测试还是开发版本:prod、test、dev
 	 * @param reportName
@@ -326,7 +315,6 @@ public class PrintController {
 	public int getCount(String userName, String profile, String reportName, String whereCondition,
 			String otherParameters, HttpServletRequest request, HttpServletResponse response)
 			throws SQLException, IOException, DocumentException {
-		userName = userName == null ? null : userName.toUpperCase();
 		ReportUtils.checkParameters(userName, reportName);
 		return printService.getCount(userName, profile, reportName, whereCondition, otherParameters);
 	}

+ 0 - 1
src/main/java/com/uas/report/controller/ResourceController.java

@@ -25,7 +25,6 @@ public class ResourceController {
 	@ResponseBody
 	public List<Resource> syncResources(String userName, HttpServletRequest request)
 			throws ClientProtocolException, URISyntaxException, IOException {
-		userName = userName == null ? null : userName.toUpperCase();
 		return resourceService.syncResources(userName);
 	}
 

+ 18 - 0
src/main/java/com/uas/report/service/impl/PrintServiceImpl.java

@@ -608,6 +608,23 @@ public class PrintServiceImpl implements PrintService {
 			if (!jrxmlFile.exists()) {
 				return specialProperties.getStandardMaster() + "/B2B";
 			}
+		} if (userName.startsWith("SAAS")) {
+			/**
+			 * saas的报表服务独立使用,文件结构:
+			 * /opt/report/data
+			 *   /DEFAULT
+			 *     /jrxml
+			 *     /Picture
+			 *   /1
+			 *     /jrxml
+			 *     /Picture
+			 */
+			String jrxmlFilePath = fileService.getJrxmlFilePath(userName, reportName);
+			File jrxmlFile = new File(jrxmlFilePath);
+			// 报表模板不存在,返回SAAS标准模板账套
+			if (!jrxmlFile.exists()) {
+				return specialProperties.getStandardMaster();
+			}
 		} else {
 			// 如果主账套与子账套共用模板
 			if (specialProperties.shareJrxmlsWithSubMaster()) {
@@ -661,6 +678,7 @@ public class PrintServiceImpl implements PrintService {
 			File jrxmlFile = new File(jrxmlFilePath);
 			// 报表模板不存在
 			if (!jrxmlFile.exists()) {
+				logger.error("file not found: " + jrxmlFile.getAbsolutePath());
 				// 替换windows下路径中的双反斜杠为单斜杠
 				throw new FileNotFoundException("报表模板不存在");
 			}

+ 16 - 12
src/main/java/com/uas/report/util/MasterManager.java

@@ -73,21 +73,25 @@ public class MasterManager {
 		if (StringUtils.isEmpty(userName)) {
 			return null;
 		}
+		String dataSourceName = userName;
+		if (dataSourceName.contains("/")) {
+			dataSourceName = dataSourceName.split("/")[0];
+		}
 		// 需要考虑B2B打印时账套名为B2B/10045740等类似的情况
 		if (!StringUtils.isEmpty(profile)) {
-			userName = userName.split("/")[0] + "_" + profile;
+			dataSourceName += "_" + profile;
 		}
-		userName = userName.toUpperCase();
-		DruidDataSource dataSource = dataSources.get(userName);
+		dataSourceName = dataSourceName.toUpperCase();
+		DruidDataSource dataSource = dataSources.get(dataSourceName);
 		// 如果Map里未存放该数据源,则可能是子帐套,需要从主账套表中获取
 		if (dataSource == null) {
 			Set<Entry<String, DruidDataSource>> entrySet = dataSources.entrySet();
 			for (Entry<String, DruidDataSource> entry : entrySet) {
-				dataSource = getDataSourceFromMainMaster(entry.getValue(), userName);
+				dataSource = getDataSourceFromMainMaster(entry.getValue(), dataSourceName);
 				if (dataSource != null) {
-					dataSources.put(userName, dataSource);
+					dataSources.put(dataSourceName, dataSource);
 					Master parent = new Master(entry.getKey());
-					masters.add(new Master(userName, parent));
+					masters.add(new Master(dataSourceName, parent));
 					return dataSource;
 				}
 			}
@@ -99,18 +103,18 @@ public class MasterManager {
 	 * 从主账套的MA_USER表中获取子账套数据源
 	 * 
 	 * @param mainMaster
-	 * @param userName
+	 * @param dataSourceName
 	 * @return
 	 * @throws SQLException 
 	 */
-	private static DruidDataSource getDataSourceFromMainMaster(DruidDataSource mainMaster, String userName) throws SQLException {
+	private static DruidDataSource getDataSourceFromMainMaster(DruidDataSource mainMaster, String dataSourceName) throws SQLException {
 		Connection connection = null;
 		PreparedStatement preparedStatement = null;
 		ResultSet resultSet = null;
 		try {
-			logger.info("mainMaster.getConnection..." + mainMaster.getUsername() + "," + userName);
+			logger.info("mainMaster.getConnection..." + mainMaster.getUsername() + "," + dataSourceName);
 			connection = mainMaster.getConnection();
-			logger.info("mainMaster.getConnection done..." + mainMaster.getUsername() + "," + userName);
+			logger.info("mainMaster.getConnection done..." + mainMaster.getUsername() + "," + dataSourceName);
 			// 先检查是否存在MASTER表
 			String sql = "select count(*) from user_tables where table_name='MASTER'";
 			preparedStatement = connection.prepareStatement(sql);
@@ -126,13 +130,13 @@ public class MasterManager {
 			// 根据当前账套用户名获取其数据库配置信息
 			sql = "select * from master where upper(MA_USER) = upper(?)";
 			preparedStatement = connection.prepareStatement(sql);
-			preparedStatement.setString(1, userName);
+			preparedStatement.setString(1, dataSourceName);
 			resultSet = preparedStatement.executeQuery();
 			if (resultSet.next() && !StringUtils.isEmpty(resultSet.getString("MS_PWD"))) {
 				String password = resultSet.getString("MS_PWD");
 				// 除了用户名、密码,其他属性一样
 				DruidDataSource result = mainMaster.cloneDruidDataSource();
-				result.setUsername(userName);
+				result.setUsername(dataSourceName);
 				result.setPassword(password);
 				return result;
 			}

+ 49 - 0
src/main/java/com/uas/report/web/UserNameResolver.java

@@ -0,0 +1,49 @@
+package com.uas.report.web;
+
+import com.uas.report.util.StringUtils;
+import org.springframework.core.MethodParameter;
+import org.springframework.web.bind.support.WebDataBinderFactory;
+import org.springframework.web.context.request.NativeWebRequest;
+import org.springframework.web.method.support.HandlerMethodArgumentResolver;
+import org.springframework.web.method.support.ModelAndViewContainer;
+
+/**
+ * 自动处理userName参数
+ * 简易版saas不需要userName,而需要companyId
+ *
+ * @author yingp
+ * @date 2018/11/8
+ */
+public class UserNameResolver implements HandlerMethodArgumentResolver {
+
+    private static final String USERNAME_PARAM_NAME = "userName";
+    private static final String COMPANY_ID_PARAM_NAME = "companyId";
+
+    private final String defaultUserName;
+
+    public UserNameResolver(String defaultUserName) {
+        this.defaultUserName = null == defaultUserName ? null : defaultUserName.toUpperCase();
+    }
+
+    @Override
+    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
+        String userName = nativeWebRequest.getParameter(USERNAME_PARAM_NAME);
+        if (!StringUtils.isEmpty(userName)) {
+            return userName.toUpperCase();
+        }
+        String companyId = nativeWebRequest.getParameter(COMPANY_ID_PARAM_NAME);
+        if (!StringUtils.isEmpty(defaultUserName)) {
+            if (null != companyId) {
+                return defaultUserName + "/" + companyId;
+            }
+            return defaultUserName;
+        }
+
+        return null;
+    }
+
+    @Override
+    public boolean supportsParameter(MethodParameter parameter) {
+        return parameter.getParameterName().equals(USERNAME_PARAM_NAME);
+    }
+}

+ 3 - 0
src/main/resources/config/application-saas-dev.properties → src/main/resources/config/application-saas-prod.properties

@@ -6,4 +6,7 @@ hasStandardJrxmls=true
 standardJrxmlsUrl=http://print.ubtob.com/report/file/standardJrxmls?userName=%s&onlyData=1
 shareJrxmlsWithSubMaster=false
 
+# saas无需切换数据源
+defaultUserName=SAAS_BIZ
+
 datasource={"SAAS_BIZ":{"driverClassName":"com.mysql.jdbc.Driver","url":"jdbc:mysql://192.168.253.12:3306/saas_biz?characterEncoding=utf-8&useSSL=false","username":"root","password":"select111***","initialSize":3,"minIdle":0,"maxActive":20,"maxWait":60000,"timeBetweenEvictionRunsMillis":60000,"minEvictableIdleTimeMillis":300000,"validationQuery":"SELECT 1","testWhileIdle":true,"testOnBorrow":true,"testOnReturn":false,"removeAbandoned":true,"removeAbandonedTimeout":120,"logAbandoned":true,"timeBetweenLogStatsMillis":600000,"poolPreparedStatements":true,"maxPoolPreparedStatementPerConnectionSize":20,"filters":"stat,slf4j","connectionProperties":"druid.stat.mergeSql=false;druid.stat.slowSqlMillis=5000"}}

+ 12 - 0
src/main/resources/config/application-saas-test.properties

@@ -0,0 +1,12 @@
+localBaseDir=/opt/report/data
+localImagesDir=/Picture
+localJrxmlDir=/jrxml
+standardMaster=DEFAULT
+hasStandardJrxmls=true
+standardJrxmlsUrl=http://print.ubtob.com/report/file/standardJrxmls?userName=%s&onlyData=1
+shareJrxmlsWithSubMaster=false
+
+# saas无需切换数据源
+defaultUserName=SAAS_BIZ
+
+datasource={"SAAS_BIZ":{"driverClassName":"com.mysql.jdbc.Driver","url":"jdbc:mysql://192.168.253.12:3306/saas_biz?characterEncoding=utf-8&useSSL=false","username":"root","password":"select111***","initialSize":3,"minIdle":0,"maxActive":20,"maxWait":60000,"timeBetweenEvictionRunsMillis":60000,"minEvictableIdleTimeMillis":300000,"validationQuery":"SELECT 1","testWhileIdle":true,"testOnBorrow":true,"testOnReturn":false,"removeAbandoned":true,"removeAbandonedTimeout":120,"logAbandoned":true,"timeBetweenLogStatsMillis":600000,"poolPreparedStatements":true,"maxPoolPreparedStatementPerConnectionSize":20,"filters":"stat,slf4j","connectionProperties":"druid.stat.mergeSql=false;druid.stat.slowSqlMillis=5000"}}