org.nuiton.topia.templates.TopiaGeneratorUtil Maven / Gradle / Ivy
The newest version!
package org.nuiton.topia.templates;
/*
* #%L
* ToPIA :: Templates
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2004 - 2014 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.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.eugene.AbstractGenerator;
import org.nuiton.eugene.EugeneCoreTagValues;
import org.nuiton.eugene.GeneratorUtil;
import org.nuiton.eugene.java.JavaGeneratorUtil;
import org.nuiton.eugene.java.ObjectModelTransformerToJava;
import org.nuiton.eugene.models.object.ObjectModel;
import org.nuiton.eugene.models.object.ObjectModelAssociationClass;
import org.nuiton.eugene.models.object.ObjectModelAttribute;
import org.nuiton.eugene.models.object.ObjectModelClass;
import org.nuiton.eugene.models.object.ObjectModelClassifier;
import org.nuiton.eugene.models.object.ObjectModelElement;
import org.nuiton.eugene.models.object.ObjectModelInterface;
import org.nuiton.eugene.models.object.ObjectModelOperation;
import org.nuiton.eugene.models.object.ObjectModelPackage;
import org.nuiton.eugene.models.object.ObjectModelParameter;
import org.nuiton.topia.persistence.internal.AbstractTopiaDao;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* Classe regroupant divers méthodes utiles pour la génération des entités
*
* Created: 13 déc. 2005
*
* @author Arnaud Thimel (Code Lutin)
* @author Tony Chemit - [email protected]
* @author Florian Desbois- [email protected]
* @author Éric Chatellier - [email protected]
* @deprecated since 3.0, prefer use {@link TopiaTemplateHelper}.
*/
@Deprecated
public class TopiaGeneratorUtil extends JavaGeneratorUtil {
/** Logger */
private static final Log log = LogFactory.getLog(TopiaGeneratorUtil.class);
/**
* Static singleton instance used to read defaultValue
* TODO AThimel 19/06/14 Remove this when remove deprecated methods using it
*/
protected final static TopiaCoreTagValues TOPIA_TAG_VALUES = new TopiaCoreTagValues();
protected final static TopiaHibernateTagValues TOPIA_HIBERNATE_TAG_VALUES = new TopiaHibernateTagValues();
/**
* dependency to add extra operations for entity dao.
*
* @since 2.3.4
*/
public static final String DEPENDENCIES_DAO = "dao";
/** Type de persistence Hibernate */
public static final String PERSISTENCE_TYPE_HIBERNATE = "hibernate";
/**
* Type de persistence LDAP
*
* @deprecated since 3.0, use nowhere in ToPIA.
*/
@Deprecated
public static final String PERSISTENCE_TYPE_LDAP = "ldap";
/** Type de persistence par défaut (si aucun précisé) */
public static final String PERSISTENCE_TYPE_DEFAULT = PERSISTENCE_TYPE_HIBERNATE;
/** Propriété des générateurs indiquant le package par défaut */
public static final String PROPERTY_DEFAULT_PACKAGE = "defaultPackage";
/** Le package par défaut si aucun n'est spécifié */
public static final String DEFAULT_PACKAGE = "org.codelutin.malo";
/** Stratégie d'heritage par defaut. */
public static final String DEFAULT_INHERITANCE_STRATEGY = "union-subclass";
/**
* Renvoie le package par défaut pour le générateur donné
*
* @param generator le générateur donné
* @return le package par défaut du générator donné
*/
public static String getDefaultPackage(AbstractGenerator> generator) {
String packageName = generator.getProperty(PROPERTY_DEFAULT_PACKAGE);
if (StringUtils.isBlank(packageName)) {
packageName = DEFAULT_PACKAGE;
}
return packageName;
}
public static String getApplicationContextPackage(ObjectModelTransformerToJava transformer,
ObjectModel model) {
String result = transformer.getDefaultPackageName();
return result;
}
public static String getPersistenceContextPackage(ObjectModelTransformerToJava transformer,
ObjectModel model) {
String result = transformer.getDefaultPackageName();
return result;
}
public static String getDaoPackage(ObjectModelTransformerToJava transformer, ObjectModel model) {
String result = transformer.getDefaultPackageName();
return result;
}
public static String getParentDaoName(ObjectModel model) {
return "Abstract" + model.getName() + "TopiaDao";
}
public static String getParentDaoFqn(ObjectModelTransformerToJava transformer, ObjectModel model) {
return getDaoPackage(transformer, model) + "." + getParentDaoName(model);
}
public static String getApplicationContextInterfaceName(ObjectModel model) {
return model.getName() + "ApplicationContext";
}
public static String getApplicationContextAbstractName(ObjectModel model) {
return "Abstract" + model.getName() + "TopiaApplicationContext";
}
public static String getApplicationContextConcreteName(ObjectModel model) {
return model.getName() + "TopiaApplicationContext";
}
public static String getPersistenceContextAbstractName(ObjectModel model) {
return "Abstract" + model.getName() + "TopiaPersistenceContext";
}
public static String getPersistenceContextConcreteName(ObjectModel model) {
return model.getName() + "TopiaPersistenceContext";
}
public static String getPersistenceContextInterfaceName(ObjectModel model) {
return model.getName() + "PersistenceContext";
}
public static String getDaoSupplierInterfaceName(ObjectModel model) {
return model.getName() + "DaoSupplier";
}
public static String getDaoSupplierName(ObjectModel model) {
return model.getName() + "TopiaDaoSupplier";
}
public static String getEntityEnumName(ObjectModel model) {
return model.getName() + "EntityEnum";
}
public static String getEntityAbstractName(ObjectModelClass input) {
return input.getName() + "Abstract";
}
public static String getEntityConcreteName(ObjectModelClass input) {
return input.getName();
}
public static String getAbstractDaoName(ObjectModelClass input) {
return "Abstract" + input.getName() + "TopiaDao";
}
public static String getGeneratedDaoName(ObjectModelClass input) {
return "Generated" + input.getName() + "TopiaDao";
}
public static String getConcreteDaoName(ObjectModelClass input) {
return input.getName() + "TopiaDao";
}
public static String getContractDaoName(ObjectModelClass input) {
return input.getName() + "Dao";
}
public static String getAbstractDaoFqn(ObjectModelClass input) {
return input.getPackageName() + "." + getAbstractDaoName(input);
}
public static String getGeneratedDaoFqn(ObjectModelClass input) {
return input.getPackageName() + "." + getGeneratedDaoName(input);
}
public static String getConcreteDaoFqn(ObjectModelClass input) {
return input.getPackageName() + "." + getConcreteDaoName(input);
}
public static String getEntityPackage(ObjectModelTransformerToJava transformer,
ObjectModel model,
ObjectModelClassifier input) {
String result = input.getPackageName();
return result;
}
/**
* Renvoie le type de persistence pour le classifier donné. Si aucun n'est
* trouvé, le type par défaut est utilisé
*
* @param classifier l'élément à tester
* @return le type de persitence pour l'élément donné.
* @since 2.5
*/
public static String getPersistenceType(ObjectModelClassifier classifier) {
String tag = TOPIA_HIBERNATE_TAG_VALUES.getPersistenceTypeTagValue(classifier);
if (tag == null) {
tag = PERSISTENCE_TYPE_DEFAULT;
}
return tag;
}
/**
* Obtain the reverse db name of an attribute.
*
* If attribute has a specific reverse attribute, use his db name, otherwise
* suffix the db name of the attribute by {@code _id}.
*
* @param attr the attribute to seek
* @return the value of the reverse name
* @since 2.5
*/
public static String getReverseDbName(ObjectModelAttribute attr) {
if (attr.getReverseAttribute() != null) {
return getDbName(attr.getReverseAttribute());
} else {
return getDbName(attr) + "_id";
}
}
/**
* Renvoie le nom BD de l'élement passé en paramètre. Elle se base sur le
* tag associé si il existe, sinon sur le nom de l'élément
*
* @param element l'élément à tester
* @return le nom de table
*/
public static String getDbName(ObjectModelElement element) {
if (element == null) {
return null;
}
String value = TOPIA_HIBERNATE_TAG_VALUES.getDbNameTagValue(element);
if (value != null) {
return value;
}
return toLowerCaseFirstLetter(element.getName());
}
/**
* Cherche et renvoie la liste des attributs constituant la clef metier
* d'une classe.
*
* @param clazz la classe à tester
* @return la liste des attributs de la clef métier
*/
public static Set getNaturalIdAttributes(
ObjectModelClass clazz) {
// use {@link LinkedHashSet} to keep order and prevent duplicate natural ids found
Set results =
new LinkedHashSet<>();
for (ObjectModelAttribute attr : clazz.getAttributes()) {
if (TOPIA_HIBERNATE_TAG_VALUES.getNaturalIdTagValue(attr)) {
results.add(attr);
}
}
// sletellier : #2050 Natural id and not null attributes are not propagated on generalized entities (http://nuiton.org/issues/2050)
Collection superclasses = clazz.getSuperclasses();
for (ObjectModelClass superClass : superclasses) {
Set naturalIdsOfSuperClass = getNaturalIdAttributes(superClass);
results.addAll(naturalIdsOfSuperClass);
}
return results;
}
/**
* Cherche et renvoie la liste des attributs qui ne doivent pas etre null dans
* une classe.
*
* @param clazz la classe à tester
* @return la liste des attributs qui ne doivent pas etre null
*/
public static Set getNotNullAttributes(
ObjectModelClass clazz) {
// use {@link LinkedHashSet} to keep order and prevent duplicate not null found
Set results =
new LinkedHashSet<>();
for (ObjectModelAttribute attr : clazz.getAttributes()) {
if (isAttributeNotNull(attr)) {
results.add(attr);
}
}
Collection superclasses = clazz.getSuperclasses();
for (ObjectModelClass superClass : superclasses) {
Set notNullOfSuperClass = getNotNullAttributes(superClass);
results.addAll(notNullOfSuperClass);
}
// Association class participants are obviously not null
if (clazz instanceof ObjectModelAssociationClass) {
List participantsAttributes = ((ObjectModelAssociationClass) clazz).getParticipantsAttributes();
results.addAll(participantsAttributes);
}
return results;
}
/**
* Detecte si un attribut est marqué comme non null.
* Les naturalId sont not null par défaut
*
* @param attribute l'attribut à tester
* @return {@code true} si l'attribut doit être non null,
* par défaut pour les naturalId, {@code false} sinon..
* @since 2.6.9
*/
public static boolean isAttributeNotNull(ObjectModelAttribute attribute) {
Boolean value = TOPIA_HIBERNATE_TAG_VALUES.getNotNullTagValue(attribute);
if (value == null) {
// valeur null, donc pas positionnee
return TOPIA_HIBERNATE_TAG_VALUES.getNaturalIdTagValue(attribute);
}
return value;
}
public static String getDOType(ObjectModelElement elem, ObjectModel model) {
String type = elem.getName();
if (elem instanceof ObjectModelAttribute) {
type = ((ObjectModelAttribute) elem).getType();
}
if (elem instanceof ObjectModelClass) {
type = ((ObjectModelClass) elem).getQualifiedName();
}
return getDOType(type, model);
}
public static String getDOType(String type, ObjectModel model) {
if (!model.hasClass(type)) {
return type;
}
ObjectModelClass clazz = model.getClass(type);
if (isEntity(clazz)) {
//tchemit-2011-09-12 What ever abstract or not, we always use an Impl
type += "Impl";
// if (shouldBeAbstract(clazz)) {
// type += "Abstract";
// } else {
// type += "Impl";
// }
}
return type;
}
private static final Set numberTypes = new HashSet<>();
private static final Set textTypes = new HashSet<>();
private static final Set booleanTypes = new HashSet<>();
private static final Set primitiveTypes = new HashSet<>();
private static final Map primitiveTypeToClass = new HashMap<>();
private static final String VOID_TYPE = "void";
static {
primitiveTypeToClass.put("byte", "java.lang.Byte");
primitiveTypeToClass.put("short", "java.lang.Short");
primitiveTypeToClass.put("int", "java.lang.Integer");
primitiveTypeToClass.put("long", "java.lang.Long");
primitiveTypeToClass.put("float", "java.lang.Float");
primitiveTypeToClass.put("double", "java.lang.Double");
primitiveTypeToClass.put("char", "java.lang.Char");
primitiveTypeToClass.put("boolean", "java.lang.Boolean");
numberTypes.add("byte");
numberTypes.add("java.lang.Byte");
numberTypes.add("Byte");
numberTypes.add("short");
numberTypes.add("java.lang.Short");
numberTypes.add("Short");
numberTypes.add("int");
numberTypes.add("java.lang.Integer");
numberTypes.add("Integer");
numberTypes.add("long");
numberTypes.add("java.lang.Long");
numberTypes.add("Long");
numberTypes.add("float");
numberTypes.add("java.lang.Float");
numberTypes.add("Float");
numberTypes.add("double");
numberTypes.add("java.lang.Double");
numberTypes.add("Double");
textTypes.add("char");
textTypes.add("java.lang.Char");
textTypes.add("Char");
textTypes.add("java.lang.String");
textTypes.add("String");
booleanTypes.add("boolean");
booleanTypes.add("java.lang.Boolean");
booleanTypes.add("Boolean");
primitiveTypes.addAll(numberTypes);
primitiveTypes.addAll(textTypes);
primitiveTypes.addAll(booleanTypes);
}
public static boolean isNumericType(ObjectModelAttribute attr) {
return numberTypes.contains(attr.getType());
}
public static boolean isTextType(ObjectModelAttribute attr) {
return textTypes.contains(attr.getType());
}
public static boolean isDateType(ObjectModelAttribute attr) {
return "java.util.Date".equals(attr.getType());
}
public static boolean isBooleanType(ObjectModelAttribute attr) {
return booleanTypes.contains(attr.getType());
}
public static boolean isPrimitiveType(ObjectModelAttribute attr) {
return primitiveTypes.contains(attr.getType());
}
public static String getClassForPrimitiveType(ObjectModelAttribute attr) {
Preconditions.checkState(isPrimitiveType(attr));
String className = primitiveTypeToClass.get(attr.getType());
Preconditions.checkNotNull(className);
return className;
}
/**
*
* Cette méthode permet de détecter si
* - l'attribut représente une relation 1-n
* - cette relation est unidirectionnelle
* - le type de l'attribut représente un entité
* - cette entité a des sous-classes dans le modèle
*
* Ce cas correspond à une incompatibilité d'Hibernate qui nous oblige a
* adopter un comportement particulier.
*
*
* @param attr l'attribut a tester
* @param model le model
* @return true si et seulement si il s'agit bien de ce type de relation
*/
public static boolean hasUnidirectionalRelationOnAbstractType(
ObjectModelAttribute attr, ObjectModel model) {
ObjectModelAttribute reverse = attr.getReverseAttribute();
//relation 1-n
if (reverse != null && isNMultiplicity(attr) &&
!isNMultiplicity(reverse)) {
//Pas de navigabilité
if (!reverse.isNavigable()) {
//Il s'agit d'une entity
ObjectModelClass clazz = model.getClass(attr.getType());
if (clazz != null && isEntity(clazz)) {
//Cette classe a des sous-classes dans le modèle
for (ObjectModelClass subClass : model.getClasses()) {
if (subClass.getSuperclasses().contains(clazz)) {
return true;
}
}
}
}
}
return false;
}
/**
* Renvoie le nom unique de table pour une relation ManyToMany en fonction
* de l'attribut {@code attr}
*
* @param attr l'attribut servant de base au calcul du nom
* @return le nom de la table
*/
public static String getManyToManyTableName(ObjectModelAttribute attr) {
String result;
if (attr.hasAssociationClass()) {
result = getDbName(attr.getAssociationClass());
} else {
String name = attr.getName();
String revers = attr.getReverseAttributeName();
if (name.compareToIgnoreCase(revers) < 0) {
result = name + '_' + revers;
} else {
result = revers + '_' + name;
}
}
return result.toLowerCase();
}
/**
* Renvoie le type d'interface à utiliser en fonction de l'attribut
*
* @param attr l'attribut a traiter
* @return String
*/
public static String getNMultiplicityHibernateType(
ObjectModelAttribute attr) {
if (JavaGeneratorUtil.isOrdered(attr)) {
return "list";
} else if (EugeneCoreTagValues.isUnique(attr)) {
return "set";
}
//attr.isOrdered() - On génère le ordered en bag
return "bag";
}
/**
* Obtain the list of entities classes with the possibility to sort the
* result.
*
* @param model the current model to scan
* @param sort flag to allow sort the result
* @return the list of filtred classes by their stereotype
*/
public static List getEntityClasses(ObjectModel model,
boolean sort) {
return getClassesByStereotype(TopiaCoreTagValues.Store.entity.getName(), model, sort);
}
/**
* Obtain the list of classes for a given stereotype with the possibility
* to sort the result.
*
* @param stereotype filter stereotype
* @param model the current model to scan
* @param sort flag to allow sort the result
* @return the list of filtred classes by their stereotype
*/
public static List getClassesByStereotype(
String stereotype, ObjectModel model, boolean sort) {
List classes = new ArrayList<>();
for (ObjectModelClass clazz : model.getClasses()) {
if (clazz.hasStereotype(stereotype)) {
classes.add(clazz);
}
}
if (sort && !classes.isEmpty()) {
Collections.sort(classes, OBJECT_MODEL_CLASS_COMPARATOR);
}
return classes;
}
public static final Comparator
OBJECT_MODEL_CLASS_COMPARATOR =
new Comparator() {
@Override
public int compare(ObjectModelClass o1,
ObjectModelClass o2) {
return o1.getQualifiedName().compareTo(
o2.getQualifiedName());
}
};
/**
* Obtain the list of fqn of object involed in the given class.
*
* @param aClass the clazz to inspect
* @param incomingFqns incoming fqns
* @return the list of fqn of attributes
*/
public static List getImports(ObjectModelClass aClass,
String... incomingFqns) {
Set tmp = new HashSet<>();
tmp.addAll(Arrays.asList(incomingFqns));
getImports(aClass, tmp);
List result = cleanImports(aClass.getPackageName(), tmp);
return result;
}
/**
* Obtain the list of fqn of object involed in the given class.
*
* @param aClass the class to inspect
* @param fqns where to store found fqns
*/
protected static void getImports(ObjectModelClass aClass,
Set fqns) {
// scan attributes
for (ObjectModelAttribute attr : aClass.getAttributes()) {
fqns.add(attr.getType());
if (isNMultiplicity(attr)) {
String collectionType = getCollectionType(attr).getName();
fqns.add(collectionType);
String collectionObject = getCollectionInstanceType(attr).getName();
fqns.add(collectionObject);
}
}
for (ObjectModelAttribute attribute : aClass.getAllOtherAttributes()) {
fqns.add(attribute.getType());
}
// scan associations
if (aClass instanceof ObjectModelAssociationClass) {
ObjectModelAssociationClass assoc =
(ObjectModelAssociationClass) aClass;
for (ObjectModelAttribute attr :
assoc.getParticipantsAttributes()) {
if (attr == null) {
continue;
}
fqns.add(attr.getType());
if (isNMultiplicity(attr)) {
String collectionType = getCollectionType(attr).getName();
fqns.add(collectionType);
String collectionObject = getCollectionInstanceType(attr).getName();
fqns.add(collectionObject);
}
}
}
// scan operations
for (ObjectModelOperation operation : aClass.getOperations()) {
getImports(operation, fqns);
}
// scan super interfaces
for (ObjectModelInterface modelInterface : aClass.getInterfaces()) {
fqns.add(modelInterface.getQualifiedName());
getImports(modelInterface, fqns);
}
// scan super classes
for (ObjectModelClass modelClass : aClass.getSuperclasses()) {
fqns.add(modelClass.getQualifiedName());
getImports(modelClass);
}
}
/**
* Obtain the list of fqn of object involed in the given interface.
*
* @param anInterface the interface to inspect
* @param fqns where to store found fqns
*/
protected static void getImports(ObjectModelInterface anInterface,
Set fqns) {
// scan operations
for (ObjectModelOperation operation : anInterface.getOperations()) {
getImports(operation, fqns);
}
// scan super interfaces
for (ObjectModelInterface modelInterface : anInterface.getInterfaces()) {
fqns.add(modelInterface.getQualifiedName());
getImports(modelInterface, fqns);
}
}
/**
* Obtain the fqn's list of all involed type in a givne operation.
*
* @param operation operation to inspect
* @param fqns where to store found fqns
*/
protected static void getImports(ObjectModelOperation operation,
Set fqns) {
String fqn = operation.getReturnType();
fqns.add(fqn);
for (ObjectModelParameter parameter : operation.getParameters()) {
fqns.add(parameter.getType());
}
}
/**
* Clean a set of fqns, transform it into a {@link List} and sort it.
*
* @param packageName the current package name
* @param fqns the dirty set of fqns
* @return the sorted cleaned list of fqns.
*/
protected static List cleanImports(String packageName,
Set fqns) {
fqns.removeAll(primitiveTypes);
fqns.remove(VOID_TYPE);
int packageLength = packageName.length();
List genericType = new ArrayList<>();
for (Iterator it = fqns.iterator(); it.hasNext(); ) {
String fqn = it.next();
int lastIndex = fqn.lastIndexOf(".");
if (lastIndex == packageLength && fqn.startsWith(packageName)) {
// same package
it.remove();
continue;
}
int genericIndex = fqn.indexOf('<');
if (genericIndex != -1) {
genericType.add(fqn.substring(0, genericIndex));
it.remove();
}
}
fqns.addAll(genericType);
ArrayList result = new ArrayList<>(fqns);
Collections.sort(result);
return result;
}
public static Map>
searchDirectUsages(ObjectModel model) {
List allEntities;
Map allEntitiesByFQN;
Map> usages;
allEntities = getEntityClasses(model, true);
allEntitiesByFQN = new TreeMap<>();
usages = new LinkedHashMap<>();
// prepare usages map and fill allEntitiesByFQN map
for (ObjectModelClass klass : allEntities) {
usages.put(klass, new HashSet());
allEntitiesByFQN.put(klass.getQualifiedName(), klass);
}
// first pass to detect direct usages
for (ObjectModelClass klass : allEntities) {
searchDirectUsages(klass, allEntitiesByFQN, usages);
}
allEntities.clear();
allEntitiesByFQN.clear();
return usages;
}
public static void searchDirectUsages(
ObjectModelClass klass,
Map allEntitiesByFQN,
Map> usages) {
if (log.isDebugEnabled()) {
log.debug("for entity " + klass.getQualifiedName());
}
for (ObjectModelAttribute attr : klass.getAttributes()) {
if (!attr.isNavigable()) {
// skip this case
continue;
}
String type;
if (attr.hasAssociationClass()) {
type = attr.getAssociationClass().getQualifiedName();
} else {
type = attr.getType();
}
if (!allEntitiesByFQN.containsKey(type)) {
// not a entity, can skip for this attribute
continue;
}
if (log.isDebugEnabled()) {
log.debug(" uses " + type);
}
// register the klass as using the targetEntity
ObjectModelClass targetEntity = allEntitiesByFQN.get(type);
Set classes = usages.get(targetEntity);
classes.add(klass);
}
}
public static boolean isImportNeeded(Collection operations,
String importName) {
if (CollectionUtils.isNotEmpty(operations)) {
for (ObjectModelOperation op : operations) {
if (op.getReturnType().contains(importName)) {
return true;
}
for (ObjectModelParameter param : op.getParameters()) {
if (param.getType().contains(importName)) {
return true;
}
}
}
}
return false;
}
public static boolean isCollectionNeeded(
Collection operations) {
return isImportNeeded(operations,
Collection.class.getSimpleName());
}
public static boolean isSetNeeded(Collection operations) {
return isImportNeeded(operations,
Set.class.getSimpleName());
}
/**
* Check if the given attribute type is an entity.
*
* @param attribute attribute to test
* @param model model containing the attribute
* @return {@code true} if type of attribute is an entity,
* {@code false} otherwise
* @see TopiaCoreTagValues.Store#entity
* @since 2.7
*/
public static boolean isEntity(ObjectModelAttribute attribute,
ObjectModel model) {
if (isPrimitiveType(attribute)) {
return false;
}
String attributeType = attribute.getType();
ObjectModelClassifier typeclassifier =
model.getClassifier(attributeType);
return typeclassifier != null && isEntity(typeclassifier);
}
/**
* Check if the given classifier has the
* {@link TopiaCoreTagValues.Store#entity} and is not an enumeration
*
* @param classifier classifier to test
* @return {@code true} if stereotype was found and classifier is not
* enumeration, {@code false} otherwise
* @see TopiaCoreTagValues.Store#entity
* @since 2.5
*/
public static boolean isEntity(ObjectModelClassifier classifier) {
return TOPIA_TAG_VALUES.isEntity(classifier, null) && !classifier.isEnum();
}
/**
* Obtain the value of the {@link TopiaHibernateTagValues.Store#inheritanceStrategy} tag value on the given classifier.
*
* @param classifier classifier to seek
* @return the none empty value of the found tag value or {@code null} if not found nor empty.
* @see TopiaHibernateTagValues.Store#inheritanceStrategy
* @since 3.0
*/
public static String getInheritanceStrategy(ObjectModelClassifier classifier) {
String value = TOPIA_HIBERNATE_TAG_VALUES.getInheritanceStrategyTagValue(classifier, null);
if (value == null) {
value = TopiaGeneratorUtil.DEFAULT_INHERITANCE_STRATEGY;
}
return value;
}
//---------------------------------------------------------------------------------------------------------------
//-- DEPRECATED API TO REMOVE ---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------
@Deprecated
public static String getLegacyDaoName(ObjectModelClass input) {
return input.getName() + "DAO";
}
/**
* @param FIXME
* @param elements FIXME
* @param stereotypes FIXME
* @return FIXME
* @deprecated since 3.0, not used anywhere in ToPIA
*/
@Deprecated
public static Collection getElementsWithStereotype(
Collection elements, String... stereotypes) {
Collection result = new ArrayList<>();
for (Type element : elements) {
if (hasStereotypes(element, stereotypes)) {
result.add(element);
}
}
return result;
}
/**
* @param element FIXME
* @param stereotypes FIXME
* @return FIXME
* @deprecated since 3.0, not used anywhere in ToPIA
*/
@Deprecated
public static boolean hasStereotypes(ObjectModelElement element,
String... stereotypes) {
for (String stereotype : stereotypes) {
if (!element.hasStereotype(stereotype)) {
return false;
}
}
return true;
}
/**
* @param clazz FIXME
* @param includeName FIXME
* @return FIXME
* @deprecated since 3.0, not used anywhere in ToPIA
*/
@Deprecated
public static String getPrimaryKeyAttributesListDeclaration(
ObjectModelClass clazz, boolean includeName) {
Collection attributeCollection;
attributeCollection = getElementsWithStereotype(clazz.getAttributes(),
TopiaCoreTagValues.Store.primaryKey.getName());
List attributes = Lists.newArrayList();
for (ObjectModelAttribute attr : attributeCollection) {
String attribute = attr.getType();
if (includeName) {
attribute += ' ';
attribute += attr.getName();
}
attributes.add(attribute);
}
return Joiner.on(", ").join(attributes);
}
/**
* @param attr FIXME
* @return FIXME
* @deprecated since 3.0, not used anywhere in ToPIA
*/
@Deprecated
public static boolean isAssociationClassDoublon(ObjectModelAttribute attr) {
return attr.getReverseAttribute() != null &&
attr.getDeclaringElement().equals(
attr.getReverseAttribute().getDeclaringElement()) &&
!GeneratorUtil.isFirstAttribute(attr);
}
/**
* Obtain the list of fqn of object involed in the given interface.
*
* @param anInterface the interface to inspect
* @param incomingFqns incoming fqns
* @return the list of fqn of attributes
* @deprecated since 3.0, not used anywhere in ToPIA
*/
@Deprecated
public static List getImports(ObjectModelInterface anInterface,
String... incomingFqns) {
Set tmp = new HashSet<>();
tmp.addAll(Arrays.asList(incomingFqns));
getImports(anInterface, tmp);
List result = cleanImports(anInterface.getPackageName(), tmp);
return result;
}
/**
* Indique si la classe specifiee n'a aucune ou que des methodes abstraites
*
* @param clazz l'instance de ObjectModelClass
* @return true si la classe n'a que des operations abstraite ou aucune
* operation
* @deprecated since 3.0, used nowhere in ToPIA
*/
@Deprecated
public static boolean hasNothingOrAbstractMethods(ObjectModelClass clazz) {
boolean result = true;
Iterator> operations = clazz.getOperations().iterator();
while (result && operations.hasNext()) {
ObjectModelOperation op = (ObjectModelOperation) operations.next();
result = op.isAbstract();
}
return result;
}
/**
* Indique si la classe specifiee devrait etre abstraite
*
* @param clazz l'instance de ObjectModelClass
* @return true dans ce cas, false sinon
* @deprecated since 3.0, used nowhere in ToPIA
*/
@Deprecated
public static boolean shouldBeAbstract(ObjectModelClass clazz) {
return clazz != null && clazz.isAbstract() &&
hasNothingOrAbstractMethods(clazz);
}
/**
* Obtain the class to use as abstract dao.
*
* It will look after a tag value {@link TopiaCoreTagValues.Store#daoSuperClass} in model
* and if not found will use the default value which is {@link AbstractTopiaDao}.
*
* @param model the model which could contains
* @return the type of the abstract dao to use
* @since 2.5
* @deprecated since 3.0-alpha-8, replaced by {@link TopiaCoreTagValues#getDaoSuperClassTagValue(ObjectModelClassifier, ObjectModelPackage, ObjectModel)}
*/
@Deprecated
public static Class> getDAOImplementation(ObjectModel model) {
String daoImpl = TOPIA_TAG_VALUES.getDaoImplementationTagValue(model);
Class> result;
if (StringUtils.isEmpty(daoImpl)) {
// use the default dao implementation of topia
result = AbstractTopiaDao.class;
} else {
try {
result = Class.forName(daoImpl);
} catch (ClassNotFoundException e) {
String message = "Could not find dao implementation named " + daoImpl;
log.error(message);
throw new IllegalStateException(message, e);
}
}
return result;
}
} // TopiaGeneratorUtil