org.nuiton.jpa.api.JpaEntities Maven / Gradle / Ivy
package org.nuiton.jpa.api;
/*
* #%L
* Nuiton Jpa :: API
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2013 CodeLutin
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* .
* #L%
*/
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import org.apache.commons.lang3.ObjectUtils;
import java.io.Serializable;
import java.util.Comparator;
/**
* Helper class around {@link JpaEntity}.
*
* @author bleny
* @author tchemit
* @since 1.0
*/
public class JpaEntities {
public static E findById(Iterable entities, String id) {
E result;
if (entities == null) {
result = null;
} else {
Optional eOptional = Iterables.tryFind(entities, entityHasId(id));
result = eOptional.orNull();
}
return result;
}
public static class GetIdFunction implements Function {
@Override
public String apply(JpaEntity entity) {
return entity.getId();
}
}
public static class ArbitraryComparator implements Comparator, Serializable {
private static final long serialVersionUID = 1L;
@Override
public int compare(E x, E y) {
return ObjectUtils.compare(x.getId(), y.getId());
}
}
public static Function getIdFunction() {
return new GetIdFunction();
}
public static boolean isEntityHasId(JpaEntity entity, String id) {
boolean result = entityHasId(id).apply(entity);
return result;
}
public static boolean isEntityHasId(JpaEntity entity) {
boolean result = entityHasId().apply(entity);
return result;
}
public static boolean isEntityHasNoId(JpaEntity entity) {
boolean result = entityHasNoId().apply(entity);
return result;
}
public static Predicate entityHasId(String id) {
return Predicates.compose(Predicates.equalTo(id), getIdFunction());
}
public static Predicate entityHasId() {
return Predicates.compose(Predicates.notNull(), getIdFunction());
}
public static Predicate entityHasNoId() {
return Predicates.compose(Predicates.equalTo(null), getIdFunction());
}
public static Comparator arbitraryComparator() {
return new ArbitraryComparator();
}
}