ApiBaseController.java

/*
 * Copyright 2019 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.api.v1;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * Base class for API controllers
 *
 * @author Matija Obreza
 */
@Slf4j
public abstract class ApiBaseController {

	public static final String APIv1_BASE = "/api/v1";
	public static final String APIv2_BASE = "/api/v2";
	public static final String APIv1_ADMIN_BASE = APIv1_BASE + "/admin";
	public static final String APIv2_ADMIN_BASE = APIv2_BASE + "/admin";
	@Value("${api.page.max:200}")
	protected int MAX_PAGE_SIZE;
	@Value("${api.page.default:50}")
	protected int DEFAULT_PAGE_SIZE;

	public ApiBaseController() {
		super();
	}

	public static class ApiError {
		public String message;
		public Object[] args;
		@JsonIgnore
		public Throwable cause;

		public ApiError(final Throwable e, final Object... arguments) {
			this.message = e.getMessage();
			this.args = arguments;
			this.cause = e;
		}
	}

	public static class OpResponse<T> {
		public T success;
		public ApiError error;

		public OpResponse(final T result) {
			this.success = result;
		}

		public OpResponse(final Throwable e, final Object... arguments) {
			this.error = new ApiError(e, arguments);
		}
	}
}