// validating if exists a tag with the name provided
HibernateUtil dh = new HibernateUtil(List.class);
dh.setQuery("from tag in class com.dotmarketing.tag.model.Tag where lower(tagName) = ?");
dh.setParam(name.toLowerCase());
Tag newTag = new Tag();
List<Tag> tags = (List<Tag>) dh.list();
// if doesn't exists then the tag is created
if (tags == null || tags.size() == 0) {
// creating tag
return saveTag(name, userId, hostId);
}
else {
//check if global tag already exists
boolean globalTagExists = false;
//check if tag exists with same tag name but for a different host
boolean tagExists = false;
for(Tag tag : tags){
if(isGlobalTag(tag)){
newTag = tag;
globalTagExists = true;
}
if(tag.getHostId()!=null && tag.getHostId().equals(hostId)){
newTag = tag;
tagExists = true;
}
}
if(!globalTagExists){
//if global doesn't exist, then save the tag and after it checks if it was stored as a global tag
try{
if(!tagExists)
newTag = saveTag(name, userId, hostId);
if(newTag.getHostId().equals(Host.SYSTEM_HOST)){
//move references of non-global tags to new global tag and delete duplicate non global tags
for(Tag tag : tags){
List<TagInode> tagInodes = getTagInodeByTagId(tag.getTagId());
for (TagInode tagInode : tagInodes){
updateTagInode(tagInode, newTag.getTagId());
}
deleteTag(tag);
}
}
}
catch(Exception e){
Logger.warn(TagFactory.class, "There was an error saving the tag. There's already a tag for selected host");
//return existent tag for selected host
}
}
}
String oldUserId = newTag.getUserId();
if ( oldUserId != null && !oldUserId.isEmpty() ) {
if ( userId == null || userId.isEmpty() ) {
userId = oldUserId;
} else if ( !oldUserId.equals( userId ) && !oldUserId.contains( userId ) ) {
userId = oldUserId + "," + userId;
}
}
newTag.setUserId( userId );
updateTag(newTag.getTagId(), userId);
// returning tag
return newTag;
}