首页 > 编程语言 >java-返回值封装

java-返回值封装

时间:2023-03-15 15:59:12浏览次数:46  
标签:code return String java 封装 HttpStatus private 返回值 public

BaseResponse.Class

@ApiIgnore
@Data
@JsonInclude(value = JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class BaseResponse<T> {

	/**
	 * 响应编码
	 */
	@ApiModelProperty(hidden = true)
	private int code;
	/**
	 * 响应消息
	 */
	@ApiModelProperty(hidden = true)
	private String message;

	/**
	 * 是否可见
	 */
	@ApiModelProperty(hidden = true)
	private boolean visible;

	@ApiModelProperty(hidden = true)
	private BaseException exception;

	/**
	 * 分页对象
	 */
	@ApiModelProperty(hidden = true)
	public Paging paging;

	/**
	 * 业务对象
	 */
	public T data;
	@ApiModelProperty(hidden = true)
	@JsonProperty("extra")
	public Map<String, ?> extraMap;

	public BaseResponse() {
		this(null, null);
	}

	public BaseResponse(T t) {
		this(t, null);
	}

	public BaseResponse(T t, Map<String, ?> extraMap) {
		if (null == t) {
			this.code = HttpStatus.OK.value();
			this.message = HttpStatus.OK.name();
		} else if (t instanceof Converter) {
			this.code = HttpStatus.OK.value();
			this.message = HttpStatus.OK.name();
			data = t;
		} else if (t instanceof BaseModel) {
			this.code = HttpStatus.OK.value();
			this.message = HttpStatus.OK.name();
			data = t;
		} else if (t instanceof List) {
			this.code = HttpStatus.OK.value();
			this.message = HttpStatus.OK.name();
			@SuppressWarnings({ "unchecked", "rawtypes" })
			PageInfo<?> pageInfo = new PageInfo((List) t);
			paging = new Paging(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal());
			data = t;
		} else if(t instanceof Map){
			this.code = HttpStatus.OK.value();
			this.message = HttpStatus.OK.name();
			data = t;
		} else if (t instanceof BadRequestException) {
			this.code = HttpStatus.BAD_REQUEST.value();
//			this.message = HttpStatus.BAD_REQUEST.name();
			this.message = ((BadRequestException)t).getMessageList().get(0);
			this.visible = true;
//			this.exception = (BadRequestException) t;
			this.exception = null;
		} else if (t instanceof InternalServerErrorException) {
			this.code = HttpStatus.INTERNAL_SERVER_ERROR.value();
			this.message = HttpStatus.INTERNAL_SERVER_ERROR.name();
			this.visible = false;
//			this.exception = (InternalServerErrorException) t;
		} else if (t instanceof OpenAPIException) {
			OpenAPIException exception = ((OpenAPIException) t);
			this.code = exception.getHttpErrorCode();
			this.message = exception.toString();
			this.visible = false;
			this.exception = null;
		} else if (t instanceof BatchResponse) {
			this.code = HttpStatus.OK.value();
			this.message = HttpStatus.OK.name();
			data = t;
		} else if (t instanceof Exception) {
			this.code = HttpStatus.UNAUTHORIZED.value();
			this.message = ((OpenAPIException) t).toString();
			this.visible = false;
			this.exception = null;
		} else {
			this.code = HttpStatus.OK.value();
			data = t;
		}
		this.extraMap = extraMap;
	}

	public Paging getPaging() {
		return paging;
	}

	public void setPaging(Paging paging) {
		this.paging = paging;
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}

	public Map<String, ?> getExtraMap() {
		return extraMap;
	}

	public void setExtraMap(Map<String, ?> extraMap) {
		this.extraMap = extraMap;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public boolean isVisible() {
		return visible;
	}

	public void setVisible(boolean visible) {
		this.visible = visible;
	}

	public BaseException getException() {
		return exception;
	}

	public void setException(BaseException exception) {
		this.exception = exception;
	}

	public class Paging {
		private int pageNum;
		private int pageSize;
		private long total;

		private Paging(int pageNum, int pageSize, long total) {
			this.pageNum = pageNum;
			this.pageSize = pageSize;
			this.total = total;
		}

		public int getPageNum() {
			return pageNum;
		}

		public void setPageNum(int pageNum) {
			this.pageNum = pageNum;
		}

		public int getPageSize() {
			return pageSize;
		}

		public void setPageSize(int pageSize) {
			this.pageSize = pageSize;
		}

		public long getTotal() {
			return total;
		}

		public void setTotal(long total) {
			this.total = total;
		}
	}

}

Converter.Interface

@FunctionalInterface
public interface Converter<S, T>{

    T convert(S s);

    default List<T> convertToList(final List<S> input) {
        if(input instanceof Page){
            Page<T> page = new Page<>();
            if(!CollectionUtils.isEmpty(input)) {
                page.addAll(input.stream().map(this::convert).collect(toList()));
            }
            page.setTotal(((Page) input).getTotal());
            page.setPageNum(((Page) input).getPageNum());
            page.setPageSize(((Page) input).getPageSize());
            return page;
        }else if(CollectionUtils.isEmpty(input)){
            return Collections.emptyList();
        }else{
            return input.stream().map(this::convert).collect(toList());
        }


    }
}

ConsumerAppUserResponse.Class


@Data
public class ConsumerAppUserResponse implements Converter<ConsumerAppUser, ConsumerAppUserResponse> {
    private Integer id;
    /**
     * 手机号
     */
    private String mobile;
    /**
     * 真实姓名
     */
    private String realname;
    /**
     * 邮箱
     */
    private String email;
    /**
     * 企业email
     */
    private String orgEmail;
    /**
     * 如果要创建企微用户,需要传递该属性信息
     */
    private List<WxworkCorpUserResponse> wxworkCorpUserList;


    @Override
    public ConsumerAppUserResponse convert(ConsumerAppUser consumerAppUser) {
        if(null == consumerAppUser){
            return null;
        }
        ConsumerAppUserResponse t = new ConsumerAppUserResponse();
        BeanUtils.copyProperties(consumerAppUser, t, "wxworkCorpUserList");
        if(CollectionUtils.isNotEmpty(consumerAppUser.getWxworkCorpUserList())){
            t.setWxworkCorpUserList(new WxworkCorpUserResponse().convertToList(consumerAppUser.getWxworkCorpUserList()));
        }
        return t;
    }
}

ConsumerAppUser.Class


@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
@JsonInclude(value = Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ConsumerAppUser extends BaseMultiTenantModel {

    /**
    * 手机号
    */
    private String mobile;
    /**
    * 真实姓名
    */
    private String realname;
    /**
     * 邮箱
     */
    private String email;
    /**
     * 微信OpenId,只用于微信登录的时候传递参数,不在数据库持久化保存
     */
    private transient String openId;
    /**
     * 微信公众号AppID,只用于微信登录的时候传递参数,不在数据库持久化保存
     */
    private transient String appId;
    /**
    * 类型
    */
    private Integer status;

    /**
    * 头像地址
    */
    private String headPortraitUrl;

    /**
    * 最后一次登录时间
    */
    private LocalDateTime lastLoginTime;

    /**
     * 飞书租户id
     */
    private String feishuTenantKey;

    /**
     * 飞书用户userId
     */
    private String feishuUserId;


    /**
     * welink租户id
     */
    private String welinkTenantId;

    /**
     * welink用户id
     */
    private String welinkUserId;

    /**
     * dingding 租户id, 实际取的是CorpId
     */
    private String dingTenantId;

    /**
     * dingding 用户id
     */
    private String dingUserId;

    /**
     * 企业email
     */
    private String orgEmail;
    /**
     * 用于存储关联的企微用户信息
     */
    private transient List<WxworkCorpUser> wxworkCorpUserList;

    public Optional<String> decideMobileOrEmailOrNameByFieldType(Integer fieldType){
        return Optional.ofNullable(fieldType).flatMap(e -> decideMobileOrEmailOrNameByFieldType(FieldType.Type.valueOf(e)));
    }

    public Optional<String> decideMobileOrEmailOrNameByFieldType(FieldType.Type type) {
        if(null == type){
            return Optional.empty();
        }
        switch (type){
            case TELEPHONE:
                return Optional.ofNullable(mobile);
            case EMAIL:
                return Optional.ofNullable(email);
            case SINGLE_LINE:
                return Optional.ofNullable(realname);
            default:
                return Optional.empty();
        }
    }

    public Optional<String> decideMobileOrEmail(FieldType.Type type) {
        if(null == type){
            return Optional.empty();
        }
        switch (type){
            case TELEPHONE:
                return Optional.ofNullable(mobile);
            case EMAIL:
                return Optional.ofNullable(email);
            default:
                return Optional.empty();
        }
    }
}

Controller


@GetMapping(consumes = APPLICATION_JSON, produces = APPLICATION_JSON)
    public ResponseEntity<BaseResponse<ConsumerAppUserResponse>> search(@RequestParam(value = "mail", required = false) final String mail,
                                                                        @RequestParam(value = "phone", required = false) final String phone) {
        ConsumerAppUser consumerAppUser = consumerAppUserWithWxworkCorpUserService.findByEmailOrPhone(mail, phone);
        ConsumerAppUserResponse consumerAppUserResponse = new ConsumerAppUserResponse().convert(consumerAppUser);
        BaseResponse<ConsumerAppUserResponse> consumerAppUserResponseBaseResponse = new BaseResponse<>(consumerAppUserResponse);
        ResponseEntity<BaseResponse<ConsumerAppUserResponse>> baseResponseResponseEntity = new ResponseEntity<>(consumerAppUserResponseBaseResponse, HttpStatus.OK);
        return baseResponseResponseEntity;
    }

标签:code,return,String,java,封装,HttpStatus,private,返回值,public
From: https://www.cnblogs.com/AlwaysStudyingLiuNing/p/17218809.html

相关文章

  • https请求,Java代码忽略https证书:解决No subject alternative names present问题
    https请求,Java代码忽略https证书:解决Nosubjectalternativenamespresent问题packagecom.test.utils;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;......
  • 【Java笔记5】运算符
    @目录一.算术运算符二.赋值运算符三.比较运算符四.逻辑运算符五.三元运算符六.运算符的优先级七.字符串拼接字符串字符串拼接运算一.算术运算符运算符说明......
  • 【Java笔记6】流程结构
    一.顺序结构按照次序一行接一行执行。二.分支结构有选择的执行某一部分代码或者不执行某一部分代码。1.if结构语法:if(结果为boolean类型的条件){ //被条件执行......
  • 【Java笔记7】随机数生成,数组,for-each
    @目录一.生成随机数:二.数组1.定义一个数组(1)数组的定义(2)数组的实例化2.数组中元素的表示方法(1)使用数组元素下标3.数组的存储4.数组默认值5.多维数组6.常见错误:数组......
  • 基于Win32自己封装一个框架
    1.vs技巧项目建错了如何修改项目类型?项目文件夹右键属性-->配置属性-->链接器-->系统-->修改子系统的值修改项目字符集项目文件夹右键属性-->配置属性-->常规-->修改字......
  • 某大厂面试题:说一说Java、Spring、Dubbo三者SPI机制的原理和区别
    大家好,我是三友~~今天来跟大家聊一聊Java、Spring、Dubbo三者SPI机制的原理和区别。其实我之前写过一篇类似的文章,但是这篇文章主要是剖析dubbo的SPI机制的源码,中间只是......
  • java 时间操作
    旧API   Date和Calendar  使用SimpleDateFormat格式化新API   LocalDateTime和ZonedDateTime  使用DateTimeFormatter格式化Datedate=new......
  • Java线程池和Spring异步处理高级篇
    开发过程中我们会遇到很多使用线程池的场景,例如异步短信通知,异步发邮件,异步记录操作日志,异步处理批量Excel解析。这些异步处理的场景我们都可以把它放在线程池中去完成,当然......
  • Java Math.random()函数
    Math.random() 函数返回一个浮点数,伪随机数在范围从0到小于1,也就是说,从0(包括0)往上,但是不包括1(排除1),然后您可以缩放到所需的范围。实现将初始种子选择到随机数生成算......
  • java protobuff, byte,字节数组等等转对象
     java中,字节数组转对象不外乎以下几种:1.使用原生的serilize进行序列化读写这个直接使用java内置的进行读写就行,但是不方便而且体积大冗余信息多。 2.使用第三方......