BaseBrAPIController.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.Collection;
import java.util.List;

import org.springframework.data.domain.Page;

import uk.ac.hutton.ics.brapi.resource.base.ArrayResult;
import uk.ac.hutton.ics.brapi.resource.base.BaseResult;
import uk.ac.hutton.ics.brapi.resource.base.Status;

/**
 * Base class for BrAPI controllers
 *
 */
public abstract class BaseBrAPIController {

	/** The Constant BR_APIv1_BASE. */
	public static final String BRAPIv1_BASE = "/brapi/v1";

	/** The Constant BR_APIv2_BASE. */
	public static final String BRAPIv2_BASE = "/brapi/v2";

	protected final List<Status> STATUS_CREATED = List.of(new Status().setMessageType("OK").setMessage("Created"));
	protected final List<Status> STATUS_UPDATED = List.of(new Status().setMessageType("OK").setMessage("Updated"));

	/**
	 * Generate BrAPI response for lists
	 * 
	 * @param <T>  target type
	 * @param collection
	 * @return General list of unpaginated records
	 */
	protected <T> BaseResult<Collection<T>> arrayResult(Collection<T> collection) {
		return new BaseResult<>(collection, List.of(new Status().setMessageType("OK").setMessage("Here you go!")));
	}

	/**
	 * Generate BrAPI response for paginated queries
	 * 
	 * @param <T>  target type
	 * @param page
	 * @return General list of records wrapped in {@code response.data}
	 */
	protected <T> BaseResult<ArrayResult<T>> arrayResult(Page<T> page) {
		return new BaseResult<>(new ArrayResult<>(page.getContent()), page.getNumber(), page.getSize(), page.getTotalElements(), page.getTotalPages());
	}

	/**
	 * Generate BrAPI response when creating new records
	 * 
	 * @param <T>  target type
	 * @param result the result object
	 * @param status List of status to include
	 * @return Records created response
	 */
	protected <T> BaseResult<T> createResult(T result, List<Status> status) {
		return new BaseResult<>(result, status);
	}

	/**
	 * Generate BrAPI response when creating new records
	 * 
	 * @param <T>  target type
	 * @param page
	 * @param status List of status to include
	 * @return Records created response
	 */
	protected <T> BaseResult<Collection<T>> createResult(Page<T> page, List<Status> status) {
		return new BaseResult<>(page.getContent(), status);
	}

}