JsonSidConverter.java

/*
 * Copyright 2018 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.genesys.blocks.util;

import com.fasterxml.jackson.databind.util.StdConverter;
import org.genesys.blocks.security.model.AclSid;

/**
 * The JsonSidConverter converts SID IDs to SID names.
 */
public class JsonSidConverter extends StdConverter<Object, String> {
	
	private static SidProvider SID_PROVIDER;
	
	/**
	 * A SID-to-name provider maps {@code id} to {@code String}.
	 */
	public static interface SidProvider {
		/**
		 * Get name of SID by {@code id}
		 * @param id SID ID
		 * @return SID name
		 */
		String getSidName(long id);
	}
	
	/**
	 * Sets the sid provider.
	 *
	 * @param sidProvider the new sid provider
	 */
	public static void setSidProvider(SidProvider sidProvider) {
		SID_PROVIDER = sidProvider;
	}

	/**
	 * Convert SID ID to SID name using SID_PROVIDER (when available)
	 */
	@Override
	public String convert(Object value) {
		if (value == null) {
			return null;
		} else if (value instanceof AclSid) {
			var sid = (AclSid) value;
			return SID_PROVIDER == null || sid.getId() == null ? value.toString() : SID_PROVIDER.getSidName(sid.getId());
		} else if (value instanceof Long) {
			return SID_PROVIDER == null ? value.toString() : SID_PROVIDER.getSidName((Long) value);
		}
		throw new IllegalArgumentException("Cannot convert the object of type " + value.getClass().getName());
	}
}