/211Project/to211-web/src/main/java/com/to211/web/controller/OrganizationController.java
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
- package com.to211.web.controller;
-
- import java.io.ByteArrayInputStream;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- import javax.annotation.Resource;
- import javax.servlet.http.HttpServletResponse;
-
- import org.apache.commons.lang.StringUtils;
- import org.hibernate.validator.constraints.impl.EmailValidator;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.multipart.MultipartFile;
- import org.springframework.web.servlet.ModelAndView;
-
- import com.alibaba.fastjson.JSON;
- import com.fdhay.authcenter.proxy.domain.annotation.Authorization;
- import com.fdhay.authcenter.proxy.domain.enums.AuthorizationType;
- import com.to211.common.Constants;
- import com.to211.common.util.FileUtils;
- import com.to211.common.util.HttpClientUtils;
- import com.to211.common.util.JavascriptUtils;
- import com.to211.domain.Domain;
- import com.to211.domain.OrganizationRegisterResponse;
- import com.to211.domain.WebDesignDTO;
- import com.to211.domain.base.json.JsonMessage;
- import com.to211.domain.enums.JsonMessageResultStatusEnum;
- import com.to211.service.DirectoryOfWebTemplateService;
- import com.to211.service.DirectoryService;
- import com.to211.service.DomainService;
- import com.to211.service.MessageService;
- import com.to211.service.OrganizationDetailService;
-
- @Controller
- @RequestMapping("/org")
- public class OrganizationController extends WebTemplateController {
-
- private static final String ERROR_MSG_DOMAIN_NAME_EXIST = "域名 - 已经被注册";
- private static final String ORGANIZATION_REGISTER_URL = Constants.cfg.getValue("organization.register.url", "organization.register.url");
- private static final String ORGANIZATION_REGISTER_APITOKEN = Constants.cfg.getValue("organization.register.APIToken", "organization.register.APIToken");
-
- protected static final String ORGANIZATION_WEB_DEFAULT_WEB_TEMPLATE_CODE = Constants.cfg.getValue("organization.web.defaultWebTemplateCode", "organization.web.defaultWebTemplateCode");
- private static final String ORGANIZATION_WEB_DEFAULT_WEB_LAYOUT_MAPPING = Constants.cfg.getValue("organization.web.defaultWebLayoutMapping", "organization.web.defaultWebLayoutMapping");
-
- @Resource
- private DomainService domainService;
- @Resource
- private DirectoryService directoryService;
- @Resource
- private MessageService messageService;
- @Resource
- private DirectoryOfWebTemplateService directoryOfWebTemplateService;
- @Resource
- private OrganizationDetailService organizationDetailService;
-
- @RequestMapping("/register")
- @Authorization(type=AuthorizationType.PUBLIC)
- public ModelAndView register(String subDomain, String email, String password) {
-
- StringBuilder errorMsg = registerPreCheck(subDomain, email, password);
- if(StringUtils.isNotEmpty(errorMsg.toString())){
- JsonMessage message = JsonMessage.fail();
- message.setResult("注册错误:" + errorMsg.toString());
- return toJSON(message);
- }
-
- Map<String, String> headers = new HashMap<String, String>(1);
- headers.put(Constants.KEY_OF_APITOKEN, ORGANIZATION_REGISTER_APITOKEN);
-
- Map<String, String> params = new HashMap<String, String>(2);
- params.put("email", email);
- params.put("password", password);
-
- try {
- String apiResponseJson = HttpClientUtils.post(ORGANIZATION_REGISTER_URL, params, headers);
- if(logger.isDebugEnabled()){
- logger.debug(apiResponseJson);
- }
- JsonMessage apiResponseMessage = JSON.parseObject(apiResponseJson, JsonMessage.class);
- if(JsonMessageResultStatusEnum.FAIL.equals(apiResponseMessage.getResultStatusCode())){
- JsonMessage message = JsonMessage.fail();
- message.setResult("注册失败:\n" + apiResponseMessage.getResult());
- return toJSON(message);
- }
-
- OrganizationRegisterResponse registerResponse = getRegisterResponse(apiResponseMessage);
- addDomainIntoDB(domainService.getFullOrgDomainName(subDomain), registerResponse);
-
- this.initOrganizationWebContent(registerResponse.getOrganizationCode());
- sendDomainApprovedEmail(subDomain, registerResponse);
-
- JsonMessage message = JsonMessage.sucess();
- message.setResult("注册成功!请通过邮箱查看详细信息\n");
- return toJSON(message);
- } catch (Exception e) {
- logger.error(e);
- JsonMessage message = JsonMessage.fail();
- message.setResult("注册失败");
- return toJSON(message);
- }
- }
-
- /**
- * 初始化机构的web主页内容
- * @param organizationCode
- */
- protected void initOrganizationWebContent(String organizationCode) {
- List<WebDesignDTO> sectionFillInList = JSON.parseArray(ORGANIZATION_WEB_DEFAULT_WEB_LAYOUT_MAPPING, WebDesignDTO.class);
- this.initOrganizationWebContent(organizationCode, ORGANIZATION_WEB_DEFAULT_WEB_TEMPLATE_CODE, sectionFillInList);
- }
-
- /**
- * 初始化机构的web主页内容
- * @param organizationCode - 要操作的机构的机构码
- * @param webTemplateCode - 用哪个模板码
- * @param sectionFillInList - 模板页面布局填充关系列表,eg:[{"sectionId": "section_1", "moduleId": "module_1"},...]
- */
- protected void initOrganizationWebContent(String organizationCode, String webTemplateCode, List<WebDesignDTO> sectionFillInList) {
- try {
- String webTempalteDataDir = directoryOfWebTemplateService.getTemplateDataBaseDirAndCreateIfNotExist(webTemplateCode);
- String orgWebDataDir = directoryService.getOrganizationWebDataBaseDirAndCreateIfNotExist(organizationCode);
-
- org.apache.commons.io.FileUtils.deleteDirectory(new File(orgWebDataDir));
- org.apache.commons.io.FileUtils.copyDirectory(new File(webTempalteDataDir), new File(orgWebDataDir));
-
- InputStream is = new ByteArrayInputStream(super.generateWebContent(webTemplateCode, sectionFillInList).getBytes(Constants.DEFAULT_CHARSET));
- FileUtils.copy(is, new File(orgWebDataDir, "index.html"));
- } catch (IOException e) {
- logger.error(e);
- }
- }
-
- @RequestMapping(value="/uploadWebContent/{organizationCode}", method=RequestMethod.GET)
- @Authorization(type=AuthorizationType.AUTHENTICATED)
- public ModelAndView uploadWebContentRequest(@PathVariable String organizationCode) {
- try {
- checkPermissionForCurrentUser(organizationCode);
- } catch (Exception e) {
- return toError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
- }
- Domain domain = domainService.selectByOrganizationCode(organizationCode);
- getModelMap().put("domain", domain);
- getModelMap().put("organizationCode", organizationCode);
- getModelMap().put("subDomain", domainService.getSubDomainName(domain.getDomainName()));
- return toView("organization/upload-web-content", getModelMap());
- }
-
- @RequestMapping(value="/uploadWebContent/{organizationCode}", method=RequestMethod.POST)
- @Authorization(type=AuthorizationType.AUTHENTICATED)
- public ModelAndView uploadWebContent(@PathVariable String organizationCode, @RequestParam("webContentFile") MultipartFile webContentFile) {
- try {
- checkPermissionForCurrentUser(organizationCode);
- } catch (Exception e) {
- return toError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
- }
- String orgWebDataDir = directoryService.getOrganizationWebDataBaseDirAndCreateIfNotExist(organizationCode);
- File zipFile = new File(orgWebDataDir, webContentFile.getName());
- try {
- FileUtils.delDirContents(new File(orgWebDataDir));
- FileUtils.copy(webContentFile.getInputStream(), zipFile);
- FileUtils.unzip(zipFile, new File(orgWebDataDir), Constants.DEFAULT_CHARSET);
- boolean isDeleted = zipFile.delete();
- logger.debug(isDeleted ? "文件删除成功:" + zipFile : "文件删除失败:" + zipFile);
- return toHTML(JavascriptUtils.generateMsg("alert('上传成功'); parent.window.location.href = parent.window.location + '?_=' + new Date().getTime();"));
- } catch (IOException e) {
- logger.error(e);
- return toError(JavascriptUtils.generateMsg("alert('上传失败:\n" + e.getMessage()) + "'); parent.window.location.href = parent.window.location + '?_=' + new Date().getTime();");
- }
- }
-
-
- /**
- * 注册前置条件检测,如果检测通过,然后内容为空,否则返回错误信息。
- * @param subDomain
- * @param email
- * @param password
- * @return - 如果检测通过,然后内容为空,否则返回错误信息
- */
- private StringBuilder registerPreCheck(String subDomain, String email, String password) {
- StringBuilder errorMsg = new StringBuilder();
- if(StringUtils.isEmpty(subDomain)){
- errorMsg.append("\n").append("域名 - 是必填字段");
- }else if(!subDomain.matches("^[a-zA-Z\\d\\_\\-]*$")){
- errorMsg.append("\n").append("域名 - 只能包含字母,数字,下划线,中划线");
- }
-
- if(StringUtils.isEmpty(email)){
- errorMsg.append("\n").append("邮箱 - 是必填字段");
- }else if(!new EmailValidator().isValid(email, null)){
- errorMsg.append("\n").append("邮箱 - 格式不正确");
- }
-
- if(StringUtils.isEmpty(password)){
- errorMsg.append("\n").append("密码 - 是必填字段");
- }
- if(domainService.isDomainExist(domainService.getFullOrgDomainName(subDomain))){
- errorMsg.append("\n").append(ERROR_MSG_DOMAIN_NAME_EXIST);
- }
- return errorMsg;
- }
-
-
- private void addDomainIntoDB(String orgDomain, OrganizationRegisterResponse registerResponse) {
- if(domainService.isDomainExist(orgDomain)){
- throw new RuntimeException(ERROR_MSG_DOMAIN_NAME_EXIST);
- }
- Domain newDomain = new Domain();
- newDomain.setDomainName(orgDomain);
- newDomain.setOrganizationCode(registerResponse.getOrganizationCode());
- newDomain.setCreateBy(getLoginUser() != null? getLoginUser().getName() : Constants.SYSTEM_USER);
- newDomain.setCreateDate(new Date());
- //设置机构主页使用的默认模板和默认的模板页面布局映射
- newDomain.setWebTemplateCode(ORGANIZATION_WEB_DEFAULT_WEB_TEMPLATE_CODE);
- newDomain.setOrgWebLayoutMapping(ORGANIZATION_WEB_DEFAULT_WEB_LAYOUT_MAPPING);
- //设置机构主页使用的默认模板和默认的模板页面布局映射
- domainService.insertSelective(newDomain);
- }
-
- private OrganizationRegisterResponse getRegisterResponse(JsonMessage apiResponseMessage) {
- return JSON.parseObject(apiResponseMessage.getResult(), OrganizationRegisterResponse.class);
- }
-
- private void sendDomainApprovedEmail(String subDomain, OrganizationRegisterResponse registerResponse) {
- //send域名注册成功的邮箱
- String subject = "机构注册申请域名已启用";
- HashMap<String, Object> modelMap = new HashMap<String, Object>();
- modelMap.put("subDomain", subDomain);
- modelMap.put("organizationRegisterResponse", registerResponse);
- modelMap.put("domain", domainService.getFullOrgDomainName(subDomain));
- modelMap.put("contextFullPath", getContextFullPath());
- String htmlContent = this.getContentFromTemplate("email/template/organization-domain-approved", modelMap);
- messageService.sendHTMLEmail(subject, htmlContent, new String[]{registerResponse.getEmail()});
- }
-
- protected void checkPermissionForCurrentUser(String organizationCode) throws Exception {
- if(!StringUtils.equals(getLoginUser().getOrganizationCode(), organizationCode)){
- throw new IllegalAccessException("您的组织机构码与您要操作的机构码不匹配!");
- }
- }
-
- }