BrAPIResponse.java
/*
* Copyright 2020 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gringlobal.brapi;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.domain.Page;
/**
* BrAPI v1 response structure
*
* @author Matija Obreza
*/
public class BrAPIResponse<T> {
public Metadata metadata = new Metadata();
public Object result;
public BrAPIResponse() {
}
public BrAPIResponse(Page<T> results) {
this.result = new Result<T>(results.getContent());
this.metadata.pagination = new Pagination();
this.metadata.pagination.update(results);
}
public BrAPIResponse(Throwable exception) {
this.metadata.status.add(new Status(exception.getMessage()));
}
public BrAPIResponse(T result) {
this.result = result;
}
/**
* Response metadata
*/
public static class Metadata {
/// If no status is reported, an empty list should be returned
public List<Status> status = new ArrayList<>();
/// The datafiles key contains a list of strings. The empty list should be
/// returned if no datafiles are present.
public List<String> datafiles = new ArrayList<>();
/// For paginated results
public Pagination pagination;
}
/**
* The status object contains a list of objects with the keys "code" and
* "message".
*/
public static class Status {
public Status(String message) {
this.message = message;
}
public Status(String code, String message) {
this.code = code;
this.message = message;
}
public String code;
public String message;
}
/**
* BrAPI pagination
*/
public static class Pagination {
public int pageSize = 0;
public int currentPage = 0;
public long totalCount = 0;
public int totalPages = 0;
/**
* Update this Pagination with information from Spring's Page<?>
*
* @param page the page
*/
public void update(Page<?> page) {
this.pageSize = page.getSize();
this.currentPage = page.getNumber();
this.totalPages = page.getTotalPages();
this.totalCount = page.getTotalElements();
}
}
public static class Result<T> {
public List<T> data;
public Result(List<T> content) {
data = content;
}
}
}