// 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;
Host host = APILocator.getHostAPI().find(hostId, APILocator.getUserAPI().getSystemUser(), true);
if(host.getMap().get("tagStorage") == null){
existHostId = host.getMap().get("identifier").toString();
}
else {
existHostId = host.getMap().get("tagStorage").toString();
}
for(Tag tag : tags){
if(isGlobalTag(tag)){
newTag = tag;
globalTagExists = true;
}
if(tag.getHostId().equals(existHostId)){
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);
}
}
}