From 94fc4dcded984d3e876e9ae11bec386309c7144d Mon Sep 17 00:00:00 2001 From: jensp Date: Tue, 30 Aug 2016 12:55:35 +0000 Subject: [PATCH] CCM NG: - Added some more JavaDoc - Replaced return values in CcmObjectRepository with Optional for methods which not return a value git-svn-id: https://svn.libreccm.org/ccm/ccm_ng@4234 8810af33-2d31-482b-a856-94f89814c4df --- .../contentsection/ContentItemManager.java | 209 +++++++++--------- .../contentsection/ContentItemRepository.java | 65 ++++-- .../roles/RolePermissionsForm.java | 92 ++++---- .../libreccm/core/CcmObjectRepository.java | 28 ++- 4 files changed, 218 insertions(+), 176 deletions(-) diff --git a/ccm-cms/src/main/java/org/librecms/contentsection/ContentItemManager.java b/ccm-cms/src/main/java/org/librecms/contentsection/ContentItemManager.java index c942ac4a8..6de79ff27 100644 --- a/ccm-cms/src/main/java/org/librecms/contentsection/ContentItemManager.java +++ b/ccm-cms/src/main/java/org/librecms/contentsection/ContentItemManager.java @@ -63,6 +63,7 @@ import javax.persistence.TypedQuery; import javax.transaction.Transactional; /** + * Manager class providing several methods to manipulate {@link ContentItem}s. * * @author Jens Pelzetter */ @@ -70,7 +71,7 @@ import javax.transaction.Transactional; public class ContentItemManager { private static final Logger LOGGER = LogManager.getLogger( - ContentItemManager.class); + ContentItemManager.class); @Inject private EntityManager entityManager; @@ -104,29 +105,29 @@ public class ContentItemManager { * {@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 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 folder The folder in which in the item is stored. + * @param type The type of the new content item. * * @return The new content item. */ @Transactional(Transactional.TxType.REQUIRED) public T createContentItem( - final String name, - final ContentSection section, - final Category folder, - final Class type) { + final String name, + final ContentSection section, + final Category folder, + final Class type) { final Optional contentType = typeRepo - .findByContentSectionAndClass(section, type); + .findByContentSectionAndClass(section, type); if (!contentType.isPresent()) { throw new IllegalArgumentException(String.format( - "ContentSection \"%s\" has no content type for \"%s\".", - section.getLabel(), - type.getName())); + "ContentSection \"%s\" has no content type for \"%s\".", + section.getLabel(), + type.getName())); } return createContentItem(name, @@ -149,54 +150,53 @@ public class ContentItemManager { * {@link WorkflowTemplate} 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 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 * @param lifecycleDefinition - * @param type The type of the new content item. + * @param type The type of the new content item. * * @return The new content item. */ @Transactional(Transactional.TxType.REQUIRED) public T createContentItem( - final String name, - final ContentSection section, - final Category folder, - final WorkflowTemplate workflowTemplate, - final LifecycleDefinition lifecycleDefinition, - final Class type) { + final String name, + final ContentSection section, + final Category folder, + final WorkflowTemplate workflowTemplate, + final LifecycleDefinition lifecycleDefinition, + final Class type) { final Optional contentType = typeRepo - .findByContentSectionAndClass(section, type); + .findByContentSectionAndClass(section, type); if (!contentType.isPresent()) { throw new IllegalArgumentException(String.format( - "ContentSection \"%s\" has no content type for \"%s\".", - section.getLabel(), - type.getName())); + "ContentSection \"%s\" has no content type for \"%s\".", + section.getLabel(), + type.getName())); } final Lifecycle lifecycle = lifecycleManager.createLifecycle( - lifecycleDefinition); + lifecycleDefinition); final Workflow workflow = workflowManager.createWorkflow( - workflowTemplate); + workflowTemplate); final T item; try { item = type.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { LOGGER.error("Failed to create new content item of type \"{}\" " - + "in content section \"{}\".", + + "in content section \"{}\".", type.getName(), section.getLabel()); throw new RuntimeException(ex); } final KernelConfig kernelConfig = confManager.findConfiguration( - KernelConfig.class); + KernelConfig.class); item.setDisplayName(name); item.getName().addValue(new Locale(kernelConfig.getDefaultLanguage()), @@ -216,7 +216,7 @@ public class ContentItemManager { * 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 item The item to move. * @param targetFolder The folder to which the item is moved. */ @Transactional(Transactional.TxType.REQUIRED) @@ -241,23 +241,23 @@ public class ContentItemManager { * Creates an copy of the draft version of the item in the provided * {@code targetFolder}. * - * @param item The item to copy. + * @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. + * target folder is the same folder as the folder of the original item an + * index is appended to the name of the item. */ @SuppressWarnings("unchecked") public void copy(final ContentItem item, final Category targetFolder) { final Optional contentType = typeRepo - .findByContentSectionAndClass( - item.getContentType().getContentSection(), item.getClass()); + .findByContentSectionAndClass( + item.getContentType().getContentSection(), item. + getClass()); if (!contentType.isPresent()) { throw new IllegalArgumentException(String.format( - "ContentSection \"%s\" has no content type for \"%s\".", - item.getContentType().getContentSection(), - item.getClass().getName())); + "ContentSection \"%s\" has no content type for \"%s\".", + item.getContentType().getContentSection(), + item.getClass().getName())); } final ContentItem draftItem = getDraftVersion(item, item.getClass()); @@ -272,30 +272,30 @@ public class ContentItemManager { copy.setContentType(contentType.get()); final Lifecycle lifecycle = lifecycleManager.createLifecycle( - contentType.get().getDefaultLifecycle()); + contentType.get().getDefaultLifecycle()); final Workflow workflow = workflowManager.createWorkflow(contentType - .get().getDefaultWorkflow()); + .get().getDefaultWorkflow()); copy.setLifecycle(lifecycle); copy.setWorkflow(workflow); draftItem.getCategories().forEach(categorization -> categoryManager - .addObjectToCategory(copy, categorization.getCategory())); + .addObjectToCategory(copy, categorization.getCategory())); final Optional itemFolder = getItemFolder(draftItem); if (itemFolder.isPresent()) { try { categoryManager.removeObjectFromCategory( - copy, getItemFolder(draftItem).get()); + copy, getItemFolder(draftItem).get()); } catch (ObjectNotAssignedToCategoryException ex) { throw new RuntimeException(ex); } } categoryManager.addObjectToCategory( - copy, - targetFolder, - CmsConstants.CATEGORIZATION_TYPE_FOLDER); + copy, + targetFolder, + CmsConstants.CATEGORIZATION_TYPE_FOLDER); // !!!!!!!!!!!!!!!!!!!!! // ToDo copy Attachments @@ -310,7 +310,7 @@ public class ContentItemManager { } for (final PropertyDescriptor propertyDescriptor : beanInfo - .getPropertyDescriptors()) { + .getPropertyDescriptors()) { if (propertyIsExcluded(propertyDescriptor.getName())) { continue; } @@ -332,9 +332,10 @@ public class ContentItemManager { } source.getAvailableLocales().forEach( - locale -> target.addValue(locale, source.getValue(locale))); + locale -> target.addValue(locale, source. + getValue(locale))); } else if (propType != null - && propType.isAssignableFrom(ContentItem.class)) { + && propType.isAssignableFrom(ContentItem.class)) { final ContentItem linkedItem; try { @@ -346,7 +347,7 @@ public class ContentItemManager { } final ContentItem linkedDraftItem = getDraftVersion( - linkedItem, linkedItem.getClass()); + linkedItem, linkedItem.getClass()); try { writeMethod.invoke(copy, linkedDraftItem); @@ -356,7 +357,7 @@ public class ContentItemManager { throw new RuntimeException(ex); } } else if (propType != null - && propType.isAssignableFrom(List.class)) { + && propType.isAssignableFrom(List.class)) { final List source; final List target; try { @@ -370,7 +371,7 @@ public class ContentItemManager { target.addAll(source); } else if (propType != null - && propType.isAssignableFrom(Map.class)) { + && propType.isAssignableFrom(Map.class)) { final Map source; final Map target; @@ -385,7 +386,7 @@ public class ContentItemManager { source.forEach((key, value) -> target.put(key, value)); } else if (propType != null - && propType.isAssignableFrom(Set.class)) { + && propType.isAssignableFrom(Set.class)) { final Set source; final Set target; @@ -459,7 +460,7 @@ public class ContentItemManager { liveItem.setWorkflow(draftItem.getWorkflow()); draftItem.getCategories().forEach(categorization -> categoryManager - .addObjectToCategory(item, categorization.getCategory())); + .addObjectToCategory(item, categorization.getCategory())); liveItem.setUuid(draftItem.getUuid()); @@ -476,7 +477,7 @@ public class ContentItemManager { } for (final PropertyDescriptor propertyDescriptor : beanInfo - .getPropertyDescriptors()) { + .getPropertyDescriptors()) { if (propertyIsExcluded(propertyDescriptor.getName())) { continue; @@ -499,9 +500,10 @@ public class ContentItemManager { } source.getAvailableLocales().forEach( - locale -> target.addValue(locale, source.getValue(locale))); + locale -> target.addValue(locale, source. + getValue(locale))); } else if (propType != null - && propType.isAssignableFrom(ContentItem.class)) { + && propType.isAssignableFrom(ContentItem.class)) { final ContentItem linkedItem; try { linkedItem = (ContentItem) readMethod.invoke(draftItem); @@ -512,13 +514,13 @@ public class ContentItemManager { } final ContentItem linkedDraftItem = getDraftVersion( - linkedItem, linkedItem.getClass()); + linkedItem, linkedItem.getClass()); if (isLive(linkedDraftItem)) { try { final Optional linkedLiveItem - = getLiveVersion( - linkedDraftItem, ContentItem.class); + = getLiveVersion( + linkedDraftItem, ContentItem.class); writeMethod.invoke(liveItem, linkedLiveItem); } catch (IllegalAccessException | IllegalArgumentException | @@ -527,7 +529,7 @@ public class ContentItemManager { } } } else if (propType != null - && propType.isAssignableFrom(List.class)) { + && propType.isAssignableFrom(List.class)) { final List source; final List target; try { @@ -541,7 +543,7 @@ public class ContentItemManager { target.addAll(source); } else if (propType != null - && propType.isAssignableFrom(Map.class)) { + && propType.isAssignableFrom(Map.class)) { final Map source; final Map target; @@ -556,7 +558,7 @@ public class ContentItemManager { source.forEach((key, value) -> target.put(key, value)); } else if (propType != null - && propType.isAssignableFrom(Set.class)) { + && propType.isAssignableFrom(Set.class)) { final Set source; final Set target; @@ -587,7 +589,8 @@ public class ContentItemManager { } /** - * Unpublishes a content item by deleting its live version if any. + * Unpublishes a content item by deleting its live version if there is a + * live version. * * @param item */ @@ -595,7 +598,7 @@ public class ContentItemManager { public void unpublish(final ContentItem item ) { final Optional liveItem = getLiveVersion( - item, ContentItem.class); + item, ContentItem.class); if (liveItem.isPresent()) { entityManager.remove(liveItem); @@ -609,11 +612,11 @@ public class ContentItemManager { * @param item The item * * @return {@code true} if the content item has a live version, - * {@code false} if not. + * {@code false} if not. */ public boolean isLive(final ContentItem item) { final TypedQuery query = entityManager.createNamedQuery( - "ContentItem.hasLiveVersion", Boolean.class); + "ContentItem.hasLiveVersion", Boolean.class); query.setParameter("uuid", item.getUuid()); return query.getSingleResult(); @@ -622,24 +625,24 @@ public class ContentItemManager { /** * Retrieves the live version of the provided content item if any. * - * @param Type of the content item. + * @param Type of the content item. * @param item The item of which the live version should be retrieved. * @param type Type of the content item. * * @return The live version of an item. If the item provided is already the - * live version the provided item is returned, otherwise the live - * version is returned. If there is no live version an empty - * {@link Optional} is returned. + * live version the provided item is returned, otherwise the live version is + * returned. If there is no live version an empty {@link Optional} is + * returned. */ public Optional getLiveVersion( - final ContentItem item, - final Class type) { + final ContentItem item, + final Class type) { if (isLive(item)) { final TypedQuery query = entityManager.createNamedQuery( - "ContentItem.findLiveVersion", type); + "ContentItem.findLiveVersion", type); query.setParameter("uuid", item.getUuid()); - + return Optional.of(query.getSingleResult()); } else { return Optional.empty(); @@ -649,38 +652,38 @@ public class ContentItemManager { /** * Retrieves the pending versions of an item if there are any. * - * @param Type of the content item to retrieve. + * @param Type of the content item to retrieve. * @param item The item of which the pending versions are retrieved. * @param type Type of the content item to retrieve. * * @return A list of the pending versions of the item. */ public List getPendingVersions( - final ContentItem item, - final Class type) { + final ContentItem item, + final Class type) { throw new UnsupportedOperationException(); } /** * Retrieves the draft version * - * @param Type of the item. + * @param Type of the item. * @param item The item of which the draft version is retrieved. * @param type Type of the item. * * @return The draft version of the provided content item. If the provided - * item is the draft version the provided item is simply returned. - * Otherwise the draft version is retrieved from the database and is - * returned. Each content item has a draft version (otherwise - * something is seriously wrong with the database) this method will + * item is the draft version the provided item is simply returned. Otherwise + * the draft version is retrieved from the database and is returned. Each + * content item has a draft version (otherwise something is seriously wrong + * with the database) this method will * never return {@code null}. */ public T getDraftVersion(final ContentItem item, final Class type) { final TypedQuery query = entityManager.createNamedQuery( - "ContentItem.findDraftVersion", type); + "ContentItem.findDraftVersion", type); query.setParameter("uuid", item.getUuid()); - + return query.getSingleResult(); } @@ -717,9 +720,9 @@ public class ContentItemManager { * {@code info}, the path including the content section would be * {@code info:/research/computer-science/artificial-intelligence/neural-nets}. * - * @param item The item whose path is generated. + * @param item The item whose path is generated. * @param withContentSection Wether to include the content section into the - * path. + * path. * * @return The path of the content item * @@ -728,9 +731,9 @@ public class ContentItemManager { public String getItemPath(final ContentItem item, final boolean withContentSection) { final List result = item.getCategories().stream(). - filter(categorization -> CmsConstants.CATEGORIZATION_TYPE_FOLDER. - equals(categorization.getType())) - .collect(Collectors.toList()); + filter(categorization -> CmsConstants.CATEGORIZATION_TYPE_FOLDER. + equals(categorization.getType())) + .collect(Collectors.toList()); if (result.isEmpty()) { return item.getDisplayName(); @@ -751,9 +754,9 @@ public class ContentItemManager { if (withContentSection) { final String sectionName = item.getContentType(). - getContentSection().getDisplayName(); + getContentSection().getDisplayName(); return String.format( - "%s/%s", sectionName, path); + "%s/%s", sectionName, path); } else { return String.format("/%s", path); } @@ -769,9 +772,9 @@ public class ContentItemManager { */ public List getItemFolders(final ContentItem item) { final List result = item.getCategories().stream(). - filter(categorization -> CmsConstants.CATEGORIZATION_TYPE_FOLDER. - equals(categorization.getType())) - .collect(Collectors.toList()); + filter(categorization -> CmsConstants.CATEGORIZATION_TYPE_FOLDER. + equals(categorization.getType())) + .collect(Collectors.toList()); final List folders = new ArrayList<>(); if (!result.isEmpty()) { @@ -797,13 +800,13 @@ public class ContentItemManager { * @param item The item * * @return An {@link Optional} containing the folder of the item if the item - * is part of a folder. + * is part of a folder. */ public Optional getItemFolder(final ContentItem item) { final List result = item.getCategories().stream(). - filter(categorization -> CmsConstants.CATEGORIZATION_TYPE_FOLDER. - equals(categorization.getType())) - .collect(Collectors.toList()); + filter(categorization -> CmsConstants.CATEGORIZATION_TYPE_FOLDER. + equals(categorization.getType())) + .collect(Collectors.toList()); if (result.size() > 0) { return Optional.of(result.get(0).getCategory()); diff --git a/ccm-cms/src/main/java/org/librecms/contentsection/ContentItemRepository.java b/ccm-cms/src/main/java/org/librecms/contentsection/ContentItemRepository.java index 418e3447a..da6ce27cf 100644 --- a/ccm-cms/src/main/java/org/librecms/contentsection/ContentItemRepository.java +++ b/ccm-cms/src/main/java/org/librecms/contentsection/ContentItemRepository.java @@ -23,15 +23,12 @@ import org.libreccm.categorization.Category; import org.libreccm.core.CcmObject; import org.libreccm.core.CcmObjectRepository; -import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.TypedQuery; -import jdk.nashorn.internal.objects.NativeArray; /** * Repository for content items. @@ -69,9 +66,9 @@ public class ContentItemRepository * nothing if there is such content item. */ public Optional findById(final long itemId) { - final CcmObject result = ccmObjectRepo.findObjectById(itemId); - if (result instanceof ContentItem) { - return Optional.of((ContentItem) result); + final Optional result = ccmObjectRepo.findObjectById(itemId); + if (result.isPresent() && result.get() instanceof ContentItem) { + return Optional.of((ContentItem) result.get()); } else { return Optional.empty(); } @@ -107,12 +104,12 @@ public class ContentItemRepository * @return The content item identified by the provided {@code uuid} or * nothing if there is such content item. */ - public ContentItem findByUuid(final String uuid) { - final CcmObject result = ccmObjectRepo.findObjectByUuid(uuid); - if (result instanceof ContentItem) { - return (ContentItem) result; + public Optional findByUuid(final String uuid) { + final Optional result = ccmObjectRepo.findObjectByUuid(uuid); + if (result.isPresent() && result.get() instanceof ContentItem) { + return Optional.of((ContentItem) result.get()); } else { - return null; + return Optional.empty(); } } @@ -131,10 +128,11 @@ public class ContentItemRepository @SuppressWarnings("unchecked") public Optional findByUuid(final String uuid, final Class type) { - final CcmObject result = ccmObjectRepo.findObjectByUuid(uuid); + final Optional result = ccmObjectRepo.findObjectByUuid(uuid); - if (result.getClass().isAssignableFrom(type)) { - return Optional.of((T) result); + if (result.isPresent() + && result.get().getClass().isAssignableFrom(type)) { + return Optional.of((T) result.get()); } else { return Optional.empty(); } @@ -166,21 +164,34 @@ public class ContentItemRepository */ public List findByFolder(final Category folder) { final TypedQuery query = getEntityManager() - .createNamedQuery("ContentItem.findByFolder", + .createNamedQuery("ContentItem.findByFolder", ContentItem.class); query.setParameter("folder", folder); return query.getResultList(); } - + + /** + * Counts the items in a folder/category. + * + * @param folder The folder/category + * @return The number of content items in the category/folder. + */ public long countItemsInFolder(final Category folder) { final TypedQuery query = getEntityManager() - .createNamedQuery("ContentItem.countItemsInFolder", Long.class); + .createNamedQuery("ContentItem.countItemsInFolder", Long.class); query.setParameter("folder", folder); - + return query.getSingleResult(); } + /** + * Counts the number of items with a specific name in a folder/category. + * + * @param folder + * @param name + * @return + */ public long countByNameInFolder(final Category folder, final String name) { final TypedQuery query = getEntityManager().createNamedQuery( "ContentItem.countByNameInFolder", Long.class); @@ -190,6 +201,15 @@ public class ContentItemRepository return query.getSingleResult(); } + /** + * Retrieves all items in a specific folder where + * {@link CcmObject#displayName} of the item starts with the provided + * pattern. + * + * @param folder The folder/category whose items are filtered. + * @param name The name pattern to use. + * @return A list with all items in the folder matching the provided filter. + */ public List filterByFolderAndName(final Category folder, final String name) { final TypedQuery query = getEntityManager() @@ -201,6 +221,15 @@ public class ContentItemRepository return query.getResultList(); } + /** + * Counts a items in a specfic folder whose {@link CcmObject#displayName} + * starts with the provided pattern. + * + * @param folder The folder/category to use. + * @param name The name pattern to use. + * @return The number of items in the folder/category which match the + * provided pattern. + */ public long countFilterByFolderAndName(final Category folder, final String name) { final TypedQuery query = getEntityManager() diff --git a/ccm-core/src/main/java/com/arsdigita/ui/admin/usersgroupsroles/roles/RolePermissionsForm.java b/ccm-core/src/main/java/com/arsdigita/ui/admin/usersgroupsroles/roles/RolePermissionsForm.java index 84a714c93..3016fe5a5 100644 --- a/ccm-core/src/main/java/com/arsdigita/ui/admin/usersgroupsroles/roles/RolePermissionsForm.java +++ b/ccm-core/src/main/java/com/arsdigita/ui/admin/usersgroupsroles/roles/RolePermissionsForm.java @@ -27,6 +27,7 @@ import com.arsdigita.bebop.ParameterSingleSelectionModel; import com.arsdigita.bebop.SaveCancelSection; import com.arsdigita.bebop.form.TextField; import com.arsdigita.globalization.GlobalizedMessage; +import java.util.Optional; import org.libreccm.cdi.utils.CdiUtil; import org.libreccm.core.CcmObject; @@ -55,14 +56,14 @@ class RolePermissionsForm extends Form { private final SaveCancelSection saveCancelSection; public RolePermissionsForm( - final RoleAdmin roleAdmin, - final ParameterSingleSelectionModel selectedRoleId) { + final RoleAdmin roleAdmin, + final ParameterSingleSelectionModel selectedRoleId) { super("rolePermissionsForm"); final ActionLink backToRole = new ActionLink(new GlobalizedMessage( - "ui.admin.group_details.add_permission.back", - ADMIN_BUNDLE)); + "ui.admin.group_details.add_permission.back", + ADMIN_BUNDLE)); backToRole.addActionListener(e -> { roleAdmin.showRolePermissionsPanel(e.getPageState()); }); @@ -75,112 +76,113 @@ class RolePermissionsForm extends Form { final Label target = (Label) e.getTarget(); final RoleRepository roleRepository = CdiUtil.createCdiUtil() - .findBean(RoleRepository.class); + .findBean(RoleRepository.class); final Role role = roleRepository.findById(Long.parseLong( - selectedRoleId.getSelectedKey(state))); + selectedRoleId.getSelectedKey(state))); target.setLabel(new GlobalizedMessage( - "ui.admin.role_details.add_permission.heading", - ADMIN_BUNDLE, - new String[]{role.getName()})); + "ui.admin.role_details.add_permission.heading", + ADMIN_BUNDLE, + new String[]{role.getName()})); }); add(heading); objectId = new TextField(OBJECT_ID); objectId.setLabel(new GlobalizedMessage( - "ui.admin.role_details.add_permission.object_id.label", - ADMIN_BUNDLE)); + "ui.admin.role_details.add_permission.object_id.label", + ADMIN_BUNDLE)); objectId.setHint(new GlobalizedMessage( - "ui.admin.role_details.add_permission.object_id.hint", - ADMIN_BUNDLE + "ui.admin.role_details.add_permission.object_id.hint", + ADMIN_BUNDLE )); add(objectId); privilege = new TextField(PRIVILEGE); privilege.setLabel(new GlobalizedMessage( - "ui.admin.role_details.add_permission.privilege.label", - ADMIN_BUNDLE)); + "ui.admin.role_details.add_permission.privilege.label", + ADMIN_BUNDLE)); privilege.setHint(new GlobalizedMessage( - "ui.admin.role_details.add_permission.privilege.hint", - ADMIN_BUNDLE + "ui.admin.role_details.add_permission.privilege.hint", + ADMIN_BUNDLE )); add(privilege); saveCancelSection = new SaveCancelSection(); add(saveCancelSection); - addValidationListener(e -> { - final PageState state = e.getPageState(); + addValidationListener(event -> { + final PageState state = event.getPageState(); if (saveCancelSection.getSaveButton().isSelected(state)) { - final FormData data = e.getFormData(); + final FormData data = event.getFormData(); final String privilegeData = data.getString(PRIVILEGE); if (privilegeData == null || privilegeData.isEmpty()) { data.addError(PRIVILEGE, new GlobalizedMessage( "ui.admin.role_details.add_permission." - + "privilege.error.notempty", + + "privilege.error.notempty", ADMIN_BUNDLE)); } final String objectIdData = data.getString(OBJECT_ID); if (objectIdData != null && !objectIdData.isEmpty()) { final CcmObjectRepository objectRepository = CdiUtil - .createCdiUtil().findBean(CcmObjectRepository.class); + .createCdiUtil().findBean(CcmObjectRepository.class); try { Long.parseLong(objectIdData); } catch (NumberFormatException ex) { data.addError( - OBJECT_ID, - new GlobalizedMessage( - "ui.admin.role_details.add_permission.object_id" - + ".error.nan", - ADMIN_BUNDLE)); + OBJECT_ID, + new GlobalizedMessage( + "ui.admin.role_details.add_permission.object_id" + + ".error.nan", + ADMIN_BUNDLE)); return; } - final CcmObject object = objectRepository.findObjectById( - Long.parseLong(objectIdData)); - if (object == null) { + final Optional object = objectRepository. + findObjectById( + Long.parseLong(objectIdData)); + if (!object.isPresent()) { data.addError( - OBJECT_ID, - new GlobalizedMessage( - "ui.admin.role_details.add_permission.object_id" - + ".error.no_object", - ADMIN_BUNDLE)); + OBJECT_ID, + new GlobalizedMessage( + "ui.admin.role_details.add_permission.object_id" + + ".error.no_object", + ADMIN_BUNDLE)); } } } }); - addProcessListener(e -> { - final PageState state = e.getPageState(); + addProcessListener(event -> { + final PageState state = event.getPageState(); if (saveCancelSection.getSaveButton().isSelected(state)) { - final FormData data = e.getFormData(); + final FormData data = event.getFormData(); final String privilegeData = data.getString(PRIVILEGE); final String objectIdData = data.getString(OBJECT_ID); final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); final RoleRepository roleRepository = cdiUtil.findBean( - RoleRepository.class); + RoleRepository.class); final Role role = roleRepository.findById(Long.parseLong( - selectedRoleId.getSelectedKey(state))); + selectedRoleId.getSelectedKey(state))); final PermissionManager permissionManager = cdiUtil.findBean( - PermissionManager.class); + PermissionManager.class); if (objectIdData == null || objectIdData.isEmpty()) { permissionManager.grantPrivilege(privilegeData, role); } else { final CcmObjectRepository objectRepository = cdiUtil - .findBean(CcmObjectRepository.class); - final CcmObject object = objectRepository.findObjectById( - Long.parseLong(objectIdData)); + .findBean(CcmObjectRepository.class); + final Optional object = objectRepository + .findObjectById(Long.parseLong(objectIdData)); permissionManager.grantPrivilege(privilegeData, role, - object); + object.get()); } } diff --git a/ccm-core/src/main/java/org/libreccm/core/CcmObjectRepository.java b/ccm-core/src/main/java/org/libreccm/core/CcmObjectRepository.java index 92777bcb9..7a5e958e7 100644 --- a/ccm-core/src/main/java/org/libreccm/core/CcmObjectRepository.java +++ b/ccm-core/src/main/java/org/libreccm/core/CcmObjectRepository.java @@ -18,6 +18,8 @@ */ package org.libreccm.core; +import java.util.Optional; + import static org.libreccm.core.CoreConstants.*; import java.util.UUID; @@ -47,7 +49,7 @@ public class CcmObjectRepository extends AbstractEntityRepository findObjectById(final long objectId) { final TypedQuery query = getEntityManager().createNamedQuery( - "CcmObject.findById", CcmObject.class); + "CcmObject.findById", CcmObject.class); query.setParameter("id", objectId); try { - return query.getSingleResult(); + return Optional.of(query.getSingleResult()); } catch (NoResultException ex) { - return null; + return Optional.empty(); } } - - public CcmObject findObjectByUuid(final String uuid) { + + public Optional findObjectByUuid(final String uuid) { final TypedQuery query = getEntityManager().createNamedQuery( - "CcmObject.findByUuid", CcmObject.class); + "CcmObject.findByUuid", CcmObject.class); query.setParameter("uuid", uuid); try { - return query.getSingleResult(); + return Optional.of(query.getSingleResult()); } catch (NoResultException ex) { - return null; + return Optional.empty(); } }