All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.convergence_platform.common.responses.ApiResponse Maven / Gradle / Ivy

Go to download

Holds the common functionality needed by all Convergence Platform-based services written in Java.

The newest version!
package io.convergence_platform.common.responses;

import io.convergence_platform.common.dto.FailureInfoDTO;
import io.convergence_platform.common.dto.ResponseHeaderDTO;
import com.fasterxml.jackson.annotation.JsonProperty;

public class ApiResponse {
    @JsonProperty("header")
    public ResponseHeaderDTO header;

    @JsonProperty("body")
    public Type body = null;

    public ApiResponse() {

    }

    public ApiResponse(String bodyType, int httpStatusCode) {
        this.header = new ResponseHeaderDTO();
        this.header.setBodyType(bodyType);
        this.header.setHttpStatusCode(httpStatusCode);
        this.header.setMessage("OK");

        this.body = null;
    }

    private ApiResponse(Type body, int httpStatusCode) {
        this.header = new ResponseHeaderDTO();
        this.header.setBodyType(body.getResponseBodyType());
        this.header.setHttpStatusCode(httpStatusCode);

        if (body instanceof FailureInfoDTO) {
            FailureInfoDTO failure = (FailureInfoDTO) body;
            this.header.setCode(failure.getCode());
            this.header.setMessage(failure.getMessage());
            this.header.setRequestId(failure.getRequestId());
            this.header.setParentRequestId(failure.getParentRequestId());
            this.body = null;
        } else {
            this.header.setMessage("OK");
            this.body = body;
        }
    }

    public boolean wasSuccessful() {
        return this.header != null && this.header.getHttpStatusCode() >= 200 && this.header.getHttpStatusCode() < 300;
    }

    public static  ApiResponse from(T response) {
        if (response == null) {
            return new ApiResponse<>("empty", 200);
        }
        int statusCode = 200;
        if (response instanceof FailureInfoDTO) {
            statusCode = ((FailureInfoDTO) response).getHttpStatusCode();
        }

        return new ApiResponse<>(response, statusCode);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy