com.silentwu.schedule.dto.ResponseDto.java Source code

Java tutorial

Introduction

Here is the source code for com.silentwu.schedule.dto.ResponseDto.java

Source

/*
 * Copyright (c) 2013 WDCY Information Technology Co. Ltd
 * www.wdcy.cc
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * WDCY Information Technology Co. Ltd ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with WDCY Information Technology Co. Ltd.
 */
package com.silentwu.schedule.dto;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;

/**
 * @author Shengzhao Li
 */
public class ResponseDto {

    private boolean successful;

    private String message = "";

    private Object data;

    public ResponseDto() {
    }

    public boolean isSuccessful() {
        return successful;
    }

    @SuppressWarnings("unchecked")
    public static <T extends ResponseDto> T fail(String message) {
        ResponseDto responseDto = new ResponseDto();
        responseDto.successful = false;
        responseDto.message = message;
        responseDto.data = null;
        return (T) responseDto;
    }

    @SuppressWarnings("unchecked")
    public static <T extends ResponseDto> T success(Object data, String message) {
        ResponseDto responseDto = new ResponseDto();
        responseDto.successful = true;
        responseDto.message = message;
        responseDto.data = data;
        return (T) responseDto;
    }

    @SuppressWarnings("unchecked")
    public <T extends ResponseDto> T setSuccessful(boolean successful) {
        this.successful = successful;
        return (T) this;
    }

    public String getMessage() {
        return message;
    }

    @SuppressWarnings("unchecked")
    public <T extends ResponseDto> T setMessage(String message) {
        this.message = message;
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    public <T extends ResponseDto> T appendErrors(BindingResult result) {
        final List<FieldError> fieldErrors = result.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            final String defaultMessage = fieldError.getDefaultMessage();
            this.message += defaultMessage + ";";
        }
        this.successful = false;
        return (T) this;
    }

    public Object getData() {
        return data;
    }

    @SuppressWarnings("unchecked")
    public <T extends ResponseDto> T setData(Object data) {
        this.data = data;
        return (T) this;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("{successful=").append(successful);
        sb.append(", message='").append(message).append('\'');
        sb.append('}');
        return sb.toString();
    }
}