PageRenderTime 293ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/211Project/to211-web/src/main/java/com/to211/web/controller/OrganizationController.java

http://java-hiking.googlecode.com/
Java | 250 lines | 198 code | 32 blank | 20 comment | 12 complexity | ba4667722215e035d8df3eb75553b982 MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception
  1. package com.to211.web.controller;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.util.Date;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10. import javax.annotation.Resource;
  11. import javax.servlet.http.HttpServletResponse;
  12. import org.apache.commons.lang.StringUtils;
  13. import org.hibernate.validator.constraints.impl.EmailValidator;
  14. import org.springframework.stereotype.Controller;
  15. import org.springframework.web.bind.annotation.PathVariable;
  16. import org.springframework.web.bind.annotation.RequestMapping;
  17. import org.springframework.web.bind.annotation.RequestMethod;
  18. import org.springframework.web.bind.annotation.RequestParam;
  19. import org.springframework.web.multipart.MultipartFile;
  20. import org.springframework.web.servlet.ModelAndView;
  21. import com.alibaba.fastjson.JSON;
  22. import com.fdhay.authcenter.proxy.domain.annotation.Authorization;
  23. import com.fdhay.authcenter.proxy.domain.enums.AuthorizationType;
  24. import com.to211.common.Constants;
  25. import com.to211.common.util.FileUtils;
  26. import com.to211.common.util.HttpClientUtils;
  27. import com.to211.common.util.JavascriptUtils;
  28. import com.to211.domain.Domain;
  29. import com.to211.domain.OrganizationRegisterResponse;
  30. import com.to211.domain.WebDesignDTO;
  31. import com.to211.domain.base.json.JsonMessage;
  32. import com.to211.domain.enums.JsonMessageResultStatusEnum;
  33. import com.to211.service.DirectoryOfWebTemplateService;
  34. import com.to211.service.DirectoryService;
  35. import com.to211.service.DomainService;
  36. import com.to211.service.MessageService;
  37. import com.to211.service.OrganizationDetailService;
  38. @Controller
  39. @RequestMapping("/org")
  40. public class OrganizationController extends WebTemplateController {
  41. private static final String ERROR_MSG_DOMAIN_NAME_EXIST = "域名 - 已经被注册";
  42. private static final String ORGANIZATION_REGISTER_URL = Constants.cfg.getValue("organization.register.url", "organization.register.url");
  43. private static final String ORGANIZATION_REGISTER_APITOKEN = Constants.cfg.getValue("organization.register.APIToken", "organization.register.APIToken");
  44. protected static final String ORGANIZATION_WEB_DEFAULT_WEB_TEMPLATE_CODE = Constants.cfg.getValue("organization.web.defaultWebTemplateCode", "organization.web.defaultWebTemplateCode");
  45. private static final String ORGANIZATION_WEB_DEFAULT_WEB_LAYOUT_MAPPING = Constants.cfg.getValue("organization.web.defaultWebLayoutMapping", "organization.web.defaultWebLayoutMapping");
  46. @Resource
  47. private DomainService domainService;
  48. @Resource
  49. private DirectoryService directoryService;
  50. @Resource
  51. private MessageService messageService;
  52. @Resource
  53. private DirectoryOfWebTemplateService directoryOfWebTemplateService;
  54. @Resource
  55. private OrganizationDetailService organizationDetailService;
  56. @RequestMapping("/register")
  57. @Authorization(type=AuthorizationType.PUBLIC)
  58. public ModelAndView register(String subDomain, String email, String password) {
  59. StringBuilder errorMsg = registerPreCheck(subDomain, email, password);
  60. if(StringUtils.isNotEmpty(errorMsg.toString())){
  61. JsonMessage message = JsonMessage.fail();
  62. message.setResult("注册错误:" + errorMsg.toString());
  63. return toJSON(message);
  64. }
  65. Map<String, String> headers = new HashMap<String, String>(1);
  66. headers.put(Constants.KEY_OF_APITOKEN, ORGANIZATION_REGISTER_APITOKEN);
  67. Map<String, String> params = new HashMap<String, String>(2);
  68. params.put("email", email);
  69. params.put("password", password);
  70. try {
  71. String apiResponseJson = HttpClientUtils.post(ORGANIZATION_REGISTER_URL, params, headers);
  72. if(logger.isDebugEnabled()){
  73. logger.debug(apiResponseJson);
  74. }
  75. JsonMessage apiResponseMessage = JSON.parseObject(apiResponseJson, JsonMessage.class);
  76. if(JsonMessageResultStatusEnum.FAIL.equals(apiResponseMessage.getResultStatusCode())){
  77. JsonMessage message = JsonMessage.fail();
  78. message.setResult("注册失败:\n" + apiResponseMessage.getResult());
  79. return toJSON(message);
  80. }
  81. OrganizationRegisterResponse registerResponse = getRegisterResponse(apiResponseMessage);
  82. addDomainIntoDB(domainService.getFullOrgDomainName(subDomain), registerResponse);
  83. this.initOrganizationWebContent(registerResponse.getOrganizationCode());
  84. sendDomainApprovedEmail(subDomain, registerResponse);
  85. JsonMessage message = JsonMessage.sucess();
  86. message.setResult("注册成功!请通过邮箱查看详细信息\n");
  87. return toJSON(message);
  88. } catch (Exception e) {
  89. logger.error(e);
  90. JsonMessage message = JsonMessage.fail();
  91. message.setResult("注册失败");
  92. return toJSON(message);
  93. }
  94. }
  95. /**
  96. * 初始化机构的web主页内容
  97. * @param organizationCode
  98. */
  99. protected void initOrganizationWebContent(String organizationCode) {
  100. List<WebDesignDTO> sectionFillInList = JSON.parseArray(ORGANIZATION_WEB_DEFAULT_WEB_LAYOUT_MAPPING, WebDesignDTO.class);
  101. this.initOrganizationWebContent(organizationCode, ORGANIZATION_WEB_DEFAULT_WEB_TEMPLATE_CODE, sectionFillInList);
  102. }
  103. /**
  104. * 初始化机构的web主页内容
  105. * @param organizationCode - 要操作的机构的机构码
  106. * @param webTemplateCode - 用哪个模板码
  107. * @param sectionFillInList - 模板页面布局填充关系列表,eg:[{"sectionId": "section_1", "moduleId": "module_1"},...]
  108. */
  109. protected void initOrganizationWebContent(String organizationCode, String webTemplateCode, List<WebDesignDTO> sectionFillInList) {
  110. try {
  111. String webTempalteDataDir = directoryOfWebTemplateService.getTemplateDataBaseDirAndCreateIfNotExist(webTemplateCode);
  112. String orgWebDataDir = directoryService.getOrganizationWebDataBaseDirAndCreateIfNotExist(organizationCode);
  113. org.apache.commons.io.FileUtils.deleteDirectory(new File(orgWebDataDir));
  114. org.apache.commons.io.FileUtils.copyDirectory(new File(webTempalteDataDir), new File(orgWebDataDir));
  115. InputStream is = new ByteArrayInputStream(super.generateWebContent(webTemplateCode, sectionFillInList).getBytes(Constants.DEFAULT_CHARSET));
  116. FileUtils.copy(is, new File(orgWebDataDir, "index.html"));
  117. } catch (IOException e) {
  118. logger.error(e);
  119. }
  120. }
  121. @RequestMapping(value="/uploadWebContent/{organizationCode}", method=RequestMethod.GET)
  122. @Authorization(type=AuthorizationType.AUTHENTICATED)
  123. public ModelAndView uploadWebContentRequest(@PathVariable String organizationCode) {
  124. try {
  125. checkPermissionForCurrentUser(organizationCode);
  126. } catch (Exception e) {
  127. return toError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
  128. }
  129. Domain domain = domainService.selectByOrganizationCode(organizationCode);
  130. getModelMap().put("domain", domain);
  131. getModelMap().put("organizationCode", organizationCode);
  132. getModelMap().put("subDomain", domainService.getSubDomainName(domain.getDomainName()));
  133. return toView("organization/upload-web-content", getModelMap());
  134. }
  135. @RequestMapping(value="/uploadWebContent/{organizationCode}", method=RequestMethod.POST)
  136. @Authorization(type=AuthorizationType.AUTHENTICATED)
  137. public ModelAndView uploadWebContent(@PathVariable String organizationCode, @RequestParam("webContentFile") MultipartFile webContentFile) {
  138. try {
  139. checkPermissionForCurrentUser(organizationCode);
  140. } catch (Exception e) {
  141. return toError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
  142. }
  143. String orgWebDataDir = directoryService.getOrganizationWebDataBaseDirAndCreateIfNotExist(organizationCode);
  144. File zipFile = new File(orgWebDataDir, webContentFile.getName());
  145. try {
  146. FileUtils.delDirContents(new File(orgWebDataDir));
  147. FileUtils.copy(webContentFile.getInputStream(), zipFile);
  148. FileUtils.unzip(zipFile, new File(orgWebDataDir), Constants.DEFAULT_CHARSET);
  149. boolean isDeleted = zipFile.delete();
  150. logger.debug(isDeleted ? "文件删除成功:" + zipFile : "文件删除失败:" + zipFile);
  151. return toHTML(JavascriptUtils.generateMsg("alert('上传成功'); parent.window.location.href = parent.window.location + '?_=' + new Date().getTime();"));
  152. } catch (IOException e) {
  153. logger.error(e);
  154. return toError(JavascriptUtils.generateMsg("alert('上传失败:\n" + e.getMessage()) + "'); parent.window.location.href = parent.window.location + '?_=' + new Date().getTime();");
  155. }
  156. }
  157. /**
  158. * 注册前置条件检测,如果检测通过,然后内容为空,否则返回错误信息。
  159. * @param subDomain
  160. * @param email
  161. * @param password
  162. * @return - 如果检测通过,然后内容为空,否则返回错误信息
  163. */
  164. private StringBuilder registerPreCheck(String subDomain, String email, String password) {
  165. StringBuilder errorMsg = new StringBuilder();
  166. if(StringUtils.isEmpty(subDomain)){
  167. errorMsg.append("\n").append("域名 - 是必填字段");
  168. }else if(!subDomain.matches("^[a-zA-Z\\d\\_\\-]*$")){
  169. errorMsg.append("\n").append("域名 - 只能包含字母,数字,下划线,中划线");
  170. }
  171. if(StringUtils.isEmpty(email)){
  172. errorMsg.append("\n").append("邮箱 - 是必填字段");
  173. }else if(!new EmailValidator().isValid(email, null)){
  174. errorMsg.append("\n").append("邮箱 - 格式不正确");
  175. }
  176. if(StringUtils.isEmpty(password)){
  177. errorMsg.append("\n").append("密码 - 是必填字段");
  178. }
  179. if(domainService.isDomainExist(domainService.getFullOrgDomainName(subDomain))){
  180. errorMsg.append("\n").append(ERROR_MSG_DOMAIN_NAME_EXIST);
  181. }
  182. return errorMsg;
  183. }
  184. private void addDomainIntoDB(String orgDomain, OrganizationRegisterResponse registerResponse) {
  185. if(domainService.isDomainExist(orgDomain)){
  186. throw new RuntimeException(ERROR_MSG_DOMAIN_NAME_EXIST);
  187. }
  188. Domain newDomain = new Domain();
  189. newDomain.setDomainName(orgDomain);
  190. newDomain.setOrganizationCode(registerResponse.getOrganizationCode());
  191. newDomain.setCreateBy(getLoginUser() != null? getLoginUser().getName() : Constants.SYSTEM_USER);
  192. newDomain.setCreateDate(new Date());
  193. //设置机构主页使用的默认模板和默认的模板页面布局映射
  194. newDomain.setWebTemplateCode(ORGANIZATION_WEB_DEFAULT_WEB_TEMPLATE_CODE);
  195. newDomain.setOrgWebLayoutMapping(ORGANIZATION_WEB_DEFAULT_WEB_LAYOUT_MAPPING);
  196. //设置机构主页使用的默认模板和默认的模板页面布局映射
  197. domainService.insertSelective(newDomain);
  198. }
  199. private OrganizationRegisterResponse getRegisterResponse(JsonMessage apiResponseMessage) {
  200. return JSON.parseObject(apiResponseMessage.getResult(), OrganizationRegisterResponse.class);
  201. }
  202. private void sendDomainApprovedEmail(String subDomain, OrganizationRegisterResponse registerResponse) {
  203. //send域名注册成功的邮箱
  204. String subject = "机构注册申请域名已启用";
  205. HashMap<String, Object> modelMap = new HashMap<String, Object>();
  206. modelMap.put("subDomain", subDomain);
  207. modelMap.put("organizationRegisterResponse", registerResponse);
  208. modelMap.put("domain", domainService.getFullOrgDomainName(subDomain));
  209. modelMap.put("contextFullPath", getContextFullPath());
  210. String htmlContent = this.getContentFromTemplate("email/template/organization-domain-approved", modelMap);
  211. messageService.sendHTMLEmail(subject, htmlContent, new String[]{registerResponse.getEmail()});
  212. }
  213. protected void checkPermissionForCurrentUser(String organizationCode) throws Exception {
  214. if(!StringUtils.equals(getLoginUser().getOrganizationCode(), organizationCode)){
  215. throw new IllegalAccessException("您的组织机构码与您要操作的机构码不匹配!");
  216. }
  217. }
  218. }