Java 代码笔记

 平时写接口总是忘记,一些事情,每次都要花时间做相同的事,所以在此记一份笔记,以后直接拷贝,相当于代码生成器,更新了模板,参数类检查的模板

标准接口代码模板 

    // 接口代码模板
    /**
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(params = "testControllerMethod", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String testControllerMethod(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson returnJson = new AjaxJson();
        TSUser user = ResourceUtil.getSessionUser();
        String ipAddress = IpUtil.getIpAddr(request);
        String interfileid = request.getParameter("interfileid");
        // 参数多的话,建议使用参数类,参数类的必填项检查,请参考类:IInterfileEntity.class

        // 系统日志
        TSSyslogEntity syslogEntity = new TSSyslogEntity();
        syslogEntity.setObjectId("");
        syslogEntity.setModuleId("circleRecoveryconfirmController");
        syslogEntity.setLogType(Globals.LOG_TYPE_SEARCH);
        syslogEntity.setIpAddress(ipAddress);
        syslogEntity.setBrowser(BrowserUtils.checkBrowse(request));
        syslogEntity.setLogLevel(Globals.LOG_LEAVEL_INFO);

        // 文件日志
        TSDoclogEntity docLogEntity = new TSDoclogEntity();
        docLogEntity.setSpecNo("F333333");
        docLogEntity.setDocId("");
        docLogEntity.setVersion("A");
        docLogEntity.setOperation("查看");

        StringBuilder logBuilder = StringUtility.createBuilder("dmsCommonFuncController testControllerMethod Start");
        logBuilder = StringUtility.builderAppend(logBuilder,"\r\n",JSONObject.toJSONString(request.getParameterMap()),"\r\n",request.getQueryString());
        recordExceptionService.recordPrintErrMsg(logBuilder.toString());
        logBuilder.delete(0,logBuilder.length());
        logBuilder=null;

        StringBuilder docLogBuilder = StringUtility.createBuilder("内部文件PDF预览");
        StringBuilder sysLogBuilder = StringUtility.createBuilder("检查发行回收单,dmsCommonFuncController testControllerMethod:");

        sysLogBuilder = StringUtility.builderAppend(sysLogBuilder, "\r\n参数:", JSONObject.toJSONString(request.getParameterMap()),"\r\n",request.getQueryString());
        try {
            syslogEntity.setLogLevel(Globals.LOG_LEAVEL_INFO);

            returnJson.setMsg(mutiLangService.getLang("tip.suc"));
            sysLogBuilder = StringUtility.builderAppend(sysLogBuilder, "\r\nResult:操作成功;");
        } catch (Exception e) {
            e.printStackTrace();
            sysLogBuilder = StringUtility.builderAppend(sysLogBuilder, "\r\nResult:操作失败;\r\nErrorMsg:\r\n", e.toString());
            returnJson.setSuccess(false);

            String errMsg = mutiLangService.getLang("system.msg.error.001");
            String excepMsg = responseWriteService.getErrMsgTranslate(e);
            errMsg = StringUtility.replace(errMsg, "#{module}", "获取Token接口", "#{errMsg}", excepMsg);
            returnJson.setMsg(errMsg);

            returnJson.setRespCode("E999");
            syslogEntity.setLogLevel(Globals.LOG_LEAVEL_ERROR);
            recordExceptionService.recordPrintException(e, request);
        } finally {
            docLogEntity.setDetailsContent(docLogBuilder.toString());
            syslogEntity.setRemark(sysLogBuilder.toString());
            dmsLogService.writeSysLog(syslogEntity);
            dmsLogService.writeDocLog(docLogEntity);

            recordExceptionService.recordPrintErrMsg(sysLogBuilder.toString());
            recordExceptionService.recordPrintErrMsg("dmsCommonFuncController testControllerMethod End");
            sysLogBuilder.delete(0, sysLogBuilder.length());
            docLogBuilder.delete(0, docLogBuilder.length());
            sysLogBuilder = null;
            docLogBuilder = null;
            syslogEntity = null;
            docLogEntity = null;
        }
        return returnJson.getJsonStr();
    }

发送系统消息和邮件代码模板 

	private void sendSysNotice(String perUser, List linkList) {
		// 通知信息
		String title = "【系统消息】:文件分享链接通知";
		//String content = "这是您申请的文件打印的链接,内容如下:
#{extension}
文件超链接提取码
"; // String tableString = ""; //String trBaseString = "#{specNo}链接#{pwd}"; StringBuilder contentBuilder = FileStream.getContentByClass("notice_temp", "publicdoc_share_email_content.mail"); StringBuilder trBaseBuilder = FileStream.getContentByClass("notice_temp", "publicdoc_share_email_trlist.mail"); TSUser user = ResourceUtil.getSessionUser(); // 发送外链邮件,系统通知 StringBuilder trBuilder = new StringBuilder(); try { for (int i = 0; i < linkList.size(); i++) { trBuilder.append(trBaseBuilder); trBuilder = StringUtility.replace(trBuilder, "#{specNo}", linkList.get(i).getSpecNo(),"#{title}",linkList.get(i).getTitle(), "#{url}", linkList.get(i).getUrl()); } String trString = trBuilder.toString(); String content = StringUtility.replace(contentBuilder,"#{extension}", trString,"#{realName}",user.getRealName()).toString(); dccCommonService.createNotice("系统", title, content, "1", "3", perUser, new Date(), ""); } catch (Exception e) { e.printStackTrace(); recordExceptionService.recordPrintException(e, null); } }

发送系统消息和邮件代码模板 - 2

 	public AjaxJson doSyncKeyWord() throws Exception{
 		AjaxJson returnJson = new AjaxJson();
 		
 		//1、获取circle_customer_keyword数据
 		List list=findHql("from CircleCustomerKeywordEntity where nodeid='F'");//loadAll(CircleCustomerKeywordEntity.class);
 		
 		if (0==list.size()) {
			return returnJson;
		}
 		
 		//2、拼接语句
		HashMap data = new HashMap();
		StringBuilder sqlBuilder = FileStream.getContentByClass(
				StringUtility.createPathString("com", "circle", "customerkeyword", "dao"), "CircleCustomerKeywordDao_insertKeyword.sql");

		StringBuilder sqlValBuilder = FileStream.getContentByClass(
				StringUtility.createPathString("com", "circle", "customerkeyword", "dao"), "CircleCustomerKeywordDao_insertKeyword_2.sql");
 		
 		//3、获取数据源
		int size=list.size();
 		for (int i = 0; i < size; i++) {
 			CircleCustomerKeywordEntity entity = list.get(i);
 			if (i>0) {
				sqlBuilder.append(sqlValBuilder);
			}
 			StringUtility.replace(sqlBuilder, "#{id}",entity.getId());//UUIDGenerator.generateByUUID()
 			StringUtility.replace(sqlBuilder, "#{KeyWord}",entity.getKeyWord());
 			StringUtility.replace(sqlBuilder, "#{deleteflag}",entity.getDeleteFlag());
 			StringUtility.replace(sqlBuilder, "#{Warehouse}",GlobalData.DOC_WARE_HOUSE);
		}
		
 		//4、写入
		data.clear();
		// 设置外部服务器数据表,置为同步成功,下次同步不会再同步一次
		//executeSql(sqlBuilder.toString(), data);

		String dbKey = "Circle_FCS";
		
		DynamicDBUtil.updateByHash(dbKey, sqlBuilder.toString(), data);
 		
 		
 		return returnJson;
 	}

	// 内部文件新建接口
	/**
	 * 根据请求带过来的流程表单的信息,创建内部文件
	 * 
	 * 参数结构:&id=c1f26a9a19024976bfc328b0961aad08&title=撒扥撒扥森扥&docType=&userName=&docTypeEN=&docLevelCode=
	 * 
	 * 返回值结构:"{\"respCode\":\"E002\",\"msg\":\"文件类型不能为空\",\"success\":false}"
	 * 
	 * @param iInterfileEntity
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "IcreateInterfile", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public String IcreateInterfile(IInterfileEntity iInterfileEntity, HttpServletRequest request,
			HttpServletResponse response) {
		AjaxJson returnJson = new AjaxJson();
		TSSyslogEntity syslogEntity = new TSSyslogEntity();
		syslogEntity.setObjectId(iInterfileEntity.getId());
		syslogEntity.setModuleId("dmsCommonFuncController");
		syslogEntity.setLogType(Globals.LOG_TYPE_INSERT);

		StringBuilder sysMsgBuilder = StringUtility.createBuilder("接口IcreateInterfile,参数:",iInterfileEntity.toString());
		try {
			syslogEntity.setLogLevel(Globals.LOG_LEAVEL_INFO);
			// -----------------参数接收类必填检查---------------------
			String resultMsg = BeanHelper.checkBeanAttr(iInterfileEntity);
			if (StringUtils.isNotBlank(resultMsg)) {
				returnJson.setSuccess(false);
				returnJson.setMsg(mutiLangService.getLang(resultMsg));
				returnJson.setRespCode("E002");
				return returnJson.getJsonStr();
			}
			// **************************************************
			TSUser user = ResourceUtil.getSessionUser();
			if (StringUtils.isNotBlank(iInterfileEntity.getUserName())) {// 如果传了账号名 ,就抓取账号名的user
				TSUser baseUser = new TSUser();
				baseUser.setUserName(iInterfileEntity.getUserName());
				user = userService.getUserInfoByUsername(baseUser);// 获取用户对象
			}

			DccInternalFileEntity internalFileEntity = new DccInternalFileEntity();
			internalFileEntity.setId(iInterfileEntity.getId());

			DccDeptcodeEntity deptEntity = OrgUtil.getHrDeptCode(user.getDepartid(), user.getPlant());
			List setList = systemService.loadAll(CircleSystemSettingEntity.class);
			CircleSystemSettingEntity systemSettingEntity = setList.get(0);
			// 人
			if ("0".equals(systemSettingEntity.getFileowner())) {
				internalFileEntity.setOwnerName(user.getRealName());
				internalFileEntity.setOwnerNo(user.getEmpno());
			}
			// 部门
			if ("1".equals(systemSettingEntity.getFileowner())) {
				internalFileEntity.setOwnerName(deptEntity.getDeptName());
				internalFileEntity.setOwnerNo(deptEntity.getHrDeptCode());
			}
			internalFileEntity.setDeptCode(deptEntity.getHrDeptCode());

			// 保存内部文件
			setInterFile(iInterfileEntity, user, internalFileEntity);// 给内部文件赋值

			// 设置返回值
			returnJson.setJsonData(JSONObject.toJSONString(internalFileEntity));

			// 创建新建记录
			createDCCFlowEntity(user, internalFileEntity);// 创建DCC 创建记录
		} catch (Exception e) {
			e.printStackTrace();
			StringUtility.builderAppend(sysMsgBuilder, "\r\nErrorMsg:",e.getMessage());
			returnJson.setSuccess(false);
			returnJson.setMsg("操作失败");
			returnJson.setRespCode("E999");
			recordExceptionService.recordPrintException(e, request);
			syslogEntity.setLogLevel(Globals.LOG_LEAVEL_ERROR);
		} finally {
			syslogEntity.setRemark(sysMsgBuilder.toString());
			dmsLogService.writeSysLog(syslogEntity);
		}

		return returnJson.getJsonStr();
	}
package com.dcc.common.entity;

import java.util.HashMap;
import java.util.Map;
import javax.validation.constraints.NotNull;
import com.alibaba.fastjson.JSONObject;

/**
 * 2022-06-15
 * @author tianming.fan
 *
 */
public class IInterfileEntity {
	
	/*add by ftm
	 * !!!数据接收类属性必须赋予默认值,否则,如果前端未给某属性传值,程序就不会检查到该属性*/
	
	private java.lang.String id="";//文件id
	private java.lang.String title="";//文件名称
	private java.lang.String docType="";//文件类型名
	private java.lang.String userName="";// 账号名
	private java.lang.String docTypeEN="";//暂时无值,可以不传
	private java.lang.String docTypeCode="";//文件类型码
	private java.lang.String docLevelCode="";//文件等级
	private java.lang.String confidentialLevel="";//机密等级
	
	private Map tipMap = new HashMap();//提示信息
	private Map requiredMap = new HashMap();//是否必填

	public Map getRequiredMap() {
		requiredMap.put("id", true);
		requiredMap.put("title", true);
		requiredMap.put("docType", true);
		requiredMap.put("userName", false);
		requiredMap.put("docTypeEN", false);
		requiredMap.put("docTypeCode", true);
		requiredMap.put("docLevelCode", true);
		requiredMap.put("confidentialLevel", true);
		return requiredMap;
	}

	public Map getTipMap() {
		tipMap.put("id", "文件ID不能为空");
		tipMap.put("title", "文件名称不能为空");
		tipMap.put("docType", "文件类型不能为空");
		tipMap.put("userName", "账号名不能为空");
		tipMap.put("docTypeEN", "文件类型英文名称不为空");
		tipMap.put("docTypeCode", "文件类型码不能为空");
		tipMap.put("docLevelCode", "文件等级不能为空");
		tipMap.put("confidentialLevel", "机密等级不能为空");
		return tipMap;
	}
	
	public java.lang.String getUserName() {
		return userName;
	}
	public void setUserName(java.lang.String userName) {
		this.userName = userName;
	}
	public java.lang.String getTitle() {
		return title;
	}
	public void setTitle(java.lang.String title) {
		this.title = title;
	}
	public java.lang.String getDocType() {
		return docType;
	}
	public void setDocType(java.lang.String docType) {
		this.docType = docType;
	}
	public java.lang.String getDocTypeCode() {
		return docTypeCode;
	}
	public void setDocTypeCode(java.lang.String docTypeCode) {
		this.docTypeCode = docTypeCode;
	}
	public java.lang.String getDocLevelCode() {
		return docLevelCode;
	}
	public void setDocLevelCode(java.lang.String docLevelCode) {
		this.docLevelCode = docLevelCode;
	}
	public java.lang.String getConfidentialLevel() {
		return confidentialLevel;
	}
	public void setConfidentialLevel(java.lang.String confidentialLevel) {
		this.confidentialLevel = confidentialLevel;
	}
	public java.lang.String getId() {
		return id;
	}
	public void setId(java.lang.String id) {
		this.id = id;
	}

	public java.lang.String getDocTypeEN() {
		return docTypeEN;
	}

	public void setDocTypeEN(java.lang.String docTypeEN) {
		this.docTypeEN = docTypeEN;
	}

	@Override
	public String toString() {
		return "IInterfileEntity [id=" + id + ", title=" + title + ", docType=" + docType + ", userName=" + userName
				+ ", docTypeEN=" + docTypeEN + ", docTypeCode=" + docTypeCode + ", docLevelCode=" + docLevelCode
				+ ", confidentialLevel=" + confidentialLevel + "]";
	}
	
	public String getJsonStr(){
		JSONObject obj = new JSONObject();
		return obj.toJSONString();
	}
}
	/**
	 * 日志方法调用案例 add by ftm 2022-05-06
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "testLog")
	@ResponseBody
	public AjaxJson testLog(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();

		// 系统日志
		TSSyslogEntity syslogEntity = new TSSyslogEntity();
		syslogEntity.setRemark("测试日志");
		syslogEntity.setObjectId("");
		syslogEntity.setModuleId(String.valueOf(request.getSession().getAttribute("moduleId")));
		syslogEntity.setLogLevel(Globals.LOG_LEAVEL_INFO);
		syslogEntity.setLogType(Globals.LOG_TYPE_UPDATE);
		dmsLogService.writeSysLog(syslogEntity);

		// 文件日志
		TSDoclogEntity docLogEntity = new TSDoclogEntity();
		docLogEntity.setSpecNo("F333333");
		docLogEntity.setDocId("");
		docLogEntity.setVersion("A");
		docLogEntity.setOperation("查看");
		docLogEntity.setDetailsContent("内部文件PDF预览");
		dmsLogService.writeDocLog(docLogEntity);

		// 审批记录日志
		TSOperatelogEntity operationEntity = new TSOperatelogEntity();
		operationEntity.setDocId("");
		operationEntity.setOperateName("同意");
		operationEntity.setOperateMemo("信息未填写");
		operationEntity.setDocStatus("DCC签核");
		operationEntity.setDocType("");
		operationEntity.setSpecNo("F000000");
		dmsLogService.writeOperateLog(operationEntity);

		return j;
	}
	/**
	 * 批量删除外发文件子表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson returnJson = new AjaxJson();

		//系统日志
		TSSyslogEntity tsLog = new TSSyslogEntity();
		String message = mutiLangService.getLang("common.delete.success");
		
		StringBuilder logBuilder = new StringBuilder();
		try{
			for(String id:ids.split(",")){
				DmsOutPubFileEntity dmsOutPubFile = systemService.getEntity(DmsOutPubFileEntity.class, 
				id
				);
				dmsOutPubFileService.delete(dmsOutPubFile);
				logBuilder = StringUtility.builderAppend(logBuilder,dmsOutPubFile.getSpecNo(),"\r\n",dmsOutPubFile.getTitle(),",",message);
			    tsLog.setLogLevel(Globals.Log_Leavel_INFO);
			    tsLog.setLogType(Globals.Log_Type_DEL);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = mutiLangService.getLang("system.msg.operation_failed");
			recordExceptionService.recordPrintException(e, request);
			logBuilder = StringUtility.builderAppend(logBuilder,message,"\r\n异常信息:",e.getMessage());
			returnJson.setRespCode("E005");//数据更新失败
			returnJson.setSuccess(false);
		    tsLog.setLogLevel(Globals.Log_Leavel_ERROR);
		    tsLog.setLogType(Globals.Log_Type_DEL);
		}finally {
		   tsLog.setRemark(logBuilder.toString());
		   dmsLogService.writeSysLog(tsLog);
		}
		returnJson.setMsg(message);
		return returnJson;
	}
	/**
	 * 更新变更申请
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(DccChangeApplyEntity dccChangeApply, HttpServletRequest request) {
		//String message = "变更申请更新成功";
		AjaxJson returnJson = new AjaxJson();
		
		//系统日志
		TSSyslogEntity tsLog = new TSSyslogEntity();
		tsLog.setModuleId("dccChangeApplyController");
		String message = mutiLangService.getLang("common.edit.success");
		
		StringBuilder logBuilder = new StringBuilder();
		
		DccChangeApplyEntity t = dccChangeApplyService.get(DccChangeApplyEntity.class, dccChangeApply.getId());
		if (null == t) {
			return doAdd(dccChangeApply, request);
		}
		try {
			MyBeanUtils.copyBeanNotNull2Bean(dccChangeApply, t);
			dccChangeApplyService.updateEntitie(t);
			//systemService.addLog(message, Globals.LOG_TYPE_UPDATE, Globals.Log_Leavel_INFO);
			
			logBuilder = StringUtility.builderAppend(logBuilder,dccChangeApply.getSpecNo(),"\r\n",dccChangeApply.getTitle(),",",message);
		    tsLog.setLogLevel(Globals.Log_Leavel_INFO);
		    tsLog.setLogType(Globals.Log_Type_UPDATE);
		} catch (Exception e) {
			e.printStackTrace();
			/*message = "变更申请更新失败";
			throw new BusinessException(e.getMessage());*/
			message = mutiLangService.getLang("system.msg.operation_failed");
			recordExceptionService.recordPrintException(e, request);
			
			logBuilder = StringUtility.builderAppend(logBuilder,message,"\r\n异常信息:",e.getMessage());
			returnJson.setRespCode("E005");//数据更新失败
			returnJson.setSuccess(false);
		   
		    tsLog.setLogLevel(Globals.Log_Leavel_ERROR);
		    tsLog.setLogType(Globals.Log_Type_UPDATE);
		}finally {
			tsLog.setRemark(logBuilder.toString());
		    dmsLogService.writeSysLog(tsLog);
		}
		returnJson.setMsg(message);
		return returnJson;
	}

String.endsWith的StringBuffer替代方法是什么?

if(buf.charAt(buf.length()-1)==File.separatorChar){
  //
}

你可能感兴趣的:(java,java)