com.getperka.flatpack.FlatPackEntity Maven / Gradle / Ivy
/*
* #%L
* FlatPack serialization code
* %%
* Copyright (C) 2012 Perka Inc.
* %%
* 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.
* #L%
*/
package com.getperka.flatpack;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.security.Principal;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.inject.Inject;
import javax.validation.ConstraintViolation;
import org.joda.time.DateTime;
import com.getperka.flatpack.util.FlatPackCollections;
import com.getperka.flatpack.util.FlatPackTypes;
import com.google.inject.TypeLiteral;
/**
* Encapsulates a return value, the role(s) to encode the entity for, and an optional collection of
* extra entities to include in the payload.
*
* @param the type of value being returned
*/
public class FlatPackEntity extends TypeReference {
/**
* A convenience method to create a FlatPackEntity for a List of entities.
*
* @param the type of entity contained in the list.
* @param clazz the entity type
*/
public static FlatPackEntity> collectionOf(
final Class clazz) {
return new FlatPackEntity>(new ParameterizedType() {
@Override
public Type[] getActualTypeArguments() {
return new Type[] { clazz };
}
@Override
public Type getOwnerType() {
return null;
}
@Override
public Type getRawType() {
return Collection.class;
}
});
}
/**
* A factory method to create a fully-specified FlatPackEntity.
*/
public static FlatPackEntity> create(Type returnType, Object toReturn, Principal principal) {
// Convert primitive types to boxed
Class> erased = FlatPackTypes.erase(returnType);
if (erased.isPrimitive()) {
returnType = FlatPackTypes.box(erased);
}
return new FlatPackEntity