/*
* Copyright (C) 2016 LibreCCM Foundation.
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.librecms.contentsection;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Collections;
import org.libreccm.categorization.Category;
import org.librecms.lifecycle.LifecycleDefinition;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import org.libreccm.categorization.Categorization;
import org.libreccm.categorization.CategoryManager;
import org.libreccm.categorization.ObjectNotAssignedToCategoryException;
import org.libreccm.core.UnexpectedErrorException;
import org.libreccm.l10n.LocalizedString;
import org.libreccm.security.AuthorizationRequired;
import org.libreccm.security.RequiresPrivilege;
import org.libreccm.workflow.Workflow;
import org.libreccm.workflow.WorkflowManager;
import static org.librecms.CmsConstants.*;
import org.librecms.contentsection.privileges.ItemPrivileges;
import org.librecms.lifecycle.Lifecycle;
import org.librecms.lifecycle.LifecycleManager;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import org.libreccm.security.PermissionChecker;
import org.libreccm.security.PermissionManager;
import org.librecms.contentsection.privileges.TypePrivileges;
/**
* Manager class providing several methods to manipulate {@link ContentItem}s.
*
* @author Jens Pelzetter
*/
@RequestScoped
public class ContentItemManager {
private static final Logger LOGGER = LogManager.getLogger(
ContentItemManager.class);
@Inject
private AssetManager assetManager;
@Inject
private CategoryManager categoryManager;
@Inject
private ContentItemRepository contentItemRepo;
@Inject
private ContentSectionManager sectionManager;
@Inject
private ContentTypeRepository typeRepo;
@Inject
private EntityManager entityManager;
@Inject
private FolderManager folderManager;
@Inject
private FolderRepository folderRepo;
@Inject
private LifecycleManager lifecycleManager;
@Inject
private PermissionChecker permissionChecker;
@Inject
private PermissionManager permissionManager;
@Inject
private WorkflowManager workflowManager;
/**
* Creates a new content item in the provided content section and folder
* with the default workflow for the content type of the item.
*
* The folder must be a subfolder of the
* {@link ContentSection#rootDocumentsFolder} of the provided content
* section. Otherwise an {@link IllegalArgumentException} is thrown.
*
* @param The type of the content item.
* @param name The name (URL stub) of the new content item.
* @param section The content section in which the item is generated.
* @param folder The folder in which in the item is stored.
* @param type The type of the new content item.
* @param locale Initial locale of the new item
*
* @return The new content item.
*/
@AuthorizationRequired
@Transactional(Transactional.TxType.REQUIRED)
public T createContentItem(
final String name,
final ContentSection section,
@RequiresPrivilege(ItemPrivileges.CREATE_NEW)
final Folder folder,
final Class type,
final Locale locale) {
return createContentItem(name,
section,
folder,
type,
item -> {
},
locale);
}
/**
* Creates a new content item in the provided content section and folder
* with the default workflow for the content type of the item.
*
* The folder must be a subfolder of the
* {@link ContentSection#rootDocumentsFolder} of the provided content
* section. Otherwise an {@link IllegalArgumentException} is thrown.
*
* @param The type of the content item.
* @param name The name (URL stub) of the new content item.
* @param section The content section in which the item is generated.
* @param folder The folder in which in the item is stored.
* @param type The type of the new content item.
* @param initalizer A {@link ContentItemInitializer} for setting mandatory
* values
* @param locale Initial locale of the new item
*
* @return The new content item.
*/
@AuthorizationRequired
@Transactional(Transactional.TxType.REQUIRED)
public T createContentItem(
final String name,
final ContentSection section,
@RequiresPrivilege(ItemPrivileges.CREATE_NEW)
final Folder folder,
final Class type,
final ContentItemInitializer initalizer,
final Locale locale) {
final Optional contentType = typeRepo
.findByContentSectionAndClass(section, type);
if (!contentType.isPresent()) {
throw new IllegalArgumentException(String.format(
"ContentSection \"%s\" has no content type for \"%s\".",
section.getLabel(),
type.getName()));
}
return createContentItem(name,
section,
folder,
contentType.get().getDefaultWorkflow(),
type,
initalizer,
locale);
}
/**
* Creates a new content item in the provided content section and folder
* with specific workflow.
*
* The folder must be a subfolder of the
* {@link ContentSection#rootDocumentsFolder} of the provided content
* section. Otherwise an {@link IllegalArgumentException} is thrown.
*
* Likewise the provided abstract {@link Workflow} must be defined in the
* provided content section. Otherwise an {@link IllegalArgumentException}
* is thrown.
*
* @param The type of the content item.
* @param name The name (URL stub) of the new content item.
* @param section The content section in which the item is
* generated.
* @param folder The folder in which in the item is stored.
* @param workflowTemplate The template for the workflow to apply to the new
* item.
* @param type The type of the new content item.
* @param locale
*
* @return The new content item.
*/
@AuthorizationRequired
@Transactional(Transactional.TxType.REQUIRED)
public T createContentItem(
final String name,
final ContentSection section,
@RequiresPrivilege(ItemPrivileges.CREATE_NEW)
final Folder folder,
final Workflow workflowTemplate,
final Class type,
final Locale locale) {
return createContentItem(name,
section,
folder,
workflowTemplate,
type,
item -> {
},
locale);
}
/**
* Creates a new content item in the provided content section and folder
* with specific workflow.
*
* The folder must be a subfolder of the
* {@link ContentSection#rootDocumentsFolder} of the provided content
* section. Otherwise an {@link IllegalArgumentException} is thrown.
*
* Likewise the provided abstract {@link Workflow} must be defined in the
* provided content section. Otherwise an {@link IllegalArgumentException}
* is thrown.
*
* @param The type of the content item.
* @param name The name (URL stub) of the new content item.
* @param section The content section in which the item is
* generated.
* @param folder The folder in which in the item is stored.
* @param workflowTemplate The template for the workflow to apply to the new
* item.
* @param type The type of the new content item.
* @param initializer Initialiser implementation for setting mandatory
* properties of the new item.
* @param locale Initial locale of the new item
*
* @return The new content item.
*/
@AuthorizationRequired
@Transactional(Transactional.TxType.REQUIRED)
public T createContentItem(
final String name,
final ContentSection section,
@RequiresPrivilege(ItemPrivileges.CREATE_NEW)
final Folder folder,
final Workflow workflowTemplate,
final Class type,
final ContentItemInitializer initializer,
final Locale locale) {
final Optional contentType = typeRepo
.findByContentSectionAndClass(section, type);
if (!contentType.isPresent()) {
throw new IllegalArgumentException(String.format(
"ContentSection \"%s\" has no content type for \"%s\".",
section.getLabel(),
type.getName()));
}
//Check if the current user is allowed to use the content type
permissionChecker.checkPermission(TypePrivileges.USE_TYPE,
contentType.get());
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException(
"The name of a content item can't be blank.");
}
final T item;
try {
item = type.newInstance();
} catch (InstantiationException | IllegalAccessException ex) {
LOGGER.error("Failed to create new content item of type \"{}\" "
+ "in content section \"{}\".",
type.getName(),
section.getLabel());
throw new RuntimeException(ex);
}
item.setDisplayName(name);
item.getName().addValue(locale,
name);
item.setVersion(ContentItemVersion.DRAFT);
item.setContentType(contentType.get());
if (workflowTemplate != null) {
final Workflow workflow = workflowManager
.createWorkflow(workflowTemplate, item);
item.setWorkflow(workflow);
}
if (initializer != null) {
initializer.initializeValues(item);
}
contentItemRepo.save(item);
categoryManager.addObjectToCategory(
item,
folder,
CATEGORIZATION_TYPE_FOLDER);
contentItemRepo.save(item);
if (item.getWorkflow() != null) {
workflowManager.start(item.getWorkflow());
}
permissionManager.copyPermissions(folder, item, true);
return item;
}
/**
* Moves a content item to another folder. If moving an item to another
* content section the caller should first check if the type of the item is
* registered in the target version using
* {@link ContentSectionManager#hasContentType(java.lang.Class, org.librecms.contentsection.ContentSection)}.
* If this method is called with for item and a folder in another content
* section and the type of the item is not registered for target section
* this method will throw an {@link IllegalArgumentException}. This method
* only moves the draft version of the item. The live version is moved after
* a the item is republished.
*
* @param item The item to move.
* @param targetFolder The folder to which the item is moved.
*/
@AuthorizationRequired
@Transactional(Transactional.TxType.REQUIRED)
public void move(
@RequiresPrivilege(ItemPrivileges.EDIT)
final ContentItem item,
@RequiresPrivilege(ItemPrivileges.CREATE_NEW)
final Folder targetFolder) {
if (item == null) {
throw new IllegalArgumentException("The item to move can't be null.");
}
if (targetFolder == null) {
throw new IllegalArgumentException(
"The target folder can't be null.");
}
final ContentItem draftItem = getDraftVersion(item, item.getClass());
final Optional currentFolder = getItemFolder(item);
if (!sectionManager.hasContentType(draftItem.getClass(),
targetFolder.getSection())) {
throw new IllegalArgumentException(String.format(
"Can't move item %d:\"%s\" to folder \"%s\"."
+ "The target folder %d:\"%s\" belongs to content section "
+ "%d:\"%s\". The content type \"%s\" has not registered"
+ "for this section.",
draftItem.getObjectId(),
draftItem.getDisplayName(),
folderManager.getFolderPath(targetFolder, true),
targetFolder.getObjectId(),
targetFolder.getDisplayName(),
targetFolder.getSection().getObjectId(),
targetFolder.getSection().getDisplayName(),
draftItem.getClass().getName()));
}
if (currentFolder.isPresent()) {
try {
categoryManager.removeObjectFromCategory(draftItem,
currentFolder.get());
} catch (ObjectNotAssignedToCategoryException ex) {
throw new RuntimeException(ex);
}
}
categoryManager.addObjectToCategory(
draftItem,
targetFolder,
CATEGORIZATION_TYPE_FOLDER);
}
/**
* Creates an copy of the draft version of the item in the provided
* {@code targetFolder}. If the target folder belongs to another content
* section the caller should first check if the type of the item is
* registered for the target section by using
* {@link ContentSectionManager#hasContentType(java.lang.Class, org.librecms.contentsection.ContentSection)}.
* If this method is called for an item and a folder in another content
* section and the type of the item is not registered for the target section
* an {@link IllegalArgumentException} is thrown.
*
* @param item The item to copy.
* @param targetFolder The folder in which the copy is created. If the
* target folder is the same folder as the folder of the
* original item an index is appended to the name of the
* item.
*
* @return The copy of the item
*/
@Transactional(Transactional.TxType.REQUIRED)
@AuthorizationRequired
@SuppressWarnings("unchecked")
public ContentItem copy(
final ContentItem item,
@RequiresPrivilege(ItemPrivileges.CREATE_NEW)
final Folder targetFolder) {
if (item == null) {
throw new IllegalArgumentException("The item to copy can't be null.");
}
if (targetFolder == null) {
throw new IllegalArgumentException(
"The target folder to which the item is copied can't be null");
}
final Optional contentType = typeRepo
.findByContentSectionAndClass(
targetFolder.getSection(), item.getClass());
if (!contentType.isPresent()) {
throw new IllegalArgumentException(String.format(
"ContentSection \"%s\" has no content type for \"%s\".",
item.getContentType().getContentSection(),
item.getClass().getName()));
}
final ContentItem draftItem = getDraftVersion(item, item.getClass());
if (!sectionManager.hasContentType(draftItem.getClass(),
targetFolder.getSection())) {
throw new IllegalArgumentException(String.format(
"Can't copy item %d:\"%s\" to folder \"%s\"."
+ "The target folder %d:\"%s\" belongs to content section "
+ "%d:\"%s\". The content type \"%s\" has not registered"
+ "for this section.",
draftItem.getObjectId(),
draftItem.getDisplayName(),
folderManager.getFolderPath(targetFolder, true),
targetFolder.getObjectId(),
targetFolder.getDisplayName(),
targetFolder.getSection().getObjectId(),
targetFolder.getSection().getDisplayName(),
draftItem.getClass().getName()));
}
final ContentItem copy;
try {
copy = draftItem.getClass().newInstance();
} catch (InstantiationException | IllegalAccessException ex) {
throw new RuntimeException(ex);
}
copy.setContentType(contentType.get());
if (draftItem.getWorkflow() != null) {
final Workflow template = draftItem.getWorkflow()
.getTemplate();
final Workflow copyWorkflow = workflowManager.createWorkflow(
template, item);
copy.setWorkflow(copyWorkflow);
}
for (AttachmentList attachmentList : item.getAttachments()) {
copyAttachmentList(attachmentList, copy);
}
final BeanInfo beanInfo;
try {
beanInfo = Introspector.getBeanInfo(item.getClass());
} catch (IntrospectionException ex) {
throw new RuntimeException(ex);
}
for (final PropertyDescriptor propertyDescriptor : beanInfo
.getPropertyDescriptors()) {
if (propertyIsExcluded(propertyDescriptor.getName())) {
continue;
}
final Class> propType = propertyDescriptor.getPropertyType();
final Method readMethod = propertyDescriptor.getReadMethod();
final Method writeMethod = propertyDescriptor.getWriteMethod();
if (writeMethod == null) {
continue;
}
if (LocalizedString.class.equals(propType)) {
final LocalizedString source;
final LocalizedString target;
try {
source = (LocalizedString) readMethod.invoke(draftItem);
target = (LocalizedString) readMethod.invoke(copy);
} catch (IllegalAccessException
| IllegalArgumentException
| InvocationTargetException ex) {
throw new RuntimeException(ex);
}
copyLocalizedString(source, target);
} else if (propType != null
&& propType.isAssignableFrom(ContentItem.class)) {
final ContentItem linkedItem;
try {
linkedItem = (ContentItem) readMethod.invoke(draftItem);
} catch (IllegalAccessException
| IllegalArgumentException
| InvocationTargetException ex) {
throw new RuntimeException(ex);
}
final ContentItem linkedDraftItem = getDraftVersion(
linkedItem, linkedItem.getClass());
try {
writeMethod.invoke(copy, linkedDraftItem);
} catch (IllegalAccessException
| IllegalArgumentException
| InvocationTargetException ex) {
throw new RuntimeException(ex);
}
} else if (propType != null
&& propType.isAssignableFrom(List.class)) {
final List