diff --git a/ccm-bundle-devel-wildfly/src/main/resources/log4j2.xml b/ccm-bundle-devel-wildfly/src/main/resources/log4j2.xml index ff0533652..427cbcdd0 100644 --- a/ccm-bundle-devel-wildfly/src/main/resources/log4j2.xml +++ b/ccm-bundle-devel-wildfly/src/main/resources/log4j2.xml @@ -80,10 +80,7 @@ - - - ${project.parent.version} - - net.sf.saxon - Saxon-HE - - org.libreccm diff --git a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemController.java b/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemController.java deleted file mode 100644 index 6d4ed905e..000000000 --- a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemController.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.contenttypes.ui; - -import org.librecms.assets.Person; -import org.librecms.contentsection.AssetRepository; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.profilesite.ProfileSiteItem; - -import java.util.Locale; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class ProfileSiteItemController { - - public static final String OWNER = "owner"; - - public static final String POSITION = "position"; - - public static final String INTERSETS = "interests"; - - public static final String MISC = "misc"; - - @Inject - private AssetRepository assetRepository; - - @Inject - private ContentItemRepository itemRepository; - - @Transactional(Transactional.TxType.REQUIRED) - public void setOwner(final long profileSiteItemId, final long ownerId) { - final ProfileSiteItem profileSiteItem = itemRepository - .findById(profileSiteItemId, ProfileSiteItem.class) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No ProfileSiteItem with ID %d found.", - profileSiteItemId - ) - ) - ); - - final Person owner = assetRepository - .findById(ownerId, Person.class) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No Person with ID %d found.", ownerId - ) - ) - ); - - profileSiteItem.setOwner(owner); - itemRepository.save(profileSiteItem); - } - - public void setPosition( - final long profileSiteItemId, final String position, final Locale locale - ) { - final ProfileSiteItem profileSiteItem = itemRepository - .findById(profileSiteItemId, ProfileSiteItem.class) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No ProfileSiteItem with ID %d found.", - profileSiteItemId - ) - ) - ); - profileSiteItem.getPosition().putValue(locale, position); - } - - public void setInterests( - final long profileSiteItemId, - final String interests, - final Locale locale - ) { - final ProfileSiteItem profileSiteItem = itemRepository - .findById(profileSiteItemId, ProfileSiteItem.class) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No ProfileSiteItem with ID %d found.", - profileSiteItemId - ) - ) - ); - profileSiteItem.getInterests().putValue(locale, interests); - } - - public void setMisc( - final long profileSiteItemId, final String misc, final Locale locale - ) { - final ProfileSiteItem profileSiteItem = itemRepository - .findById(profileSiteItemId, ProfileSiteItem.class) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No ProfileSiteItem with ID %d found.", - profileSiteItemId - ) - ) - ); - profileSiteItem.getMisc().putValue(locale, misc); - } - -} diff --git a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemCreate.java b/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemCreate.java deleted file mode 100644 index 2f02dcccd..000000000 --- a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemCreate.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.contenttypes.ui; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.assets.AssetSearchWidget; -import com.arsdigita.cms.ui.authoring.CreationSelector; -import com.arsdigita.cms.ui.authoring.PageCreateForm; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.assets.Person; -import org.librecms.contentsection.ContentItemInitializer; -import org.librecms.profilesite.ProfileSiteConstants; -import org.librecms.profilesite.ProfileSiteItem; - -import java.util.Locale; - -/** - * - * @author Jens Pelzetter - */ -public class ProfileSiteItemCreate extends PageCreateForm { - - private final static String OWNER_SEARCH = "owner"; - - private AssetSearchWidget ownerSearch; - - public ProfileSiteItemCreate( - final ItemSelectionModel itemModel, - final CreationSelector creationSelector, - final StringParameter selectedLanguageParam - ) { - super(itemModel, creationSelector, selectedLanguageParam); - } - - @Override - public void addWidgets() { - ownerSearch = new AssetSearchWidget(OWNER_SEARCH, Person.class); - ownerSearch.setLabel( - new GlobalizedMessage( - "profile_site.owner.label", ProfileSiteConstants.BUNDLE - ) - ); - add(ownerSearch); - } - - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - super.validate(event); - final FormData formData = event.getFormData(); - - if (!formData.containsKey(OWNER_SEARCH) - || formData.get(OWNER_SEARCH) == null) { - formData.addError( - new GlobalizedMessage( - "profile_site.owner.not_selected", - ProfileSiteConstants.BUNDLE - ) - ); - } - } - - @Override - protected ContentItemInitializer getItemInitializer( - final FormData formData, final PageState state - ) { - return (item) -> item.setOwner((Person) formData.get(OWNER_SEARCH)); - } - - -} diff --git a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemInterestsForm.java b/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemInterestsForm.java deleted file mode 100644 index a0f7f25f7..000000000 --- a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemInterestsForm.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.contenttypes.ui; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.BasicItemForm; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.profilesite.ProfileSiteConstants; -import org.librecms.profilesite.ProfileSiteItem; - -import java.util.Locale; - -/** - * - * @author Jens Pelzetter - */ -public class ProfileSiteItemInterestsForm - extends BasicItemForm - implements FormProcessListener, FormInitListener { - - private final StringParameter selectedLangParam; - - public ProfileSiteItemInterestsForm( - final ItemSelectionModel itemModel, - final StringParameter selectedLangParam - ) { - super("ProfileSiteItemEditInterests", itemModel, selectedLangParam); - this.selectedLangParam = selectedLangParam; - } - - @Override - public void addWidgets() { - add( - new Label( - new GlobalizedMessage( - "profile_site_item.ui.interests", - ProfileSiteConstants.BUNDLE - ) - ) - ); - final ParameterModel interestsParam = new StringParameter( - ProfileSiteItemController.POSITION); - final TextArea interests = new TextArea(interestsParam); - interests.setCols(80); - interests.setRows(8); - add(interests); - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - final ProfileSiteItem profile - = (ProfileSiteItem) getItemSelectionModel() - .getSelectedItem(state); - - data.put(ProfileSiteItemController.POSITION, profile.getInterests()); - - setVisible(state, true); - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - final ProfileSiteItem profile - = (ProfileSiteItem) getItemSelectionModel() - .getSelectedItem(state); - - if ((profile != null) - && getSaveCancelSection().getSaveButton().isSelected(state)) { - - final ProfileSiteItemController controller = CdiUtil - .createCdiUtil() - .findBean(ProfileSiteItemController.class); - - final Locale selectedLocale = SelectedLanguageUtil.selectedLocale( - state, selectedLangParam - ); - - controller.setInterests( - profile.getObjectId(), - (String) data.get(ProfileSiteItemController.POSITION), - selectedLocale - ); - } - - init(event); - } - -} diff --git a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemInterestsStep.java b/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemInterestsStep.java deleted file mode 100644 index db9e51832..000000000 --- a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemInterestsStep.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.contenttypes.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.BasicItemForm; -import com.arsdigita.cms.ui.authoring.SimpleEditStep; -import com.arsdigita.cms.ui.workflow.WorkflowLockedComponentAccess; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.DomainObjectPropertySheet; - -import org.librecms.profilesite.ProfileSiteConstants; - -/** - * - * @author Jens Pelzetter - */ -public class ProfileSiteItemInterestsStep extends SimpleEditStep { - - private String EDIT_POSITION_SHEET_NAME = "editInterests"; - - public ProfileSiteItemInterestsStep( - final ItemSelectionModel itemModel, - final AuthoringKitWizard parent, - final StringParameter selectedLangParam - ) { - this(itemModel, parent, selectedLangParam, null); - } - - public ProfileSiteItemInterestsStep( - final ItemSelectionModel itemModel, - final AuthoringKitWizard parent, - final StringParameter selectedLangParam, - final String prefix - ) { - super(itemModel, parent, selectedLangParam, prefix); - - final BasicItemForm editInterestsForm = new ProfileSiteItemInterestsForm( - itemModel, selectedLangParam - ); - add( - EDIT_POSITION_SHEET_NAME, - new GlobalizedMessage( - "profile_site_site.ui.interests.edit", - ProfileSiteConstants.BUNDLE - ), - new WorkflowLockedComponentAccess(parent, itemModel), - editInterestsForm.getSaveCancelSection().getCancelButton() - ); - - setDisplayComponent(getProfileSiteItemInterestsSheet( - itemModel, selectedLangParam) - ); - } - - public static final Component getProfileSiteItemInterestsSheet( - final ItemSelectionModel itemModel, - final StringParameter selectedLangParam - ) { - final DomainObjectPropertySheet sheet = new DomainObjectPropertySheet( - itemModel, false, selectedLangParam - ); - - sheet.add( - new GlobalizedMessage( - "profile_site_item.ui.interests", - ProfileSiteConstants.BUNDLE - ), - ProfileSiteItemController.POSITION - ); - - return sheet; - } - -} diff --git a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemMiscForm.java b/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemMiscForm.java deleted file mode 100644 index 3d351c32b..000000000 --- a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemMiscForm.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.contenttypes.ui; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.BasicItemForm; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.profilesite.ProfileSiteConstants; -import org.librecms.profilesite.ProfileSiteItem; - -import java.util.Locale; - -/** - * - * @author Jens Pelzetter - */ -public class ProfileSiteItemMiscForm - extends BasicItemForm - implements FormProcessListener, FormInitListener { - - private final StringParameter selectedLangParam; - - public ProfileSiteItemMiscForm( - final ItemSelectionModel itemModel, - final StringParameter selectedLangParam - ) { - super("ProfileSiteItemEditMisc", itemModel, selectedLangParam); - this.selectedLangParam = selectedLangParam; - } - - @Override - public void addWidgets() { - add( - new Label( - new GlobalizedMessage( - "profile_site_item.ui.misc", - ProfileSiteConstants.BUNDLE - ) - ) - ); - final ParameterModel miscParam = new StringParameter( - ProfileSiteItemController.POSITION); - final TextArea misc = new TextArea(miscParam); - misc.setCols(80); - misc.setRows(8); - add(misc); - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - final ProfileSiteItem profile - = (ProfileSiteItem) getItemSelectionModel() - .getSelectedItem(state); - - data.put(ProfileSiteItemController.POSITION, profile.getMisc()); - - setVisible(state, true); - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - final ProfileSiteItem profile - = (ProfileSiteItem) getItemSelectionModel() - .getSelectedItem(state); - - if ((profile != null) - && getSaveCancelSection().getSaveButton().isSelected(state)) { - - final ProfileSiteItemController controller = CdiUtil - .createCdiUtil() - .findBean(ProfileSiteItemController.class); - - final Locale selectedLocale = SelectedLanguageUtil.selectedLocale( - state, selectedLangParam - ); - - controller.setMisc( - profile.getObjectId(), - (String) data.get(ProfileSiteItemController.POSITION), - selectedLocale - ); - } - - init(event); - } - -} diff --git a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemMiscStep.java b/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemMiscStep.java deleted file mode 100644 index 654820940..000000000 --- a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemMiscStep.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.contenttypes.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.BasicItemForm; -import com.arsdigita.cms.ui.authoring.SimpleEditStep; -import com.arsdigita.cms.ui.workflow.WorkflowLockedComponentAccess; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.DomainObjectPropertySheet; - -import org.librecms.profilesite.ProfileSiteConstants; - -/** - * - * @author Jens Pelzetter - */ -public class ProfileSiteItemMiscStep extends SimpleEditStep { - - private String EDIT_POSITION_SHEET_NAME = "editMisc"; - - public ProfileSiteItemMiscStep( - final ItemSelectionModel itemModel, - final AuthoringKitWizard parent, - final StringParameter selectedLangParam - ) { - this(itemModel, parent, selectedLangParam, null); - } - - public ProfileSiteItemMiscStep( - final ItemSelectionModel itemModel, - final AuthoringKitWizard parent, - final StringParameter selectedLangParam, - final String prefix - ) { - super(itemModel, parent, selectedLangParam, prefix); - - final BasicItemForm editMiscForm = new ProfileSiteItemMiscForm( - itemModel, selectedLangParam - ); - add( - EDIT_POSITION_SHEET_NAME, - new GlobalizedMessage( - "profile_site_site.ui.misc.edit", - ProfileSiteConstants.BUNDLE - ), - new WorkflowLockedComponentAccess(parent, itemModel), - editMiscForm.getSaveCancelSection().getCancelButton() - ); - - setDisplayComponent(getProfileSiteItemMiscSheet( - itemModel, selectedLangParam) - ); - } - - public static final Component getProfileSiteItemMiscSheet( - final ItemSelectionModel itemModel, - final StringParameter selectedLangParam - ) { - final DomainObjectPropertySheet sheet = new DomainObjectPropertySheet( - itemModel, false, selectedLangParam - ); - - sheet.add( - new GlobalizedMessage( - "profile_site_item.ui.misc", - ProfileSiteConstants.BUNDLE - ), - ProfileSiteItemController.POSITION - ); - - return sheet; - } - -} diff --git a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemPositionForm.java b/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemPositionForm.java deleted file mode 100644 index 1c6c7e7db..000000000 --- a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemPositionForm.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.contenttypes.ui; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.BasicItemForm; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.profilesite.ProfileSiteConstants; -import org.librecms.profilesite.ProfileSiteItem; - -import java.util.Locale; - -/** - * - * @author Jens Pelzetter - */ -public class ProfileSiteItemPositionForm - extends BasicItemForm - implements FormProcessListener, FormInitListener { - - private final StringParameter selectedLangParam; - - public ProfileSiteItemPositionForm( - final ItemSelectionModel itemModel, - final StringParameter selectedLangParam - ) { - super("ProfileSiteItemEditPosition", itemModel, selectedLangParam); - this.selectedLangParam = selectedLangParam; - } - - @Override - public void addWidgets() { - add( - new Label( - new GlobalizedMessage( - "profile_site_item.ui.position", - ProfileSiteConstants.BUNDLE - ) - ) - ); - final ParameterModel positionParam = new StringParameter( - ProfileSiteItemController.POSITION); - final TextArea position = new TextArea(positionParam); - position.setCols(80); - position.setRows(8); - add(position); - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - final ProfileSiteItem profile - = (ProfileSiteItem) getItemSelectionModel() - .getSelectedItem(state); - - data.put(ProfileSiteItemController.POSITION, profile.getPosition()); - - setVisible(state, true); - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - final ProfileSiteItem profile - = (ProfileSiteItem) getItemSelectionModel() - .getSelectedItem(state); - - if ((profile != null) - && getSaveCancelSection().getSaveButton().isSelected(state)) { - - final ProfileSiteItemController controller = CdiUtil - .createCdiUtil() - .findBean(ProfileSiteItemController.class); - - final Locale selectedLocale = SelectedLanguageUtil.selectedLocale( - state, selectedLangParam - ); - - controller.setPosition( - profile.getObjectId(), - (String) data.get(ProfileSiteItemController.POSITION), - selectedLocale - ); - } - - init(event); - } - -} diff --git a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemPositionStep.java b/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemPositionStep.java deleted file mode 100644 index a0d549999..000000000 --- a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemPositionStep.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.contenttypes.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.BasicItemForm; -import com.arsdigita.cms.ui.authoring.SimpleEditStep; -import com.arsdigita.cms.ui.workflow.WorkflowLockedComponentAccess; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.DomainObjectPropertySheet; - -import org.librecms.profilesite.ProfileSiteConstants; - -/** - * - * @author Jens Pelzetter - */ -public class ProfileSiteItemPositionStep extends SimpleEditStep { - - private String EDIT_POSITION_SHEET_NAME = "editPosition"; - - public ProfileSiteItemPositionStep( - final ItemSelectionModel itemModel, - final AuthoringKitWizard parent, - final StringParameter selectedLangParam - ) { - this(itemModel, parent, selectedLangParam, null); - } - - public ProfileSiteItemPositionStep( - final ItemSelectionModel itemModel, - final AuthoringKitWizard parent, - final StringParameter selectedLangParam, - final String prefix - ) { - super(itemModel, parent, selectedLangParam, prefix); - - final BasicItemForm editPositionForm = new ProfileSiteItemPositionForm( - itemModel, selectedLangParam - ); - add( - EDIT_POSITION_SHEET_NAME, - new GlobalizedMessage( - "profile_site_site.ui.position.edit", - ProfileSiteConstants.BUNDLE - ), - new WorkflowLockedComponentAccess(parent, itemModel), - editPositionForm.getSaveCancelSection().getCancelButton() - ); - - setDisplayComponent(getProfileSiteItemPositionSheet( - itemModel, selectedLangParam) - ); - } - - public static final Component getProfileSiteItemPositionSheet( - final ItemSelectionModel itemModel, - final StringParameter selectedLangParam - ) { - final DomainObjectPropertySheet sheet = new DomainObjectPropertySheet( - itemModel, false, selectedLangParam - ); - - sheet.add( - new GlobalizedMessage( - "profile_site_item.ui.position", - ProfileSiteConstants.BUNDLE - ), - ProfileSiteItemController.POSITION - ); - - return sheet; - } - -} diff --git a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemPropertiesStep.java b/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemPropertiesStep.java deleted file mode 100644 index fcab7902e..000000000 --- a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemPropertiesStep.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.contenttypes.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SegmentedPanel; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.BasicPageForm; -import com.arsdigita.cms.ui.authoring.SimpleEditStep; -import com.arsdigita.cms.ui.workflow.WorkflowLockedComponentAccess; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.DomainObjectPropertySheet; - -import org.librecms.assets.Person; -import org.librecms.profilesite.ProfileSiteConstants; -import org.librecms.profilesite.ProfileSiteItem; - -/** - * - * @author Jens Pelzetter - */ -public class ProfileSiteItemPropertiesStep extends SimpleEditStep { - - public static final String EDIT_SHEET_NAME = "editProfileSiteItem"; - - public ProfileSiteItemPropertiesStep( - final ItemSelectionModel itemModel, - final AuthoringKitWizard parent, - final StringParameter selectedLangParam - ) { - super(itemModel, parent, selectedLangParam); - - setDefaultEditKey(EDIT_SHEET_NAME); - - final SimpleEditStep basicProperties = new SimpleEditStep( - itemModel, parent, selectedLangParam, EDIT_SHEET_NAME - ); - final BasicPageForm editBasicSheet = new ProfileSiteItemPropertyForm( - itemModel, this, selectedLangParam - ); - - basicProperties.add( - EDIT_SHEET_NAME, - new GlobalizedMessage( - ProfileSiteConstants.BUNDLE, - "profile_site.ui.edit_basic_properties" - ), - new WorkflowLockedComponentAccess(editBasicSheet, itemModel), - editBasicSheet.getSaveCancelSection().getCancelButton() - ); - - basicProperties.setDisplayComponent( - getProfileSiteItemPropertiesSheet(itemModel, selectedLangParam) - ); - - final SegmentedPanel segmentedPanel = new SegmentedPanel(); - segmentedPanel.addSegment( - new Label( - new GlobalizedMessage( - ProfileSiteConstants.BUNDLE, - "profile_site.ui.basic_properties" - ) - ), - basicProperties - ); - - setDisplayComponent(segmentedPanel); - } - - public static Component getProfileSiteItemPropertiesSheet( - final ItemSelectionModel itemModel, - final StringParameter selectedLangParam - ) { - final DomainObjectPropertySheet sheet = new DomainObjectPropertySheet( - itemModel, false, selectedLangParam - ); - - sheet.add( - new GlobalizedMessage( - ProfileSiteConstants.BUNDLE, "profile_site.ui.OWNER" - ), - ProfileSiteItemController.OWNER, - new OwnerFormatter() - ); - - return sheet; - } - - private static class OwnerFormatter - implements DomainObjectPropertySheet.AttributeFormatter { - - @Override - public String format( - final Object obj, final String attribute, final PageState state - ) { - final ProfileSiteItem profileSiteItem = (ProfileSiteItem) obj; - - final Person owner = profileSiteItem.getOwner(); - - if (owner == null) { - return ""; - } else { - return owner.getDisplayName(); - } - } - - } - -} diff --git a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemPropertyForm.java b/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemPropertyForm.java deleted file mode 100644 index 092cb18e6..000000000 --- a/ccm-cms-profile/src/main/java/com/arsdigita/cms/contenttypes/ui/ProfileSiteItemPropertyForm.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.contenttypes.ui; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.assets.AssetSearchWidget; -import com.arsdigita.cms.ui.authoring.BasicPageForm; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.assets.Person; -import org.librecms.profilesite.ProfileSiteConstants; -import org.librecms.profilesite.ProfileSiteItem; - - -/** - * - * @author Jens Pelzetter - */ -public class ProfileSiteItemPropertyForm - extends BasicPageForm - implements FormInitListener, FormProcessListener, FormValidationListener { - - public static final String ID = "PublicPersonalProfile_edit"; - - private static final String OWNER_SEARCH = "ownerSearch"; - - private final ItemSelectionModel itemModel; - - public ProfileSiteItemPropertyForm( - final ItemSelectionModel itemModel, - final ProfileSiteItemPropertiesStep step, - final StringParameter selectedLangParam - ) { - super(ID, itemModel, selectedLangParam); - this.itemModel = itemModel; - addValidationListener(this); - } - - @Override - public void addWidgets() { - super.addWidgets(); - - final AssetSearchWidget ownerSearch = new AssetSearchWidget( - OWNER_SEARCH, Person.class - ); - add(ownerSearch); - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - final FormData formData = event.getFormData(); - final ProfileSiteItem profileSiteItem = (ProfileSiteItem) super - .initBasicWidgets(event); - formData.put(OWNER_SEARCH, profileSiteItem.getOwner()); - } - - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - super.validate(event); - - final FormData formData = event.getFormData(); - if (!formData.containsKey(OWNER_SEARCH) - || formData.get(OWNER_SEARCH) == null) { - formData.addError( - new GlobalizedMessage( - "profile_site.owner.not_selected", - ProfileSiteConstants.BUNDLE - ) - ); - } - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final ProfileSiteItem profileSiteItem = (ProfileSiteItem) super - .processBasicWidgets(event); - final FormData formData = event.getFormData(); - final Person owner = (Person) formData.get(OWNER_SEARCH); - - final ProfileSiteItemController controller = CdiUtil - .createCdiUtil() - .findBean(ProfileSiteItemController.class); - controller.setOwner(profileSiteItem.getObjectId(), owner.getObjectId()); - - init(event); - } - - - -} diff --git a/ccm-cms-profile/src/main/java/org/librecms/profilesite/ProfileSiteItem.java b/ccm-cms-profile/src/main/java/org/librecms/profilesite/ProfileSiteItem.java index 2f5718e77..63fb2d471 100644 --- a/ccm-cms-profile/src/main/java/org/librecms/profilesite/ProfileSiteItem.java +++ b/ccm-cms-profile/src/main/java/org/librecms/profilesite/ProfileSiteItem.java @@ -18,17 +18,10 @@ */ package org.librecms.profilesite; -import com.arsdigita.cms.contenttypes.ui.ProfileSiteItemCreate; -import com.arsdigita.cms.contenttypes.ui.ProfileSiteItemInterestsStep; -import com.arsdigita.cms.contenttypes.ui.ProfileSiteItemMiscStep; -import com.arsdigita.cms.contenttypes.ui.ProfileSiteItemPositionStep; -import com.arsdigita.cms.contenttypes.ui.ProfileSiteItemPropertiesStep; import org.libreccm.l10n.LocalizedString; import org.librecms.assets.Person; import org.librecms.contentsection.ContentItem; -import org.librecms.contenttypes.AuthoringKit; -import org.librecms.contenttypes.AuthoringStep; import org.librecms.contenttypes.ContentTypeDescription; import java.util.Objects; @@ -53,43 +46,6 @@ import static org.librecms.profilesite.ProfileSiteConstants.*; labelBundle = "org.librecms.profilesite.ProfileSiteItem", descriptionBundle = "org.librecms.profilesite.ProfileSiteItem" ) -@AuthoringKit( - createComponent = ProfileSiteItemCreate.class, - steps = { - @AuthoringStep( - component = ProfileSiteItemPropertiesStep.class, - labelBundle = ProfileSiteConstants.BUNDLE, - labelKey = "profile_site_item.basic_properties.label", - descriptionBundle = ProfileSiteConstants.BUNDLE, - descriptionKey = "profile_site_item.basic_properties.description", - order = 1 - ), - @AuthoringStep( - component = ProfileSiteItemPositionStep.class, - labelBundle = ProfileSiteConstants.BUNDLE, - labelKey = "profile_site_item.position.label", - descriptionBundle = ProfileSiteConstants.BUNDLE, - descriptionKey = "profile_site_item.position.description", - order = 2 - ), - @AuthoringStep( - component = ProfileSiteItemInterestsStep.class, - labelBundle = ProfileSiteConstants.BUNDLE, - labelKey = "profile_site_item.interests.label", - descriptionBundle = ProfileSiteConstants.BUNDLE, - descriptionKey = "profile_site_item.interests.description", - order = 3 - ), - @AuthoringStep( - component = ProfileSiteItemMiscStep.class, - labelBundle = ProfileSiteConstants.BUNDLE, - labelKey = "profile_site_item.misc.label", - descriptionBundle = ProfileSiteConstants.BUNDLE, - descriptionKey = "profile_site_item.misc.description", - order = 4 - ) - } -) public class ProfileSiteItem extends ContentItem { private static final long serialVersionUID = 1L; diff --git a/ccm-cms/pom.xml b/ccm-cms/pom.xml index 49a8c9740..912626128 100644 --- a/ccm-cms/pom.xml +++ b/ccm-cms/pom.xml @@ -123,11 +123,6 @@ jsoup - - org.apache.commons - commons-lang3 - - junit junit diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/CMS.java b/ccm-cms/src/main/java/com/arsdigita/cms/CMS.java deleted file mode 100755 index d8059095f..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/CMS.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms; - -/** - *

- * A central location for commonly used CMS services and their accessories.

- * - *

- * Context. {@link #getContext()} fetches the context record ({@link - * com.arsdigita.kernel.KernelContext}) of the current thread.

- * - * @author Daniel Berrange - * @see com.arsdigita.kernel.Kernel - */ -public abstract class CMS { - - - /** - * The CMS XML namespace. - */ - public final static String CMS_XML_NS = "http://www.arsdigita.com/cms/1.0"; - - /** - * Constant string used as key for creating Workspace (content-center) as a - * legacy application. - */ - public static final String WORKSPACE_PACKAGE_KEY = "content-center"; - - /** - * Constant string used as key for creating service package as a legacy - * application. - */ - public final static String SERVICE_PACKAGE_KEY = "cms-service"; - - static final CMSContext s_initialContext = new CMSContext(); - - private static final ThreadLocal s_context = new ThreadLocal() { - - @Override - public Object initialValue() { - return s_initialContext; - } - - }; - - /** - * Get the context record of the current thread. - * - * @post return != null - */ - public static final CMSContext getContext() { - return (CMSContext) s_context.get(); - } - - static final void setContext(CMSContext context) { - s_context.set(context); - } - - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/CMSContext.java b/ccm-cms/src/main/java/com/arsdigita/cms/CMSContext.java deleted file mode 100755 index 942cf88f1..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/CMSContext.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms; - -import com.arsdigita.util.Assert; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; - - -/** - *

The entry point into all the global state that CCM CMS code expects to - * have available to it when running, e.g. the current content section, - * current item - * - *

This is a session object that provides an environment in which - * code can execute. The CMSContext contains all session-specific - * variables. One session object is maintained per thread.

- * - *

Accessors of this class will assert that the item it returned is - * not null. If the caller wants to handle the case where an item is - * null explicitly, then use the hasContentItem and hasContentSection - * methods first. - * - * @see com.arsdigita.kernel.KernelContext - * @see com.arsdigita.cms.CMS - * - * @author Daniel Berrange - */ -public final class CMSContext { - - private static final Logger LOGGER = LogManager.getLogger(CMSContext.class); - - private ContentSection m_section = null; - private ContentItem m_item = null; - private SecurityManager m_security = null; - - CMSContext() { - // Empty - } - - public final String getDebugInfo() { - final String info = "Current state of " + this + ":\n" + - " getContentSection() -> " + getContentSection() + "\n" + - " getContentItem() -> " + getContentItem() + "\n" + - " getSecurityManager() -> " + getSecurityManager(); - - return info; - } - - final CMSContext copy() { - final CMSContext result = new CMSContext(); - - result.m_section = m_section; - result.m_item = m_item; - result.m_security = m_security; - - return result; - } - - /** - * Checks if a content section is available - * @return true if a content section is available - */ - public final boolean hasContentSection() { - return m_section != null; - } - - /** - * Gets the current content section - * not anymore: hasContentSection() == true - * @return the currently selected content section - */ - public final ContentSection getContentSection() { - // removing this which is not true when viewing category pages - //Assert.exists(m_section, "section"); - return m_section; - } - - /** - * Sets the current content section - * @param section the new content section - */ - public final void setContentSection(final ContentSection section) { - m_section = section; - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Content section set to " + section); - } - } - - /** - * Checks if a content item is available - * @return true if a content item is available - */ - public final boolean hasContentItem() { - return m_item != null; - } - - /** - * Returns the current content item - * @pre hasContentItem() == true - * @return the current content item - */ - public final ContentItem getContentItem() { - // removing this which is necessarily true in ContentList - //Assert.exists(m_item, "item"); - if (LOGGER.isDebugEnabled() && m_item == null) { - LOGGER.debug("Content item is null"); - } - return m_item; - } - - /** - * Sets the current content item - * @param item the new content item - */ - public final void setContentItem(final ContentItem item) { - m_item = item; - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Content item set to " + item); - } - } - - /** - * Checks if there is a CMS SecurityManager for this - * session. - * - * @see com.arsdigita.cms.SecurityManager - * @return true if a security manager is available - */ - public final boolean hasSecurityManager() { - return m_security != null; - } - - /** - * Returns the current security manager. - * - * @return the current security manager - */ - public final SecurityManager getSecurityManager() { - Assert.exists(m_security, SecurityManager.class); - - return m_security; - } - - public final void setSecurityManager(final SecurityManager security) { - m_security = security; - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Security manager set to " + security); - } - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ContentCenter.java b/ccm-cms/src/main/java/com/arsdigita/cms/ContentCenter.java deleted file mode 100644 index 73eb958ae..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ContentCenter.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 com.arsdigita.cms; - -import org.libreccm.web.CcmApplication; - -/** - * - * @author Jens Pelzetter - */ -public class ContentCenter extends CcmApplication { - - private static final long serialVersionUID = 6672720141286517654L; - - - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ContentCenterServlet.java b/ccm-cms/src/main/java/com/arsdigita/cms/ContentCenterServlet.java deleted file mode 100644 index 6333b9db6..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ContentCenterServlet.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * 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 com.arsdigita.cms; - -import com.arsdigita.bebop.Page; -import com.arsdigita.cms.dispatcher.CMSPage; -import com.arsdigita.cms.ui.CMSApplicationPage; -import com.arsdigita.cms.ui.contentcenter.MainPage; - -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.dispatcher.RequestContext; -import com.arsdigita.kernel.security.Util; -import com.arsdigita.templating.PresentationManager; -import com.arsdigita.templating.Templating; -import com.arsdigita.ui.login.LoginHelper; -import com.arsdigita.web.ApplicationFileResolver; -import com.arsdigita.web.BaseApplicationServlet; -import com.arsdigita.web.LoginSignal; -import com.arsdigita.web.WebConfig; -import com.arsdigita.xml.Document; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.shiro.authz.AuthorizationException; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.libreccm.security.Shiro; -import org.libreccm.web.CcmApplication; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionRepository; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * CMS ContentCenter (content-center) application servlet serves all request - * made within the Content Center application. - * - * @author Peter Boy - * @author Jens Pelzetter - */ -@WebServlet(urlPatterns = "/content-center/*") -public class ContentCenterServlet extends BaseApplicationServlet { - - private static final long serialVersionUID = 16543266935651171L; - - /** - * URL (pathinfo) -> Page object mapping. Based on it (and the http request - * url) the doService method to selects a page to display - */ - private final Map pages = new HashMap<>(); - - /** - * Path to directory containg ccm-cms template files - */ - private String m_templatePath; - /** - * Resolvers to find templates (JSP) and other stuff stored in file system. - */ - private ApplicationFileResolver m_resolver; - - private static final Logger LOGGER = LogManager.getLogger( - ContentCenterServlet.class); - - /** - * Use parent's class initialisation extension point to perform additional - * initialisation tasks. - */ - @Override - protected void doInit() { - LOGGER.info("starting doInit method"); - - // NEW STUFF here used to process the pages in this servlet - // Addresses previously noted in WEB-INF/resources/content-center-map.xml - // Obviously not required. - - - addPage("/", new MainPage()); // index page at address ~/cc - addPage("/index", new MainPage()); - - -// addPage("/item-search", new CMSItemSearchPage()); - // Old style - //addPage("/item-search", new ItemSearchPage()); - //addPage("/searchredirect", new CMSSearchResultRedirector()); - - // STUFF to use for JSP extension, i.e. jsp's to try for URLs which are not - // handled by the this servlet directly. - /** - * Set Template base path for JSP's - */ - // ToDo: Make it configurable by an appropriate config registry entry! - // m_templatePath = CMS.getConfig().getTemplateRoot(); - m_templatePath = "/templates/ccm-cms/content-center"; - /** - * Set TemplateResolver class - */ - m_resolver = WebConfig.getConfig().getResolver(); - } - - @Override - protected void doService(final HttpServletRequest sreq, - final HttpServletResponse sresp, - final CcmApplication app) throws ServletException, - IOException { - LOGGER.info("starting doService method"); - - // ContentCenter workspace = (ContentCenter) app; - - /* Check user and privilegies */ - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final Shiro shiro = cdiUtil.findBean(Shiro.class); - if (!shiro.getSubject().isAuthenticated()) { - throw new LoginSignal(sreq); // send to login page - } - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - final ContentSectionRepository sectionRepo = cdiUtil.findBean( - ContentSectionRepository.class); - final List sections = sectionRepo.findAll(); - boolean hasAccess = false; - for (final ContentSection section : sections) { - if (permissionChecker.isPermitted(ItemPrivileges.EDIT, - section.getRootDocumentsFolder())) { - hasAccess = true; - break; - } - } - - if (!hasAccess) { // user has no access privilege - throw new AuthorizationException( - "User is not entitled to access any content section"); - // throw new LoginSignal(sreq); // send to login page - } - - // New way to fetch the page - String pathInfo = sreq.getPathInfo(); - if (pathInfo.length() > 1 && pathInfo.endsWith("/")) { - /* NOTE: ServletAPI specifies, pathInfo may be empty or will - * start with a '/' character. It currently carries a - * trailing '/' if a "virtual" page, i.e. not a real jsp, but - * result of a servlet mapping. But Application requires url - * NOT to end with a trailing '/' for legacy free applications. */ - pathInfo = pathInfo.substring(0, pathInfo.length() - 1); - } - - // An empty remaining URL or a URL which doesn't end in trailing slash: - // probably want to redirect. - // Probably DEPRECATED with new access method or only relevant for jsp - // extension - // if (m_trailingSlashList.contains(url) && !originalUrl.endsWith("/")) { - // DispatcherHelper.sendRedirect(sresp, originalUrl + "/"); - // return; - // } - final Page page = pages.get(pathInfo); - if (page != null) { - - // Check user access. - checkUserAccess(sreq, sresp); - - if (page instanceof CMSPage) { - // backwards compatibility fix until migration completed - final CMSPage cmsPage = (CMSPage) page; - final RequestContext ctx = DispatcherHelper.getRequestContext(); - cmsPage.init(); - cmsPage.dispatch(sreq, sresp, ctx); - } else { - final CMSApplicationPage cmsAppPage = (CMSApplicationPage) page; - cmsAppPage.init(sreq, sresp, app); - // Serve the page. - final Document doc = cmsAppPage.buildDocument(sreq, sresp); - - PresentationManager pm = Templating.getPresentationManager(); - pm.servePage(doc, sreq, sresp); - } - - } else { - // Fall back on the JSP application dispatcher. - // NOTE: The JSP must ensure the proper authentication and - // authorisation if required! - LOGGER.info("NO page registered to serve the requst url."); - - RequestDispatcher rd = m_resolver.resolve(m_templatePath, - sreq, sresp, app); - if (rd != null) { - LOGGER.debug("Got dispatcher " + rd); - - final HttpServletRequest origreq = DispatcherHelper - .restoreOriginalRequest(sreq); - rd.forward(origreq, sresp); - } else { - - sresp.sendError(404, sreq.getRequestURI() - + " not found on this server."); - } - - } - - LOGGER.info("doService method completed"); - - } // END doService() - - /** - * Internal service mechod, adds one pair of Url - Page to the internal hash - * map, used as a cache. - * - * @param pathInfo url stub for a page to display - * @param page Page object to display - */ - private void addPage(final String pathInfo, final Page page) { - - // Current Implementation requires pathInfo to start with a leading '/' - // SUN Servlet API specifies: "PathInfo *may be empty* or will start - // with a '/' character." - pages.put(pathInfo, page); - - } - -// /** -// * Service Method returns the URL stub for the class name, can return null -// * if not mapped -// */ -// // Currently still in use by c.ad.cms.ui.ItemSearchWidget -// public static String getURLStubForClass(String classname) { -// LOGGER.debug("Getting URL Stub for : " + classname); -// Iterator itr = s_pageURLs.keySet().iterator(); -// while (itr.hasNext()) { -// String classname2 = (String) itr.next(); -// s_log.debug("key: " + classname + " value: " -// + (String) s_pageURLs.get(classname2)); -// } -// String url = (String) s_pageURLs.get(classname); -// return url; -// } - /** - * Verify that the user is logged in and is able to view the page. - * Subclasses can override this method if they need to, but should always be - * sure to call super.checkUserAccess(...) - * - * @param request The HTTP request - * @param response The HTTP response - * @param actx The request context - * - */ - protected void checkUserAccess(final HttpServletRequest request, - final HttpServletResponse response //, - /// final RequestContext actx - ) - throws ServletException { - - if (!CdiUtil.createCdiUtil().findBean(Shiro.class).getSubject() - .isAuthenticated()) { - throw new LoginSignal(request); - } - } - - /** - * Redirects the client to the login page, setting the return url to the - * current request URI. - * - * @exception ServletException If there is an exception thrown while trying - * to redirect, wrap that exception in a - * ServletException - * - */ - protected void redirectToLoginPage(HttpServletRequest req, - HttpServletResponse resp) - throws ServletException { - String url = Util.getSecurityHelper() - .getLoginURL(req) - + "?" + LoginHelper.RETURN_URL_PARAM_NAME - + "=" + DispatcherHelper.encodeReturnURL(req); - try { - LoginHelper.sendRedirect(req, resp, url); - } catch (IOException e) { - LOGGER.error("IO Exception", e); - throw new ServletException(e.getMessage(), e); - } - } - - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ContentItemXMLRenderer.java.off b/ccm-cms/src/main/java/com/arsdigita/cms/ContentItemXMLRenderer.java.off deleted file mode 100644 index 0ce8896c3..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ContentItemXMLRenderer.java.off +++ /dev/null @@ -1,155 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.arsdigita.cms; - -import com.arsdigita.cms.contenttypes.GenericAddress; -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.domain.DomainObject; -import com.arsdigita.domain.DomainObjectTraversalAdapter; -import com.arsdigita.domain.DomainObjectXMLRenderer; -import com.arsdigita.globalization.GlobalizationHelper; -import com.arsdigita.persistence.metadata.Property; -import com.arsdigita.xml.Element; -import org.apache.log4j.Logger; - -/** - * This is a special ContentItemXMLRenderer for CMS to get a more transparent - * way to handle ContentBundles during XML output. - * - * The problem was to change RelatedLinks and therefore Link to always link to - * the corresponding ContentBundle instead of the content item. To get the - * corresponding content item during XML generation, I have to test for - * ContentBundle and negotiate the language version. - * This is not possible in com.arsdigita.ccm - * - * @author quasi - */ -public class ContentItemXMLRenderer extends DomainObjectXMLRenderer { - - private static final Logger logger = - Logger.getLogger(ContentItemXMLRenderer.class); - private String m_propertyName = ""; - private String m_keyName = ""; - private String m_relationAttribute = ""; - - public ContentItemXMLRenderer(final Element root) { - super(root); - } - - // This method will be called by DomainObjectTraversal.walk() - // It's purpose is to test for ContentBundle objects and if found, replace - // that object with the negotiated version of the content item. - // Otherwise this methd will do nothing. - @Override - protected void walk(final DomainObjectTraversalAdapter adapter, - final DomainObject obj, - final String path, - final String context, - final DomainObject linkObject) { - //final long start = System.nanoTime(); - - DomainObject nObj = obj; - - if (nObj instanceof ContentBundle) { - - nObj = ((ContentBundle) obj).getInstance(GlobalizationHelper.getNegotiatedLocale(), true); - } - - super.walk(adapter, nObj, path, context, linkObject); - - //System.out.printf("Walked object in %d ms\n", (System.nanoTime() - start) / 1000000); - } - - @Override - protected void handleAttribute(final DomainObject obj, final String path, final Property property) { - final String propertyName = property.getName(); - - // Special handling for the isoCountryCode field in GenericAddress - if (obj instanceof GenericAddress && "isoCountryCode".equals(propertyName)) { - //if (propertyName.equals("isoCountryCode")) { - super.handleAttribute(obj, path, property); - - final Element element = newElement(m_element, "country"); - element.setText(GenericAddress.getCountryNameFromIsoCode(((GenericAddress) obj).getIsoCountryCode())); - return; - - } - - // Special handling for the relation attribute keys - if (!m_relationAttribute.isEmpty()) { - String key = ""; - - // The RelationAttribute is part of this domain object as field - if (obj instanceof RelationAttributeInterface - && ((RelationAttributeInterface) obj). - hasRelationAttributeProperty(propertyName)) { - - final RelationAttributeInterface relationAttributeObject = (RelationAttributeInterface) obj; - key = relationAttributeObject.getRelationAttributeKey( - propertyName); - - } - - // This RelationAttribute is part of an n:m association as link attribute - if (obj instanceof LinkDomainObject - && propertyName.equals(m_keyName)) { - key = (String) ((LinkDomainObject) obj).get(m_keyName); - } - - // Replace value of the property defined in RELATION_ATTRIBUTES string - // of the primary domain object with the localized String. - if (!key.isEmpty()) { -// logger.debug(String.format( -// "Getting relation attribute value for key '%s' of relation attribute '%s'", -// key, m_relationAttribute)); - final RelationAttributeCollection relationAttributeCollection = new RelationAttributeCollection( - m_relationAttribute, key); - relationAttributeCollection.addLanguageFilter(GlobalizationHelper. - getNegotiatedLocale().getLanguage()); - if (!relationAttributeCollection.isEmpty()) { - relationAttributeCollection.next(); - final Element element = newElement(m_element, m_keyName); - element.setText(relationAttributeCollection.getName()); - final Element elementId = newElement(m_element, m_keyName + "Id"); - elementId.setText(relationAttributeCollection.getKey()); - relationAttributeCollection.close(); - } - return; - } - } - - super.handleAttribute(obj, path, property); - } - - @Override - protected void beginAssociation(final DomainObject obj, final String path, final Property property) { - super.beginAssociation(obj, path, property); - - final String propertyName = property.getName(); - - if (obj instanceof RelationAttributeInterface - && ((RelationAttributeInterface) obj).hasRelationAttributeProperty( - propertyName)) { - - final RelationAttributeInterface relationAttributeObject = (RelationAttributeInterface) obj; - - m_propertyName = propertyName; - m_keyName = relationAttributeObject.getRelationAttributeKeyName(propertyName); - m_relationAttribute = relationAttributeObject.getRelationAttributeName(propertyName); - - } - } - - @Override - protected void endAssociation(final DomainObject obj, final String path, final Property property) { - - m_propertyName = ""; - m_keyName = ""; - m_relationAttribute = ""; - - super.endAssociation(obj, path, property); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ItemSelectionModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ItemSelectionModel.java deleted file mode 100755 index 9c9eb488e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ItemSelectionModel.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.ui.CcmObjectSelectionModel; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentType; -import org.librecms.contentsection.ContentTypeRepository; -import org.librecms.contenttypes.ContentTypeInfo; - -import java.math.BigDecimal; - -/** - *

- * Loads a subclass of a {@link com.arsdigita.cms.ContentItem} from the - * database. This model should be used as a parameter to the constructor of - * authoring kit components.

- * - *

- * It is possible to instantiate this model with a {@link - * com.arsdigita.cms.ContentType} as a constructor parameter. In this case, the - * model will only instantiate items that are of the specified content type, or - * one of it subclasses.

- * - * @author Stanislav Freidin (stas@arsdigita.com) - * @author Jens Pelzetter - * - * @see com.arsdigita.kernel.ui.ACSObjectSelectionModel - * @see com.arsdigita.bebop.SingleSelectionModel - */ -public class ItemSelectionModel extends CcmObjectSelectionModel { - - private Long typeId; - - public ItemSelectionModel(final LongParameter parameter) { - super(ContentItem.class.getName(), parameter); - } - - public ItemSelectionModel(final String parameterName) { - super(ContentItem.class.getName(), parameterName); - } - - /** - * Construct a new ItemSelectionModel - * - * @param type The content type for the items this model will - * generate - * - * @param parameterName The name of the state parameter which will be used - * to store the item. - */ - public ItemSelectionModel(final ContentType type, - final String parameterName) { - this(type, new LongParameter(parameterName)); - } - - /** - * Construct a new ItemSelectionModel - * - * @param type The content type for the items this model will generate - * - * @param parameter The state parameter which should be used by this item - * - */ - public ItemSelectionModel(final ContentType type, - final LongParameter parameter) { - super(type.getContentItemClass(), parameter); - typeId = type.getObjectId(); - } - - /** - * Construct a new ItemSelectionModel - * - * @param type The content type for the items this model will generate - * - * @param model The {@link SingleSelectionModel} which will supply a - * {@link BigDecimal} id of the currently selected object - * - */ - public ItemSelectionModel(final ContentType type, - final SingleSelectionModel model) { - super(type.getContentItemClass(), model); - typeId = type.getObjectId(); - } - - public ItemSelectionModel(final ContentTypeInfo type, - final SingleSelectionModel model) { - super(type.getContentItemClass().getName(), model); - typeId = null; - } - - public ItemSelectionModel(final ContentTypeInfo type, - final LongParameter parameter) { - super(type.getContentItemClass().getName(), parameter); - typeId = null; - } - - /** - * A convenience method that gets the currently selected object and casts it - * to a ContentItem - * - * @param state the current page state - * - * @return the currently selected ContentItem, or null if no - * item was selected. - */ - public final ContentItem getSelectedItem(final PageState state) { - return getSelectedObject(state); - } - - /** - * - * @return The content type of the items which are produced by this model, - * or null if the content type has not been specified in the - * constructor. - */ - public ContentType getContentType() { - - ContentType type = null; - - if (typeId != null) { - type = CdiUtil.createCdiUtil().findBean(ContentTypeRepository.class) - .findById(typeId).get(); - } - - return type; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/PageLocations.java b/ccm-cms/src/main/java/com/arsdigita/cms/PageLocations.java deleted file mode 100755 index 656129039..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/PageLocations.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms; - -/** - * Specifies the standard locations of the pages that comprise the - * content section user interface. - * - * @author Karl Goldstein (karlg at arsdigita dot com) - * - * @version $Id: PageLocations.java 2090 2010-04-17 08:04:14Z pboy $ - **/ -public interface PageLocations { - public String SECTION_PAGE = "admin/index.jsp"; - public String ITEM_PAGE = "admin/item.jsp"; -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/CMSDispatcher.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/CMSDispatcher.java deleted file mode 100755 index d5a83e93d..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/CMSDispatcher.java +++ /dev/null @@ -1,718 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.dispatcher.ChainedDispatcher; -import com.arsdigita.dispatcher.Dispatcher; -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.dispatcher.JSPApplicationDispatcher; -import com.arsdigita.dispatcher.RedirectException; -import com.arsdigita.dispatcher.RequestContext; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.web.LoginSignal; -import com.arsdigita.web.URL; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.File; -import java.io.IOException; -import java.util.HashMap; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.shiro.authz.AuthorizationException; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.security.PermissionChecker; -import org.libreccm.security.Shiro; -import org.libreccm.security.User; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionManager; -import org.librecms.contentsection.ContentSectionRepository; -import org.librecms.contentsection.privileges.ItemPrivileges; -import org.librecms.dispatcher.ItemResolver; - -/** - *

- * The CMS Dispatcher serves all request made within a content section. This - * dispatcher is called by the Subsite dispatcher.

- * - *

- * Here are the steps for a request to - * http://yourserver/cms/cheese in excruciating detail:

- * - *
    - *
  1. - * A client sends a request to the web server, which passes it on to the global - * ACS dispatcher.

  2. - * - *
  3. - * The global ACS dispatcher examines the first part of the URL, notices that - * CMS is mounted at /cms and hands the request to the CMS - * dispatcher.

  4. - * - *
  5. - * The CMS dispatcher determines whether a Page has been registered to - * the URL /cheese in this section via its - * {@link com.arsdigita.cms.dispatcher.PageResolver}.

  6. - * - *
  7. - * Since no page is registered to the URL, the CMS dispatcher asks the content - * section (via its {@link com.arsdigita.cms.dispatcher.ItemResolver}) for a - * content item for /cheese in this content section. The result of this - * process is a {@link com.arsdigita.cms.ContentItem} object.

  8. - * - *
  9. - * The CMS dispatcher asks the content section for a Page - * to use as the "master template" for this item. The content section may apply - * item-, type-, or request-specific rules to make this decision (for example, - * check a user preference for normal or accessible style, or a query parameter - * for a printable version).

  10. - * - *
  11. - * The CMS dispatcher hands the master Page object to the - * {@link com.arsdigita.sitenode.SiteNodePresentationManager} to serve the - * page.

  12. - * - *
  13. - * The presentation manager asks the master Page object for an XML - * document representing the data for the page.

  14. - * - *
  15. - * The master template begins walking through its component hierarchy, - * converting each component to XML by calling its - * generateXML method. The component responsible for rendering the - * content item uses an {@link com.arsdigita.cms.dispatcher.XMLGenerator} to - * convert the content item to XML.

  16. - * - *
  17. - * The presentation manager receives the completed XML document, and selects an - * XSL transformer to use for generating the HTML. The stylesheet on which the - * transformer is based contains templates for all styles and all content types - * in the content section, in particular those from the file - * cms-item.xsl.

  18. - *
- * - * @author Michael Pih (pihman@arsdigita.com) - * @author Uday Mathur (umathur@arsdigita.com) - * @author Jack Chung (flattop@arsdigita.com) - * @author Jens Pelzetter - */ -public class CMSDispatcher implements Dispatcher, ChainedDispatcher { - - private static Logger LOGGER = LogManager.getLogger(CMSDispatcher.class); - - public static final String CONTENT_SECTION - = "com.arsdigita.cms.dispatcher.section"; - - public static final String CONTENT_ITEM - = "com.arsdigita.cms.dispatcher.item"; - - public static final String[] INDEX_FILES = { - "index.jsp", "index.html", "index.htm"}; - - private static final String DEBUG = "/debug"; - private static final String ADMIN_SECTION = "admin"; - - public static final String ADMIN_URL = "admin/index"; - - /** - * The context for previewing items - */ - public static final String PREVIEW = "preview"; - - // Content section cache - private static HashMap s_pageResolverCache = new HashMap(); -// private static HashMap s_itemResolverCache = new HashMap(); - private static HashMap s_xmlGeneratorCache = new HashMap(); - - private boolean m_adminPagesOnly = false; - - public CMSDispatcher() { - this(false); - } - - public CMSDispatcher(boolean adminOnly) { - m_adminPagesOnly = adminOnly; - } - - /** - * Handles requests made to a CMS package instance. 1) fetches the current - * content section 2) fetches the resource mapped to the current section/URL - * 3) if no resource, fetches the item associated with the current - * section/URL 4) if no item, passes request to the JSP dispatcher, which - * serves JSP's, HTML pages, and media from the cms/packages/www directory - * - * @param request The request - * @param response The response - * @param actx The request context - */ - public void dispatch(HttpServletRequest request, - HttpServletResponse response, - RequestContext actx) - throws IOException, ServletException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Dispatching request for " + new URL(request) - .toDebugString()); - } - - // This is the path to the current site node. - String processedUrl = actx.getProcessedURLPart(); - String webappURLContext = request.getContextPath(); - if (processedUrl.startsWith(webappURLContext)) { - processedUrl = processedUrl.substring(webappURLContext.length()); - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Determined the path to the current site node; it " - + "is '" + processedUrl + "' according to the " - + "request context"); - } - - // This is the path within the site node. - String remainingUrl = actx.getRemainingURLPart(); - if (remainingUrl.endsWith("/")) { - remainingUrl = remainingUrl.substring(0, remainingUrl.length() - 1); - } else if (remainingUrl.endsWith(ItemDispatcher.FILE_SUFFIX)) { - remainingUrl = remainingUrl.substring(0, remainingUrl.length() - - ItemDispatcher.FILE_SUFFIX - .length()); - } else if (remainingUrl.equals("")) { - remainingUrl = "index"; - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Determined the path after the current site node; " - + "it is '" + remainingUrl + "'"); - } - - // Fetch the current content section. - ContentSection section = null; - try { - section = findContentSection(processedUrl); - } catch (Exception ex) { - throw new ServletException(ex); - } - request.setAttribute(CONTENT_SECTION, section); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Found content section '" + section + "'"); - } - - // Check user access to this page and deny access if necessary. - checkUserAccess(request, response, actx); - - // Look for a site-node-specific asset (if any). - // KG: This hack will be replaced by a ChainedDispatcher - try { - LOGGER.debug("Looking for a site node asset"); - - String siteNodeAssetURL = getSiteNodeAsset(request, actx); - if (siteNodeAssetURL != null) { - LOGGER.debug("Site node asset found at '" + siteNodeAssetURL - + "'"); - - DispatcherHelper.cacheDisable(response); - DispatcherHelper.setRequestContext(request, actx); - DispatcherHelper.forwardRequestByPath(siteNodeAssetURL, - request, response); - return; - } - - LOGGER.debug("No site node asset found; proceeding with normal " - + "dispatching"); - } catch (RedirectException e) { - throw new ServletException(e); - } - - // Fetch the requested resource (if any). - ResourceHandler resource = getResource(section, remainingUrl); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Got a resource '" + resource + "'"); - } - - if (resource != null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Found resource '" + remainingUrl + "'; " - + "dispatching to it"); - } - - LOGGER.info("resource dispatch for " + remainingUrl); - // Found resource, now serve it. - // NB, ResouceHandler implementations should take care of caching options - resource.dispatch(request, response, actx); - - } else { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("No resource found at '" + remainingUrl + "'; " - + "searching for a previewable content item at " - + "this path"); - } - - // If the remaining URL starts with "preview/", then try and - // preview this item. Otherwise look for the live item. - boolean preview = false; - if (remainingUrl.startsWith(PREVIEW)) { - remainingUrl = remainingUrl.substring(PREVIEW.length()); - preview = true; - } - - // Check for published / previewable item. - ContentItem item = null; - - // Check if the user has access to view public pages - final PermissionChecker permissionChecker = CdiUtil.createCdiUtil() - .findBean(PermissionChecker.class); - - if (permissionChecker.isPermitted( - ItemPrivileges.VIEW_PUBLISHED, item)) { - if (preview) { - item = getContentItem(section, - remainingUrl, - CMSDispatcher.PREVIEW); - } else { - item = getContentItem(section, - remainingUrl, - "live"); - } - if (item != null) { - request.setAttribute(CONTENT_ITEM, item); - } - } - - if (item != null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Found item " + item + "; serving it"); - } - - DispatcherHelper.cacheDisable(response); - preview(request, response, actx); - } else { - LOGGER.debug("No item to preview found; falling back to " - + "JSP dispatcher to look for some concrete " - + "resource in the file system"); - - // If no resource was found, look for a JSP page. - JSPApplicationDispatcher jsp = JSPApplicationDispatcher - .getInstance(); - //DispatcherHelper.cacheDisable(response); - jsp.dispatch(request, response, actx); - } - - } - - } - - public int chainedDispatch(HttpServletRequest request, - HttpServletResponse response, - RequestContext actx) - throws IOException, ServletException { - if (m_adminPagesOnly) { - String url = actx.getRemainingURLPart(); - - if (url.endsWith(ItemDispatcher.FILE_SUFFIX)) { - url = url.substring(0, url.length() - ItemDispatcher.FILE_SUFFIX - .length()); - } else if (url.endsWith("/")) { - url = url.substring(0, url.length() - 1); - } - - if (url.equals(ADMIN_URL)) { - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Resolving admin URL '" + url + "'"); - } - - dispatch(request, response, actx); - - return ChainedDispatcher.DISPATCH_BREAK; - } else { - return ChainedDispatcher.DISPATCH_CONTINUE; - } - } - - dispatch(request, response, actx); - return ChainedDispatcher.DISPATCH_BREAK; - } - - /** - * Verify that the user is logged in and is able to view the page. - * Subclasses can override this method if they need to, but should always be - * sure to call super.checkUserAccess(...) - * - * @param request The HTTP request - * @param response The HTTP response - * @param actx The request context - * - * @throws javax.servlet.ServletException - * - */ - protected void checkUserAccess(HttpServletRequest request, - HttpServletResponse response, - RequestContext actx) - throws ServletException, AuthorizationException { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final Shiro shiro = cdiUtil.findBean(Shiro.class); - User user = shiro.getUser().get(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - - ContentSection section = getContentSection(request); - - if (isAdminPage(actx.getRemainingURLPart())) { - - // Handle admin page requests. - // If the user is not logged in, redirect to the login page. - // Otherwise, perform the Admin Pages access check. - if (user == null) { - redirectToLoginPage(request, response); - return; - } - //if (!sm.canAccess(user, SecurityManager.ADMIN_PAGES)) { - permissionChecker.checkPermission(ItemPrivileges.EDIT, - section.getRootDocumentsFolder()); - } else { - // For public page requests, use the SecurityManager to check access - // SecurityManager.canAccess(user, SecurityManager.PUBLIC_PAGES) must - permissionChecker.checkPermission( - ItemPrivileges.VIEW_PUBLISHED, - section.getRootDocumentsFolder()); - } - } - - /** - * Fetches the content section from the request attributes. - * - * @param request The HTTP request - * - * @return The content section - * - * @pre ( state != null ) - */ - public static ContentSection getContentSection(HttpServletRequest request) { - return (ContentSection) request.getAttribute(CONTENT_SECTION); - } - - /** - * Fetches the content item from the request attributes. - * - * @param request The HTTP request - * - * @return The content item - * - * @pre ( state != null ) - */ - public static ContentItem getContentItem(HttpServletRequest request) { - return (ContentItem) request.getAttribute(CONTENT_ITEM); - } - - /** - * Looks up the current content section using the remaining URL stored in - * the request context object and the SiteNode class. - * - * @param url The section URL stub - * - * @return The current Content Section - */ - protected ContentSection findContentSection(String url) { - - // MP: This is a hack to get the debugging info in - // SiteNodePresentationManager.servePage, but since it's - // debugging info... - // Remove /debug from the start of the URL if it exists. - if (url.startsWith(DEBUG)) { - url = url.substring(DEBUG.length()); - } - - final String debugXMLString = "/xml"; - if (url.startsWith(debugXMLString)) { - url = url.substring(debugXMLString.length()); - } - - final String debugXSLString = "/xsl"; - if (url.startsWith(debugXSLString)) { - url = url.substring(debugXSLString.length()); - } - - final String sectionLabel = url; - - // Fetch the current site node from the URL. - final ContentSectionRepository sectionRepo = CdiUtil.createCdiUtil() - .findBean(ContentSectionRepository.class); - final ContentSection section = sectionRepo - .findByLabel(url) - .orElseThrow(() -> new UnexpectedErrorException( - String.format("No ContentSection '%s' found.", sectionLabel))); - return section; - } - - /** - * Fetch a resource based on the URL stub. - * - * @param section The current content section - * @param url The section-relative URL - * - * @return A ResourceHandler resource or null if none exists. - * - * @pre (url != null) - */ - protected ResourceHandler getResource(ContentSection section, String url) - throws ServletException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Searching for a resource for the URL fragment '" + url - + "' under " + section); - } - - final PageResolver pageResolver = CMSDispatcher.getPageResolver(section); - - final ResourceHandler handler = pageResolver.getPage(url); - - return handler; - } - - /** - * Lookup a content item by section and URL. - * - * @param section The content section - * @param url The URL relative to the content section - * @param context The use context - * - * @return The item associated with the URL, or null if no such item exists - * - * @throws javax.servlet.ServletException - */ - protected ContentItem getContentItem(ContentSection section, String url, - String context) - throws ServletException { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentSectionManager sectionManager = cdiUtil.findBean( - ContentSectionManager.class); - final ItemResolver itemResolver = sectionManager - .getItemResolver(section); - - return itemResolver.getItem(section, url, context); - } - - /** - * Preview the current content item. - * - * @param request The HTTP request - * @param response The HTTP response - * @param actx The request context - */ - protected void preview(HttpServletRequest request, - HttpServletResponse response, - RequestContext actx) - throws IOException, ServletException { - - ContentSection section = getContentSection(request); - ContentItem item = getContentItem(request); - - ItemResolver itemResolver = CMSDispatcher.getItemResolver(section); - CMSPage page = itemResolver.getMasterPage(item, request); - page.dispatch(request, response, actx); - } - - /** - * Flushes the page resolver cache. - * - * @param section The current content section - * @param url The section-relative URL - */ - public static void releaseResource(ContentSection section, String url) { - final String pageResolverClassName = section.getPageResolverClass(); - final PageResolver pageResolver; - try { - pageResolver = (PageResolver) Class.forName(pageResolverClassName) - .newInstance(); - } catch (ClassNotFoundException - | IllegalAccessException - | InstantiationException ex) { - throw new RuntimeException(ex); - } - pageResolver.releasePage(url); - } - - /** - * Fetches the PageResolver for a content section. Checks cache first. - * - * @param section The content section - * - * @return The PageResolver associated with the content section - */ - public static PageResolver getPageResolver(ContentSection section) { - LOGGER.debug("Getting the page resolver"); - - final String name = section.getLabel(); - PageResolver pr = (PageResolver) s_pageResolverCache.get(name); - - if (pr == null) { - LOGGER.debug("The page resolver was not cached; fetching a new " - + "one and placing it in the cache"); - - final String pageResolverClassName = section.getPageResolverClass(); - final PageResolver pageResolver; - try { - pageResolver = (PageResolver) Class.forName( - pageResolverClassName) - .newInstance(); - } catch (ClassNotFoundException - | IllegalAccessException - | InstantiationException ex) { - throw new RuntimeException(ex); - } - s_pageResolverCache.put(name, pageResolver); - } - - return pr; - } - - /** - * Fetches the ItemResolver for a content section. Checks cache first. - * - * @param section The content section - * - * @return The ItemResolver associated with the content section - */ - public static ItemResolver getItemResolver(ContentSection section) { - - final Class clazz; - try { - clazz = Class.forName(section.getItemResolverClass()); - } catch (ClassNotFoundException ex) { - throw new UncheckedWrapperException(ex); - } - - return (ItemResolver) CdiUtil.createCdiUtil().findBean(clazz); - - } - - /** - * Fetches the XMLGenerator for a content section. Checks cache first. - * - * @param section The content section - * - * @return The XMLGenerator associated with the content section - */ - public static XMLGenerator getXMLGenerator(ContentSection section) { - String name = section.getLabel(); - XMLGenerator xmlGenerator = (XMLGenerator) s_xmlGeneratorCache.get(name); - if (xmlGenerator == null) { - final String xmlGeneratorClassName = section.getXmlGeneratorClass(); - try { - xmlGenerator = (XMLGenerator) Class.forName( - xmlGeneratorClassName).newInstance(); - } catch (ClassNotFoundException - | IllegalAccessException - | InstantiationException ex) { - throw new RuntimeException(ex); - } - s_xmlGeneratorCache.put(name, xmlGenerator); - } - - return xmlGenerator; - } - - /** - * Does this URL correspond to an admin page? - */ - protected boolean isAdminPage(String url) { - - // MP: This is a hack to get the debugging info in - // SiteNodePresentationManager.servePage, but since it's - // debugging info... - // Remove /debug from the start of the URL if it exists. - if (url.startsWith(DEBUG)) { - url = url.substring(DEBUG.length()); - } - - return (url != null && (url.startsWith(ADMIN_SECTION) || url.startsWith( - PREVIEW))); - } - - /** - * Redirects the client to the login page, setting the return url to the - * current request URI. - * - * @exception ServletException If there is an exception thrown while trying - * to redirect, wrap that exception in a - * ServletException - * - */ - protected void redirectToLoginPage(HttpServletRequest req, - HttpServletResponse resp) - throws ServletException { - throw new LoginSignal(req); - } - - // modified from JSPApplicationDispatcher - private String getSiteNodeAsset(HttpServletRequest request, - RequestContext actx) - throws RedirectException { - - String siteNodeAssetURL = null; - - ServletContext sctx = actx.getServletContext(); - String processedURL = actx.getProcessedURLPart(); - String remainingURL = actx.getRemainingURLPart(); - // REMOVE THIS HACK ONCE we have working publish to file code in the build - //String templateRoot = PublishToFile.getDefaultDestinationForType(Template.class); - String templateRoot = null; - - /* Allow a graceful early exit if publishToFile is not initialized */ - if (null == templateRoot) { - return null; - } - - File siteNodeAssetRoot = new File(templateRoot, processedURL); - File assetFile = new File(siteNodeAssetRoot, remainingURL); - - String contextPath = request.getContextPath(); - - if (assetFile.isDirectory()) { - - if (remainingURL.endsWith("/")) { - throw new RedirectException(actx.getOriginalURL() + "/"); - } - - for (int i = 0; i < INDEX_FILES.length; i++) { - File indexFile = new File(assetFile, INDEX_FILES[i]); - if (indexFile.exists()) { - assetFile = indexFile; - } - } - } - - if (assetFile.exists()) { - siteNodeAssetURL = contextPath + "/" + templateRoot - + processedURL + remainingURL; - } - - return siteNodeAssetURL; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/CMSPage.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/CMSPage.java deleted file mode 100755 index 5ba7e4c3e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/CMSPage.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.bebop.BebopConfig; -import com.arsdigita.bebop.Container; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.page.PageTransformer; -import com.arsdigita.cms.CMS; -import com.arsdigita.dispatcher.RequestContext; -import com.arsdigita.templating.PresentationManager; -import com.arsdigita.web.Web; -import com.arsdigita.xml.Document; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.libreccm.security.Shiro; -import org.libreccm.security.User; -import org.libreccm.web.CcmApplication; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionServlet; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.util.Optional; - -/** - *

- * A CMSPage is a Bebop {@link com.arsdigita.bebop.Page} implementation - * of the {@link com.arsdigita.cms.dispatcher.ResourceHandler} interface.

- * - *

- * It stores the current {@link com.arsdigita.cms.ContentSection} and, if - * applicable, the {@link com.arsdigita.cms.ContentItem} in the page state as - * request local objects. Components that are part of the CMSPage - * may access these objects by calling:

- *
- *     getContentSection(PageState state);
- * 
- * - * @author Michael Pih (pihman@arsdigita.com) - * @author Uday Mathur (umathur@arsdigita.com) - */ -public class CMSPage extends Page implements ResourceHandler { - - private static final Logger LOGGER = LogManager.getLogger(CMSPage.class); - - /** - * The global assets URL stub XML parameter name. - */ - public final static String ASSETS = "ASSETS"; - - /** - * The XML page class. - */ - public final static String PAGE_CLASS = "CMS"; - - /** - * Map of XML parameters - */ - private HashMap m_params; - - /** - * */ - private PageTransformer m_transformer; - - public CMSPage() { - super(); - buildPage(); - } - - public CMSPage(String title) { - super(title); - buildPage(); - } - - public CMSPage(String title, Container panel) { - super(title, panel); - buildPage(); - } - - public CMSPage(Label title) { - super(title); - buildPage(); - } - - public CMSPage(Label title, Container panel) { - super(title, panel); - buildPage(); - } - - /** - * Builds the page. - */ - protected void buildPage() { - // Set the class attribute value. May be overwritten by child class - // to hold a more specific value - setClassAttr(PAGE_CLASS); - - // Global XML params. - // MP: This only works with older versions of Xalan. - m_params = new HashMap(); - setXMLParameter(ASSETS, Utilities.getGlobalAssetsURL()); - - // MP: This is a hack to so that the XML params work with the newer - // version of Xalan. - // Sets attribute in SimpleComponent, attributes of the same name will - // be overweritten. - setAttribute(ASSETS, Utilities.getGlobalAssetsURL()); - - // Make sure the error display gets rendered. - getErrorDisplay().setIdAttr("page-body"); - - final Class presenterClass = BebopConfig - .getConfig().getPresenterClass(); - final PresentationManager pm; - try { - pm = presenterClass.getDeclaredConstructor().newInstance(); - } catch (InstantiationException - | IllegalAccessException - | InvocationTargetException - | NoSuchMethodException ex) { - throw new RuntimeException(ex); - } - - if (pm instanceof PageTransformer) { - m_transformer = (PageTransformer) pm; - } else { - m_transformer = new PageTransformer(); - } - } - - /** - * Finishes and locks the page. If the page is already locked, does nothing. - * - * This method is called by the {@link com.arsdigita.dispatcher.Dispatcher} - * that initializes this page. - */ - @Override - public synchronized void init() { - LOGGER.debug("Initializing the page"); - - if (!isLocked()) { - LOGGER.debug("The page hasn't been locked; locking it now"); - - lock(); - } - } - - /** - * Fetches the value of the XML parameter. - * - * @param name The parameter name - * - * @return The parameter value - * - * @pre (name != null) - */ - public String getXMLParameter(String name) { - return (String) m_params.get(name); - } - - /** - * Set an XML parameter. - * - * @param name The parameter name - * @param value The parameter value - * - * @pre (name != null) - */ - public void setXMLParameter(String name, String value) { - m_params.put(name, value); - } - - /** - * Fetch the request-local content section. - * - * @param request The HTTP request - * - * @return The current content section - * - * @deprecated use com.arsdigita.cms.CMS.getContext().getContentSection() - * instead Despite of being deprecated it can not be removed because it is - * required by the interface Resourcehandler which is implemented by this - * class. On the other hand, if deprecated, implementing ResourceHandler may - * not be required - */ - @Override - public ContentSection getContentSection(HttpServletRequest request) { - // Resets all content sections associations. - // return ContentSectionDispatcher.getContentSection(request); - return ContentSectionServlet.getContentSection(request); - } - - /** - * Fetch the request-local content section. - * - * @param state The page state - * - * @return The current content section - * - * @deprecated use com.arsdigita.cms.CMS.getContext().getContentSection() - * instead Despite of being deprecated it can not be removed because it is - * required by ContentItemPage which extends CMSPage and uses this method. - */ - public ContentSection getContentSection(PageState state) { - return getContentSection(state.getRequest()); - } - - /** - * Fetch the request-local content item. - * - * @param request The HTTP request - * - * @return The current content item - * - * @deprecated use com.arsdigita.cms.CMS.getContext().getContentItem() - * instead Despite of being deprecated it can not be removed because it is - * required by the interface Resourcehandler which is implemented by this - * class. On the other hand, if deprecated, implementing ResourceHandler may - * not be required - */ - public ContentItem getContentItem(HttpServletRequest request) { - // resets all content item associations - return ContentSectionDispatcher.getContentItem(request); - } - - /** - * Fetch the request-local content item. - * - * @param state The page state - * - * @return The current content item - * - * @deprecated use com.arsdigita.cms.CMS.getContext().getContentItem() - * instead. Despite of being deprecated it can not be removed because it is - * required by ContentItemPage which extends CMSPage and uses this method. - */ - public ContentItem getContentItem(PageState state) { - return getContentItem(state.getRequest()); - } - - /** - * Services the Bebop page. - * - * @param request The servlet request object - * @param response the servlet response object - * @param actx The request context - * - * @pre m_transformer != null - */ - @Override - public void dispatch(final HttpServletRequest request, - final HttpServletResponse response, - final RequestContext actx) - throws IOException, ServletException { - - final CcmApplication app = Web.getWebContext().getApplication(); - ContentSection section = null; - - if (app == null) { - //Nothing to do - } else if (app instanceof ContentSection) { - section = (ContentSection) app; - } - - if (section != null) { - CMS.getContext().setContentSection(section); - } - - final String itemId = request.getParameter("item_id"); - - if (itemId != null) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil.findBean( - ContentItemRepository.class); - final ContentItem item = itemRepo - .findById(Long.parseLong(itemId)).get(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - permissionChecker.checkPermission(ItemPrivileges.PREVIEW, - item); - CMS.getContext().setContentItem(item); - } - - final Document document = buildDocument(request, response); - - m_transformer.servePage(document, request, response); - } - - /** - * Overwrites bebop.Page#generateXMLHelper to add the name of the user - * logged in to the page (displayed as part of the header). - * - * @param ps - * @param parent - * - * @return - */ - @Override - protected Element generateXMLHelper(PageState ps, Document parent) { - Element page = super.generateXMLHelper(ps, parent); - final Optional user = CdiUtil.createCdiUtil() - .findBean(Shiro.class).getUser(); - if (user.isPresent()) { - page.addAttribute("name", user.get().getName()); - } - - return page; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ContentItemDispatcher.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ContentItemDispatcher.java deleted file mode 100755 index 5296089a2..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ContentItemDispatcher.java +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.dispatcher.Dispatcher; -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.dispatcher.RequestContext; -import com.arsdigita.util.Assert; -import com.arsdigita.web.Web; - -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; - -/** - * This is the dispatcher for content-sections. It maintains a - * ContentItem-to-Template cache Code that modifies a published ContentItem's - * template must update the cache in this class by calling the appropriate cache - * methods. - * - * @author bche@redhat.com - */ -public class ContentItemDispatcher implements Dispatcher { - - /** cache for the template resolver */ - public static Map s_templateResolverCache = Collections - .synchronizedMap(new HashMap()); - - /** */ - protected ItemXML m_itemXML; - - /** - * */ - public ContentItemDispatcher() { - m_itemXML = new ItemXML(); - } - - /** - * @see com.arsdigita.dispatcher.Dispatcher#dispatch (HttpServletRequest, - * HttpServletResponse, RequestContext) - */ - public void dispatch(final HttpServletRequest request, - final HttpServletResponse response, - final RequestContext actx) - throws IOException, ServletException { - - Boolean bXMLMode = (Boolean) request - .getAttribute("xmlMode"); - if (bXMLMode != null && bXMLMode.booleanValue()) { - //if this is XML mode, then use itemXML - m_itemXML.dispatch(request, response, actx); - } else { - //this is normal dispatching - - //get the Content Item - //final ContentItem item = (ContentItem) request.getAttribute - // (ContentSectionServlet.CONTENT_ITEM); - final ContentItem item = getContentItem(request); - //get the Content Section - final ContentSection section = (ContentSection) Web.getWebContext() - .getApplication(); - - Assert.exists(item); - - //get the item's template -// final String sTemplateURL = getTemplatePath(item, request, actx); - - //dispatch to the template - DispatcherHelper.setRequestContext(request, actx); - DispatcherHelper.forwardRequestByPath(null, request, - response); - - } - } - - /** - * Fetches the content item from the request attributes. - * - * @param request The HTTP request - * - * @return The content item - * - * @pre ( request != null ) - */ - public static ContentItem getContentItem(HttpServletRequest request) { - return (ContentItem) request.getAttribute( - "com.arsdigita.cms.dispatcher.item"); - } - -// //synchronize access to the cache -// private static synchronized void cachePut(BigDecimal contentItemID, -// String sTemplatePath) { -// s_cache.put(contentItemID, sTemplatePath); -// } -// -// private static synchronized void cacheRemove(BigDecimal contentItemID) { -// s_cache.remove(contentItemID); -// } -// -// /** -// * Method cacheRemove. Removes the cached template path for the contentItem -// * item -// * -// * @param item -// */ -// public static void cacheRemove(ContentItem item) { -// if (item == null) { -// return; -// } -// if (s_log.isDebugEnabled()) { -// s_log.debug("removing cached entry for item " + item.getName() -// + " with ID " + item.getID()); -// } -// s_cache.remove(item.getID()); -// } - - /** - * Method cachePut. Maps the ContentItem item to the template t in the cache - * - * @param item - * @param t - */ -// public static void cachePut(ContentItem item, Template t) { -// ContentSection section = item.getContentSection(); -// String sPath = getTemplatePath(section, t); -// -// //only cache live items -// if (item == null || item.getVersion().compareTo(ContentItem.LIVE) != 0) { -// return; -// } -// -// if (s_log.isDebugEnabled()) { -// s_log.debug("updating mapping for item " + item.getName() -// + " with ID " + item.getID() + " in section " + section -// .getName() + " of type " + item.getContentType().getName() -// + " to template " + sPath); -// } -// -// cachePut(item.getID(), sPath); -// } - - /** - * Method cachePut. Maps all the content items of ContentType type and in - * ContentSection section that don't have their own templates to the - * template t in the cache - * - * @param section - * @param type - * @param t - */ -// public static void cachePut(ContentSection section, -// ContentType type, -// Template t) { -// s_log.debug("updating cache for section " + section.getName() -// + " and type " + type.getName()); -// -// //get all the items in the section -// ItemCollection items = section.getItems(); -// -// //filter items by content type -// BigDecimal typeID = type.getID(); -// Filter filter = items.addFilter("type.id = :typeID"); -// filter.set("typeID", typeID); -// -// //get only live items -// Filter liveFilter = items.addFilter("version = '" + ContentItem.LIVE -// + "'"); -// -// //filter out content items in ContentSection section of -// //ContentType type with a template for the "public" context -// Filter itemsFilter = items.addNotInSubqueryFilter("id", -// "com.arsdigita.cms.ItemsWithTemplateMapping"); -// itemsFilter.set("sectionId", section.getID()); -// itemsFilter.set("typeId", type.getID()); -// -// //TODO: FILTER OUT CONTENT ITEMS IN THIS SECTION OF THIS TYPE -// //WITH A TEMPLATE FOR THE "PUBLIC" CONTEXT -// /* -// * select items.item_id -// * from cms_items items, cms_item_template_map map -// * where items.item_id = map.item_id -// * and use_context = 'public' -// * and items.version = 'live' -// * and items.section_id = :section_id -// * and items.type_id = :type_id -// */ -// synchronized (s_cache) { -// //update the cache for all items -// while (items.next()) { -// cachePut(items.getContentItem(), t); -// } -// } -// } - -// private static String getTemplatePath(ContentSection section, -// Template template) { -// //the template path is -// // TEMPLATE_ROOT/[content-section-name]/[template-path] -// final String sep = java.io.File.separator; -// String sPath = ContentSectionConfig.getConfig().getTemplateRoot() + sep -// + section.getName() + sep + template.getPath(); -// return sPath; -// } -// -// private static void updateTemplateCache(ContentSection section, -// ContentItem item, -// String sTemplatePath) { -// //use the live version of the item for the cache -// item = item.getLiveVersion(); -// s_log.debug("updating mapping for item " + item.getName() + " with ID " -// + item.getID() + " in section " + item.getContentSection() -// .getName() + " of type " + item.getContentType().getName() -// + " to template " + sTemplatePath); -// cachePut(item.getID(), sTemplatePath); -// } -// -// private String cacheGet(BigDecimal key) { -// return (String) s_cache.get(key); -// } - -// private String getTemplatePath(ContentItem item, -// HttpServletRequest req, -// RequestContext ctx) { -// -// //check if the template path is cached -// //BigDecimal id = item.getID(); -// //String sPath = cacheGet(id); -// //return from cache -// // current cache scheme doesn't work when there are -// //multiple templates per item, as would happen with -// // multiple template contexts or in the case of -// //category item resolution, more than one category for -// //the item. -// //if (sPath != null) { -// //s_log.debug("returning template path from cache"); -// // return sPath; -// //} -// //s_log.debug("template path not in cache, so fecthing"); -// //template is not in the cache, so retrieve it and place it in -// //the cache -// String sPath = fetchTemplateURL(item, req, ctx); -// //cachePut(id, sPath); -// -// return sPath; -// } - - /** - * Fetches the URL of a template for an item. The returned URL is relative - * to the webapp context. - */ -// public String fetchTemplateURL(ContentItem item, -// HttpServletRequest request, -// RequestContext actx) { -// if (s_log.isDebugEnabled()) { -// s_log.debug("fetching URL for item " + item.getName() + " with ID " -// + item.getID()); -// } -// -// ContentSection section = item.getContentSection(); -// String templateURL = getTemplateResolver(section).getTemplate(section, -// item, -// request); -// -// if (s_log.isDebugEnabled()) { -// s_log.debug("templateURL is " + templateURL); -// } -// return templateURL; -// -// } -// -// /** -// * Fetches the TemplateResolver for a content section. Checks cache first. -// * -// * @param section The content section -// * -// * @return The TemplateResolver associated with the content section -// */ -// public TemplateResolver getTemplateResolver(ContentSection section) { -// -// String name = section.getName(); -// TemplateResolver ir = (TemplateResolver) s_templateResolverCache.get( -// name); -// -// if (ir == null) { -// ir = section.getTemplateResolver(); -// s_templateResolverCache.put(name, ir); -// } -// -// return ir; -// } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ContentPanel.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ContentPanel.java deleted file mode 100755 index 920538f65..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ContentPanel.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleComponent; -import com.arsdigita.cms.CMS; -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.util.Assert; -import com.arsdigita.xml.Element; - -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionServlet; -import org.librecms.dispatcher.ItemResolver; - -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - *

- * This ContentPanel component fetches the - * {@link com.arsdigita.cms.dispatcher.XMLGenerator} for the content - * section.

- * - * @author Michael Pih (pihman@arsdigita.com) - * @version $Revision$ $Date$ - * @version $Id$ - */ -public class ContentPanel extends SimpleComponent { - - public ContentPanel() { - super(); - } - - /** - * Fetches an XML Generator. This method can be overridden to fetch any - * {@link com.arsdigita.cms.dispatcher.XMLGenerator}, but by default, it - * fetches the XMLGenerator registered to the current - * {@link com.arsdigita.cms.ContentSection}. - * - * @param state The page state - * - * @return The XMLGenerator used by this Content Panel - */ - protected XMLGenerator getXMLGenerator(PageState state) { - ContentSection section = CMS.getContext().getContentSection(); - Assert.exists(section); - try { - return (XMLGenerator) Class.forName(section.getXmlGeneratorClass()) - .newInstance(); - } catch (ClassNotFoundException | - InstantiationException | - IllegalAccessException ex) { - throw new RuntimeException(ex); - } - } - - /** - * Generates XML that represents a content item. - * - * @param state The page state - * @param parent The parent DOM element - * - * @see com.arsdigita.cms.dispatcher.XMLGenerator - */ - @Override - public void generateXML(PageState state, Element parent) { - if (isVisible(state)) { - Element content = parent.newChildElement("cms:contentPanel", - CMS.CMS_XML_NS); - exportAttributes(content); - - // Generate path information about the content item - generatePathInfoXML(state, content); - - // Take advantage of caching in the CMS Dispatcher. - XMLGenerator xmlGenerator = getXMLGenerator(state); - - xmlGenerator.generateXML(state, content, null); - } - } - - /** - * Generate information about the path to this content item. - * - * @param state the page state - * @param parent the element that will contain the path info - */ - protected void generatePathInfoXML(PageState state, Element parent) { - Element pathInfo = parent - .newChildElement("cms:pathInfo", CMS.CMS_XML_NS); - - if (CMS.getContext().hasContentSection()) { - pathInfo.newChildElement("cms:sectionPath", CMS.CMS_XML_NS).setText( - CMS.getContext().getContentSection().getPrimaryUrl()); - } - String url = DispatcherHelper.getRequestContext().getRemainingURLPart(); - if (url.startsWith(CMSDispatcher.PREVIEW)) { - pathInfo.newChildElement("cms:previewPath", CMS.CMS_XML_NS).setText( - ContentSectionServlet.PREVIEW); - } - pathInfo.newChildElement("cms:templatePrefix", CMS.CMS_XML_NS).setText( - "/" + ItemResolver.TEMPLATE_CONTEXT_PREFIX); - - if (CMS.getContext().hasContentItem()) { - ContentItem item = CMS.getContext().getContentItem(); - pathInfo.newChildElement("cms:itemPath", CMS.CMS_XML_NS).setText("/" - + item.getName()); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ContentSectionDispatcher.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ContentSectionDispatcher.java deleted file mode 100755 index d2988c5c6..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ContentSectionDispatcher.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.dispatcher.Dispatcher; -import com.arsdigita.dispatcher.DispatcherChain; -import com.arsdigita.dispatcher.RequestContext; -import com.arsdigita.util.Assert; -import com.arsdigita.web.Web; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.libreccm.web.ApplicationManager; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Unsupported Refactored content section - * dispatcher (under development). - * - * @author Karl Goldstein (karlg@arsdigita.com) - * @version $Revision$ $DateTime: 2004/08/17 23:15:09 $ - * @version $Id$ - */ -public class ContentSectionDispatcher implements Dispatcher { - - public static final String CONTENT_ITEM - = "com.arsdigita.cms.dispatcher.item"; - - static final String CONTENT_SECTION = "com.arsdigita.cms.dispatcher.section"; - - private DispatcherChain dispatcherChain = new DispatcherChain(); - - public ContentSectionDispatcher() { - - dispatcherChain.addChainedDispatcher(new CMSDispatcher(true)); - dispatcherChain.addChainedDispatcher(new FileDispatcher()); - dispatcherChain.addChainedDispatcher(new ItemDispatcher()); - dispatcherChain.addChainedDispatcher(new CMSDispatcher()); - } - - public void dispatch(HttpServletRequest request, - HttpServletResponse response, - RequestContext context) - throws IOException, ServletException { - - setContentSection(request, context); - dispatcherChain.dispatch(request, response, context); - } - - /** - * Fetches the content section from the request attributes. - * - * @param request The HTTP request - * - * @return The content section - * - * @pre ( request != null ) - */ - public static ContentSection getContentSection(HttpServletRequest request) { - return (ContentSection) request.getAttribute(CONTENT_SECTION); - } - - /** - * Fetches the content item from the request attributes. - * - * @param request The HTTP request - * - * @return The content item - * - * @pre ( request != null ) - */ - public static ContentItem getContentItem(HttpServletRequest request) { - return (ContentItem) request.getAttribute(CONTENT_ITEM); - } - - /** - * Looks up the current content section using the remaining URL stored in - * the request context object and the SiteNode class. - * - * @param url The section URL stub - * - * @return The current Content Section - */ - private void setContentSection(HttpServletRequest request, - // SiteNodeRequestContext actx) - RequestContext actx) - throws ServletException { - - final ContentSection section = (ContentSection) Web.getWebContext() - .getApplication(); - request.setAttribute(CONTENT_SECTION, section); - } - - /** - * Checks that the current user has permission to access the admin pages. - * - * @param request - * @param section - */ - public static boolean checkAdminAccess(HttpServletRequest request, - ContentSection section) { - - return CdiUtil.createCdiUtil().findBean(PermissionChecker.class) - .isPermitted(ItemPrivileges.EDIT, section - .getRootDocumentsFolder()); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/DefaultTemplateResolver.java.off b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/DefaultTemplateResolver.java.off deleted file mode 100755 index 16c522f5b..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/DefaultTemplateResolver.java.off +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.cms.ContentItem; -import com.arsdigita.cms.ContentSection; -import com.arsdigita.cms.ContentType; -import com.arsdigita.cms.Folder; -import com.arsdigita.cms.Template; -import com.arsdigita.cms.TemplateManager; -import com.arsdigita.cms.TemplateManagerFactory; -import com.arsdigita.mimetypes.MimeType; -import com.arsdigita.util.Assert; -import org.apache.log4j.Logger; - -import javax.servlet.http.HttpServletRequest; - -/** - * ------- May be outdated. TemplateResolver has been reworked. ---------- - * Resolves the JSP template to use for dispatching an - * item. This replaces TemplateResolver since the latter - * has a useless API. - * ------------------------------------------------------------------------ - * - *

In general, the process for resolving a template involves two - * steps:

- * - *
    - * - *
  1. The template resolver examines specific properties of the - * item, the content section, and/or the request itself and selects - * an appropriate context. A context is simply a token - * such as "plain" or "fancy". - * - *
  2. Based on the selected context, the template resolver - * identifies an appropriate template for the item. This is a - * three-step process: (1) the resolver queries for an association - * between the item and a specific template for the selected - * context; (2) if no such association exists, the resolver queries - * the item's content type for a default template to use in the - * selected context; (3) if a default template is not found, return - * null (at which point the dispatcher should probably give up and - * return a 404 error). - * - *
- */ - -public class DefaultTemplateResolver extends AbstractTemplateResolver - implements TemplateResolver { - - private static Logger s_log = Logger.getLogger(DefaultTemplateResolver.class); - - /** - * Returns the JSP template filename relative to the webapp - * root. - * - * @param section The ContentSection for the request - * @param item The ContentItem for the request - * @param request The current HttpServletRequest - * - * @return The path to the jsp template. - */ - public String getTemplate(ContentSection section, - ContentItem item, - HttpServletRequest request) { - - String template = getItemTemplate(section, item, request); - MimeType mimeType = MimeType.loadMimeType(Template.JSP_MIME_TYPE); - - if (template == null) { - if (s_log.isDebugEnabled()) { - s_log.debug("No item template, looking for content type template"); - } - template = getTypeTemplate(section, item, request, mimeType); - } - - if (template == null) { - if (s_log.isDebugEnabled()) { - s_log.debug("No content type template, looking for default template"); - } - - template = getDefaultTemplate(section, item, request); - - Assert.exists(template, "default template"); - } - - if (s_log.isInfoEnabled()) { - s_log.info("Got template " + template + " for item " + item.getOID()); - } - - return ContentSection.getConfig().getTemplateRoot() + template; - } - - /** - * Returns the JSP template filename relative to the webapp - * root for a given Template reference. - * - * @param template The Template to resolve the URL for. - * - * @return The path to the jsp template. - */ - public String getTemplatePath(Template template) { - - return ContentSection.getConfig().getTemplateRoot() + - getTemplateFilename(template, template.getContentSection()); - } - - /** - * Returns the XSL template filename relative to the webapp - * root for a given Template reference. - * - * @param template The Template to resolve the URL for. - * - * @return The path to the xsl template. - */ - public String getTemplateXSLPath(Template template) { - - return ContentSection.getConfig().getTemplateRoot() + - getTemplateXSLFilename(template, template.getContentSection()); - } - - /** - * Returns the template associated with the item (if any) - */ - protected String getItemTemplate(ContentSection section, - ContentItem item, - HttpServletRequest request) { - TemplateManager manager = TemplateManagerFactory.getInstance(); - String context = getTemplateContext(request); - Template template = manager.getTemplate(item, context); - - return template == null ? null : getTemplateFilename( - template, section - ); - } - - /** - * Returns the template associated with the type (if any) - * @deprecated Use the version that specifies a mime type - */ - protected String getTypeTemplate(ContentSection section, - ContentItem item, - HttpServletRequest request) { - MimeType mimeType = MimeType.loadMimeType(Template.JSP_MIME_TYPE); - return getTypeTemplate(section, item, request, mimeType); - } - - /** - * Returns the template associated with the type (if any) - */ - protected String getTypeTemplate(ContentSection section, - ContentItem item, - HttpServletRequest request, - MimeType mimeType) { - TemplateManager manager = TemplateManagerFactory.getInstance(); - ContentType type = item.getContentType(); - - Template template = null; - - if (type != null ) { - String context = getTemplateContext(request); - template = manager.getDefaultTemplate(section, type, context, mimeType); - } else { - if (s_log.isDebugEnabled()) { - s_log.debug("Item has no content type, not looking for a " + - "content type specific template"); - } - } - - return template == null ? null : getTemplateFilename( - template, section - ); - } - - /** - * Returns the default template - */ - protected String getDefaultTemplate(ContentSection section, - ContentItem item, - HttpServletRequest request) { - String path = (item instanceof Folder) ? - ContentSection.getConfig().getDefaultFolderTemplatePath() : - ContentSection.getConfig().getDefaultItemTemplatePath(); - - return path; - } - - /** - * Returns the filename for a Template object - */ - protected String getTemplateFilename(Template template, - ContentSection section, - ContentItem item, - HttpServletRequest request) { - return getTemplateFilename(template, section); - } - - /** - * Returns the filename for a Template object - */ - protected String getTemplateXSLFilename(Template template, - ContentSection section, - ContentItem item, - HttpServletRequest request) { - return getTemplateXSLFilename(template, section); - } - - /** - * Returns the filename for a Template object - */ - protected String getTemplateFilename(Template template, - ContentSection section) { - - String templateName = template.getPath(); - String sectionURL = section.getPath(); - return sectionURL + "/" + templateName; - } - - /** - * Returns the filename for a Template object - */ - protected String getTemplateXSLFilename(Template template, - ContentSection section) { - - String templateName = template.getPathNoJsp() + ".xsl"; - String sectionURL = section.getPath(); - - return sectionURL + "/" + templateName; - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/FileDispatcher.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/FileDispatcher.java deleted file mode 100755 index efea84744..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/FileDispatcher.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.dispatcher.ChainedDispatcher; -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.dispatcher.RequestContext; - -import org.apache.logging.log4j.LogManager; - -import java.io.File; -import java.io.IOException; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.logging.log4j.Logger; - -/** - * Dispatches to a file stored under the CMS package root - * (/packages/cms/www). This includes both unmanaged files copied - * or created directly in the file system, as well as pages and assets published - * to the file system from CMS. - * - * @author Karl Goldstein (karlg@arsdigita.com) - * @version $Revision$ $DateTime: 2004/08/17 23:15:09 $ - * @version $Id$ - * - */ -public class FileDispatcher implements ChainedDispatcher { - - private static final Logger LOGGER = LogManager.getLogger( - ChainedDispatcher.class); - - @Override - public int chainedDispatch(HttpServletRequest request, - HttpServletResponse response, - RequestContext context) - throws IOException, ServletException { - - File jspFile = getPackageFile(context); - - if (jspFile.exists() && !jspFile.isDirectory()) { - String packageURL = context.getPageBase() + context - .getRemainingURLPart(); - LOGGER.debug("DISPATCHING to " + packageURL); - - // don't match folders, since they don't actually match a file - if (!packageURL.endsWith("/")) { - LOGGER.debug("DISPATCHING to " + packageURL); - // Don't set caching headers - let JSP file do it if required - //DispatcherHelper.maybeCacheDisable(response); - DispatcherHelper.setRequestContext(request, context); - DispatcherHelper.forwardRequestByPath(packageURL, request, - response); - return ChainedDispatcher.DISPATCH_BREAK; - } - } - - return ChainedDispatcher.DISPATCH_CONTINUE; - } - - /** - * Matches the request URL to a file in the package www directory. - * - */ - private File getPackageFile(RequestContext appContext) { - - ServletContext servletContext = appContext.getServletContext(); - - String filePath = appContext.getRemainingURLPart(); - - String packageDocRoot = servletContext.getRealPath(appContext - .getPageBase()); - - File jspFile = new File(packageDocRoot, filePath); - - return jspFile; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ItemDispatcher.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ItemDispatcher.java deleted file mode 100755 index 1d4ea4cb4..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ItemDispatcher.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.dispatcher.ChainedDispatcher; -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.dispatcher.RequestContext; -import com.arsdigita.web.LoginSignal; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.libreccm.security.Shiro; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionManager; -import org.librecms.contentsection.ContentSectionServlet; -import org.librecms.contentsection.privileges.ItemPrivileges; -import org.librecms.dispatcher.ItemResolver; - -/** - * Dispatches to the JSP or Servlet for rendering a content item. - * - * @author Karl Goldstein (karlg@arsdigita.com) - * - */ -public class ItemDispatcher implements ChainedDispatcher { - - private static Logger LOGGER = LogManager.getLogger(ItemDispatcher.class); - - public static Map s_itemResolverCache = Collections.synchronizedMap( - new HashMap()); - public static Map s_templateResolverCache = Collections.synchronizedMap( - new HashMap()); - - public static final String FILE_SUFFIX = ".jsp"; - public static final String INDEX_FILE = "/index"; -// public static final String TEMPLATE_ROOT = -// "/packages/content-section/templates"; -// public static final String DEFAULT_ITEM_TEMPLATE = "/default/item.jsp"; -// public static final String DEFAULT_FOLDER_TEMPLATE = "/default/folder.jsp"; - - public static final String XML_SUFFIX = ".xml"; - public static final String XML_MODE = "xmlMode"; - - private static boolean m_cacheItems = true; - - /** - * The context for previewing items - */ - public static final String PREVIEW = "/preview"; - - protected ItemXML m_itemXML; - - public ItemDispatcher() { - super(); - m_itemXML = new ItemXML(); - } - - public static void setCacheItems(boolean value) { - m_cacheItems = value; - } - - public int chainedDispatch(final HttpServletRequest request, - final HttpServletResponse response, - final RequestContext actx) - throws IOException, ServletException { - String queryString = request.getQueryString(); - String url = actx.getRemainingURLPart(); - - LOGGER.info("Resolving item URL " + url); - - if (url.endsWith(XML_SUFFIX)) { - request.setAttribute(XML_MODE, Boolean.TRUE); - LOGGER.debug("StraightXML Requested"); - url = "/" + url.substring(0, url.length() - XML_SUFFIX.length()); - } else { - request.setAttribute(XML_MODE, Boolean.FALSE); - // it's neither a .jsp or a .xml, thus its an error - if (url.endsWith(FILE_SUFFIX)) { - url = "/" + url - .substring(0, url.length() - FILE_SUFFIX.length()); - } else if (url.endsWith("/")) { - url = "/" + url.substring(0, url.length() - 1); - } else { - LOGGER.warn("Fail: URL doesn't have right suffix."); - return ChainedDispatcher.DISPATCH_CONTINUE; - } - } - - final ContentSection section = ContentSectionServlet.getContentSection( - request); - // ContentSectionDispatcher.getContentSection(request); - - final ContentItem item = getItem(section, url); - if (item == null) { - LOGGER.warn("Fail: No live item found matching " + url); - return ChainedDispatcher.DISPATCH_CONTINUE; - } - - request.setAttribute(ContentSectionDispatcher.CONTENT_ITEM, item); - - LOGGER.debug("MATCHED " + item.getObjectId()); - - // Work out how long to cache for.... - // We take minimum(default timeout, lifecycle expiry) - //ToDo -// Lifecycle cycle = item.getLifecycle(); - int expires = DispatcherHelper.getDefaultCacheExpiry(); -// if (cycle != null) { -// Date endDate = cycle.getEndDate(); -// -// if (endDate != null) { -// int maxAge = (int) ( ( endDate.getTime() - System.currentTimeMillis() ) / 1000l ); -// if (maxAge < expires) { -// expires = maxAge; -// } -// } -// } -//ToDo end - // NB, this is not the same as the security check previously - // We are checking if anyone can access - ie can we allow - // this page to be publically cached - if (m_cacheItems && !url.startsWith(PREVIEW)) { -// if (sm.canAccess((User)null, SecurityManager.PUBLIC_PAGES, item)) { - if (CdiUtil.createCdiUtil().findBean(PermissionChecker.class) - .isPermitted( - ItemPrivileges.VIEW_PUBLISHED, item)) { - DispatcherHelper.cacheForWorld(response, expires); - } else { - DispatcherHelper.cacheForUser(response, expires); - } - } else { - DispatcherHelper.cacheDisable(response); - } - - if (((Boolean) request.getAttribute(XML_MODE)).booleanValue()) { - m_itemXML.dispatch(request, response, actx); - return ChainedDispatcher.DISPATCH_BREAK; - } else { - - // normal dispatching - // This part assumes the template is JSP. -// final String templateURL = getTemplateURL(section, item, request, -// actx); -// s_log.debug("TEMPLATE " + templateURL); - DispatcherHelper.setRequestContext(request, actx); - DispatcherHelper.forwardRequestByPath(null, request, - response); - return ChainedDispatcher.DISPATCH_BREAK; - } - } - - public ContentItem getItem(ContentSection section, String url) { - - ItemResolver itemResolver = getItemResolver(section); - ContentItem item; - // Check if the user has access to view public or preview pages - boolean hasPermission = true; - HttpServletRequest request = DispatcherHelper.getRequest(); - - // If the remaining URL starts with "preview/", then try and - // preview this item. Otherwise look for the live item. - boolean preview = false; - if (url.startsWith(PREVIEW)) { - url = url.substring(PREVIEW.length()); - preview = true; - } - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - - if (preview) { - item = itemResolver.getItem(section, url, "draft"); - if (item != null) { - hasPermission = permissionChecker.isPermitted( - ItemPrivileges.PREVIEW, item); - } - } else { - item = itemResolver.getItem(section, url, "live"); - if (item != null) { - hasPermission = permissionChecker.isPermitted( - ItemPrivileges.VIEW_PUBLISHED, item); - } - } - - if (item == null && url.endsWith(INDEX_FILE)) { - - // look up folder if it's an index - url = url.substring(0, url.length() - INDEX_FILE.length()); - LOGGER.info("Attempting to match folder " + url); - item = itemResolver.getItem(section, url, "live"); - if (item != null) { - hasPermission = permissionChecker.isPermitted( - ItemPrivileges.VIEW_PUBLISHED, item); - } - } - // chris.gilbert@westsussex.gov.uk - if user is not logged in, give them a chance to do that, else show them the door - if (!hasPermission && !cdiUtil.findBean(Shiro.class).getSubject() - .isAuthenticated()) { - throw new LoginSignal(request); - } - if (!hasPermission) { - throw new com.arsdigita.dispatcher.AccessDeniedException(); - } - - return item; - } - - /** - * Fetches the ItemResolver for a content section. - * - * @param section The content section - * - * @return The ItemResolver associated with the content section - */ - public ItemResolver getItemResolver(ContentSection section) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentSectionManager sectionManager = cdiUtil.findBean( - ContentSectionManager.class); - - return sectionManager.getItemResolver(section); - } - - /** - * Fetches the ItemResolver for a content section. Checks cache first. - * - * @param section The content section - * - * @return The ItemResolver associated with the content section - */ -// public TemplateResolver getTemplateResolver(ContentSection section) { -// -// String name = section.getName(); -// TemplateResolver ir = (TemplateResolver) s_templateResolverCache.get( -// name); -// -// if (ir == null) { -// ir = section.getTemplateResolver(); -// s_templateResolverCache.put(name, ir); -// } -// -// return ir; -// } - /** - * Fetches the URL of a template for an item. The returned URL is relative - * to the webapp context. - */ -// public String getTemplateURL(ContentSection section, -// ContentItem item, -// HttpServletRequest request, -// RequestContext actx) { -// -// String templateURL = getTemplateResolver(section).getTemplate(section, -// item, -// request); -// -// return templateURL; -// } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ItemXML.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ItemXML.java deleted file mode 100755 index d859ef41e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ItemXML.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - - -import com.arsdigita.cms.CMS; -import com.arsdigita.dispatcher.RequestContext; -import com.arsdigita.xml.Document; -import com.arsdigita.xml.Element; - -import org.librecms.contentsection.ContentItem; - -import java.io.IOException; -import java.io.OutputStream; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - - -/*** - * - * XMLPage - * - * Designed to allow you to output straight XML directly from the ContentItem - * that implements XMLGenerator, with none of the surrounding headers, footers, etc - * - * @author slater@arsdigita.com - * - ***/ - -public class ItemXML extends ResourceHandlerImpl { - - public ItemXML() { - super(); - } - - public void dispatch(HttpServletRequest request, - HttpServletResponse response, - RequestContext actx) - throws IOException, ServletException { - - ContentItem item = getContentItem(request); - - Element content = new Element("cms:item", CMS.CMS_XML_NS); - -// ContentItemXMLRenderer renderer = -// new ContentItemXMLRenderer(content); - //ToDo -// renderer.setWrapAttributes(true); -// renderer.setWrapRoot(false); -// renderer.setWrapObjects(false); -// -// renderer.walk(item, SimpleXMLGenerator.ADAPTER_CONTEXT); -//ToDo End - - Document doc; - try { - doc = new Document(content); - } catch (javax.xml.parsers.ParserConfigurationException e) { - throw new javax.servlet.ServletException(e); - } - - OutputStream out = response.getOutputStream(); - try { - out.write(doc.toString(true).getBytes()); - } catch (IOException e) { - throw new ServletException(e); - } finally { - out.close(); - } - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/MasterPage.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/MasterPage.java deleted file mode 100755 index 2278982b1..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/MasterPage.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.util.Assert; - -import org.librecms.contentsection.ContentSection; - -import javax.servlet.http.HttpServletRequest; - - -/** - *

A {@link com.arsdigita.cms.dispatcher.CMSPage} used for serving - * content items.

- * - *

This page contains a ContentPanel component which fetches - * the {@link com.arsdigita.cms.dispatcher.XMLGenerator} for the content - * section.

- * - * @author Michael Pih (pihman@arsdigita.com) - * @version $Revision$ $DateTime: 2004/08/17 23:15:09 $ - * @version $Id$ - */ -public class MasterPage extends CMSPage { - - public MasterPage() { - super("Master", new SimpleContainer()); - setIdAttr("master_page"); - - add(new ContentPanel()); - } - - /** - * Fetch the request-local content section. - * - * @param request The HTTP request - * @return The current content section - */ - public ContentSection getContentSection(HttpServletRequest request) { - // Resets all content sections associations. - ContentSection section = super.getContentSection(request); - Assert.exists(section); - return section; - } - - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/PageResolver.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/PageResolver.java deleted file mode 100755 index 9ea2c6581..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/PageResolver.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - - -import java.math.BigDecimal; -import java.util.HashMap; - - -/** - *

This class contains methods for registering and resolving {@link - * ResourceHandler CMS resources} in a specific content section.

- * - *

The PageResolver includes methods for caching resource - * mappings.

- * - * @author Michael Pih (pihman@arsdigita.com) - * @version $Revision$ $Date$ - * @version $Id$ - */ -public abstract class PageResolver { - - private BigDecimal m_sectionID; - - // Used for caching pages - private HashMap m_pages; - - - public PageResolver() { - m_pages = new HashMap(); - } - - public void setContentSectionID(BigDecimal id) { - m_sectionID = id; - } - - protected BigDecimal getContentSectionID() { - return m_sectionID; - } - - - /** - * Fetch the page associated with the request URL. - * - * @param url The content section-relative URL stub - * @return The resource - */ - public ResourceHandler getPage(String url) { - return (ResourceHandler) m_pages.get(url); - } - - /** - * Register a page to the content section. - * - * @param page The master page - * @param url The desired URL of the page - */ - public abstract void registerPage(ResourceHandler page, String url); - - - /** - * Register a page to the content section. - * - * @param page The master page - * @param url The desired URL of the page - */ - public abstract void unregisterPage(ResourceHandler page, String url); - - - /** - * Loads a page into the page resolver cache. - * - * @param url The URL of the resource to load into the cache - * @param page The resource - */ - public void loadPage(String url, ResourceHandler page) { - m_pages.put(url, page); - } - - /** - * Flushes a page from the page resolver cache. - * - * @param url The URL of the resource to remove from the cache - */ - public void releasePage(String url) { - m_pages.remove(url); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ResourceHandler.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ResourceHandler.java deleted file mode 100755 index 72efec6dd..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ResourceHandler.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.dispatcher.Dispatcher; - -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; - - -/** - * An interface for resources that can be served. - * - * @author Michael Pih (pihman@arsdigita.com) - * @version $Revision$ $DateTime: 2004/08/17 23:15:09 $ - * @version $Id$ - **/ -public interface ResourceHandler extends Dispatcher { - - /** - * This method is called by the {@link com.arsdigita.dispatcher.Dispatcher} - * that initializes this page. - */ - public void init() throws ServletException; - - /** - * Fetches the content section context for this resource. - * - * @param request The HTTP request - * @return A content section or null if there is none - * @pre ( request != null ) - */ - public ContentSection getContentSection(HttpServletRequest request); - - /** - * Fetches the content item context for this resource. - * - * @param request The HTTP request - * @return A content item or null if there is none - * @pre ( request != null ) - */ - public ContentItem getContentItem(HttpServletRequest request); - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ResourceHandlerImpl.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ResourceHandlerImpl.java deleted file mode 100755 index 5ba96df8a..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/ResourceHandlerImpl.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.dispatcher.RequestContext; -import com.arsdigita.util.Assert; - -import org.apache.shiro.authz.AuthorizationException; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * An interface for resources that can be served. - * - * @author Michael Pih (pihman@arsdigita.com) - * @version $Revision$ $DateTime: 2004/08/17 23:15:09 $ - * @version $Id$ - * - */ -public abstract class ResourceHandlerImpl implements ResourceHandler { - - /** - * This method is called by the {@link com.arsdigita.dispatcher.Dispatcher} - * that initializes this page. - */ - public void init() throws ServletException { - // Do nothing. - } - - /** - * Fetch the request-local content section. - * - * @param request The HTTP request - * - * @return The current content section - */ - public ContentSection getContentSection(HttpServletRequest request) { - // resets all content sections associations - ContentSection section = CMSDispatcher.getContentSection(request); - Assert.exists(section); - return section; - } - - /** - * Fetch the request-local content item. - * - * @param request The HTTP request - * - * @return The current content item - */ - public ContentItem getContentItem(HttpServletRequest request) { - // resets all content item associations - return CMSDispatcher.getContentItem(request); - } - - public void checkUserAccess(HttpServletRequest request, - HttpServletResponse response, - RequestContext actx, - ContentItem item) { - if (!CdiUtil.createCdiUtil().findBean(PermissionChecker.class) - .isPermitted(ItemPrivileges.VIEW_PUBLISHED, item)) { - throw new AuthorizationException( - "cms.dispatcher.no_permission_to_access_resource"); - } - } - - /** - * Services this resource. - * - * @param request The servlet request object - * @param response the servlet response object - * @param actx The request context - */ - public abstract void dispatch(HttpServletRequest request, - HttpServletResponse response, - RequestContext actx) - throws IOException, ServletException; - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/SimpleXMLGenerator.java.off b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/SimpleXMLGenerator.java.off deleted file mode 100755 index 29e87838c..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/SimpleXMLGenerator.java.off +++ /dev/null @@ -1,445 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.CMSConfig; -import com.arsdigita.cms.ContentItem; -import com.arsdigita.cms.ContentItemXMLRenderer; -import com.arsdigita.cms.ExtraXMLGenerator; -import com.arsdigita.cms.SecurityManager; -import com.arsdigita.cms.UserDefinedContentItem; -import com.arsdigita.cms.XMLDeliveryCache; -import com.arsdigita.cms.util.GlobalizationUtil; -import com.arsdigita.domain.DataObjectNotFoundException; -import com.arsdigita.domain.DomainObjectFactory; -import com.arsdigita.domain.DomainObjectTraversal; -import com.arsdigita.domain.SimpleDomainObjectTraversalAdapter; -import com.arsdigita.kernel.Kernel; -import com.arsdigita.kernel.Party; -import com.arsdigita.kernel.permissions.PermissionDescriptor; -import com.arsdigita.kernel.permissions.PermissionService; -import com.arsdigita.kernel.permissions.PrivilegeDescriptor; -import com.arsdigita.metadata.DynamicObjectType; -import com.arsdigita.persistence.OID; -import com.arsdigita.persistence.metadata.Property; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.xml.Element; -import org.apache.log4j.Logger; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - *

The default XMLGenerator implementation.

- * - * @author Michael Pih - * @version $Revision: #20 $ $DateTime: 2004/08/17 23:15:09 $ - * @version $Id: SimpleXMLGenerator.java 2167 2011-06-19 21:12:12Z pboy $ - */ -public class SimpleXMLGenerator implements XMLGenerator { - - private static final Logger s_log = Logger.getLogger(SimpleXMLGenerator.class); - public static final String ADAPTER_CONTEXT = SimpleXMLGenerator.class.getName(); - /** - * jensp 2011-10-23: Sometimes the extra XML is not needed, for example - * when embedding the XML of a content item into the XML output of another - * content item. The default value {@code true}. To change the value - * call {@link #setUseExtraXml(booelan)} after creating an instance of - * your generator. - */ - private boolean useExtraXml = true; - /** - * jensp 2012-04-18: This value is forwarded to this ExtraXMLGenerators - * by calling {@link ExtraXMLGenerator#setListMode(boolean)}. The behavior - * triggered by this value depends on the specific implementation of - * the {@code ExtraXMLGenerator} - */ - private boolean listMode = false; - /** - * Extra attributes for the cms:item element. - */ - private final Map itemAttributes = new LinkedHashMap(); - /** - * Allows to overwrite the name and the namespace of the XML element - * used to wrap the rendered item. - */ - private String itemElemName = "cms:item"; - private String itemElemNs = CMS.CMS_XML_NS; - - // Register general purpose adaptor for all content items - static { - s_log.debug("Static initializer starting..."); - final SimpleDomainObjectTraversalAdapter adapter = new SimpleDomainObjectTraversalAdapter(); - adapter.addAssociationProperty("/object/type"); - adapter.addAssociationProperty("/object/categories"); - - DomainObjectTraversal.registerAdapter( - ContentItem.BASE_DATA_OBJECT_TYPE, - adapter, - ADAPTER_CONTEXT); - s_log.debug("Static initializer finished"); - } - - public SimpleXMLGenerator() { - super(); - } - - public void setUseExtraXml(final boolean useExtraXml) { - this.useExtraXml = useExtraXml; - } - - public void setListMode(final boolean listMode) { - this.listMode = listMode; - } - - public void addItemAttribute(final String name, final String value) { - itemAttributes.put(name, value); - } - - public void setItemElemName(final String itemElemName, final String itemElemNs) { - this.itemElemName = itemElemName; - this.itemElemNs = itemElemNs; - } - - /** - * Generates the XML to render the content panel. - * - * @param state The page state - * @param parent The parent DOM element - * @param useContext The use context - */ - @Override - public void generateXML(final PageState state, final Element parent, final String useContext) { - //final long start = System.nanoTime(); - - //ContentSection section = CMS.getContext().getContentSection(); - ContentItem item = getContentItem(state); - - s_log.info("Generate XML for item " + item.getOID()); - - Party currentParty = Kernel.getContext().getParty(); - if (currentParty == null) { - currentParty = Kernel.getPublicUser(); - } - // check if current user can edit the current item (nb privilege is granted on draft item, but live item - // has draft as its permission context - // - // Note that the xml that is generated is only of use if you DO NOT CACHE content pages. - // cg. - final PermissionDescriptor edit = new PermissionDescriptor( - PrivilegeDescriptor.get(SecurityManager.CMS_EDIT_ITEM), item, currentParty); - if (PermissionService.checkPermission(edit)) { - parent.addAttribute("canEdit", "true"); - final Element canEditElem = parent.newChildElement("canEdit"); - canEditElem.setText("true"); - - } - final PermissionDescriptor publish = new PermissionDescriptor( - PrivilegeDescriptor.get(SecurityManager.CMS_PUBLISH), item, currentParty); - if (PermissionService.checkPermission(publish)) { - parent.addAttribute("canPublish", "true"); - } - final String className = item.getDefaultDomainClass(); - - // Ensure correct subtype of ContentItem is instantiated - if (!item.getClass().getName().equals(className)) { - s_log.info("Specializing item"); - try { - item = (ContentItem) DomainObjectFactory.newInstance( - new OID(item.getObjectType().getQualifiedName(), item.getID())); - } catch (DataObjectNotFoundException ex) { - throw new UncheckedWrapperException( - (String) GlobalizationUtil.globalize( - "cms.dispatcher.cannot_find_domain_object").localize(), - ex); - } - } - - // Implementing XMLGenerator directly is now deprecated - if (item instanceof XMLGenerator) { - s_log.info("Item implements XMLGenerator interface"); - final XMLGenerator xitem = (XMLGenerator) item; - xitem.generateXML(state, parent, useContext); - - } else if ("com.arsdigita.cms.UserDefinedContentItem".equals(className)) { - s_log.info("Item is a user defined content item"); - final UserDefinedContentItem UDItem = (UserDefinedContentItem) item; - generateUDItemXML(UDItem, state, parent, useContext); - - } else { - s_log.info("Item is using DomainObjectXMLRenderer"); - - // This is the preferred method - //final Element content = startElement(useContext, parent); - final Element content = startElement(useContext); - s_log.debug("Item is not in cache, generating item."); - - final XMLDeliveryCache xmlCache = XMLDeliveryCache.getInstance(); - - if (CMSConfig.getInstanceOf().getEnableXmlCache() && xmlCache.isCached(item.getOID(), useContext, listMode)) { - xmlCache.retrieveFromCache(content, item.getOID(), useContext, listMode); - } else { - final ContentItemXMLRenderer renderer = new ContentItemXMLRenderer(content); - - renderer.setWrapAttributes(true); - renderer.setWrapRoot(false); - renderer.setWrapObjects(false); - renderer.setRevisitFullObject(true); - - //System.out.printf("Prepared renderer in %d ms\n", (System.nanoTime() - start) - // / 1000000); - - renderer.walk(item, ADAPTER_CONTEXT); - - //System.out.printf("Rendered standard item xml in %d ms\n", (System.nanoTime() - start) - // / 1000000); - - //parent.addContent(content); - - //Only item XML Cache End - -// s_log.debug("Content elem content: "); -// logElementTree(content); -// s_log.debug("Content elem content end -- "); - - - /* - * 2011-08-27 jensp: Introduced to remove the annoying special templates - * for MultiPartArticle, SiteProxy and others. The method called - * here was already definied but not used. - * - * 2011-10-23 jensp: It is now possible to disable the use of - * extra XML. - */ - //final long extraXMLStart = System.nanoTime(); - if (useExtraXml) { - for (ExtraXMLGenerator generator : item.getExtraXMLGenerators()) { - generator.setListMode(listMode); - generator.generateXML(item, content, state); - } - } - - //Only published items - //Only the XML of the item itself, no extra XML - if (CMSConfig.getInstanceOf().getEnableXmlCache() && item.isLiveVersion()) { - xmlCache.cache(item.getOID(), item, content, useContext, listMode); - } - } - - if (PermissionService.checkPermission(edit)) { - final ItemResolver resolver = item.getContentSection().getItemResolver(); - final Element editLinkElem = content.newChildElement("editLink"); - final ContentItem draftItem = item.getDraftVersion(); - editLinkElem.setText(resolver.generateItemURL(state, - draftItem, - item.getContentSection(), - draftItem.getVersion())); - } - - parent.addContent(content); - - //System.out.printf("Rendered item in %d ms\n\n", (System.nanoTime() - start) / 1000000); - } - } - - /** - * Fetches the current content item. This method can be overridden to - * fetch any {@link com.arsdigita.cms.ContentItem}, but by default, - * it fetches the ContentItem that is set in the page state - * by the dispatcher. - * - * @param state The page state - * @return A content item - */ - protected ContentItem getContentItem(final PageState state) { - if (CMS.getContext().hasContentItem()) { - return CMS.getContext().getContentItem(); - } else { - final CMSPage page = (CMSPage) state.getPage(); - return page.getContentItem(state); - } - } - - protected void generateUDItemXML(final UserDefinedContentItem UDItem, - final PageState state, - final Element parent, - final String useContext) { - - final Element element = startElement(useContext, parent); - final Element additionalAttrs = UDItemElement(useContext); - - element.addAttribute("type", UDItem.getContentType().getName()); - element.addAttribute("id", UDItem.getID().toString()); - element.addAttribute("name", UDItem.getName()); - element.addAttribute("title", UDItem.getTitle()); - element.addAttribute("javaClass", UDItem.getContentType().getClassName()); - - final DynamicObjectType dot = new DynamicObjectType(UDItem.getSpecificObjectType()); - final Iterator declaredProperties = - dot.getObjectType().getDeclaredProperties(); - Property currentProperty; - Object value; - while (declaredProperties.hasNext()) { - currentProperty = (Property) declaredProperties.next(); - value = (Object) UDItem.get(currentProperty.getName()); - if (value != null) { - element.addContent( - UDItemAttrElement(currentProperty.getName(), - value.toString())); - } else { - element.addContent( - UDItemAttrElement(currentProperty.getName(), - "none specified")); - } - } - - //element.addContent(additionalAttrs); - //parent.addContent(element); - - } - - private Element startElement(final String useContext, final Element parent) { - //Element element = new Element("cms:item", CMS.CMS_XML_NS); - //final Element element = new Element(itemElemName, itemElemNs); - final Element element = parent.newChildElement(itemElemName, itemElemNs); - if (useContext != null) { - element.addAttribute("useContext", useContext); - } - - for (Map.Entry attr : itemAttributes.entrySet()) { - element.addAttribute(attr.getKey(), attr.getValue()); - } - - return element; - } - - private Element startElement(final String useContext) { - final Element element = new Element(itemElemName, itemElemNs); - - if (useContext != null) { - element.addAttribute("useContext", useContext); - } - - for (Map.Entry attr : itemAttributes.entrySet()) { - element.addAttribute(attr.getKey(), attr.getValue()); - } - - return element; - } - - private Element startCachedElement(final String useContext) { - final Element element = new Element(itemElemName, itemElemNs) { - @Override - public Element newChildElement(Element copyFrom) { - s_log.debug("Copy of element added to cached elem."); - return super.newChildElement(copyFrom); - } - - @Override - public Element newChildElement(String name, Element copyFrom) { - s_log.debug("Copy of element added to cached elem."); - return super.newChildElement(name, copyFrom); - } - - @Override - public Element addContent(final Element newContent) { - s_log.debug("Content added to cached element"); - return super.addContent(newContent); - } - - }; - - if (useContext != null) { - element.addAttribute("useContext", useContext); - } - - for (Map.Entry attr : itemAttributes.entrySet()) { - element.addAttribute(attr.getKey(), attr.getValue()); - } - - return element; - } - - private void copyElement(final Element parent, final Element element) { - final Element copy = parent.newChildElement(element.getName()); - final Iterator attrs = element.getAttributes().entrySet().iterator(); - Map.Entry attr; - while (attrs.hasNext()) { - attr = (Map.Entry) attrs.next(); - copy.addAttribute((String) attr.getKey(), (String) attr.getValue()); - } - - final Iterator childs = element.getChildren().iterator(); - while (childs.hasNext()) { - copyElement(copy, (Element) childs.next()); - } - - if (element.getText() != null) { - copy.setText(element.getText()); - } - - if (element.getCDATASection() != null) { - copy.setCDATASection(element.getCDATASection()); - } - - } - - private Element UDItemElement(final String useContext) { - final Element element = new Element("cms:UDItemAttributes", CMS.CMS_XML_NS); - /* - if ( useContext != null ) { - element.addAttribute("useContext", useContext); - } - */ - return element; - } - - private Element UDItemAttrElement(final String name, final String value) { - final Element element = new Element("cms:UDItemAttribute", CMS.CMS_XML_NS); - element.addAttribute("UDItemAttrName", name); - element.addAttribute("UDItemAttrValue", value); - return element; - } - - private void logElementTree(final Element element) { - s_log.debug("Tree of element" + element.getName() + ":\n"); - s_log.debug("\n" + logElementTree(element, new StringBuilder(), 0)); - } - - private String logElementTree(final Element element, final StringBuilder builder, final int depth) { - for (int i = 0; i < depth; i++) { - builder.append('\t'); - } - builder.append('<').append(element.getName()).append(">\n"); - - for (Object childObj : element.getChildren()) { - final Element child = (Element) childObj; - logElementTree(child, builder, depth + 1); - } - - for (int i = 0; i < depth; i++) { - builder.append('\t'); - } - builder.append("\n"); - return builder.toString(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/TemplateResolver.java.off b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/TemplateResolver.java.off deleted file mode 100755 index cd38be0bc..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/TemplateResolver.java.off +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import javax.servlet.http.HttpServletRequest; - -/** - * Reimplementation, based on ItemTemplateResolver - * - *

- * Many sites offer alternative views of the same content item depending on - * device or browser, or on user preference. For example, a site may have - * "plain" and "fancy" versions of its pages. The fancy versions would be the - * defaults, while the plain versions would be appropriate for users with - * low-bandwidth connections, older browsers, or a distaste for flashy - * appurtenances. In this the case the selection might be made based on a - * cookie.

- * - *

- * Another common example is the "printable" version of a page. In this case a - * query variable might be more appropriate.

- * - * - * @author Karl Goldstein (karlg@arsdigita.com) - * @version $Id: TemplateResolver.java 1967 2009-08-29 21:05:51Z pboy $ - * - */ -public interface TemplateResolver { - - /** - * Returns the JSP template filename relative to the webapp root. - * - * @param section The ContentSection for the request - * @param item The ContentItem for the request - * @param request The current HttpServletRequest - * - * @return The path to the jsp template. - */ - public String getTemplate(ContentSection section, - ContentItem item, - HttpServletRequest request); - - /** - * Returns the JSP template filename relative to the webapp root for a given - * Template reference. - * - * @param template The Template to resolve the URL for. - * - * @return The path to the jsp template. - */ - public String getTemplatePath(Template template); - - /** - * Returns the XSL template filename relative to the webapp root for a given - * Template reference. - * - * @param template The Template to resolve the URL for. - * - * @return The path to the xsl template. - */ - public String getTemplateXSLPath(Template template); - - /** - * Sets the TemplateContext parameter in the request - * - * @param sTemplateContext the template context to set - * @param request the request in which to set the template context - */ - public void setTemplateContext(String sTemplateContext, - HttpServletRequest request); - - /** - * Gets the template context from the request. - * - * @param request the request from which to get the template context - * - * @return the template context - */ - public String getTemplateContext(HttpServletRequest request); - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/Utilities.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/Utilities.java deleted file mode 100755 index 4a2956d50..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/Utilities.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.cms.CMS; -import com.arsdigita.dispatcher.DispatcherHelper; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.servlet.http.HttpServletResponse; - -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.librecms.CmsConstants; -import org.librecms.assets.BinaryAsset; -import org.librecms.assets.Image; -import org.librecms.contentsection.ContentSection; - -/** - *

- * This class provides many utility functions for the Content Management - * System.

- * Specifically used by various JSP templates. - * - * @author Michael Pih (pihman@arsdigita.com) - */ -public class Utilities { - - public static final Logger LOGGER = LogManager.getLogger(Utilities.class); - - // Used for caching util lookups - private static HashMap m_cache = new HashMap(); - - private static Date s_lastSectionRefresh = null; - private static Map s_sectionRefreshTimes = Collections.synchronizedMap( - new HashMap()); - - /** - * Fetch the location of the CMS ContentCenter package. - * - * @return The URL of the CMS ContentCenter package - * - * @deprecated use ContentCenter.getURL() instead - */ - public static String getWorkspaceURL() { - - return CmsConstants.CONTENT_CENTER_URL; - - } - - /** - * Fetch the location (URL) of the CMS Services package. Caches the result. - * - * @return The URL of the CMS Services package - * - * @deprecated Use Service.getURL( instead - */ - public static String getServiceURL() { - String url = (String) m_cache.get(CmsConstants.SERVICE_PACKAGE_KEY); - if (url == null) { - // chris.gilbert@westsussex.gov.uk - // We don't want application context in this url, especially when - // it gets cached in a static variable - if I have a - // file that is maintained by a non cms application eg - // forum, then I can end up with a url that doesn't work - // and so breaks file links everywhere - // url = getSingletonPackageURLSansContext(CMS.SERVICE_PACKAGE_KEY); - url = CmsConstants.SERVICE_URL; - m_cache.put(CmsConstants.SERVICE_PACKAGE_KEY, url); - } - - return url; - } - - /** - * The URL to log out. - * - * @return The logout URL - */ - public static String getLogoutURL() { - //StringBuffer buf = new StringBuffer(getServiceURL()); - StringBuilder buf = new StringBuilder(CmsConstants.SERVICE_URL); - buf.append("logout"); - return buf.toString(); - } - - /** - * Construct a URL which serves a binary asset. - * - * @param asset The binary asset - * - * @return the URL which will serve the specified binary asset - * - * @deprecated Use Service.getAssetURL(BinaryAsset asset) instead - */ - public static String getAssetURL(BinaryAsset asset) { - return getAssetURL(asset.getObjectId()); - } - - /** - * Constuct a URL which serves a binary asset. - * - * @param assetId The asset ID - * - * @return the URL which will serve the specified binary asset - * - * @deprecated Use Service.getAssetURL(BigDecimal assetId) instead - */ - public static String getAssetURL(long assetId) { - // StringBuffer buf = new StringBuffer(getServiceURL()); - StringBuilder buf = new StringBuilder(CmsConstants.SERVICE_URL); - buf.append("stream/asset?"); - buf.append(CmsConstants.ASSET_ID).append("=").append(assetId); - return buf.toString(); - } - - /** - * Construct a URL which serves an image. - * - * @param asset The image asset whose image is to be served - * - * @return the URL which will serve the specified image asset - * - * @deprecated Use Service.getImageURL(ImageAsset) instead! - */ - public static String getImageURL(Image asset) { - // StringBuffer buf = new StringBuffer(getServiceURL()); - StringBuilder buf = new StringBuilder(CmsConstants.SERVICE_URL); - buf.append("stream/image/?"); - buf.append(CmsConstants.IMAGE_ID).append("=") - .append(asset.getObjectId()); - return buf.toString(); - } - - public static String getGlobalAssetsURL() { - return getWebappContext(); - } - - /** - * Fetch the context path of the request. This is typically "/". - * - * @return The webapp context path - */ - public static String getWebappContext() { - return DispatcherHelper.getWebappContext(); - } - - /** - * Check for the last refresh on authoring kits or content types in a - * section. - * - */ - public static synchronized Date - getLastSectionRefresh(ContentSection section) { - - // cache by URL string instead of by section object to avoid - // holding the reference. - String sectionURL = section.getPrimaryUrl(); - - Date lastModified = (Date) s_sectionRefreshTimes.get(sectionURL); - if (lastModified == null) { - lastModified = new Date(); - s_lastSectionRefresh = lastModified; - s_sectionRefreshTimes.put(sectionURL, lastModified); - } - - return lastModified; - } - - /** - * Check for the last refresh on authoring kits or content types in any - * section. - * - */ - public static Date getLastSectionRefresh() { - - // instantiate last refresh lazily to ensure that first result is - // predictable. - if (s_lastSectionRefresh == null) { - s_lastSectionRefresh = new Date(); - } - return s_lastSectionRefresh; - } - - /** - * Force the authoring UI to reload. This should be done every time an - * authoring kit or a content type are updated. - */ - public static void refreshItemUI(PageState state) { - // Drop the authoring kit UI to force it to refresh - // THE URL SHOULD NOT BE HARDCODED ! - - ContentSection section = CMS.getContext().getContentSection(); - - // OLD APPROACH: used in conjunction with CMSDispatcher. This - // shouldn't do any harm even if CMSDispatcher is not being used. - CMSDispatcher.releaseResource(section, "admin/item"); - refreshAdminUI(state); - - // NEW APPROACH: used in conjunction with - // ContentSectionDispatcher. cache by URL string instead of by - // section object to avoid holding the reference. This shouldn't - // do any harm even if ContentSectionDispatcher is not being used. - s_lastSectionRefresh = new Date(); - s_sectionRefreshTimes.put(section.getPrimaryUrl(), - s_lastSectionRefresh); - } - - /** - * Force the authoring UI to reload. This should be done every time an - * authoring kit or a content type are updated. - */ - public static void refreshAdminUI(PageState state) { - // Drop the admin UI to force it to refresh - // THE URL SHOULD NOT BE HARDCODED ! - - ContentSection section = CMS.getContext().getContentSection(); - - CMSDispatcher.releaseResource(section, "admin"); - CMSDispatcher.releaseResource(section, "admin/index"); - CMSDispatcher.releaseResource(section, ""); - } - - /** - * Add the "pragma: no-cache" header to the HTTP response to make sure the - * browser does not cache tha page - * - * @param response The HTTP response - * - * @deprecated use - * com.arsdigita.dispatcher.DispatcherHelper.cacheDisable(HttpServletResponse) - */ - public static void disableBrowserCache(HttpServletResponse response) { - response.addHeader("pragma", "no-cache"); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/XMLGenerator.java b/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/XMLGenerator.java deleted file mode 100755 index dabc5e599..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/dispatcher/XMLGenerator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.dispatcher; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.xml.Element; - - -/** - *

Generates XML representing a Content Item.

- * - *

As the last step of servicing a page, the - * {@link com.arsdigita.cms.dispatcher.MasterPage} will go through the - * hierarchy of its components and ask each of them to convert themselves - * to XML. A MasterPage contains a special component that knows how to ask - * its content section for the XML generator that should be applied. The - * XML generator's generateXML method in turn asks the - * containing page for the content item, the one that the - * {@link com.arsdigita.cms.dispatcher.ItemResolver} found before, and - * formats it as an XML document.

- * - * @author Michael Pih (pihman@arsdigita.com) - * @version $Id$ - */ -public interface XMLGenerator { - - /** - * Generates the XML to render the content panel. - * - * @param state The page state - * @param parent The parent DOM element - * @param useContext The use context - */ - public void generateXML(PageState state, Element parent, String useContext); - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/lifecycle/Duration.java b/ccm-cms/src/main/java/com/arsdigita/cms/lifecycle/Duration.java deleted file mode 100755 index 4ece2dcfe..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/lifecycle/Duration.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.lifecycle; - -import com.arsdigita.util.Assert; - -/** - * Utility methods for lifecycle durations. - * - * @author Michael Pih - * @author 0) { - buffer.append(dhm[0]).append(" days"); - } - - if (dhm[1] > 0) { - if (dhm[0] > 0) { - buffer.append(", "); - } - buffer.append(dhm[1]).append(" hours"); - } - - if (dhm[0] > 0 || dhm[1] > 0) { - buffer.append(", "); - } - buffer.append(dhm[2]).append(" minutes"); - - return buffer.toString(); - } - - /** - * Formats time in minutes longo a days/hours/minutes format. - * - * @param minutes - * @return - */ - public static long[] formatDHM(final long minutes) { - long[] dhm = new long[3]; - - long days = minutes / (60 * 24); - long hours = minutes / 60; // no pun longended - long mins = minutes; - - if (days > 0) { - hours -= (days * 24); - mins -= (days * 24 * 60); - } - if (hours > 0) { - mins -= (hours * 60); - } - - dhm[0] = days; - dhm[1] = hours; - dhm[2] = mins; - return dhm; - } - - /** - * Formats time in minutes longo a days/hours/minutes format. - * - * @return - * @see #formatDHM(long) - * @param minutes timespan in minutes - */ - public static Long[] formatDHM(final Long minutes) { - long dhm[] = formatDHM(minutes.longValue()); - return copyArray(dhm); - } - - private static Long[] copyArray(long[] from) { - Assert.exists(from, "from"); - Long[] to = new Long[from.length]; - for (int ii = 0; ii < from.length; ii++) { - to[ii] = from[ii]; - } - return to; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseAdminPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseAdminPane.java deleted file mode 100755 index 56b689a10..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseAdminPane.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.bebop.tree.TreeModelBuilder; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.SelectionPanel; - -import org.librecms.CmsConstants; - -/** - * A base component for use in CMS admin panes. - * - * @param Type managed by the {@link SingleSelectionModel} used by instances - * of this class. - * - * @author Justin Ross <jross@redhat.com> - */ -public abstract class BaseAdminPane extends SelectionPanel { - - protected BaseAdminPane() { - super(); - } - - protected BaseAdminPane(final Component title, - final Component selector) { - super(title, selector); - } - - protected BaseAdminPane(final GlobalizedMessage title, - final Component selector) { - super(title, selector); - } - - protected BaseAdminPane(final Component title, - final Component selector, - final SingleSelectionModel model) { - super(title, selector, model); - } - - protected BaseAdminPane(final GlobalizedMessage title, - final Component selector, - final SingleSelectionModel model) { - super(title, selector, model); - } - - protected BaseAdminPane(final Component title, - final ListModelBuilder builder) { - super(title, builder); - } - - protected BaseAdminPane(final GlobalizedMessage title, - final ListModelBuilder builder) { - super(title, builder); - } - - protected BaseAdminPane(final Component title, - final TreeModelBuilder builder) { - super(title, builder); - } - - protected BaseAdminPane(final GlobalizedMessage title, - final TreeModelBuilder builder) { - super(title, builder); - } - - protected static GlobalizedMessage gz(final String key) { - return new GlobalizedMessage(key, CmsConstants.CMS_BUNDLE); - } - - protected static String lz(final String key) { - return (String) gz(key).localize(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseDeleteForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseDeleteForm.java deleted file mode 100755 index 65adf39f8..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseDeleteForm.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.globalization.GlobalizedMessage; - -/** - * @author Justin Ross - */ -public abstract class BaseDeleteForm extends BaseForm - implements FormProcessListener { - - protected final Submit m_delete; - protected final Submit m_cancel; - - public BaseDeleteForm(final Component message) { - super("delete", new Label(gz("cms.ui.attention"))); - - addComponent(message); - - m_delete = new Submit("delete", gz("cms.ui.delete")); - addAction(m_delete); - - m_cancel = new Submit("cancel", gz("cms.ui.cancel")); - addAction(m_cancel); - - addProcessListener(this); - } - - public BaseDeleteForm(final GlobalizedMessage message) { - this(new Label(message)); - } - - @Override - public final boolean isCancelled(final PageState state) { - return m_cancel.isSelected(state); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseForm.java deleted file mode 100755 index 9c69fd08a..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseForm.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.GridPanel; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.form.FormErrorDisplay; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.NotEmptyValidationListener; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.parameters.StringLengthValidationListener; -import com.arsdigita.bebop.parameters.TrimmedStringParameter; -import com.arsdigita.cms.ui.item.ContentItemRequestLocal; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.Cancellable; -import com.arsdigita.toolbox.ui.Section; -import com.arsdigita.util.Assert; - -import org.librecms.CmsConstants; - -/** - * A convenience class for CMS forms. - * - * @author Jens Pelzetter - * @author Justin Ross - */ -public abstract class BaseForm extends Form implements Cancellable { - - private final BodySection m_body; - private final BoxPanel m_actions; - private Cancel m_cancel; - - protected BaseForm(final String name, final Label heading) { - super(name, new GridPanel(1)); - - setRedirecting(true); - - m_body = new BodySection(heading); - m_actions = new BoxPanel(BoxPanel.HORIZONTAL); - - add(m_body); - add(m_actions); - - addComponent(new FormErrorDisplay(this)); - } - - protected BaseForm(final String name, - final GlobalizedMessage heading) { - this(name, new Label(heading)); - } - - private class BodySection extends Section { - - final SimpleContainer m_container; - - BodySection(final Label heading) { - setHeading(heading); - - m_container = new GridPanel(2); - setBody(m_container); - } - - final void add(final Component component) { - m_container.add(component); - } - - final void add(final Component component, int hints) { - m_container.add(component, hints); - } - - } - - protected final void addComponent(final Component component) { - m_body.add(component, GridPanel.FULL_WIDTH); - } - - protected final void addField(final Label name, final Component widget) { - m_body.add(name); - m_body.add(widget); - } - - protected final void addField(final GlobalizedMessage name, - final Component widget) { - addField(new Label(name), widget); - } - - protected final void addAction(final Submit button) { - m_actions.add(button); - } - - protected final void addAction(final Cancel button) { - m_cancel = button; - m_actions.add(button); - } - - protected final void addSecurityListener(final String action) { - addSubmissionListener(new FormSecurityListener(action)); - } - - protected final void addSecurityListener(final String action, - final ContentItemRequestLocal item) { - addSubmissionListener(new FormSecurityListener(action, item)); - } - - @Override - public boolean isCancelled(final PageState state) { - return m_cancel != null && m_cancel.isSelected(state); - } - - protected final class Name extends TextField { - - public Name(final String key, final int max, final boolean required) { - super(new TrimmedStringParameter(key)); - - if (required) { - addValidationListener(new NotEmptyValidationListener()); - } - - setSize(40); - setMaxLength(max); - } - - } - - protected final class Description extends TextArea { - - public Description(final String key, - final int maxLength, - final boolean isRequired) { - super(new TrimmedStringParameter(key)); - Assert.isTrue(maxLength > 0, "Max length cannot be negative"); - - if (isRequired) { - addValidationListener(NotNullValidationListener.DEFAULT); - } - addValidationListener(new StringLengthValidationListener(maxLength)); - setCols(40); - setRows(5); - setWrap(TextArea.SOFT); - } - - } - - protected final class Finish extends Submit { - - public Finish() { - super("finish", gz("cms.ui.finish")); - } - - } - - protected final class Cancel extends Submit { - - public Cancel() { - super("cancel", gz("cms.ui.cancel")); - } - - } - - protected static final GlobalizedMessage gz(final String key) { - return new GlobalizedMessage(key, CmsConstants.CMS_BUNDLE); - } - - protected static final String lz(final String key) { - return (String) gz(key).localize(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseItemPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseItemPane.java deleted file mode 100755 index 9e9ec1a4d..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseItemPane.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.ModalPanel; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.librecms.CmsConstants; - -/** - * @author Justin Ross - * @author Jens Pelzetter - */ -public abstract class BaseItemPane extends ModalPanel { - - private static final Logger LOGGER = LogManager.getLogger - (BaseItemPane.class); - - protected BaseItemPane() { - super(); - } - - protected final static GlobalizedMessage gz(final String key) { - return new GlobalizedMessage(key, CmsConstants.CMS_BUNDLE); - } - - protected final static String lz(final String key) { - return (String) gz(key).localize(); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseTree.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseTree.java deleted file mode 100755 index 81940c8c2..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/BaseTree.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Tree; -import com.arsdigita.bebop.event.ChangeEvent; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.event.TreeExpansionEvent; -import com.arsdigita.bebop.event.TreeExpansionListener; -import com.arsdigita.bebop.tree.TreeModelBuilder; - -/** - * A convenience class for CMS trees. - * - * @author Justin Ross <jross@redhat.com> - */ -public class BaseTree extends Tree { - - public BaseTree(final TreeModelBuilder builder) { - super(builder); - - addChangeListener(new Change()); - addTreeExpansionListener(new TreeExpansion()); - } - - private class Change implements ChangeListener { - public final void stateChanged(final ChangeEvent e) { - final PageState state = e.getPageState(); - final Object key = BaseTree.this.getSelectedKey(state); - - if (key != null) { - expand(key.toString(), state); - } - } - } - - private class TreeExpansion implements TreeExpansionListener { - public final void treeExpanded(final TreeExpansionEvent e) { - //s_log.error("expanded"); - } - - public final void treeCollapsed(final TreeExpansionEvent e) { - //s_log.error("collapsed"); - } - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/BrowsePane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/BrowsePane.java deleted file mode 100755 index f16a37f45..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/BrowsePane.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Link; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.SegmentedPanel; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.Tree; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.tree.TreeCellRenderer; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.ui.folder.FolderRequestLocal; -import com.arsdigita.cms.ui.folder.FolderSelectionModel; -import com.arsdigita.cms.ui.folder.FolderTreeModelBuilder; -import com.arsdigita.cms.ui.folder.FolderTreeModelController; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.LayoutPanel; -import com.arsdigita.util.Assert; - -import org.libreccm.categorization.Category; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.CcmObject; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionManager; -import org.librecms.contentsection.Folder; -import org.librecms.dispatcher.ItemResolver; - -import java.util.List; - -/** - * A pane that contains a folder tree on the left and a folder manipulator on - * the right. It is a part of the content section main page and is displayed as - * the "Browse" tab. - * - * @author David LutterKort <dlutter@redhat.com> - * @author Jens Pelzetter - */ -public class BrowsePane extends LayoutPanel implements Resettable { - - private final BaseTree tree; - private final SingleSelectionModel selectionModel; - private final FolderSelectionModel folderModel; // To support legacy UI code - private final FolderRequestLocal folderRequestLocal; - private final FlatItemList flatItemList; - - public BrowsePane() { - - /* The folder tree displayed on the left side / left column */ - tree = new BaseTree(new FolderTreeModelBuilder() { - - @Override - protected Folder getRootFolder(final PageState state) { - final ContentSection section = CMS - .getContext() - .getContentSection(); - return section.getRootDocumentsFolder(); - } - - }); - selectionModel = tree.getSelectionModel(); - folderModel = new FolderSelectionModel(selectionModel) { - - @Override - protected Long getRootFolderID(final PageState state) { - final ContentSection section = CMS - .getContext() - .getContentSection(); - return section.getRootDocumentsFolder().getObjectId(); - } - - }; - folderRequestLocal = new FolderRequestLocal(folderModel); - - final SegmentedPanel left = new SegmentedPanel(); - setLeft(left); - - final Label heading = new Label( - new GlobalizedMessage("cms.ui.folder_browser", - CmsConstants.CMS_BUNDLE)); - left.addSegment(heading, tree); - - flatItemList = new FlatItemList(folderRequestLocal, folderModel); - setBody(flatItemList); - - flatItemList.getManipulator().getItemView().addProcessListener( - new ProcessListener()); - flatItemList.getManipulator().getTargetSelector().addProcessListener( - new ProcessListener()); - flatItemList.getManipulator().getTargetSelector().addSubmissionListener( - new SubmissionListener()); - } - - @Override - public final void register(final Page page) { - super.register(page); - - page.addActionListener(new FolderListener()); - page.addActionListener(new TreeListener()); - } - - @Override - public final void reset(final PageState state) { - super.reset(state); - - flatItemList.reset(state); - } - - // Private classes and methods - /** - * - */ - private final class ProcessListener implements FormProcessListener { - - @Override - public final void process(final FormSectionEvent event) { - final PageState state = event.getPageState(); - - if (event.getSource() == flatItemList.getManipulator().getItemView()) { - // Hide everything except for the flat item list - tree.setVisible(state, false); - } else if (event.getSource() == flatItemList.getManipulator() - .getTargetSelector()) { - tree.setVisible(state, true); - } - } - - } - - private final class SubmissionListener implements FormSubmissionListener { - - @Override - public final void submitted(final FormSectionEvent event) { - final PageState state = event.getPageState(); - - if (event.getSource() == flatItemList.getManipulator() - .getTargetSelector()) { - if (!flatItemList.getManipulator().getTargetSelector() - .isVisible(state)) { - tree.setVisible(state, true); - } - } - } - - } - - private final class FolderListener implements ActionListener { - - @Override - public final void actionPerformed(final ActionEvent event) { - final PageState state = event.getPageState(); - - if (!selectionModel.isSelected(state)) { - final String folder = state - .getRequest() - .getParameter(ContentSectionPage.SET_FOLDER); - - if (folder == null) { - final Category root = CMS - .getContext() - .getContentSection() - .getRootDocumentsFolder(); - final Long folderID = root.getObjectId(); - - /* - ToDo - User user = Web.getWebContext().getUser(); - if (user != null) { - Folder homeFolder = Folder.getUserHomeFolder( - user, CMS.getContext().getContentSection()); - if (homeFolder != null) { - folderID = homeFolder.getID(); - } - - }*/ - selectionModel.setSelectedKey(state, folderID); - } else { - selectionModel.setSelectedKey(state, Long.parseLong(folder)); - } - } - } - - } - - private final class TreeListener implements ActionListener { - - @Override - public final void actionPerformed(final ActionEvent event) { - final PageState state = event.getPageState(); - - final Category root = CMS - .getContext() - .getContentSection() - .getRootDocumentsFolder(); - - if (!root.equals(folderRequestLocal.getFolder(state))) { - // Expand the ancestor nodes of the currently - // selected node. - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderTreeModelController controller = cdiUtil.findBean( - FolderTreeModelController.class); - final List ancestorIds = controller.findAncestorIds( - folderRequestLocal.getFolder(state)); - ancestorIds.forEach(id -> tree.expand(id.toString(), state)); - - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/CMSApplicationPage.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/CMSApplicationPage.java deleted file mode 100644 index a39a58456..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/CMSApplicationPage.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * 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 com.arsdigita.cms.ui; - -import com.arsdigita.bebop.BebopConfig; -import com.arsdigita.bebop.Container; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.page.PageTransformer; -import com.arsdigita.cms.dispatcher.Utilities; -import com.arsdigita.templating.PresentationManager; -import com.arsdigita.xml.Document; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.Shiro; -import org.libreccm.security.User; -import org.libreccm.web.CcmApplication; - -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * A CMSApplicationPage is a Bebop {@link com.arsdigita.bebop.Page} - * implementation serving as a base for any CMS pageElement served by a servlet. - * - * It stores the current {@link com.arsdigita.cms.ContentSection} and, if - * applicable, the {@link com.arsdigita.cms.ContentItem} in the pageElement - * state as request local objects. Components that are part of the - * CMSPage may access these objects by calling: - *
- *     getContentSection(PageState state);
- * 
- * - * @author Michael Pih (pihman@arsdigita.com) - * @author Uday Mathur (umathur@arsdigita.com) - * @author Jens Pelzetter - */ -public class CMSApplicationPage extends Page { - - private static final Logger LOGGER = LogManager.getLogger( - CMSApplicationPage.class); - - /** - * The global assets URL stub XML parameter name. - */ - public final static String ASSETS = "ASSETS"; - - /** - * The XML pageElement class. - */ - public final static String PAGE_CLASS = "CMS"; - - /** - * Map of XML parameters - */ - private Map parameters; - - /** - * - */ - private PageTransformer pageTransformer; - - public CMSApplicationPage() { - super(); - buildPage(); - } - - public CMSApplicationPage(final String title) { - super(title); - buildPage(); - } - - public CMSApplicationPage(final String title, final Container panel) { - super(title, panel); - buildPage(); - } - - public CMSApplicationPage(final Label title) { - super(title); - buildPage(); - } - - public CMSApplicationPage(final Label title, final Container panel) { - super(title, panel); - buildPage(); - } - - /** - * Builds the pageElement. - */ - private void buildPage() { - - // Set the class attribute value (down in SimpleComponent). - setClassAttr(PAGE_CLASS); - - // Global XML params. - // MP: This only works with older versions of Xalan. - parameters = new HashMap<>(); - setXMLParameter(ASSETS, Utilities.getGlobalAssetsURL()); - - // MP: This is a hack to so that the XML params work with the newer - // version of Xalan. - setAttribute(ASSETS, Utilities.getGlobalAssetsURL()); - - // Make sure the error display gets rendered. - getErrorDisplay().setIdAttr("page-body"); - - final Class presenterClass = BebopConfig - .getConfig() - .getPresenterClass(); - final PresentationManager presenter; - try { - presenter = presenterClass.getDeclaredConstructor().newInstance(); - } catch (InstantiationException - | IllegalAccessException - | NoSuchMethodException - | InvocationTargetException ex) { - throw new RuntimeException("Failed to create PresentationManager", - ex); - } - - if (presenter instanceof PageTransformer) { - pageTransformer = (PageTransformer) presenter; - } else { - pageTransformer = new PageTransformer(); - } - } - - /** - * Finishes and locks the pageElement. If the pageElement is already locked, - * does nothing. - * - * Client classes may overwrite this method to add context specific bits to - * the page before it is locked. - * - * This method is called by the various servlets serving the various pages - * of the CMS package, before serving and displaying the page. - * - * @param request - * @param response - * @param app - */ - public synchronized void init(final HttpServletRequest request, - final HttpServletResponse response, - final CcmApplication app) { - LOGGER.debug("Initializing the page"); - - if (!isLocked()) { - LOGGER.debug("The page hasn't been locked; locking it now"); - - lock(); - } - } - - /** - * Fetches the value of the XML parameter. - * - * @param name The parameter name - * - * @return The parameter value - * - * @pre (name != null) - */ - public String getXMLParameter(final String name) { - return parameters.get(name); - } - - /** - * Set an XML parameter. - * - * @param name The parameter name - * @param value The parameter value - * - * @pre (name != null) - */ - public void setXMLParameter(String name, String value) { - parameters.put(name, value); - } - - /** - * Overwrites bebop.Page#generateXMLHelper to add the name of the user - * logged in to the pageElement (displayed as part of the header). - * - * @param state - * @param parent - * - * @return pageElement for use in generateXML - */ - @Override - protected Element generateXMLHelper(final PageState state, - final Document parent) { - - /* Retain elements already included. */ - Element pageElement = super.generateXMLHelper(state, parent); - - /* Add name of user logged in. */ - // Note: There are at least 2 ways in the API to determin the user - // TODO: Check for differences, determin the best / recommended way and - // document it in the classes. Probably remove one ore the other - // way from the API if possible. - final Shiro shiro = CdiUtil.createCdiUtil().findBean(Shiro.class); - final Optional user = shiro.getUser(); - // User user = Web.getWebContext().getUser(); - if (user.isPresent()) { - pageElement.addAttribute("name", user.get().getName()); - } - - return pageElement; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/CMSContainer.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/CMSContainer.java deleted file mode 100755 index e9b898b2a..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/CMSContainer.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.SimpleContainer; - - - -/** - * A simple container with XML wrapper tags. - * - * @author Michael Pih (pihman@arsdigita.com) - * @version $Id$ - */ -public class CMSContainer extends SimpleContainer { - - public final static String CMS_XML_NS = "http://www.arsdigita.com/cms/1.0"; - - - public CMSContainer() { - super("cms:container", CMS_XML_NS); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/CMSDHTMLEditor.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/CMSDHTMLEditor.java deleted file mode 100755 index f26d5d37f..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/CMSDHTMLEditor.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.form.DHTMLEditor; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.CMS; - -import org.librecms.CMSConfig; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.contentsection.ContentSection; - -/** - * - * - */ -public class CMSDHTMLEditor extends DHTMLEditor { - - public CMSDHTMLEditor(final String name) { - super(new StringParameter(name), - CMSConfig.getConfig().getDHTMLEditorConfig()); - addPlugins(); - hideButtons(); - - final ContentSection section = CMS.getContext().getContentSection(); - final GlobalizationHelper globalizationHelper = CdiUtil - .createCdiUtil() - .findBean(GlobalizationHelper.class); - setAttribute("current-contentsection-id", - Long.toString(section.getObjectId())); - setAttribute("current-contentsection-primaryurl", - section.getPrimaryUrl()); - setAttribute("current-contentsection-title", - globalizationHelper - .getValueFromLocalizedString(section.getTitle())); - - } - - public CMSDHTMLEditor(final ParameterModel model) { - super(model, - CMSConfig.getConfig().getDHTMLEditorConfig()); - - addPlugins(); - hideButtons(); - } - - private void addPlugins() { - - CMSConfig - .getConfig() - .getDhtmlEditorPlugins() - .forEach(plugin -> addPlugin(plugin)); - } - - private void hideButtons() { - - CMSConfig - .getConfig() - .getDhtmlEditorHiddenButtons() - .forEach(hiddenButton -> hideButton(hiddenButton)); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/CMSForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/CMSForm.java deleted file mode 100755 index 782190e37..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/CMSForm.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.Container; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.PageState; -import com.arsdigita.toolbox.ui.Cancellable; - -/** - * A convenience class for CMS forms. The "CMS Admin" class eliminates - * the nested tables created by the Bebop ColumnPanel. This is mainly - * to increase form rendering. - * - * @author Michael Pih - */ -public class CMSForm extends Form implements Cancellable { - - public static final String CLASS = "CMS Admin"; - - public CMSForm(final String name) { - super(name); - - setClassAttr(CLASS); - getPanel().setClassAttr(CLASS); - } - - public CMSForm(final String name, final Container panel) { - super(name, panel); - - setClassAttr(CLASS); - panel.setClassAttr(CLASS); - } - - /** - * Determines whether the form has been cancelled. - * Override this method if the form can be cancelled. - * - * @param state The page state - * @return true if the form is cancelled, false otherwise - */ - @Override - public boolean isCancelled(final PageState state) { - return false; - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/CategoryForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/CategoryForm.java deleted file mode 100755 index 5b4a66e00..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/CategoryForm.java +++ /dev/null @@ -1,481 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.*; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.OptionGroup; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.parameters.BigDecimalParameter; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.bebop.util.SequentialMap; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.ui.authoring.BasicItemForm; -import com.arsdigita.globalization.Globalization; -import com.arsdigita.util.StringUtils; -import com.arsdigita.util.UncheckedWrapperException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.CcmObject; - -import javax.enterprise.inject.spi.CDI; -import java.math.BigDecimal; -import java.util.*; - -/** - * This is an abstract class which displays the category assignment UI. - * - * Displays two listboxes for assigning categories to items, with two - * submit buttons to move categories back and forth. The left - * listbox displays all available categories which have not been - * assigned to the current item. The right listbox displays all categories - * assigned to the current item. - *

- * - * - * @author Stanislav Freidin (sfreidin@arsdigita.com) - * @author Yannick Bülter - */ -public abstract class CategoryForm extends Form - implements FormProcessListener, FormValidationListener { - - private static final Logger LOGGER = LogManager.getLogger( - CategoryForm.class); - private static final String SEPARATOR = ">"; - public static final String FREE = "free"; - public static final String ASSIGNED = "assigned"; - public static final String ASSIGN = "assign"; - public static final String REMOVE = "remove"; - public static final int SELECT_WIDTH = 30; - public static final int SELECT_HEIGHT = 10; - public static final String FILLER_OPTION = StringUtils.repeat("_", SELECT_WIDTH); - - private final RequestLocal m_assigned; - private Submit m_assign, m_remove; - - private final Label m_freeLabel; - private final Label m_assignedLabel; - - /** - * Construct a new CategoryForm component - * - * @param name the name of the form - */ - public CategoryForm(String name) { - super(name, new ColumnPanel(3)); - - ColumnPanel panel = (ColumnPanel) getPanel(); - panel.setBorder(false); - panel.setPadColor("#FFFFFF"); - panel.setColumnWidth(1, "0%"); - panel.setColumnWidth(2, "0%"); - panel.setColumnWidth(3, "0"); - panel.setWidth("0%"); - panel.setClassAttr("CMS Admin"); - - // Create the request local - m_assigned = new RequestLocal() { - - @Override - public Object initialValue(PageState state) { - CategoryMap m = new CategoryMap(); - initAssignedCategories(state, m); - return m; - } - }; - - // Top row - m_freeLabel = new Label(GlobalizationUtil.globalize("cms.ui.item.categories.available"), false); - m_freeLabel.setFontWeight(Label.BOLD); - add(m_freeLabel, ColumnPanel.LEFT); - - //add(new Label(" ", false)); - add(new Embedded(" ", false)); - - m_assignedLabel = new Label(GlobalizationUtil.globalize("cms.ui.item.categories.assigned"), false); - m_assignedLabel.setFontWeight(Label.BOLD); - add(m_assignedLabel, ColumnPanel.LEFT); - - // Middle Row - SingleSelect freeWidget = new SingleSelect(new BigDecimalParameter(FREE)); - try { - freeWidget.addPrintListener(new FreePrintListener()); - } catch (TooManyListenersException e) { - UncheckedWrapperException.throwLoggedException(getClass(), "Too many listeners", e); - } - freeWidget.setSize(SELECT_HEIGHT); - add(freeWidget); - - BoxPanel box = new BoxPanel(BoxPanel.VERTICAL, true); - box.setWidth("2%"); - addSubmitButtons(box); - add(box, ColumnPanel.CENTER | ColumnPanel.MIDDLE); - - SingleSelect assignedWidget = - new SingleSelect(new BigDecimalParameter(ASSIGNED)); - try { - assignedWidget.addPrintListener(new AssignedPrintListener()); - } catch (TooManyListenersException e) { - UncheckedWrapperException.throwLoggedException(getClass(), "Too many listeners", e); - } - assignedWidget.setSize(SELECT_HEIGHT); - add(assignedWidget); - - // Add listeners - addProcessListener(this); - addValidationListener(this); - - setClassAttr("CategoryForm"); - } - - protected void addSubmitButtons(Container c) { - addAssignButton(c); - addRemoveButton(c); - } - - protected void addAssignButton(Container c) { - m_assign = new Submit(ASSIGN, ">>"); - m_assign.setSize(10); - c.add(m_assign); - } - - protected void addRemoveButton(Container c) { - m_remove = new Submit(REMOVE, "<<"); - m_remove.setSize(10); - c.add(m_remove); - } - - /** - * Set the caption of the unassigned categories label - * - * @param caption the new caption - */ - public void setUnassignedCaption(String caption) { - m_freeLabel.setLabel(caption); - } - - /** - * Set the caption of the assigned categories label - * - * @param caption the new caption - */ - public void setAssignedCaption(String caption) { - m_assignedLabel.setLabel(caption); - } - - /** - * @param s the page state - * @return a {@link CategoryMap} of all assigned categories - */ - public CategoryMap getAssignedCategories(PageState s) { - return (CategoryMap) m_assigned.get(s); - } - - // A print listener which populates the listbox with all - // unassigned categories, apart from result of getExcludedCategory() - // (if not null), and the root category. - // Ordering is alphabetical based on qualified path, so entries are - // ordered like a tree with all nodes expanded. - // Ideally ordering should be like an expanded tree but based on - // the sortkey order of the categories. However, I don't know - // if it would be possible to write a comparison function that - // could do this efficiently, and I'm not even going to try - // chris.gilbert@westsussex.gov.uk - // - private class FreePrintListener implements PrintListener { - - @Override - public void prepare(PrintEvent e) { - - OptionGroup target = (OptionGroup) e.getTarget(); - target.clearOptions(); - PageState state = e.getPageState(); -// Category root = getRootCategory(state); -// if (root == null) { -// return; -// } - - // exclude children of the excluded category (as per javadoc on - // getExcludedCategory() method. This prevents attempts - // to create circular category graph (which causes - // exception in Category during addMapping if not checked here - Category excludedCat = getExcludedCategory(state); - CategoryMap excluded = new CategoryMap(); - if (excludedCat != null) { - java.util.List excludedSubTree = getExcludedCategory(state).getSubCategories(); - excludedSubTree.forEach(excluded::add); - } - CategoryMap assigned = getAssignedCategories(state); - SortedMap sortedCats = new TreeMap(); -// java.util.List children = root.getSubCategories(); -// children.forEach(x -> sortedCats.put(x.getName(), x.getUniqueId())); - - Iterator it = sortedCats.entrySet().iterator(); - Map.Entry entry; - String path; - String id; - boolean notExcluded; - boolean notAlreadyAssigned; -// boolean notRoot; - - while (it.hasNext()) { - entry = (Map.Entry) it.next(); - path = (String) entry.getKey(); - id = (String) entry.getValue(); - - notExcluded = !excluded.containsKey(id); - notAlreadyAssigned = !assigned.containsKey(id); -// notRoot = !id.equals(root.getUniqueId()); - - if (notExcluded && notAlreadyAssigned) {// && notRoot) { - target.addOption(new Option(id, new Text(path))); - } - - } - - addFillerOption(target); - } - } - - /** - * Populate a {@link CategoryMap} with all categories which are assigned to - * the item. Child classes should override this method to do the right thing. - * - * @param map The sequential map of all categories which are assigned to - * the current item. Overridden method should repeatedly - * call map.addCategory(someCategory); - * @param state The page state - */ - protected abstract void initAssignedCategories(PageState state, CategoryMap map); - - /** - * Assign a category, moving it from the list on the left - * to the list on the right - * - * @param s the page state - * @param cat the category to assign - */ - protected abstract void assignCategory(PageState s, Category cat); - - /** - * Unassign a category, moving it from the list on the right - * to the list on the left - * - * @param s the page state - * @param cat the category to unassign - */ - protected abstract void unassignCategory(PageState s, Category cat); - - /** - * This method returns the URL for the givne item to make sure that - * the item it is not possible to have two objects in the same category - * with the same URL. - * @param state The Page State - */ - protected abstract String getItemURL(PageState state); - - /** - * This allows the validation code to validate the properties of the - * object - */ - protected abstract CcmObject getObject(PageState state); - - /** - * Get the category which will act as the root for the lists - * of assigned and unassigned categories. The default implementation - * returns the root category for the content section. Child classes - * should override this method if they wish to provide an alternate root category. - * - * @param state the page state - * @return the root category which should be used to populate the lists - * of assigned and unassigned categories - */ -// public Category getRootCategory(PageState state) { -// return null; -// return CMS.getContext().getContentSection().getRootCategory(); -// } - - /** - * Return a category which should be excluded from the list of - * free categories. It is permissible to return null - * - * @param s the page state - * @return a category whose subtree will not be shown in the - * category list - */ - protected Category getExcludedCategory(PageState s) { - return null; - } - - // Populates the "assigned categories" widget - @Deprecated - private class AssignedPrintListener implements PrintListener { - - @Override - public void prepare(PrintEvent e) { - OptionGroup o = (OptionGroup) e.getTarget(); - o.clearOptions(); - PageState state = e.getPageState(); - CategoryMap m = getAssignedCategories(state); - - if (!m.isEmpty()) { - for (Iterator i = m.values().iterator(); i.hasNext();) { - Category c = (Category) i.next(); - o.addOption(new Option(c.getUniqueId(), new Text(getCategoryPath(c)))); - } - } else { - o.addOption(new Option("", new Text("-- none --"))); - } - - addFillerOption(o); - } - } - - // Process the form: assign/unassign categories - @Override - public void process(FormSectionEvent e) throws FormProcessException { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryRepository categoryRepository = cdiUtil.findBean(CategoryRepository.class); - - PageState state = e.getPageState(); - FormData data = e.getFormData(); - Long id; - - if (m_assign.isSelected(state)) { - id = ((BigDecimal) data.get(FREE)).longValue(); - Optional optional = categoryRepository.findById(id); - if (optional.isPresent()) { - Category cat = optional.get(); - assignCategory(state, cat); - data.put(ASSIGNED, id); - } else { - throw new FormProcessException(GlobalizationUtil.globalize(String.format("Can't find category with id %d", id))); - } - } else if (m_remove.isSelected(state)) { - id = ((BigDecimal) data.get(ASSIGNED)).longValue(); - Optional optional = categoryRepository.findById(id); - if (optional.isPresent()) { - Category cat = optional.get(); - unassignCategory(state, cat); - data.put(FREE, id); - } else { - throw new FormProcessException(GlobalizationUtil.globalize(String.format("Can't find category with id %d", id))); - } - } - } - - // Validate the form: make sure that a category is selected - // for the remove/assign buttons - @Override - public void validate(FormSectionEvent e) throws FormProcessException { - PageState state = e.getPageState(); - FormData data = e.getFormData(); - if (m_assign.isSelected(state)) { - if (data.get(FREE) == null) { - data.addError(GlobalizationUtil.globalize("cms.ui.category.assign_select_missing")); - } else { - // we need to make sure that no other item in this - // category has the same name (url) - Long id = ((BigDecimal) data.get(FREE)).longValue(); - - // Assign a new category -// try { -// String url = getItemURL(state); -// -// if (url != null) { -// DataQuery query = SessionManager.getSession().retrieveQuery("com.arsdigita.categorization.getAllItemURLsForCategory"); -// query.setParameter("categoryID", id); -// query.addEqualsFilter("lower(url)", url.toLowerCase()); -// -// if (query.size() > 0) { -// // we need to make sure that there is not an item -// ACSObject item = getObject(state); -// Collection list; -// if (item instanceof ContentItem) { -// list = BasicItemForm.getAllVersionIDs((ContentItem) item); -// } else { -// list = new ArrayList(); -// list.add(item.getID()); -// } -// BigDecimal itemID; -// while (query.next()) { -// itemID = (BigDecimal) query.get("itemID"); -// if (!list.contains(itemID)) { -// data.addError("There is already an item " -// + "with the url " + url -// + " in the category " -// + cat.getName()); -// break; -// } -// } -// } -// } -// } catch (DataObjectNotFoundException ex) { -// s_log.error("Error processing category. Unable to find " -// + "category with id " + id); -// throw new FormProcessException(ex); -// } - } - } else if (m_remove.isSelected(state)) { - if (data.get(ASSIGNED) == null) { - data.addError(GlobalizationUtil.globalize("cms.ui.category.assign_select_missing")); - } - } - } - - // Add a "filler" option to the option group in order to ensure - // the correct horizontal width - private static void addFillerOption(OptionGroup o) { - o.addOption(new Option("", FILLER_OPTION)); - } - - /** - * @return the full path to a category - */ - public static String getCategoryPath(Category c) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager categoryManager = cdiUtil.findBean(CategoryManager.class); - return categoryManager.getCategoryPath(c); - } - - /** - * A convenience method that abstracts SequentialMap - * to deal with categories - */ - protected static class CategoryMap extends SequentialMap { - - public CategoryMap() { - super(); - } - - public void add(Category c) { - super.put(c.getUniqueId(), c); - } - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/CcmObjectRequestLocal.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/CcmObjectRequestLocal.java deleted file mode 100755 index 204e60c85..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/CcmObjectRequestLocal.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; - -import org.libreccm.core.CcmObject; - - -public class CcmObjectRequestLocal extends RequestLocal { - - public final CcmObject getACSObject(final PageState state) { - return (CcmObject) get(state); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentItemContextBar.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentItemContextBar.java deleted file mode 100755 index ea833518b..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentItemContextBar.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.CMS; - -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.PageLocations; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.web.ParameterMap; -import com.arsdigita.web.URL; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentItemL10NManager; - -import java.util.List; -import java.util.Locale; - -/** - *

- * The context bar of the content section UI.

- * - * @author Justin Ross - * @author Jens Pelzetter - */ -class ContentItemContextBar extends ContentSectionContextBar { - - private final ItemSelectionModel itemSelectionModel; - private final StringParameter selectedLanguageParam; - - ContentItemContextBar(final ItemSelectionModel itemSelectionModel, - final StringParameter selectedLanguageParam) { - super(); - - this.itemSelectionModel = itemSelectionModel; - this.selectedLanguageParam = selectedLanguageParam; - } - - @Override - protected final List entries(final PageState state) { - final List entries = super.entries(state); - final ContentItem item = itemSelectionModel.getSelectedObject(state); - final ContentSection section = CMS.getContext().getContentSection(); - - final URL url = URL.there(state.getRequest(), - section.getPrimaryUrl() + "/" - + PageLocations.ITEM_PAGE, - params(item)); - - final StringBuilder title = new StringBuilder(); - title.append(localize("cms.ui.content_item")); - title.append(": ") - .append(item.getDisplayName()); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemL10NManager l10nManager = cdiUtil - .findBean(ContentItemL10NManager.class); - final String selectedLanguage = (String) state - .getValue(selectedLanguageParam); - final Locale selectedLocale; - if (selectedLanguage == null - || selectedLanguage.isEmpty()) { - selectedLocale = KernelConfig.getConfig().getDefaultLocale(); - } else { - selectedLocale = new Locale(selectedLanguage); - } - - final String language; - if (l10nManager.hasLanguage(item, selectedLocale)) { - language = selectedLanguage; - } else { - state.setValue(selectedLanguageParam, - KernelConfig.getConfig().getDefaultLanguage()); - language = KernelConfig.getConfig().getDefaultLanguage(); - } - if (language != null) { - title.append(" (") - .append(language) - .append(")"); - } - - entries.add(new Entry(title.toString(), url)); - - return entries; - } - - private static ParameterMap params(final ContentItem item) { - final ParameterMap params = new ParameterMap(); - - params.setParameter(ContentItemPage.ITEM_ID, item.getObjectId()); - - return params; - } - - private static String localize(final String key) { - return (String) ContentSectionPage.globalize(key).localize(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentItemPage.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentItemPage.java deleted file mode 100755 index fbbec5045..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentItemPage.java +++ /dev/null @@ -1,698 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Link; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.TabbedPane; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.PageLocations; -import com.arsdigita.cms.dispatcher.CMSPage; -import com.arsdigita.cms.ui.authoring.WizardSelector; -import com.arsdigita.cms.ui.item.ContentItemRequestLocal; -import com.arsdigita.cms.ui.item.CustomizedPreviewLink; -import com.arsdigita.cms.ui.item.ItemLanguages; -import com.arsdigita.cms.ui.item.Summary; -import com.arsdigita.cms.ui.lifecycle.ItemLifecycleAdminPane; -import com.arsdigita.cms.ui.revision.ItemRevisionAdminPane; -import com.arsdigita.cms.ui.templates.ItemTemplates; -import com.arsdigita.cms.ui.workflow.ItemWorkflowAdminPane; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.kernel.ui.ACSObjectSelectionModel; -import com.arsdigita.util.Assert; -import com.arsdigita.xml.Document; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.librecms.CMSConfig; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemL10NManager; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentItemVersion; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentType; - -import java.io.IOException; -import java.util.Locale; -import java.util.Objects; -import java.util.Optional; - -import javax.servlet.http.HttpServletRequest; - -/** - * Page for administering a content item. - * - * @author Michael Pih - * @author Stanislav Freidin - * @author Jack Chung - * @author Sören Bernstein - * @author Jens Pelzetter - * - */ -public class ContentItemPage extends CMSPage implements ActionListener { - - /** - * Private Logger instance for debugging purpose. - */ - private static final Logger LOGGER = LogManager.getLogger( - ContentItemPage.class); - /** - * The URL parameter that must be passed in in order to set the current tab. - * This is a KLUDGE right now because the TabbedDialog's current tab is - * selected with a local state parameter - */ - public static final String SET_TAB = "set_tab"; - /** - * The name of the global state parameter that holds the item id. - */ - public static final String ITEM_ID = "item_id"; - /** - * The name of th global state parameter that holds the selected language. - */ - public static final String SELECTED_LANGUAGE = "selected_language"; - /** - * The name of the global state parameter which holds the return URL. - */ - public static final String RETURN_URL = "return_url"; - /** - * The name of the global state parameter that determines whether or not to - * use the streamlined authoring process (assuming the option is turned on). - * - */ - public static final String STREAMLINED_CREATION = "streamlined_creation"; - public static final String STREAMLINED_CREATION_ACTIVE = "active"; - public static final String STREAMLINED_CREATION_INACTIVE = "active"; - /** - * Index of the summary tab - */ - public static final int SUMMARY_TAB = 0; - /** - *

- * The name of the state parameter which indicates the content type of the - * item the user wishes to create. or edit.

- * - *

- * The parameter must be a BigDecimalParameter which encodes the id of the - * content type.

- */ - public static final String CONTENT_TYPE = "content_type"; - public static final int AUTHORING_TAB = 1; - public static final int LANGUAGE_TAB = 2; - public static final int WORKFLOW_TAB = 3; - public static final int PUBLISHING_TAB = 4; - public static final int HISTORY_TAB = 5; - public static final int TEMPLATES_TAB = 6; - - private final TabbedPane tabbedPane; - private final StringParameter returnUrlParameter; - private final ItemSelectionModel itemSelectionModel; -// private final SingleSelectionModel selectedLanguageModel; - private final ACSObjectSelectionModel typeSelectionModel; - private final ContentItemRequestLocal itemRequestLocal; - private final Summary summaryPane; - private final ItemWorkflowAdminPane workflowPane; - private final ItemLifecycleAdminPane lifecyclePane; - private final WizardSelector wizardPane; - private final ItemLanguages languagesPane; - private final ItemRevisionAdminPane revisionsPane; - private final ItemTemplates templatesPane; - private final Link previewLink; - private final GlobalNavigation globalNavigation; - private final ContentItemContextBar contextBar; - - private final StringParameter selectedLanguageParam; - - private class ItemRequestLocal extends ContentItemRequestLocal { - - @Override - protected final Object initialValue(final PageState state) { - return CMS.getContext().getContentItem(); - } - - } - - private class TitlePrinter implements PrintListener { - - @Override - public final void prepare(final PrintEvent event) { - - final PageState state = event.getPageState(); - - final Label label = (Label) event.getTarget(); - final ContentItem item = itemRequestLocal.getContentItem(event. - getPageState()); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemL10NManager l10nManager = cdiUtil - .findBean(ContentItemL10NManager.class); - final String selectedLanguage = (String) state - .getValue(selectedLanguageParam); - final Locale selectedLocale; - if (selectedLanguage == null - || selectedLanguage.isEmpty()) { - selectedLocale = KernelConfig.getConfig().getDefaultLocale(); - } else { - selectedLocale = new Locale(selectedLanguage); - } - - final String language; - if (l10nManager.hasLanguage(item, selectedLocale)) { - language = selectedLanguage; - } else { - state.setValue(selectedLanguageParam, - KernelConfig.getConfig().getDefaultLanguage()); - language = KernelConfig.getConfig().getDefaultLanguage(); - } - - final StringBuffer title = new StringBuffer(item.getDisplayName()); - if (language != null) { - title - .append(" (") - .append(language) - .append(")"); - } - - label.setLabel(title.toString()); - } - - } - - /** - * Constructs a new ContentItemPage. - */ - public ContentItemPage() { - super("", new SimpleContainer()); - - itemRequestLocal = new ItemRequestLocal(); - - setClassAttr("cms-admin"); - setTitle(new Label(new TitlePrinter())); - - // Add the item id global state parameter - final LongParameter itemId = new LongParameter(ITEM_ID); - itemId.addParameterListener(new NotNullValidationListener(ITEM_ID)); - addGlobalStateParam(itemId); - itemSelectionModel = new ItemSelectionModel(itemId); - - // Add the selected item language as parameter - selectedLanguageParam = new StringParameter(SELECTED_LANGUAGE); - selectedLanguageParam.addParameterListener( - new NotNullValidationListener(SELECTED_LANGUAGE)); - addGlobalStateParam(selectedLanguageParam); -// selectedLanguageModel = new ParameterSingleSelectionModel<>( -// selectedLanguageParam); -// selectedLanguageParam -// .setDefaultValue(KernelConfig.getConfig().getDefaultLanguage()); - - // Add the content type global state parameter - final LongParameter contentType = new LongParameter(CONTENT_TYPE); - addGlobalStateParam(contentType); - - // Add the streamlined creation global state parameter - final StringParameter streamlinedCreation = new StringParameter( - STREAMLINED_CREATION); - addGlobalStateParam(streamlinedCreation); - - typeSelectionModel = new ACSObjectSelectionModel(ContentType.class - .getName(), - ContentType.class - .getName(), - contentType); - - // Validate the item ID parameter (caches the validation). - getStateModel().addValidationListener( - event -> validateItemID(event.getPageState())); - - // Add the return url global state parameter - returnUrlParameter = new StringParameter(RETURN_URL); - addGlobalStateParam(returnUrlParameter); - - globalNavigation = new GlobalNavigation(); - add(globalNavigation); - - contextBar = new ContentItemContextBar(itemSelectionModel, - selectedLanguageParam); - add(contextBar); - - // Create panels. - summaryPane = new Summary(itemSelectionModel); - wizardPane = new WizardSelector(itemSelectionModel, typeSelectionModel); - languagesPane = new ItemLanguages(itemSelectionModel, -// selectedLanguageModel, - selectedLanguageParam); - workflowPane = new ItemWorkflowAdminPane(itemId); // Make this use m_item XXX - lifecyclePane = new ItemLifecycleAdminPane(itemRequestLocal); - revisionsPane = new ItemRevisionAdminPane(itemRequestLocal); - templatesPane = new ItemTemplates(itemSelectionModel); - - // Create tabbed pane. - tabbedPane = new TabbedPane(); - add(tabbedPane); - - tabbedPane.setIdAttr("page-body"); - - tabbedPane.addTab(new Label(gz("cms.ui.item.summary")), summaryPane); - tabbedPane. - addTab(new Label(gz("cms.ui.item.authoring")), wizardPane); - tabbedPane.addTab(new Label(gz("cms.ui.item.languages")), - languagesPane); - tabbedPane.addTab(new Label(gz("cms.ui.item.workflow")), - workflowPane); - tabbedPane.addTab(new Label(gz("cms.ui.item.lifecycles")), - lifecyclePane); - tabbedPane.addTab(new Label(gz("cms.ui.item.history")), - revisionsPane); - tabbedPane.addTab(new Label(gz("cms.ui.item.templates")), - templatesPane); - - tabbedPane.addActionListener(new ActionListener() { - - @Override - public final void actionPerformed(final ActionEvent event) { - - final PageState state = event.getPageState(); - final Component pane = tabbedPane.getCurrentPane(state); - - if (pane instanceof Resettable) { - ((Resettable) pane).reset(state); - } - } - - }); - - // Build the preview link. - previewLink = new Link(new Label(gz("cms.ui.preview")), - new PrintListener() { - - @Override - public final void prepare( - final PrintEvent event) { - final Link link = (Link) event.getTarget(); - link.setTarget(getPreviewURL(event. - getPageState())); - link.setTargetFrame(Link.NEW_FRAME); - } - - }); - previewLink.setIdAttr("preview_link"); - add(previewLink); - - addActionListener(this); - - // Add validation to make sure we are not attempting to edit a live item - getStateModel().addValidationListener(new FormValidationListener() { - - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - - PageState s = event.getPageState(); - FormData data = event.getFormData(); - final ContentItem item = itemRequestLocal.getContentItem(s); - if (item != null - && ContentItemVersion.LIVE == item.getVersion()) { - LOGGER.error(String.format( - "The item %d is live and cannot be edited.", item. - getObjectId())); - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.live_item_not_editable", - CmsConstants.CMS_BUNDLE)); - } - } - - }); - } - - /** - * Ensures that the item_id parameter references a valid {@link - * com.arsdigita.cms.ContentItem}. - * - * @param state The page state - * - * @pre state != null - * @exception FormProcessException if the item_id is not valid - */ - protected void validateItemID(final PageState state) throws - FormProcessException { - final ContentItem item = itemRequestLocal.getContentItem(state); - - if (item == null) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.invalid_item_id", CmsConstants.CMS_BUNDLE)); - } - } - - /** - * Fetch the request-local content section. - * - * @deprecated use com.arsdigita.cms.CMS.getContext().getContentSection() - * instead - * @param request The HTTP request - * - * @return The current content section - */ - @Override - public ContentSection getContentSection(final HttpServletRequest request) { - // Resets all content sections associations. - ContentSection section = super.getContentSection(request); - Assert.exists(section); - return section; - } - - /** - * Overrides CMSPage.getContentItem(PageState state) to get the current - * content item from the page state. - * - * @deprecated Use the ItemSelectionModel - * @param state The page state - * - * @return The current content item, null if there is none - */ - @Override - public ContentItem getContentItem(final PageState state) { - return (ContentItem) itemSelectionModel.getSelectedObject(state); - } - - /** - * Set the current tab, if necessary - * - * @param event - */ - @Override - public void actionPerformed(final ActionEvent event) { - final PageState state = event.getPageState(); - final String setTab = state.getRequest().getParameter(SET_TAB); - - // Hide the templates tab, the workflow tab, and the preview - // link if the current item is a template. - final ContentItem item = itemRequestLocal.getContentItem(state); - - // ToDo: Reenable when Templates have been ported. Not clear yet if - // Templates will be ContentItems in LibreCMS... -// if (item instanceof Template) { -// tabbedPane.setTabVisible(state, templatesPane, false); -// tabbedPane.setTabVisible(state, workflowPane, false); -// tabbedPane.setTabVisible(state, languagesPane, false); -// m_previewLink.setVisible(state, false); -// } else { -// tabbedPane.setTabVisible(state, -// templatesPane, -// !ContentSectionConfig.getConfig().getHideTemplatesTab()); -// } - // Set the current tab based on parameters - if (setTab != null) { - Integer tab; - - try { - tab = Integer.valueOf(setTab); - } catch (NumberFormatException ex) { - // Stop processing set_tab parameter. - LOGGER.warn("Stopping processing of set_tab parameter.", ex); - return; - } - - if (tab < tabbedPane.size()) { - tabbedPane.setSelectedIndex(state, tab); - } - } - } - - /** - * Construct a URL for displaying a certain item - * - * @param nodeURL The URL where this page is mounted - * @param itemId The id of the item to display - * @param tab The index of the tab to display - * - * @return - */ - public static String getItemURL(final String nodeURL, - final Long itemId, - final int tab) { - return getItemURL(nodeURL, itemId, tab, false); - } - - /** - * Construct a URL for displaying a certain item - * - * @param nodeURL The URL where this page is mounted - * @param itemId The id of the item to display - * @param tab The index of the tab to display - * @param streamlinedCreation Whether to activate Streamlined item authoring - * - * @return - */ - public static String getItemURL(final String nodeURL, - final Long itemId, - final int tab, - final boolean streamlinedCreation) { - final StringBuilder urlBuilder = new StringBuilder(); - - urlBuilder - .append(nodeURL) - .append(PageLocations.ITEM_PAGE) - .append("?") - .append(ITEM_ID) - .append("=") - .append(itemId.toString()) - .append("&") - .append(SET_TAB) - .append("=") - .append(tab); - - if (streamlinedCreation - && CMSConfig.getConfig().isUseStreamlinedCreation()) { - - urlBuilder - .append("&") - .append(STREAMLINED_CREATION) - .append("=") - .append(STREAMLINED_CREATION_ACTIVE); - } - - return urlBuilder.toString(); - } - - /** - * @param itemId - * @param tab - * - * @return - * - * @deprecated Use getItemURL instead - */ - public static String getRelativeItemURL(final Long itemId, final int tab) { - final StringBuilder url = new StringBuilder(); - url - .append(PageLocations.ITEM_PAGE) - .append("?") - .append(ITEM_ID) - .append("=") - .append(itemId.toString()) - .append("&") - .append(SET_TAB) - .append("=") - .append(tab); - - return url.toString(); - } - - /** - * Constructs a URL for displaying a certain item. - * - * @param item the ContentItem object to display - * @param tab The index of the tab to display - * - * @return - */ - public static String getItemURL(final ContentItem item, - final int tab) { - - final ContentSection section = item.getContentType().getContentSection(); - - if (section == null) { - return null; - } else { - final String nodeURL = section.getPrimaryUrl() + "/"; - - return getItemURL(nodeURL, item.getObjectId(), tab); - } - } - - /** - * Constructs a URL for displaying a certain item. - * - * @param itemId the id of the ContentItem object to display - * @param tab The index of the tab to display - * - * @return - */ - public static String getItemURL(final long itemId, - final int tab) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil.findBean( - ContentItemRepository.class); - - final Optional item = itemRepo.findById(itemId); - - if (item.isPresent()) { - return getItemURL(item.get(), tab); - } else { - return null; - } - } - - /** - * Redirect back to wherever the user came from, using the value of the - * return_url parameter. - * - * @param state The current page state - */ - public void redirectBack(final PageState state) { - try { - final String returnUrl = (String) state.getValue(returnUrlParameter); - state.getResponse().sendRedirect(returnUrl); - } catch (IOException ex) { - LOGGER.error("IO Error redirecting back", ex); - // do nothing - } - } - - /** - * Fetch the preview URL. - */ - private String getPreviewURL(final PageState state) { - final ContentItem item = itemRequestLocal.getContentItem(state); - - if (item instanceof CustomizedPreviewLink) { - final String previewLink = ((CustomizedPreviewLink) item). - getPreviewUrl( - state); - if ((previewLink == null) || previewLink.isEmpty()) { - return getDefaultPreviewLink(state, item); - } else { - return previewLink; - } - } else { - return getDefaultPreviewLink(state, item); - } - } - - /** - * - * @param state - * @param item - * - * @return - */ - private String getDefaultPreviewLink(final PageState state, - final ContentItem item) { - final ContentSection section = CMS.getContext().getContentSection(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); -// final ContentSectionManager sectionManager = cdiUtil.findBean( -// ContentSectionManager.class); -// final ItemResolver itemResolver = sectionManager -// .getItemResolver(section); - - // Pass in the "Live" context since we need it for the preview -// return itemResolver.generateItemURL(state, -// item, -// section, -// CMSDispatcher.PREVIEW); - final ContentItemPageController controller = cdiUtil - .findBean(ContentItemPageController.class); - - return controller.getDefaultPreviewLink(section, item, state); - } - - protected final static GlobalizedMessage gz(final String key) { - return new GlobalizedMessage(key, CmsConstants.CMS_BUNDLE); - } - - protected final static String lz(final String key) { - return (String) gz(key).localize(); - } - - public static boolean isStreamlinedCreationActive(final PageState state) { - return CMSConfig.getConfig().isUseStreamlinedCreation() - && STREAMLINED_CREATION_ACTIVE.equals(state.getRequest(). - getParameter(STREAMLINED_CREATION)); - } - - protected TabbedPane getTabbedPane() { - return tabbedPane; - } - - protected WizardSelector getWizardPane() { - return wizardPane; - } - - /** - * Adds the content type to the output. - * - * @param state PageState - * @param parent Parent document - * - * @return page - */ - @Override - protected Element generateXMLHelper(final PageState state, - final Document parent) { - - Objects.requireNonNull(itemRequestLocal.getContentItem(state), - "No ContentItem in current request."); - - final Element page = super.generateXMLHelper(state, parent); - final Element contenttype = page.newChildElement("bebop:contentType", - BEBOP_XML_NS); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - - final ContentItemPageController controller = cdiUtil - .findBean(ContentItemPageController.class); - contenttype - .setText(controller - .getContentTypeLabel(itemRequestLocal.getContentItem(state))); - - return page; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentItemPageController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentItemPageController.java deleted file mode 100644 index 8d504dd12..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentItemPageController.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.cms.dispatcher.CMSDispatcher; - -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionManager; -import org.librecms.contentsection.ContentSectionRepository; -import org.librecms.dispatcher.ItemResolver; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class ContentItemPageController { - - @Inject - private GlobalizationHelper globalizationHelper; - - @Inject - private ContentSectionRepository sectionRepo; - - @Inject - private ContentSectionManager sectionManager; - @Inject - private ContentItemRepository itemRepo; - - @Transactional(Transactional.TxType.REQUIRED) - protected String getContentTypeLabel(final ContentItem item) { - - final ContentItem theItem = itemRepo - .findById(item.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", - item.getObjectId()))); - - return theItem - .getContentType() - .getLabel() - .getValue(globalizationHelper.getNegotiatedLocale()); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected String getDefaultPreviewLink(final ContentSection section, - final ContentItem item, - final PageState state) { - - final ContentSection contentSection = sectionRepo - .findById(section.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentSectio with ID %d in the database.", - section.getObjectId()))); - - final ContentItem contentItem = itemRepo - .findById(item.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", - item.getObjectId()))); - - final ItemResolver itemResolver = sectionManager - .getItemResolver(contentSection); - - return itemResolver.generateItemURL(state, - contentItem, - contentSection, - CMSDispatcher.PREVIEW); - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentSectionContextBar.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentSectionContextBar.java deleted file mode 100755 index ebaec6d78..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentSectionContextBar.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.PageLocations; - -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; - -import com.arsdigita.web.ParameterMap; -import com.arsdigita.web.URL; - -import org.apache.logging.log4j.LogManager; - -import java.math.BigDecimal; -import java.util.List; -import java.util.Stack; - -import org.apache.logging.log4j.Logger; - -/** - * The context bar of the content section UI. - * - * @author Justin Ross - * @author Jens Pelzetter - */ -public class ContentSectionContextBar extends WorkspaceContextBar { - - private static final Logger LOGGER = LogManager.getLogger( - ContentSectionContextBar.class); - - @Override - protected List entries(final PageState state) { - - /* Include breadcrumb entries already set by content-center (i.e. the - * URL of the content center itself */ - final List entries = super.entries(state); - - final ContentSection section = CMS.getContext().getContentSection(); - final Stack folderEntryStack = new Stack<>(); - String currentFolderLabel = null; - ParameterMap params = new ParameterMap(); - boolean isTemplate = false; - BigDecimal templateID = null; - - if (CMS.getContext().hasContentItem()) { - final ContentItem item = CMS.getContext().getContentItem(); - if (item == null) { - LOGGER.warn("item is null"); - } else if (item.getContentType() == null) { - LOGGER.warn( - "item.getContentType() returns null. item.class.getName(): " - + item.getClass().getName()); - } - - //ToDo NG - Not sure what happens here... -// final Optional parent = item.getParent(); -// -// while (!isTemplate -// && parent.isPresent() -// && parent.get() instanceof ContentItem) { -// if (currentFolderLabel != null) { -// final URL folderURL = URL.there -// (state.getRequest(), -// section.getPath() + "/" + PageLocations.SECTION_PAGE, -// params); -// folderEntryStack.push(new Entry(currentFolderLabel, folderURL)); -// currentFolderLabel = null; -// params = new ParameterMap(); -// } -// final ContentItem pitem = (ContentItem) parent; -// -// if (pitem instanceof Folder) { -// final Folder folder = (Folder) pitem; -// parent = folder.getParent(); -// -// currentFolderLabel = folder.getLabel(); -// if (parent != null || folder.equals(section.getRootFolder())) { -// params.setParameter -// (ContentSectionPage.SET_FOLDER, folder.getID()); -// } -// } else if (pitem instanceof ContentBundle) { -// final ACSObject ppitem = pitem.getParent(); -// -// if (ppitem != null && ppitem instanceof Folder) { -// final Folder folder = (Folder) ppitem; -// -// parent = folder.getParent(); -// currentFolderLabel = folder.getLabel(); -// if (parent != null || folder.equals(section -// .getRootFolder())) { -// params.setParameter -// (ContentSectionPage.SET_FOLDER, folder.getID()); -// } -// } else { -// parent = null; -// } -// } else { -// parent = null; -// } -// } - } - - if (isTemplate) { - params.setParameter(ContentSectionPage.SET_TAB, - new BigDecimal( - ContentSectionPage.CONTENTTYPES_TAB)); - params.setParameter(ContentSectionPage.SET_TEMPLATE, templateID); - } - - // add section-level entry. if this is for an item page, the URL - // will be for the root folder. - final URL url = URL.there( - state.getRequest(), - String.format("%s/" + PageLocations.SECTION_PAGE, - section.getPrimaryUrl()), - params); - - final String sectionTitle = lz("cms.ui.content_section"); - final String title = sectionTitle + ": " + section.getLabel(); - - entries.add(new Entry(title, url)); - - // add any folders to the path now - while (!folderEntryStack.empty()) { - entries.add(folderEntryStack.pop()); - } - - return entries; - } - - private static String lz(final String key) { - return (String) ContentSectionPage.globalize(key).localize(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentSectionPage.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentSectionPage.java deleted file mode 100755 index 94b4d4701..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentSectionPage.java +++ /dev/null @@ -1,537 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleComponent; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.TabbedPane; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.PageLocations; - -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; - -import com.arsdigita.cms.dispatcher.CMSPage; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.cms.ui.category.CategoryAdminPane; -//ToDo NG import com.arsdigita.cms.ui.category.CategoryAdminPane; -import com.arsdigita.cms.ui.cse.ContentSoonExpiredPane; -import com.arsdigita.cms.ui.folder.FolderAdminPane; -import com.arsdigita.cms.ui.lifecycle.LifecycleAdminPane; -import com.arsdigita.cms.ui.role.RoleAdminPane; -import com.arsdigita.cms.ui.type.ContentTypeAdminPane; -import com.arsdigita.cms.ui.workflow.WorkflowAdminPane; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.LayoutPanel; -import com.arsdigita.util.Assert; - -import javax.servlet.http.HttpServletRequest; - -import org.librecms.CMSConfig; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItemVersion; -import org.librecms.contentsection.privileges.AdminPrivileges; - -/** - * Contains the entire admin UI for a content section. - * - * Developers Note: It is based on the dispatcher model is is going to be - * replaced by the newer servlet based model. @see - * c.ad.cms.ui.contentsection.MainPage (currently not active). - * - * @author Jack Chung - * @author Michael Pih - * @author Xixi D'Moon - * @author Justin Ross - * @author Jens Pelzetter - */ -public class ContentSectionPage extends CMSPage implements ActionListener { - - /** - * The URL parameter that can be passed in in order to set the current - * folder. This is used in getting back to the correct level of folder - * expansion from content item page. - */ - public static final String SET_FOLDER = "set_folder"; - /** - * The URL parameter that can be passed in in order to set the current - * template (for setting the content type) - */ - public static final String SET_TEMPLATE = "set_template"; - /** - * The URL parameter that can be passed in in order to set the current tab. - * This is a KLUDGE right now because the TabbedDialog's current tab is - * selected with a local state parameter. - */ - public static final String SET_TAB = "set_tab"; - /** - * Index of the search tab - */ - public static final int SEARCH_TAB = 0; - /** - * Index of the browse tab - */ - public static final int BROWSE_TAB = 1; - /** - * Index of the roles tab - */ - public static final int ROLES_TAB = 2; - /** - * Index of the workflows tab - */ - public static final int WORKFLOW_TAB = 3; - /** - * Index of the lifecycles tab - */ - public static final int LIFECYCLES_TAB = 4; - /** - * Index of the categories tab - */ - public static final int CATEGORIES_TAB = 5; - /** - * Index of the content types tab - */ - public static final int CONTENTTYPES_TAB = 6; - public static final int USER_ADMIN_TAB = 7; - - private TabbedPane m_tabbedPane; - private FolderAdminPane m_folderPane; - private BrowsePane m_browsePane; - private ItemSearch m_searchPane; - private AssetPane m_assetPane; -//ToDo NG private ImagesPane m_imagesPane; - private RoleAdminPane m_rolePane; - private WorkflowAdminPane m_workflowPane; - private LifecycleAdminPane m_lifecyclePane; - private CategoryAdminPane m_categoryPane; - private ContentTypeAdminPane m_typePane; - //private LayoutPanel m_userAdminPane; - private LayoutPanel m_csePane; - private ReportPane m_reportPane; - - /** - * Creates the content section index page containing - a Navigaton bar for - * the various tasks (items, search, images, ....) - a breadcrumb - .... - * Contains the UI for administering a content section. - */ - public ContentSectionPage() { - super(new Label(new TitlePrinter()), new SimpleContainer()); - - setClassAttr("cms-admin"); - - add(new GlobalNavigation()); - add(new ContentSectionContextBar()); - - // Initialize the individual panes - m_folderPane = getFolderAdminPane(); - m_browsePane = getBrowsePane(); - m_searchPane = getSearchPane(); - m_assetPane = getAssetPane(); -//ToDo NG m_imagesPane = getImagesPane(); - m_rolePane = getRoleAdminPane(); - m_workflowPane = getWorkflowAdminPane(); - m_lifecyclePane = getLifecycleAdminPane(); - m_categoryPane = getCategoryAdminPane(); - m_typePane = getContentTypeAdminPane(); - // userAdminPane removed, used to contain just one item (reset user - // folder) which moved to the FolderAdminPane - //m_userAdminPane = getUserAdminPane(); - m_csePane = getCSEPane(); - m_reportPane = getReportPane(); - - // The panes - m_tabbedPane = createTabbedPane(); - m_tabbedPane.setIdAttr("page-body"); - m_tabbedPane.addActionListener(this); - add(m_tabbedPane); - - addActionListener(new ActionListener() { - - @Override - public final void actionPerformed(ActionEvent e) { - final PageState state = e.getPageState(); - - final String tab = state.getRequest().getParameter(SET_TAB); - - if (tab != null) { - m_tabbedPane.setSelectedIndex(state, Integer.valueOf(tab) - .intValue()); - } - - final PermissionChecker permissionChecker = CdiUtil - .createCdiUtil().findBean(PermissionChecker.class); - - if (CMSConfig.getConfig().isHideAdminTabs()) { - m_tabbedPane.setTabVisible( - state, - m_workflowPane, - permissionChecker.isPermitted(AdminPrivileges.ADMINISTER_WORKFLOWS)); - m_tabbedPane.setTabVisible( - state, - m_categoryPane, - permissionChecker.isPermitted( - AdminPrivileges.ADMINISTER_CATEGORIES)); - m_tabbedPane.setTabVisible( - state, - m_lifecyclePane, - permissionChecker.isPermitted( - AdminPrivileges.ADMINISTER_LIFECYLES)); - m_tabbedPane.setTabVisible( - state, - m_typePane, - permissionChecker.isPermitted( - AdminPrivileges.ADMINISTER_CONTENT_TYPES)); - - m_tabbedPane.setTabVisible( - state, - m_rolePane, - permissionChecker.isPermitted( - AdminPrivileges.ADMINISTER_ROLES)); - // csePane: should check permission - m_tabbedPane.setTabVisible(state, m_csePane, true); - // TODO Check for reportPane as well - } - } - - }); - } - - /** - * Creates, and then caches, the browse pane. Overriding this method to - * return null will prevent this tab from appearing. - * - * @return - */ - protected FolderAdminPane getFolderAdminPane() { - if (m_folderPane == null) { - m_folderPane = new FolderAdminPane(); - } - return m_folderPane; - } - - /** - * Creates, and then caches, the browse pane. Overriding this method to - * return null will prevent this tab from appearing. - * - * @return - */ - protected BrowsePane getBrowsePane() { - if (m_browsePane == null) { - m_browsePane = new BrowsePane(); - } - return m_browsePane; - } - - /** - * Creates, and then caches, the search pane. Overriding this method to - * return null will prevent this tab from appearing. - * - * @return - */ - protected ItemSearch getSearchPane() { - if (m_searchPane == null) { - m_searchPane - = new ItemSearch( - ContentItemVersion.DRAFT.toString(), - CMSConfig.getConfig().isLimitItemSearchToContentSection()); - } - return m_searchPane; - } - - protected AssetPane getAssetPane() { - if (m_assetPane == null) { - m_assetPane = new AssetPane(); - } - - return m_assetPane; - } - -// ToDo NG -// protected ImagesPane getImagesPane() { -// if (m_imagesPane == null) { -// m_imagesPane = new ImagesPane(); -// } -// return m_imagesPane; -// } - protected RoleAdminPane getRoleAdminPane() { - if (m_rolePane == null) { - m_rolePane = new RoleAdminPane(); - } - return m_rolePane; - } - - /** - * Creates, and then caches, the workflow administration pane. Overriding - * this method to return null will prevent this tab from appearing. - */ - protected WorkflowAdminPane getWorkflowAdminPane() { - if (m_workflowPane == null) { - m_workflowPane = new WorkflowAdminPane(); - } - return m_workflowPane; - } - - /** - * Creates, and then caches, the lifecycle administration pane. Overriding - * this method to return null will prevent this tab from appearing. - */ - protected LifecycleAdminPane getLifecycleAdminPane() { - if (m_lifecyclePane == null) { - m_lifecyclePane = new LifecycleAdminPane(); - } - return m_lifecyclePane; - } - - /** - * Creates, and then caches, the category administration pane. Overriding - * this method to return null will prevent this tab from appearing. - */ - protected CategoryAdminPane getCategoryAdminPane() { - if (m_categoryPane == null) { - m_categoryPane = new CategoryAdminPane(); - } - return m_categoryPane; - } - - /** - * Creates, and then caches, the content type administration pane. - * Overriding this method to return null will prevent this tab from - * appearing. - * - * @return - */ - protected ContentTypeAdminPane getContentTypeAdminPane() { - if (m_typePane == null) { - m_typePane = new ContentTypeAdminPane(); - } - return m_typePane; - } - -// protected LayoutPanel getUserAdminPane() { -// if (m_userAdminPane == null) { -// m_userAdminPane = new LayoutPanel(); -// m_userAdminPane.setLeft(new SimpleComponent()); -// m_userAdminPane.setBody(new UserAdminPane()); -// } -// return m_userAdminPane; -// } - protected LayoutPanel getCSEPane() { - if (m_csePane == null) { - m_csePane = new LayoutPanel(); - m_csePane.setLeft(new SimpleComponent()); - m_csePane.setBody(new ContentSoonExpiredPane()); - } - return m_csePane; - } - - protected ReportPane getReportPane() { - if (m_reportPane == null) { - m_reportPane = new ReportPane(); - } - return m_reportPane; - } - - /** - * Adds the specified component, with the specified tab name, to the tabbed - * pane only if it is not null. - * - * @param pane The pane to which to add the tab - * @param tabName The name of the tab if it's added - * @param comp The component to add to the pane - */ - protected void addToPane(final TabbedPane pane, - final String tabName, - final Component comp) { - if (comp != null) { - pane.addTab(new Label(tabName), comp); - } - } - - private void tab(final TabbedPane pane, - final String key, - final Component tab) { - if (tab != null) { - pane.addTab(new Label(gz(key)), tab); - } - } - - /** - *

- * Created the TabbedPane to use for this page. Adds the tabs to the pane. - * The default implementation uses a {@link - * com.arsdigita.bebop.TabbedPane}. This implementation also adds browse, - * search, staff admin, viewers admin, workflow admin, category admin, and - * content type panes.

- * - *

- * Developers can override this method to add only the tabs they want, or to - * add additional tabs after the default CMS tabs are added.

- * - * @return - */ - protected TabbedPane createTabbedPane() { - final TabbedPane pane = new TabbedPane(); - - //tab(pane, "cms.ui.folders", getFolderAdminPane()); - tab(pane, "cms.ui.browse", getBrowsePane()); - tab(pane, "cms.ui.search", getSearchPane()); - tab(pane, "cms.ui.assets", getAssetPane()); -// ToDo NG replace with media tab tab(pane, "cms.ui.images", getImagesPane()); - tab(pane, "cms.ui.roles", getRoleAdminPane()); - tab(pane, "cms.ui.workflows", getWorkflowAdminPane()); - tab(pane, "cms.ui.lifecycles", getLifecycleAdminPane()); - tab(pane, "cms.ui.categories", getCategoryAdminPane()); - tab(pane, "cms.ui.content_types", getContentTypeAdminPane()); - tab(pane, "cms.ui.cse", getCSEPane()); - tab(pane, "cms.ui.reports", getReportPane()); - - return pane; - } - - /** - * Fetch the request-local content section. - * - * @param request The HTTP request - * - * @return The current content section - */ - @Override - public ContentSection getContentSection(final HttpServletRequest request) { - // Resets all content sections associations. - ContentSection section = super.getContentSection(request); - Assert.exists(section); - return section; - } - - /** - * When a new tab is selected, reset the state of the formerly-selected - * pane. - * - * @param event The event fired by selecting a tab - */ - @Override - public void actionPerformed(final ActionEvent event) { - final PageState state = event.getPageState(); - - final Component pane = m_tabbedPane.getCurrentPane(state); - -//ToDo NG if (pane == m_searchPane) { -// m_searchPane.reset(state); -// } else if (pane == m_imagesPane) { -// m_imagesPane.reset(state); -// } else - if (pane == m_assetPane) { - m_assetPane.reset(state); - } else if (pane == m_folderPane) { - m_folderPane.reset(state); -//ToDo NG } else if (pane == m_browsePane) { -// m_browsePane.reset(state); -// } else if (pane == m_rolePane) { -// m_rolePane.reset(state); - } else if (pane == m_workflowPane) { - m_workflowPane.reset(state); - } else if (pane == m_lifecyclePane) { - m_lifecyclePane.reset(state); - } else if (pane == m_categoryPane) { - m_categoryPane.reset(state); - } else if (pane == m_typePane) { - m_typePane.reset(state); -// } else if (pane == m_userAdminPane) { - //m_userAdminPane.reset(state); - } else if (pane == m_csePane) { - m_csePane.reset(state); - } - } - - /** - * Construct a URL for displaying the tab - * - * @param item The item from which we get the corresponding content section - * @param tab The index of the tab to display - * - * @return - */ - public static String getSectionURL(final ContentItem item, final int tab) { - // Get the content section associated with the content item. - final ContentSection section = item.getContentType().getContentSection(); - - final String url = section.getPrimaryUrl() + PageLocations.SECTION_PAGE - + "?" + SET_TAB + "=" + tab; - - return url; - } - - private static GlobalizedMessage gz(final String key) { - return new GlobalizedMessage(key, CmsConstants.CMS_BUNDLE); - } - - /** - * Getting the GlobalizedMessage using a CMS Class targetBundle. - * - * @param key The resource key - * - * @return - * - * @pre key != null - */ - public static GlobalizedMessage globalize(final String key) { - return new GlobalizedMessage(key, CmsConstants.CMS_BUNDLE); - } - - /** - * - * @param key - * @param args - * - * @return - */ - public static GlobalizedMessage globalize(final String key, - final Object[] args) { - return new GlobalizedMessage(key, CmsConstants.CMS_BUNDLE, args); - } - - /** - * Helper class to be able to use a PrintListener to set the titel of the - * page. - */ - private static class TitlePrinter implements PrintListener { - - /** - * - * @param event - */ - @Override - public void prepare(final PrintEvent event) { - final Label l = (Label) event.getTarget(); - - l.setLabel(CMS.getContext().getContentSection().getLabel()); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentSectionRequestLocal.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentSectionRequestLocal.java deleted file mode 100755 index a01e36cf4..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ContentSectionRequestLocal.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; -import com.arsdigita.cms.CMS; - -import org.librecms.contentsection.ContentSection; - -/** - * - */ -public final class ContentSectionRequestLocal extends RequestLocal { - - @Override - protected Object initialValue(final PageState state) { - return CMS.getContext().getContentSection(); - } - - public final ContentSection getContentSection(final PageState state) { - return (ContentSection) get(state); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/FileUploadSection.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/FileUploadSection.java deleted file mode 100755 index 90439fecb..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/FileUploadSection.java +++ /dev/null @@ -1,488 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Container; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormSection; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.FileUpload; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.OptionGroup; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.dispatcher.MultipartHttpServletRequest; -import java.io.File; -import javax.activation.MimeType; -import javax.activation.MimeTypeParseException; -import javax.activation.MimetypesFileTypeMap; -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import org.librecms.CmsConstants; - -/** - * A form section with two widgets: a mime-type selection widget and a file - * upload widget. The section will attempt to automatically guess the mime type - * from the filename (if necessary), and return the mime type. - * - * @author Stanislav Freidin (sfreidin@arsdigita.com) - * @author Jens Pelzetter - */ -public class FileUploadSection extends FormSection { - - private SingleSelect mimeWidget; - private FileUpload fileWidget; - private String mimePrefix; - private String defaultMimeType; - private String parameterPrefix; - - /** - * The mime type widget - */ - public static final String MIME_TYPE = "mime_type"; - - /** - * The file upload widget - */ - public static final String FILE_UPLOAD = "file_upload"; - - /** - * Automatically guess the mime type - */ - public static final String GUESS_MIME = "-guess-"; - - /** - * Construct a new FileUploadSection - * - * @param mimeLabel The label for the mime type widget - * - * @param mimePrefix Populate the mime type widget with all mime types that - * match the prefix. Some of the possible prefixes are "text", "image", - * "binary", etc. - * - * @param defaultMimeType The default mime type that should be assumed if - * the guessing fails - * - * @param panel The panel that is to be used to lay out the components - * - */ - public FileUploadSection(final GlobalizedMessage mimeLabel, - final String mimePrefix, - final String defaultMimeType, - final Container panel) { - this(mimeLabel, mimePrefix, defaultMimeType, "", panel); - } - - /** - * Construct a new FileUploadSection - * - * @param mimeLabel The label for the mime type widget - * - * @param mimePrefix Populate the mime type widget with all mime types that - * match the prefix. Some of the possible prefixes are "text", "image", - * "binary", etc. - * - * @param defaultMimeType The default mime type that should be assumed if - * the guessing fails - * - * @param panel The panel that is to be used to lay out the components - * - * @deprecated use the same constructor but with the GlobalizedMessage for - * the mimeLabel - */ - public FileUploadSection(final String mimeLabel, - final String mimePrefix, - final String defaultMimeType, - final Container panel) { - // This takes advantage of the fact that the "key" is returned - // when it is not present in the message bundle - this(new GlobalizedMessage(mimeLabel), - mimePrefix, - defaultMimeType, - panel); - } - - /** - * Construct a new FileUploadSection - * - * @param mimeLabel The label for the mime type widget - * - * @param mimePrefix Populate the mime type widget with all mime types that - * match the prefix. Some of the possible prefixes are "text", "image", - * "binary", etc. - * - * @param defaultMimeType The default mime type that should be assumed if - * the guessing fails - * - * @param parameterPrefix Prepended to MIME_TYPE and FILE_UPLOAD for - * parameter names so that more than 1 file upload widgets may be used per - * form - * - * @param panel The panel that is to be used to lay out the components - * - * @deprecated use the same constructor but with the GlobalizedMessage for - * the mimeLabel - */ - public FileUploadSection(final String mimeLabel, - final String mimePrefix, - final String defaultMimeType, - final String parameterPrefix, - final Container panel - ) { - // This takes advantage of the fact that the "key" is returned - // when it is not present in the message bundle - this(new GlobalizedMessage(mimeLabel, CmsConstants.CMS_BUNDLE), - mimePrefix, - defaultMimeType, - parameterPrefix, - panel); - } - - /** - * Construct a new FileUploadSection - * - * @param mimeLabel The label for the mime type widget - * - * @param mimePrefix Populate the mime type widget with all mime types that - * match the prefix. Some of the possible prefixes are "text", "image", - * "binary", etc. - * - * @param defaultMimeType The default mime type that should be assumed if - * the guessing fails - * - * @param parameterPrefix Prepended to MIME_TYPE and FILE_UPLOAD for - * parameter names so that more than 1 file upload widgets may be used per - * form - * - * @param panel The panel that is to be used to lay out the components - * - */ - public FileUploadSection(final GlobalizedMessage mimeLabel, - final String mimePrefix, - final String defaultMimeType, - final String parameterPrefix, - final Container panel) { - - super(panel); - - this.mimePrefix = mimePrefix; - this.defaultMimeType = defaultMimeType; - if (parameterPrefix == null) { - this.parameterPrefix = ""; - } else { - this.parameterPrefix = parameterPrefix; - } - - add(new Label(mimeLabel, false)); - mimeWidget = new SingleSelect(getMimeTypeWidgetName()); - addMimeOptions(mimeWidget, mimePrefix); - mimeWidget - .addOption(new Option(GUESS_MIME, - new Label(new GlobalizedMessage( - "cms.ui.authoring.file_upload.auto_detect", - CmsConstants.CMS_BUNDLE)))); - - mimeWidget.setDefaultValue(GUESS_MIME); - add(mimeWidget); - - add(new Label(new GlobalizedMessage("cms.ui.upload_new_content", - CmsConstants.CMS_BUNDLE))); - fileWidget = new FileUpload(getFileUploadWidgetName()); - add(fileWidget); - } - - /** - * Construct a new FileUploadSection - * - * @param mimeLabel The label for the mime type widget - * - * @param mimePrefix Populate the mime type widget with all mime types that - * match the prefix. Some of the possible prefixes are "text", "image", - * "binary", etc. - * - * @param defaultMimeType The default mime type that should be assumed if - * the guessing fails - * - * @param parameterPrefix Prepended to MIME_TYPE and FILE_UPLOAD for - * parameter names so that more than 1 file upload widgets may be used per - * form - * - */ - public FileUploadSection(final GlobalizedMessage mimeLabel, - final String mimePrefix, - final String defaultMimeType, - final String parameterPrefix) { - this(mimeLabel, - mimePrefix, - defaultMimeType, - parameterPrefix, - new ColumnPanel(2, true)); - final ColumnPanel panel = (ColumnPanel) getPanel(); - panel.setBorder(false); - panel.setPadColor("#FFFFFF"); - } - - /** - * Construct a new FileUploadSection - * - * @param mimeLabel The label for the mime type widget - * - * @param mimePrefix Populate the mime type widget with all mime types that - * match the prefix. Some of the possible prefixes are "text", "image", - * "binary", etc. - * - * @param defaultMimeType The default mime type that should be assumed if - * the guessing fails - * - * @param parameterPrefix Prepended to MIME_TYPE and FILE_UPLOAD for - * parameter names so that more than 1 file upload widgets may be used per - * form - * - * @deprecated use the same constructor but with the GlobalizedMessage for - * the mimeLabel - */ - public FileUploadSection(final String mimeLabel, - final String mimePrefix, - final String defaultMimeType, - final String parameterPrefix) { - // This takes advantage of the fact that the "key" is returned - // when it is not present in the message bundle - this(new GlobalizedMessage(mimeLabel, CmsConstants.CMS_BUNDLE), - mimePrefix, - defaultMimeType, - parameterPrefix); - } - - /** - * Construct a new FileUploadSection - * - * @param mimeLabel The label for the mime type widget - * - * @param mimePrefix Populate the mime type widget with all mime types that - * match the prefix. Some of the possible prefixes are "text", "image", - * "binary", etc. - * - * @param defaultMimeType The default mime type that should be assumed if - * the guessing fails - * - * @deprecated use the same constructor but with the GlobalizedMessage for - * the mimeLabel - */ - public FileUploadSection(final String mimeLabel, - final String mimePrefix, - final String defaultMimeType) { - - // This takes advantage of the fact that the "key" is returned - // when it is not present in the message bundle - this(new GlobalizedMessage(mimeLabel, CmsConstants.CMS_BUNDLE), - mimePrefix, - defaultMimeType, - ""); - } - - /** - * Construct a new FileUploadSection - * - * @param mimeLabel The GlobalizedMessage for the label for the mime type - * widget - * - * @param mimePrefix Populate the mime type widget with all mime types that - * match the prefix. Some of the possible prefixes are "text", "image", - * "binary", etc. - * - * @param defaultMimeType The default mime type that should be assumed if - * the guessing fails - * - */ - public FileUploadSection(GlobalizedMessage mimeLabel, - String mimePrefix, - String defaultMimeType) { - this(mimeLabel, mimePrefix, defaultMimeType, ""); - } - - /** - * Try to guess the mime type from the filename, and return it. The parent - * form should call this method in its process listener. Note that this - * method may return null if the mime type could not be guessed. - * - * @param event The form section event - * @return The mime type of the file. - */ - public MimeType getMimeType(final FormSectionEvent event) { - - final FormData data = event.getFormData(); - - final String fileName = (String) data.get(getFileUploadWidgetName()); - final String mimeTypeName = (String) data.get(getMimeTypeWidgetName()); - - // Guess the mime type from the filename - MimeType mimeType = null; - if (fileName != null) { - try { - if (GUESS_MIME.equals(mimeTypeName)) { - // Guess the mime type from the file extension - mimeType = new MimeType(MimetypesFileTypeMap - .getDefaultFileTypeMap() - .getContentType(fileName)); - } else { - mimeType = new MimeType(mimeTypeName); - } - } catch (MimeTypeParseException ex) { - mimeType = null; - } - } - - // Failed to guess it, failed to load it, fall back on the default - if (mimeType == null) { - try { - mimeType = new MimeType(defaultMimeType); - } catch (MimeTypeParseException ex) { - mimeType = null; - } - } - - return mimeType; - } - - /** - * Obtain a File object from the file upload widget. The containing form - * should call this method in its process listener. - * - * @param event The form section event - * @return - */ - public File getFile(final FormSectionEvent event) { - - final String fileName = getFileName(event); - - if (fileName != null && fileName.length() > 0) { - return ((MultipartHttpServletRequest) unwrapRequest(event - .getPageState() - .getRequest())) - .getFile(getFileUploadWidgetName()); - } - - return null; - } - - private ServletRequest unwrapRequest(final HttpServletRequest request) { - - ServletRequest current = request; - while (current instanceof HttpServletRequestWrapper) { - current = ((HttpServletRequestWrapper) current).getRequest(); - } - - return current; - } - - /** - * Obtain a filename from the file upload widget. The containing form should - * call this method in its process listener. - * - * @param event The form section event - * @return - */ - public String getFileName(final FormSectionEvent event) { - - return event - .getFormData() - .getString(getFileUploadWidgetName()); - } - - /** - * Set the value for the mime type widget. The containing form should call - * this method in its init listener - * - * @param event The form section event - * @param mimeType The mime type to set, such as "text/html" or "img/jpeg" - * - */ - public void setMimeType(final FormSectionEvent event, - final String mimeType) { - event - .getFormData() - .put(getMimeTypeWidgetName(), mimeType); - } - - /** - * @return the mime type widget - */ - public SingleSelect getMimeTypeWidget() { - return mimeWidget; - } - - /** - * @return the file upload widget - */ - public FileUpload getFileUploadWidget() { - return fileWidget; - } - - /** - * @return the parameter name prefix - */ - public String getParameterPrefix() { - return parameterPrefix; - } - - /** - * @return the file upload parameter name - */ - public String getFileUploadWidgetName() { - return parameterPrefix + FILE_UPLOAD; - } - - /** - * @return the mime typeparameter name - */ - public String getMimeTypeWidgetName() { - return parameterPrefix + MIME_TYPE; - } - - /** - * Add mime-type options to the option group by loading all mime types which - * match a certain prefix from the database - * - * @param mimeTypeOptions The mime type widget to which options should be - * added - * - * @param mimePrefix Populate the mime type widget with all mime types that - * match the prefix. Some of the possible prefixes are "text", "image", - * "binary", etc. - * - */ - public static void addMimeOptions(final OptionGroup mimeTypeOptions, - final String mimePrefix) { - -// MimeTypeCollection types; -// if (mimePrefix == null || mimePrefix.equals("")) { -// types = MimeType.getAllMimeTypes(); -// } else { -// types = MimeType.searchMimeTypes(mimePrefix + "/"); -// } -// while (types.next()) { -// MimeType type = types.getMimeType(); -// mimeTypeOptions.addOption(new Option(type.getMimeType(), type.getLabel())); -// } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/FlatItemList.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/FlatItemList.java deleted file mode 100755 index e20ccb72b..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/FlatItemList.java +++ /dev/null @@ -1,468 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.ActionLink; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.SegmentedPanel; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.ChangeEvent; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.CMS; - -import org.librecms.contentsection.ContentSection; - -import com.arsdigita.cms.ui.authoring.CreationSelector; -import com.arsdigita.cms.ui.authoring.news.NewItemForm; -import com.arsdigita.cms.ui.folder.FolderCreateForm; -import com.arsdigita.cms.ui.folder.FolderEditorForm; -import com.arsdigita.cms.ui.folder.FolderManipulator; -import com.arsdigita.cms.ui.folder.FolderPath; -import com.arsdigita.cms.ui.folder.FolderRequestLocal; -import com.arsdigita.cms.ui.folder.FolderSelectionModel; -import com.arsdigita.cms.ui.permissions.CMSPermissionsPane; -import com.arsdigita.globalization.GlobalizedMessage; - -import com.arsdigita.toolbox.ui.ActionGroup; -import com.arsdigita.ui.CcmObjectSelectionModel; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.libreccm.security.PermissionManager; -import org.librecms.CmsConstants; -import org.librecms.contentsection.Folder; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Encapsulates a {@link FolderManipulator} in order to create a flat item - * listing. Also contains a new item form. - * - * @author Stanislav Freidin - * @author Jens Pelzetter - */ -public class FlatItemList extends SegmentedPanel implements FormProcessListener, - ChangeListener, - FormSubmissionListener, - Resettable, - ActionListener { - - private static final String CONTENT_TYPE_ID = "ct"; - // The folder selectors - private final FolderSelectionModel folderSelectionModel; - private final FolderRequestLocal folderRequestLocal; - private final NewItemForm newItemForm; - private final SingleSelectionModel typeSelectionModel; - private final CreationSelector creationSelector; - private final FolderManipulator folderManipulator; - private final FolderCreateForm folderCreator; -// private final ActionLink m_setHomeFolderAction; -// private final ActionLink m_removeHomeFolderAction; - private final ActionLink createFolderAction; -// private final ActionLink togglePrivateAction; -// private final Label m_homeFolderLabel; - private final Segment browseSegment; - private final Segment newItemSegment; - private final Segment newFolderSegment; - private final Segment editFolderSegment; - private final Segment permissionsSegment; - private final CMSPermissionsPane permissionsPane; - // Folder edit/rename functionality. - private final ActionLink editFolderAction; - private final FolderEditorForm folderEditor; - private final Label contentLabel; - private final FolderPath folderPath; - private final Label chooseLabel; - private final StringParameter selectedLanguageParam; - - /** - * Construct a new item listing pane. The provided folder selection model is - * used to keep track of the currently displayed folder. - * - * @param folderRequestLocal - * @param folderSelectionModel maintains the currently displayed folder. - */ - @SuppressWarnings("unchecked") - public FlatItemList(final FolderRequestLocal folderRequestLocal, - final FolderSelectionModel folderSelectionModel) { - this.folderRequestLocal = folderRequestLocal; - this.folderSelectionModel = folderSelectionModel; - folderSelectionModel.addChangeListener(event -> reset(event - .getPageState())); - - setIdAttr("flat-item-list"); - - newItemSegment = addSegment(); - newItemSegment.setIdAttr("folder-new-item"); - - newFolderSegment = addSegment(); - newFolderSegment.setIdAttr("folder-new-folder"); - - editFolderSegment = addSegment(); - editFolderSegment.setIdAttr("folder-edit-folder"); - - browseSegment = addSegment(); - browseSegment.setIdAttr("folder-browse"); - - final ActionGroup browseActions = new ActionGroup(); - browseSegment.add(browseActions); - - // The top 'browse' segment - contentLabel = new Label(globalize("cms.ui.contents_of"), false); - browseSegment.addHeader(contentLabel); - chooseLabel = new Label(globalize("cms.ui.choose_target_folder"), - false); - browseSegment.addHeader(chooseLabel); - folderPath = new FolderPath(folderSelectionModel); - - browseSegment.addHeader(folderPath); - folderManipulator = new FolderManipulator(folderSelectionModel); - folderManipulator.getItemView().addProcessListener(this); - folderManipulator.getTargetSelector().addProcessListener(this); - folderManipulator.getTargetSelector().addSubmissionListener(this); - - browseActions.setSubject(folderManipulator); - - createFolderAction = new ActionLink(new Label(globalize( - "cms.ui.new_folder"))); - createFolderAction.addActionListener(this); - browseActions.addAction(createFolderAction); - - editFolderAction = new ActionLink(new Label(globalize( - "cms.ui.edit_folder"))); - editFolderAction.addActionListener(this); - browseActions.addAction(editFolderAction); - - newItemForm = new SectionNewItemForm("newItem"); - newItemForm.addProcessListener(this); - browseActions.addAction(newItemForm); - - permissionsSegment = addSegment(); - permissionsSegment.setIdAttr("folder-permissions"); - - final ActionGroup permissionActions = new ActionGroup(); - permissionsSegment.add(permissionActions); - - permissionsSegment.addHeader(new Label(new GlobalizedMessage( - "cms.ui.permissions", CmsConstants.CMS_BUNDLE))); - - selectedLanguageParam = new StringParameter(ContentItemPage.SELECTED_LANGUAGE); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionManager permissionManager = cdiUtil.findBean( - PermissionManager.class); - final List privileges = permissionManager - .listDefiniedPrivileges(ItemPrivileges.class); - final Map privNameMap = new HashMap<>(); - privileges.forEach(privilege -> privNameMap.put(privilege, privilege)); - - permissionsPane = new CMSPermissionsPane( - privileges.toArray(new String[]{}), - privNameMap, - (CcmObjectSelectionModel) folderSelectionModel); - permissionActions.setSubject(permissionsPane); - - newItemSegment.addHeader(new Label(globalize("cms.ui.new_item"))); - typeSelectionModel = new ParameterSingleSelectionModel<>( - new LongParameter(CONTENT_TYPE_ID)); - typeSelectionModel.addChangeListener(this); - - creationSelector = new CreationSelector(typeSelectionModel, - folderSelectionModel, - selectedLanguageParam); - newItemSegment.add(creationSelector); - //m_newItemSeg.add(new Label("
", false)); - - // The 'new folder' segment - newFolderSegment.addHeader(new Label(globalize("cms.ui.new_folder"))); -// final Form folderCreate = new Form("fcreat"); - folderCreator = new FolderCreateForm("fcreat", folderSelectionModel); - folderCreator.addSubmissionListener(this); - folderCreator.addProcessListener(this); - //folderCreator.add(folderCreator); - newFolderSegment.add(folderCreator); - newFolderSegment.add(new Label("
", false)); - - editFolderSegment.addHeader(new Label(globalize("cms.ui.edit_folder"))); - folderEditor = new FolderEditorForm("fedit", folderSelectionModel); - folderEditor.addSubmissionListener(this); - folderEditor.addProcessListener(this); - //Form folderEditorForm = new Form("fedit_form"); - //folderEditorForm.add(folderEditor); - editFolderSegment.add(folderEditor); - editFolderSegment.add(new Label("
", false)); - } - - @Override - public void register(final Page page) { - super.register(page); - - page.setVisibleDefault(chooseLabel, false); -// page.setVisibleDefault(browseSegment, true); - page.setVisibleDefault(newItemSegment, false); - page.setVisibleDefault(newFolderSegment, false); - page.setVisibleDefault(editFolderSegment, false); - - page.addComponentStateParam(this, - typeSelectionModel.getStateParameter()); - page.addGlobalStateParam(selectedLanguageParam); - - page.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(final ActionEvent event) { - final PageState state = event.getPageState(); - - if (state.isVisibleOnPage(FlatItemList.this)) { - showHideSegments(state); - } - } - - }); - } - - /** - * Show/hide segments based on access checks. - * - * @param state The page state - * - * @pre ( state != null ) - */ - private void showHideSegments(final PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - final Folder folder = folderRequestLocal.getFolder(state); - - // MP: This should be checked on the current folder instead of just - // the content section. - final boolean newItem = permissionChecker.isPermitted( - ItemPrivileges.CREATE_NEW, folder); - - if (!newItem) { - browseMode(state); - } - - createFolderAction.setVisible(state, newItem); - newItemForm.setVisible(state, newItem); - - final boolean editItem = permissionChecker.isPermitted( - ItemPrivileges.EDIT, folder); - - editFolderAction.setVisible(state, editItem); -// chooseLabel.setVisible(state, editItem); -// editFolderSegment.setVisible(state, editItem); - - if (permissionChecker.isPermitted(ItemPrivileges.ADMINISTER, folder)) { - permissionsSegment.setVisible(state, true); - } else { - permissionsSegment.setVisible(state, false); - } - } - - private void browseMode(final PageState state) { - browseSegment.setVisible(state, true); - permissionsSegment.setVisible(state, true); - chooseLabel.setVisible(state, false); - contentLabel.setVisible(state, true); - folderPath.setVisible(state, true); - newItemSegment.setVisible(state, false); - newFolderSegment.setVisible(state, false); - editFolderSegment.setVisible(state, false); - - typeSelectionModel.clearSelection(state); - } - - private void newItemMode(final PageState state) { - permissionsSegment.setVisible(state, false); - newItemSegment.setVisible(state, true); - } - - private void newFolderMode(final PageState state) { - permissionsSegment.setVisible(state, false); - newFolderSegment.setVisible(state, true); - } - - @Override - public void submitted(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - if (event.getSource() == folderCreator - && folderCreator.isCancelled(state)) { - browseMode(state); - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.cancelled", CmsConstants.CMS_BUNDLE)); - } else if (event.getSource() == folderEditor - && folderEditor.isCancelled(state)) { - browseMode(state); - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.cancelled", CmsConstants.CMS_BUNDLE)); - } else if (event.getSource() == folderManipulator.getTargetSelector()) { - // This only works if this submission listener is run - // after the target selector's one - if (!folderManipulator.getTargetSelector().isVisible(state)) { - browseMode(state); - } - } - } - - @Override - public void process(final FormSectionEvent event) { - final PageState state = event.getPageState(); - final Object source = event.getSource(); - if (source == newItemForm) { - final Long typeID = newItemForm.getTypeID(state); - typeSelectionModel.setSelectedKey(state, typeID); - newItemMode(state); - } else if (source == folderCreator || source == folderEditor) { - browseMode(state); - } else if (source == folderManipulator.getItemView()) { - // Hide everything except for the browseSeg - permissionsSegment.setVisible(state, false); - chooseLabel.setVisible(state, true); - contentLabel.setVisible(state, false); - folderPath.setVisible(state, false); - } else if (source == folderManipulator.getTargetSelector()) { - browseMode(state); - } - } - - @Override - public void stateChanged(final ChangeEvent event) { - final PageState state = event.getPageState(); - if (event.getSource().equals(typeSelectionModel)) { - if (!typeSelectionModel.isSelected(state)) { - browseMode(state); - } - } - } - - @Override - public void actionPerformed(final ActionEvent event) { - final PageState state = event.getPageState(); - final Object source = event.getSource(); - if (source == createFolderAction) { - newFolderMode(state); - } else if (source == editFolderAction) { - permissionsSegment.setVisible(state, false); - editFolderSegment.setVisible(state, true); - } -// else if (source == togglePrivateAction) { -// togglePermissions(state); -// } -// } else if (source == m_setHomeFolderAction) { -// User user = Web.getWebContext().getUser(); -// Folder folder = m_folder.getFolder(state); -// user = (User) DomainObjectFactory.newInstance(user.getOID()); -// Folder.setUserHomeFolder(user, folder); -// } else if (source == m_removeHomeFolderAction) { -// User user = Web.getWebContext().getUser(); -// ContentSection section = CMS.getContext().getContentSection(); -// UserHomeFolderMap map = UserHomeFolderMap -// .findUserHomeFolderMap(user, section); -// if (map != null) { -// map.delete(); -// } -// } - } - - private void togglePermissions(final PageState state) { - final Folder currentFolder = folderRequestLocal.getFolder(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - permissionChecker.checkPermission(ItemPrivileges.ADMINISTER, - currentFolder); - - permissionsPane.reset(state); - } - - @Override - public void reset(final PageState state) { - browseMode(state); - folderManipulator.reset(state); - // switching between folders used to keep showing the permission pane - // in the same perm mode (direct or inherited) regardless - // of the folder status - permissionsPane.reset(state); - } - - public final FolderManipulator getManipulator() { - return folderManipulator; - } - - public final CMSPermissionsPane getPermissionsPane() { - return permissionsPane; - } - - public void setPermissionLinkVis(final PageState state) { -// final Folder currentFolder = folderRequestLocal.getFolder(state); -// final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); -// final PermissionChecker permissionChecker = cdiUtil.findBean( -// PermissionChecker.class); -// if (!permissionChecker.isPermitted(ItemPrivileges.ADMINISTER, -// currentFolder)) { -// togglePrivateAction.setVisible(state, false); -// } - } - - private static class SectionNewItemForm extends NewItemForm { - - public SectionNewItemForm(final String name) { - super(name); - } - - @Override - public ContentSection getContentSection(final PageState state) { - return CMS.getContext().getContentSection(); - } - - } - - /** - * Getting the GlobalizedMessage using a CMS Class targetBundle. - * - * @param key The resource key - * - * @pre ( key != null ) - */ - private static GlobalizedMessage globalize(final String key) { - return ContentSectionPage.globalize(key); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/FormSecurityListener.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/FormSecurityListener.java deleted file mode 100755 index e9e0577b4..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/FormSecurityListener.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; - -import org.librecms.contentsection.ContentItem; - -import com.arsdigita.cms.ui.item.ContentItemRequestLocal; -import com.arsdigita.dispatcher.AccessDeniedException; - -import com.arsdigita.util.Assert; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; - -/** - * @author Justin Ross <jross@redhat.com> - */ -public class FormSecurityListener implements FormSubmissionListener { - - private final String m_action; - private final ContentItemRequestLocal m_item; - - public FormSecurityListener(final String action, - final ContentItemRequestLocal item) { - Assert.exists(action, String.class); - - m_action = action; - m_item = item; - } - - public FormSecurityListener(final String action) { - this(action, null); - } - - @Override - public final void submitted(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - - if (m_item == null) { - if (permissionChecker.isPermitted(m_action)) { - return; - } - } else { - final ContentItem item = m_item.getContentItem(state); - - if (permissionChecker.isPermitted(m_action, item)) { - return; - } - } - - throw new AccessDeniedException(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/GlobalNavigation.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/GlobalNavigation.java deleted file mode 100755 index a0b22979c..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/GlobalNavigation.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleComponent; -import com.arsdigita.cms.CMS; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.ui.UI; -import com.arsdigita.ui.admin.AdminUiConstants; -import com.arsdigita.ui.login.LoginServlet; -import com.arsdigita.web.URL; -import com.arsdigita.xml.Element; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.CoreConstants; -import org.libreccm.security.PermissionChecker; -import org.libreccm.web.ApplicationManager; -import org.libreccm.web.ApplicationRepository; -import org.libreccm.web.ApplicationType; -import org.libreccm.web.CcmApplication; -import org.librecms.CmsConstants; - -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -/** - *

- * Global navigation elements for the CMS admin UIs.

- * - * @author Justin Ross <jross@redhat.com> - */ -// Made public (instead of unspecified, resulting in protected) in 6.6.8 -public class GlobalNavigation extends SimpleComponent { - - - private final String m_adminPath; - private final String m_centerPath; - private final String m_changePasswordPath; - private final String m_helpPath; - private final String m_signOutPath; - private final String m_wspcPath; - - /** - * - */ - public GlobalNavigation() { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ApplicationManager appManager = cdiUtil.findBean( - ApplicationManager.class); - final ApplicationRepository appRepo = cdiUtil.findBean( - ApplicationRepository.class); - final Map appTypes = appManager - .getApplicationTypes(); - final ApplicationType adminAppType = appTypes.get( - AdminUiConstants.ADMIN_APP_TYPE); - final List adminApps = appRepo.findByType(adminAppType - .name()); - final ApplicationType contentCenterAppType = appTypes.get( - CmsConstants.CONTENT_CENTER_APP_TYPE); - final List contentCenterApps = appRepo.findByType( - contentCenterAppType.name()); - - m_adminPath = adminApps.get(0).getPrimaryUrl(); - m_centerPath = contentCenterApps.get(0).getPrimaryUrl(); - m_changePasswordPath = LoginServlet.getChangePasswordPageURL(); - m_helpPath = "/nowhere"; // We don't have this yet XXX. - m_signOutPath = LoginServlet.getLogoutPageURL(); - m_wspcPath = UI.getWorkspaceURL(); - } - - /** - * - * @param state - * @param parent - */ - @Override - public void generateXML(final PageState state, final Element parent) { - if (isVisible(state)) { - final HttpServletRequest sreq = state.getRequest(); - - final Element nav = parent.newChildElement("cms:globalNavigation", - CMS.CMS_XML_NS); - final String centerTitle = (String) new GlobalizedMessage( - "cms.ui.content_center", CmsConstants.CMS_BUNDLE).localize(); - final String adminTitle = (String) new GlobalizedMessage( - "cms.ui.admin_center", CmsConstants.CMS_BUNDLE).localize(); - final String wspcTitle = (String) new GlobalizedMessage( - "cms.ui.my_workspace", CmsConstants.CMS_BUNDLE).localize(); - final String signOutTitle = (String) new GlobalizedMessage( - "cms.ui.sign_out", CmsConstants.CMS_BUNDLE).localize(); - final String helpTitle = (String) new GlobalizedMessage( - "cms.ui.help", CmsConstants.CMS_BUNDLE).localize(); - final String changePasswordTitle = (String) new GlobalizedMessage( - "cms.ui.change_password", CmsConstants.CMS_BUNDLE).localize(); - - link(sreq, nav, "cms:contentCenter", m_centerPath, centerTitle); - - /* If the current user has admin permissions, insert a link to the admin center */ - if (CdiUtil.createCdiUtil().findBean(PermissionChecker.class) - .isPermitted(CoreConstants.PRIVILEGE_ADMIN)) { - link(sreq, nav, "cms:adminCenter", m_adminPath, adminTitle); - } - - link(sreq, nav, "cms:workspace", m_wspcPath, wspcTitle); - link(sreq, nav, "cms:changePassword", m_changePasswordPath, - changePasswordTitle); - link(sreq, nav, "cms:signOut", m_signOutPath, signOutTitle); - link(sreq, nav, "cms:help", m_helpPath, helpTitle); - } - } - - /** - * - * @param sreq - * @param parent - * @param name - * @param path - * @param title - * - * @return - */ - private static Element link(final HttpServletRequest sreq, - final Element parent, - final String name, - final String path, - final String title) { - final Element link = parent.newChildElement(name, CMS.CMS_XML_NS); - - link.addAttribute("href", URL.there(sreq, path).toString()); - link.addAttribute("title", title); - - return link; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ImagesPane.java.todo b/ccm-cms/src/main/java/com/arsdigita/cms/ui/ImagesPane.java.todo deleted file mode 100644 index 897899eb4..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ImagesPane.java.todo +++ /dev/null @@ -1,265 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.FormModel; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.List; -import com.arsdigita.bebop.MapComponentSelectionModel; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.SegmentedPanel; -import com.arsdigita.bebop.SegmentedPanel.Segment; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.event.ChangeEvent; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.util.GlobalizationUtil; -import com.arsdigita.toolbox.ui.ActionGroup; -import com.arsdigita.toolbox.ui.LayoutPanel; -import com.arsdigita.toolbox.ui.Section; -import com.arsdigita.util.Assert; -import com.arsdigita.util.LockableImpl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import org.apache.log4j.Logger; - -/** - * A {@link LayoutPanel} to insert into {@link ContentSectionPage}. - * - * @author Sören Bernstein - */ -public class ImagesPane extends LayoutPanel implements Resettable { - - public static final Logger S_LOG = Logger.getLogger(ImagesPane.class); - private final StringParameter m_imageComponentKey; - private final MapComponentSelectionModel m_imageComponent; - private final ImageComponentAdminListener m_adminListener; - final private SegmentedPanel m_body; - private HashMap m_bodySegments = new HashMap(); - private final ResettableParameterSingleSelectionModel m_model; - private final List m_links; - private final LinksSection m_modes; - - public ImagesPane() { - super(); - - m_model = new ResettableParameterSingleSelectionModel(new - StringParameter(List.SELECTED)); - m_model.setDefaultSelection(ImageComponent.LIBRARY); - m_model.addChangeListener(new ImageAdminSelectionListener()); - - m_links = new List(new ImageAdminListModelBuilder()); - m_links.setSelectionModel(m_model); - - final SimpleContainer left = new SimpleContainer(); - setLeft(left); - - m_modes = new LinksSection(); - left.add(m_modes); - - m_body = new SegmentedPanel(); - setBody(m_body); - - m_imageComponentKey = new StringParameter("imageComponent"); - - final ParameterSingleSelectionModel componentModel = new - ParameterSingleSelectionModel(m_imageComponentKey); - m_imageComponent = new MapComponentSelectionModel(componentModel, - new HashMap()); - - final Map selectors = m_imageComponent.getComponentsMap(); - m_adminListener = new ImageComponentAdminListener(m_imageComponent, this); - - // Image library component - final ImageLibraryComponent library = new - ImageLibraryComponent(ImageComponent.ADMIN_IMAGES); - library.getForm().addInitListener(m_adminListener); - library.getForm().addProcessListener(m_adminListener); - selectors.put(ImageComponent.LIBRARY, library); - m_bodySegments.put(ImageComponent.LIBRARY, m_body.addSegment( - new Label(GlobalizationUtil.globalize( - "cms.contentasset.image.ui.image_library")), - library)); - - // Image upload component - final ImageUploadComponent upload = new - ImageUploadComponent(ImageComponent.ADMIN_IMAGES); - upload.getForm().addInitListener(m_adminListener); - upload.getForm().addSubmissionListener(m_adminListener); - upload.getForm().addProcessListener(m_adminListener); - selectors.put(ImageComponent.UPLOAD, upload); - m_bodySegments.put(ImageComponent.UPLOAD, m_body.addSegment( - new Label(GlobalizationUtil.globalize( - "cms.contentasset.image.ui.image_upload")), - upload)); - - } - - @Override - public final void register(final Page page) { - super.register(page); - - Iterator keys = m_bodySegments.keySet().iterator(); - - while (keys.hasNext()) { - String key = keys.next(); - page.setVisibleDefault(m_bodySegments.get(key), - m_model.getDefaultSelection().equals(key)); - } - - page.addComponentStateParam(this, m_imageComponentKey); - } - - /** - * Resets this pane and all its resettable components. - * - * @param state Page state - */ - @Override - public final void reset(final PageState state) { - super.reset(state); - - m_model.reset(state); - this.setActiveImageComponent(state, m_model.getDefaultSelection()); - } - - public final void setActiveImageComponent(PageState state, String activeComp) { - - Iterator keys = m_bodySegments.keySet().iterator(); - m_imageComponent.setSelectedKey(state, activeComp); - - while (keys.hasNext()) { - - String key = keys.next(); - final boolean visibility = key.equals(activeComp); - state.setVisible(m_bodySegments.get(key), visibility); - - for (int index = 0; index < m_bodySegments.get(key).size(); index++) { - - Component component = m_bodySegments.get(key).get(index); - - // Reset all components if they are of type Resettable - if (component instanceof Resettable) { - ((Resettable) component).reset(state); - } - - // Set visibility - component.setVisible(state, visibility); - } - } - } - - /** - * - */ - private class ResettableParameterSingleSelectionModel - extends ParameterSingleSelectionModel - implements Resettable { - - private String defaultKey; - - public ResettableParameterSingleSelectionModel(ParameterModel m) { - super(m); - } - - public void setDefaultSelection(String selKey) { - this.defaultKey = selKey; - } - - public String getDefaultSelection() { - return defaultKey; - } - - public void reset(PageState state) { - - if (Assert.isEnabled()) { - final FormModel model = state.getPage().getStateModel(); - Assert.isTrue(model.containsFormParam(getStateParameter())); - } - - state.setValue(getStateParameter(), this.defaultKey); - } - } - - /** - * - */ - private class ImageAdminListModel implements ListModel { - - private ArrayList m_keys; - private int m_index = -1; - - public ImageAdminListModel(ArrayList keys) { - m_keys = keys; - } - - public boolean next() { - return (m_index++ < m_keys.size() - 1); - } - - public Object getElement() { - return GlobalizationUtil.globalize( - "cms.contentasset.image.ui.image_" + m_keys.get(m_index)).localize(); - } - - public String getKey() { - return m_keys.get(m_index); - } - } - - private class ImageAdminListModelBuilder extends LockableImpl - implements ListModelBuilder { - - public ListModel makeModel(final List list, final PageState state) { - ArrayList keys = new ArrayList(2); - keys.add(ImageComponent.LIBRARY); - keys.add(ImageComponent.UPLOAD); - return new ImageAdminListModel(keys); - } - } - - private class ImageAdminSelectionListener implements ChangeListener { - - public final void stateChanged(final ChangeEvent e) { - S_LOG.debug("Selection state changed; I may change " - +"the body's visible pane"); - - final PageState state = e.getPageState(); - -// ImagesPane.this.reset(state); - - if (m_model.isSelected(state)) { - S_LOG.debug("The selection model is selected; displaying " - +"the item pane"); - - ImagesPane.this.setActiveImageComponent( - state, - state.getControlEventValue()); - } - } - } - - private class LinksSection extends Section { - - LinksSection() { - setHeading(GlobalizationUtil.globalize( - "cms.contentasset.image.ui.images")); - - final ActionGroup group = new ActionGroup(); - setBody(group); - - group.setSubject(m_links); - } - } -} \ No newline at end of file diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ItemSearch.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/ItemSearch.java deleted file mode 100755 index 05b157226..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ItemSearch.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.SimpleContainer; - -import org.librecms.contentsection.ContentItem; - -/** - * A wrapper around the {@link ItemSearchSection} which embeds the form section - * in a form. - * - * @author Stanislav Freidin (sfreidin@arsdigita.com) - * @author Jens Pelzetter - */ -public class ItemSearch extends Form implements Resettable { - - public static final String SINGLE_TYPE_PARAM = ItemSearchSection.SINGLE_TYPE_PARAM; - - private ItemSearchSection itemSearchSection; - - /** - * Construct a new ItemSearch component Default to limit the - * search to current content section - * - * @param context the context for the retrieved items. Should be - * {@link ContentItem#DRAFT} or {@link ContentItem#LIVE} - */ - public ItemSearch(String context) { - this(context, true); - } - - /** - * Construct a new ItemSearch component - * - * @param context the context for the retrieved items. Should be - * {@link ContentItem#DRAFT} or {@link ContentItem#LIVE} - * @param limitToContentSection limit the search to the current content - * section - */ - public ItemSearch(final String context, - final boolean limitToContentSection) { - super("itemSearch", new SimpleContainer()); - //setMethod("GET"); - itemSearchSection = createSearchSection(context, limitToContentSection); - super.add(itemSearchSection); - } - - protected ItemSearchSection createSearchSection(final String context, - boolean limitToContentSection) { - return new ItemSearchSection(context, limitToContentSection); - } - - @Override - public void reset(final PageState state) { - itemSearchSection.reset(state); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ItemSearchSection.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/ItemSearchSection.java deleted file mode 100755 index 11f6a1381..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ItemSearchSection.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.Container; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.FormSection; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.parameters.BigDecimalParameter; - -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentType; - -import com.arsdigita.cms.ui.search.ItemQueryComponent; -import com.arsdigita.globalization.GlobalizedMessage; - -import com.arsdigita.search.ui.ResultsPane; -import com.arsdigita.search.ui.QueryGenerator; -import com.arsdigita.toolbox.ui.LayoutPanel; - -import org.librecms.CmsConstants; - -/** - * Contains a form for specifying search parameters, as well as a - * {@link com.arsdigita.search.ui.ResultsPane} which will perform the search and - * display the results - * - * @author Stanislav Freidin (sfreidin@arsdigita.com) - * @version $Id: ItemSearchSection.java 1940 2009-05-29 07:15:05Z terry $ - */ -public class ItemSearchSection extends FormSection implements Resettable { - - public static final String SINGLE_TYPE_PARAM = "single_type"; - - private ItemQueryComponent itemQueryComponent; - private Component resultsComponent; - - /** - * Construct a new ItemSearchSection component - * - * @param context the context for the retrieved items. Should be - * {@link ContentItem#DRAFT} or {@link ContentItem#LIVE} - * @param limitToContentSection limit the search to the current content - * section - */ - public ItemSearchSection(final String context, - final boolean limitToContentSection) { - this(null, context, limitToContentSection); - } - - /** - * Construct a new ItemSearchSection component - * - * @param context the context for the retrieved items. Should be - * {@link ContentItem#DRAFT} or {@link ContentItem#LIVE} - * @param name The name of the search parameter for the particular - * FormSection - * @param limitToContentSection limit the search to the current content - * section - */ - public ItemSearchSection(final String name, - final String context, - final boolean limitToContentSection) { - this(name, context, limitToContentSection, null); - } - - public ItemSearchSection(final String name, - final String context, - final boolean limitToContentSection, - final ContentType type) { - super(new SimpleContainer()); - final String thisName; - if (name == null) { - thisName = "itemSearch"; - } else { - thisName = name; - } - - if (type == null) { - itemQueryComponent = createQueryGenerator(context, - limitToContentSection); - } else { - itemQueryComponent = createQueryGenerator(context, - limitToContentSection, - type); - } - resultsComponent = createResultsPane(itemQueryComponent); - - LayoutPanel searchPanel = new LayoutPanel(); - searchPanel.setLeft(itemQueryComponent); - searchPanel.setBody(resultsComponent); - this.add(searchPanel); - - addQueryGenerator(this); - addResultsPane(this); - addFormListener(); - - setClassAttr("itemSearch"); - } - - - @Override - public void reset(final PageState state) { - resultsComponent.setVisible(state, false); - } - - protected ItemQueryComponent createQueryGenerator( - final String context, final boolean limitToContentSection) { - return new ItemQueryComponent(context, limitToContentSection); - } - - protected ItemQueryComponent createQueryGenerator( - final String context, - final boolean limitToContentSection, - final ContentType type) { - - return new ItemQueryComponent(context, limitToContentSection, type); - } - - protected Component createResultsPane(QueryGenerator generator) { - ResultsPane pane = new ResultsPane(generator); - pane.setRelativeURLs(true); - pane.setSearchHelpMsg(new GlobalizedMessage("cms.ui.search.help", - CmsConstants.CMS_BUNDLE)); - pane.setNoResultsMsg(new GlobalizedMessage("cms.ui.search.no_results", - CmsConstants.CMS_BUNDLE)); - return pane; - } - - protected void addResultsPane(final Container container) { - container.add(resultsComponent); - } - - protected void addQueryGenerator(final Container container) { - container.add(itemQueryComponent); - } - - protected void processQuery(final PageState state) { - resultsComponent.setVisible(state, itemQueryComponent.hasQuery(state)); - } - - protected void addFormListener() { - addProcessListener(new SearchFormProcessListener()); - } - - // Hide results by default - @Override - public void register(final Page page) { - super.register(page); - page.setVisibleDefault(resultsComponent, false); - page.addGlobalStateParam(new BigDecimalParameter(SINGLE_TYPE_PARAM)); - } - - /** - * Displays the "keywords" and "content types" widgets - */ - private class SearchFormProcessListener implements FormProcessListener { - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - PageState s = event.getPageState(); - processQuery(s); - } - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ListOptionPrintListener.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/ListOptionPrintListener.java deleted file mode 100755 index 82a6fa705..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ListOptionPrintListener.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.OptionGroup; - -import java.util.List; - -/** - * Migrated from the {@code DataQueryOptionPrintListener} in the old system. - * Renamed and refactored to operate on a list. - * - * @author Jens Pelzetter - * - * @param Type of the objects in the list. - */ -public abstract class ListOptionPrintListener implements PrintListener { - - public ListOptionPrintListener() { - } - - protected abstract List getDataQuery(final PageState state); - - @Override - public void prepare(final PrintEvent event) { - final PageState state = event.getPageState(); - final OptionGroup target = (OptionGroup) event.getTarget(); - final List dataQuery = getDataQuery(state); - - target.clearOptions(); - - dataQuery.forEach(item -> target.addOption( - new Option(getKey(item), - getValue(item)))); - } - - public abstract String getKey(final T object); - - public String getValue(final T object) { - return getKey(object); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/PartyAddForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/PartyAddForm.java deleted file mode 100755 index f8ffdbbcd..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/PartyAddForm.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.CheckboxGroup; -import com.arsdigita.bebop.form.Hidden; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.OptionGroup; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.Widget; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.xml.Element; - -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.security.Party; -import org.librecms.CmsConstants; - -import java.util.List; -import java.util.TooManyListenersException; - -/** - * Form for adding multiple parties to a role. - * - * @author Scott Seago (scott@arsdigita.com) - * @author Yannick Bülter - */ -public abstract class PartyAddForm extends SimpleContainer - implements FormInitListener, FormProcessListener { - - private final static String SEARCH_QUERY = "searchQuery"; - private final static String PARTIES = "parties"; - private final static String SUBMIT = "addSubmit"; - private final static String CANCEL = "addCancel"; - - private Widget searchWidget; - private RequestLocal queryRequestLocal; - - private CMSContainer noMatchesContainer; - private CMSContainer matchesContainer; - - private Form form; - private Hidden searchQueryField; - private Submit cancelButton; - - /** - * Private access prevents this constructor from ever being called directly. - */ - private PartyAddForm() { - super(); - } - - /** - * Constructor. - * - * @param searchWidget The widget on the search form that contains the value - * of the search string. - */ - public PartyAddForm(final Widget searchWidget) { - - this(); - - this.searchWidget = searchWidget; - - queryRequestLocal = new RequestLocal() { - - @Override - protected Object initialValue(final PageState state) { - return makeQuery(state); - } - - }; - - form = makeForm(); - - final Label title = new Label(new GlobalizedMessage("cms.ui.matches", - CmsConstants.CMS_BUNDLE)); - title.setFontWeight(Label.BOLD); - - final Label label = new Label(new GlobalizedMessage( - "cms.ui.there_was_no_one_matching_the_search_criteria", - CmsConstants.CMS_BUNDLE)); - label.setFontWeight("em"); - - noMatchesContainer = new CMSContainer(); - noMatchesContainer.add(title); - noMatchesContainer.add(label); - super.add(noMatchesContainer); - - matchesContainer = new CMSContainer(); - matchesContainer.add(title); - matchesContainer.add(form); - super.add(matchesContainer); - } - - /** - * Build the form used to add parties. - * - * @return The form - */ - private Form makeForm() { - - final CMSForm addPartyForm = new CMSForm("AddParties") { - - @Override - public final boolean isCancelled(final PageState state) { - return cancelButton.isSelected(state); - } - - }; - - // This hidden field will store the search query. A hidden widget is - // used instead of a request local variable because the search query - // should only be updated when the search form is submitted. - searchQueryField = new Hidden(SEARCH_QUERY); - addPartyForm.add(searchQueryField, ColumnPanel.FULL_WIDTH); - - final Label hintLabel = new Label( - new GlobalizedMessage("cms.ui.party_add_form.hint", - CmsConstants.CMS_BUNDLE)); - addPartyForm.add(hintLabel, ColumnPanel.FULL_WIDTH); - - // Add the list of parties that can be added. - final CheckboxGroup partyCheckboxes = new CheckboxGroup(PARTIES); - partyCheckboxes.addValidationListener(new NotNullValidationListener()); - try { - partyCheckboxes.addPrintListener(event -> { - final CheckboxGroup target = (CheckboxGroup) event.getTarget(); - final PageState state = event.getPageState(); - // Ensures that the init listener gets fired before the - // print listeners. - final FormData data = addPartyForm.getFormData(state); - addParties(state, target); - }); - } catch (TooManyListenersException ex) { - throw new UnexpectedErrorException(ex); - } - addPartyForm.add(partyCheckboxes, ColumnPanel.FULL_WIDTH); - - // Submit and Cancel buttons. - final SimpleContainer buttonContainer = new SimpleContainer(); - final Submit submitButton = new Submit(SUBMIT, - new GlobalizedMessage( - "cms.ui.save", - CmsConstants.CMS_BUNDLE)); - buttonContainer.add(submitButton); - cancelButton = new Submit(CANCEL, - new GlobalizedMessage("cms.ui.cancel", - CmsConstants.CMS_BUNDLE)); - buttonContainer.add(cancelButton); - addPartyForm.add(buttonContainer, ColumnPanel.FULL_WIDTH - | ColumnPanel.CENTER); - - addPartyForm.addInitListener(this); - addPartyForm.addProcessListener(this); - - return addPartyForm; - } - - /** - * Fetches the form for adding parties. - * - * @return The "add party" form - */ - public Form getForm() { - return form; - } - - /** - * Fetches the widget that contains the search string. - * - * @return The widget that contains the search string - */ - protected Widget getSearchWidget() { - return searchQueryField; - } - - /** - * Return true if the form is cancelled, false otherwise. - * - * @param state The page state - * - * @return true if the form is cancelled, false otherwise. - * - * @pre ( state != null ) - */ - public boolean isCancelled(final PageState state) { - return cancelButton.isSelected(state); - } - - /** - * Adds parties to the option group. - * - * @param state The page state - * @param target The option group - * - * @pre ( state != null && target != null ) - */ - private void addParties(final PageState state, final OptionGroup target) { - - @SuppressWarnings("unchecked") - final List parties = (List) queryRequestLocal.get(state); - - target.clearOptions(); - - for (final Party party : parties) { - target.addOption(new Option( - Long.toString(party.getPartyId()), - new Label(new GlobalizedMessage(party.getName())) - )); - } - } - - /** - * Generates a {@link Object} that encapsulates search results. - * - * @param state The page state - * - * @return - */ - protected abstract List makeQuery(PageState state); - - /** - * Stores the search query in the hidden field. - * - * @param event The form event - * - * @throws com.arsdigita.bebop.FormProcessException - */ - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - - PageState state = event.getPageState(); - - searchQueryField.setValue(state, searchWidget.getValue(state)); - } - - /** - * Process listener for the "Add parties" form. - * - * @param event The form event - * - * @throws com.arsdigita.bebop.FormProcessException - */ - @Override - public abstract void process(FormSectionEvent event) - throws FormProcessException; - - /** - * Displays the appropriate frame. - * - * @param state The page state - * @param parent The parent DOM element - */ - @Override - public void generateXML(final PageState state, final Element parent) { - - @SuppressWarnings("unchecked") - final List searchResults = (List) queryRequestLocal.get(state); - - if (searchResults.size() > 0) { - matchesContainer.generateXML(state, parent); - } else { - noMatchesContainer.generateXML(state, parent); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/PartySearchForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/PartySearchForm.java deleted file mode 100755 index f4f35c4e8..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/PartySearchForm.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.util.Assert; - -/** - * Form to search for parties to be added to a staff group. - * - * @author Scott Seago <sseago@redhat.com> - * @version $Id: PartySearchForm.java 1942 2009-05-29 07:53:23Z terry $ - */ -public class PartySearchForm extends BaseForm { - - private final TextField searchField; - - public PartySearchForm() { - super("SearchParties", gz("cms.ui.search")); - - addComponent(new Label(gz("cms.ui.search_prompt"))); - - searchField = new TextField(new StringParameter("query")); - searchField.setSize(40); - addComponent(searchField); - - addAction(new Submit("finish", gz("cms.ui.search"))); - addAction(new Cancel()); - - } - - @Override - public final void register(final Page page) { - super.register(page); - - Assert.isTrue(page.stateContains(this)); - } - - public TextField getSearchWidget() { - return searchField; - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ReportPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/ReportPane.java deleted file mode 100644 index 0eb5efee3..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/ReportPane.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (C) 2009 Permeance Technologies Pty Ltd. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -package com.arsdigita.cms.ui; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.List; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.ChangeEvent; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ui.report.ContentSectionSummaryTable; -import com.arsdigita.cms.ui.report.Report; -import com.arsdigita.cms.ui.report.ReportListModel; -import com.arsdigita.toolbox.ui.ActionGroup; -import com.arsdigita.toolbox.ui.Section; -import com.arsdigita.util.LockableImpl; - -/** - * A pane that shows selectable reports and their results. A selectable list of - * reports is shown on the left-hand side, a selected report is shown as body. - * - * @author - * thomas-buckel - * @author - * tim-permeance - * @author Jens Pelzetter - */ -public class ReportPane extends BaseAdminPane { - - private final SingleSelectionModel selectionModel; - private final java.util.List availableReports; - - public ReportPane() { - availableReports = getReports(); - - selectionModel = new ParameterSingleSelectionModel<>( - new StringParameter(List.SELECTED)); - selectionModel.addChangeListener(new SelectionListener()); - setSelectionModel(selectionModel); - - List m_reports = new List(new ReportListModelBuilder(availableReports)); - m_reports.setSelectionModel(selectionModel); - - final ReportsListSection reportsListSection = new ReportsListSection( - m_reports); - setLeft(reportsListSection); - - // Register the actual components of the reports for later usage - for (Report report : availableReports) { - getBody().add(report.getComponent()); - } - - setIntroPane(new Label(gz("cms.ui.reports.intro"))); - } - - /** - * @return List of available reports. - */ - private java.util.List getReports() { - java.util.List reports = new ArrayList<>(); - reports.add(new Report("cms.ui.reports.css.reportName", - new ContentSectionSummaryTable())); - // Add other reports as required - - Collections.sort( - reports, - (r1, r2) -> r1.getName().compareTo(r2.getName())); - - return reports; - } - - /** - * Get the report model that matches the given key. - * - * @param key Key to match. - * - * @return Report model that matches that given key, null if no matching - * report was found. - */ - private Report getReportByKey(final String key) { - for (Report report : availableReports) { - if (report.getKey().equals(key)) { - return report; - } - } - return null; - } - - /** - * UI section for left-hand list of reports. - */ - private class ReportsListSection extends Section { - - ReportsListSection(final List reports) { - setHeading(gz("cms.ui.reports.header")); - ActionGroup group = new ActionGroup(); - setBody(group); - group.setSubject(reports); - } - - } - - /** - * SelectionListener for selected report. It shows the selected report in - * the body of this component. - */ - private class SelectionListener implements ChangeListener { - - @Override - public final void stateChanged(final ChangeEvent event) { - - final PageState state = event.getPageState(); - - getBody().reset(state); - - if (selectionModel.isSelected(state)) { - Report selectedReport = getReportByKey(selectionModel - .getSelectedKey(state).toString()); - if (selectedReport != null) { - getBody().push(state, selectedReport.getComponent()); - } - } - } - - } - - /** - * ListModelBuilder creating a ReportListModel for a list of reports. - */ - private static class ReportListModelBuilder - extends LockableImpl - implements ListModelBuilder { - - private final java.util.List reports; - - private ReportListModelBuilder(final java.util.List reports) { - this.reports = reports; - } - - @Override - public final ListModel makeModel(final List list, - final PageState state) { - return new ReportListModel(reports); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/SecurityPropertyEditor.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/SecurityPropertyEditor.java deleted file mode 100755 index 91fd9ecb3..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/SecurityPropertyEditor.java +++ /dev/null @@ -1,392 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.FormSection; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.PropertyEditor; -import com.arsdigita.bebop.PropertyEditorModel; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.ComponentAccess; -import com.arsdigita.util.Assert; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.librecms.CmsConstants; - -/** - * Extends {@link com.arsdigita.bebop.PropertyEditor} to provide access control - * features. Each link may be associated with a {@link - * com.arsdigita.toolbox.ui.ComponentAccess} object; if the current does not - * have sufficient privileges, the link will be hidden. - *

- * The simple use pattern for this component is as follows: - * - *


- * SecurityPropertyEditor editor = new SecurityPropertyEditor();
- * editor.setDisplayComponent(new FooComponent());
- * NameEditForm n = new NameEditForm();
- * ComponentAccess ca1 = new ComponentAccess(n);
- * ca1.addAccessCheck(WORKFLOW_ADMIN);
- * ca1.addAccessCheck(CATEGORY_ADMIN);
- * editor.add("name", "Edit Name", ca, n.getCancelButton());
- * AddressEditForm a = new AddressEditForm();
- * ComponentAccess ca2 = new ComponentAccess(a);
- * editor.add("address", "Edit Address", ca2, a.getCancelButton());
- * 
- * - * @author Michael Pih (pihman@arsdigita.com) - * @author Stanislav Freidin (sfreidin@arsdigita.com) - * @author Jens Pelzetter - */ -public class SecurityPropertyEditor extends PropertyEditor { - - private final Map accessChecks; - - /** - * Construct a new, empty PropertyEditor. The {@link - * #setDisplayComponent(Component)} method must be called before this - * component is locked. - */ - public SecurityPropertyEditor() { - this(null); - } - - /** - * Construct a new, PropertyEditor with the given display - * component - * - * @param display The display component - */ - public SecurityPropertyEditor(final Component display) { - super(display); - accessChecks = new HashMap<>(); - setModelBuilder(new AccessListModelBuilder()); - } - - /** - * Add a component to the property editor. The component will be completely - * invisible; it is up to the user to call {@link #showComponent(PageState, - * String)} to display the component, and to call {@link - * #showDisplayPane(PageState)} when the component needs to be hidden. - * - * @param key The symbolic key for the component; must be unique for this - * PropertyEditor - * @param componentAccess The {@link ComponentAccess} object which contains - * the child component, along with security restrictions - */ - public void addComponent(final String key, - final ComponentAccess componentAccess) { - super.addComponent(key, componentAccess.getComponent()); - accessChecks.put(key, componentAccess); - } - - /** - * Add a component to the list of links. It is up to the component to - * correctly call showDisplayPane when it's done. - * - * @param key The symbolic key for the component; must be unique for this - * PropertyEditor - * @param label The label for the link - * @param componentAccess The component access - * @deprecated use addComponent(String,GlobalizedMessage,ComponentAccess) - * instead. - */ - public void addComponent(final String key, - final String label, - final ComponentAccess componentAccess) { - addComponent(key, componentAccess); - getLabelsMap().put(key, label); - } - - /** - * Add a component to the list of links. It is up to the component to - * correctly call showDisplayPane when it's done. - * - * @param key The symbolic key for the component; must be unique for this - * PropertyEditor - * @param label The label for the link - * @param componentAccess The component access - */ - public void addComponent(final String key, - final GlobalizedMessage label, - final ComponentAccess componentAccess) { - addComponent(key, componentAccess); - getLabelsMap().put(key, label); - } - - /** - * Specify a new {@link ComponentAccess} for a component which has already - * been added to the SecurityPropertyEditor. - * - * @param key the key under which the component was added - * @param componentAccess the ComponentAccess instance that - * will determine when the link for the specified component should be - * visible - * @pre access.getComponent() == m_forms.get(key) - */ - public void setComponentAccess(final String key, - final ComponentAccess componentAccess) { - Assert.isUnlocked(this); - final Component component = getComponent(key); - Assert.exists(component, "the specified component"); - Assert.isTrue(componentAccess.getComponent().equals(component), - "The specified component does not match the component that" - + " id already in the PropertyEditor"); - accessChecks.put(key, componentAccess); - } - - /** - * Add a form to the set of forms which could be used to edit the - * properties. - * - * @param key The symbolic key for the form; must be unique for this - * PropertyEditor - * @param label The label for the link to access the form - * @param componentAccess The form ComponentAccess - * - * @deprecated use add(String,GlobalizedMessage,ComponentAccess) - */ - public void add(final String key, - final String label, - final ComponentAccess componentAccess) { - final Component component = componentAccess.getComponent(); - if (component instanceof Form) { - final Form form = (Form) component; - accessChecks.put(key, componentAccess); - add(key, label, form); - addSecurityListener(form); - } else if (component instanceof FormSection) { - final FormSection section = (FormSection) componentAccess. - getComponent(); - accessChecks.put(key, componentAccess); - add(key, label, section); - addSecurityListener(section); - } else { - throw new IllegalArgumentException( - "The ComponentAccess object does " - + "not contain a form section."); - } - } - - /** - * Add a form to the set of forms which could be used to edit the - * properties. - * - * @param key The symbolic key for the form; must be unique for this - * PropertyEditor - * @param label The label for the link to access the form - * @param componentAccess The form ComponentAccess - */ - public void add(final String key, - final GlobalizedMessage label, - final ComponentAccess componentAccess) { - final Component component = componentAccess.getComponent(); - if (component instanceof Form) { - final Form form = (Form) component; - accessChecks.put(key, componentAccess); - add(key, label, form); - addSecurityListener(form); - } else if (component instanceof FormSection) { - final FormSection section = (FormSection) componentAccess. - getComponent(); - accessChecks.put(key, componentAccess); - add(key, label, section); - addSecurityListener(section); - } else { - throw new IllegalArgumentException( - "The ComponentAccess object does " - + "not contain a form section."); - } - } - - /** - * Add a form to the set of forms which could be used to edit the properties - * - * @param key The symbolic key for the form; must be unique for this - * PropertyEditor - * @param label The label for the link to access the form. - * @param componentAccess The form ComponentAccess - * @param cancelButton The Cancel button on the form. - * - * @deprecated use add(String,GlobalizedMessage,ComponentAccess,Submit) - * instead - */ - public void add(final String key, - final String label, - final ComponentAccess componentAccess, - final Submit cancelButton) { - add(key, label, componentAccess); - addCancelListener((FormSection) componentAccess.getComponent(), - cancelButton); - } - - /** - * Add a form to the set of forms which could be used to edit the properties - * - * @param key The symbolic key for the form; must be unique for this - * PropertyEditor - * @param label The label for the link to access the form. - * @param componentAccess The form ComponentAccess - * @param cancelButton The Cancel button on the form. - */ - public void add(final String key, - final GlobalizedMessage label, - final ComponentAccess componentAccess, - final Submit cancelButton) { - add(key, label, componentAccess); - addCancelListener((FormSection) componentAccess.getComponent(), - cancelButton); - } - - /** - * Add a submission listener to the form that will hide all components and - * show the display pane. This method should be used to add submission - * listeners to forms which are buried deep inside some component, and are - * not members of this PropertyEditor. - * - * @param form The form - */ - public void addSecurityListener(final FormSection form) { - form.addSubmissionListener(new FormSubmissionListener() { - - @Override - public void submitted(final FormSectionEvent event) throws - FormProcessException { - - final PageState state = event.getPageState(); - - // Cancel the form if the user does not pass the access checks. - final String key = (String) getList().getSelectedKey(state); - final ComponentAccess componentAccess - = (ComponentAccess) accessChecks.get(key); - - if (key == null || componentAccess == null) { - // no components currently selected and therefore - // no access checks to run for visibility - // or - // there are no access restrictions on the form - return; - } - - if (!componentAccess.canAccess()) { - showDisplayPane(state); - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.insufficient_privileges", - CmsConstants.CMS_BUNDLE)); - } - } - }); - } - - /** - * Add all required listeners to the form to ensure that if the form is - * submitted successfully or cancelled, the display pane will be shown. This - * method should be used to add listeners to forms which are buried deep - * inside some component, and are not members of this - * PropertyEditor. - * - * @param form The form - * @param cancelButton the "Cancel" button on the form - */ - @Override - public void addListeners(final FormSection form, - final Submit cancelButton) { - addSecurityListener(form); - super.addListeners(form, cancelButton); - } - - /** - * Return the map of keys to access checks - * - * @return Map of keys to access check - */ - protected final Map getAccessMap() { - return accessChecks; - } - - /** - * Returns an {@link SecurityPropertyEditor.AccessListModel} during each - * request - */ - protected static class AccessListModelBuilder extends DefaultModelBuilder { - - public AccessListModelBuilder() { - super(); - } - - @Override - public PropertyEditorModel makeModel( - final PropertyEditor propertyEditor, final PageState state) { - - return new AccessListModel( - getProperties(propertyEditor), - ((SecurityPropertyEditor) propertyEditor).getAccessMap(), - state); - } - } - - /** - * Performs access checks for each property; skips the properties that the - * user is not allowed to access - */ - protected static class AccessListModel extends DefaultModel { - - private final Map accessMap; - private final PageState state; - - public AccessListModel(final Iterator iter, - final Map accessMap, - final PageState state) { - super(iter); - this.accessMap = accessMap; - this.state = state; - } - - @Override - public boolean next() { - - while (super.next()) { - final Object key = getKey(); - final ComponentAccess ca = accessMap.get(key.toString()); - - if (ca == null) { - return true; - } - - if (ca.canAccess()) { - return true; - } - - // Otherwise, skip the property - } - - return false; - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/SortableList.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/SortableList.java deleted file mode 100755 index 020183214..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/SortableList.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.List; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.util.BebopConstants; -import com.arsdigita.cms.CMS; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.Assert; -import com.arsdigita.xml.Element; - -import java.io.IOException; - -/** - * This list offers the option for the code to provide the developer with links - * to sort the given categories. - * - * NOTE: This UI currently does not scale well with large numbers of items since - * it just lists all of them. It would probably be nice to integrate a paginator - * as well to as to allow the user to move an item in large distances and to - * insert an item in the middle. Right now, when you add an item it is just - * placed at the end. However, if you want the item to appear in the middle then - * you must hit the "up" arrow n/2 times where n is the number of items in the - * list. This clearly is not a good setup. - * - * - * @author Randy Graebner (randyg@alum.mit.edu) - * @author Yannick Bülter - */ -public abstract class SortableList extends List { - - // It would be really nice if this used the save variable as is - // used by List but because List has it as private, we cannot do that. - private static final String SELECT_EVENT = "s"; - protected static final String PREV_EVENT = "prev"; - protected static final String NEXT_EVENT = "next"; - public boolean m_sortItems; - - /** - * This just makes a standard {@link SortableList} - */ - public SortableList(ParameterSingleSelectionModel model) { - this(model, false); - } - - public SortableList(ParameterSingleSelectionModel model, - boolean suppressSort) { - super(model); - m_sortItems = !suppressSort; - } - - /** - * This geneates the XML as specified by the arguments pass in to the - * constructor. - */ - public void generateXML(PageState state, Element parent) { - if (!isVisible(state)) { - return; - } - - // They want the special sort items - ListModel m = getModel(state); - - if (!m.next()) { - super.generateXML(state, parent); - return; - } - - // because m.next() returned true, we know there are items - // in the list - Element list = parent - .newChildElement("cms:sortableList", CMS.CMS_XML_NS); - exportAttributes(list); - - Component c; - Object selKey = getSelectedKey(state); - int i = 0; - boolean hasNext; - do { - Element item = list.newChildElement(BebopConstants.BEBOP_CELL, - BEBOP_XML_NS); - if (m_sortItems) { - - item.addAttribute("configure", "true"); - } - String key = m.getKey(); - Assert.exists(key); - - // Converting both keys to String for comparison - // since ListModel.getKey returns a String - boolean selected = (selKey != null) - && key.equals(selKey.toString()); - - if (selected) { - item.addAttribute("selected", "selected"); - } - - generateLabelXML(state, item, - new Label(new GlobalizedMessage(m.getElement() - .toString())), key, m.getElement()); - - hasNext = m.next(); - - // Add attributes containing URLs that fire control events - // for various portlet actions - try { - // Maybe add attribute containing URL for "move up" link - if (i > 0) { - state.setControlEvent(this, PREV_EVENT, key); - item.addAttribute("prevURL", state.stateAsURL()); - } - - // Maybe add attribute containing URL for "move down" link - if (hasNext) { - state.setControlEvent(this, NEXT_EVENT, key); - item.addAttribute("nextURL", state.stateAsURL()); - } - - } catch (IOException ex) { - throw new IllegalStateException("Caught IOException: " - + ex.getMessage()); - } - i++; - } while (hasNext); - - state.clearControlEvent(); - } - - protected void generateLabelXML(PageState state, Element parent, - Label label, String key, Object element) { - state.setControlEvent(this, SELECT_EVENT, key); - Component c = new ControlLink(label); - c.generateXML(state, parent); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/UserAddForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/UserAddForm.java deleted file mode 100755 index 269b57d7b..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/UserAddForm.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.CheckboxGroup; -import com.arsdigita.bebop.form.Hidden; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.OptionGroup; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.Widget; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.xml.Element; - -import org.libreccm.security.User; -import org.librecms.CmsConstants; - -import java.util.List; -import java.util.TooManyListenersException; - -/** - * Form for adding multiple users to a role. - * - * @author Michael Pih - * @author Uday Mathur - * @author Jens Pelzetter - */ -public abstract class UserAddForm extends SimpleContainer - implements FormProcessListener { - - private final static String SEARCH_QUERY = "searchQuery"; - private final static String USERS = "users"; - private final static String SUBMIT = "addSubmit"; - private final static String CANCEL = "addCancel"; - - private final static String DQ_USER_ID = "userId"; - private final static String DQ_NAME = "name"; - - private Widget m_search; - private RequestLocal m_query; - private String m_label; - private String m_submitText; - - private CMSContainer m_noMatches; - private CMSContainer m_matches; - - private Form m_form; - private Hidden m_searchQuery; - private CheckboxGroup m_users; - private Submit m_submit; - private Submit m_cancel; - - /** - * Constructor. - * - * @param search The widget on the search form that contains the value of - * the search string. - */ - public UserAddForm(final Widget search) { - this(search, "AddUsers"); - } - - public UserAddForm(final Widget search, final String name) { - this(search, name, - "Check the box next to the name of the person(s) to assign.", - "Add Members"); - } - - public UserAddForm(final Widget search, - final String name, - final String text, - final String submitText) { - m_label = text; - m_submitText = submitText; - m_search = search; - - m_query = new RequestLocal() { - - @Override - protected Object initialValue(final PageState state) { - return makeQuery(state); - } - - }; - - m_form = makeForm(name); - - final Label title = new Label(new GlobalizedMessage("cms.ui.matches", - CmsConstants.CMS_BUNDLE)); - title.setFontWeight(Label.BOLD); - - final Label label = new Label(new GlobalizedMessage( - "cms.ui.there_was_no_one_matching_the_search_criteria", - CmsConstants.CMS_BUNDLE)); - label.setFontWeight("em"); - - m_noMatches = new CMSContainer(); - m_noMatches.add(title); - m_noMatches.add(label); - add(m_noMatches); - - m_matches = new CMSContainer(); - m_matches.add(title); - m_matches.add(m_form); - add(m_matches); - } - - /** - * Build the form used to add users. - * - * @param name - * - * @return The form - */ - protected Form makeForm(final String name) { - final CMSForm form = new CMSForm(name) { - - public final boolean isCancelled(final PageState state) { - return m_cancel.isSelected(state); - } - - }; - - // This hidden field will store the search query. A hidden widget is - // used instead of a request local variable because the search query - // should only be updated when the search form is submitted. - m_searchQuery = new Hidden(SEARCH_QUERY); - form.add(m_searchQuery, ColumnPanel.FULL_WIDTH); - - Label l = new Label(m_label); - form.add(l, ColumnPanel.FULL_WIDTH); - - // Add the list of users that can be added. - m_users = new CheckboxGroup(USERS); - m_users.addValidationListener(new NotNullValidationListener()); - try { - m_users.addPrintListener(new PrintListener() { - - @Override - public void prepare(PrintEvent event) { - CheckboxGroup target = (CheckboxGroup) event.getTarget(); - PageState state = event.getPageState(); - // Ensures that the init listener gets fired before the - // print listeners. - FormData data = m_form.getFormData(state); - addUsers(state, target); - } - - }); - } catch (TooManyListenersException ex) { - throw new RuntimeException(ex); - } - form.add(m_users, ColumnPanel.FULL_WIDTH); - - // Submit and Cancel buttons. - SimpleContainer s = new SimpleContainer(); - m_submit = new Submit(SUBMIT, m_submitText); - s.add(m_submit); - m_cancel = new Submit(CANCEL, "Cancel"); - s.add(m_cancel); - form.add(s, ColumnPanel.FULL_WIDTH | ColumnPanel.CENTER); - - form.addProcessListener(this); - - return form; - } - - /** - * Fetches the form for adding users. - * - * @return The "add user" form - */ - public Form getForm() { - return m_form; - } - - /** - * Fetches the widget that contains the search string. - * - * @return The widget that contains the search string - */ - protected Widget getSearchWidget() { - return m_searchQuery; - } - - /** - * Return true if the form is cancelled, false otherwise. - * - * @param state The page state - * - * @return true if the form is cancelled, false otherwise. - * - * @pre ( state != null ) - */ - public boolean isCancelled(final PageState state) { - return m_cancel.isSelected(state); - } - - /** - * Adds users to the option group. - * - * @param state The page state - * @param target The option group - * - * @pre ( state != null && target != null ) - */ - protected void addUsers(final PageState state, final OptionGroup target) { - - @SuppressWarnings("unchecked") - final List users = (java.util.List) m_query.get(state); - - users.forEach(user -> target.addOption( - new Option(Long.toString(user.getPartyId()), - user.getName()))); - } - - /** - * Generates a {@link List} that encapsulates search results. - * - * @param state The page state - * - * @return - */ - protected abstract List makeQuery(final PageState state); - - /** - * Process listener for the "Add users" form. - * - * @param event The form event - * - * @throws com.arsdigita.bebop.FormProcessException - */ - @Override - public abstract void process(final FormSectionEvent event) - throws FormProcessException; - - /** - * Displays the appropriate frame. - * - * @param state The page state - * @param parent The parent DOM element - */ - @Override - public void generateXML(final PageState state, - final Element parent) { - - m_searchQuery.setValue(state, m_search.getValue(state)); - @SuppressWarnings("unchecked") - final List searchResults = (List) m_query.get(state); - - if (searchResults.size() > 0) { - m_matches.generateXML(state, parent); - } else { - m_noMatches.generateXML(state, parent); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/UserSearchForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/UserSearchForm.java deleted file mode 100755 index 5192688c4..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/UserSearchForm.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; - -/** - * Form to search for users to be added to a staff group. - * - * - * @author Michael Pih - */ -public class UserSearchForm extends CMSForm { - - private final static String SEARCH_LABEL = "Search"; - - private TextField m_search; - - public UserSearchForm(String name) { - this(name, - new Label(new GlobalizedMessage( - "cms.ui.search_to_add_new_members", - CmsConstants.CMS_BUNDLE))); - - } - - public UserSearchForm(String name, Label heading) { - super(name, new ColumnPanel(3)); - heading.setFontWeight(Label.BOLD); - add(heading, ColumnPanel.FULL_WIDTH); - - add(new Label(new GlobalizedMessage( - "cms.ui.enter_first_name_last_name_andor_email_address", - CmsConstants.CMS_BUNDLE))); - - m_search = new TextField(new StringParameter("query")); - m_search.setSize(20); - add(m_search, ColumnPanel.RIGHT); - - Submit submit = new Submit("submit"); - submit.setButtonLabel(SEARCH_LABEL); - add(submit, ColumnPanel.LEFT); - } - - public TextField getSearchWidget() { - return m_search; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/VisibilityComponent.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/VisibilityComponent.java deleted file mode 100755 index db0375357..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/VisibilityComponent.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; -import com.arsdigita.toolbox.ui.ProxyComponent; -import com.arsdigita.util.Assert; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; - -/** - * @author Justin Ross - * @author Jens Pelzetter - */ -public class VisibilityComponent extends ProxyComponent { - - private final String m_action; - - public VisibilityComponent(final Component child, final String action) { - super(child); - - m_action = action; - } - - @Override - public boolean isVisible(final PageState state) { - return super.isVisible(state) && hasPermission(state); - } - - public boolean hasPermission(final PageState state) { - Assert.exists(m_action, String.class); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - - return permissionChecker.isPermitted(m_action); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/WorkspaceContextBar.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/WorkspaceContextBar.java deleted file mode 100755 index 1d8e9be84..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/WorkspaceContextBar.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.ContextBar; -import com.arsdigita.web.URL; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.web.ApplicationRepository; -import org.libreccm.web.CcmApplication; -import org.librecms.CmsConstants; - -import java.util.List; - -/** - *

- * The context bar of the content center UI.

- * - * @author Justin Ross - * @author Jens Pelzetter - */ -// Made public (instead of unspecified) in 6.6.8 -public class WorkspaceContextBar extends ContextBar { - - /** - * A logger instance, primarily to assist debugging . - */ - private static final Logger LOGGER = LogManager.getLogger( - WorkspaceContextBar.class); - - /** - * - * @param state - * - * @return - */ - @Override - protected List entries(final PageState state) { - - final List entries = super.entries(state); - - final String centerTitle = (String) new GlobalizedMessage( - "cms.ui.content_center", CmsConstants.CMS_BUNDLE).localize(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ApplicationRepository appRepo = cdiUtil.findBean( - ApplicationRepository.class); - final List apps = appRepo.findByType( - CmsConstants.CONTENT_CENTER_APP_TYPE); - - final String centerPath = apps.get(0).getPrimaryUrl(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Got Url: " + centerPath); - } - final URL url = URL.there(state.getRequest(), centerPath); - entries.add(new Entry(centerTitle, url)); - - return entries; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AbstractAssetForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AbstractAssetForm.java deleted file mode 100644 index 87eaae99c..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AbstractAssetForm.java +++ /dev/null @@ -1,433 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.Asset; - -import org.libreccm.core.UnexpectedErrorException; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.TooManyListenersException; - -/** - * Basic Form for manipulating assets. - * - * @author Jens Pelzetter - * @param The type of the asset. - */ -public abstract class AbstractAssetForm - extends Form implements FormInitListener, - FormProcessListener, - FormSubmissionListener { - - private static final String ASSET_TITLE = "asset-name"; - - private static final String ASSET_NAME = "asset-title"; - - private final AssetPane assetPane; - - private final SingleSelectionModel selectionModel; - - private BoxPanel showLocalePanel; - - private SingleSelect showLocaleSelect; - - private Submit showLocaleSubmit; - - private BoxPanel addLocalePanel; - - private SingleSelect addLocaleSelect; - - private Submit addLocaleSubmit; - - private TextField name; - - private TextField title; - - private SaveCancelSection saveCancelSection; - - public AbstractAssetForm(final AssetPane assetPane) { - super("asset-form", new ColumnPanel(1)); - - this.assetPane = assetPane; - selectionModel = assetPane.getSelectedAssetModel(); - - initComponents(); - } - - private void initComponents() { - - showLocalePanel = new BoxPanel(BoxPanel.HORIZONTAL); - final Label showLocaleLabel = new Label(new PrintListener() { - - @Override - public void prepare(final PrintEvent event) { - final PageState state = event.getPageState(); - final Long selectedAssetId = getSelectedAssetId(state); - final Label target = (Label) event.getTarget(); - if (selectedAssetId == null) { - target.setLabel(new GlobalizedMessage( - "cms.ui.asset.initial_locale", - CmsConstants.CMS_BUNDLE)); - } else { - target.setLabel(new GlobalizedMessage( - "cms.ui.asset.show_locale", - CmsConstants.CMS_BUNDLE)); - } - } - - }); - showLocaleSelect = new SingleSelect("selected-locale"); - try { - showLocaleSelect.addPrintListener(new PrintListener() { - - @Override - public void prepare(final PrintEvent event) { - final PageState state = event.getPageState(); - - final Long selectedAssetId = getSelectedAssetId(state); - if (selectedAssetId == null) { - final SingleSelect target = (SingleSelect) event - .getTarget(); - - target.clearOptions(); - - final List langs = new ArrayList<>( - KernelConfig.getConfig().getSupportedLanguages()); - langs.sort((lang1, lang2) -> lang1.compareTo(lang2)); - - langs.forEach(lang -> { - target.addOption(new Option(lang, new Text(lang))); - }); - } else { - final SingleSelect target = (SingleSelect) event - .getTarget(); - - target.clearOptions(); - - final List availableLocales = getController() - .availableLocales(selectedAssetId, - getAssetClass()); - availableLocales.sort((locale1, locale2) -> { - return locale1.toString().compareTo(locale2 - .toString()); - }); - availableLocales.forEach(locale -> target.addOption( - new Option(locale.toString(), - new Text(locale.toString())))); - } - } - - }); - } catch (TooManyListenersException ex) { - throw new UnexpectedErrorException(ex); - } - showLocaleSubmit = new Submit(new GlobalizedMessage( - "cms.ui.asset.show_locale", - CmsConstants.CMS_BUNDLE)) { - - @Override - public boolean isVisible(final PageState state) { - return getSelectedAssetId(state) != null; - } - - }; - showLocalePanel.add(showLocaleLabel); - showLocalePanel.add(showLocaleSelect); - showLocalePanel.add(showLocaleSubmit); - add(showLocalePanel); - - addLocalePanel = new BoxPanel(BoxPanel.HORIZONTAL) { - - @Override - public boolean isVisible(final PageState state) { - return getSelectedAssetId(state) != null; - } - - }; - final Label addLocaleLabel = new Label( - new GlobalizedMessage("cms.ui.asset.add_locale", - CmsConstants.CMS_BUNDLE)); - addLocaleSelect = new SingleSelect("add-locale-select"); - try { - addLocaleSelect.addPrintListener(new PrintListener() { - - @Override - public void prepare(final PrintEvent event) { - final PageState state = event.getPageState(); - - final Long selectedAssetId = getSelectedAssetId(state); - if (selectedAssetId != null) { - final SingleSelect target = (SingleSelect) event - .getTarget(); - - target.clearOptions(); - - final List creatableLocales = getController() - .creatableLocales(selectedAssetId, - getAssetClass()); - creatableLocales.sort((locale1, locale2) -> { - return locale1 - .toString() - .compareTo(locale2.toString()); - }); - creatableLocales.forEach(locale -> target.addOption( - new Option(locale.toString(), - new Text(locale.toString())))); - } - } - - }); - } catch (TooManyListenersException ex) { - throw new UnexpectedErrorException(ex); - } - addLocaleSubmit = new Submit(new GlobalizedMessage( - "cms.ui.asset.add_locale", - CmsConstants.CMS_BUNDLE)); - addLocalePanel.add(addLocaleLabel); - addLocalePanel.add(addLocaleSelect); - addLocalePanel.add(addLocaleSubmit); - add(addLocalePanel); - - add(new Label(new GlobalizedMessage("cms.ui.asset.name", - CmsConstants.CMS_BUNDLE))); - name = new TextField(ASSET_NAME); - add(name); - - add(new Label(new GlobalizedMessage("cms.ui.asset.title", - CmsConstants.CMS_BUNDLE))); - title = new TextField(ASSET_TITLE); - add(title); - - addWidgets(); - - saveCancelSection = new SaveCancelSection(); - add(saveCancelSection); - - addInitListener(this); - addProcessListener(this); - addSubmissionListener(this); - } - - protected void addWidgets() { - //Nothing here - } - - protected String getTitle(final PageState state) { - return (String) title.getValue(state); - } - - protected Long getSelectedAssetId(final PageState state) { - - final Object key = selectionModel.getSelectedKey(state); - if (key == null) { - return null; - } else { - return (Long) key; - } - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - - final PageState state = event.getPageState(); - - final Long selectedAssetId = getSelectedAssetId(state); - - final Map data; - if (selectedAssetId == null) { - showLocaleSelect.setValue(state, - KernelConfig - .getConfig() - .getDefaultLocale() - .toString()); - - data = Collections.emptyMap(); - - } else { - - showLocaleSelect.setValue(state, - getSelectedLocale(state)); - - data = getController().getAssetData(selectedAssetId, - getAssetClass(), - getSelectedLocale(state)); - - name.setValue(state, - data.get(AbstractAssetFormController.DISPLAY_NAME)); - title.setValue(state, - data.get(AbstractAssetFormController.TITLE)); - } - - initForm(state, data); - } - - protected Locale getSelectedLocale(final PageState state) { - - final Object selected = showLocaleSelect.getValue(state); - if (selected == null) { - return KernelConfig.getConfig().getDefaultLocale(); - } else if (selected instanceof Locale) { - return (Locale) selected; - } else if (selected instanceof String) { - return new Locale((String) selected); - } else { - return new Locale(selected.toString()); - } - } - - protected String getTitleValue(final PageState state) { - return (String) title.getValue(state); - } - - protected void initForm(final PageState state, - final Map data) { - - if (!data.isEmpty()) { - - name.setValue(state, - data.get(AbstractAssetFormController.DISPLAY_NAME)); - -// final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); -// @SuppressWarnings("unchecked") -// final AbstractAssetFormController controller = cdiUtil -// .findBean(AbstractAssetFormController.class); - title.setValue(state, - data.get(AbstractAssetFormController.TITLE)); - showLocale(state); - } - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - -// final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - if (showLocaleSubmit.isSelected(state)) { - - final Long selectedAssetId = getSelectedAssetId(state); - - initForm(state, - getController().getAssetData(selectedAssetId, - getAssetClass(), - getSelectedLocale(state))); - - return; - } - - if (addLocaleSubmit.isSelected(state)) { - final Locale add = new Locale((String) addLocaleSelect - .getValue(state)); - final Long selectedAssetId = getSelectedAssetId(state); - getController().addLocale(selectedAssetId, add, getAssetClass()); - } - - if (saveCancelSection.getSaveButton().isSelected(state)) { - - final Map data = new HashMap<>(); - data.put(AbstractAssetFormController.DISPLAY_NAME, - name.getValue(state)); - data.put(AbstractAssetFormController.TITLE, - title.getValue(state)); - data.putAll(collectData(event)); - - final Long selectedAssetId; - if (getSelectedAssetId(state) == null) { - - selectedAssetId = getController() - .createAsset(assetPane - .getFolderSelectionModel() - .getSelectedObject(state), - getSelectedLocale(state), - getAssetClass(), - data); - } else { - selectedAssetId = getSelectedAssetId(state); - } - - getController().updateAsset(selectedAssetId, - getSelectedLocale(state), - getAssetClass(), - data); - - assetPane.browseMode(state); - } - } - - protected abstract Class getAssetClass(); - - protected abstract void showLocale(final PageState state); - - protected abstract Map collectData( - final FormSectionEvent event) - throws FormProcessException; - - @Override - public void submitted(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (saveCancelSection.getCancelButton().isSelected(state)) { - selectionModel.clearSelection(state); - assetPane.browseMode(state); - } - } - - protected AssetFormController getController() { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AssetFormControllers controllers = cdiUtil - .findBean(AssetFormControllers.class); - - return controllers.findController(getAssetClass()); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AbstractAssetFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AbstractAssetFormController.java deleted file mode 100644 index 0fa230288..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AbstractAssetFormController.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets; - -import org.librecms.assets.AssetL10NManager; -import org.librecms.contentsection.Asset; -import org.librecms.contentsection.AssetManager; -import org.librecms.contentsection.AssetRepository; -import org.librecms.contentsection.Folder; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; - -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * An base class for implementations of {@link AssetFormController}. - * - * @author Jens Pelzetter - * @param - */ -public abstract class AbstractAssetFormController implements - AssetFormController { - - protected static final String DISPLAY_NAME = "displayName"; - protected static final String TITLE = "title"; - - @Inject - private AssetManager assetManager; - - @Inject - private AssetRepository assetRepository; - - @Inject - private AssetL10NManager l10nManager; - - /** - * Retrieves the basic data of the provided asset. Subclasses should not - * overrride this method. Instead they should provided an implementation of - * {@link #getAssetData(org.librecms.contentsection.Asset, java.util.Locale)}. - * - * @param assetType The {@link Asset} from which the data is read. - * @param selectedLocale The locale for which the data is read. - * - * @return A map with the data of the basic properties of the provided - * asset. - */ - @Transactional(Transactional.TxType.REQUIRED) - @Override - public Map getAssetData(final Long assetId, - final Class assetType, - final Locale selectedLocale) { - - Objects.requireNonNull(assetId, "Can't get data from asset null."); - Objects.requireNonNull(selectedLocale, - "Can't get data from asset for locale null."); - - final T asset = loadAsset(assetId, assetType); - - final Map data = new HashMap<>(); - - data.put(DISPLAY_NAME, asset.getDisplayName()); - data.put(TITLE, asset.getTitle().getValue(selectedLocale)); - - data.putAll(getAssetData(asset, selectedLocale)); - - return data; - } - - protected abstract Map getAssetData( - final T asset, final Locale selectedLocale); - - @Transactional(Transactional.TxType.REQUIRED) - @Override - public long createAsset(final Folder infolder, - final Locale selectedLocale, - final Class assetType, - final Map data) { - - if (!data.containsKey(DISPLAY_NAME)) { - throw new IllegalArgumentException( - "data does not contain a value for displayName."); - } - - if (!data.containsKey(TITLE)) { - throw new IllegalArgumentException( - "data does not contain a value for title."); - } - - final String name = (String) data.get(DISPLAY_NAME); - final String title = (String) data.get(TITLE); - - final T asset = assetManager - .createAsset(name, - title, - selectedLocale, - infolder, - assetType); - - return asset.getObjectId(); - } - - /** - * Updates the provided asset with the provided data. - * - * This method is not intended to be overridden, but can't be {@code final} - * because of limitations of CDI. To update type specific properties - * implement - * {@link #updateAssetProperties(org.librecms.contentsection.Asset, java.util.Locale, java.util.Map)}. - * - * This method calls - * {@link AssetRepository#save(org.librecms.contentsection.Asset)} after the - * properties are set to save the changes to the database. - * - * @param assetId The ID of the asset to update. - * @param selectedLocale The locale for which the asset is updated. - * @param data The data used to update the asset. - */ - @Transactional(Transactional.TxType.REQUIRED) - @Override - public void updateAsset(final Long assetId, - final Locale selectedLocale, - final Class assetType, - final Map data) { - - Objects.requireNonNull(selectedLocale, - "Can't get update asset for locale null."); - Objects.requireNonNull(data, "Can't update asset without data."); - - final T asset = loadAsset(assetId, assetType); - if (data.containsKey(DISPLAY_NAME)) { - asset.setDisplayName((String) data.get(DISPLAY_NAME)); - } - - if (data.containsKey(TITLE)) { - - final String title = (String) data.get(TITLE); - asset.getTitle().putValue(selectedLocale, title); - } - - updateAssetProperties(asset, selectedLocale, data); - - assetRepository.save(asset); - } - - /** - * Override this method to process data for type specific properties. - * - * This method is called by - * {@link #updateAsset(org.librecms.contentsection.Asset, java.util.Locale, java.util.Map)}. - * Implementations should not call - * {@link AssetRepository#save}. Saving the update asset is done by - * {@link #updateAsset(org.librecms.contentsection.Asset, java.util.Locale, java.util.Map)}. - * - * An implementation should not assume that a value for each property is - * present in the provided map. Instead the overriding method should check - * if a value for a property is available by using - * {@link Map#containsKey(java.lang.Object)} first. - * - * @param asset The asset to update. - * @param selectedLocale The locale for which the asset is updated. - * @param data The data used to update the asset. - */ - public abstract void updateAssetProperties(final T asset, - final Locale selectedLocale, - final Map data); - - /** - * Determines for which locales the provided asset has data. - * - * @param assetId The asset. - * - * @return A list of all locales for which the asset has data. - */ - @Transactional(Transactional.TxType.REQUIRED) - @Override - public List availableLocales(final Long assetId, - final Class assetType) { - - Objects.requireNonNull( - assetId, - "Can't get available locales for asset with ID null."); - - final T selectedAsset = loadAsset(assetId, assetType); - - return new ArrayList<>(l10nManager.availableLocales(selectedAsset)); - } - - /** - * Determines for locales the asset has no data yet. - * - * @param assetId The asset. - * - * @return A list of all locales for which the provided asset has no data - * yet. - */ - @Transactional(Transactional.TxType.REQUIRED) - @Override - public List creatableLocales(final Long assetId, - final Class assetType) { - - Objects.requireNonNull( - assetId, - "Can't get creatable locales for asset with ID null."); - - final T selectedAsset = loadAsset(assetId, assetType); - - return new ArrayList<>(l10nManager.creatableLocales(selectedAsset)); - } - - @Transactional(Transactional.TxType.REQUIRED) - @Override - public void addLocale(final Long assetId, - final Locale locale, - final Class assetType) { - - Objects.requireNonNull(assetId, "Can't add a locale to asset null."); - Objects.requireNonNull(locale, "Can't add locale null to an asset."); - - final T selectedAsset = loadAsset(assetId, assetType); - - l10nManager.addLanguage(selectedAsset, locale); - } - - /** - * - * @param assetId - * @param assetType - * - * @return - */ - protected T loadAsset(final Long assetId, final Class assetType) { - - Objects.requireNonNull(assetId, "null is not a valid assetId"); - - return assetRepository - .findById(assetId, assetType) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No asset with ID %d found.", assetId))); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowser.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowser.java deleted file mode 100644 index b5a70488b..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowser.java +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.Image; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Paginator; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.TableActionAdapter; -import com.arsdigita.bebop.event.TableActionEvent; -import com.arsdigita.bebop.event.TableActionListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.DefaultTableCellRenderer; -import com.arsdigita.bebop.table.DefaultTableColumnModel; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableHeader; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.ui.folder.FolderSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import java.util.Date; - -import org.libreccm.cdi.utils.CdiUtil; - -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionManager; - -import static org.librecms.CmsConstants.*; - -/** - * Browse folder and assets. - * - * @author Jens Pelzetter - */ -public class AssetFolderBrowser extends Table { - - protected static final String SORT_ACTION_UP = "sortActionUp"; - protected static final String SORT_ACTION_DOWN = "sortActionDown"; - protected final static String SORT_KEY_NAME = "name"; - protected final static String SORT_KEY_TITLE = "title"; - protected final static String SORT_KEY_TYPE = "type"; - protected final static String SORT_KEY_LAST_MODIFIED_DATE = "lastModified"; - protected final static String SORT_KEY_CREATION_DATE = "creationDate"; - - private final AssetPane assetPane; - private TableActionListener folderChanger; - private TableActionListener folderDeleter; - private TableColumn nameColumn; - private TableColumn deleteColumn; - private final StringParameter sortTypeParameter = new StringParameter( - "sortType"); - private final StringParameter sortDirectionParameter = new StringParameter( - "sortDir"); - - private Paginator paginator; - private long folderSize; - - public AssetFolderBrowser(final AssetPane assetPane) { - super(); - sortTypeParameter.setDefaultValue(SORT_KEY_NAME); - sortDirectionParameter.setDefaultValue(SORT_ACTION_UP); - - this.assetPane = assetPane; - - initComponents(); - } - - private void initComponents() { - - final GlobalizedMessage[] headers = { - new GlobalizedMessage("cms.ui.folder.name", - CMS_FOLDER_BUNDLE), - new GlobalizedMessage("cms.ui.folder.title", - CMS_FOLDER_BUNDLE), - new GlobalizedMessage("cms.ui.folder.type", - CMS_FOLDER_BUNDLE), - new GlobalizedMessage("cms.ui.asset.thumbnail", - CMS_BUNDLE), - new GlobalizedMessage("cms.ui.folder.creation_date", - CMS_FOLDER_BUNDLE), - new GlobalizedMessage("cms.ui.folder.last_modified", - CMS_FOLDER_BUNDLE), - new GlobalizedMessage("cms.ui.folder.action", - CMS_FOLDER_BUNDLE)}; - - setModelBuilder(new AssetFolderBrowserTableModelBuilder()); - setColumnModel(new DefaultTableColumnModel(headers)); - setHeader(new TableHeader(getColumnModel())); - setClassAttr("dataTable"); - - getHeader().setDefaultRenderer( - new com.arsdigita.cms.ui.util.DefaultTableCellRenderer()); - - nameColumn = getColumn(AssetFolderBrowserTableModel.COL_NAME); - nameColumn.setCellRenderer(new NameCellRenderer()); - nameColumn.setHeaderRenderer(new HeaderCellRenderer(SORT_KEY_NAME)); - - getColumn(AssetFolderBrowserTableModel.COL_THUMBNAIL) - .setCellRenderer(new ThumbnailCellRenderer()); - - getColumn(AssetFolderBrowserTableModel.COL_CREATION_DATE) - .setHeaderRenderer( - new HeaderCellRenderer(SORT_KEY_CREATION_DATE)); - getColumn(AssetFolderBrowserTableModel.COL_CREATION_DATE) - .setCellRenderer(new DateCellRenderer()); - - getColumn(AssetFolderBrowserTableModel.COL_LAST_MODIFIED) - .setHeaderRenderer(new HeaderCellRenderer( - SORT_KEY_LAST_MODIFIED_DATE)); - getColumn(AssetFolderBrowserTableModel.COL_LAST_MODIFIED) - .setCellRenderer(new DateCellRenderer()); - - deleteColumn = getColumn(AssetFolderBrowserTableModel.COL_DELETEABLE); - deleteColumn.setCellRenderer(new ActionCellRenderer()); - deleteColumn.setAlign("center"); - - folderChanger = new FolderChanger(); - addTableActionListener(folderChanger); - - folderDeleter = new ItemDeleter(); - addTableActionListener(folderDeleter); - - setEmptyView(new Label(new GlobalizedMessage("cms.ui.folder.no_assets", - CMS_FOLDER_BUNDLE))); - } - - @Override - public void register(final Page page) { - - super.register(page); - - page.addComponentStateParam( - this, - getFolderSelectionModel().getStateParameter()); - page.addComponentStateParam(this, sortTypeParameter); - page.addComponentStateParam(this, sortDirectionParameter); - } - - protected FolderSelectionModel getFolderSelectionModel() { - return assetPane.getFolderSelectionModel(); - } - - protected SingleSelectionModel getSelectedAssetModel() { - return assetPane.getSelectedAssetModel(); - } - - protected Paginator getPaginator() { - return paginator; - } - - protected void setPaginator(final Paginator paginator) { - this.paginator = paginator; - } - - protected String getSortType(final PageState state) { - return (String) state.getValue(sortTypeParameter); - } - - protected String getSortDirection(final PageState state) { - return (String) state.getValue(sortDirectionParameter); - } - - private class HeaderCellRenderer extends DefaultTableCellRenderer { - - private final String headerKey; - - public HeaderCellRenderer(final String headerKey) { - super(true); - this.headerKey = headerKey; - } - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - final GlobalizedMessage headerName = (GlobalizedMessage) value; - final String sortKey = (String) state.getValue(sortTypeParameter); - final boolean isCurrentKey = sortKey.equals(key); - final String currentSortDirection = (String) state - .getValue(sortDirectionParameter); - final String imageUrlStub; - - if (SORT_ACTION_UP.equals(currentSortDirection)) { - imageUrlStub = "gray-triangle-up.gif"; - } else { - imageUrlStub = "gray-triangle-down.gif"; - } - - final ControlLink link = new ControlLink(new Label(headerName)) { - - @Override - public void setControlEvent(final PageState state) { - String sortDirectionAction; - // by default, everything sorts "up" unless it - // is the current key and it is already pointing up - if (SORT_ACTION_UP.equals(currentSortDirection) - && isCurrentKey) { - sortDirectionAction = SORT_ACTION_DOWN; - } else { - sortDirectionAction = SORT_ACTION_UP; - } - state.setControlEvent(table, - sortDirectionAction, - headerKey); - } - - }; - final Label label = new Label(); - label.setLabel(headerName); - label.setClassAttr("folderBrowserLink"); - label.setOutputEscaping(false); - label.setFontWeight(Label.BOLD); - - final SimpleContainer container = new SimpleContainer(); - container.add(label); - if (isCurrentKey) { - Image image = new Image("/assets/" + imageUrlStub); - image.setBorder("0"); - container.add(image); - } - link.setChild(container); - return link; - } - - } - - /** - * Produce links to view an item or control links for folders to change into - * the folder. - */ - private class NameCellRenderer extends DefaultTableCellRenderer { - - public NameCellRenderer() { - super(true); - } - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - final String name = (String) value; - final ContentSection section = CMS.getContext(). - getContentSection(); - final ContentSectionManager sectionManager = CdiUtil. - createCdiUtil() - .findBean(ContentSectionManager.class); - - final boolean isFolder = ((AssetFolderBrowserTableModel) table - .getTableModel(state)) - .isFolder(); - final long objectId = getObjectId(key); - - if (isFolder) { - //return new ControlLink(new Text(name)); - return super.getComponent(table, - state, - value, - isSelected, - objectId, - row, - column); - } else { - return new ControlLink(new Text(name)); - -// return new Link(new Text(name), -// itemResolver.generateItemURL(state, -// objectId, -// name, -// section, -// "DRAFT")); - } - } - - } - - private class ThumbnailCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - if (value == null) { - return new Text(""); - } else { - final Image image = new Image((String) value, ""); - return image; - } - } - - } - - private class DateCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - if (value instanceof Date) { - final Date date = (Date) value; - return new Text(String.format("%1$TF %1$TT", date)); - } else if (value == null) { - return new Text(""); - } else { - return new Text(value.toString()); - } - } - - } - - /** - * Produce delete links for items and non-empty folders. - */ - private class ActionCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - if ((!(Boolean) value)) { - return new Label(" ", false); - } else { - final ControlLink link = new ControlLink( - new Label( - new GlobalizedMessage("cms.ui.folder.delete", - CmsConstants.CMS_FOLDER_BUNDLE))); - link.setConfirmation( - new GlobalizedMessage( - "cms.ui.folder.delete_confirmation_assets", - CmsConstants.CMS_FOLDER_BUNDLE)); - return link; - } - } - - } - - // Deletes an item - private class ItemDeleter extends TableActionAdapter { - - @Override - public void cellSelected(final TableActionEvent event) { - int col = event.getColumn(); - - if (deleteColumn != getColumn(col)) { - return; - } - - final PageState state = event.getPageState(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AssetFolderBrowserController controller = cdiUtil.findBean( - AssetFolderBrowserController.class); - controller.deleteObject((String) event.getRowKey()); - - ((Table) event.getSource()).clearSelection(state); - } - - } - - private class FolderChanger extends TableActionAdapter { - - @Override - public void cellSelected(final TableActionEvent event) { - final PageState state = event.getPageState(); - final int col = event.getColumn(); - - if (nameColumn != getColumn(col)) { - return; - } - - clearSelection(state); - final String rowKey = (String) event.getRowKey(); - if (rowKey.startsWith(CmsConstants.FOLDER_BROWSER_KEY_PREFIX_FOLDER)) { - getFolderSelectionModel().setSelectedKey(state, - getObjectId(rowKey)); - } else if (rowKey.startsWith( - CmsConstants.FOLDER_BROWSER_KEY_PREFIX_ASSET)) { - getSelectedAssetModel().setSelectedKey(state, - getObjectId(rowKey)); - assetPane.editAssetMode(state); - } - } - - } - - private long getObjectId(final Object key) { - - final String keyStr = (String) key; - - if (keyStr.startsWith("folder-")) { - return Long.parseLong(keyStr.substring("folder-".length())); - } else if (keyStr.startsWith("asset-")) { - return Long.parseLong(keyStr.substring("asset-".length())); - } else { - return Long.parseLong(keyStr); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserController.java deleted file mode 100644 index b3ed0b26b..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserController.java +++ /dev/null @@ -1,638 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets; - -import com.arsdigita.cms.CMS; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.web.CCMDispatcherServlet; - -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.CmsConstants; -import org.librecms.assets.AssetTypeInfo; -import org.librecms.assets.AssetTypesManager; -import org.librecms.contentsection.Asset; - -import org.librecms.contentsection.Folder; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.stream.Collectors; - -import javax.annotation.PostConstruct; -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.persistence.EntityManager; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Join; -import javax.persistence.criteria.Order; -import javax.persistence.criteria.Path; -import javax.persistence.criteria.Root; -import javax.transaction.Transactional; - -import org.libreccm.core.CcmObject; -import org.librecms.contentsection.AssetManager; -import org.librecms.contentsection.AssetRepository; -import org.librecms.contentsection.FolderManager; -import org.librecms.contentsection.FolderRepository; - -import java.util.Collections; -import java.util.Optional; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.librecms.assets.Image; - -import static org.librecms.CmsConstants.*; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -public class AssetFolderBrowserController { - - private static final Logger LOGGER = LogManager - .getLogger(AssetFolderBrowserController.class); - - @Inject - private EntityManager entityManager; - - @Inject - private ConfigurationManager confManager; - - @Inject - private CategoryManager categoryManager; - - @Inject - private AssetTypesManager typesManager; - - @Inject - private FolderRepository folderRepo; - - @Inject - private FolderManager folderManager; - - @Inject - private AssetRepository assetRepo; - - @Inject - private AssetManager assetManager; - - @Inject - private GlobalizationHelper globalizationHelper; - - private Locale defaultLocale; - - /** - * Initialisation method called by the CDI-Container after an instance of - * this class has be created by the container. Sets the - * {@link #defaultLocale} property using the the value from the - * {@link KernelConfig}. - */ - @PostConstruct - private void init() { - final KernelConfig kernelConfig = confManager.findConfiguration( - KernelConfig.class); - defaultLocale = kernelConfig.getDefaultLocale(); - } - - @Transactional(Transactional.TxType.REQUIRED) - List getAssetRows(final Folder folder, - final String orderBy, - final String orderDirection, - final int firstResult, - final int maxResults) { - final List subFolders = findSubFolders(folder, - "%", - orderBy, - orderDirection, - firstResult, - maxResults); - final List subFolderRows = subFolders - .stream() - .map(subFolder -> buildRow(subFolder)) - .collect(Collectors.toList()); - - if (subFolders.size() > maxResults) { - return subFolderRows; - } else { - final int maxAssets = maxResults - subFolders.size(); - final int firstAsset = firstResult - subFolders.size(); - - final List assets = findAssetsInFolder(folder, - "%", - orderBy, - orderDirection, - firstAsset, - maxAssets); - final List assetRows = assets - .stream() - .map(asset -> buildRow(asset)) - .collect(Collectors.toList()); - - final List rows = new ArrayList<>(); - rows.addAll(subFolderRows); - rows.addAll(assetRows); - - return rows; - } - } - - @Transactional(Transactional.TxType.REQUIRED) - protected long countObjects(final Folder folder) { - - return countObjects(folder, "%"); - - } - - @Transactional(Transactional.TxType.REQUIRED) - protected long countObjects(final Folder folder, final String filterTerm) { - - Objects.requireNonNull(folder); - Objects.requireNonNull(filterTerm); - - final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = builder.createQuery(Long.class); - final Root from = criteriaQuery.from(CcmObject.class); - - criteriaQuery = criteriaQuery.select(builder.count(from)); - - final List subFolders = findSubFolders( - folder, - filterTerm, - AssetFolderBrowser.SORT_KEY_NAME, - AssetFolderBrowser.SORT_ACTION_UP, - -1, - -1); - final List assets = findAssetsInFolder( - folder, - filterTerm, - AssetFolderBrowser.SORT_KEY_NAME, - AssetFolderBrowser.SORT_ACTION_UP, - -1, - -1); - - if (subFolders.isEmpty() && assets.isEmpty()) { - return 0; - } else if (subFolders.isEmpty() && !assets.isEmpty()) { - criteriaQuery = criteriaQuery.where(from.in(assets)); - } else if (!subFolders.isEmpty() && assets.isEmpty()) { - criteriaQuery = criteriaQuery.where(from.in(subFolders)); - } else { - criteriaQuery = criteriaQuery.where(builder.or( - from.in(subFolders), - from.in(assets))); - } - - return entityManager.createQuery(criteriaQuery).getSingleResult(); - - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void copyObjects(final Folder targetFolder, - final String[] objectIds) { - - Objects.requireNonNull(targetFolder); - Objects.requireNonNull(objectIds); - - for (final String objectId : objectIds) { - if (objectId.startsWith(FOLDER_BROWSER_KEY_PREFIX_FOLDER)) { - copyFolder(targetFolder, - Long.parseLong(objectId.substring( - FOLDER_BROWSER_KEY_PREFIX_FOLDER.length()))); - } else if (objectId.startsWith(FOLDER_BROWSER_KEY_PREFIX_ASSET)) { - copyAsset(targetFolder, - Long.parseLong(objectId.substring( - FOLDER_BROWSER_KEY_PREFIX_ASSET.length()))); - } else { - throw new IllegalArgumentException(String.format( - "ID '%s' does not start with '%s' or '%s'.", - objectId, - FOLDER_BROWSER_KEY_PREFIX_FOLDER, - FOLDER_BROWSER_KEY_PREFIX_ASSET)); - } - } - - } - - private void copyFolder(final Folder targetFolder, - final long folderId) { - - Objects.requireNonNull(targetFolder); - - final Folder folder = folderRepo.findById(folderId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No folder with ID %d in the database. " - + "Where did that ID come from?", - folderId))); - - folderManager.copyFolder(folder, targetFolder); - - } - - private void copyAsset(final Folder targetFolder, - final long assetId) { - - Objects.requireNonNull(targetFolder); - - final Asset asset = assetRepo - .findById(assetId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No asset ith ID %d in the database. Where did that ID come from?", - assetId))); - - assetManager.copy(asset, targetFolder); - } - - @Transactional(Transactional.TxType.REQUIRED) - public void moveObjects(final Folder targetFolder, - final String[] objectIds) { - - Objects.requireNonNull(targetFolder); - Objects.requireNonNull(objectIds); - - for (final String objectId : objectIds) { - if (objectId.startsWith(FOLDER_BROWSER_KEY_PREFIX_FOLDER)) { - moveFolder(targetFolder, - Long.parseLong(objectId.substring( - FOLDER_BROWSER_KEY_PREFIX_FOLDER.length()))); - } else if (objectId.startsWith(FOLDER_BROWSER_KEY_PREFIX_ASSET)) { - moveAsset(targetFolder, - Long.parseLong(objectId.substring( - FOLDER_BROWSER_KEY_PREFIX_ASSET.length()))); - } else { - throw new IllegalArgumentException(String.format( - "ID '%s' does not start with '%s' or '%s'.", - objectId, - FOLDER_BROWSER_KEY_PREFIX_FOLDER, - FOLDER_BROWSER_KEY_PREFIX_ASSET)); - } - } - } - - private void moveFolder(final Folder targetFolder, final long folderId) { - - Objects.requireNonNull(targetFolder); - - final Folder folder = folderRepo.findById(folderId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No folder with ID %d in the database. " - + "Where did that ID come from?", - folderId))); - - folderManager.moveFolder(folder, targetFolder); - } - - private void moveAsset(final Folder targetFolder, final long assetId) { - - Objects.requireNonNull(targetFolder); - - final Asset asset = assetRepo - .findById(assetId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No asset with ID %d in the database. Where did that ID come from?", - assetId))); - - assetManager.move(asset, targetFolder); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected List createInvalidTargetsList(final List sources) { - - Objects.requireNonNull(sources); - - final List sourceFolderIds = sources - .stream() - .filter(source -> source.startsWith( - FOLDER_BROWSER_KEY_PREFIX_FOLDER)) - .collect(Collectors.toList()); - final List parentFolderIds = sourceFolderIds - .stream() - .map(sourceFolderId -> findParentFolderId(sourceFolderId)) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toList()); - final List> subFolderIds = sourceFolderIds - .stream() - .map(sourceFolderId -> findSubFolderIds(sourceFolderId)) - .collect(Collectors.toList()); - - final List invalidTargetIds = new ArrayList<>(); - invalidTargetIds.addAll(sourceFolderIds); - invalidTargetIds.addAll(parentFolderIds); - for (final List subFolderIdList : subFolderIds) { - invalidTargetIds.addAll(subFolderIdList); - } - - return invalidTargetIds; - - } - - private Optional findParentFolderId(final String folderId) { - - Objects.requireNonNull(folderId); - - if (!folderId.startsWith(FOLDER_BROWSER_KEY_PREFIX_FOLDER)) { - throw new IllegalArgumentException(String.format( - "Provided string '%s' is not an ID of a folder.", - folderId)); - } - - final long objectId = Long.parseLong(folderId.substring( - FOLDER_BROWSER_KEY_PREFIX_FOLDER.length())); - final Folder folder = folderRepo.findById(objectId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No folder with ID %d found in database. " - + "Where did that ID come form?", - objectId))); - final Optional parentFolder = folderManager.getParentFolder( - folder); - if (parentFolder.isPresent()) { - return Optional.empty(); - } else { - return Optional.ofNullable(String.format( - "%s%d", - FOLDER_BROWSER_KEY_PREFIX_FOLDER, - parentFolder.get().getObjectId())); - } - } - - private List findSubFolderIds(final String folderId) { - - Objects.requireNonNull(folderId); - - if (!folderId.startsWith(FOLDER_BROWSER_KEY_PREFIX_FOLDER)) { - throw new IllegalArgumentException(String.format( - "Provided string '%s' is not the ID of a folder.", - folderId)); - } - - final long objectId = Long.parseLong(folderId.substring( - FOLDER_BROWSER_KEY_PREFIX_FOLDER.length())); - final Folder folder = folderRepo.findById(objectId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No folder with ID %d found in database. " - + "Where did that ID come form?", - objectId))); - return findSubFolders(folder) - .stream() - .map(subFolder -> String.format("%s%d", - FOLDER_BROWSER_KEY_PREFIX_FOLDER, - subFolder.getObjectId())) - .collect(Collectors.toList()); - } - - private List findSubFolders(final Folder folder) { - - Objects.requireNonNull(folder); - - if (folder.getSubFolders() == null - || folder.getSubFolders().isEmpty()) { - return Collections.emptyList(); - } - - final List subFolders = new ArrayList<>(); - for (final Folder subFolder : folder.getSubFolders()) { - subFolders.add(subFolder); - subFolders.addAll(findSubFolders(subFolder)); - } - - return subFolders; - } - - /** - * Called by the {@link AssetFolderBrowser} to delete an object. - * - * @param objectId - */ - @Transactional(Transactional.TxType.REQUIRED) - protected void deleteObject(final String objectId) { - - Objects.requireNonNull(objectId); - - if (objectId.startsWith("folder-")) { - final long folderId = Long.parseLong( - objectId.substring("folder-".length())); - - folderRepo - .findById(folderId) - .ifPresent(folderRepo::delete); - } else if (objectId.startsWith("asset-")) { - final long assetId = Long.parseLong( - objectId.substring("asset-".length())); - - assetRepo - .findById(assetId) - .ifPresent(assetRepo::delete); - } else { - throw new IllegalArgumentException( - "The objectId is expected to start with 'folder-' or 'asset-'."); - } - } - - private AssetFolderBrowserTableRow buildRow(final Folder folder) { - - final AssetFolderBrowserTableRow row = new AssetFolderBrowserTableRow(); - - row.setObjectId(folder.getObjectId()); - row.setObjectUuid(folder.getUuid()); - row.setName(folder.getName()); - if (folder.getTitle().hasValue(globalizationHelper - .getNegotiatedLocale())) { - row.setTitle(folder.getTitle().getValue(globalizationHelper - .getNegotiatedLocale())); - } else { - row.setTitle(folder.getTitle().getValue(defaultLocale)); - } - row.setFolder(true); - row.setDeletable(!categoryManager.hasSubCategories(folder) - && !categoryManager.hasObjects(folder)); - - return row; - } - - private AssetFolderBrowserTableRow buildRow(final Asset asset) { - - final AssetFolderBrowserTableRow row = new AssetFolderBrowserTableRow(); - - row.setObjectId(asset.getObjectId()); - row.setObjectUuid(asset.getUuid()); - row.setName(asset.getDisplayName()); - if (asset.getTitle().hasValue(globalizationHelper - .getNegotiatedLocale())) { - row.setTitle(asset.getTitle().getValue(globalizationHelper - .getNegotiatedLocale())); - } else { - row.setTitle(asset.getTitle().getValue(defaultLocale)); - } - if (asset instanceof Image) { - row.setThumbnailUrl(String - .format("%s/content-sections/%s/images/" - + "uuid-%s?width=150&height=100", - CCMDispatcherServlet.getContextPath(), - CMS.getContext().getContentSection().getLabel(), - asset.getUuid())); - } - final AssetTypeInfo typeInfo = typesManager - .getAssetTypeInfo(asset.getClass()); - row.setTypeLabelBundle(typeInfo.getLabelBundle()); - row.setTypeLabelKey(typeInfo.getLabelKey()); - - row.setFolder(false); - - row.setDeletable(!assetManager.isAssetInUse(asset)); - - return row; - } - - private List findSubFolders(final Folder folder, - final String filterTerm, - final String orderBy, - final String orderDirection, - final int firstResult, - final int maxResults) { - - final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - - final CriteriaQuery criteria = builder - .createQuery(Folder.class); - final Root from = criteria.from(Folder.class); - - final Order order; - if (AssetFolderBrowser.SORT_KEY_NAME.equals(orderBy) - && AssetFolderBrowser.SORT_ACTION_DOWN. - equals(orderDirection)) { - order = builder.desc(from.get("name")); - } else { - order = builder.asc(from.get("name")); - } - - final TypedQuery query = entityManager - .createQuery( - criteria.where( - builder.and( - builder. - equal(from.get("parentCategory"), - folder), - builder.like(builder.lower(from.get( - "name")), - filterTerm) - ) - ) - .orderBy(order) - ); - - if (firstResult >= 0) { - query.setFirstResult(firstResult); - } - - if (maxResults >= 0) { - query.setMaxResults(maxResults); - } - - return query.getResultList(); - } - - private List findAssetsInFolder(final Folder folder, - final String filterTerm, - final String orderBy, - final String orderDirection, - final int firstResult, - final int maxResults) { - - final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - - final CriteriaQuery criteria = builder.createQuery(Asset.class); - final Root fromAsset = criteria.from(Asset.class); - final Join join = fromAsset.join("categories"); - - final Path orderPath; - switch (orderBy) { - case AssetFolderBrowser.SORT_KEY_NAME: - orderPath = fromAsset.get("displayName"); - break; - case AssetFolderBrowser.SORT_KEY_CREATION_DATE: - orderPath = fromAsset.get("creationDate"); - break; - case AssetFolderBrowser.SORT_KEY_LAST_MODIFIED_DATE: - orderPath = fromAsset.get("lastModifed"); - break; - default: - orderPath = fromAsset.get("displayName"); - break; - } - - final Order order; - if (AssetFolderBrowser.SORT_ACTION_DOWN.equals(orderDirection)) { - order = builder.desc(orderPath); - } else { - order = builder.asc(orderPath); - } - - LOGGER.debug("The database contains {} assets.", - entityManager.createQuery(criteria.select(fromAsset) - .where( - builder.and( - builder.equal(join.get("category"), - folder), - builder.equal(join.get("type"), - CmsConstants.CATEGORIZATION_TYPE_FOLDER), - builder.like(builder.lower( - fromAsset.get( - "displayName")), - filterTerm) - ))).getResultList().size()); - - final TypedQuery query = entityManager - .createQuery( - criteria.select(fromAsset) - .where( - builder.and( - builder.equal(join.get( - "category"), folder), - builder.equal(join.get("type"), - CmsConstants.CATEGORIZATION_TYPE_FOLDER), - builder.like(builder.lower( - fromAsset.get( - "displayName")), - filterTerm) - ) - ) - .orderBy(order) - ); - - if (firstResult >= 0) { - query.setFirstResult(firstResult); - } - - if (maxResults >= 0) { - query.setMaxResults(maxResults); - } - - return query.getResultList(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserPaginationModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserPaginationModelBuilder.java deleted file mode 100644 index 85ea33141..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserPaginationModelBuilder.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.PaginationModelBuilder; -import com.arsdigita.bebop.Paginator; -import com.arsdigita.cms.ui.folder.FolderSelectionModel; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.Folder; - -/** - * - * @author Jens Pelzetter - */ -class AssetFolderBrowserPaginationModelBuilder implements PaginationModelBuilder { - - private final AssetFolderBrowser folderBrowser; - - public AssetFolderBrowserPaginationModelBuilder( - final AssetFolderBrowser folderBrowser) { - - this.folderBrowser = folderBrowser; - } - - @Override - public int getTotalSize(final Paginator paginator, final PageState state) { - - final FolderSelectionModel folderSelectionModel = folderBrowser - .getFolderSelectionModel(); - final Folder folder = folderSelectionModel.getSelectedObject(state); - if (folder == null) { - return 0; - } else { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AssetFolderBrowserController controller = cdiUtil.findBean( - AssetFolderBrowserController.class); - return (int) controller.countObjects(folder); - } - } - - @Override - public boolean isVisible(final PageState state) { - return folderBrowser != null && folderBrowser.isVisible(state); - } - - - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserTableModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserTableModel.java deleted file mode 100644 index 56b7a2d6a..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserTableModel.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets; - -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; - -import java.util.Iterator; -import java.util.List; - -/** - * - * @author Jens Pelzetter - */ -class AssetFolderBrowserTableModel implements TableModel { - - protected static final int COL_NAME = 0; - protected static final int COL_TITLE = 1; - protected static final int COL_TYPE = 2; - protected static final int COL_THUMBNAIL = 3; - protected static final int COL_CREATION_DATE = 4; - protected static final int COL_LAST_MODIFIED = 5; - protected static final int COL_DELETEABLE = 6; - - private final Iterator iterator; - private AssetFolderBrowserTableRow currentRow; - - public AssetFolderBrowserTableModel( - final List rows) { - - iterator = rows.iterator(); - } - - @Override - public int getColumnCount() { - return 6; - } - - @Override - public boolean nextRow() { - if (iterator.hasNext()) { - currentRow = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - switch (columnIndex) { - case COL_NAME: - return currentRow.getName(); - case COL_TITLE: - return currentRow.getTitle(); - case COL_TYPE: - final String typeLabelBundle = currentRow.getTypeLabelBundle(); - final String typeLabelKey = currentRow.getTypeLabelKey(); - if (typeLabelKey == null) { - return new GlobalizedMessage("empty_text", - CmsConstants.CMS_BUNDLE); - } else { - return new GlobalizedMessage(typeLabelKey, typeLabelBundle); - } - case COL_THUMBNAIL: - return currentRow.getThumbnailUrl(); - case COL_CREATION_DATE: - return currentRow.getCreated(); - case COL_LAST_MODIFIED: - return currentRow.getLastModified(); - case COL_DELETEABLE: - return currentRow.isDeletable(); - default: - throw new IllegalArgumentException(String.format( - "Illegal column index %d.", columnIndex)); - } - } - - @Override - public Object getKeyAt(final int columnIndex) { - if (currentRow.isFolder()) { - return String.format("folder-%d", currentRow.getObjectId()); - } else { - return String.format("asset-%d", currentRow.getObjectId()); - } - } - - public boolean isFolder() { - return currentRow.isFolder(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserTableModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserTableModelBuilder.java deleted file mode 100644 index afbf71efd..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserTableModelBuilder.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Paginator; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.ui.folder.FolderSelectionModel; -import com.arsdigita.util.LockableImpl; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.Folder; - -import java.util.List; - -/** - * Creates the {@link TableModel} for the {@link AssetFolderBrowser}. - * - * @author Jens Pelzetter - */ -class AssetFolderBrowserTableModelBuilder - extends LockableImpl - implements TableModelBuilder { - - private static final Logger LOGGER = LogManager - .getLogger(AssetFolderBrowserTableModelBuilder.class); - - @Override - public TableModel makeModel(final Table table, - final PageState state) { - - if (!(table instanceof AssetFolderBrowser)) { - throw new IllegalArgumentException( - "The AssetFolderBrowserTableModelBuilder can only be used " - + "for the AssetFolderBrowser."); - } - - final AssetFolderBrowser assetFolderBrowser = (AssetFolderBrowser) table; - final FolderSelectionModel folderSelectionModel = assetFolderBrowser - .getFolderSelectionModel(); - final Folder folder = folderSelectionModel.getSelectedObject(state); - if (folder == null) { - return Table.EMPTY_MODEL; - } else { - assetFolderBrowser.getRowSelectionModel().clearSelection(state); - final Paginator paginator = assetFolderBrowser.getPaginator(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AssetFolderBrowserController controller = cdiUtil - .findBean(AssetFolderBrowserController.class); - final String orderBy; - if (assetFolderBrowser.getSortType(state) == null) { - orderBy = AssetFolderBrowser.SORT_KEY_NAME; - } else { - orderBy = assetFolderBrowser.getSortType(state); - } - final String orderDirection; - if (assetFolderBrowser.getSortDirection(state) == null) { - orderDirection = AssetFolderBrowser.SORT_ACTION_UP; - } else { - orderDirection = assetFolderBrowser.getSortDirection(state); - } - final int first = paginator.getFirst(state); - final int pageSize = paginator.getPageSize(state); - - final long start = System.nanoTime(); - LOGGER.debug("Retrieving table rows..."); - final List rows = controller - .getAssetRows(folder, - orderBy, - orderDirection, - first - 1, - pageSize); - - LOGGER.debug("Retrieve table rows in {} ms.", - (System.nanoTime() - start) / 1000); - return new AssetFolderBrowserTableModel(rows); - - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserTableRow.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserTableRow.java deleted file mode 100644 index 045a35093..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFolderBrowserTableRow.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets; - -import java.util.Date; - -/** - * - * @author Jens Pelzetter - */ -class AssetFolderBrowserTableRow { - - private long objectId; - private String objectUuid; - private String name; - private String title; - private String thumbnailUrl; - private String typeLabelBundle; - private String typeLabelKey; - private Date created; - private Date lastModified; - private boolean deletable; - private boolean folder; - - public long getObjectId() { - return objectId; - } - - public void setObjectId(final long objectId) { - this.objectId = objectId; - } - - public String getObjectUuid() { - return objectUuid; - } - - public void setObjectUuid(final String objectUuid) { - this.objectUuid = objectUuid; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getTitle() { - return title; - } - - public void setTitle(final String title) { - this.title = title; - } - - public String getThumbnailUrl() { - return thumbnailUrl; - } - - public void setThumbnailUrl(final String thumbnailUrl) { - this.thumbnailUrl = thumbnailUrl; - } - - public String getTypeLabelBundle() { - return typeLabelBundle; - } - - public void setTypeLabelBundle(final String typeLabelBundle) { - this.typeLabelBundle = typeLabelBundle; - } - - public String getTypeLabelKey() { - return typeLabelKey; - } - - public void setTypeLabelKey(final String typeLabelKey) { - this.typeLabelKey = typeLabelKey; - } - - public Date getCreated() { - if (created == null) { - return null; - } else { - return new Date(created.getTime()); - } - } - - protected void setCreated(final Date created) { - if (created == null) { - this.created = null; - } else { - this.created = new Date(created.getTime()); - } - } - - public Date getLastModified() { - if (lastModified == null) { - return null; - } else { - return new Date(lastModified.getTime()); - } - } - - protected void setLastModified(final Date lastModified) { - if (lastModified == null) { - this.lastModified = null; - } else { - this.lastModified = new Date(lastModified.getTime()); - } - } - - public boolean isDeletable() { - return deletable; - } - - public void setDeletable(final boolean deletable) { - this.deletable = deletable; - } - - public boolean isFolder() { - return folder; - } - - public void setFolder(final boolean folder) { - this.folder = folder; - } - - - - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFormController.java deleted file mode 100644 index c188d613a..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFormController.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets; - -import org.librecms.contentsection.Asset; -import org.librecms.contentsection.Folder; - -import java.util.List; -import java.util.Locale; -import java.util.Map; - -/** - * - * Interface for the CDI backend for the forms to manage assets.To avoid - * problems with transactions etc. - * - * the Bebop based forms should access any other CDI beans beside the - * approbriate implementation of this interface. To minimize the efford to - * create an implementation the {@link AbstractAssetFormController} class should - * be used. This class provides basic implementations for most methods. - * - * Implementations of the methods defined by this interface should annotated - * with {@code @Transactional(Transactional.TxType.REQUIRED)}. - * - * @author Jens Pelzetter - * - * @param The type asset managed by this controller. - */ -public interface AssetFormController { - - /** - * Gets the data for the forms from the asset. - * - * @param assetId The ID of the asset. - * @param assetType - * @param selectedLocale The selected locale - * - * @return The values of the properties of the asset for the the selected - * locale. - */ - Map getAssetData(Long assetId, - Class assetType, - Locale selectedLocale); - - /** - * Updates the asset with the provided data and saves the changes. - * - * @param assetId - * @param selectedLocale - * @param assetType - * @param data - */ - void updateAsset(Long assetId, - Locale selectedLocale, - Class assetType, - Map data); - - long createAsset(Folder inFolder, - Locale selectedLocale, - Class assetType, - Map data); - - - - /** - * Determines in which locales the provided asset is available. - * - * - * @param assetId - * @param assetType - * - * @return A list of the locales for which the asset has data. - */ - List availableLocales(Long assetId, Class assetType); - - /** - * Determines for which the provided asset has no data. - * - * - * @param assetId - * @param assetType - * - * @return A list of the locales for which the asset has data yet. - */ - List creatableLocales(Long assetId, Class assetType); - - void addLocale(final Long assetId, - final Locale locale, - final Class assetType); - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFormControllers.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFormControllers.java deleted file mode 100644 index 8fa79557f..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetFormControllers.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets; - -import org.librecms.contentsection.Asset; - -import javax.enterprise.context.RequestScoped; -import javax.enterprise.inject.Any; -import javax.enterprise.inject.Instance; -import javax.enterprise.util.AnnotationLiteral; -import javax.inject.Inject; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -public class AssetFormControllers { - - @Inject - @Any - private Instance> controllers; - - @SuppressWarnings("unchecked") - public AssetFormController findController( - final Class assetType) { - - final IsControllerForAssetTypeLiteral literal - = new IsControllerForAssetTypeLiteral( - assetType); - - final Instance> instance = controllers - .select(literal); - - if (instance.isUnsatisfied()) { - throw new IllegalArgumentException(String.format( - "No controller for asset type \"%s\".", - assetType.getClass().getName())); - } else { - return (AssetFormController) instance.iterator().next(); - } - } - - private class IsControllerForAssetTypeLiteral - extends AnnotationLiteral - implements IsControllerForAssetType { - - private static final long serialVersionUID = 1L; - - private final Class assetType; - - public IsControllerForAssetTypeLiteral( - final Class assetType) { - - this.assetType = assetType; - } - - @Override - public Class value() { - - return assetType; - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetPane.java deleted file mode 100644 index 02c3d87d5..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetPane.java +++ /dev/null @@ -1,1229 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets; - -import com.arsdigita.bebop.ActionLink; -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.MetaForm; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Paginator; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.RequestLocal; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.SegmentedPanel; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.Tree; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.CheckboxGroup; -import com.arsdigita.bebop.form.FormErrorDisplay; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.parameters.ArrayParameter; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.tree.TreeCellRenderer; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.ui.BaseTree; -import com.arsdigita.cms.ui.folder.FolderCreateForm; -import com.arsdigita.cms.ui.folder.FolderEditorForm; -import com.arsdigita.cms.ui.folder.FolderRequestLocal; -import com.arsdigita.cms.ui.folder.FolderSelectionModel; -import com.arsdigita.cms.ui.folder.FolderTreeModelBuilder; -import com.arsdigita.cms.ui.folder.FolderTreeModelController; -import com.arsdigita.cms.ui.permissions.CMSPermissionsPane; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.ActionGroup; -import com.arsdigita.toolbox.ui.LayoutPanel; -import com.arsdigita.ui.CcmObjectSelectionModel; - -import java.lang.reflect.InvocationTargetException; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Category; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.Folder; - -import java.util.List; - -import org.librecms.CMSConfig; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.core.CcmObject; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.security.PermissionChecker; -import org.libreccm.security.PermissionManager; -import org.librecms.assets.AssetTypeInfo; -import org.librecms.assets.AssetTypesManager; -import org.librecms.contentsection.Asset; -import org.librecms.contentsection.AssetManager; -import org.librecms.contentsection.AssetRepository; -import org.librecms.contentsection.FolderManager; -import org.librecms.contentsection.FolderRepository; -import org.librecms.contentsection.privileges.AssetPrivileges; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.ResourceBundle; -import java.util.TooManyListenersException; - -import static org.librecms.CmsConstants.*; - -/** - * - * @author Jens Pelzetter - */ -public class AssetPane extends LayoutPanel implements Resettable { - - private static final Logger LOGGER = LogManager.getLogger(AssetPane.class); - - public static final String SET_FOLDER = "set_folder"; - private static final String SOURCES_PARAM = "sources"; - private static final String ACTION_PARAM = "action"; - private static final String MOVE = "Move"; - private static final String COPY = "Copy"; - - private final BaseTree tree; - private final SingleSelectionModel selectionModel; - private final FolderSelectionModel folderSelectionModel; - private final FolderRequestLocal folderRequestLocal; - private final SingleSelectionModel selectedAssetModel; - private final ArrayParameter sourcesParameter = new ArrayParameter( - new StringParameter(SOURCES_PARAM)); - private final StringParameter actionParameter = new StringParameter( - ACTION_PARAM); - private final StringParameter selectedAssetTypeParam = new StringParameter( - "selected_asset_type"); - - private AssetFolderBrowser folderBrowser; - private Form browserForm; - private SingleSelect actionSelect; - private Submit actionSubmit; - private TargetSelector targetSelector; - - private SegmentedPanel.Segment browseSegment; -// private SegmentedPanel.Segment currentFolderSegment; - private SegmentedPanel.Segment actionsSegment; - private SegmentedPanel.Segment newFolderSegment; - private SegmentedPanel.Segment editFolderSegment; - private SegmentedPanel.Segment editAssetSegment; - private SegmentedPanel.Segment folderPermissionsSegment; - - @SuppressWarnings("unchecked") - public AssetPane() { - tree = new BaseTree(new FolderTreeModelBuilder() { - - @Override - protected Folder getRootFolder(final PageState state) { - final ContentSection section = CMS - .getContext() - .getContentSection(); - return section.getRootAssetsFolder(); - } - - }); - selectionModel = tree.getSelectionModel(); - folderSelectionModel = new FolderSelectionModel(selectionModel) { - - @Override - protected Long getRootFolderID(final PageState state) { - final ContentSection section = CMS - .getContext() - .getContentSection(); - return section.getRootAssetsFolder().getObjectId(); - } - - }; - folderRequestLocal = new FolderRequestLocal(folderSelectionModel); - - selectedAssetModel = new ParameterSingleSelectionModel<>( - new LongParameter("selected-asset")); - - final SegmentedPanel left = new SegmentedPanel(); - setLeft(left); - - final Label heading = new Label( - new GlobalizedMessage("cms.ui.folder_browser", - CmsConstants.CMS_BUNDLE)); - left.addSegment(heading, tree); - -// final Text placeholder = new Text("Placeholder"); - setBody(createBrowserPane()); - - } - - private SimpleContainer createBrowserPane() { - - final SegmentedPanel panel = new SegmentedPanel(); - - browseSegment = panel.addSegment(); - browserForm = new Form("assetFolderBrowser", - new BoxPanel(BoxPanel.VERTICAL)); - browserForm.setMethod(Form.GET); - folderBrowser = new AssetFolderBrowser(this); - final Paginator paginator = new Paginator( - new AssetFolderBrowserPaginationModelBuilder(folderBrowser), - CMSConfig.getConfig().getFolderBrowseListSize()); - folderBrowser.setPaginator(paginator); - - final CheckboxGroup checkboxGroup = new CheckboxGroup(sourcesParameter); - browserForm.add(checkboxGroup); - final TableColumn checkboxCol = new TableColumn(); - checkboxCol.setHeaderValue( - new GlobalizedMessage("empty_text", CmsConstants.CMS_BUNDLE)); - checkboxCol.setCellRenderer(new TableCellRenderer() { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - final Option result = new Option(key.toString(), - new Text("")); - result.setGroup(checkboxGroup); - return result; - } - - }); - folderBrowser.getColumnModel().add(0, checkboxCol); - - browserForm.add(paginator); - browserForm.add(folderBrowser); - final SimpleContainer actionFormContainer = new SimpleContainer(); - actionFormContainer.add(new Label( - new GlobalizedMessage( - "cms.ui.folder.edit_selection", - CmsConstants.CMS_FOLDER_BUNDLE))); - actionSelect = new SingleSelect(actionParameter); - actionSelect.addOption( - new Option(COPY, - new Label(new GlobalizedMessage( - "cms.ui.folder.copy.action", - CmsConstants.CMS_FOLDER_BUNDLE)))); - actionSelect.addOption( - new Option(MOVE, - new Label(new GlobalizedMessage( - "cms.ui.folder.move.action", - CmsConstants.CMS_FOLDER_BUNDLE)))); - actionFormContainer.add(actionSelect); - actionSubmit = new Submit( - "Go", - new GlobalizedMessage("cms.ui.folder.go", - CmsConstants.CMS_FOLDER_BUNDLE)); - actionFormContainer.add(actionSubmit); - browserForm.addProcessListener(new FormProcessListener() { - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - moveCopyMode(state); - - } - - }); - browserForm.add(actionFormContainer); - - targetSelector = new TargetSelector(); - targetSelector.addProcessListener(new FormProcessListener() { - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - browseMode(state); - targetSelector.setVisible(state, false); - - final Folder folder = targetSelector.getTarget(state); - final String[] objectIds = getSources(state); - - if (isCopy(state)) { - copyObjects(folder, objectIds); - } else if (isMove(state)) { - moveObjects(folder, objectIds); - } - - reset(state); - } - - }); - targetSelector.addValidationListener( - new TargetSelectorValidationListener()); - targetSelector.addSubmissionListener(new FormSubmissionListener() { - - @Override - public void submitted(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (targetSelector.isCancelled(state)) { - reset(state); - browseMode(state); - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.folder.cancelled", - CmsConstants.CMS_FOLDER_BUNDLE)); - } - } - - }); - browseSegment.add(targetSelector); - -// browseSegment.add(paginator); -// browseSegment.add(folderBrowser); - browseSegment.add(browserForm); - -// currentFolderSegment = panel.addSegment(); -// currentFolderSegment.addHeader(new Text("Current folder")); -// final Label currentFolderLabel = new Label(); -// currentFolderLabel.addPrintListener(new PrintListener() { -// -// @Override -// public void prepare(final PrintEvent event) { -// final PageState state = event.getPageState(); -// final Label target = (Label) event.getTarget(); -// -// final long selectedId = Long.parseLong(selectionModel -// .getSelectedKey(state).toString()); -// final long currentFolderId = folderSelectionModel -// .getSelectedObject(state).getObjectId(); -// target.setLabel(String.format( -// "selectedId = %d; currentFolderId = %d", -// selectedId, -// currentFolderId)); -// } -// -// }); -// currentFolderSegment.add(currentFolderLabel); - actionsSegment = panel.addSegment(); - actionsSegment.setIdAttr("folder-browse"); - - final ActionGroup actions = new ActionGroup(); - actionsSegment.add(actions); - - final FolderCreateForm folderCreateForm = new FolderCreateForm( - "fcreat", folderSelectionModel); - folderCreateForm.addSubmissionListener(new FormSubmissionListener() { - - @Override - public void submitted(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - if (event.getSource() == folderCreateForm - && folderCreateForm.isCancelled(state)) { - browseMode(state); - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.cancelled", CmsConstants.CMS_BUNDLE)); - - } - } - - }); - folderCreateForm.addProcessListener(new FormProcessListener() { - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final Object source = event.getSource(); - if (source == folderCreateForm) { - browseMode(state); - } - } - - }); - newFolderSegment = panel.addSegment( - new Label(new GlobalizedMessage("cms.ui.new_folder", - CmsConstants.CMS_BUNDLE)), - folderCreateForm); - - final FolderEditorForm folderEditorForm = new FolderEditorForm( - "fedit", folderSelectionModel); - folderEditorForm.addSubmissionListener(new FormSubmissionListener() { - - @Override - public void submitted(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - if (event.getSource() == folderEditorForm - && folderEditorForm.isCancelled(state)) { - browseMode(state); - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.cancelled", CmsConstants.CMS_BUNDLE)); - } - } - - }); - folderEditorForm.addProcessListener(new FormProcessListener() { - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final Object source = event.getSource(); - if (source == folderEditorForm) { - browseMode(state); - } - } - - }); - editFolderSegment = panel.addSegment( - new Label(new GlobalizedMessage("cms.ui.edit_folder", - CmsConstants.CMS_BUNDLE)), - folderEditorForm); - - final ActionLink createFolderAction = new ActionLink( - new Label(new GlobalizedMessage("cms.ui.new_folder", - CmsConstants.CMS_BUNDLE))); - createFolderAction.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(final ActionEvent event) { - final PageState state = event.getPageState(); - final Object source = event.getSource(); - if (source == createFolderAction) { - newFolderMode(state); - } - } - - }); - actions.addAction(createFolderAction); - - final ActionLink editFolderAction = new ActionLink( - new Label(new GlobalizedMessage("cms.ui.edit_folder", - CmsConstants.CMS_BUNDLE))); - editFolderAction.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(final ActionEvent event) { - final PageState state = event.getPageState(); - final Object source = event.getSource(); - if (source == editFolderAction) { - editFolderMode(state); - } - } - - }); - actions.addAction(editFolderAction); - - final Form newAssetForm = new Form("new-asset-form", - new BoxPanel(BoxPanel.HORIZONTAL)); - newAssetForm.setMethod("GET"); - newAssetForm.add(new Label(new GlobalizedMessage( - "cms.ui.assets.new", CmsConstants.CMS_BUNDLE))); - final SingleSelect newAssetTypeSelect = new SingleSelect( - selectedAssetTypeParam); - try { - newAssetTypeSelect.addPrintListener(new PrintListener() { - - @Override - public void prepare(final PrintEvent event) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AssetTypesManager typesManager = cdiUtil - .findBean(AssetTypesManager.class); - final SingleSelect target = (SingleSelect) event.getTarget(); - target.clearOptions(); - for (final AssetTypeInfo type : typesManager - .getAvailableAssetTypes()) { - final String labelKey = type.getLabelKey(); - final String labelBundle = type.getLabelBundle(); - final ResourceBundle bundle = ResourceBundle - .getBundle(labelBundle); - final String label = bundle.getString(labelKey); - target.addOption(new Option( - type.getAssetClass().getName(), - new Text(label))); - } - } - - }); - } catch (TooManyListenersException ex) { - throw new UnexpectedErrorException(ex); - } - newAssetForm.add(newAssetTypeSelect); - newAssetForm.add(new Submit(new GlobalizedMessage( - "cms.ui.assets.new.create", CmsConstants.CMS_BUNDLE))); - newAssetForm.addProcessListener(new FormProcessListener() { - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - editAssetMode(event.getPageState()); - } - - }); - - actionsSegment.add(newAssetForm); - - final MetaForm editAssetForm = new MetaForm("editAsset") { - - @Override - public Form buildForm(final PageState state) { - - final boolean newAsset; - - final Long selectedAssetId = selectedAssetModel - .getSelectedKey(state); - newAsset = selectedAssetId == null; - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - - final String selectedAssetType; - if (newAsset) { - selectedAssetType = (String) newAssetTypeSelect - .getValue(state); - } else { - final AssetRepository assetRepo = cdiUtil - .findBean(AssetRepository.class); - final Asset asset = assetRepo.findById(selectedAssetModel - .getSelectedKey(state)) - .orElseThrow(() -> new IllegalArgumentException( - String.format("No asset with ID %d in the " - + "database.", - selectedAssetModel - .getSelectedKey(state)))); - selectedAssetType = asset.getClass().getName(); - } - - final AssetTypesManager typesManager = cdiUtil - .findBean(AssetTypesManager.class); - final AssetTypeInfo typeInfo = typesManager - .getAssetTypeInfo(selectedAssetType); - final Class assetForm = typeInfo - .getAssetForm(); - try { - return assetForm - .getConstructor(AssetPane.class) - .newInstance(AssetPane.this); - } catch (NoSuchMethodException - | SecurityException - | InstantiationException - | IllegalAccessException - | InvocationTargetException ex) { - throw new UnexpectedErrorException(String.format( - "Failed to create form '%s' for editing assets " - + "of type '%s'.", - assetForm.getName(), - selectedAssetType)); - } - - } - - }; - editAssetSegment = panel.addSegment(); - editAssetSegment.addHeader( - new Label(new PrintListener() { - - @Override - public void prepare(final PrintEvent event) { - - final PageState state = event.getPageState(); - final Label target = (Label) event.getTarget(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AssetTypesManager typesManager = cdiUtil - .findBean(AssetTypesManager.class); - - if (selectedAssetModel.isSelected(state)) { - target.setLabel( - new GlobalizedMessage( - "cms.ui.admin.assets.edit", - CmsConstants.CMS_BUNDLE)); - } else { - final String assetType = (String) newAssetTypeSelect - .getValue(state); - final AssetTypeInfo typeInfo = typesManager - .getAssetTypeInfo(assetType); - final ResourceBundle bundle = ResourceBundle.getBundle( - typeInfo.getLabelBundle()); - final String typeLabel = bundle - .getString(typeInfo.getLabelKey()); - - target.setLabel(new GlobalizedMessage( - "cms.ui.admin.assets.create", - CmsConstants.CMS_BUNDLE, - new Object[]{typeLabel})); - } - } - - })); - editAssetSegment.add(editAssetForm); - - folderPermissionsSegment = panel.addSegment(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionManager permissionManager = cdiUtil - .findBean(PermissionManager.class); - final String[] privileges = permissionManager - .listDefiniedPrivileges(AssetPrivileges.class) - .toArray(new String[]{}); - final Map privilegeNameMap = new HashMap<>(); - Arrays - .stream(privileges) - .forEach(privilege -> privilegeNameMap.put(privilege, privilege)); - final CcmObjectSelectionModel objSelectionModel - = new CcmObjectSelectionModel<>( - CcmObject.class, folderSelectionModel); - final CMSPermissionsPane folderPermissionsPane = new CMSPermissionsPane( - privileges, privilegeNameMap, objSelectionModel); - folderPermissionsSegment.add(folderPermissionsPane); - - - return panel; - - } - - protected void browseMode(final PageState state) { - tree.setVisible(state, true); - browseSegment.setVisible(state, true); - folderBrowser.setVisible(state, true); - browserForm.setVisible(state, true); - targetSelector.setVisible(state, false); - actionsSegment.setVisible(state, true); - newFolderSegment.setVisible(state, false); - editFolderSegment.setVisible(state, false); - editAssetSegment.setVisible(state, false); - folderPermissionsSegment.setVisible(state, true); - } - - protected void moveCopyMode(final PageState state) { - tree.setVisible(state, false); - browseSegment.setVisible(state, true); - folderBrowser.setVisible(state, false); - browserForm.setVisible(state, false); - targetSelector.setVisible(state, true); - actionsSegment.setVisible(state, false); - newFolderSegment.setVisible(state, false); - editFolderSegment.setVisible(state, false); - targetSelector.expose(state); - editAssetSegment.setVisible(state, false); - folderPermissionsSegment.setVisible(state, false); - } - - protected void newFolderMode(final PageState state) { - tree.setVisible(state, false); - browseSegment.setVisible(state, false); - folderBrowser.setVisible(state, false); - browserForm.setVisible(state, false); - targetSelector.setVisible(state, false); - actionsSegment.setVisible(state, false); - newFolderSegment.setVisible(state, true); - editFolderSegment.setVisible(state, false); - editAssetSegment.setVisible(state, false); - folderPermissionsSegment.setVisible(state, false); - } - - protected void editFolderMode(final PageState state) { - tree.setVisible(state, false); - browseSegment.setVisible(state, false); - targetSelector.setVisible(state, false); - actionsSegment.setVisible(state, false); - newFolderSegment.setVisible(state, false); - editFolderSegment.setVisible(state, true); - editAssetSegment.setVisible(state, false); - folderPermissionsSegment.setVisible(state, false); - } - - protected void editAssetMode(final PageState state) { - tree.setVisible(state, false); - browseSegment.setVisible(state, false); - targetSelector.setVisible(state, false); - actionsSegment.setVisible(state, false); - newFolderSegment.setVisible(state, false); - editFolderSegment.setVisible(state, false); - editAssetSegment.setVisible(state, true); - folderPermissionsSegment.setVisible(state, false); - } - - @Override - public void register(final Page page) { - - super.register(page); - - page.addActionListener(new TreeListener()); - page.addActionListener(new FolderListener()); - - page.setVisibleDefault(tree, true); - page.setVisibleDefault(browseSegment, true); - page.setVisibleDefault(folderBrowser, true); - page.setVisibleDefault(browserForm, true); - page.setVisibleDefault(targetSelector, false); - page.setVisibleDefault(actionsSegment, true); - page.setVisibleDefault(newFolderSegment, false); - page.setVisibleDefault(editFolderSegment, false); - page.setVisibleDefault(editAssetSegment, false); - page.setVisibleDefault(folderPermissionsSegment, true); - - page.addComponentStateParam(this, actionParameter); - page.addComponentStateParam(this, sourcesParameter); - page.addComponentStateParam(this, selectedAssetTypeParam); - page.addComponentStateParam(this, - selectedAssetModel.getStateParameter()); - } - - @Override - public void reset(final PageState state) { - - super.reset(state); - - folderBrowser.getPaginator().reset(state); - - state.setValue(actionParameter, null); - state.setValue(sourcesParameter, null); - - } - - protected SingleSelectionModel getSelectedAssetModel() { - return selectedAssetModel; - } - - protected FolderSelectionModel getFolderSelectionModel() { - return folderSelectionModel; - } - - private String[] getSources(final PageState state) { - - final String[] result = (String[]) state.getValue(sourcesParameter); - - if (result == null) { - return new String[0]; - } else { - return result; - } - } - - protected final boolean isMove(final PageState state) { - return MOVE.equals(getAction(state)); - } - - protected final boolean isCopy(final PageState state) { - return COPY.equals(getAction(state)); - } - - private String getAction(final PageState state) { - return (String) state.getValue(actionParameter); - } - - protected void moveObjects(final Folder target, final String[] objectIds) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AssetFolderBrowserController controller = cdiUtil.findBean( - AssetFolderBrowserController.class); - - controller.moveObjects(target, objectIds); - } - - protected void copyObjects(final Folder target, final String[] objectIds) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AssetFolderBrowserController controller = cdiUtil.findBean( - AssetFolderBrowserController.class); - - controller.copyObjects(target, objectIds); - } - - private final class FolderListener implements ActionListener { - - @Override - @SuppressWarnings("unchecked") - public void actionPerformed(final ActionEvent event) { - - final PageState state = event.getPageState(); - - if (!selectionModel.isSelected(state)) { - final String folder = state - .getRequest() - .getParameter(SET_FOLDER); - - if (folder == null) { - final Category root = CMS - .getContext() - .getContentSection() - .getRootAssetsFolder(); - final Long folderId = root.getObjectId(); - - selectionModel.setSelectedKey(state, folderId); - } else { - selectionModel.setSelectedKey(state, Long.parseLong(folder)); - } - } - } - - } - - private final class TreeListener implements ActionListener { - - @Override - public void actionPerformed(final ActionEvent event) { - - final PageState state = event.getPageState(); - - final Category root = CMS - .getContext() - .getContentSection() - .getRootAssetsFolder(); - - if (!root.equals(folderRequestLocal.getFolder(state))) { - // Expand the ancestor nodes of the currently - // selected node. - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderTreeModelController controller = cdiUtil.findBean( - FolderTreeModelController.class); - final List ancestorIds = controller.findAncestorIds( - folderRequestLocal.getFolder(state)); - ancestorIds.forEach(id -> tree.expand(id.toString(), state)); - - } - } - - } - - private class TargetSelector extends Form implements Resettable { - - private final FolderSelectionModel targetFolderModel; - private final AssetFolderTree folderTree; - private final Submit cancelButton; - - public TargetSelector() { - super("targetSelector", new BoxPanel()); - setMethod(GET); - targetFolderModel = new FolderSelectionModel("target") { - - @Override - protected Long getRootFolderID(final PageState state) { - final ContentSection section = CMS - .getContext() - .getContentSection(); - return section.getRootAssetsFolder().getObjectId(); - } - - }; - folderTree = new AssetFolderTree(targetFolderModel); - - folderTree.setCellRenderer(new FolderTreeCellRenderer()); - - final Label label = new Label(new PrintListener() { - - @Override - public void prepare(final PrintEvent event) { - - final PageState state = event.getPageState(); - final Label label = (Label) event.getTarget(); - final int numberOfItems = getSources(state).length; - final Category folder = (Category) folderSelectionModel - .getSelectedObject(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager categoryManager = cdiUtil - .findBean(CategoryManager.class); - - final String targetFolderPath; - if (targetFolderModel.getSelectedObject(state) == null) { - targetFolderPath = ""; - } else { - targetFolderPath = categoryManager.getCategoryPath( - targetFolderModel.getSelectedObject(state)); - } - - if (isMove(state)) { - label.setLabel(new GlobalizedMessage( - "cms.ui.folder.move", - CmsConstants.CMS_FOLDER_BUNDLE, - new Object[]{ - numberOfItems, - categoryManager.getCategoryPath(folder), - targetFolderPath - })); - } else if (isCopy(state)) { - label.setLabel(new GlobalizedMessage( - "cms.ui.folder.copy", - CMS_BUNDLE, - new Object[]{ - numberOfItems, - categoryManager.getCategoryPath(folder), - targetFolderPath - })); - } - } - - }); - - label.setOutputEscaping(false); - add(label); - add(folderTree); - add(new FormErrorDisplay(this)); - final SaveCancelSection saveCancelSection = new SaveCancelSection(); - cancelButton = saveCancelSection.getCancelButton(); - add(saveCancelSection); - } - - @Override - public void register(final Page page) { - super.register(page); - page.addComponentStateParam(this, - targetFolderModel.getStateParameter()); - } - - public void expose(final PageState state) { - - final Folder folder = folderSelectionModel.getSelectedObject(state); - targetFolderModel.clearSelection(state); - if (folder != null) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderManager folderManager = cdiUtil.findBean( - FolderManager.class); - if (!folderManager.getParentFolder(folder).isPresent()) { - folderTree.expand(Long.toString(folder.getObjectId()), - state); - } else { - final List parents = folderManager - .getParentFolders(folder); - parents - .stream() - .map(parent -> Long.toString(parent.getObjectId())) - .forEach(folderId -> folderTree.expand(folderId, - state)); - } - } - } - - @Override - public void reset(final PageState state) { - folderTree.clearSelection(state); - state.setValue(folderTree.getSelectionModel().getStateParameter(), - null); - } - - public Folder getTarget(final PageState state) { - return targetFolderModel.getSelectedObject(state); - } - - public boolean isCancelled(final PageState state) { - return cancelButton.isSelected(state); - } - - } - - private class FolderTreeCellRenderer implements TreeCellRenderer { - - private final RequestLocal invalidFoldersRequestLocal - = new RequestLocal(); - - /** - * Render the folders appropriately. The selected folder is a bold - * label. Invalid folders are plain labels. Unselected, valid folders - * are control links. Invalid folders are: the parent folder of the - * sources, any of the sources, and any subfolders of the sources. - */ - @Override - @SuppressWarnings("unchecked") - public Component getComponent(final Tree tree, - final PageState state, - final Object value, - final boolean isSelected, - final boolean isExpanded, - final boolean isLeaf, - final Object key) { - - // Get the list of invalid folders once per request. - final List invalidFolders; - - if (invalidFoldersRequestLocal.get(state) == null) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AssetFolderBrowserController controller = cdiUtil - .findBean(AssetFolderBrowserController.class); - invalidFolders = controller.createInvalidTargetsList( - Arrays.asList(getSources(state))); - invalidFoldersRequestLocal.set(state, invalidFolders); - } else { - invalidFolders = (List) invalidFoldersRequestLocal - .get(state); - } - final Label label = new Label(value.toString()); - - if (invalidFolders.contains(String.format( - FOLDER_BROWSER_KEY_PREFIX_FOLDER + "%s", key))) { - return label; - } - - // Bold if selected - if (isSelected) { - label.setFontWeight(Label.BOLD); - return label; - } - - return new ControlLink(label); - } - - } - - private class TargetSelectorValidationListener - implements FormValidationListener { - - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (getSources(state).length <= 0) { - throw new IllegalStateException("No source items specified"); - } - - final Folder target = targetSelector.getTarget(state); - final FormData data = event.getFormData(); - if (target == null) { - data.addError(new GlobalizedMessage( - "cms.ui.folder.need_select_target_folder", - CmsConstants.CMS_FOLDER_BUNDLE)); - //If the target is null, we can skip the rest of the checks - return; - } - - if (target.equals(folderSelectionModel.getSelectedObject(state))) { - data.addError(new GlobalizedMessage( - "cms.ui.folder.not_within_same_folder", - CmsConstants.CMS_FOLDER_BUNDLE)); - } - - // check create item permission - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - if (!permissionChecker.isPermitted( - ItemPrivileges.CREATE_NEW, target)) { - data.addError("cms.ui.folder.no_permission_for_item", - CmsConstants.CMS_FOLDER_BUNDLE); - } - - for (String source : getSources(state)) { - - validateObject(source, target, state, data); - - } - } - - private void validateObject(final String objectId, - final Folder target, - final PageState state, - final FormData data) { - - Objects.requireNonNull(objectId, "objectId can't be null."); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderRepository folderRepo = cdiUtil - .findBean(FolderRepository.class); - final AssetRepository assetRepo = cdiUtil - .findBean(AssetRepository.class); - final AssetManager assetManager = cdiUtil - .findBean(AssetManager.class); - final AssetFolderBrowserController controller = cdiUtil - .findBean(AssetFolderBrowserController.class); - final FolderManager folderManager = cdiUtil - .findBean(FolderManager.class); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - - final CcmObject object; - final String name; - if (objectId.startsWith(FOLDER_BROWSER_KEY_PREFIX_FOLDER)) { - - final long folderId = Long.parseLong(objectId.substring( - FOLDER_BROWSER_KEY_PREFIX_FOLDER.length())); - final Folder folder = folderRepo.findById(folderId).orElseThrow( - () -> new IllegalArgumentException(String.format( - "No folder with id %d in database.", folderId))); - - name = folder.getName(); - - //Check if folder or subfolder contains in use assets - if (isMove(state)) { - final FolderManager.FolderIsMovable movable = folderManager - .folderIsMovable(folder, target); - switch (movable) { - case DIFFERENT_SECTIONS: - addErrorMessage(data, - "cms.ui.folder.different_sections", - name); - break; - case HAS_IN_USE_ASSETS: - addErrorMessage(data, - "cms.ui.folder.has_in_use_assets", - name); - break; - case DIFFERENT_TYPES: - addErrorMessage(data, - "cms.ui.folder.different_folder_types", - name); - break; - case IS_ROOT_FOLDER: - addErrorMessage(data, - "cms.ui.folder.is_root_folder", - name); - break; - case SAME_FOLDER: - addErrorMessage(data, - "cms.ui.folder.same_folder", - name); - break; - case YES: - //Nothing - break; - default: - throw new UnexpectedErrorException(String.format( - "Unknown state '%s' for '%s'.", - movable, - FolderManager.FolderIsMovable.class. - getName())); - } - } - - object = folder; - } else if (objectId.startsWith(FOLDER_BROWSER_KEY_PREFIX_ASSET)) { - final long assetId = Long.parseLong(objectId.substring( - FOLDER_BROWSER_KEY_PREFIX_ASSET.length())); - final Asset asset = assetRepo - .findById(assetId) - .orElseThrow(() -> new IllegalArgumentException( - String.format( - "No asset with id %d in the database.", - assetId))); - - name = asset.getDisplayName(); - - if (isMove(state) && assetManager.isAssetInUse(asset)) { - addErrorMessage(data, "cms.ui.folder.item_is_live", name); - } - - object = asset; - } else { - throw new IllegalArgumentException(String.format( - "Provided objectId '%s' does not start with '%s' " - + "or '%s'.", - objectId, - FOLDER_BROWSER_KEY_PREFIX_FOLDER, - FOLDER_BROWSER_KEY_PREFIX_ASSET)); - } - - final long count = controller.countObjects(target, name); - if (count > 0) { - // there is an item or subfolder in the target folder that already has this name - addErrorMessage(data, "cms.ui.folder.item_already_exists", - name); - } - - if (!(permissionChecker.isPermitted( - ItemPrivileges.DELETE, object)) - && isMove(state)) { - addErrorMessage(data, - "cms.ui.folder.no_permission_for_item", - object.getDisplayName()); - } - - } - - } - - private void addErrorMessage(final FormData data, - final String message, - final String itemName) { - data.addError(new GlobalizedMessage(message, - CmsConstants.CMS_FOLDER_BUNDLE, - new Object[]{itemName})); - } - - private class AssetFolderTree extends Tree { - - public AssetFolderTree(final FolderSelectionModel folderSelectionModel) { - - super(new FolderTreeModelBuilder() { - - @Override - protected Folder getRootFolder(final PageState state) { - final ContentSection section = CMS - .getContext() - .getContentSection(); - - return section.getRootAssetsFolder(); - } - - }); - setSelectionModel(folderSelectionModel); - } - - @Override - public void setSelectedKey(final PageState state, final Object key) { - if (key instanceof String) { - final Long keyAsLong; - if (((String) key).startsWith( - FOLDER_BROWSER_KEY_PREFIX_FOLDER)) { - keyAsLong = Long.parseLong(((String) key).substring( - FOLDER_BROWSER_KEY_PREFIX_FOLDER.length())); - } else { - keyAsLong = Long.parseLong((String) key); - } - super.setSelectedKey(state, keyAsLong); - } else if (key instanceof Long) { - super.setSelectedKey(state, key); - } else { - //We know that a FolderSelectionModel only takes keys of type Long. - //Therefore we try to cast here - final Long keyAsLong = (Long) key; - super.setSelectedKey(state, keyAsLong); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetSearchWidget.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetSearchWidget.java deleted file mode 100644 index 8b95bc58d..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetSearchWidget.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.form.Widget; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.cms.CMS; -import com.arsdigita.xml.Element; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.assets.AssetTypeInfo; -import org.librecms.assets.AssetTypesManager; -import org.librecms.contentsection.Asset; -import org.librecms.contentsection.AssetRepository; -import org.librecms.contentsection.ContentSection; - -import java.util.Map; -import java.util.ResourceBundle; - -/** - * A widget for selecting an asset. The widget does not contain any other - * widgets, only the information required to create an HTML/JavaScript dialog - * for selecting an asset. To create the dialog the - * {@link org.librecms.contentsection.rs.Assets} class can be used which - * provides several methods for getting the assets of an content section. - * - * @author Jens Pelzetter - */ -public class AssetSearchWidget extends Widget { - - private Class type; - - public AssetSearchWidget(final String name) { - super(new LongParameter(name)); - } - - public AssetSearchWidget(final String name, - final Class type) { - this(name); - this.type = type; - } - - @Override - public boolean isCompound() { - return true; - } - - @Override - protected String getType() { - return "asset-search-widget"; - } - - @Override - protected String getElementTag() { - return "cms:asset-search-widget"; - } - - @Override - public void generateWidget(final PageState state, - final Element parent) { - - final Element widget = parent.newChildElement(getElementTag(), - CMS.CMS_XML_NS); - - widget.addAttribute("name", getName()); - - if (type != null) { - widget.addAttribute("asset-type", type.getName()); - } - - final ContentSection section = CMS.getContext().getContentSection(); - widget.addAttribute("content-section", section.getLabel()); - - final Long value = (Long) getValue(state); - if (value != null) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AssetSearchWidgetController controller = cdiUtil - .findBean(AssetSearchWidgetController.class); - - final Map data = controller.getData(value); - - final Element selected = widget - .newChildElement("cms:selected-asset", CMS.CMS_XML_NS); - selected.addAttribute( - "assetId", data.get(AssetSearchWidgetController.OBJECT_ID) - ); - selected.addAttribute("title", - data.get(AssetSearchWidgetController.TITLE)); - selected.addAttribute("type", - data.get(AssetSearchWidgetController.TYPE)); - - exportAttributes(widget); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetSearchWidgetController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetSearchWidgetController.java deleted file mode 100644 index cac64adad..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/AssetSearchWidgetController.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets; - -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.assets.AssetTypeInfo; -import org.librecms.assets.AssetTypesManager; -import org.librecms.contentsection.Asset; -import org.librecms.contentsection.AssetRepository; - -import java.util.HashMap; -import java.util.Map; -import java.util.ResourceBundle; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -public class AssetSearchWidgetController { - - protected static final String OBJECT_ID = "objectId"; - protected static final String TYPE = "type"; - protected static final String TITLE = "title"; - - @Inject - private AssetRepository assetRepository; - - @Inject - private AssetTypesManager typesManager; - - @Inject - private GlobalizationHelper globalizationHelper; - - @Transactional(Transactional.TxType.REQUIRED) - public Map getData(final long assetId) { - - final Asset asset = assetRepository - .findById(assetId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No Asset with ID %d in the database.", assetId))); - - final Map data = new HashMap<>(); - - data.put(OBJECT_ID, Long.toString(asset.getObjectId())); - - data.put(TITLE, - globalizationHelper - .getValueFromLocalizedString(asset.getTitle())); - final AssetTypeInfo typeInfo = typesManager - .getAssetTypeInfo(asset.getClass().getName()); - final ResourceBundle bundle = ResourceBundle - .getBundle(typeInfo.getLabelBundle(), - globalizationHelper.getNegotiatedLocale()); - final String typeLabel = bundle.getString(typeInfo.getLabelKey()); - - data.put(TYPE, typeLabel); - - return data; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/IsControllerForAssetType.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/IsControllerForAssetType.java deleted file mode 100644 index 9962cf2fa..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/IsControllerForAssetType.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets; - -import org.librecms.contentsection.Asset; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import javax.inject.Qualifier; - -/** - * - * @author Jens Pelzetter - */ -@Qualifier -@Retention(RetentionPolicy.RUNTIME) -@Target({ - ElementType.METHOD, - ElementType.FIELD, - ElementType.PARAMETER, - ElementType.TYPE -}) -public @interface IsControllerForAssetType { - - Class value(); - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/ItemSearchWidget.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/ItemSearchWidget.java deleted file mode 100644 index c43804d81..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/ItemSearchWidget.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.form.Widget; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.cms.CMS; -import com.arsdigita.xml.Element; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentSection; -import org.librecms.contenttypes.ContentTypeInfo; -import org.librecms.contenttypes.ContentTypesManager; - -import java.util.ResourceBundle; - -/** - * - * @author Jens Pelzetter - */ -public class ItemSearchWidget extends Widget { - - private Class type; - - public ItemSearchWidget(final String name) { - super(new LongParameter(name)); - } - - @Override - public boolean isCompound() { - return true; - } - - @Override - protected String getType() { - return "item-search-widget"; - } - - @Override - protected String getElementTag() { - return "cms:item-search-widget"; - } - - @Override - public void generateWidget(final PageState state, - final Element parent) { - - final Element widget = parent.newChildElement(getElementTag(), - CMS.CMS_XML_NS); - - widget.addAttribute("name", getName()); - widget.addAttribute("content-section", - CMS.getContext().getContentSection().getLabel()); - - if (type != null) { - widget.addAttribute("asset-type", type.getName()); - } - -// final ContentSection section = CMS.getContext().getContentSection(); -// widget.addAttribute("content-section", section.getLabel()); - - final Long value = (Long) getValue(state); - if (value != null) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil - .findBean(ContentItemRepository.class); - final ContentTypesManager typesManager = cdiUtil - .findBean(ContentTypesManager.class); - final GlobalizationHelper globalizationHelper = cdiUtil - .findBean(GlobalizationHelper.class); - - final ContentItem item = itemRepo - .findById(value) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", value))); - - final Element selected = widget - .newChildElement("cms:selected-content-item", CMS.CMS_XML_NS); - selected.addAttribute("contentItemId", - Long.toString(item.getObjectId())); - selected.addAttribute("name", item.getDisplayName()); - selected.addAttribute( - "title", - globalizationHelper.getValueFromLocalizedString(item.getTitle())); - final ContentTypeInfo typeInfo = typesManager - .getContentTypeInfo(item.getClass()); - final ResourceBundle bundle = ResourceBundle - .getBundle(typeInfo.getLabelBundle(), - globalizationHelper.getNegotiatedLocale()); - final String typeLabel = bundle.getString(typeInfo.getLabelKey()); - selected.addAttribute("type", typeLabel); - - exportAttributes(widget); - - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractBinaryAssetForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractBinaryAssetForm.java deleted file mode 100644 index 58cf71b42..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractBinaryAssetForm.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.cms.ui.FileUploadSection; -import com.arsdigita.cms.ui.assets.AbstractAssetForm; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.globalization.GlobalizedMessage; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; - -import org.librecms.CmsConstants; -import org.librecms.assets.BinaryAsset; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -/** - * Base form for assets which extend {@link BinaryAsset}. - * - * @author Jens Pelzetter - * @param Type of binary asset - */ -public abstract class AbstractBinaryAssetForm - extends AbstractAssetForm { - - private TextArea description; - - private Text fileName; - - private Text mimeType; - - private Text size; - - private FileUploadSection fileUpload; - - public AbstractBinaryAssetForm(final AssetPane assetPane) { - super(assetPane); - } - - @Override - protected void addWidgets() { - - final BoxPanel panel = new BoxPanel(BoxPanel.VERTICAL); - - panel.add(new Label(new GlobalizedMessage( - "cms.ui.assets.binaryasset.description", - CmsConstants.CMS_BUNDLE))); - description = new TextArea("binaryasset-description"); - panel.add(description); - - panel.add(new Label( - new GlobalizedMessage("cms.ui.assets.binaryasset.filename", - CmsConstants.CMS_BUNDLE))); - fileName = new Text(); - panel.add(fileName); - - panel.add(new Label( - new GlobalizedMessage("cms.ui.assets.binaryasset.mimetype", - CmsConstants.CMS_BUNDLE))); - mimeType = new Text(); - panel.add(mimeType); - - panel.add(new Label( - new GlobalizedMessage("cms.ui.assets.binaryasset.size", - CmsConstants.CMS_BUNDLE))); - size = new Text(); - panel.add(size); - - fileUpload = new FileUploadSection( - new GlobalizedMessage("cms.ui.assets.binaryasset.mimetype", - CmsConstants.CMS_BUNDLE), - "", - ""); - panel.add(fileUpload); - - add(panel); - - setEncType(CmsConstants.FORM_ENCTYPE_MULTIPART); - } - - @Override - protected void initForm(final PageState state, - final Map data) { - - super.initForm(state, data); - - if (!data.isEmpty()) { - - description.setValue(state, - data.get("description")); - - if (data.containsKey("data")) { - - final byte[] binaryData = (byte[]) data.get("data"); - if (binaryData.length == 0) { - fileName.setText("-"); - mimeType.setText("-"); - size.setText("-"); - } else { - fileName.setText((String) data.get("fileName")); - mimeType.setText((String) data.get("mimeType")); - size.setText(Long.toString((long) data.get("size"))); - } - - } else { - fileName.setText("-"); - mimeType.setText("-"); - size.setText("-"); - } - } - } - - @Override - protected void showLocale(final PageState state) { - - final Long selectedAssetId = getSelectedAssetId(state); - - if (selectedAssetId != null) { - - final Map data = getController() - .getAssetData(selectedAssetId, - getAssetClass(), - getSelectedLocale(state)); - - description - .setValue( - state, - data - .get(AbstractBinaryAssetFormController.DESCRIPTION)); - } - } - - @Override - protected Map collectData(final FormSectionEvent event) - throws FormProcessException { - - return getFileData(event); - } - - private Map getFileData(final FormSectionEvent event) - throws FormProcessException { - - final File file = fileUpload.getFile(event); - if (file == null) { - return Collections.emptyMap(); - } else { - final Path path = file.toPath(); - final byte[] data; - try { - data = Files.readAllBytes(path); - } catch (IOException ex) { - throw new FormProcessException(ex); - } - - final Map assetData = new HashMap<>(); - - assetData.put(AbstractBinaryAssetFormController.DATA, - data); - assetData.put(AbstractBinaryAssetFormController.FILE_NAME, - fileUpload.getFileName(event)); - assetData.put(AbstractBinaryAssetFormController.SIZE, - data.length); - assetData.put(AbstractBinaryAssetFormController.MIME_TYPE, - fileUpload.getMimeType(event)); - - return assetData; - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractBinaryAssetFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractBinaryAssetFormController.java deleted file mode 100644 index 151f6d651..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractBinaryAssetFormController.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.AbstractAssetFormController; - -import org.librecms.assets.BinaryAsset; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import javax.activation.MimeType; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - * @param - */ -public abstract class AbstractBinaryAssetFormController - extends AbstractAssetFormController { - - protected static final String DESCRIPTION = "description"; - - protected static final String FILE_NAME = "fileName"; - - protected static final String MIME_TYPE = "mimeType"; - - protected static final String DATA = "data"; - - protected static final String SIZE = "size"; - - @Override - @Transactional(Transactional.TxType.REQUIRED) - protected Map getAssetData(final T asset, - final Locale selectedLocale) { - - final Map data = new HashMap<>(); - - final String description = asset - .getDescription() - .getValue(selectedLocale); - - data.put(DESCRIPTION, description); - data.put(FILE_NAME, asset.getFileName()); - data.put(MIME_TYPE, asset.getMimeType()); - data.put(DATA, asset.getData()); - data.put(SIZE, asset.getSize()); - - return data; - } - - @Override - @Transactional(Transactional.TxType.REQUIRED) - public void updateAssetProperties(final T asset, - final Locale selectedLocale, - final Map data) { - - if (data.containsKey(DESCRIPTION)) { - asset.getDescription().putValue(selectedLocale, - (String) data.get(DESCRIPTION)); - } - - if (data.containsKey(FILE_NAME)) { - asset.setFileName((String) data.get(FILE_NAME)); - } - - if (data.containsKey(MIME_TYPE)) { - asset.setMimeType((MimeType) data.get(MIME_TYPE)); - } - - if (data.containsKey(DATA)) { - //asset.setData((byte[]) data.get(DATA)); - } - - if (data.containsKey(SIZE)) { - asset.setSize((long) data.get(SIZE)); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractBookmarkForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractBookmarkForm.java deleted file mode 100644 index 98be1388a..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractBookmarkForm.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.cms.ui.assets.AbstractAssetForm; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; -import org.librecms.assets.Bookmark; -import org.librecms.contentsection.Asset; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * Abstract base form for all forms for {@link BookmarkAsset}s. - * - * @author Jens Pelzetter - * @param Type of the Bookmark Asset. - */ -public abstract class AbstractBookmarkForm - extends AbstractAssetForm { - - private TextArea description; - - private TextField url; - - public AbstractBookmarkForm(final AssetPane assetPane) { - super(assetPane); - } - - @Override - protected void addWidgets() { - - add(new Label( - new GlobalizedMessage("cms.ui.assets.bookmark.description", - CmsConstants.CMS_BUNDLE))); - description = new TextArea("bookmark-description"); - add(description); - - add(new Label(new GlobalizedMessage("cms.ui.assets.bookmark.url", - CmsConstants.CMS_BUNDLE))); - url = new TextField("bookmark-url"); - add(url); - - addValidationListener(new FormValidationListener() { - - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - - try { - new URL((String) url.getValue(state)); - } catch (MalformedURLException ex) { - data.addError(new GlobalizedMessage( - "cms.ui.assets.bookmark.url.malformed", - CmsConstants.CMS_BUNDLE)); - } - } - - }); - - } - - @Override - protected void initForm(final PageState state, - final Map data) { - - super.initForm(state, data); - - if (!data.isEmpty()) { - - description - .setValue( - state, - data.get(AbstractBookmarkFormController.DESCRIPTION)); - url.setValue(state, data.get(AbstractBookmarkFormController.URL)); - - } - } - - @Override - protected void showLocale(final PageState state) { - - final Long selectedAssetId = getSelectedAssetId(state); - - if (selectedAssetId != null) { - - final Map data = getController() - .getAssetData(selectedAssetId, - getAssetClass(), - getSelectedLocale(state)); - - description.setValue( - state, - data.get(AbstractBinaryAssetFormController.DESCRIPTION)); - } - } - - protected void updateData(final Bookmark bookmark, - final PageState state) { - bookmark - .getDescription() - .putValue(getSelectedLocale(state), - (String) description.getValue(state)); - - bookmark.setUrl((String) url.getValue(state)); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractBookmarkFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractBookmarkFormController.java deleted file mode 100644 index db319efa8..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractBookmarkFormController.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.AbstractAssetFormController; - -import org.librecms.assets.Bookmark; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -/** - * - * @author Jens Pelzetter - * @param - */ -public abstract class AbstractBookmarkFormController - extends AbstractAssetFormController { - - protected static final String DESCRIPTION = "description"; - - protected static final String URL = "url"; - - @Override - protected Map getAssetData(final T asset, - final Locale selectedLocale) { - - final String description = asset - .getDescription() - .getValue(selectedLocale); - - final String url = asset.getUrl(); - - final Map data = new HashMap<>(); - - data.put("description", description); - data.put("url", url); - - return data; - } - - @Override - public void updateAssetProperties(final T asset, - final Locale selectedLocale, - final Map data) { - - if (data.containsKey(DESCRIPTION)) { - - asset.getDescription().putValue(selectedLocale, - (String) data.get(DESCRIPTION)); - - } - - if (data.containsKey(URL)) { - - asset.setUrl((String) data.get(URL)); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractContactableEntityForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractContactableEntityForm.java deleted file mode 100644 index c271e493c..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractContactableEntityForm.java +++ /dev/null @@ -1,434 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.event.TableActionEvent; -import com.arsdigita.bebop.event.TableActionListener; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableColumnModel; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.ui.assets.AbstractAssetForm; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.cms.ui.assets.AssetSearchWidget; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.CmsConstants; -import org.librecms.assets.ContactEntryKey; -import org.librecms.assets.ContactableEntity; -import org.librecms.assets.PostalAddress; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TooManyListenersException; - -import static org.librecms.CmsConstants.*; - -/** - * - * @author Jens Pelzetter - * @param - */ -public abstract class AbstractContactableEntityForm - extends AbstractAssetForm { - - private static final int COL_CONTACT_ENTRIES_KEY = 0; - - private static final int COL_CONTACT_ENTRIES_VALUE = 1; - - private static final int COL_CONTACT_ENTRIES_REMOVE = 2; - - private SimpleContainer contactEntriesContainer; - - private Table contactEntriesTable; - - private SingleSelect contactEntryKeySelect; - - private TextField contactEntryValueField; - - private Submit addContactEntryLink; - - private AssetSearchWidget postalAddressSearchWidget; - - public AbstractContactableEntityForm(final AssetPane assetPane) { - - super(assetPane); - } - - @Override - protected void addWidgets() { - - addPropertyWidgets(); - - contactEntriesContainer = new BoxPanel(BoxPanel.VERTICAL) { - - @Override - public boolean isVisible(final PageState state) { - return getSelectedAssetId(state) != null; - } - - }; - add(contactEntriesContainer); - - contactEntriesTable = buildContactEntriesTable(); - contactEntriesContainer.add(contactEntriesTable); - - contactEntryKeySelect = new SingleSelect(new StringParameter( - "contactentry-key")); - try { - contactEntryKeySelect - .addPrintListener(new ContactEntryKeySelectPrintListener()); - } catch (TooManyListenersException ex) { - throw new RuntimeException(ex); - } - contactEntriesContainer.add(new Label( - new GlobalizedMessage( - "cms.ui.authoring.assets.contactable.contactentries.key", - CMS_BUNDLE)) - ); - contactEntriesContainer.add(contactEntryKeySelect); - - contactEntryValueField = new TextField("contact-entry-value"); - contactEntriesContainer.add(new Label( - new GlobalizedMessage( - "cms.ui.authoring.assets.contactable.contactentries.value", - CMS_BUNDLE)) - ); - contactEntriesContainer.add(contactEntryValueField); - - addContactEntryLink = new Submit( - new GlobalizedMessage( - "cms.ui.authoring.assets.contactable.contactentries.add", - CMS_BUNDLE) - ); - contactEntriesContainer.add(addContactEntryLink); - - contactEntriesContainer.add(new Label( - new GlobalizedMessage( - "cms.ui.authoring.assets.contactable.postaladdress", - CMS_BUNDLE)) - ); - postalAddressSearchWidget = new AssetSearchWidget( - "contactable-postaladdress", PostalAddress.class - ); - contactEntriesContainer.add(postalAddressSearchWidget); - - } - - @Override - public void initForm(final PageState state, - final Map data) { - - super.initForm(state, data); - - final Long selectedAssetId = getSelectedAssetId(state); - - if (selectedAssetId != null) { - - postalAddressSearchWidget.setValue( - state, - data.get(AbstractContactableEntityFormController.POSTAL_ADDRESS) - ); - } - } - - @Override - protected Map collectData( - final FormSectionEvent event) { - - final PageState state = event.getPageState(); - - final Map data = new HashMap<>(); - - if (postalAddressSearchWidget.getValue(state) != null) { - - data.put(AbstractContactableEntityFormController.POSTAL_ADDRESS, - postalAddressSearchWidget.getValue(state)); - } - - return data; - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (addContactEntryLink.isSelected(state)) { - - final Long selectedAssetId = getSelectedAssetId(state); - if (selectedAssetId == null) { - throw new FormProcessException( - new GlobalizedMessage( - "cms.ui.assets.none_selected", CMS_BUNDLE) - ); - } - - @SuppressWarnings("unchecked") - final AbstractContactableEntityFormController controller - = (AbstractContactableEntityFormController) getController(); - - final String key = (String) contactEntryKeySelect - .getValue(state); - final String value = (String) contactEntryValueField.getValue(state); - - controller.addContactEntry(key, value, selectedAssetId); - - contactEntryKeySelect.setValue(state, null); - contactEntryValueField.setValue(state, null); - } else { - super.process(event); - } - } - - protected abstract void addPropertyWidgets(); - - private Table buildContactEntriesTable() { - - final Table table = new Table(); -// { - -// @Override -// public boolean isVisible(final PageState state) { -// return getSelectedAsset(state).isPresent(); -// } -// }; - final TableColumnModel columnModel = table.getColumnModel(); - columnModel.add(new TableColumn( - COL_CONTACT_ENTRIES_KEY, - new Label( - new GlobalizedMessage( - "cms.ui.authoring.assets.contactable.contactentries.key", - CmsConstants.CMS_BUNDLE - ) - ) - )); - columnModel.add(new TableColumn( - COL_CONTACT_ENTRIES_VALUE, - new Label( - new GlobalizedMessage( - "cms.ui.authoring.assets.contactable.contactentries.value", - CmsConstants.CMS_BUNDLE - ) - ) - )); - columnModel.add(new TableColumn( - COL_CONTACT_ENTRIES_REMOVE, - new Label( - new GlobalizedMessage( - "cms.ui.authoring.assets.contactable.contactentries.remove", - CmsConstants.CMS_BUNDLE - ) - ) - )); - - table.setModelBuilder(new ContactEntriesTableModelBuilder()); - - table - .getColumn(COL_CONTACT_ENTRIES_REMOVE) - .setCellRenderer(new ContactEntryRemoveCellRenderer()); - - table.setEmptyView( - new Label( - new GlobalizedMessage( - "cms.ui.authoring.assets.contactable.contactentries.none", - CmsConstants.CMS_BUNDLE - ) - ) - ); - - table.addTableActionListener(new TableActionListener() { - - @Override - public void cellSelected(final TableActionEvent event) - throws FormProcessException { - - final Integer rowKey = (Integer) event.getRowKey(); - - @SuppressWarnings("unchecked") - final AbstractContactableEntityFormController controller - = (AbstractContactableEntityFormController) getController(); - final PageState state = event.getPageState(); - final Long selectedId = getSelectedAssetId(state); - if (selectedId != null) { - controller.removeContactEntry(rowKey, selectedId); - } - } - - @Override - public void headSelected(final TableActionEvent event) { - - // Nothing - } - - }); - - return table; - } - - private class ContactEntriesTableModelBuilder - extends LockableImpl implements TableModelBuilder { - - @Override - public TableModel makeModel(final Table table, - final PageState state) { - - final Long selectedId = getSelectedAssetId(state); - if (selectedId == null) { - throw new RuntimeException("No asset selected."); - } - - @SuppressWarnings("unchecked") - final AbstractContactableEntityFormController controller - = (AbstractContactableEntityFormController) getController(); - final List contactEntries = controller - .getContactEntries(selectedId, getSelectedLocale(state)); - - return new ContactEntriesTableModel(contactEntries); - } - - } - - private class ContactEntriesTableModel implements TableModel { - - private final Iterator contactEntries; - - private String[] currentContactEntry; - - public ContactEntriesTableModel( - final List contactEntries) { - - this.contactEntries = contactEntries.iterator(); - } - - @Override - public int getColumnCount() { - return 3; - } - - @Override - public boolean nextRow() { - - if (contactEntries.hasNext()) { - currentContactEntry = contactEntries.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - - switch (columnIndex) { - case COL_CONTACT_ENTRIES_KEY: - return currentContactEntry[1]; - case COL_CONTACT_ENTRIES_VALUE: - return currentContactEntry[2]; - case COL_CONTACT_ENTRIES_REMOVE: - return new Label( - new GlobalizedMessage( - "cms.ui.authoring.assets.contactable" - + ".contactentries.remove", - CmsConstants.CMS_BUNDLE - ) - ); - default: - throw new IllegalArgumentException(String.format( - "Illegal column index %d.", columnIndex)); - - } - } - - @Override - public Object getKeyAt(int columnIndex) { - return currentContactEntry[0]; - } - - } - - private class ContactEntryRemoveCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - return new ControlLink((Component) value); - } - - } - - private class ContactEntryKeySelectPrintListener implements PrintListener { - - @Override - public void prepare(final PrintEvent event) { - - final SingleSelect target = (SingleSelect) event.getTarget(); - target.clearOptions(); - - target.addOption( - new Option("", - new Label(new GlobalizedMessage("cms.ui.select_one", - CMS_BUNDLE))) - ); - - final AbstractContactableEntityFormController controller = (AbstractContactableEntityFormController) getController(); - - final PageState state = event.getPageState(); - - final List keys = controller - .findAvailableContactEntryKeys(getSelectedLocale(state)); - - for (final String[] key : keys) { - target.addOption(new Option(key[0], new Text(key[1]))); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractContactableEntityFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractContactableEntityFormController.java deleted file mode 100644 index 4cfebbf64..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AbstractContactableEntityFormController.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.AbstractAssetFormController; - -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.assets.ContactEntry; -import org.librecms.assets.ContactEntryKey; -import org.librecms.assets.ContactEntryKeyByLabelComparator; -import org.librecms.assets.ContactEntryKeyRepository; -import org.librecms.assets.ContactableEntity; -import org.librecms.assets.ContactableEntityManager; -import org.librecms.assets.ContactableEntityRepository; -import org.librecms.assets.PostalAddress; -import org.librecms.contentsection.AssetRepository; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - * @param - */ -public abstract class AbstractContactableEntityFormController - extends AbstractAssetFormController { - - protected static final String POSTAL_ADDRESS = "postalAddress"; - - @Inject - private AssetRepository assetRepository; - - @Inject - private ContactableEntityRepository contactableEntityRepository; - - @Inject - private ContactableEntityManager contactableEntityManager; - - @Inject - private ContactEntryKeyRepository keyRepository; - - @Inject - private GlobalizationHelper globalizationHelper; - - @Transactional(Transactional.TxType.REQUIRED) - @Override - protected Map getAssetData(final T asset, - final Locale selectedLocale) { - - final Map data = new HashMap<>(); - - final PostalAddress postalAddress = asset.getPostalAddress(); - if (postalAddress != null) { - data.put(POSTAL_ADDRESS, postalAddress.getObjectId()); - } - - return data; - } - - @Override - public void updateAssetProperties(final T asset, - final Locale selectedLocale, - final Map data) { - - if (data.containsKey(POSTAL_ADDRESS)) { - - final long addressId = (long) data.get(POSTAL_ADDRESS); - final PostalAddress postalAddress = assetRepository - .findById(addressId, PostalAddress.class) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No PostalAddress with ID %d found.", addressId))); - - contactableEntityManager - .addPostalAddressToContactableEntity(postalAddress, asset); - } - } - - /** - * Returns the contact entries of the provided contentable entity for the - * provided language. - * - * @param contactableId The ID of the contactable entity. - * @param selectedLocale The selected locale. - * - * @return An list of the contact entires - */ - @Transactional(Transactional.TxType.REQUIRED) - public List getContactEntries( - final Long contactableId, final Locale selectedLocale) { - - Objects.requireNonNull(contactableId, - "Can't get contact entries from null."); - - final ContactableEntity entity = contactableEntityRepository - .findById(contactableId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContactEntity with ID %d found.", contactableId))); - - return entity - .getContactEntries() - .stream() - .map(contactEntry -> toContactEntryArray(contactEntry, - selectedLocale)) - .collect(Collectors.toList()); - } - - private String[] toContactEntryArray(final ContactEntry entry, - final Locale selectedLocale) { - - final String key = entry.getKey().getEntryKey(); - final String label = entry.getKey().getLabel().getValue(selectedLocale); - final String value = entry.getValue(); - - return new String[]{key, label, value}; - } - - @Transactional(Transactional.TxType.REQUIRED) - public void addContactEntry(final String contactEntryKey, - final String contactEntryValue, - final Long toContactableEntityWithId) { - - final ContactableEntity contactable = contactableEntityRepository - .findById(toContactableEntityWithId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContactableEntity with ID %d found", - toContactableEntityWithId))); - - final ContactEntryKey key = keyRepository - .findByEntryKey(contactEntryKey) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContactEntryKey with key \"%s\" found.", contactEntryKey))); - final ContactEntry entry = new ContactEntry(); - entry.setKey(key); - entry.setValue(contactEntryValue); - entry.setOrder(contactable.getContactEntries().size()); - - contactableEntityManager - .addContactEntryToContactableEntity(entry, contactable); - } - - @Transactional(Transactional.TxType.REQUIRED) - public void removeContactEntry(final int withIndex, - final Long fromContactableEntityWithId) { - - final ContactableEntity contactable = contactableEntityRepository - .findById(fromContactableEntityWithId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContactableEntity with ID %d found", - fromContactableEntityWithId))); - - if (contactable.getContactEntries().size() > withIndex) { - - final ContactEntry contactEntry = contactable - .getContactEntries() - .get(withIndex); - contactableEntityManager.removeContactEntryFromContactableEntity( - contactEntry, contactable - ); - } - } - - @Transactional(Transactional.TxType.REQUIRED) - public List findAvailableContactEntryKeys( - final Locale selectedLocale) { - - return keyRepository - .findAll() - .stream() - .sorted(new ContactEntryKeyByLabelComparator(selectedLocale)) - .map(key -> buildContactEntryKeyArray(key, - selectedLocale)) - .collect(Collectors.toList()); - } - - private String[] buildContactEntryKeyArray( - final ContactEntryKey contactEntryKey, final Locale selectedLocale) { - - final String key = contactEntryKey.getEntryKey(); - final String label = contactEntryKey.getLabel().getValue(selectedLocale); - - return new String[]{key, label}; - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AudioForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AudioForm.java deleted file mode 100644 index 67288af40..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AudioForm.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.cms.ui.assets.AssetSearchWidget; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; -import org.librecms.assets.AudioAsset; -import org.librecms.assets.LegalMetadata; - -import java.util.Map; - -/** - * - * @author Yannick Bülter - * @author Jens Pelzetter - */ -public class AudioForm extends AbstractBinaryAssetForm { - - private AssetSearchWidget assetSearchWidget; - - public AudioForm(final AssetPane assetPane) { - super(assetPane); - } - - @Override - protected void addWidgets() { - - assetSearchWidget = new AssetSearchWidget("legal-metadata", - LegalMetadata.class); - - add(new Label(new GlobalizedMessage( - "cms.ui.assets.audio.legal_metadata.label", - CmsConstants.CMS_BUNDLE - ))); - add(assetSearchWidget); - } - - @Override - protected void initForm(final PageState state, - final Map data) { - - super.initForm(state, data); - - if (data.containsKey(AudioFormController.LEGAL_METADATA_ID)) { - - final Long legalMetadataId = (Long) data - .get(AudioFormController.LEGAL_METADATA_ID); - if (legalMetadataId != null) { - assetSearchWidget.setValue(state, legalMetadataId); - } - } - } - - @Override - protected Class getAssetClass() { - return AudioAsset.class; - } - -// @Override -// protected Asset createAsset(final FormSectionEvent event) -// throws FormProcessException { -// -// final AudioAsset audioAsset = (AudioAsset) super.createAsset(event); -// -// final PageState state = event.getPageState(); -// -// updateData(audioAsset, state); -// -// return audioAsset; -// } -// @Override -// protected void updateAsset(final Asset asset, -// final FormSectionEvent event) -// throws FormProcessException { -// -// super.updateAsset(asset, event); -// -// final PageState state = event.getPageState(); -// -// final AudioAsset audioAsset = (AudioAsset) asset; -// -// updateData(audioAsset, state); -// } - -// protected void updateData(final AudioAsset audioAsset, -// final PageState state) { -// -// final Long legalMetadataId = (Long) assetSearchWidget.getValue(state); -// if (legalMetadataId != null) { -// final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); -// final AssetRepository assetRepo = cdiUtil.findBean( -// AssetRepository.class); -// final LegalMetadata legalMetadata = (LegalMetadata) assetRepo -// .findById(legalMetadataId) -// .orElseThrow(() -> new IllegalArgumentException(String.format( -// "No LegalMetadata asset with ID %d in the database.", -// legalMetadataId))); -// -// audioAsset.setLegalMetadata(legalMetadata); -// } -// } - -// @Override -// protected BinaryAsset createBinaryAsset(final PageState state) { -// return new AudioAsset(); -// } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AudioFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AudioFormController.java deleted file mode 100644 index a7bf6c172..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/AudioFormController.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.IsControllerForAssetType; - -import org.librecms.assets.AudioAsset; -import org.librecms.assets.LegalMetadata; -import org.librecms.contentsection.AssetRepository; -import org.librecms.contentsection.Folder; - -import java.util.Locale; -import java.util.Map; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -@IsControllerForAssetType(AudioAsset.class) -public class AudioFormController extends AbstractBinaryAssetFormController { - - protected static final String LEGAL_METADATA_ID = "legalMetadataId"; - - @Inject - private AssetRepository assetRepository; - - @Override - protected Map getAssetData(final AudioAsset asset, - final Locale selectedLocale) { - - final Map data = super.getAssetData(asset, - selectedLocale); - - final LegalMetadata legalMetadata = asset.getLegalMetadata(); - if (legalMetadata != null) { - data.put(LEGAL_METADATA_ID, legalMetadata.getObjectId()); - } - - return data; - } - - @Override - public void updateAssetProperties(final AudioAsset asset, - final Locale selectedLocale, - final Map data) { - - super.updateAssetProperties(asset, selectedLocale, data); - - if (data.containsKey(LEGAL_METADATA_ID)) { - - final long legalMetadataId = (long) data.get(LEGAL_METADATA_ID); - - final LegalMetadata legalMetadata = assetRepository - .findById(legalMetadataId, LegalMetadata.class) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No LegalMetadata with ID %d found.", legalMetadataId))); - - asset.setLegalMetadata(legalMetadata); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/BookmarkForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/BookmarkForm.java deleted file mode 100644 index 124e89df2..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/BookmarkForm.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.cms.ui.assets.AssetPane; - -import org.librecms.assets.Bookmark; - -import java.util.Collections; -import java.util.Map; - -/** - * - * @author Jens Pelzetter - */ -public class BookmarkForm extends AbstractBookmarkForm { - -// private TextArea description; -// private TextField url; - public BookmarkForm(final AssetPane assetPane) { - super(assetPane); - } - -// @Override -// protected void addWidgets() { -// -// add(new Label( -// new GlobalizedMessage("cms.ui.assets.bookmark.description", -// CmsConstants.CMS_BUNDLE))); -// description = new TextArea("bookmark-description"); -// add(description); -// -// add(new Label(new GlobalizedMessage("cms.ui.assets.bookmark.url", -// CmsConstants.CMS_BUNDLE))); -// url = new TextField("bookmark-url"); -// add(url); -// -// addValidationListener(new FormValidationListener() { -// -// @Override -// public void validate(final FormSectionEvent event) -// throws FormProcessException { -// -// final PageState state = event.getPageState(); -// final FormData data = event.getFormData(); -// -// try { -// new URL((String) url.getValue(state)); -// } catch (MalformedURLException ex) { -// data.addError(new GlobalizedMessage( -// "cms.ui.assets.bookmark.url.malformed", -// CmsConstants.CMS_BUNDLE)); -// } -// } -// -// }); -// -// } -// -// @Override -// protected void initForm(final PageState state, -// final Optional selectedAsset) { -// -// if (selectedAsset.isPresent()) { -// -// if (!(selectedAsset.get() instanceof Bookmark)) { -// throw new IllegalArgumentException(String.format( -// "The provided asset must be an instanceof of class '%s' or " -// + "an subclass but is an instanceof of class '%s'.", -// Bookmark.class.getName(), -// selectedAsset.get().getClass().getName())); -// } -// -// final Bookmark bookmark = selectedAsset.get(); -// -// description.setValue(state, -// bookmark -// .getDescription() -// .getValue(getSelectedLocale(state))); -// url.setValue(state, bookmark.getUrl()); -// -// } -// -// } -// -// @Override -// protected void showLocale(final PageState state) { -// final Optional selectedAsset = getSelectedAsset(state); -// -// if (selectedAsset.isPresent()) { -// if (!(getSelectedAsset(state).get() instanceof Bookmark)) { -// throw new IllegalArgumentException( -// "Selected asset is not a bookmark"); -// } -// -// final Bookmark bookmark = selectedAsset.get(); -// -// description.setValue(state, -// bookmark -// .getDescription() -// .getValue(getSelectedLocale(state))); -// } -// } - @Override - @SuppressWarnings("unchecked") - protected Class getAssetClass() { - return Bookmark.class; - } - -// @Override -// protected Asset createAsset(final FormSectionEvent event) -// throws FormProcessException { -// -// Objects.requireNonNull(event); -// -// final PageState state = event.getPageState(); -// -// final Bookmark bookmark = new Bookmark(); -// -// updateData(bookmark, state); -// -// return bookmark; -// } -// protected void updateData(final Bookmark bookmark, -// final PageState state) { -// bookmark -// .getDescription() -// .addValue(getSelectedLocale(state), -// (String) description.getValue(state)); -// -// bookmark.setUrl((String) url.getValue(state)); -// } -// -// -// @Override -// protected void updateAsset(final Asset asset, -// final FormSectionEvent event) -// throws FormProcessException { -// -// Objects.requireNonNull(asset); -// Objects.requireNonNull(event); -// -// final PageState state = event.getPageState(); -// -// if (!(asset instanceof Bookmark)) { -// throw new IllegalArgumentException(String.format( -// "Provided asset is not an instance of class (or sub class of) " -// + "'%s' but is an instance of class '%s'", -// Bookmark.class.getName(), -// asset.getClass().getName())); -// } -// -// final Bookmark bookmark = (Bookmark) asset; -// -// updateData(bookmark, state); -// } - @Override - protected Map collectData(final FormSectionEvent event) - throws FormProcessException { - - return Collections.emptyMap(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/BookmarkFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/BookmarkFormController.java deleted file mode 100644 index 9e5ff7ac3..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/BookmarkFormController.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.IsControllerForAssetType; - -import org.librecms.assets.Bookmark; - -import javax.enterprise.context.RequestScoped; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -@IsControllerForAssetType(Bookmark.class) -public class BookmarkFormController - extends AbstractBookmarkFormController { - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ExternalAudioAssetForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ExternalAudioAssetForm.java deleted file mode 100644 index 25f931406..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ExternalAudioAssetForm.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.cms.ui.assets.AssetSearchWidget; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; -import org.librecms.assets.ExternalAudioAsset; -import org.librecms.assets.LegalMetadata; - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Jens Pelzetter - * @author Yannick Bülter - */ -public class ExternalAudioAssetForm - extends AbstractBookmarkForm { - - private AssetSearchWidget assetSearchWidget; - - public ExternalAudioAssetForm(final AssetPane assetPane) { - super(assetPane); - } - - @Override - public void addWidgets() { - super.addWidgets(); - - add(new Label(new GlobalizedMessage( - "cms.ui.assets.external_audio_asset.legal_metadata.label", - CmsConstants.CMS_BUNDLE))); - assetSearchWidget = new AssetSearchWidget("legal-metadata", - LegalMetadata.class); - add(assetSearchWidget); - } - - @Override - protected void initForm(final PageState state, - final Map data) { - - super.initForm(state, data); - - final Long selectedAssetId = getSelectedAssetId(state); - - if (selectedAssetId != null) { - - if (data.containsKey( - ExternalAudioAssetFormController.LEGAL_METADATA_ID)) { - - final long legalMetadataId = (long) data - .get(ExternalAudioAssetFormController.LEGAL_METADATA_ID); - - assetSearchWidget.setValue(state, legalMetadataId); - } - } - } - - @Override - protected Class getAssetClass() { - return ExternalAudioAsset.class; - } - - @Override - protected Map collectData(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - final Map data = new HashMap<>(); - if (assetSearchWidget.getValue(state) != null) { - - data.put(ExternalAudioAssetFormController.LEGAL_METADATA_ID, - assetSearchWidget.getValue(state)); - } - - return data; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ExternalAudioAssetFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ExternalAudioAssetFormController.java deleted file mode 100644 index 35efe05df..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ExternalAudioAssetFormController.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.IsControllerForAssetType; - -import org.librecms.assets.ExternalAudioAsset; -import org.librecms.assets.LegalMetadata; -import org.librecms.contentsection.AssetRepository; - -import java.util.Locale; -import java.util.Map; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -@IsControllerForAssetType(ExternalAudioAsset.class) -public class ExternalAudioAssetFormController - extends AbstractBookmarkFormController { - - protected static final String LEGAL_METADATA_ID = "legalMetadataId"; - - @Inject - private AssetRepository assetRepository; - - @Override - protected Map getAssetData(final ExternalAudioAsset asset, - final Locale selectedLocale) { - - final Map data = super.getAssetData(asset, - selectedLocale); - - final LegalMetadata legalMetadata = asset.getLegalMetadata(); - if (legalMetadata != null) { - data.put(LEGAL_METADATA_ID, legalMetadata.getObjectId()); - } - - return data; - } - - @Override - public void updateAssetProperties(final ExternalAudioAsset asset, - final Locale selectedLocale, - final Map data) { - - super.updateAssetProperties(asset, selectedLocale, data); - - if (data.containsKey(LEGAL_METADATA_ID)) { - - final long legalMetadataId = (long) data.get(LEGAL_METADATA_ID); - final LegalMetadata legalMetadata = assetRepository - .findById(legalMetadataId, LegalMetadata.class) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No LegalMetadata with ID %d found.", legalMetadataId))); - - asset.setLegalMetadata(legalMetadata); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ExternalVideoAssetForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ExternalVideoAssetForm.java deleted file mode 100644 index d0760b9ad..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ExternalVideoAssetForm.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.cms.ui.assets.AssetSearchWidget; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; - -import org.librecms.assets.ExternalVideoAsset; -import org.librecms.assets.LegalMetadata; - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Jens Pelzetter - */ -public class ExternalVideoAssetForm - extends AbstractBookmarkForm { - - private AssetSearchWidget assetSearchWidget; - - public ExternalVideoAssetForm(final AssetPane assetPane) { - super(assetPane); - } - - @Override - public void addWidgets() { - super.addWidgets(); - - add(new Label(new GlobalizedMessage( - "cms.ui.assets.external_video_asset.legal_metadata.label", - CmsConstants.CMS_BUNDLE))); - assetSearchWidget = new AssetSearchWidget("legal-metadata", - LegalMetadata.class); - add(assetSearchWidget); - } - - @Override - protected void initForm(final PageState state, - final Map data) { - - super.initForm(state, data); - - final Long selectedAssetId = getSelectedAssetId(state); - if (selectedAssetId != null) { - - if (data.containsKey( - ExternalVideoAssetFormController.LEGAL_METADATA_ID)) { - assetSearchWidget.setValue( - state, - data.get(ExternalVideoAssetFormController.LEGAL_METADATA_ID)); - } - } - } - - @Override - protected Class getAssetClass() { - return ExternalVideoAsset.class; - } - - @Override - protected Map collectData(final FormSectionEvent event) - throws FormProcessException { - - final Map data = new HashMap<>(); - final PageState state = event.getPageState(); - - if (assetSearchWidget.getValue(state) != null) { - data.put(ExternalAudioAssetFormController.LEGAL_METADATA_ID, - assetSearchWidget.getValue(state)); - } - - return data; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ExternalVideoAssetFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ExternalVideoAssetFormController.java deleted file mode 100644 index bd2cc2c8a..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ExternalVideoAssetFormController.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.IsControllerForAssetType; - -import org.librecms.assets.ExternalVideoAsset; -import org.librecms.assets.LegalMetadata; -import org.librecms.contentsection.AssetRepository; - -import java.util.Locale; -import java.util.Map; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -@IsControllerForAssetType(ExternalVideoAsset.class) -public class ExternalVideoAssetFormController - extends AbstractBookmarkFormController { - - protected static final String LEGAL_METADATA_ID = "legalMetadataId"; - - @Inject - private AssetRepository assetRepository; - - @Transactional(Transactional.TxType.REQUIRED) - @Override - protected Map getAssetData(final ExternalVideoAsset asset, - final Locale selectedLocale) { - - final Map data = super.getAssetData(asset, - selectedLocale); - if (asset.getLegalMetadata() != null) { - - data.put(LEGAL_METADATA_ID, asset.getLegalMetadata().getObjectId()); - } - - return data; - } - - @Override - public void updateAssetProperties(final ExternalVideoAsset asset, - final Locale selectedLocale, - final Map data) { - - super.updateAssetProperties(asset, selectedLocale, data); - - if (data.containsKey(LEGAL_METADATA_ID)) { - - final long legalMetadataId = (long) data.get(LEGAL_METADATA_ID); - - final LegalMetadata legalMetadata = assetRepository - .findById(legalMetadataId, LegalMetadata.class) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No LegalMetadata with ID %d found.", legalMetadataId))); - - asset.setLegalMetadata(legalMetadata); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/FileAssetForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/FileAssetForm.java deleted file mode 100644 index bc01566bb..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/FileAssetForm.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.AssetPane; - -import org.librecms.assets.FileAsset; - -/** - * - * @author Jens Pelzetter - */ -public class FileAssetForm extends AbstractBinaryAssetForm { - - public FileAssetForm(final AssetPane assetPane) { - super(assetPane); - } - - @Override - protected Class getAssetClass() { - return FileAsset.class; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/FileAssetFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/FileAssetFormController.java deleted file mode 100644 index 4e7e6ac52..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/FileAssetFormController.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.IsControllerForAssetType; - -import org.librecms.assets.FileAsset; - -import javax.enterprise.context.RequestScoped; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -@IsControllerForAssetType(FileAsset.class) -public class FileAssetFormController extends AbstractBinaryAssetFormController { - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ImageForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ImageForm.java deleted file mode 100644 index 2ff95c29f..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ImageForm.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.cms.ui.assets.AssetSearchWidget; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.assets.Image; -import org.librecms.assets.LegalMetadata; -import org.librecms.contentsection.Asset; -import org.librecms.contentsection.AssetRepository; - -import java.util.Map; - -/** - * - * @author Yannick Bülter - * @author Jens Pelzetter - */ -public class ImageForm extends AbstractBinaryAssetForm { - - private TextField width; - private TextField height; - private AssetSearchWidget assetSearchWidget; - - public ImageForm(final AssetPane assetPane) { - super(assetPane); - } - - @Override - protected void addWidgets() { - - super.addWidgets(); - - width = new TextField("width-text"); - height = new TextField("height-text"); - assetSearchWidget = new AssetSearchWidget("legal-metadata", - LegalMetadata.class); - - add(new Label(new GlobalizedMessage( - "cms.ui.assets.image.width.label", - CmsConstants.CMS_BUNDLE - ))); - add(width); - - add(new Label(new GlobalizedMessage( - "cms.ui.assets.image.height.label", - CmsConstants.CMS_BUNDLE - ))); - add(height); - - add(new Label(new GlobalizedMessage( - "cms.ui.assets.image.legal_metadata.label", - CmsConstants.CMS_BUNDLE - ))); - add(assetSearchWidget); - } - - @Override - protected void initForm(final PageState state, - final Map data) { - - super.initForm(state, data); - - if (getSelectedAssetId(state) != null) { - - if (data.containsKey(ImageFormController.WIDTH)) { - final long widthValue = (long) data - .get(ImageFormController.WIDTH); - width.setValue(state, Long.toString(widthValue)); - } - if (data.containsKey(ImageFormController.HEIGHT)) { - final long heightValue = (long) data - .get(ImageFormController.HEIGHT); - height.setValue(state, Long.toString(heightValue)); - } - - if (data.containsKey(ImageFormController.LEGAL_METADATA_ID)) { - assetSearchWidget - .setValue(state, - data.get(ImageFormController.LEGAL_METADATA_ID)); - } - } - } - - @Override - protected Class getAssetClass() { - return Image.class; - } - - @Override - protected Map collectData(final FormSectionEvent event) - throws FormProcessException { - - final Map data = super.collectData(event); - final PageState state = event.getPageState(); - - data.put(ImageFormController.WIDTH, width.getValue(state)); - data.put(ImageFormController.HEIGHT, height.getValue(state)); - - if (assetSearchWidget.getValue(state) != null) { - data.put(ImageFormController.LEGAL_METADATA_ID, - assetSearchWidget.getValue(state)); - } - - return data; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ImageFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ImageFormController.java deleted file mode 100644 index 7bf33e469..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/ImageFormController.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.IsControllerForAssetType; - -import org.librecms.assets.Image; -import org.librecms.assets.LegalMetadata; -import org.librecms.contentsection.AssetRepository; - -import java.util.Locale; -import java.util.Map; - -import javax.enterprise.context.RequestScoped; - -import javax.inject.Inject; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -@IsControllerForAssetType(Image.class) -public class ImageFormController - extends AbstractBinaryAssetFormController { - - protected static final String LEGAL_METADATA_ID = "legalMetadataId"; - protected static final String HEIGHT = "height"; - protected static final String WIDTH = "width"; - - @Inject - private AssetRepository assetRepository; - - @Override - protected Map getAssetData(final Image asset, - final Locale selectedLocale) { - - final Map data = super.getAssetData(asset, - selectedLocale); - - data.put(WIDTH, asset.getWidth()); - data.put(HEIGHT, asset.getHeight()); - - if (asset.getLegalMetadata() != null) { - data.put(LEGAL_METADATA_ID, - asset.getLegalMetadata().getObjectId()); - } - - return data; - } - - @Override - public void updateAssetProperties(final Image asset, - final Locale selectedLocale, - final Map data) { - - super.updateAssetProperties(asset, selectedLocale, data); - - if (data.containsKey(WIDTH)) { - asset.setWidth((long) data.get(WIDTH)); - } - - if (data.containsKey(HEIGHT)) { - asset.setHeight((long) data.get(HEIGHT)); - } - - if (data.containsKey(LEGAL_METADATA_ID)) { - final long legalMetadataId = (long) data.get(LEGAL_METADATA_ID); - - final LegalMetadata legalMetadata = assetRepository - .findById(legalMetadataId, LegalMetadata.class) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No LegalMetadata with ID %d found.", legalMetadataId))); - - asset.setLegalMetadata(legalMetadata); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/LegalMetadataForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/LegalMetadataForm.java deleted file mode 100644 index 72933c1e4..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/LegalMetadataForm.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.cms.ui.assets.AbstractAssetForm; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; -import org.librecms.assets.LegalMetadata; - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Jens Pelzetter - */ -public class LegalMetadataForm extends AbstractAssetForm { - - private TextArea rightsHolder; - private TextArea rights; - private TextArea publisher; - private TextArea creator; - - public LegalMetadataForm(final AssetPane assetPane) { - super(assetPane); - } - - @Override - protected void addWidgets() { - - final BoxPanel panel = new BoxPanel(BoxPanel.VERTICAL); - - panel.add(new Label(new GlobalizedMessage( - "cms.ui.assets.legalmetadata.rightsholder", - CmsConstants.CMS_BUNDLE))); - rightsHolder = new TextArea("legalmetadata-rightsholder"); - panel.add(rightsHolder); - - panel.add(new Label(new GlobalizedMessage( - "cms.ui.assets.legalmetadata.rights", - CmsConstants.CMS_BUNDLE))); - rights = new TextArea("legalmetadata-rights"); - panel.add(rights); - - panel.add(new Label(new GlobalizedMessage( - "cms.ui.assets.legalmetadata.publisher", - CmsConstants.CMS_BUNDLE))); - publisher = new TextArea("legalmetadata-rights"); - panel.add(publisher); - - panel.add(new Label(new GlobalizedMessage( - "cms.ui.assets.legalmetadata.creator", - CmsConstants.CMS_BUNDLE))); - creator = new TextArea("legalmetadata-creator"); - panel.add(creator); - - add(panel); - } - - @Override - protected void initForm(final PageState state, - final Map data) { - - super.initForm(state, data); - - if (getSelectedAssetId(state) != null) { - - rightsHolder.setValue( - state, - data.get(LegalMetadataFormController.RIGHTS_HOLDER)); - rights.setValue(state, - data.get(LegalMetadataFormController.RIGHTS)); - publisher.setValue(state, - data.get(LegalMetadataFormController.PUBLISHER)); - creator.setValue(state, - data.get(LegalMetadataFormController.CREATOR)); - } - } - - @Override - protected void showLocale(final PageState state) { - - final Long selectedAssetId = getSelectedAssetId(state); - - if (selectedAssetId != null) { - - final Map data = getController() - .getAssetData(selectedAssetId, - LegalMetadata.class, - getSelectedLocale(state)); - - rights.setValue(state, - data.get(LegalMetadataFormController.RIGHTS)); - } - } - - @Override - protected Class getAssetClass() { - return LegalMetadata.class; - } - - @Override - protected Map collectData(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final Map data = new HashMap<>(); - - data.put(LegalMetadataFormController.CREATOR, creator.getValue(state)); - data.put(LegalMetadataFormController.PUBLISHER, - publisher.getValue(state)); - data.put(LegalMetadataFormController.RIGHTS, - rights.getValue(state)); - data.put(LegalMetadataFormController.RIGHTS_HOLDER, - rightsHolder.getValue(state)); - - return data; - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/LegalMetadataFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/LegalMetadataFormController.java deleted file mode 100644 index 402a19fc7..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/LegalMetadataFormController.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.AbstractAssetFormController; -import com.arsdigita.cms.ui.assets.IsControllerForAssetType; - -import org.librecms.assets.LegalMetadata; - -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.enterprise.context.RequestScoped; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -@IsControllerForAssetType(LegalMetadata.class) -public class LegalMetadataFormController - extends AbstractAssetFormController { - - protected static final String CONTRIBUTORS = "contributors"; - protected static final String CREATOR = "creator"; - protected static final String PUBLISHER = "publisher"; - protected static final String RIGHTS = "rights"; - protected static final String RIGHTS_HOLDER = "rightsHolder"; - - @Override - protected Map getAssetData(final LegalMetadata asset, - final Locale selectedLocale) { - - final Map data = new HashMap<>(); - - data.put(RIGHTS_HOLDER, asset.getRightsHolder()); - data.put(RIGHTS, asset.getRights().getValue(selectedLocale)); - data.put(PUBLISHER, asset.getPublisher()); - data.put(CREATOR, asset.getCreator()); - data.put(CONTRIBUTORS, asset.getContributors()); - - return data; - } - - @Override - public void updateAssetProperties(final LegalMetadata asset, - final Locale selectedLocale, - final Map data) { - - if (data.containsKey(RIGHTS_HOLDER)) { - asset.setRightsHolder((String) data.get(RIGHTS_HOLDER)); - } - - if (data.containsKey(RIGHTS)) { - asset.getRights().putValue(selectedLocale, - (String) data.get(RIGHTS)); - } - - if (data.containsKey(PUBLISHER)) { - asset.setPublisher((String) data.get(PUBLISHER)); - } - - if (data.containsKey(CREATOR)) { - asset.setCreator((String) data.get(CREATOR)); - } - - if (data.containsKey(CONTRIBUTORS)) { - @SuppressWarnings("unchecked") - final List contributors = (List) data - .get(CONTRIBUTORS); - asset.setContributors(contributors); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/OrganizationForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/OrganizationForm.java deleted file mode 100644 index f76a33eb7..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/OrganizationForm.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; -import org.librecms.assets.Organization; - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Jens Pelzetter - */ -public class OrganizationForm extends AbstractContactableEntityForm { - - private TextField organizationName; - - public OrganizationForm(final AssetPane assetPane) { - - super(assetPane); - } - - @Override - public void initForm(final PageState state, - final Map data) { - - super.initForm(state, data); - - if (getSelectedAssetId(state) != null) { - - organizationName.setValue( - state, - data.get(OrganizationFormController.ORGANIZATION_NAME)); - } - } - - @Override - protected void addPropertyWidgets() { - - add(new Label( - new GlobalizedMessage("cms.ui.assets.organization.name", - CmsConstants.CMS_BUNDLE))); - organizationName = new TextField("organization-name"); - add(organizationName); - } - - @Override - protected Class getAssetClass() { - - return Organization.class; - } - - @Override - protected void showLocale(final PageState state) { - - // Organization has no localizable fields. - } - - @Override - protected Map collectData(final FormSectionEvent event) { - - final PageState state = event.getPageState(); - - final Map data = super.collectData(event); - data.put(OrganizationFormController.ORGANIZATION_NAME, - organizationName.getValue(state)); - - return data; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/OrganizationFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/OrganizationFormController.java deleted file mode 100644 index 832437182..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/OrganizationFormController.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.IsControllerForAssetType; - -import org.librecms.assets.Organization; - -import java.util.Locale; -import java.util.Map; - -import javax.enterprise.context.RequestScoped; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -@IsControllerForAssetType(Organization.class) -public class OrganizationFormController - extends AbstractContactableEntityFormController { - - protected static final String ORGANIZATION_NAME = "organizationName"; - - @Override - protected Map getAssetData(final Organization asset, - final Locale selectedLocale) { - - final Map data = super.getAssetData(asset, - selectedLocale); - data.put(ORGANIZATION_NAME, asset.getName()); - - return data; - } - - @Override - public void updateAssetProperties(final Organization asset, - final Locale selectedLocale, - final Map data) { - - super.updateAssetProperties(asset, selectedLocale, data); - - if (data.containsKey(ORGANIZATION_NAME)) { - final String organizationName = (String) data.get(ORGANIZATION_NAME); - asset.setName(organizationName); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/PersonForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/PersonForm.java deleted file mode 100644 index 1d928b84e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/PersonForm.java +++ /dev/null @@ -1,323 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.Date; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableColumnModel; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.LockableImpl; - -import org.librecms.assets.Person; - -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import static org.librecms.CmsConstants.*; - -/** - * - * @author Jens Pelzetter - */ -public class PersonForm extends AbstractContactableEntityForm { - - private TextField surnameField; - - private TextField givenNameField; - - private TextField prefixField; - - private TextField suffixField; - - private Submit addPersonNameButton; - - private Date birthdateField; - - public PersonForm(final AssetPane assetPane) { - super(assetPane); - } - - @Override - protected void addPropertyWidgets() { - - final Label surnameLabel = new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.person.surname", - CMS_BUNDLE)); - surnameField = new TextField("surname"); - add(surnameLabel); - add(surnameField); - - final Label givenNameLabel = new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.person.given_name", - CMS_BUNDLE)); - givenNameField = new TextField("givenName"); - add(givenNameLabel); - add(givenNameField); - - final Label prefixLabel = new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.person.prefix", - CMS_BUNDLE - )); - prefixField = new TextField("prefix"); - add(prefixLabel); - add(prefixField); - - final Label suffixLabel = new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.person.suffix", - CMS_BUNDLE - )); - suffixField = new TextField("suffix"); - add(suffixLabel); - add(suffixField); - - add(buildPersonNamesTable()); - - addPersonNameButton = new Submit(new GlobalizedMessage( - "cms.ui.authoring.assets.person.add_name", - CMS_BUNDLE)); - add(addPersonNameButton); - - final Label birthdateLabel = new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.person.birthdate", - CMS_BUNDLE)); - add(birthdateLabel); - birthdateField = new Date("birthdate"); - final LocalDate today = LocalDate.now(ZoneId.systemDefault()); - birthdateField.setYearRange(1930, today.getYear()); - add(birthdateField); - } - - @Override - protected Class getAssetClass() { - return Person.class; - } - - @Override - protected void showLocale(final PageState state) { - - // Nothing - } - - @Override - protected Map collectData(final FormSectionEvent event) { - - final PageState state = event.getPageState(); - - final Map data = new HashMap<>(); - - data.put(PersonFormController.SURNAME, surnameField.getValue(state)); - data.put(PersonFormController.GIVENNAME, - givenNameField.getValue(state)); - data.put(PersonFormController.PREFIX, prefixField.getValue(state)); - data.put(PersonFormController.SUFFIX, suffixField.getValue(state)); - - data.put(PersonFormController.BIRTHDATE, - birthdateField.getValue(state)); - - return data; - } - - @Override - public void initForm(final PageState state, - final Map data) { - - super.initForm(state, data); - - if (data.containsKey(PersonFormController.SURNAME)) { - surnameField.setValue(state, - data.get(PersonFormController.SURNAME)); - } - - if (data.containsKey(PersonFormController.GIVENNAME)) { - givenNameField.setValue(state, - data.get(PersonFormController.GIVENNAME)); - } - - if (data.containsKey(PersonFormController.PREFIX)) { - prefixField.setValue(state, data.get(PersonFormController.PREFIX)); - } - - if (data.containsKey(PersonFormController.SUFFIX)) { - suffixField.setValue(state, data.get(PersonFormController.SUFFIX)); - } - - if (data.containsKey(PersonFormController.BIRTHDATE)) { - birthdateField.setValue(state, - data.get(PersonFormController.BIRTHDATE)); - } - } - - @Override - public void process(final FormSectionEvent event) throws - FormProcessException { - - if (addPersonNameButton.equals(event.getSource())) { - - final PersonFormController controller - = (PersonFormController) getController(); - controller.addPersonName(getSelectedAssetId(event.getPageState())); - - } else { - super.process(event); - } - } - - private Table buildPersonNamesTable() { - - final Table table = new Table() { - - @Override - public boolean isVisible(final PageState state) { - return getSelectedAssetId(state) != null; - } - }; - - final TableColumnModel columnModel = table.getColumnModel(); - columnModel.add(new TableColumn( - 0, - new Label( - new GlobalizedMessage( - "cms.ui.authoring.assets.person.surname", - CMS_BUNDLE - ) - ) - )); - columnModel.add(new TableColumn( - 1, - new Label( - new GlobalizedMessage( - "cms.ui.authoring.assets.person.givenName", - CMS_BUNDLE - ) - ) - )); - columnModel.add(new TableColumn( - 2, - new Label( - new GlobalizedMessage( - "cms.ui.authoring.assets.person.prefix", - CMS_BUNDLE - ) - ) - )); - columnModel.add(new TableColumn( - 3, - new Label( - new GlobalizedMessage( - "cms.ui.authoring.assets.person.suffix", - CMS_BUNDLE - ) - ) - )); - - table.setModelBuilder(new PersonNamesTableModelBuilder()); - - table.setEmptyView(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.person.names.none"))); - - return table; - } - - private class PersonNamesTableModelBuilder - extends LockableImpl - implements TableModelBuilder { - - @Override - public TableModel makeModel(final Table table, final PageState state) { - - final Long selectedPersonId = getSelectedAssetId(state); - if (selectedPersonId == null) { - throw new RuntimeException("No asset selected."); - } - - final PersonFormController controller - = (PersonFormController) getController(); - final List personNames = controller - .getPersonNames(selectedPersonId); - - return new PersonNamesTableModel(personNames); - } - - } - - private class PersonNamesTableModel implements TableModel { - - private final Iterator personNames; - - private String[] currentPersonName; - - private int row; - - public PersonNamesTableModel(final List personNames) { - - this.personNames = Objects - .requireNonNull(personNames, - "Can't create PersonNamesTableModel without a " - + "list of person names.") - .iterator(); - } - - @Override - public int getColumnCount() { - return 4; - } - - @Override - public boolean nextRow() { - - if (personNames.hasNext()) { - currentPersonName = personNames.next(); - row++; - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - - return currentPersonName[columnIndex]; - - } - - @Override - public Object getKeyAt(final int columnIndex) { - - return row; - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/PersonFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/PersonFormController.java deleted file mode 100644 index 07ac21250..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/PersonFormController.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.IsControllerForAssetType; - -import org.librecms.assets.Person; -import org.librecms.assets.PersonManager; -import org.librecms.assets.PersonName; -import org.librecms.assets.PersonRepository; - -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -@IsControllerForAssetType(Person.class) -public class PersonFormController - extends AbstractContactableEntityFormController { - - protected static final String SUFFIX = "suffix"; - - protected static final String PREFIX = "prefix"; - - protected static final String GIVENNAME = "givenName"; - - protected static final String SURNAME = "surname"; - - protected static final String BIRTHDATE = "birthdate"; - - protected static final String PERSON_NAMES = "personNames"; - - protected static final int SURNAME_INDEX = 0; - - protected static final int GIVENNAME_INDEX = 1; - - protected static final int PREFIX_INDEX = 2; - - protected static final int SUFFIX_INDEX = 3; - - @Inject - private PersonRepository personRepository; - - @Inject - private PersonManager personManager; - - @Transactional - @Override - protected Map getAssetData(final Person asset, - final Locale selectedLocale) { - - final Map data = super.getAssetData(asset, - selectedLocale); - - final PersonName personName = asset.getPersonName(); - data.put(SURNAME, personName.getSurname()); - data.put(GIVENNAME, personName.getGivenName()); - data.put(PREFIX, personName.getPrefix()); - data.put(SUFFIX, personName.getSuffix()); - - final List names = asset - .getPersonNames() - .subList(0, asset.getPersonNames().size() - 1) - .stream() - .map(this::convertPersonName) - .collect(Collectors.toList()); - data.put(PERSON_NAMES, names); - - final LocalDate birthdate = asset.getBirthdate(); - if (birthdate != null) { - final Instant instant = birthdate - .atStartOfDay() - .atZone(ZoneId.systemDefault()) - .toInstant(); - final Date birthdateValue = Date.from(instant); - data.put(BIRTHDATE, birthdateValue); - } - - return data; - } - - @Transactional(Transactional.TxType.REQUIRED) - protected List getPersonNames(final Long personId) { - - final Person person = personRepository - .findById(personId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No Person with ID %d found.", personId))); - - return person - .getPersonNames() - .subList(0, person.getPersonNames().size() - 1) - .stream() - .map(this::convertPersonName) - .collect(Collectors.toList()); - } - - private String[] convertPersonName(final PersonName name) { - - final String[] result = new String[4]; - - result[SURNAME_INDEX] = name.getSurname(); - result[GIVENNAME_INDEX] = name.getGivenName(); - result[PREFIX_INDEX] = name.getPrefix(); - result[SUFFIX_INDEX] = name.getSuffix(); - - return result; - } - - @Override - public void updateAssetProperties(final Person asset, - final Locale selectedLocale, - final Map data) { - - super.updateAssetProperties(asset, selectedLocale, data); - - if (data.containsKey(BIRTHDATE)) { - - final Date birthdateValue = (Date) data.get(BIRTHDATE); - final Instant instant = birthdateValue.toInstant(); - final LocalDate birthdate = LocalDateTime - .ofInstant(instant, ZoneId.systemDefault()) - .toLocalDate(); - - asset.setBirthdate(birthdate); - } - - final String surname = (String) data.get(SURNAME); - final String givenName = (String) data.get(GIVENNAME); - final String prefix = (String) data.get(PREFIX); - final String suffix = (String) data.get(SUFFIX); - - if (asset.getPersonName() == null) { - final PersonName personName = new PersonName(); - personName.setGivenName(givenName); - personName.setSuffix(suffix); - personName.setPrefix(prefix); - personName.setSurname(surname); - personManager.addPersonName(asset, personName); - } - } - - @Transactional(Transactional.TxType.REQUIRED) - public void addPersonName(final long personId) { - final Person person = personRepository - .findById(personId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No Person with ID %d found.", personId))); - - personManager.addPersonName(person, new PersonName()); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/PostalAddressForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/PostalAddressForm.java deleted file mode 100644 index 8e0f5fa34..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/PostalAddressForm.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.cms.ui.assets.AbstractAssetForm; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.assets.PostalAddress; - -import java.util.HashMap; -import java.util.Map; - -import static org.librecms.CmsConstants.*; - -/** - * - * @author Jens Pelzetter - */ -public class PostalAddressForm extends AbstractAssetForm { - - private TextArea addressArea; - private TextField postalCodeField; - private TextField cityField; - private TextField stateField; - private TextField isoCountryCodeField; - - public PostalAddressForm(final AssetPane assetPane) { - super(assetPane); - } - - @Override - protected void addWidgets() { - - super.addWidgets(); - - addressArea = new TextArea("address"); - addressArea.setLabel(new GlobalizedMessage( - "cms.ui.authoring.assets.postaladdress.address", CMS_BUNDLE)); - addressArea.setCols(80); - addressArea.setRows(10); - add(addressArea); - - postalCodeField = new TextField("postalCode"); - postalCodeField.setLabel(new GlobalizedMessage( - "cms.ui.authoring.assets.postaladdress.postalcode", CMS_BUNDLE)); - add(postalCodeField); - - cityField = new TextField("city"); - cityField.setLabel(new GlobalizedMessage( - "cms.ui.authoring.assets.postaladdress.city", CMS_BUNDLE)); - add(cityField); - - stateField = new TextField("state"); - stateField.setLabel(new GlobalizedMessage( - "cms.ui.authoring.assets.postaladdress.state", CMS_BUNDLE)); - add(stateField); - } - - @Override - protected Class getAssetClass() { - return PostalAddress.class; - } - - @Override - protected void showLocale(final PageState state) { - // Nothing - } - - @Override - protected Map collectData(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - final Map data = new HashMap<>(); - - data.put(PostalAddressFormController.ADDRESS, - addressArea.getValue(state)); - data.put(PostalAddressFormController.CITY, - cityField.getValue(state)); - data.put(PostalAddressFormController.POSTAL_CODE, - postalCodeField.getValue(state)); - data.put(PostalAddressFormController.STATE, - stateField.getValue(state)); - - return data; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/PostalAddressFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/PostalAddressFormController.java deleted file mode 100644 index 1b0360f0f..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/PostalAddressFormController.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.AbstractAssetFormController; -import com.arsdigita.cms.ui.assets.IsControllerForAssetType; - -import org.librecms.assets.PostalAddress; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import javax.enterprise.context.RequestScoped; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -@IsControllerForAssetType(PostalAddress.class) -public class PostalAddressFormController - extends AbstractAssetFormController { - - protected static final String STATE = "state"; - protected static final String CITY = "city"; - protected static final String POSTAL_CODE = "postalCode"; - protected static final String ADDRESS = "address"; - - @Override - protected Map getAssetData(final PostalAddress asset, - final Locale selectedLocale) { - - final Map data = new HashMap<>(); - - data.put(ADDRESS, asset.getAddress()); - data.put(POSTAL_CODE, asset.getPostalCode()); - data.put(CITY, asset.getCity()); - data.put(STATE, asset.getState()); - - return data; - } - - @Override - public void updateAssetProperties(final PostalAddress asset, - final Locale selectedLocale, - final Map data) { - - if (data.containsKey(ADDRESS)) { - asset.setAddress((String) data.get(ADDRESS)); - } - - if (data.containsKey(POSTAL_CODE)) { - asset.setPostalCode((String) data.get(POSTAL_CODE)); - } - - if (data.containsKey(CITY)) { - asset.setCity((String) data.get(CITY)); - } - - if (data.containsKey(STATE)) { - asset.setState((String) data.get(STATE)); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/RelatedLinkForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/RelatedLinkForm.java deleted file mode 100644 index d589b4a58..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/RelatedLinkForm.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.cms.ui.assets.AbstractAssetForm; -import com.arsdigita.cms.ui.assets.AssetPane; - -import org.librecms.assets.RelatedLink; -import org.librecms.assets.SideNote; - -import java.util.Map; - -/** - * - * @author Jens Pelzetter - */ -public class RelatedLinkForm extends AbstractAssetForm{ - - public RelatedLinkForm(final AssetPane assetPane) { - super(assetPane); - } - - @Override - protected Class getAssetClass() { - return RelatedLink.class; - } - - @Override - protected void showLocale(final PageState state) { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - protected Map collectData(final FormSectionEvent event) throws - FormProcessException { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/SideNoteForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/SideNoteForm.java deleted file mode 100644 index bc5849925..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/SideNoteForm.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.cms.ui.assets.AbstractAssetForm; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; -import org.librecms.assets.SideNote; - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Jens Pelzetter - */ -public class SideNoteForm extends AbstractAssetForm { - - private TextArea text; - - public SideNoteForm(final AssetPane assetPane) { - super(assetPane); - } - - @Override - protected void addWidgets() { - - add(new Label(new GlobalizedMessage("cms.ui.assets.sidenote.text", - CmsConstants.CMS_BUNDLE))); - text = new TextArea("sidenote-text"); - add(text); - } - - @Override - protected void initForm(final PageState state, - final Map data) { - - super.initForm(state, data); - - if (getSelectedAssetId(state) != null) { - - text.setValue(state, data.get(SideNoteFormController.TEXT)); - } - - } - - @Override - protected void showLocale(final PageState state) { - - if (getSelectedAssetId(state) != null) { - - final Long selectedAssetId = getSelectedAssetId(state); - final Map data = getController() - .getAssetData(selectedAssetId, - SideNote.class, - getSelectedLocale(state)); - - text.setValue(state, data.get(SideNoteFormController.TEXT)); - } - } - - @Override - protected Class getAssetClass() { - return SideNote.class; - } - - @Override - protected Map collectData(final FormSectionEvent event) - throws FormProcessException { - - final Map data = new HashMap<>(); - final PageState state = event.getPageState(); - - data.put(SideNoteFormController.TEXT, text.getValue(state)); - - return data; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/SideNoteFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/SideNoteFormController.java deleted file mode 100644 index 01ccd05dc..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/SideNoteFormController.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.AbstractAssetFormController; -import com.arsdigita.cms.ui.assets.IsControllerForAssetType; - -import org.librecms.assets.SideNote; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import javax.enterprise.context.RequestScoped; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -@IsControllerForAssetType(SideNote.class) -public class SideNoteFormController - extends AbstractAssetFormController { - - protected static final String TEXT = "text"; - - @Override - protected Map getAssetData(final SideNote asset, - final Locale selectedLocale) { - - final Map data = new HashMap<>(); - - data.put(TEXT, asset.getText().getValue(selectedLocale)); - - return data; - } - - @Override - public void updateAssetProperties(final SideNote asset, - final Locale selectedLocale, - final Map data) { - - if (data.containsKey(TEXT)) { - - final String value = (String) data.get(TEXT); - asset.getText().putValue(selectedLocale, value); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/VideoForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/VideoForm.java deleted file mode 100644 index 32b320ab6..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/VideoForm.java +++ /dev/null @@ -1,130 +0,0 @@ - /* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.cms.ui.assets.AssetPane; -import com.arsdigita.cms.ui.assets.AssetSearchWidget; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; -import org.librecms.assets.VideoAsset; -import org.librecms.assets.LegalMetadata; - -import java.util.Map; - -/** - * - * @author Yannick Bülter - * @author Jens Pelzetter - * - */ -public class VideoForm extends AbstractBinaryAssetForm { - - private TextField width; - private TextField height; - private AssetSearchWidget assetSearchWidget; - - public VideoForm(final AssetPane assetPane) { - super(assetPane); - } - - @Override - protected void addWidgets() { - - width = new TextField("width-text"); - height = new TextField("height-text"); - assetSearchWidget = new AssetSearchWidget("legal-metadata", - LegalMetadata.class); - - add(new Label(new GlobalizedMessage( - "cms.ui.assets.video.width.label", - CmsConstants.CMS_BUNDLE - ))); - add(width); - - add(new Label(new GlobalizedMessage( - "cms.ui.assets.video.height.label", - CmsConstants.CMS_BUNDLE - ))); - add(height); - - add(new Label(new GlobalizedMessage( - "cms.ui.assets.video.legal_metadata.label", - CmsConstants.CMS_BUNDLE - ))); - add(assetSearchWidget); - } - - @Override - protected void initForm(final PageState state, - final Map data) { - - super.initForm(state, data); - - if (getSelectedAssetId(state) != null) { - - final long widthValue = (long) data.get(VideoFormController.WIDTH); - final long heightValue = (long) data - .get(VideoFormController.HEIGHT); - - width.setValue(state, Long.toString(widthValue)); - height.setValue(state, Long.toString(heightValue)); - - if (data.containsKey(VideoFormController.LEGAL_METADATA_ID)) { - - assetSearchWidget.setValue( - state, - data.containsKey(VideoFormController.LEGAL_METADATA_ID)); - - } - } - } - - @Override - protected Class getAssetClass() { - return VideoAsset.class; - } - - @Override - protected Map collectData(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - final Map data = super.collectData(event); - - data.put(VideoFormController.WIDTH, width.getValue(state)); - data.put(VideoFormController.HEIGHT, height.getValue(state)); - - if (assetSearchWidget.getValue(state) != null) { - - data.put(VideoFormController.LEGAL_METADATA_ID, - assetSearchWidget.getValue(state)); - - } - - return data; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/VideoFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/VideoFormController.java deleted file mode 100644 index f2d4c6c7e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/forms/VideoFormController.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.assets.forms; - -import com.arsdigita.cms.ui.assets.IsControllerForAssetType; - -import org.librecms.contentsection.AssetRepository; - -import java.util.Locale; -import java.util.Map; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; - -import org.librecms.assets.LegalMetadata; -import org.librecms.assets.VideoAsset; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -@IsControllerForAssetType(VideoAsset.class) -public class VideoFormController - extends AbstractBinaryAssetFormController { - - protected static final String LEGAL_METADATA_ID = "legalMetadataId"; - protected static final String HEIGHT = "height"; - protected static final String WIDTH = "width"; - - @Inject - private AssetRepository assetRepository; - - @Override - protected Map getAssetData(final VideoAsset asset, - final Locale selectedLocale) { - - final Map data = super.getAssetData(asset, - selectedLocale); - - data.put(WIDTH, asset.getWidth()); - data.put(HEIGHT, asset.getHeight()); - - if (asset.getLegalMetadata() != null) { - final long legalMetadataId = asset.getLegalMetadata().getObjectId(); - data.put(LEGAL_METADATA_ID, legalMetadataId); - } - - return data; - } - - @Override - public void updateAssetProperties(final VideoAsset asset, - final Locale selectedLocale, - final Map data) { - - super.updateAssetProperties(asset, selectedLocale, data); - - if (data.containsKey(WIDTH)) { - final long width = (long) data.get(WIDTH); - asset.setWidth(width); - } - - if (data.containsKey(HEIGHT)) { - final long height = (long) data.get(HEIGHT); - asset.setHeight(height); - } - - if (data.containsKey(LEGAL_METADATA_ID)) { - - final LegalMetadata legalMetadata = assetRepository - .findById((long) data.get(LEGAL_METADATA_ID), - LegalMetadata.class) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No LegalMetadata with ID %d found", - data.get(LEGAL_METADATA_ID) - ))); - asset.setLegalMetadata(legalMetadata); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/searchpage/AssetSearchPage.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/searchpage/AssetSearchPage.java deleted file mode 100644 index 2ce5e16df..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/searchpage/AssetSearchPage.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.searchpage; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Link; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableColumnModel; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.dispatcher.CMSPage; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.LayoutPanel; -import com.arsdigita.util.LockableImpl; -import java.util.List; -import org.libreccm.cdi.utils.CdiUtil; - -import org.librecms.CmsConstants; - -/** - * Page contains the widgets for selecting an asset. - * - * @author Jens Pelzetter - */ -public class AssetSearchPage extends CMSPage { - - private static final String QUERY_PARAM = "query"; - private static final String WIDGET_PARAM = "widget"; - private static final String ASSET_TYPE_PARAM = "assettype"; - - private static final int RESULTS_TABLE_COL_TITLE = 0; - private static final int RESULTS_TABLE_COL_PLACE = 1; - private static final int RESULTS_TABLE_COL_TYPE = 2; - - private final LongParameter contentSectionId; - - private TextField query; - - public AssetSearchPage() { - super(new Label(new GlobalizedMessage("cms.ui.assets.search_page.title", - CmsConstants.CMS_BUNDLE)), - new SimpleContainer()); - - addGlobalStateParam(new StringParameter(ASSET_TYPE_PARAM)); - addGlobalStateParam(new StringParameter(WIDGET_PARAM)); - addGlobalStateParam(new StringParameter(QUERY_PARAM)); - - contentSectionId = new LongParameter("content-section-id"); - - final LayoutPanel mainPanel = new LayoutPanel(); - - final Form queryForm = new Form("asset-search-page-query-form"); - queryForm.add(new Label(new GlobalizedMessage( - "cms.ui.assets.search_page.query", - CmsConstants.CMS_BUNDLE))); - query = new TextField("asset-search-page-query-form"); - queryForm.add(query); - final Submit querySubmit = new Submit(new GlobalizedMessage( - "cms.ui.assets.search_page.query.submit")); - queryForm.add(querySubmit); - - queryForm.addInitListener(new FormInitListener() { - - @Override - public void init(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - - final String query = (String) data.get(QUERY_PARAM); - - } - - }); - - mainPanel.setLeft(queryForm); - - final Table resultsTable = new Table(); - resultsTable.setEmptyView( - new Label( - new GlobalizedMessage( - "cms.ui.assets.search_page.none", - CmsConstants.CMS_BUNDLE))); - resultsTable.setClassAttr("dataTable"); - - final TableColumnModel columnModel = resultsTable.getColumnModel(); - columnModel.add(new TableColumn( - RESULTS_TABLE_COL_TITLE, - new GlobalizedMessage( - "cms.ui.assets.search_page.results_table.title", - CmsConstants.CMS_BUNDLE))); - columnModel.add(new TableColumn( - RESULTS_TABLE_COL_PLACE, - new GlobalizedMessage( - "cms.ui.assets.search_page.results_table.place", - CmsConstants.CMS_BUNDLE))); - columnModel.add(new TableColumn( - RESULTS_TABLE_COL_TYPE, - new GlobalizedMessage( - "cms.ui.assets.search_page.results_table.type", - CmsConstants.CMS_BUNDLE))); - resultsTable.setModelBuilder(new ResultsTableModelBuilder()); - - mainPanel.setBody(resultsTable); - - } - - private class ResultsTableModelBuilder - extends LockableImpl - implements TableModelBuilder { - - @Override - public TableModel makeModel(final Table table, final PageState state) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AssetSearchPageController controller = cdiUtil - .findBean(AssetSearchPageController.class); - - final List rows = controller - .findAssets((String) query.getValue(state)); - return new ResultsTableModel(rows); - } - - } - - private class TitleCellRenderer - extends LockableImpl - implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - if (value == null) { - return new Text("???"); - } - - final Link link = new Link(new Text(value.toString()), ""); - - return link; - - - } - - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/searchpage/AssetSearchPageController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/searchpage/AssetSearchPageController.java deleted file mode 100644 index e62e8c967..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/searchpage/AssetSearchPageController.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.searchpage; - -import java.util.List; -import java.util.ResourceBundle; -import java.util.stream.Collectors; -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.assets.AssetTypeInfo; -import org.librecms.assets.AssetTypesManager; -import org.librecms.contentsection.Asset; -import org.librecms.contentsection.AssetManager; -import org.librecms.contentsection.AssetRepository; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class AssetSearchPageController { - - @Inject - private AssetRepository assetRepo; - - @Inject - private AssetTypesManager assetTypesManager; - - @Inject - private AssetManager assetManager; - - @Inject - private GlobalizationHelper globalizationHelper; - - @Transactional(Transactional.TxType.REQUIRED) - protected List findAssets(final String title) { - - final List assets = assetRepo.findByTitle(title); - - return assets - .stream() - .map(asset -> createRow(asset)) - .collect(Collectors.toList()); - - } - - private ResultsTableRow createRow(final Asset asset) { - final ResultsTableRow row = new ResultsTableRow(); - - row.setAssetUuid(asset.getUuid()); - row.setTitle(globalizationHelper - .getValueFromLocalizedString(asset.getTitle())); - - final AssetTypeInfo typeInfo = assetTypesManager - .getAssetTypeInfo(asset.getClass()); - final ResourceBundle bundle = ResourceBundle - .getBundle(typeInfo.getLabelBundle(), - globalizationHelper.getNegotiatedLocale()); - row.setType(bundle.getString(typeInfo.getLabelKey())); - - row.setPlace(assetManager.getAssetPath(asset)); - - return row; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/searchpage/ResultsTableModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/searchpage/ResultsTableModel.java deleted file mode 100644 index 85c84d05c..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/searchpage/ResultsTableModel.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.searchpage; - -import com.arsdigita.bebop.table.TableModel; -import java.util.Iterator; -import java.util.List; - -/** - * - * @author Jens Pelzetter - */ -class ResultsTableModel implements TableModel { - - private static final int COL_TITLE = 0; - private static final int COL_PLACE = 1; - private static final int COL_TYPE = 2; - - private final Iterator iterator; - private ResultsTableRow currentRow; - - public ResultsTableModel(final List rows) { - iterator = rows.iterator(); - } - - @Override - public int getColumnCount() { - return 3; - } - - @Override - public boolean nextRow() { - if (iterator.hasNext()) { - currentRow = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - switch(columnIndex) { - case COL_TITLE: - return currentRow.getTitle(); - case COL_PLACE: - return currentRow.getPlace(); - case COL_TYPE: - return currentRow.getType(); - default: - throw new IllegalArgumentException("Illegal column index."); - } - } - - @Override - public Object getKeyAt(final int columnIndex) { - return currentRow.getAssetUuid(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/searchpage/ResultsTableRow.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/searchpage/ResultsTableRow.java deleted file mode 100644 index aaf2292d0..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/assets/searchpage/ResultsTableRow.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.assets.searchpage; - -/** - * - * @author Jens Pelzetter - */ -class ResultsTableRow { - - private String assetUuid; - private String title; - private String place; - private String type; - - public String getAssetUuid() { - return assetUuid; - } - - public void setAssetUuid(final String assetUuid) { - this.assetUuid = assetUuid; - } - - public String getTitle() { - return title; - } - - public void setTitle(final String title) { - this.title = title; - } - - public String getPlace() { - return place; - } - - public void setPlace(final String place) { - this.place = place; - } - - public String getType() { - return type; - } - - public void setType(final String type) { - this.type = type; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/AdditionalDisplayComponent.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/AdditionalDisplayComponent.java deleted file mode 100644 index bef38563b..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/AdditionalDisplayComponent.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2007 Chris Gilbert All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.Component; -import com.arsdigita.cms.ItemSelectionModel; - -/** - * class used for decoupled display components that caters for a callback to - * provide them with a handle on the ItemSelectionModel - * - * @author chris.gilbert@westsussex.gov.uk - * - */ -public interface AdditionalDisplayComponent extends Component { - - public void setItemSelectionModel(ItemSelectionModel model); - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ApplyWorkflowController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ApplyWorkflowController.java deleted file mode 100644 index 0000eccd4..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ApplyWorkflowController.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring; - -import org.libreccm.security.PermissionChecker; -import org.libreccm.workflow.AssignableTask; -import org.libreccm.workflow.AssignableTaskManager; -import org.libreccm.workflow.Workflow; -import org.libreccm.workflow.WorkflowManager; -import org.libreccm.workflow.WorkflowRepository; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionRepository; -import org.librecms.contentsection.ContentType; -import org.librecms.contentsection.ContentTypeRepository; -import org.librecms.contentsection.Folder; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.nio.charset.IllegalCharsetNameException; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class ApplyWorkflowController { - - @Inject - private ContentTypeRepository typeRepo; - - @Inject - private ContentSectionRepository sectionRepo; - - @Inject - private WorkflowRepository templateRepo; - - @Inject - private WorkflowManager workflowManager; - - @Inject - private AssignableTaskManager assignableTaskManager; - - @Inject - private PermissionChecker permissionChecker; - - @Transactional(Transactional.TxType.REQUIRED) - protected Workflow getDefaultWorkflow(final ContentType contentType) { - - Objects.requireNonNull(contentType); - - final ContentType type = typeRepo - .findById(contentType.getObjectId()) - .orElseThrow(() -> new IllegalCharsetNameException(String.format( - "No ContentType with ID %d in the database. Where did that ID come from?", - contentType.getObjectId()))); - - return type.getDefaultWorkflow(); - } - - @Transactional(Transactional.TxType.REQUIRED) - Long getDefaultWorkflowId(final ContentType contentType) { - final Workflow workflowTemplate - = getDefaultWorkflow(contentType); - if (workflowTemplate == null) { - return null; - } else { - return workflowTemplate.getWorkflowId(); - } - } - - @Transactional(Transactional.TxType.REQUIRED) - protected List getWorkflowTemplates( - final ContentSection section) { - - final ContentSection contentSection = sectionRepo - .findById(section.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContentSection with ID %d in the database. " - + "Where did that ID come from?", - section.getObjectId()))); - - return new ArrayList<>(contentSection.getWorkflowTemplates()); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void applyWorkflow(final ContentItem item, - final Folder folder, - final Long workflowTemplateId) { - - Objects.requireNonNull(item); - Objects.requireNonNull(folder); - Objects.requireNonNull(workflowTemplateId); - - final Workflow workflowTemplate; - if (workflowTemplateId == null - && permissionChecker - .isPermitted(ItemPrivileges.APPLY_ALTERNATE_WORKFLOW, folder)) { - - workflowTemplate = templateRepo - .findById(workflowTemplateId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No WorkflowTemplate with ID %d in database. " - + "Where did that ID come from?", - workflowTemplateId))); - } else { - workflowTemplate = item.getContentType().getDefaultWorkflow(); - } - - if (workflowTemplate != null) { - - final Workflow workflow = workflowManager - .createWorkflow(workflowTemplate, item); - workflowManager.start(workflow); - - if (!workflow.getTasks().isEmpty()) { - - if (workflow.getTasks().get(0) instanceof AssignableTask) { - - final AssignableTask task = (AssignableTask) workflow - .getTasks() - .get(0); - assignableTaskManager.lockTask(task); - } - } - - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ApplyWorkflowFormSection.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ApplyWorkflowFormSection.java deleted file mode 100755 index ad1cd176f..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ApplyWorkflowFormSection.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Container; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.FormSection; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.bebop.form.RadioGroup; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.NotNullValidationListener; - -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentType; -import org.librecms.contentsection.Folder; - -import com.arsdigita.cms.ui.workflow.WorkflowsOptionPrintListener; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.libreccm.workflow.Workflow; -import org.librecms.CmsConstants; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.util.List; -import java.util.TooManyListenersException; - -/** - * A FormSection which will allow users with - * SecrityConstants.APPLY_ALTERNATE_WORFLOWS permission to choose a different - * workflow to apply to a new item. - * - * @author Stanislav Freidin (stas@arsdigita.com) - * @author Jens Pelzetter - */ -public class ApplyWorkflowFormSection - extends FormSection - implements FormInitListener { - - private static final Logger LOGGER = LogManager - .getLogger(ApplyWorkflowFormSection.class); - - private RadioGroup radioGroup; - private CreationSelector creationSelector; - private ContentType contentType; - private ApplyWorkflowPrintListener printListener; - - /** - * Construct a new ApplyWorkflowFormSection - */ - public ApplyWorkflowFormSection() { - this(null); - } - - /** - * Construct a new ApplyWorkflowFormSection - * - * @param type - */ - public ApplyWorkflowFormSection(final ContentType type) { - this(type, new ColumnPanel(2, true)); - } - - /** - * Construct a new ApplyWorkflowFormSection - * - * @param type - * @param panel Container to use for this FormSection - */ - public ApplyWorkflowFormSection(final ContentType type, - final Container panel) { - super(panel); - - radioGroup = new RadioGroup(new LongParameter("workflowSelect")); - radioGroup.setClassAttr("vertical"); - contentType = type; - printListener = new ApplyWorkflowPrintListener(); - - try { - // should we filter on WorkflowDefinitions where this user - // is assigned to at least one initial task, or should we - // assume that users with "alternate workflow" permission - // are advanced enough to know what they're doing? - radioGroup.addPrintListener(printListener); - } catch (TooManyListenersException ex) { - LOGGER.error("Too many listeners", ex); - } - - super.add(new Label(new GlobalizedMessage("cms.ui.authoring.workflow", - CmsConstants.CMS_BUNDLE))); - radioGroup.addValidationListener(new NotNullValidationListener() { - - @Override - public void validate(final ParameterEvent event) { - final PageState state = event.getPageState(); - if (!ApplyWorkflowFormSection.this.isVisible(state)) { - return; - } - super.validate(event); - } - - }); - super.add(radioGroup); - super.addInitListener(this); - } - - /** - * Initialises the workflow selection widget to the default workflow for the - * content type. - * - * @param event - * - * @throws com.arsdigita.bebop.FormProcessException - */ - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - - final PageState state = event.getPageState(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ApplyWorkflowController controller = cdiUtil - .findBean(ApplyWorkflowController.class); - final Long workflowTemplateId = controller - .getDefaultWorkflowId(contentType); - if (workflowTemplateId != null) { - radioGroup.setValue(state, workflowTemplateId); - } - } - - /** - * Sets the CreationSelector which should be the same as that of the - * creation component. This cannot be set in the constructor since for most - * creation components, addWidgets() is called via the superclass - * constructor, so this member will not yet be set. - * - * @param creationSelector CreationSelector to use for this FormSection - */ - public void setCreationSelector(final CreationSelector creationSelector) { - this.creationSelector = creationSelector; - } - - /** - * Sets the ContentType for the creation component. - * - * @param contentType ContentType to use for this FormSection - */ - public void setContentType(final ContentType contentType) { - this.contentType = contentType; - } - - /** - * Whether or not this component is visible. The additional visibility - * requirement is that the user must have the - * SecurityConstants.APPLY_ALTERNATE_WORKFLOWS privilege on the parent - * folder. - * - * @param state The PageState - * - * @return - */ - @Override - public boolean isVisible(final PageState state) { - boolean result = false; - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil - .findBean(PermissionChecker.class); - - if (super.isVisible(state) - && permissionChecker - .isPermitted(ItemPrivileges.APPLY_ALTERNATE_WORKFLOW, - creationSelector.getFolder(state))) { - - return !printListener.getCollection(state).isEmpty(); - } - return result; - } - - public Long getSelectedWorkflowTemplateId(final PageState state) { - return (Long) radioGroup.getValue(state); - } - - /** - * Apply the proper initial workflow to the item. If the user has - * SecurityConstants.APPLY_ALTERNATE_WORKFLOWS permission on the parent - * folder and a workflow has been chosen, use this workflow. - * Otherwise use the default workflow for the content type. - * - * @param state The PageState - * @param item The new ContentItem - */ - public void applyWorkflow(final PageState state, final ContentItem item) { - - final Long workflowTemplateId = (Long) radioGroup.getValue(state); - final Folder folder = creationSelector.getFolder(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ApplyWorkflowController controller = cdiUtil - .findBean(ApplyWorkflowController.class); - - if (workflowTemplateId != null) { - controller.applyWorkflow(item, folder, workflowTemplateId); - } - -// final WorkflowTemplate template; -// -// final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); -// final PermissionChecker permissionChecker = cdiUtil -// .findBean(PermissionChecker.class); -// final WorkflowTemplateRepository templateRepo = cdiUtil -// .findBean(WorkflowTemplateRepository.class); -// -// if (flowId != null -// && permissionChecker.isPermitted( -// ItemPrivileges.APPLY_ALTERNATE_WORKFLOW, folder)) { -// template = templateRepo -// .findById(flowId) -// .orElseThrow(() -> new IllegalArgumentException(String.format( -// "No WorkflowTemplate with ID %d in database. " -// + "Where did that ID come from?"))); -// } else { -// template = item.getContentType().getDefaultWorkflow(); -// } -// -// if (template != null) { -// -// final WorkflowManager workflowManager = cdiUtil -// .findBean(WorkflowManager.class); -// -// final Workflow workflow = workflowManager.createWorkflow(template, -// item); -// workflowManager.start(workflow); -// -// if (!workflow.getTasks().isEmpty()) { -// -// if (workflow.getTasks().get(0) instanceof AssignableTask) { -// -// final AssignableTaskManager taskManager = cdiUtil -// .findBean(AssignableTaskManager.class); -// final AssignableTask task = (AssignableTask) workflow -// .getTasks() -// .get(0); -// taskManager.lockTask(task); -// } -// } -// } - } - - private class ApplyWorkflowPrintListener - extends WorkflowsOptionPrintListener { - - @Override - protected ContentSection getContentSection(final PageState state) { - - return creationSelector.getContentSection(state); - } - - @Override - protected List getCollection(final PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ApplyWorkflowController controller = cdiUtil - .findBean(ApplyWorkflowController.class); - - final ContentSection section = creationSelector - .getContentSection(state); - - return controller.getWorkflowTemplates(section); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/AuthoringKitSelector.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/AuthoringKitSelector.java deleted file mode 100755 index 8368b2adf..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/AuthoringKitSelector.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.Component; - -import com.arsdigita.bebop.MapComponentSelectionModel; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.SingleSelectionModel; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.LogManager; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.logging.log4j.Logger; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contenttypes.AuthoringKitInfo; -import org.librecms.contenttypes.ContentTypeInfo; -import org.librecms.contenttypes.ContentTypesManager; - -import java.util.List; -import java.util.Objects; - -/** - * Selects a component based on content type. Helper class for {@link - * com.arsdigita.cms.ui.authoring.WizardSelector}. - * - * @author unknown - * @author Jens Pelzetter - */ -public abstract class AuthoringKitSelector extends SimpleContainer { - - private static final Logger LOGGER = LogManager.getLogger( - AuthoringKitSelector.class); - private final Map components; - private final MapComponentSelectionModel selectionModel; - private final List types; - - /** - * Construct a new AuthoringKitSelector. Load all the possible authoring - * kits from the database and construct components for them. - * - * @param model the {@link ItemSelectionModel} which will supply the - * selector with the id of a content type - * - * @pre itemModel != null - */ - public AuthoringKitSelector(final SingleSelectionModel model) { - super(); - - components = new HashMap<>(); - selectionModel = new MapComponentSelectionModel<>(model, components); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentTypesManager typesManager = cdiUtil.findBean( - ContentTypesManager.class); - types = typesManager.getAvailableContentTypes(); - - if (types.isEmpty()) { - throw new RuntimeException("No Content Types were found."); - } - } - - // Overloaded add methods - @Override - public void add(final Component component) { - throw new UnsupportedOperationException(); - } - - // Overloaded add methods - @Override - public void add(final Component component, final int constraints) { - throw new UnsupportedOperationException(); - } - - /** - * Instantiate all the authoring kit wizards. The child class should call - * this method after it is done with initialisation. - */ - protected void processKit() { - for (final ContentTypeInfo type : types) { - final AuthoringKitInfo kit = type.getAuthoringKit(); - if (kit != null) { - final Component component = instantiateKitComponent(kit, type); - if (component != null) { - super.add(component); - components.put(type.getContentItemClass().getName(), - component); - LOGGER.info("Added component {} for {}", - Objects.toString(component), - type.getContentItemClass().getName()); - } - } - } - } - - /** - * Instantiate an authoring kit component. Child classes should override - * this to do the right thing. It is permissible for this method to return - * null. - * - * @param kit for this kit - * @param type for this type - * - * @return - */ - protected abstract Component instantiateKitComponent( - final AuthoringKitInfo kit, final ContentTypeInfo type); - - /** - * - * @param typeClass - * - * @return The component the given type id - */ - public Component getComponent(final String typeClass) { - return components.get(typeClass); - } - - /** - * @return The selection model used by this wizard - */ - public MapComponentSelectionModel getComponentSelectionModel() { - return selectionModel; - } - - // Choose the right component and run it - @Override - public void generateXML(final PageState state, final Element parent) { - if (isVisible(state)) { - final Component component = selectionModel.getComponent(state); - if (component == null) { - throw new IllegalStateException("No component for " - + selectionModel - .getSelectedKey(state)); - } - component.generateXML(state, parent); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/AuthoringKitWizard.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/AuthoringKitWizard.java deleted file mode 100755 index d94bc038c..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/AuthoringKitWizard.java +++ /dev/null @@ -1,595 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.GridPanel; -import com.arsdigita.bebop.List; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.ChangeEvent; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.list.ListCellRenderer; -import com.arsdigita.bebop.parameters.StringParameter; - -import org.librecms.contentsection.ContentType; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.ContentItemPage; -import com.arsdigita.cms.ui.item.ItemWorkflowRequestLocal; -import com.arsdigita.cms.ui.workflow.AssignedTaskSection; -import com.arsdigita.cms.ui.workflow.AssignedTaskTable; -import com.arsdigita.cms.ui.workflow.TaskFinishForm; -import com.arsdigita.cms.ui.workflow.TaskRequestLocal; -import com.arsdigita.cms.ui.workflow.WorkflowRequestLocal; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.LayoutPanel; -import com.arsdigita.toolbox.ui.ModalPanel; -import com.arsdigita.toolbox.ui.Section; -import com.arsdigita.util.Assert; -import com.arsdigita.util.SequentialMap; -import com.arsdigita.util.UncheckedWrapperException; - -import org.apache.logging.log4j.Logger; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.Iterator; -import java.util.Objects; -import java.util.ResourceBundle; - -import org.apache.logging.log4j.LogManager; -import org.librecms.CMSConfig; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.l10n.GlobalizationHelper; -import org.libreccm.workflow.Task; -import org.libreccm.workflow.TaskRepository; -import org.librecms.CmsConstants; -import org.librecms.contenttypes.AuthoringKit; -import org.librecms.contenttypes.AuthoringKitInfo; -import org.librecms.contenttypes.AuthoringStepInfo; -import org.librecms.contenttypes.ContentTypeInfo; -import org.librecms.ui.authoring.ContentItemAuthoringStepInfo; -import org.librecms.ui.authoring.ContentItemAuthoringStepManager; - -/** - * This class represents a single authoring kit. The wizard accepts a - * {@link ContentType} in the constructor; it then extracts the - * {@link AuthoringKit} for the content type, and creates the components for all - * the steps in the kit. - * - * Note that the individual authoring kit steps must provide the following - * constructor: - * - *

- * public TheClass(ItemSelectionModel model, AuthoringKitWizard parent) { ... }
- * 
- * - * This constructor will be called when the component is automatically - * instantiated by the AuthoringKitWizard. - * - */ -public class AuthoringKitWizard extends LayoutPanel implements Resettable { - - /** - * Private Logger instance for this class - */ - private static final Logger LOGGER = LogManager - .getLogger(AuthoringKitWizard.class); - - private final static Class[] ARGUMENTS = new Class[]{ - ItemSelectionModel.class, - AuthoringKitWizard.class, - StringParameter.class - }; - private static final Class[] USER_DEFINED_ARGS = new Class[]{ - ItemSelectionModel.class, - AuthoringKitWizard.class, - ContentType.class - }; - - private final Object[] values; - private final ContentTypeInfo typeInfo; - private final AuthoringKitInfo kitInfo; - private final ItemSelectionModel selectionModel; - private final WorkflowRequestLocal workflowRequestLocal; - private final AssignedTaskTable assignedTaskTable; - private final SequentialMap labels; - private final List list; - private String defaultKey; - private final GridPanel leftPanel; - private final ModalPanel bodyPanel; - private final SimpleContainer stepsContainer; - private final TaskFinishForm taskFinishForm; - - private final StringParameter selectedLanguageParam; - - /** - * The name of the state parameter that determines whether the wizard is in - * item creation mode or item editing mode. - */ - public static final String IS_EDITING = "is_edit"; - /** - * The key for the item creation step. - */ - public static final String CREATION = "_creation_"; - - private final static String SEC_PAGE_EDIT_DYN - = "com.arsdigita.cms.ui.authoring.SecondaryPageEditDynamic"; - private final static String PAGE_EDIT_DYN - = "com.arsdigita.cms.ui.authoring.PageEditDynamic"; - - /** - * Construct a new AuthoringKitWizard. Add all the steps in the authoring - * kit to the wizard. - * - * @param typeInfo The content type of the items that this wizard will - * handle - * @param selectionModel - */ - public AuthoringKitWizard(final ContentTypeInfo typeInfo, - final ItemSelectionModel selectionModel) { - LOGGER.debug("Authoring kit wizard for type {} undergoing creation...", - Objects.toString(typeInfo)); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ConfigurationManager confManager = cdiUtil.findBean( - ConfigurationManager.class); - - selectedLanguageParam = new StringParameter( - ContentItemPage.SELECTED_LANGUAGE); - final GlobalizationHelper globalizationHelper = cdiUtil - .findBean(GlobalizationHelper.class); - selectedLanguageParam.setDefaultValue(globalizationHelper - .getNegotiatedLocale() - .toString()); - - this.typeInfo = typeInfo; - kitInfo = typeInfo.getAuthoringKit(); - this.selectionModel = selectionModel; - values = new Object[]{selectionModel, this, selectedLanguageParam}; - workflowRequestLocal = new ItemWorkflowRequestLocal(); - labels = new SequentialMap(); - - leftPanel = new GridPanel(1); - setLeft(leftPanel); - - assignedTaskTable = new AssignedTaskTable(workflowRequestLocal); - - leftPanel.add(new AssignedTaskSection(workflowRequestLocal, - assignedTaskTable)); - - final Section stepSection = new Section( - new GlobalizedMessage("cms.ui.authoring.steps", - CmsConstants.CMS_BUNDLE)); - leftPanel.add(stepSection); - - list = new List(); - stepSection.setBody(list); - - list.setListData(labels); - list.setCellRenderer(new ListCellRenderer() { - - @Override - public Component getComponent(final List list, - final PageState state, - final Object value, - final String key, - final int index, - final boolean isSelected) { - final Label label; - if (value instanceof GlobalizedMessage) { - label = new Label((GlobalizedMessage) value); - } else { - label = new Label((String) value); - } - if (isSelected) { - label.setFontWeight(Label.BOLD); - return label; - } - return new ControlLink(label); - } - - }); - - bodyPanel = new ModalPanel(); - setBody(bodyPanel); - - stepsContainer = new SimpleContainer(); - bodyPanel.add(stepsContainer); - bodyPanel.setDefault(stepsContainer); - - final java.util.List steps = kitInfo. - getAuthoringSteps(); - - if (Assert.isEnabled()) { - Assert.isTrue(!steps.isEmpty(), - String.format("The authoring kit for content type " - + "s\"%s\" has no steps.", - typeInfo.getContentItemClass().getName())); - } - - final CMSConfig cmsConfig = confManager.findConfiguration( - CMSConfig.class); - - StepComponent panel = null; - for (final AuthoringStepInfo step : steps) { - final String key = step.getComponent().getName(); - - if (defaultKey == null) { - defaultKey = key; - } - - /** - * The "label" and "description" are only here for backwards - * compatibility - */ - final ResourceBundle labelBundle = ResourceBundle - .getBundle(step.getLabelBundle()); - final ResourceBundle descBundle = ResourceBundle - .getBundle(step.getDescriptionBundle()); - final String labelKey = step.getLabelKey(); - final String label = labelBundle.getString(labelKey); - final String descriptionKey = step.getDescriptionKey(); - - final Class componentClass = step. - getComponent(); - final String compClassName = componentClass.getName(); - - if (panel != null) { - panel.setNextStepKey(key); - } - panel = new StepComponent(compClassName); - stepsContainer.add(panel); - final Component component; - - if (compClassName.equals(SEC_PAGE_EDIT_DYN) - || compClassName.equals(PAGE_EDIT_DYN)) { - component = instantiateUserDefinedStep(compClassName, typeInfo); - } else { - component = instantiateStep(compClassName); - } - panel.add(component); - if (component instanceof AuthoringStepComponent) { - ((AuthoringStepComponent) component).addCompletionListener( - new StepCompletionListener()); - } - - final GlobalizedMessage gzLabel; - if (labelKey != null) { - if (step.getLabelBundle() == null) { - gzLabel = new GlobalizedMessage(labelKey, - CmsConstants.CMS_BUNDLE); - } else { - gzLabel = new GlobalizedMessage(labelKey, - step.getLabelBundle()); - } - } else { - gzLabel = null; - } - if (gzLabel == null) { - labels.put(key, label); - } else { - labels.put(key, gzLabel); - } - } - - final java.util.List skipSteps = cmsConfig.getSkipAssetSteps(); - if (LOGGER.isDebugEnabled()) { - for (final String step : skipSteps) { - LOGGER.debug("skip step \"{}\"...", step); - } - } - - for (final ContentItemAuthoringStepInfo stepInfo - : getContentItemAuthoringSteps()) { - - if (panel != null) { - panel.setNextStepKey(stepInfo.getStep()); - } - - panel = new StepComponent(stepInfo.getStep()); - stepsContainer.add(panel); - - final Component component = instantiateStep(stepInfo - .getStep().getName()); - if (component instanceof AuthoringStepComponent) { - ((AuthoringStepComponent) component) - .addCompletionListener(new StepCompletionListener()); - } - panel.add(component); - - labels.put(stepInfo.getStep(), - new GlobalizedMessage(stepInfo.getLabelKey(), - stepInfo.getLabelBundle())); - } - - list.addChangeListener(new StepListener()); - - taskFinishForm = new TaskFinishForm(new TaskSelectionRequestLocal()); - bodyPanel.add(taskFinishForm); - - bodyPanel.connect(assignedTaskTable, 2, taskFinishForm); - bodyPanel.connect(taskFinishForm); - - taskFinishForm - .addProcessListener( - event -> assignedTaskTable - .getRowSelectionModel() - .clearSelection(event.getPageState()) - ); - } - - private final class StepListener implements ChangeListener { - - @Override - public final void stateChanged(final ChangeEvent event) { - final PageState state = event.getPageState(); - final String key = list.getSelectedKey(state).toString(); - - final Iterator iter = stepsContainer.children(); - - while (iter.hasNext()) { - final StepComponent step = (StepComponent) iter.next(); - - if (step.getStepKey().toString().equals(key)) { - step.setVisible(state, true); - } else { - step.setVisible(state, false); - } - } - } - - } - - /** - * - */ - private final class StepCompletionListener implements ActionListener { - - @Override - @SuppressWarnings("unchecked") - public final void actionPerformed(final ActionEvent event) { - final PageState state = event.getPageState(); - if (ContentItemPage.isStreamlinedCreationActive(state)) { - final String key = list.getSelectedKey(state).toString(); - - final Iterator iter = stepsContainer.children(); - - while (iter.hasNext()) { - final StepComponent step = (StepComponent) iter.next(); - if (step.getStepKey().toString().equals(key)) { - Object nextStep = step.getNextStepKey(); - if (nextStep != null) { - list - .getSelectionModel() - .setSelectedKey(state, nextStep.toString()); - } - } - } - } - } - - } - - @Override - public final void register(final Page page) { - super.register(page); - - final Iterator iter = stepsContainer.children(); - - while (iter.hasNext()) { - final StepComponent child = (StepComponent) iter.next(); - - page.setVisibleDefault(child, false); - } - - page.addGlobalStateParam(selectedLanguageParam); - - page.addActionListener(new ActionListener() { - - @Override - public final void actionPerformed(final ActionEvent event) { - final PageState state = event.getPageState(); - - if (state.isVisibleOnPage(AuthoringKitWizard.this)) { - @SuppressWarnings("unchecked") - final SingleSelectionModel model = list - .getSelectionModel(); - - if (!model.isSelected(state)) { - model.setSelectedKey(state, defaultKey); - } - } - } - - }); - } - - private java.util.List getContentItemAuthoringSteps() { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemAuthoringStepManager manager = cdiUtil - .findBean(ContentItemAuthoringStepManager.class); - - return manager.getContentItemAuthoringStepInfos(); - } - - /** - * @return The content type handled by this wizard - */ - public ContentTypeInfo getContentType() { - return typeInfo; - } - - public List getList() { - return list; - } - - /** - * @return The authoring kit which is represented by this wizard - */ - public AuthoringKitInfo getAuthoringKit() { - return kitInfo; - } - - /** - * @return The ItemSelectionModel used by the steps in this wizard - */ - public ItemSelectionModel getItemSelectionModel() { - return selectionModel; - } - - /** - * Instantiate the specified authoring kit step. Will throw a - * RuntimeException on failure. - * - * @param className The Java class name of the step - * - * @return The instance of the component. - */ - protected Component instantiateStep(final String className) { - - LOGGER.debug("Instantiating kit wizard \"{}\" with arguments {}...", - className, - ARGUMENTS); - - try { - // Get the creation component - final Class createClass = Class.forName(className); - final Constructor constr = createClass.getConstructor(ARGUMENTS); - final Component component = (Component) constr.newInstance(values); - - return component; - } catch (ClassNotFoundException - | IllegalAccessException - | IllegalArgumentException - | InstantiationException - | InvocationTargetException - | NoSuchMethodException - | SecurityException ex) { - LOGGER.error( - "Failed to instantiate authoring kit component \"{}\"...", - className); - LOGGER.error("Exception is: ", ex); - throw new UncheckedWrapperException(String.format( - "Failed to instantiate authoring kit component \"%s\".", - className), - ex); - } - } - - /** - * Instantiate the specified authoring kit step for a user defined content - * type. Will throw a RuntimeException on failure. - * - * @param className The Java class name of the step - * @param originatingType - * - * @return - */ - protected Component instantiateUserDefinedStep( - final String className, final ContentTypeInfo originatingType) { - - try { - // Get the creation component - final Class createClass = Class.forName(className); - final Constructor constr = createClass.getConstructor( - USER_DEFINED_ARGS); - final Object[] userDefinedVals = new Object[]{selectionModel, - this, - originatingType}; - final Component component = (Component) constr.newInstance( - userDefinedVals); - - return component; - } catch (ClassNotFoundException - | NoSuchMethodException - | InstantiationException - | IllegalAccessException - | InvocationTargetException ex) { - throw new UncheckedWrapperException(ex); - } - } - - /** - * Reset the state of this wizard - */ - @Override - public final void reset(final PageState state) { - list.setSelectedKey(state, defaultKey); - } - - private final class StepComponent extends SimpleContainer { - - private final Object key; - private Object nextKey; - - public StepComponent(final Object key) { - this.key = key; - } - - public Object getStepKey() { - return key; - } - - public Object getNextStepKey() { - return nextKey; - } - - public void setNextStepKey(final Object nextKey) { - this.nextKey = nextKey; - } - - } - - private final class TaskSelectionRequestLocal extends TaskRequestLocal { - - @Override - protected final Object initialValue(final PageState state) { - final String key = assignedTaskTable - .getRowSelectionModel() - .getSelectedKey(state) - .toString(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final TaskRepository taskRepo = cdiUtil - .findBean(TaskRepository.class); - - final Task task = taskRepo - .findById(Long.parseLong(key)) - .orElseThrow(() -> new UnexpectedErrorException(String - .format("No Task with ID %s in the database.", - key))); - - return task; - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/AuthoringStepComponent.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/AuthoringStepComponent.java deleted file mode 100755 index 12e4ed642..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/AuthoringStepComponent.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.event.ActionListener; - -/** - * Interface which authoring step components should implement. It's - * currently an optional interface. - * - * @author Scott Seago (sseago@redhat.com) - */ -public interface AuthoringStepComponent { - - /** - * Add a completion listener to this component - */ - void addCompletionListener(ActionListener listener); - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/BasicItemForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/BasicItemForm.java deleted file mode 100755 index 017470a22..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/BasicItemForm.java +++ /dev/null @@ -1,429 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.FormSection; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.form.Hidden; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.parameters.TrimmedStringParameter; -import com.arsdigita.bebop.parameters.URLTokenValidationListener; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.web.Web; -import com.arsdigita.xml.Element; - -import org.libreccm.categorization.Category; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemRepository; - -import java.util.Objects; - -/** - * A form for editing subclasses of ContentItem. This is just a convenience - * class. - * - * @author Stanislav Freidin - * @author Jens Pelzetter - */ -public abstract class BasicItemForm extends FormSection - implements FormInitListener, - FormProcessListener, - FormValidationListener { - - public static final String CONTENT_ITEM_ID = "ContentItemId"; - public static final String NAME = "ContentItemName"; - public static final String TITLE = "ContentPageTitle"; - public static final String LANGUAGE = "ContentItemLanguage"; - - private final ItemSelectionModel itemSelectionModel; - private final StringParameter selectedLanguageParam; - - private SaveCancelSection saveCancelSection; - private final FormSection widgetSection; - /** - * Currently, to insert JavaScript code the Label Widget is "abused". - */ - private final Label script = new Label(String - .format("", - Web.getWebappContextPath()), - false); - - /** - * Construct a new BasicItemForm with 2 ColumnPanels and add basic content. - * The left Panel is used for Labels, the right Panel for values. - * - * @param formName the name of this form - * @param itemSelectionModel The {@link ItemSelectionModel} which will be - * responsible for loading the current item - * @param selectedLanguageParam - */ - public BasicItemForm(final String formName, - final ItemSelectionModel itemSelectionModel, - final StringParameter selectedLanguageParam) { - - super(new ColumnPanel(2)); - - Objects.requireNonNull(selectedLanguageParam); - - widgetSection = new FormSection(new ColumnPanel(2, true)); - - super.add(widgetSection, ColumnPanel.INSERT); - this.itemSelectionModel = itemSelectionModel; - this.selectedLanguageParam = selectedLanguageParam; - - /* Prepare Panel design */ - final ColumnPanel panel = (ColumnPanel) getPanel(); - panel.setBorder(false); - panel.setPadColor("#FFFFFF"); - panel.setColumnWidth(1, "20%"); - panel.setColumnWidth(2, "80%"); - panel.setWidth("100%"); - - /* Add basic contents */ - addWidgets(); - - saveCancelSection = new SaveCancelSection(); - super.add(saveCancelSection, - ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - - addInitListener(this); - addProcessListener(this); - addValidationListener(this); - } - - /** - * Construct a new BasicItemForm with a specified number of ColumnPanels and - * without any content. - * - * @param formName the name of this form - * @param columnPanel the column panel of the form - * @param itemSelectionModel The {@link ItemSelectionModel} which will be - * responsible for loading the current item - * @param selectedLanguageParam - */ - public BasicItemForm(final String formName, - final ColumnPanel columnPanel, - final ItemSelectionModel itemSelectionModel, - final StringParameter selectedLanguageParam) { - - super(columnPanel); - - Objects.requireNonNull(selectedLanguageParam); - - widgetSection = new FormSection(new ColumnPanel(columnPanel. - getNumCols(), - true)); - super.add(widgetSection, ColumnPanel.INSERT); - this.itemSelectionModel = itemSelectionModel; - this.selectedLanguageParam = selectedLanguageParam; - } - - /** - * create and add the save/cancel section for this form - */ - public void addSaveCancelSection() { - saveCancelSection = new SaveCancelSection(); - super.add(saveCancelSection, - ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - } - - /** - * Add basic widgets to the form. - * - * Widgets added are 'title' and 'name (url)' which are part of any content - * item. Child classes will override this method to perform all their - * widget-adding needs but are supposed to use super() to add the basic - * widgets. - */ - protected void addWidgets() { - //add(new FormErrorDisplay(this), ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - - final Hidden id = new Hidden(CONTENT_ITEM_ID); - add(id); - - // JavaScript auto-name generation is off by default. - // It is turned on under the following circumstances - // - // * If the name is null, upon starting edit of the title - // * If the name is null, upon finishing edit of name - // - // The rationale is that, auto-name generation is useful - // if the name is currently null, but once a name has been - // created you don't want to subsequently change it since - // it breaks URLs & potentially overwrites the user's - // customizations. - final TextField titleWidget = new TextField(new TrimmedStringParameter( - TITLE)); - titleWidget.setLabel(getTitleLabel()); - titleWidget.setHint(getTitleHint()); - titleWidget.addValidationListener(new NotNullValidationListener()); - titleWidget.setOnFocus("if (this.form." + NAME + ".value == '') { " - + " defaulting = true; this.form." + NAME - + ".value = urlize(this.value); }"); - titleWidget.setOnKeyUp( - "if (defaulting) { this.form." + NAME - + ".value = urlize(this.value) }"); - add(titleWidget); - - // For some content types it may be useful to change the label of - // the name (or URL) field to something different than 'name (url)'. - // This can now be accomplished by overwriting the getNameLabel() method. - // (jensp 2011-01-28) -// add(new Label(getNameLabel())); - final TextField nameWidget = new TextField(new TrimmedStringParameter( - NAME)); - nameWidget.setLabel(getNameLabel()); - nameWidget.setHint(getNameHint()); - // We just check parameter specific properties here! Additionally, - // context properties as uniqueness in folder must be validated - // for the form es the whole (using the validate method required by - // implementing FormValidationListener in this form. - nameWidget.addValidationListener(new NotNullValidationListener()); - nameWidget.addValidationListener(new URLTokenValidationListener()); - nameWidget.setMaxLength(190); - nameWidget.setOnFocus("defaulting = false"); - nameWidget.setOnBlur( - "if (this.value == '') " - + "{ defaulting = true; this.value = urlize(this.form." - + TITLE - + ".value) } " - + " else { this.value = urlize(this.value); }"); - add(nameWidget); - - } - - @Override - public void generateXML(final PageState state, - final Element parent) { - script.generateXML(state, parent); - super.generateXML(state, parent); - } - - /** - * @return the item selection model used in this form - */ - public ItemSelectionModel getItemSelectionModel() { - return itemSelectionModel; - } - - /** - * @return the save/cancel section for this form - */ - public SaveCancelSection getSaveCancelSection() { - return saveCancelSection; - } - - /** - * Perform form initialisation. Children should override this this method to - * pre-fill the widgets with data, instantiate the content item, etc. - * - * @param event - * - * @throws FormProcessException - */ - @Override - public abstract void init(final FormSectionEvent event) throws FormProcessException; - - /** - * Process the form. Children have to override this method to save the - * user's changes to the database. - * - * @param event - * - * @throws FormProcessException - */ - @Override - public abstract void process(final FormSectionEvent event) throws FormProcessException; - - /** - * Validate the form. Children have to override this method to provide - * context form validation, specifically name (url) uniqueness in a folder! - * - * @param event - * - * @throws com.arsdigita.bebop.FormProcessException - */ - @Override - public void validate(final FormSectionEvent event) throws FormProcessException { - // do nothing - } - - /** - * Adds a component to this container. - * - * @param component the component to add to this BasicPageForm - * - */ - @Override - public void add(final Component component) { - widgetSection.add(component); - } - - /** - * Adds a component with the specified layout constraints to this container. - * Layout constraints are defined in each layout container as static ints. - * Use a bitwise OR to specify multiple constraints. - * - * @param component the component to add to this container - * @param constraints layout constraints (a bitwise OR of static ints in the - * particular layout) - */ - @Override - public void add(final Component component, - final int constraints) { - widgetSection.add(component, constraints); - } - - /** - * This method can be overridden to change the label of the title field. To - * change to label of the title field can be useful for some content types. - * For example, for an organisation the label "Title" for the field may be - * confusing for the normal user. For such a content type, the label would - * be changed to something like "Name of the organisation". - * - * @return (Content for the) Label for the title field as string - */ - protected GlobalizedMessage getTitleLabel() { - return new GlobalizedMessage("cms.contenttypes.ui.title", - CmsConstants.CMS_BUNDLE); - } - - /** - * Provides the text for the user hint providing some detailed information - * how to use this widget. This method can be overwritten to adjust the text - * for some content types. {@link #getTitleLabel()} - * - * @return - */ - protected GlobalizedMessage getTitleHint() { - return new GlobalizedMessage("cms.contenttypes.ui.title_hint", - CmsConstants.CMS_BUNDLE); - } - - /** - * This method does the same as {@link #getTitleLabel() } for the labe l of - * the name (URL) field. - * - * @return (Content for the) Label for the name field as string - */ - protected GlobalizedMessage getNameLabel() { - return new GlobalizedMessage("cms.contenttypes.ui.name", - CmsConstants.CMS_BUNDLE); - } - - /** - * Provides the text for the user hint providing some detailed information - * how to use this widget. This method can be overwritten to adjust the text - * for some content types. {@link #getNameLabel()} - * - * @return - */ - protected GlobalizedMessage getNameHint() { - return new GlobalizedMessage("cms.contenttypes.ui.name_hint", - CmsConstants.CMS_BUNDLE); - } - - // ////////////////////////////////////////////////////////////////////// - // - // VALIDATION helper methods - // - // ////////////////////////////////////////////////////////////////////// - /** - * Ensure that the name of an item is unique within a folder. A "New item" - * form should call this method in the validation listener. - * - * @param parent the folder in which to check - * @param event the {@link FormSectionEvent} which was passed to the - * validation listener - */ - public void validateNameUniqueness(final Category parent, - final FormSectionEvent event) { - - final FormData data = event.getFormData(); - final String newName = (String) data.get(NAME); - - validateNameUniqueness(parent, event, newName); - } - - /** - * - * @param parent - * @param event - * @param newName - */ - public void validateNameUniqueness(final Category parent, - final FormSectionEvent event, - final String newName) { - - final String ERR_MSG = "cms.ui.authoring.an_item_with_this_name_exists"; - - if (newName != null) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil - .findBean(ContentItemRepository.class); - - final long result = itemRepo.countByNameInFolder(parent, newName); - - if (result > 0) { - // Try to get a currently selected content item - final ContentItem item; - if (getItemSelectionModel() == null) { - item = null; - } else { - item = getItemSelectionModel() - .getSelectedObject(event.getPageState()); - } - if (item == null) { // The content item being null - // means it is a creation form. - // Therefore finding any item of the same name is a fault. - event.getFormData() - .addError(new GlobalizedMessage(ERR_MSG, - CmsConstants.CMS_BUNDLE)); - } else { - // means we are in a edit form. - // We need to add all of the items that are different - // versions of this item to the list so that we do not mark - // an error if those are the only problems. - event.getFormData() - .addError(new GlobalizedMessage( - ERR_MSG, - CmsConstants.CMS_BUNDLE, - new Object[]{item.getUuid()})); - } - } - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/BasicPageForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/BasicPageForm.java deleted file mode 100755 index 46b0ec8f7..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/BasicPageForm.java +++ /dev/null @@ -1,360 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.bebop.event.ParameterListener; -import com.arsdigita.bebop.parameters.DateParameter; -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; - -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.Folder; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.Assert; - -import org.librecms.CMSConfig; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.workflow.Workflow; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItemInitializer; -import org.librecms.contentsection.ContentType; - -import java.util.Date; -import java.util.Locale; -import java.util.Objects; -import java.util.Optional; - -/** - * A form for editing basic properties of documents (that is subclasses of class - * ContentPage). - * - * Document specific classes inherit from this class which provides the basic - * widgets for title, name launch date to use by those classes. - * - * This is just a convenience class. It uses parent class to construct the form - * including basic widgets (i.e. title and name/URL as well as save/cancel - * buttons) and adds optional launch date. - * - * Note: It is for editing existing content (specifically due to its validation - * method). - * - * @author Stanislav Freidin (stas@arsdigita.com) - * @author Jens Pelzetter - */ -public abstract class BasicPageForm extends BasicItemForm { - - private static final String LAUNCH_DATE = "launch_date"; - - private final StringParameter selectedLanguageParam; - - /** - * Construct a new BasicPageForm - * - * @param formName the name of this form - * @param itemModel The {@link ItemSelectionModel} which will be - * responsible for loading the current item - * @param selectedLanguageParam - */ - public BasicPageForm(final String formName, - final ItemSelectionModel itemModel, - final StringParameter selectedLanguageParam) { - - super(formName, itemModel, selectedLanguageParam); - Objects.requireNonNull(selectedLanguageParam); - this.selectedLanguageParam = selectedLanguageParam; - } - - /** - * Construct a new BasicPageForm with nothing on it - * - * @param formName the name of this form - * @param columnPanel the column panel of the form - * @param itemModel The {@link ItemSelectionModel} which will be - * responsible for loading the current item - * @param selectedLanguageParam - */ - public BasicPageForm(final String formName, - final ColumnPanel columnPanel, - final ItemSelectionModel itemModel, - final StringParameter selectedLanguageParam) { - - super(formName, columnPanel, itemModel, selectedLanguageParam); - this.selectedLanguageParam = selectedLanguageParam; - } - - /** - * Add various widgets to the form. Child classes should override this - * method to perform all their widget-adding needs - */ - @Override - protected void addWidgets() { - - /* Add basic widgets title/name which are part of any content item */ - super.addWidgets(); - - final CMSConfig cmsConfig = CMSConfig.getConfig(); - - /* Optionally add Lunchdate */ - if (!cmsConfig.isHideLaunchDate()) { - add(new Label(new GlobalizedMessage( - "cms.ui.authoring.page_launch_date", - CmsConstants.CMS_BUNDLE))); - final ParameterModel launchDateParam - = new DateParameter(LAUNCH_DATE); - com.arsdigita.bebop.form.Date launchDate - = new com.arsdigita.bebop.form.Date( - launchDateParam); - if (CMSConfig.getConfig().isRequireLaunchDate()) { - launchDate.addValidationListener( - new LaunchDateValidationListener()); - // if launch date is required, help user by suggesting today's date - launchDateParam.setDefaultValue(new Date()); - } - add(launchDate); - } - } - - /** - * Utility method to initialise the name/title widgets. Child classes may - * call this method from the init listener - * - * @param event the {@link FormSectionEvent} which was passed to the init - * listener - * - * @return the ContentPage instance which was extracted from the - * ItemSelectionModel - */ - public ContentItem initBasicWidgets(final FormSectionEvent event) { - Assert.exists(getItemSelectionModel()); - - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - final ContentItem item = getItemSelectionModel() - .getSelectedObject(state); - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - if (item != null) { - // Preset fields - data.put(CONTENT_ITEM_ID, Long.toString(item.getObjectId())); - data.put(NAME, item.getName().getValue(selectedLocale)); - data.put(TITLE, item.getTitle().getValue(selectedLocale)); - final CMSConfig cmsConfig = CMSConfig.getConfig(); - if (!cmsConfig.isHideLaunchDate()) { - data.put(LAUNCH_DATE, item.getLaunchDate()); - // if launch date is required, help user by suggesting today's date - if (cmsConfig.isRequireLaunchDate() - && item.getLaunchDate() == null) { - data.put(LAUNCH_DATE, new Date()); - } - } - } - - return item; - } - - /** - * Class specific implementation of FormValidationListener interface - * (inherited from BasicItemForm). - * - * @param event - * - * @throws FormProcessException - */ - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - - super.validate(event); - - final PageState state = event.getPageState(); - - final ContentItem item = getItemSelectionModel() - .getSelectedItem(event.getPageState()); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final BasicPageFormController controller = cdiUtil - .findBean(BasicPageFormController.class); - - final Optional folder = controller.getItemFolder(item); - if (folder.isPresent()) { - final String name = event.getFormData().getString(NAME); - final String selectedLang = (String) state - .getValue(selectedLanguageParam); - final Locale selectedLocale = new Locale(selectedLang); - if (!item.getName().hasValue(selectedLocale) - || !item.getName().getValue(selectedLocale).equals(name)) { - validateNameUniqueness(folder.get(), event); - } - } - } - - /** - * Utility method to process the name/title widgets. Child classes may call - * this method from the process listener. - * - * @param event the {@link FormSectionEvent} which was passed to the process - * listener - * - * @return - */ - public ContentItem processBasicWidgets(final FormSectionEvent event) { - Assert.exists(getItemSelectionModel()); - - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - final ContentItem item = getItemSelectionModel() - .getSelectedObject(state); - - if (item != null) { - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - item.getName().putValue(selectedLocale, (String) data.get(NAME)); - item.getTitle().putValue(selectedLocale, (String) data.get(TITLE)); - if (!CMSConfig.getConfig().isHideLaunchDate()) { - item.setLaunchDate((Date) data.get(LAUNCH_DATE)); - } - } - - return item; - } - - /** - * A utility method that will create a new item and tell the selection model - * to select the new item. - * - * Creation components may call this method in the process listener of their - * form. See {@link PageCreate} for an example. - * - * @param - * @param state - * @param name - * @param section - * @param folder - * @param initializer - * @param locale - * - * @return the new content item (or a proper subclass thereof) - * - * @throws com.arsdigita.bebop.FormProcessException - */ - public T createContentPage( - final PageState state, - final String name, - final ContentSection section, - final Folder folder, - final ContentItemInitializer initializer, - final Locale locale) throws FormProcessException { - - return createContentItemPage(state, - name, - section, - folder, - null, - initializer, - locale); - } - - public T createContentItemPage( - final PageState state, - final String name, - final ContentSection section, - final Folder folder, - final Workflow workflowTemplate, - final ContentItemInitializer initializer, - final Locale locale) throws FormProcessException { - - final ItemSelectionModel selectionModel = getItemSelectionModel(); - final ContentType contentType = selectionModel.getContentType(); - - // Create new item - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final BasicPageFormController controller = cdiUtil - .findBean(BasicPageFormController.class); - - final T item; - try { - @SuppressWarnings("unchecked") - final Class clazz = (Class) Class - .forName(contentType.getContentItemClass()); - - if (workflowTemplate == null) { - item = controller - .createContentItem(name, - section, - folder, - clazz, - initializer, - locale); - } else { - item = controller.createContentItem(name, - section, - folder, - workflowTemplate, - clazz, - initializer, - locale); - } - } catch (ClassNotFoundException ex) { - throw new FormProcessException( - "Couldn't create contentpage", - new GlobalizedMessage( - "cms.ui.authoring.couldnt_create_contentpage", - CmsConstants.CMS_BUNDLE), - ex); - } - - // Make sure the item will be remembered across requests - selectionModel.setSelectedKey(state, item.getObjectId()); - - return item; - } - - /** - * Constructs a new LaunchDateValidationListener. - */ - private class LaunchDateValidationListener implements ParameterListener { - - @Override - public void validate(final ParameterEvent event) { - - final ParameterData data = event.getParameterData(); - final Object value = data.getValue(); - - if (value == null) { - data.addError("launch date is required"); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/BasicPageFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/BasicPageFormController.java deleted file mode 100644 index 4dade5733..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/BasicPageFormController.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring; - -import org.libreccm.workflow.Workflow; -import org.libreccm.workflow.WorkflowRepository; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemInitializer; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionRepository; -import org.librecms.contentsection.Folder; -import org.librecms.contentsection.FolderRepository; - -import java.util.Locale; -import java.util.Optional; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class BasicPageFormController { - - @Inject - private ContentSectionRepository sectionRepo; - - @Inject - private ContentItemRepository itemRepo; - - @Inject - private ContentItemManager itemManager; - - @Inject - private FolderRepository folderRepo; - - @Inject - private WorkflowRepository workflowRepo; - - @Transactional(Transactional.TxType.REQUIRED) - protected T createContentItem( - final String name, - final ContentSection section, - final Folder folder, - final Class clazz, - final ContentItemInitializer initializer, - final Locale locale) { - - return createContentItem(name, - section, - folder, - null, - clazz, - initializer, - locale); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected T createContentItem( - final String name, - final ContentSection section, - final Folder folder, - final Workflow workflowTemplate, - final Class clazz, - final ContentItemInitializer initializer, - final Locale locale) { - - final ContentSection contentSection = sectionRepo - .findById(section.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentSection with ID %d in the database.", - section.getObjectId()))); - - final Folder itemFolder = folderRepo - .findById(folder.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No Folder with ID %d in the database.", - folder.getObjectId()))); - - final T item; - if (workflowTemplate == null) { - - item = itemManager.createContentItem(name, - contentSection, - itemFolder, - clazz, - initializer, - locale); - - } else { - final Workflow itemWorkflowTemplate = workflowRepo - .findById(workflowTemplate.getWorkflowId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No WorkflowTemplate with ID %d in the database.", - workflowTemplate.getWorkflowId()))); - - item = itemManager.createContentItem(name, - contentSection, - itemFolder, - itemWorkflowTemplate, - clazz, - initializer, - locale); - } - - return item; - } - - @Transactional(Transactional.TxType.REQUIRED) - protected Optional getItemFolder(final ContentItem item) { - - final Optional contentItem = itemRepo - .findById(item.getObjectId()); - - if (contentItem.isPresent()) { - return itemManager.getItemFolder(contentItem.get()); - } else { - return Optional.empty(); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/CategoryWidget.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/CategoryWidget.java deleted file mode 100755 index 6dbd4b1bf..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/CategoryWidget.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (C) 2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.form.Widget; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.parameters.ArrayParameter; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.parameters.BigDecimalParameter; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.xml.Element; -import com.arsdigita.xml.XML; - -import org.libreccm.categorization.Category; - -import com.arsdigita.cms.CMS; -import com.arsdigita.kernel.KernelConfig; - -import org.librecms.CMSConfig; -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentSection; - -import java.util.Arrays; -import java.util.Set; -import java.util.HashSet; -import java.util.Map; -import java.util.HashMap; -import java.util.List; -import java.util.ArrayList; -import java.util.Iterator; -import java.math.BigDecimal; - -import static javax.naming.ldap.SortControl.*; - -public class CategoryWidget extends Widget { - - private LongParameter rootParameter; - private StringParameter modeParameter; - - public CategoryWidget(final String name, - final LongParameter rootParameter, - final StringParameter modeParameter) { - - super(new ArrayParameter(new BigDecimalParameter(name))); - - this.rootParameter = rootParameter; - this.modeParameter = modeParameter; - } - - @Override - protected String getType() { - return "category"; - } - - @Override - public boolean isCompound() { - return false; - } - - @Override - protected void generateWidget(final PageState state, - final Element parent) { - - Element widget = parent.newChildElement("cms:categoryWidget", - CMS.CMS_XML_NS); - exportAttributes(widget); - - widget.addAttribute("mode", (String) state.getValue(modeParameter)); - widget.addAttribute("name", getName()); - - final Set selectedCategories = new HashSet<>(); - - final Long[] values = (Long[]) getValue(state); - if (values != null) { - selectedCategories.addAll(Arrays.asList(values)); - } - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryRepository categoryRepo = cdiUtil - .findBean(CategoryRepository.class); - final Category rootCategory = categoryRepo - .findById((Long) state.getValue(rootParameter)) - .orElseThrow(() -> new IllegalArgumentException( - String.format( - "No Category with ID %d in the database. " - + "Where did that ID come from?", - state.getValue(rootParameter)))); - - final List categories = rootCategory.getSubCategories(); - - final Map children = new HashMap(); -// ToDo, I don't understand was is done here... -// while (categories.next()) { -// final Category cat = categories.getCategory(); -// final BigDecimal parentID = (BigDecimal) categories -// .get("parents.id"); -// -// List childList = (List) children.get(parentID); -// if (childList == null) { -// childList = new ArrayList(); -// children.put(parentID, childList); -// } -// -// childList.add( -// new CategorySortKeyPair(cat, (BigDecimal) categories.get( -// "parents.link.sortKey"))); -// } - - generateCategory(widget, null, rootCategory, null, selectedCategories, - children); - } - - public void generateCategory(final Element parent, - final String path, - final Category category, - final Long sortKey, - final Set selected, - final Map children) { - - final Element element = new Element("cms:category", - CMS.CMS_XML_NS); - - element.addAttribute("id", XML.format(category.getObjectId())); - element.addAttribute("name", category.getName()); - element.addAttribute("description", - category - .getDescription() - .getValue(KernelConfig - .getConfig() - .getDefaultLocale())); - if (selected.contains(category.getObjectId())) { - element.addAttribute("isSelected", "1"); - } else { - element.addAttribute("isSelected", "0"); - } - if (category.isAbstractCategory()) { - element.addAttribute("isAbstract", "1"); - } else { - element.addAttribute("isAbstract", "0"); - } - if (category.isEnabled()) { - element.addAttribute("isEnabled", "1"); - } else { - element.addAttribute("isEnabled", "0"); - } - if (sortKey != null) { - element.addAttribute("sortKey", sortKey.toString()); - } - // sort order attribute added to every node in order that same xsl may - // be used to transform xml fragments returned by ajax in the Aplaws - // extension -// element.addAttribute("order", -// CMSConfig.getConfig().getCategoryTreeOrder()); - - String fullname = path == null ? "/" : path + " > " + category.getName(); - element.addAttribute("fullname", fullname); - StringBuilder nodeID = new StringBuilder(parent.getAttribute("node-id")); - if (nodeID.length() > 0) { - nodeID.append("-"); - } - nodeID.append(category.getObjectId()); - element.addAttribute("node-id", nodeID.toString()); - parent.addContent(element); - - List c = (List) children.get(category.getObjectId()); - if (c != null) { - Iterator i = c.iterator(); - while (i.hasNext()) { - CategorySortKeyPair pair = (CategorySortKeyPair) i.next(); - Category child = pair.getCategory(); - Long childSortKey = pair.getSortKey(); - generateCategory(element, - fullname, - child, - childSortKey, - selected, - children); - } - } - } - - private class CategorySortKeyPair { - - private Category category; - private Long sortKey; - - public CategorySortKeyPair(final Category category, - final Long sortKey) { - this.category = category; - this.sortKey = sortKey; - } - - public Category getCategory() { - return category; - } - - public Long getSortKey() { - return sortKey; - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/CreationComponent.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/CreationComponent.java deleted file mode 100755 index b636a5d88..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/CreationComponent.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.Container; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.event.FormProcessListener; - -/** - * Interface which item creation components should implement. It's - * currently an optional interface, but user defined content types - * will not work unless they inherit from a type whose creation - * component implements this. This interface currently only defines - * methods which are essential to the operation of UDCT creation - * components. - * - * @author Scott Seago (sseago@redhat.com) - */ -public interface CreationComponent extends Container, FormProcessListener { - - /** - * Instantiate and add the save/cancel section for this CreationComponent. - */ - void addSaveCancelSection(); - - /** - * Return the save/cancel section for this CreationComponent. - * - * @return the save/cancel section for this CreationComponent. - */ - SaveCancelSection getSaveCancelSection(); - - /** - * Removes the specified process listener from the - * list of process listeners (if it had previously been added). - * - * @param listener the process listener to remove - */ - void removeProcessListener(FormProcessListener listener); - - /** - * Return the ApplyWorkflowFormSection associated with this CreationComponent. - * - * @return the ApplyWorkflowFormSection associated with this CreationComponent. - */ - ApplyWorkflowFormSection getWorkflowSection(); - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/CreationSelector.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/CreationSelector.java deleted file mode 100755 index d4f854f32..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/CreationSelector.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormSection; -import com.arsdigita.bebop.MetaForm; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.form.FormErrorDisplay; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.ContentItemPage; -import com.arsdigita.cms.ui.folder.FolderSelectionModel; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.web.RedirectSignal; -import com.arsdigita.web.URL; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentType; -import org.librecms.contentsection.ContentTypeManager; -import org.librecms.contentsection.ContentTypeRepository; -import org.librecms.contentsection.Folder; -import org.librecms.contentsection.FolderRepository; -import org.librecms.contenttypes.AuthoringKitInfo; -import org.librecms.contenttypes.ContentTypeInfo; -import org.librecms.contenttypes.ContentTypesManager; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.Optional; - -/** - * An invisible component which contains all the possible creation components. - * The components are loaded from the database at construction time. The - * selector uses a {@link SingleSelectionModel} in order to get the ID of the - * current content type. - * - * Important: This component is passed in the constructor to - * every authoring kit creation component (such as {@link PageCreate}). The - * creation component is supposed to follow the following pattern: - * - *
- *   // The member variable m_parent points to the CreationSelector
- *   SomeContentItem item = somehowCreateTheItem(state);
- *   item.setParent(m_parent.getFolder(state));
- *   m_parent.editItem(state, item);
- * 
- * - * If the creation component wishes to cancel the creation process, it should - * call - * - *
m_parent.redirectBack(state);
- * - * The component may also call - * - *
m_parent.getContentSection(state);
- * - * in order to get the current content section. - * - * @author unknown - * @author Jens Pelzetter - */ -public class CreationSelector extends MetaForm { - - private static final Logger LOGGER = LogManager.getLogger( - CreationSelector.class); - - private final FolderSelectionModel folderSelectionModel; - private final SingleSelectionModel typeSelectionModel; - private final StringParameter selectedLanguageParam; - - private static final Class[] ARGUMENTS = new Class[]{ - ItemSelectionModel.class, - CreationSelector.class, - StringParameter.class - }; - - private Object[] values; - - private final ItemSelectionModel itemSelectionModel; - private final LongParameter itemIdParameter; - - public static final String ITEM_ID = "iid"; - - /** - * Constructs a new CreationSelector. Load all the possible - * creation components from the database and stick them in the Map. - * - * @param typeSelectionModel the {@link SingleSelectionModel} which will - * supply a BigDecimal ID of the content type to - * instantiate - * - * @param folderSelectionModel the {@link FolderSelectionModel} containing - * the folder in which new items are to be - * created - * @param selectedLanguageParam - */ - public CreationSelector(final SingleSelectionModel typeSelectionModel, - final FolderSelectionModel folderSelectionModel, - final StringParameter selectedLanguageParam) { - - super("pageCreate"); - - this.typeSelectionModel = typeSelectionModel; - this.folderSelectionModel = folderSelectionModel; - this.selectedLanguageParam = selectedLanguageParam; - - itemIdParameter = new LongParameter(ITEM_ID); - itemSelectionModel = new ItemSelectionModel(itemIdParameter); - } - - /** - * - * @param state - * - * @return - */ - @Override - public Form buildForm(final PageState state) { - final Long typeId = typeSelectionModel.getSelectedKey(state); - final Component component; - final Form returnForm = new Form("pageCreate"); - final FormErrorDisplay formErrorDisplay = new FormErrorDisplay(this); - formErrorDisplay.setStateParamsAreRegistered(false); - returnForm.add(formErrorDisplay, ColumnPanel.FULL_WIDTH - | ColumnPanel.LEFT); - - if (typeId != null) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentTypeRepository typeRepo = cdiUtil.findBean( - ContentTypeRepository.class); - final ContentTypeManager typeManager = cdiUtil.findBean( - ContentTypeManager.class); - final ContentTypesManager typesManager = cdiUtil.findBean( - ContentTypesManager.class); - - final Optional type = typeRepo.findById(typeId); - if (!type.isPresent()) { - throw new UncheckedWrapperException(String.format( - "Type with id %d not found.", typeId)); - } - final ContentTypeInfo typeInfo = typesManager - .getContentTypeInfo(type.get()); - final AuthoringKitInfo kit = typeInfo.getAuthoringKit(); - component = instantiateKitComponent(kit, type.get()); - if (component != null) { - returnForm.add(component); - returnForm.setMethod(Form.POST); - returnForm.setEncType("multipart/form-data"); - } - } - return returnForm; - } - - /** - * Add the item_id parameter. - * - * @param page - */ - @Override - public void register(final Page page) { - super.register(page); - page.addComponentStateParam(this, itemIdParameter); - } - - /** - * Get the creation component. - * - * @param kit - * @param type - * - * @return - */ - protected Component instantiateKitComponent(final AuthoringKitInfo kit, - final ContentType type) { - final Class createClass = kit - .getCreateComponent(); - final Object[] vals; - - try { - final ItemSelectionModel itemSelectionModel - = new ItemSelectionModel( - type, itemIdParameter); - vals = new Object[]{itemSelectionModel, - this, - selectedLanguageParam}; - - final Constructor constructor = createClass - .getConstructor(ARGUMENTS); - final Component component = (Component) constructor - .newInstance(vals); - return component; - } catch (IllegalAccessException - | IllegalArgumentException - | InstantiationException - | NoSuchMethodException - | SecurityException - | InvocationTargetException ex) { - LOGGER.error("Failed to instantiate creation component \"{}\".", - kit.getCreateComponent().getName()); - LOGGER.error("Exception: ", ex); - throw new UncheckedWrapperException(String.format( - "Failed to instantiate creation component \"%s\".", - kit.getCreateComponent().getName()), - ex); - } - } - - /** - * Return the currently selected folder. Creation components will place new - * items in this folder. - * - * @param state represents the current request - * - * @return the currently selected folder, in which new items should be - * placed. - */ - public final Folder getFolder(final PageState state) { - return folderSelectionModel.getSelectedObject(state); - } - - /** - * Return the currently selected content section. New items created by - * creation components will belong to this section. This is the content - * section to which the folder returned by {@link #getFolder getFolder} - * belongs. - * - * @param state represents the current request - * - * @return the currently selected content section. - */ - public final ContentSection getContentSection(final PageState state) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CreationSelectorController controller = cdiUtil - .findBean(CreationSelectorController.class); - - return controller.getContentSectionForFolder(getFolder(state)); - } - - /** - * Forward to the item editing UI. The creation component of an authoring - * kit may call this method to indicate that the creation process is - * complete. - * - * @param state the page state - * @param item the newly created item - */ - public void editItem(final PageState state, final ContentItem item) { - final ContentSection section = getContentSection(state); - - final String nodeUrl = String.join("", URL.getDispatcherPath(), - section.getPrimaryUrl(), - "/"); - final String target = ContentItemPage.getItemURL( - nodeUrl, item.getObjectId(), ContentItemPage.AUTHORING_TAB, true); - - throw new RedirectSignal(target, true); - } - - /** - * Cancel item editing and go back to where the user came from - * - * @param state the page state - */ - public void redirectBack(final PageState state) { - typeSelectionModel.clearSelection(state); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/CreationSelectorController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/CreationSelectorController.java deleted file mode 100644 index 60974a12c..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/CreationSelectorController.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring; - -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionRepository; -import org.librecms.contentsection.Folder; -import org.librecms.contentsection.FolderRepository; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class CreationSelectorController { - - @Inject - private FolderRepository folderRepo; - - @Inject - private ContentSectionRepository sectionRepo; - - @Transactional(Transactional.TxType.REQUIRED) - protected ContentSection getContentSectionForFolder(final Folder folder) { - - final Folder theFolder = folderRepo - .findById(folder.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No Folder with ID %d in the database. Where did that ID come from?", - folder.getObjectId()))); - - final ContentSection section = theFolder.getSection(); - - return sectionRepo - .findById(section.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContentSection with ID %d in the database.", - section.getObjectId()))); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ItemCategoryExtension.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ItemCategoryExtension.java deleted file mode 100644 index 619903445..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ItemCategoryExtension.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.SimpleComponent; - -/** - * NOOP base implementation of category authoring step extension. - * Summary component returned by #getSummary() is show on category summary page, - * usually an ActionLink which activates the Form component returned by #getForm(). - * - * @author Alan Pevec - */public class ItemCategoryExtension { - - public SimpleComponent[] getSummary() { - return new SimpleComponent[0]; - } - - public SimpleComponent[] getForm() { - return new SimpleComponent[0]; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ItemCategoryForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ItemCategoryForm.java deleted file mode 100755 index 35a0ebb09..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ItemCategoryForm.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import org.apache.logging.log4j.Logger; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.form.Widget; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.categorization.ui.ACSObjectCategoryForm; -import com.arsdigita.cms.CMS; - -import org.apache.logging.log4j.LogManager; -import org.libreccm.core.CcmObject; - -/** - * (No description available yet). - * - * Usage of this class is configured in parameter - * c.ad.cms.category_authoring_add_form - */ -public class ItemCategoryForm extends ACSObjectCategoryForm { - - private static Logger LOGGER = LogManager.getLogger(ItemCategoryForm.class); - - public ItemCategoryForm(final LongParameter rootParameter, - final StringParameter modeParameter, - final Widget widget) { - - super(rootParameter, modeParameter, widget); - LOGGER.debug("creating new ItemTerm Form with widget " + widget); - } - - public ItemCategoryForm(final LongParameter root, - final StringParameter mode) { - - this(root, mode, new CategoryWidget("category", root, mode)); - } - - /* - * @see com.arsdigita.categorization.ui.ACSObjectCategoryForm#getObject() - */ - @Override - protected CcmObject getObject(final PageState state) { - return CMS.getContext().getContentItem(); - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ItemCategoryStep.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ItemCategoryStep.java deleted file mode 100755 index 8d876a45c..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ItemCategoryStep.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (C) 2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.SimpleComponent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.web.RedirectSignal; - -import com.arsdigita.cms.CMS; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.util.Classes; - -import org.librecms.CMSConfig; -import org.libreccm.core.UnexpectedErrorException; -import org.librecms.CmsConstants; -import org.librecms.ui.authoring.ContentItemAuthoringStep; - -import java.math.BigDecimal; - -@ContentItemAuthoringStep( - labelBundle = CmsConstants.CMS_BUNDLE, - labelKey = "item_category_step.label", - descriptionBundle = CmsConstants.CMS_BUNDLE, - descriptionKey = "item_category_step.description" -) -public class ItemCategoryStep extends SimpleContainer implements Resettable { - - private final LongParameter rootParameter; - private final StringParameter modeParameter; - - private final ItemCategorySummary itemCategorySummary; - - private final SimpleComponent addComponent; - - private final SimpleComponent[] extensionSummaries; - private final SimpleComponent[] extensionForms; - private int extensionsCount; - - public ItemCategoryStep(final ItemSelectionModel itemSelectionModel, - final AuthoringKitWizard authoringKitWizard, - final StringParameter selectedLanguage) { - - super("cms:categoryStep", CMS.CMS_XML_NS); - - rootParameter = new LongParameter("root"); - modeParameter = new StringParameter("mode"); - - itemCategorySummary = new ItemCategorySummary(); - itemCategorySummary.registerAction(ItemCategorySummary.ACTION_ADD, - new AddActionListener("plain")); - itemCategorySummary.registerAction(ItemCategorySummary.ACTION_ADD_JS, - new AddActionListener("javascript")); - - final String addFormClassName = CMSConfig - .getConfig() - .getCategoryAuthoringAddForm(); - final Class addFormClass; - try { - addFormClass = Class.forName(addFormClassName); - } catch (ClassNotFoundException ex) { - throw new UnexpectedErrorException(ex); - } - addComponent = (SimpleComponent) Classes - .newInstance(addFormClass, - new Class[]{LongParameter.class, - StringParameter.class}, - new Object[]{rootParameter, modeParameter}); - addComponent.addCompletionListener(new ResetListener()); - - final String extensionClassName = CMSConfig - .getConfig() - .getCategoryAuthoringExtension(); - final Class extensionClass; - try { - extensionClass = Class.forName(extensionClassName); - } catch (ClassNotFoundException ex) { - throw new UnexpectedErrorException(ex); - } - final ItemCategoryExtension extension = (ItemCategoryExtension) Classes - .newInstance(extensionClass); - - extensionSummaries = extension.getSummary(); - extensionForms = extension.getForm(); - int nSummaries = extensionSummaries.length; - int nForms = extensionForms.length; - if (nSummaries != nForms) { - throw new UnexpectedErrorException( - "Invalid category step extension."); - } - extensionsCount = nForms; - for (int i = 0; i < extensionsCount; i++) { - extensionSummaries[i] - .addCompletionListener(new ExtensionListener(i)); - extensionForms[i].addCompletionListener(new ResetListener()); - super.add(extensionSummaries[i]); - super.add(extensionForms[i]); - } - super.add(itemCategorySummary); - super.add(addComponent); - } - - @Override - public void register(final Page page) { - super.register(page); - - page.setVisibleDefault(addComponent, false); - for (int i = 0; i < extensionsCount; i++) { - page.setVisibleDefault(extensionForms[i], false); - } - page.addGlobalStateParam(rootParameter); - page.addGlobalStateParam(modeParameter); - } - - @Override - public void reset(final PageState state) { - state.setValue(rootParameter, null); - state.setValue(modeParameter, null); - - itemCategorySummary.setVisible(state, true); - addComponent.setVisible(state, false); - for (int i = 0; i < extensionsCount; i++) { - extensionSummaries[i].setVisible(state, true); - extensionForms[i].setVisible(state, false); - } - } - - private class AddActionListener implements ActionListener { - - private final String mode; - - public AddActionListener(final String mode) { - this.mode = mode; - } - - @Override - public void actionPerformed(final ActionEvent event) { - - final PageState state = event.getPageState(); - - state.setValue(rootParameter, - new BigDecimal(state.getControlEventValue())); - - state.setValue(ItemCategoryStep.this.modeParameter, - mode); - - itemCategorySummary.setVisible(state, false); - addComponent.setVisible(state, true); - for (int i=0;iJens Pelzetter - */ -@RequestScoped -class ItemCategoryStepController { - - @Inject - private ContentSectionRepository sectionRepo; - - @Transactional(Transactional.TxType.REQUIRED) - protected List getRootCategories(final ContentSection section) { - - Objects.requireNonNull(section); - - final ContentSection contentSection = sectionRepo - .findById(section.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentSection with ID %d in the database.", - section.getObjectId()))); - - return contentSection - .getDomains() - .stream() - .map(domainOwnership -> domainOwnership.getDomain()) - .map(domain -> domain.getRoot()) - .collect(Collectors.toList()); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ItemCategorySummary.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ItemCategorySummary.java deleted file mode 100755 index a6eaabbef..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ItemCategorySummary.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.PageState; - -import org.libreccm.categorization.Category; - -import com.arsdigita.categorization.ui.ACSObjectCategorySummary; -import com.arsdigita.cms.CMS; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.CcmObject; -import org.libreccm.security.PermissionChecker; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.util.List; - -public class ItemCategorySummary extends ACSObjectCategorySummary { - - public ItemCategorySummary() { - super(); - } - - @Override - protected boolean canEdit(final PageState state) { - - final PermissionChecker permissionChecker = CdiUtil - .createCdiUtil() - .findBean(PermissionChecker.class); - - return permissionChecker.isPermitted(ItemPrivileges.CATEGORIZE, - CMS.getContext().getContentItem()); - } - - - /* - * @see com.arsdigita.categorization.ui.ObjectCategorySummary#getObject() - */ - @Override - protected CcmObject getObject(final PageState state) { - - return CMS.getContext().getContentItem(); - } - - /* - * @see com.arsdigita.categorization.ui.ObjectCategorySummary#getXMLPrefix() - */ - @Override - protected String getXMLPrefix() { - return "cms"; - } - - /* - * @see com.arsdigita.categorization.ui.ObjectCategorySummary#getXMLNameSpace() - */ - @Override - protected String getXMLNameSpace() { - return CMS.CMS_XML_NS; - } - - /* - * @see com.arsdigita.categorization.ui.ObjectCategorySummary#getRootCategories() - */ - @Override - protected List getRootCategories(final PageState state) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ItemCategoryStepController controller = cdiUtil - .findBean(ItemCategoryStepController.class); - - return controller.getRootCategories(CMS.getContext().getContentSection()); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/LanguageWidget.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/LanguageWidget.java deleted file mode 100755 index f484cbc65..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/LanguageWidget.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; -import org.librecms.util.LanguageUtil; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.Pair; - -import java.util.List; -import org.libreccm.cdi.utils.CdiUtil; - -/** - * Language picker for the multilingual content items. - */ -public class LanguageWidget extends SingleSelect { - - public LanguageWidget(String name) { - this(new StringParameter(name)); - } - - public LanguageWidget(ParameterModel model) { - super(model); - setupOptions(); - } - - /** - * Adds list of languages. Default version shows all supported languages for - * this CMS installation, as defined in the enterprise.init: - * com.arsdigita.cms.installer.Initializer: languages - */ - protected void setupOptions() { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final LanguageUtil languageUtil = cdiUtil.findBean(LanguageUtil.class); - final List languages = languageUtil.convertToG11N(languageUtil. - getSupportedLanguages2LA()); - for(final Pair pair : languages) { - final String langCode = (String) pair.getKey(); - final GlobalizedMessage langName = (GlobalizedMessage) pair.getValue(); - - addOption(new Option(langCode, new Label(langName))); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/PageCreateForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/PageCreateForm.java deleted file mode 100755 index 7f54e11e2..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/PageCreateForm.java +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.parameters.StringParameter; - -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentType; -import org.librecms.contentsection.Folder; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.util.Assert; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.libreccm.workflow.Workflow; -import org.libreccm.workflow.WorkflowRepository; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemInitializer; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contenttypes.ContentTypeInfo; -import org.librecms.contenttypes.ContentTypesManager; - -import java.util.Locale; -import java.util.ResourceBundle; - -/** - * A form which will create a new document (that is subclasses of class - * ContentPage). - * - * Used to create a new document / content item. Creates widgets to select the - * workflow, and language. It displays the type of document as well. Super class - * adds additional widgets (title and name/URL) to complete the form. - * - * It's a pane which is part of a more complex page, additionally containing - * folder structure, content items in the folder, permissions, etc. - * - * @author Stanislav Freidin (stas@arsdigita.com) - * @author Jens Pelzetter - */ -public class PageCreateForm - extends BasicPageForm - implements FormSubmissionListener, CreationComponent { - - /** - * The state parameter which specifies the content section - */ - public static final String SECTION_ID = "sid"; - - private final CreationSelector creationSelector; - private ApplyWorkflowFormSection workflowSection; - private final StringParameter selectedLanguageParam; - - private LanguageWidget languageWidget; - - /** - * Construct a new PageCreationForm - * - * @param itemModel The {@link ItemSelectionModel} which will be - * responsible for loading the current item - * @param creationSelector The {@link CreationSelector} parent. This - * class should call either the {@link - * CreationSelector#redirectBack(PageState)} or {@link - * CreationSelector#editItem(PageState, ContentItem)} methods on the parent - * eventually - * @param selectedLanguageParam - */ - public PageCreateForm(final ItemSelectionModel itemModel, - final CreationSelector creationSelector, - final StringParameter selectedLanguageParam) { - - super("PageCreate", itemModel, selectedLanguageParam); - - this.creationSelector = creationSelector; - this.selectedLanguageParam = selectedLanguageParam; - - workflowSection.setCreationSelector(creationSelector); - super.addSubmissionListener(this); - - super.getSaveCancelSection().getSaveButton() - .setButtonLabel(new GlobalizedMessage("cms.ui.create", - CmsConstants.CMS_BUNDLE)); - } - - /** - * Add various widgets to the form. Child classes should override this - * method to perform all their widget-adding needs. - */ - @Override - protected void addWidgets() { - - /* Retrieve Content Type */ - final ContentType type = getItemSelectionModel().getContentType(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentTypesManager typesManager = cdiUtil - .findBean(ContentTypesManager.class); - final ContentTypeInfo typeInfo = typesManager.getContentTypeInfo(type); - - /* Add workflow selection based on configured Content Type */ - workflowSection = new ApplyWorkflowFormSection(type); - add(workflowSection, ColumnPanel.INSERT); - /* content type */ - add(new Label(new GlobalizedMessage("cms.ui.authoring.content_type", - CmsConstants.CMS_BUNDLE))); - final Label typeOutput = new Label( - new ContentTypePrintListener(typeInfo)); - add(typeOutput); - /* language selection */ - add(new Label(new GlobalizedMessage("cms.ui.language.field", - CmsConstants.CMS_BUNDLE))); - languageWidget = new LanguageWidget(LANGUAGE); - add(languageWidget); -// add(new LanguageWidget(LANGUAGE)); - - /* Additional widgets from super type: title and name (url) */ - super.addWidgets(); - } - - /** - * Return the ApplyWorkflowFormSection associated with this - * CreationComponent. - * - * @return the ApplyWorkflowFormSection associated with this - * CreationComponent. - */ - @Override - public ApplyWorkflowFormSection getWorkflowSection() { - return workflowSection; - } - - /** - * Create a new item id. - * - * @param event - * - * @throws com.arsdigita.bebop.FormProcessException - */ - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - - //Init language widget with default language. - final PageState state = event.getPageState(); - languageWidget.setValue(state, KernelConfig.getConfig().getDefaultLanguage()); - } - - /** - * If the Cancel button was pressed, hide self and show the display - * component. - * - * @param event - * - * @throws com.arsdigita.bebop.FormProcessException - */ - @Override - public void submitted(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (getSaveCancelSection().getCancelButton().isSelected(state)) { - creationSelector.redirectBack(state); - - throw new FormProcessException( - new GlobalizedMessage("cms.ui.authoring.submission_cancelled", - CmsConstants.CMS_BUNDLE)); - } - } - - /** - * Validate inputs to ensure name uniqueness. Note: We can't call - * {@code super.validate(FormSectionEvent)} here because the super method - * {@link BasicPageForm#validate(com.arsdigita.bebop.event.FormSectionEvent)} - * tries to access things which on existing yet. - * - * @param event - * - * @throws com.arsdigita.bebop.FormProcessException - */ - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - - final Folder folder = creationSelector.getFolder(event.getPageState()); - validateNameUniqueness(folder, event); - } - - /** - * Class specific implementation if FormProcessListener (as inherited from - * BasicItemForm), saves fields to the database. - * - * @param event - * - * @throws FormProcessException - */ - @Override - public final void process(final FormSectionEvent event) - throws FormProcessException { - - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - final ContentSection section = creationSelector.getContentSection(state); - final Folder folder = creationSelector.getFolder(state); - - Assert.exists(section, ContentSection.class); - - final Long selectedWorkflowTemplateId = workflowSection - .getSelectedWorkflowTemplateId(state); - - final Locale locale = new Locale((String) data.get(LANGUAGE)); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - - final ContentItem item; - if (selectedWorkflowTemplateId == null) { - item = createContentPage(state, - (String) data.get(NAME), - section, - folder, - getItemInitializer(data, state), - locale); - } else { - final WorkflowRepository workflowRepo = cdiUtil - .findBean(WorkflowRepository.class); - final Workflow workflowTemplate = workflowRepo - .findById(selectedWorkflowTemplateId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No WorkflowTemplate with ID %d in the database.", - selectedWorkflowTemplateId))); - - item = createContentItemPage(state, - (String) data.get(NAME), - section, - folder, - workflowTemplate, - getItemInitializer(data, state), - locale); - } - -// item.getName().putValue(locale, (String) data.get(NAME)); - item.getTitle().putValue(locale, (String) data.get(TITLE)); - - final ContentItemRepository itemRepo = cdiUtil - .findBean(ContentItemRepository.class); - itemRepo.save(item); - - state.setValue(selectedLanguageParam, locale.toString()); - - creationSelector.editItem(state, item); - } - - protected ContentItemInitializer getItemInitializer( - final FormData data, final PageState state) { - - return item -> { - }; - } - - protected StringParameter getSelectedLanguageParam() { - return selectedLanguageParam; - } - - private class ContentTypePrintListener implements PrintListener { - - private final ContentTypeInfo typeInfo; - - public ContentTypePrintListener(final ContentTypeInfo typeInfo) { - this.typeInfo = typeInfo; - } - - @Override - public void prepare(final PrintEvent event) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final GlobalizationHelper globalizationHelper = cdiUtil - .findBean(GlobalizationHelper.class); - final ResourceBundle bundle = ResourceBundle - .getBundle(typeInfo.getLabelBundle(), - globalizationHelper.getNegotiatedLocale()); - - final String typeLabel = bundle.getString(typeInfo.getLabelKey()); - - final Label target = (Label) event.getTarget(); - target.setLabel(typeLabel); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/PageFileForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/PageFileForm.java deleted file mode 100644 index 39d96464e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/PageFileForm.java +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.form.FormErrorDisplay; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.FileUploadSection; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.UncheckedWrapperException; - -import org.libreccm.l10n.LocalizedString; -import org.librecms.CmsConstants; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; - -import javax.activation.MimeType; - -/** - * A form for editing TextAsset items. Displays a "file upload" widget, - * auto-guesses mime type - */ -class PageFileForm extends Form implements FormProcessListener, - FormValidationListener { - - private final TextBody textBody; - - private SaveCancelSection saveCancelSection; - private FileUploadSection fileUploadSection; - // Variables saved by validate for processing - private RequestLocal fileUploadContent; - private RequestLocal fileUploadUsedINSO; - /** - * The text entry widget - */ - public static final String TEXT_ENTRY = "text_entry"; - - /** - * Construct a new PageFileForm - * - * @param itemSelectionModel - */ - public PageFileForm(final TextBody textBody) { - - super("PageFileUpload", new BoxPanel(BoxPanel.VERTICAL)); - - this.textBody = textBody; - - setMethod(Form.POST); - setEncType("multipart/form-data"); - - addWidgets(); - } - - private void addWidgets() { - - fileUploadSection = new FileUploadSection( - new GlobalizedMessage("cms.ui.authoring.text.mime_type"), - "text", - textBody.getDefaultMimeType()); - - fileUploadSection - .getFileUploadWidget() - .addValidationListener(new NotNullValidationListener()); - fileUploadSection - .getMimeTypeWidget() - .setDefaultValue(FileUploadSection.GUESS_MIME); - add(fileUploadSection); - - saveCancelSection = new SaveCancelSection(); - add(saveCancelSection); - - final FormErrorDisplay errorDisplay = new FormErrorDisplay(this); - add(errorDisplay); - - addValidationListener(this); - addProcessListener(this); - - fileUploadContent = new RequestLocal(); - fileUploadUsedINSO = new RequestLocal(); - - } - - protected String getFileUploadContent(PageState state) { - return (String) fileUploadContent.get(state); - } - - /** - * Make sure that files of this type can be uploaded - */ - private void validateFileType(final MimeType mime, final boolean textType) - throws FormProcessException { - // boolean validType = textType || ((mime instanceof TextMimeType) - // && ((TextMimeType) mime). - // allowINSOConvert().booleanValue()); - boolean validType = true; //ToDo - if (!validType) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.authoring.invalid_file_type", - CmsConstants.CMS_BUNDLE)); - } - // boolean insoWorks = MimeTypeStatus.getMimeTypeStatus(). - // getInsoFilterWorks().intValue() == 1; - boolean insoWorks = true; //ToDo - if (!textType && !insoWorks) { - // Can't convert. inso filter is not working. Give message. - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.authoring.couldnt_convert_missing_inso", - CmsConstants.CMS_BUNDLE)); - } - } - - /** - * read in the content of the file (in bytes). - */ - private byte[] readFileBytes(final File file) throws FormProcessException { - byte[] fileBytes; - try (final FileInputStream fs = new FileInputStream(file)) { - fileBytes = new byte[fs.available()]; - fs.read(fileBytes); - } catch (IOException ex) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.authoring.unable_to_load_file", - CmsConstants.CMS_BUNDLE)); - } - return fileBytes; - } - - /** - * Convert bytes to String, possibly using INSO filter to convert to HTML - * type - */ - private String convertBytes(final byte[] fileBytes, final boolean textType, - final boolean[] usedInso) throws - FormProcessException { - String fileContent; - // If mime type is not text type, try to convert to html - if (!textType) { - fileContent = new String(fileBytes); - if (fileContent != null) { - // Converted successfully, flag type should be html - usedInso[0] = true; - } else { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.authoring.couldnt_convert_inso_failed", - CmsConstants.CMS_BUNDLE)); - } - } else { - // Text type, no need to convert - final String enc = "UTF-8"; - try { - fileContent = new String(fileBytes, enc); - } catch (UnsupportedEncodingException ex) { - throw new UncheckedWrapperException( - "cannot convert to encoding " + enc, ex); - } - usedInso[0] = false; - } - return fileContent; - } - - /** - * Extract the contents of the HTML Body tag. (Done to prevent base and - * other header tags from interfering with page display). - */ - private String extractHTMLBody(final String htmlText) throws - FormProcessException { - final String lowerCase = htmlText.toLowerCase(); - int bodyStart = lowerCase.indexOf("", bodyStart); - int bodyEnd = lowerCase.indexOf("", bodyStart_v); - if (bodyStart == -1 || bodyEnd == -1) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.authoring.html_file_missing_body_tags", - CmsConstants.CMS_BUNDLE)); - } - return htmlText.substring(bodyStart_v + 1, bodyEnd); - } - - /** - * Validate file upload - * - * @throws com.arsdigita.bebop.FormProcessException - */ - @Override - public void validate(final FormSectionEvent event) throws - FormProcessException { - MimeType mime = fileUploadSection.getMimeType(event); - // boolean textType = mime.getPrefix().equals(TextMimeType.TEXT_PREFIX); - final boolean textType = true; //ToDo - validateFileType(mime, textType); - // Convert the file to HTML, if possible - File file = fileUploadSection.getFile(event); - byte[] file_bytes = readFileBytes(file); - boolean[] usedInso = new boolean[1]; - String file_content = convertBytes(file_bytes, textType, usedInso); - // ToDo if (TextMimeType.MIME_TEXT_HTML.equals(mime.getMimeType())) { - file_content = extractHTMLBody(file_content); - // } - final PageState state = event.getPageState(); - fileUploadContent.set(state, file_content); - fileUploadUsedINSO.set(state, usedInso[0]); - } - - /** - * Process file upload. Must be validated first. - */ - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - // Get the text asset or create a new one - final String text = textBody.getText(state); - final File file = fileUploadSection.getFile(event); - // Get info created during validation - final String uploadContent = (String) fileUploadContent.get(state); - boolean usedINSO = (Boolean) fileUploadUsedINSO.get(state); - // Set the mime type - // final MimeType mime = fileUploadSection.getMimeType(event); - // if (usedINSO) { - // mime = MimeType.loadMimeType("text/html"); - // } - // if (mime != null) { - // text.setMimeType(mime); - // } - // Save the uploaded content - //ToDo text.setText(uploadContent); - //t.setName(fileName); // ??? - // file = null; - // Save everything - textBody.updateText(state, text); - // if (text.isNew() || text.isModified()) { - // text.save(); - // } - } - - /** - * @return the save/cancel section for this form - */ - public SaveCancelSection getSaveCancelSection() { - return saveCancelSection; - } - - /** - * @return the save/cancel section for this form - */ - public FileUploadSection getFileUploadSection() { - return fileUploadSection; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/PageTextForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/PageTextForm.java deleted file mode 100644 index 0ffd6d471..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/PageTextForm.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.cms.ui.CMSDHTMLEditor; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CMSConfig; -import org.libreccm.l10n.LocalizedString; -import org.librecms.CmsConstants; - -/** - * A form for editing the body of the text. - */ -public class PageTextForm - extends Form - implements FormInitListener, - FormProcessListener, - FormSubmissionListener { - - private final TextBody textBody; - - // private SingleSelect mimeWidget; - // private Label mimeLabel; - private TextArea textWidget; - private SaveCancelSection saveCancelSection; - /** - * The text entry widget - */ - public static final String TEXT_ENTRY = "text_entry"; - /** - * The mime type widget - */ - public static final String MIME_TYPE = "mime_type"; - - /** - * Construct a new PageTextForm - * - */ - public PageTextForm(final TextBody textBody) { - - super("PageTextForm", new ColumnPanel(2)); - - this.textBody = textBody; - - setMethod(Form.POST); - setEncType("multipart/form-data"); - - addWidgets(); - } - - private void addWidgets() { - - final ColumnPanel panel = (ColumnPanel) getPanel(); - panel.setBorder(false); - panel.setPadColor("#FFFFFF"); - panel.setColumnWidth(1, "20%"); - panel.setColumnWidth(2, "80%"); - panel.setWidth("100%"); - - add(new Label(new GlobalizedMessage( - "cms.ui.authoring.edit_body_text", - CmsConstants.CMS_BUNDLE)), - ColumnPanel.LEFT | ColumnPanel.FULL_WIDTH); - - textWidget = new CMSDHTMLEditor(PageTextForm.TEXT_ENTRY); - textWidget.setRows(25); - textWidget.setCols(40); - // cg - sets editor size - closer to actual published page - // width, and similar size as htmlarea. - // could be configurable - unset means default 100% x 400px - textWidget.setMetaDataAttribute("width", "575"); - textWidget.setMetaDataAttribute("height", "500"); - textWidget.setWrap(CMSDHTMLEditor.SOFT); - add(textWidget, ColumnPanel.LEFT - | ColumnPanel.FULL_WIDTH); - - saveCancelSection = new SaveCancelSection(); - add(saveCancelSection, ColumnPanel.FULL_WIDTH); - - // optionally, we clear the text of MSWord tags every time - // the text is submitted/saved - if (CMSConfig.getConfig().isSaveTextCleansWordTags()) { - saveCancelSection.getSaveButton().setOnClick( - "wordClean_" - + PageTextForm.TEXT_ENTRY - + "();"); - } - - addInitListener(this); - addProcessListener(this); - - } - - // These are here so that TemplateBody can set them. - // public final void setMimeWidget(final SingleSelect widget) { - // mimeWidget = widget; - // } - public final void setTextWidget(final TextArea widget) { - textWidget = widget; - } - - public final void setSaveCancel(final SaveCancelSection widget) { - saveCancelSection = widget; - } - - /** - * Initialise the text area with the current value. - * - * @param event - * - * @throws FormProcessException - */ - public void init(final FormSectionEvent event) throws FormProcessException { - - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - - final String text = textBody.getText(state); - - if (text != null) { - data.put(TEXT_ENTRY, text); - } - } - - /** - * Cancels streamlined editing. - * - * @param event - */ - @Override - public void submitted(final FormSectionEvent event) { - - if (getSaveCancelSection() - .getCancelButton() - .isSelected(event.getPageState())) { - - textBody.cancelStreamlinedCreation(event.getPageState()); - } - } - - // process: update the mime type and content - @Override - public void process(final FormSectionEvent event) throws - FormProcessException { - - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - final String text = (String) data.get(TEXT_ENTRY); - textBody.updateText(state, text); - - textBody.maybeForwardToNextStep(event.getPageState()); - } - - /** - * @return the save/cancel section for this form - */ - public SaveCancelSection getSaveCancelSection() { - return saveCancelSection; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ResettableContainer.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ResettableContainer.java deleted file mode 100755 index 357674f6e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/ResettableContainer.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.SimpleContainer; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * A container which implements the {@link Resettable} interface and provides - * other useful methods. - * - * @author Phong Nguyen - * @author Jens Pelzetter - */ -public class ResettableContainer extends SimpleContainer implements Resettable { - - /** - * A list of all resettable components in this container - */ - private final List resettableComponents = new ArrayList<>(); - - /** - * A list of all components that are not visible by default - */ - private final List componentsNotVisibleByDefault - = new ArrayList<>(); - - /** - * Constructs a new, empty {@code RessetableContainer}. - * - */ - public ResettableContainer() { - super(); - } - - /** - * Constructs a new, empty {@code ResettableContainer}. - * - * @param key The key for this container. - * - */ - public ResettableContainer(final String key) { - super(); - setKey(key); - } - - /** - * Constructs a new, empty {@code RessetableContainer}. The container will - * wrap its children in the specified tag. - * - * @param tag The name of the XML element that will be used to wrap - * the children of this container. - * @param namespace The namespace for the tag. - * - */ - public ResettableContainer(final String tag, final String namespace) { - super(tag, namespace); - } - - /** - * Adds a component to container. - * - * @param component The component to be added. - * - */ - @Override - public void add(final Component component) { - add(component, true); - } - - /** - * Add a component to this container - * - * @param component The component to be added. - * @param constraints This parameter is ignored. Child classes should - * override the add method if they wish to provide - * special handling of constraints. - * - */ - @Override - public void add(final Component component, final int constraints) { - add(component); - } - - /** - * Adds the component to this pane with the specified default visibility. - * - * @param component - * @param defaultVisibility The default visibility of this component - * - * - */ - public void add(final Component component, - final boolean defaultVisibility) { - - super.add(component); - if (component instanceof Resettable) { - resettableComponents.add(component); - } - if (!defaultVisibility) { - componentsNotVisibleByDefault.add(component); - } - } - - /** - * Sets the visibility of all child components to false, except for the - * component with the specified key. - * - * @param state The state of the current request. - * @param key The key of the component. There will be no visibility - * changes if key is null. - * - */ - public void onlyShowComponent(final PageState state, - final String key) { - - if (key == null) { - return; - } - - @SuppressWarnings("unchecked") - final Iterator iter = children(); - Component child; - while (iter.hasNext()) { - child = iter.next(); - child.setVisible(state, key.equals(child.getKey())); - } - } - - /** - * Sets the visibility of all child components to false, except for the - * specified component. - * - * @param state The state of the current request. - * @param component The key of the component. There will be no visibility - * changes if {@code component} is null. - * - */ - public void onlyShowComponent(final PageState state, - final Component component) { - - if (component == null) { - return; - } - - @SuppressWarnings("unchecked") - final Iterator iter = children(); - Component child; - while (iter.hasNext()) { - child = iter.next(); - child.setVisible(state, child.equals(component)); - } - } - - /** - * Resets all resettable components added to this container. - * - * @param state The state of the current request. - * - */ - @Override - public void reset(final PageState state) { - // Reset all resettable components automatically - final Iterator iter = resettableComponents.iterator(); - while (iter.hasNext()) { - ((Resettable) iter.next()).reset(state); - } - } - - /** - * Registers with page that this container belongs to and sets the default - * visibility of child components. - * - * @param page The page this container belongs to. - * - */ - @Override - public void register(final Page page) { - final Iterator iter = componentsNotVisibleByDefault - .iterator(); - while (iter.hasNext()) { - page.setVisibleDefault(iter.next(), false); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/SelectedLanguageUtil.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/SelectedLanguageUtil.java deleted file mode 100644 index 9e005c042..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/SelectedLanguageUtil.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.kernel.KernelConfig; - -import java.util.Locale; - -/** - * - * @author Jens Pelzetter - */ -public class SelectedLanguageUtil { - - private SelectedLanguageUtil() { - //Nothing - } - - public static final Locale selectedLocale( - final PageState state, - final StringParameter selectedLanguageParam) { - - final String selectedLanguage = (String) state - .getValue(selectedLanguageParam); - if (selectedLanguage == null) { - return KernelConfig.getConfig().getDefaultLocale(); - } else { - return new Locale(selectedLanguage); - } - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/SimpleEditStep.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/SimpleEditStep.java deleted file mode 100755 index fa44a872b..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/SimpleEditStep.java +++ /dev/null @@ -1,353 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.RequestEvent; -import com.arsdigita.bebop.event.RequestListener; -import com.arsdigita.bebop.parameters.StringParameter; - -import org.librecms.contentsection.ContentItem; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.ContentItemPage; -import com.arsdigita.cms.ui.SecurityPropertyEditor; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.ComponentAccess; -import com.arsdigita.toolbox.ui.DomainObjectPropertySheet; - -import java.text.DateFormat; - -import java.util.ArrayList; -import java.util.List; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.CmsConstants; - -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.Arrays; -import java.util.Objects; -import java.util.Optional; - -/** - * A simple implementation of an Authoring Kit editing step. Extends - * {@link SecurityPropertyEditor} and provides authoring kit integration. See - * the authoring kit documentation for more info. - * - * Child classes should a). call setDisplayComponent() b). call add() zero or - * more times - * - * @author Stanislav Freidin - * @author Jens Pelzetter - */ -public class SimpleEditStep extends SecurityPropertyEditor - implements AuthoringStepComponent, RequestListener { - - private AuthoringKitWizard authoringKitWizard; - private ItemSelectionModel itemSelectionModel; - private String defaultEditKey = null; - - private StringParameter streamlinedCreationParameter; - private static final String STREAMLINED = "_streamlined"; - private static final String STREAMLINED_DONE = "1"; - - private final StringParameter selectedLanguageParameter; - - private static List additionalDisplayComponents - = new ArrayList<>(); - - /** - * allow additional display components to be added to all implementations of - * SimpleEditStep. This allows shared optional packages such as notes to - * display information on the initial authoring page of all content types - * without causing dependencies from ccm-cms. - * - * Any additional components must be added before the edit step is created. - * An initialiser is a suitable location - * - * @param additionalDisplayComponent - */ - public static void addAdditionalDisplayComponent( - AdditionalDisplayComponent additionalDisplayComponent) { - - additionalDisplayComponents.add(additionalDisplayComponent); - } - - /** - * Construct a new SimpleEditStep component - * - * @param itemModel The {@link ItemSelectionModel} which will be - * responsible for loading the current item - * - * @param parent The parent wizard which contains the form. - * The component may use the wizard's methods, - * such as stepForward and stepBack, in its - * process listener. - * @param selectedLanguageParam - */ - public SimpleEditStep(final ItemSelectionModel itemModel, - final AuthoringKitWizard parent, - final StringParameter selectedLanguageParam) { - this(itemModel, parent, selectedLanguageParam, ""); - } - - /** - * Construct a new SimpleEditStep component - * - * @param itemSelectionModel The {@link ItemSelectionModel} which will be - * responsible for loading the current item - * - * @param authoringKitWizard The parent wizard which contains the form. The - * component may use the wizard's methods, such as - * stepForward and stepBack, in its process - * listener. - * @param selectedLanguageParam - * - * @param parameterSuffix Additional global parameter name suffix if - * there are multiple SimpleEditStep instances in - * an authoring kit. - */ - public SimpleEditStep(final ItemSelectionModel itemSelectionModel, - final AuthoringKitWizard authoringKitWizard, - final StringParameter selectedLanguageParam, - final String parameterSuffix) { - - super(); - - Objects.requireNonNull(selectedLanguageParam); - - this.authoringKitWizard = authoringKitWizard; - this.itemSelectionModel = itemSelectionModel; - - this.selectedLanguageParameter = selectedLanguageParam; - - streamlinedCreationParameter = new StringParameter( - authoringKitWizard.getContentType().getContentItemClass().getName() - + "_properties_done" + parameterSuffix); - - authoringKitWizard - .getList() - .addActionListener(event -> showDisplayPane(event.getPageState())); - - additionalDisplayComponents - .stream() - .forEach(component -> { - component.setItemSelectionModel(itemSelectionModel); - addDisplayComponent(component); - }); - } - - /** - * Registers global state parameter for cancelling streamlined creation - * - * @param page - */ - @Override - public void register(final Page page) { - - super.register(page); - page.addGlobalStateParam(streamlinedCreationParameter); - page.addRequestListener(this); - } - - /** - * @return the parent wizard - */ - public AuthoringKitWizard getParentWizard() { - return authoringKitWizard; - } - - /** - * @return The item selection model - */ - public ItemSelectionModel getItemSelectionModel() { - return itemSelectionModel; - } - - /** - * Forward to the next step if the streamlined creation parameter is turned - * on _and_ the streamlined_creation global state parameter is set to - * 'active' - * - * @param state the PageState - */ - public void maybeForwardToNextStep(final PageState state) { - if (ContentItemPage.isStreamlinedCreationActive(state) - && !STREAMLINED_DONE.equals(state.getValue( - streamlinedCreationParameter))) { - state.setValue(streamlinedCreationParameter, STREAMLINED_DONE); - fireCompletionEvent(state); - } - } - - /** - * Cancel streamlined creation for this step if the streamlined creation - * parameter is turned on _and_ the streamlined_creation global state param - * is set to 'active' - * - * @param state the PageState - */ - public void cancelStreamlinedCreation(final PageState state) { - - if (ContentItemPage.isStreamlinedCreationActive(state)) { - state.setValue(streamlinedCreationParameter, STREAMLINED_DONE); - } - } - - public void setDefaultEditKey(final String key) { - defaultEditKey = key; - } - - /** - * Open the edit component if the streamlined creation parameter is turned - * on _and_ the streamlined_creation global state param is set to 'active' - * - * @param e - */ - @Override - public void pageRequested(final RequestEvent e) { - PageState state = e.getPageState(); - - // XXX: This method is called on every page request for every authoring - // step in every authoring kit. This has in the past revealed a caching - // side-effect bug, but should in the main be harmless. Except of course - // for performance. - // Ideally this method would only be called for a single authoring step - // on each page load. However, at the stage that this is called, - // visibility has not been set, and getting the selected authoring kit - // or component is not straightforward, and would almost certainly - // involve duplicating code. - // This need to be rethought. - //if( !state.isVisibleOnPage( this ) ) return; - if (defaultEditKey != null && itemSelectionModel.getSelectedItem(state) - != null) { - - final ComponentAccess componentAccess = getAccessMap() - .get(defaultEditKey); - - if (ContentItemPage.isStreamlinedCreationActive(state) - && !STREAMLINED_DONE - .equals(state.getValue(streamlinedCreationParameter)) - && componentAccess != null - && componentAccess.canAccess(state)) { - showComponent(state, defaultEditKey); - } - } - - } - - /** - * Public class which implements an AttributeFormatter interface for boolean - * values. Its format(...) class returns a string representation for either - * a false or a true value. - */ - protected static class LaunchDateAttributeFormatter - implements DomainObjectPropertySheet.AttributeFormatter { - - /** - * Constructor, does nothing. - */ - public LaunchDateAttributeFormatter() { - } - - /** - * Formatter for the value of a (LaunchDate) attribute. - * - * It currently relays on the prerequisite that the passed in property - * attribute is in fact a date property. No type checking yet! - * - * Note: the format method has to be executed at each page request. Take - * care to properly adjust globalisation and localisation here! - * - * @param object Object containing the attribute to format. - * @param attribute Name of the attribute to retrieve and format - * @param state PageState of the request - * - * @return A String representation of the retrieved boolean attribute of - * the domain object. - */ - @Override - public String format(final Object object, - final String attribute, - final PageState state) { - - if (object != null && object instanceof ContentItem) { - - final ContentItem page = (ContentItem) object; - final BeanInfo beanInfo; - try { - beanInfo = Introspector - .getBeanInfo(page.getClass()); - } catch (IntrospectionException ex) { - throw new UnexpectedErrorException(ex); - } - final Optional propertyDescriptor = Arrays - .stream(beanInfo.getPropertyDescriptors()) - .filter(propDesc -> attribute.equals(propDesc.getName())) - .findAny(); - if (propertyDescriptor.isPresent()) { - final Method readMethod = propertyDescriptor - .get() - .getReadMethod(); - final Object value; - try { - value = readMethod.invoke(object); - } catch (IllegalAccessException | InvocationTargetException ex) { - throw new IllegalArgumentException(ex); - } - if (value == null) { - return (String) new GlobalizedMessage("cms.ui.unknown", - CmsConstants.CMS_BUNDLE) - .localize(); - } else { - final GlobalizationHelper globalizationHelper = CdiUtil - .createCdiUtil() - .findBean(GlobalizationHelper.class); - - // Note: No type safety here! We relay that it is - // attached to a date property! - return DateFormat.getDateInstance( - DateFormat.LONG, - globalizationHelper.getNegotiatedLocale()) - .format(value); - } - } else { - return (String) new GlobalizedMessage("cms.ui.unknown", - CmsConstants.CMS_BUNDLE) - .localize(); - } - - } else { - return (String) new GlobalizedMessage("cms.ui.unknown", - CmsConstants.CMS_BUNDLE) - .localize(); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/TextAssetBodyLabelCellRenderer.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/TextAssetBodyLabelCellRenderer.java deleted file mode 100755 index 33f734be3..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/TextAssetBodyLabelCellRenderer.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.PageState; - - -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Component; - -import org.libreccm.l10n.LocalizedString; - -// Renders strings as labels -public class TextAssetBodyLabelCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - throw new UnsupportedOperationException("ToDo"); - -// final Label label; -// if ("content".equals(key) && value instanceof LocalizedString) { -// // We have different styles for different mime types -// final LocalizedString asset = (LocalizedString )value; -// label = new Label(asset.getText()); -// label.setIdAttr("webPage"); -// String type = asset.getMimeType().getMimeType() -// .toLowerCase(); -// if (type.indexOf("text/xml") > -1 || -// type.indexOf("text/xsl") > -1 || -// type.indexOf("text/x-jsp") > -1) { -// label.setClassAttr("preformatted"); -// label.setOutputEscaping(true); -// } else { -// label.setOutputEscaping(false); -// } -// } else if (MIME_TYPE_KEY.equals(key) && value instanceof TextAsset) { -// label = new Label(((TextAsset)value).getMimeType().getLabel(), -// false); -// } else { -// label = new Label(value.toString()); -// label.setOutputEscaping(false); -// } -// -// return label; - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/TextBody.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/TextBody.java deleted file mode 100755 index 5c275030e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/TextBody.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.event.RequestEvent; -import com.arsdigita.bebop.event.RequestListener; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.parameters.StringParameter; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.ContentItemPage; -import com.arsdigita.cms.ui.FileUploadSection; -import com.arsdigita.cms.ui.SecurityPropertyEditor; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.DomainObjectPropertySheet; - -import org.librecms.CMSConfig; -import org.libreccm.l10n.LocalizedString; -import org.librecms.CmsConstants; - -/** - * Displays the mime-type and the body of a single {@code TextAsset}. Maintains - * a form or uploading files into the text body of the asset, and a form for - * editing the text of the asset. - *

- * Unlike most other authoring components, this component does not require the - * asset to exist. If the asset does not exist (i.e., if - * !m_assetModel.isSelected(state)), the upload and editing forms - * will create a new asset and set it in the model by calling - * setSelectedObject on the asset selection model. Child classes - * should override the {@link #createTextAsset(PageState)} method in to create a - * valid text asset. - *

- * This component is used primarily in {@link GenericArticleBody} and - * {@link com.arsdigita.cms.ui.templates.TemplateBody} - * - * Note: In CCM NG (version 7 and newer) {@code TextAsset} does not - * longer exist. Instead fields of type {@link LocalizedString} are used. This - * class has been adapted to use {@link LocalizedString}. The name of the class - * etc. has been kept to make the migration easier. - * - * @author Stanislav Freidin (sfreidin@arsdigita.com) - * @version Jens Pelzetter - */ -public abstract class TextBody - extends SecurityPropertyEditor - implements Resettable, AuthoringStepComponent, RequestListener { - - public static final String FILE_UPLOAD = "file"; - public static final String TEXT_ENTRY = "text"; - - private static final String STREAMLINED_DONE = "1"; - private static final CMSConfig CMS_CONFIG = CMSConfig.getConfig(); - - private final StringParameter streamlinedCreationParam; - private final StringParameter selectedLanguageParam; - private final ItemSelectionModel itemSelectionModel; - - /** - * Construct a new GenericArticleBody component - * - * @param assetModel The {@link ItemSelectionModel} which will be - * responsible for maintaining the current - * asset - * @param selectedLanguageParam Parameter for the currently selected locale. - */ - public TextBody(final ItemSelectionModel assetModel, - final StringParameter selectedLanguageParam) { - - this(assetModel, null, selectedLanguageParam); - } - - /** - * Construct a new GenericArticleBody component - * - * @param itemSelectionModel The {@link ItemSelectionModel} which will be - * responsible for maintaining the current asset - * @param authoringKitWizard The parent wizard which contains the form. - * The form may use the wizard's methods, such - * as stepForward and stepBack, in its process - * listener. - * @param selectedLangugeParam Parameter for the currently selected locale. - */ - public TextBody(final ItemSelectionModel itemSelectionModel, - final AuthoringKitWizard authoringKitWizard, - final StringParameter selectedLangugeParam) { - - super(); - this.itemSelectionModel = itemSelectionModel; - - if (authoringKitWizard == null) { - streamlinedCreationParam = new StringParameter("item_body_done"); - } else { - streamlinedCreationParam = new StringParameter( - String.format("%s_body_done", - authoringKitWizard - .getContentType() - .getContentItemClass() - .getName())); - } - - this.selectedLanguageParam = selectedLangugeParam; - - if (!CMS_CONFIG.isHideTextAssetUploadFile()) { - final PageFileForm pageFileForm = getPageFileForm(); - add(FILE_UPLOAD, - new GlobalizedMessage("cms.ui.upload", CmsConstants.CMS_BUNDLE), - pageFileForm, - pageFileForm.getSaveCancelSection().getCancelButton()); - } - - final PageTextForm pageTextForm = new PageTextForm(this); - add(TEXT_ENTRY, - new GlobalizedMessage("cms.ui.edit", CmsConstants.CMS_BUNDLE), - pageTextForm, - pageTextForm.getSaveCancelSection().getCancelButton()); - - // Specify full path to properties of the text asset - final DomainObjectPropertySheet sheet = getTextBodyPropertySheet( - itemSelectionModel); - sheet.add(new GlobalizedMessage("cms.ui.article.text", - CmsConstants.CMS_BUNDLE), - getTextPropertyName()); - - setDisplayComponent(sheet); - - getDisplayPane().setClassAttr("invertedPropertyDisplay"); - - } - - /** - * Determines the name of the property holding the text. - * - * @return The name of the property holding the text. - */ - protected abstract String getTextPropertyName(); - - protected DomainObjectPropertySheet getTextBodyPropertySheet( - final ItemSelectionModel itemSelectionModel) { - - final DomainObjectPropertySheet sheet = new DomainObjectPropertySheet( - itemSelectionModel); - - return sheet; - -// return new TextBodyPropertySheet(itemSelectionModel, -// selectedLanguageParam); - } - - /** - * Adds the options for the mime type select widget of - * GenericArticleForm and sets the default mime type. - * - * @param mimeSelect - */ - protected void setMimeTypeOptions(final SingleSelect mimeSelect) { - FileUploadSection.addMimeOptions(mimeSelect, "text"); - mimeSelect.setOptionSelected("text/html"); - } - - /** - * To be overwritten by subclasses, should return the text for the currently - * selected locale. - * - * @param state The current page state - * - * @return The text of the currently selected locale. - */ - public abstract String getText(final PageState state); - - /** - * Reset this component to its original state - * - * @param state the current page state - */ - @Override - public void reset(final PageState state) { - showDisplayPane(state); - } - - /** - * Update the text for the currently selected locale. - * - * @param state the current page state - * @param text the new next text for the currently selected locale. - */ - protected abstract void updateText(PageState state, String text); - - /** - * Return the ItemSelectionModel which will be used to maintain - * the current text asset - * - * @return - */ - public ItemSelectionModel getItemSelectionModel() { - return itemSelectionModel; - } - - /** - * Forward to the next step if the streamlined creation parameter is turned - * on _and_ the streamlined_creation global state parameter is set to - * 'active' - * - * @param state the PageState - */ - protected void maybeForwardToNextStep(final PageState state) { - if (ContentItemPage.isStreamlinedCreationActive(state) - && !STREAMLINED_DONE. - equals(state.getValue(streamlinedCreationParam))) { - state.setValue(streamlinedCreationParam, STREAMLINED_DONE); - fireCompletionEvent(state); - } - } - - /** - * Cancel streamlined creation for this step if the streamlined creation - * parameter is turned on _and_ the streamlined_creation global state param - * is set to 'active' - * - * @param state the PageState - */ - protected void cancelStreamlinedCreation(final PageState state) { - if (ContentItemPage.isStreamlinedCreationActive(state)) { - state.setValue(streamlinedCreationParam, STREAMLINED_DONE); - } - } - - /** - * Open the edit component if the streamlined creation parameter is turned - * on _and_ the streamlined_creation global state param is set to 'active' - * - * @param event - */ - @Override - public void pageRequested(final RequestEvent event) { - - final PageState state = event.getPageState(); - - if (ContentItemPage.isStreamlinedCreationActive(state) - && !STREAMLINED_DONE. - equals(state.getValue(streamlinedCreationParam))) { - showComponent(state, TEXT_ENTRY); - } - //} - - } - - /** - * This is the form that is used to upload files. This method can be used so - * that a subclass can use their own subclass of PageFileForm. - * - * @return The form for uploading a text. - */ - protected PageFileForm getPageFileForm() { - return new PageFileForm(this); - } - - protected String getDefaultMimeType() { - return "text/plain"; - } - - /** - * Registers global state parameter for cancelling streamlined creation - */ - @Override - public void register(final Page page) { - super.register(page); - page.addGlobalStateParam(streamlinedCreationParam); - page.addRequestListener(this); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/TextBodyPropertySheet.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/TextBodyPropertySheet.java deleted file mode 100755 index 1bbfac4a4..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/TextBodyPropertySheet.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (C) 2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.PropertySheet; -import com.arsdigita.bebop.PropertySheetModel; -import com.arsdigita.bebop.PropertySheetModelBuilder; -import com.arsdigita.util.LockableImpl; -import com.arsdigita.toolbox.ui.DomainObjectPropertySheet; - -import java.util.Iterator; - -import com.arsdigita.globalization.GlobalizedMessage; - -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; - -import org.libreccm.l10n.LocalizedString; - -/** - * This extends DomainObjectPropertySheet and has a lot of duplicate code from - * it because it uses so many private inner classes - * - */ -public class TextBodyPropertySheet extends DomainObjectPropertySheet { - - /** - * Construct a new TextAssetBodyPropertySheet - * - * @param objModel The selection model which feeds domain - * objects to this property sheet. - * @param selectedLanguageParam - * - */ - public TextBodyPropertySheet( - final ItemSelectionModel objModel, - final StringParameter selectedLanguageParam) { - - super(objModel, false, selectedLanguageParam); - setModelBuilder(new TMBAdapter(new DomainObjectModelBuilder())); - getColumn(1).setCellRenderer(new TextAssetBodyLabelCellRenderer()); - } - - // Build up the object properties model from the iterator over all properties - private static class TextAssetBodyPropertiesModel - implements PropertySheetModel { - -// public final static String MIME_TYPE_KEY -// = TextAssetBodyLabelCellRenderer.MIME_TYPE_KEY; - private static final String ERROR = "No current property. " - + "Make sure that nextRow() was " - + "called at least once."; - - private LocalizedString textAsset; - private PageState pageState; - private Iterator properties; - private Property currentProperty; - - public TextAssetBodyPropertiesModel(final LocalizedString textAsset, - final Iterator properties, - final PageState pageState) { - this.textAsset = textAsset; - this.properties = properties; - this.pageState = pageState; - currentProperty = null; - } - - @Override - public boolean nextRow() { - - if (properties.hasNext()) { - currentProperty = properties.next(); - return true; - } else { - return false; - } - } - - /** - * @deprecated use getGlobalizedLabel() instead - */ - @Override - @Deprecated - public String getLabel() { - return getGlobalizedLabel().getKey(); - } - - @Override - public GlobalizedMessage getGlobalizedLabel() { - if (currentProperty == null) { - throw new IllegalStateException(ERROR); - } - return currentProperty.getGlobalizedLabel(); - } - - @Override - public String getValue() { - return getObjectValue().toString(); - } - - public Object getObjectValue() { - if (currentProperty == null) { - throw new IllegalStateException(ERROR); - } - - return textAsset; - } - - public String getAttribute() { - return currentProperty.getAttribute(); - } - - } - - // Builds an TextAssetBodyPropertiesModel - private static class DomainObjectModelBuilder extends LockableImpl - implements PropertySheetModelBuilder { - - @Override - public PropertySheetModel makeModel(final PropertySheet sheet, - final PageState state) { - - TextBodyPropertySheet propSheet - = (TextBodyPropertySheet) sheet; - throw new UnsupportedOperationException("ToDo"); - } - - } - - // These are both from PropertySheet - // Convert a PropertySheetModelBuilder to a TableModelBuilder - private static class TMBAdapter - extends LockableImpl implements TableModelBuilder { - - private final PropertySheetModelBuilder modelBuilder; - - public TMBAdapter(final PropertySheetModelBuilder builder) { - this.modelBuilder = builder; - } - - @Override - public TableModel makeModel(final Table table, - final PageState state) { - return new TableModelAdapter( - (TextAssetBodyPropertiesModel) modelBuilder.makeModel( - (PropertySheet) table, state)); - } - - @Override - public void lock() { - modelBuilder.lock(); - super.lock(); - } - - } - - // Wraps a PropertySheetModel - private static class TableModelAdapter implements TableModel { - - private final TextAssetBodyPropertiesModel propertiesModel; - private int row; - - public TableModelAdapter( - final TextAssetBodyPropertiesModel propertiesModel) { - - this.propertiesModel = propertiesModel; - row = -1; - } - - @Override - public int getColumnCount() { - return 2; - } - - @Override - public boolean nextRow() { - row++; - return propertiesModel.nextRow(); - } - - @Override - public Object getElementAt(final int columnIndex) { - if (columnIndex == 0) { - return propertiesModel.getGlobalizedLabel(); - } else { - return propertiesModel.getObjectValue(); - } - } - - @Override - public Object getKeyAt(final int columnIndex) { - return propertiesModel.getAttribute(); - } - - public PropertySheetModel getPSModel() { - return propertiesModel; - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/WizardSelector.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/WizardSelector.java deleted file mode 100755 index b5d990d37..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/WizardSelector.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.parameters.LongParameter; - -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentType; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.kernel.ui.ACSObjectSelectionModel; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.xml.Element; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contenttypes.AuthoringKitInfo; -import org.librecms.contenttypes.ContentTypeInfo; - - -/** - * An invisible component which contains all the possible authoring kits. The - * kits are loaded from the database at construction time. The selector chooses - * which kit to display at page rendering time based on the value of the - * content_type state parameter. - * - * Essentially, this component is a hack which is used to get around the fact - * that we cannot instantiate stateful components dynamically. - * - * @author unknown - * @author Jens Pelzetter - */ -public class WizardSelector extends AuthoringKitSelector - implements Resettable { - - private final ItemSelectionModel itemSelectionModel; - - /** - * Construct a new WizardSelector. Load all the possible authoring kits from - * the database and construct wizards for them. - * - * @param model the {@link ItemSelectionModel} which will supply the - * wizard with its item - * - * @param typeModel the {@link ACSObjectSelectionModel} which will supply - * the default content type - * - * @pre itemModel != null - */ - public WizardSelector(final ItemSelectionModel model, - final SingleSelectionModel typeModel) { - super(typeModel); - itemSelectionModel = model; - super.processKit(); - } - - /** - * Get the wizard for the given kit. - * - * @param kit - * @param type - * - * @return - */ - @Override - public Component instantiateKitComponent(final AuthoringKitInfo kit, - final ContentTypeInfo type) { - - final ItemSelectionModel itemModel = new ItemSelectionModel( - type, (LongParameter) itemSelectionModel.getStateParameter()); - - final AuthoringKitWizard wizard - = new AuthoringKitWizard(type, itemModel); - return wizard; - } - - /** - * @return The item selection model used by this wizard - */ - public ItemSelectionModel getSelectionModel() { - return itemSelectionModel; - } - - // Determine the current wizard - private Component getCurrentWizard(PageState state) { - - // Get the current item and extract its content type - if (!itemSelectionModel.isSelected(state)) { - throw new UncheckedWrapperException("No item selected."); - } - - final ContentItem item = itemSelectionModel.getSelectedObject(state); - -// final ContentType type = item.getContentType(); -// final String typeClass; -// -// if (type == null) { -// // Try to get the default content type -// typeClass = getComponentSelectionModel().getSelectedKey(state); -// if (typeClass == null || typeClass.isEmpty()) { -// throw new UncheckedWrapperException("Content type is missing"); -// } -// } else { -// typeClass = type.getContentItemClass(); -// } - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final WizardSelectorController controller = cdiUtil - .findBean(WizardSelectorController.class); - - final String typeClass = controller.getTypeClass(item); - - // Return the selected wizard - return getComponent(typeClass); - } - - // Choose the right wizard and run it - @Override - public void generateXML(final PageState state, final Element parent) { - - final Component component = getCurrentWizard(state); - - if (component == null) { - throw new UncheckedWrapperException("No Wizard."); - } - - component.generateXML(state, parent); - } - - /** - * Reset the state of the current wizard - */ - @Override - public void reset(final PageState state) { - final Resettable resettable = (Resettable) getCurrentWizard(state); - if (resettable != null) { - resettable.reset(state); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/WizardSelectorController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/WizardSelectorController.java deleted file mode 100644 index 0494697aa..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/WizardSelectorController.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring; - -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentType; - -import java.util.Objects; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -public class WizardSelectorController { - - @Inject - private ContentItemRepository itemRepo; - - @Transactional(Transactional.TxType.REQUIRED) - public String getTypeClass(final ContentItem item) { - - Objects.requireNonNull(item); - - final ContentItem contentItem = itemRepo - .findById(item.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", - item.getObjectId()))); - - final ContentType type = contentItem.getContentType(); - - return type.getContentItemClass(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/ArticlePropertiesStep.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/ArticlePropertiesStep.java deleted file mode 100755 index d991c8fde..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/ArticlePropertiesStep.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.article; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; - -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.BasicPageForm; -import com.arsdigita.cms.ui.workflow.WorkflowLockedComponentAccess; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.DomainObjectPropertySheet; - -import org.librecms.CmsConstants; - -import java.util.Objects; - -/** - * Authoring step to edit the simple attributes of the Article content type (and - * its subclasses). The attributes edited are 'name', 'title', 'article date', - * 'location', 'lead', and 'article type'. This authoring step replaces the - * {@code com.arsdigita.ui.authoring.PageEdit} step for this type. - */ -public class ArticlePropertiesStep extends GenericArticlePropertiesStep { - - /** - * The name of the editing sheet added to this step - */ - public final static String EDIT_SHEET_NAME = "edit"; - - private final StringParameter selectedLanguageParam; - - public ArticlePropertiesStep(final ItemSelectionModel itemModel, - final AuthoringKitWizard parent, - final StringParameter selectedLanguageParam) { - - super(itemModel, parent, selectedLanguageParam); - - Objects.requireNonNull(selectedLanguageParam); - - this.selectedLanguageParam = selectedLanguageParam; - } - - @Override - protected void createEditSheet(final ItemSelectionModel itemModel, - final StringParameter selectedLanguageParam) { - - final BasicPageForm editSheet = new ArticlePropertyForm( - itemModel, - this, - selectedLanguageParam); - add(EDIT_SHEET_NAME, - new GlobalizedMessage("cms.ui.edit", CmsConstants.CMS_BUNDLE), - new WorkflowLockedComponentAccess(editSheet, itemModel), - editSheet.getSaveCancelSection().getCancelButton()); - } - - @Override - protected void setDisplayComponent( - final ItemSelectionModel itemModel) { - setDisplayComponent(getArticlePropertySheet(itemModel, - selectedLanguageParam)); - } - - /** - * Returns a component that displays the properties of the Article specified - * by the ItemSelectionModel passed in. - * - * @param itemModel The ItemSelectionModel to use - * @param selectedLanguageParam - * - * @pre itemModel != null - * @return A component to display the state of the basic properties of the - * release - */ - public static Component getArticlePropertySheet( - final ItemSelectionModel itemModel, - final StringParameter selectedLanguageParam) { - - final DomainObjectPropertySheet sheet - = (DomainObjectPropertySheet) getGenericArticlePropertySheet( - itemModel, - selectedLanguageParam); - - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.lead", - CmsConstants.CMS_BUNDLE), - "description"); - - return sheet; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/ArticlePropertyForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/ArticlePropertyForm.java deleted file mode 100755 index 64420f5f1..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/ArticlePropertyForm.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.article; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.parameters.NotEmptyValidationListener; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringInRangeValidationListener; -import com.arsdigita.bebop.parameters.StringParameter; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; - -import org.librecms.CMSConfig; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contenttypes.Article; - -import java.util.Locale; -import java.util.Objects; - -/** - * Form to edit the basic properties of an article. This form can be extended to - * create forms for Article subclasses. - */ -public class ArticlePropertyForm extends GenericArticlePropertyForm - implements FormProcessListener, FormInitListener, FormSubmissionListener { - - public static final String LEAD = "lead"; - - private final ArticlePropertiesStep propertiesStep; - private final StringParameter selectedLanguageParam; - - /** - * Creates a new form to edit the Article object specified by the item - * selection model passed in. - * - * @param itemModel The ItemSelectionModel to use to obtain the - * Article to work on - * @param selectedLanguageParam - */ - public ArticlePropertyForm(final ItemSelectionModel itemModel, - final StringParameter selectedLanguageParam) { - this(itemModel, null, selectedLanguageParam); - } - - /** - * Creates a new form to edit the Article object specified by the item - * selection model passed in. - * - * @param itemModel The ItemSelectionModel to use to obtain the - * Article to work on - * @param propertiesStep The ArticlePropertiesStep which controls - * this form. - * @param selectedLanguageParam - */ - public ArticlePropertyForm( - final ItemSelectionModel itemModel, - final ArticlePropertiesStep propertiesStep, - final StringParameter selectedLanguageParam) { - - super(itemModel, propertiesStep, selectedLanguageParam); - - Objects.requireNonNull(selectedLanguageParam); - - this.propertiesStep = propertiesStep; - this.selectedLanguageParam = selectedLanguageParam; - addSubmissionListener(this); - } - - /** - * Adds widgets to the form. - */ - @Override - protected void addWidgets() { - super.addWidgets(); - - ParameterModel leadParam = new StringParameter(LEAD); - if (CMSConfig.getConfig().isMandatoryDescriptions()) { - leadParam.addParameterListener( - new NotEmptyValidationListener( - new GlobalizedMessage( - "cms.contenttypes.ui.description_missing", - CmsConstants.CMS_BUNDLE))); - } - leadParam - .addParameterListener(new StringInRangeValidationListener(0, - 1000)); - TextArea lead = new TextArea(leadParam); - lead.setLabel(new GlobalizedMessage("cms.contenttypes.ui.lead", - CmsConstants.CMS_BUNDLE)); - lead.setHint(new GlobalizedMessage("cms.contenttypes.ui.lead_hint", - CmsConstants.CMS_BUNDLE)); - lead.setCols(40); - lead.setRows(5); - add(lead); - } - - @Override - public void validate(final FormSectionEvent event) throws - FormProcessException { - super.validate(event); - } - - /** - * Form initialisation hook. Fills widgets with data. - * - * @param event - */ - @Override - public void init(final FormSectionEvent event) { - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - final Article article = (Article) super.initBasicWidgets(event); - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - data.put(LEAD, article.getDescription().getValue(selectedLocale)); - } - - /** - * Cancels streamlined editing. - */ - @Override - public void submitted(final FormSectionEvent event) { - if (propertiesStep != null && getSaveCancelSection().getCancelButton() - .isSelected(event.getPageState())) { - propertiesStep.cancelStreamlinedCreation(event.getPageState()); - } - } - - /** - * Form processing hook. Saves Event object. - * - * @param event - */ - @Override - public void process(final FormSectionEvent event) { - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - - final Article article = (Article) super.processBasicWidgets(event); - - // save only if save button was pressed - if (article != null - && getSaveCancelSection().getSaveButton() - .isSelected(event.getPageState())) { - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - article - .getDescription() - .putValue(selectedLocale, (String) data.get(LEAD)); - - final ContentItemRepository itemRepo = CdiUtil - .createCdiUtil() - .findBean(ContentItemRepository.class); - itemRepo.save(article); - } - if (propertiesStep != null) { - propertiesStep.maybeForwardToNextStep(event.getPageState()); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/ArticleTextBody.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/ArticleTextBody.java deleted file mode 100755 index 7704c4590..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/ArticleTextBody.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.article; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.cms.ui.authoring.TextBody; - -import org.librecms.contenttypes.Article; - -import com.arsdigita.cms.ui.workflow.WorkflowLockedComponentAccess; -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentItemRepository; - -import java.util.Locale; - -/** - * Displays the current text body of the article and allows the user to edit it, - * by uploading a file or entering text in a text box. - * - * The {@link com.arsdigita.bebop.PropertySheet} class is often used as the - * display component in the default authoring kit steps of this class. - * - * @author Stanislav Freidin (sfreidin@arsdigita.com) - * @author Jens Pelzetter - */ -public class ArticleTextBody extends TextBody { - - private final AuthoringKitWizard authoringKitWizard; - private final ItemSelectionModel itemSelectionModel; - private final StringParameter selectedLanguageParam; - - /** - * Construct a new GenericArticleBody component - * - * @param itemSelectionModel The {@link ItemSelectionModel} which will be - * responsible for loading the current item - * - * @param authoringKitWizard The parent wizard which contains the form. - * The form may use the wizard's methods, such - * as stepForward and stepBack, in its process - * listener. - * @param selectedLanguageParam - */ - public ArticleTextBody(final ItemSelectionModel itemSelectionModel, - final AuthoringKitWizard authoringKitWizard, - final StringParameter selectedLanguageParam) { - - super(itemSelectionModel, selectedLanguageParam); - this.itemSelectionModel = itemSelectionModel; - this.authoringKitWizard = authoringKitWizard; - this.selectedLanguageParam = selectedLanguageParam; - - // Rest the component when it is hidden - authoringKitWizard - .getList() - .addActionListener(event -> reset(event.getPageState())); - - // Set the right component access on the forms - final Component uploadComponent = getComponent(FILE_UPLOAD); - if (uploadComponent != null) { - setComponentAccess(FILE_UPLOAD, - new WorkflowLockedComponentAccess( - uploadComponent, itemSelectionModel)); - } - final Component textEntryComponent = getComponent(TEXT_ENTRY); - setComponentAccess(TEXT_ENTRY, - new WorkflowLockedComponentAccess( - textEntryComponent, itemSelectionModel)); - } - - /** - * Adds the options for the mime type select widget of - * GenericArticleForm and sets the default mime type. - * - * @param mimeSelect - */ - @Override - protected void setMimeTypeOptions(final SingleSelect mimeSelect) { - mimeSelect.addOption(new Option("text/html", "HTML Text")); - mimeSelect.setOptionSelected("text/html"); - } - - /** - * Updates the text for the currently selected locale. - * - * @param state the current page state - * @param text the new text for the currently selected locale - */ - @Override - protected void updateText(final PageState state, - final String text) { - - final Article article = getSelectedArticle(state); - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - article.getText().putValue(selectedLocale, text); - - final ContentItemRepository itemRepo = CdiUtil - .createCdiUtil() - .findBean(ContentItemRepository.class); - itemRepo.save(article); - } - - /** - * Get the current {@link Article} - * - * @param state The current page state. - * - * @return The currently selected article. - */ - protected Article getSelectedArticle(final PageState state) { - - return (Article) itemSelectionModel.getSelectedObject(state); - } - - @Override - protected String getTextPropertyName() { - return "text"; - } - - @Override - public String getText(final PageState state) { - - final Article article = getSelectedArticle(state); - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - return article.getText().getValue(selectedLocale); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/GenericArticlePropertiesStep.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/GenericArticlePropertiesStep.java deleted file mode 100755 index 9205bd1ad..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/GenericArticlePropertiesStep.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.article; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; - -import com.arsdigita.bebop.parameters.StringParameter; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.toolbox.ui.DomainObjectPropertySheet; -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.BasicPageForm; -import com.arsdigita.cms.ui.authoring.SimpleEditStep; -import com.arsdigita.cms.ui.workflow.WorkflowLockedComponentAccess; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CMSConfig; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; - -import java.text.DateFormat; -import java.util.Objects; - -/** - * Authoring step to edit the simple attributes of the GenericArticle content - * type (and its subclasses). The attributes edited are 'name', 'title', - * 'article date', 'location', and 'article type'. This authoring step replaces - * the {@code com.arsdigita.ui.authoring.PageEdit} step for this type. - */ -public class GenericArticlePropertiesStep extends SimpleEditStep { - - /** - * The name of the editing sheet added to this step - */ - public static final String EDIT_SHEET_NAME = "edit"; - - private DomainObjectPropertySheet domainObjectPropertySheet; - - private final StringParameter selectedLanguageParam; - - public GenericArticlePropertiesStep( - final ItemSelectionModel itemModel, - final AuthoringKitWizard parent, - final StringParameter selectedLanguageParam) { - - super(itemModel, parent, selectedLanguageParam); - - Objects.requireNonNull(selectedLanguageParam); - - this.selectedLanguageParam = selectedLanguageParam; - - setDefaultEditKey(EDIT_SHEET_NAME); - createEditSheet(itemModel, selectedLanguageParam); - - setDisplayComponent(itemModel); - } - - protected void createEditSheet(final ItemSelectionModel itemModel, - final StringParameter selectedLanguageParam) { - - final BasicPageForm editSheet = new GenericArticlePropertyForm( - itemModel, - this, - selectedLanguageParam); - add(EDIT_SHEET_NAME, - new GlobalizedMessage("cms.ui.edit", CmsConstants.CMS_BUNDLE), - new WorkflowLockedComponentAccess(editSheet, itemModel), - editSheet.getSaveCancelSection().getCancelButton()); - } - - protected void setDisplayComponent(final ItemSelectionModel itemModel) { - setDisplayComponent(getGenericArticlePropertySheet( - itemModel, - selectedLanguageParam)); - } - - protected StringParameter getSelectedLanguageParam() { - return selectedLanguageParam; - } - - /** - * Returns a component that displays the properties of the Article specified - * by the ItemSelectionModel passed in. - * - * @param itemModel The ItemSelectionModel to use - * @param selectedLanguageParam - * - * @pre itemModel != null - * @return A component to display the state of the basic properties of the - * release - */ - public static Component getGenericArticlePropertySheet( - final ItemSelectionModel itemModel, - final StringParameter selectedLanguageParam) { - - final DomainObjectPropertySheet sheet = new DomainObjectPropertySheet( - itemModel, - false, - selectedLanguageParam); - - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.title", - CmsConstants.CMS_BUNDLE), - "title"); - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.name", - CmsConstants.CMS_BUNDLE), - "name"); - if (!CMSConfig.getConfig().isHideLaunchDate()) { - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.launch_date", - CmsConstants.CMS_BUNDLE), - "launchDate", - new DomainObjectPropertySheet.AttributeFormatter() { - - @Override - public String format(final Object item, - final String attribute, - final PageState state) { - final ContentItem page = (ContentItem) item; - if (page.getLaunchDate() != null) { - return DateFormat - .getDateInstance(DateFormat.LONG) - .format(page.getLaunchDate()); - } else { - return (String) new GlobalizedMessage( - "cms.ui.unknown", - CmsConstants.CMS_BUNDLE) - .localize(); - } - } - - }); - } - return sheet; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/GenericArticlePropertyForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/GenericArticlePropertyForm.java deleted file mode 100755 index dbfedcbd9..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/article/GenericArticlePropertyForm.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.article; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; - -import org.librecms.contenttypes.Article; - -import com.arsdigita.cms.ui.authoring.BasicPageForm; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentItemRepository; - -/** - * Form to edit the basic properties of an article. This form can be extended to - * create forms for Article subclasses. - */ -public class GenericArticlePropertyForm extends BasicPageForm - implements FormProcessListener, FormInitListener, FormSubmissionListener { - - private GenericArticlePropertiesStep propertiesStep; - - /** - * Creates a new form to edit the Article object specified by the item - * selection model passed in. - * - * @param itemModel The ItemSelectionModel to use to obtain the Article to - * work on - * @param selectedLanguageParam - */ - public GenericArticlePropertyForm( - final ItemSelectionModel itemModel, - final StringParameter selectedLanguageParam) { - - this(itemModel, null, selectedLanguageParam); - } - - /** - * Creates a new form to edit the GenericArticle object specified by the - * item selection model passed in. - * - * @param itemModel The ItemSelectionModel to use to obtain the - * GenericArticle to work on - * @param step The GenericArticlePropertiesStep which controls this - * form. - * @param selectedLanguageParam - */ - public GenericArticlePropertyForm( - final ItemSelectionModel itemModel, - final GenericArticlePropertiesStep step, - final StringParameter selectedLanguageParam) { - - super(ID, itemModel, selectedLanguageParam); - propertiesStep = step; - addSubmissionListener(this); - } - - /** - * Adds widgets to the form. - */ - @Override - protected void addWidgets() { - super.addWidgets(); - } - - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - - super.validate(event); - } - - /** - * Form initialisation hook. Fills widgets with data. - * - * @param event - */ - @Override - public void init(final FormSectionEvent event) { - // Do some initialization hook stuff - final FormData data = event.getFormData(); - final Article article = (Article) super.initBasicWidgets(event); - } - - /** - * Cancels streamlined editing. - * - * @param event - */ - @Override - public void submitted(final FormSectionEvent event) { - if (propertiesStep != null - && getSaveCancelSection().getCancelButton().isSelected(event - .getPageState())) { - propertiesStep.cancelStreamlinedCreation(event.getPageState()); - } - } - - /** - * Form processing hook. Saves Event object. - * - * @param event - */ - @Override - public void process(final FormSectionEvent event) { - - final Article article = (Article) super.processBasicWidgets(event); - - // save only if save button was pressed - if (article != null - && getSaveCancelSection().getSaveButton().isSelected(event - .getPageState())) { - - final ContentItemRepository itemRepo = CdiUtil - .createCdiUtil() - .findBean(ContentItemRepository.class); - - itemRepo.save(article); - } - if (propertiesStep != null) { - propertiesStep.maybeForwardToNextStep(event.getPageState()); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/AttachmentListSelectionModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/AttachmentListSelectionModel.java deleted file mode 100644 index b47f0a79d..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/AttachmentListSelectionModel.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.ParameterModel; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.AttachmentList; -import org.librecms.contentsection.AttachmentListManager; - -/** - * - * @author Jens Pelzetter - */ -public class AttachmentListSelectionModel implements - SingleSelectionModel { - - private final SingleSelectionModel model; - - public AttachmentListSelectionModel(final LongParameter parameter) { - this.model = new ParameterSingleSelectionModel<>(parameter); - } - - public AttachmentListSelectionModel(final String parameterName) { - this(new LongParameter(parameterName)); - } - - @Override - public boolean isSelected(final PageState state) { - return model.isSelected(state); - } - - @Override - public Long getSelectedKey(final PageState state) { - - final Object key = model.getSelectedKey(state); - if (key == null) { - return null; - } else if (key instanceof Long) { - return (Long) key; - } else if (key instanceof String) { - return Long.parseLong((String) key); - } else { - return Long.parseLong(key.toString()); - } - } - - @Override - public void setSelectedKey(final PageState state, final Long key) { - model.setSelectedKey(state, key); - } - - public AttachmentList getSelectedAttachmentList(final PageState state) { - final Long key = getSelectedKey(state); - if (key == null) { - return null; - } else { - final AttachmentListManager manager = CdiUtil - .createCdiUtil() - .findBean(AttachmentListManager.class); - return manager.getAttachmentList(key).get(); - } - } - - @Override - public void clearSelection(final PageState state) { - model.clearSelection(state); - } - - @Override - public void addChangeListener(final ChangeListener changeListener) { - model.addChangeListener(changeListener); - } - - @Override - public void removeChangeListener(final ChangeListener changeListener) { - model.removeChangeListener(changeListener); - } - - @Override - public ParameterModel getStateParameter() { - return model.getStateParameter(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/AttachmentSelectionModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/AttachmentSelectionModel.java deleted file mode 100644 index ca120633a..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/AttachmentSelectionModel.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.ParameterModel; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ItemAttachment; -import org.librecms.contentsection.ItemAttachmentManager; - -/** - * - * @author Jens Pelzetter - */ -public class AttachmentSelectionModel implements SingleSelectionModel { - - private final SingleSelectionModel model; - - public AttachmentSelectionModel(final LongParameter parameter) { - this.model = new ParameterSingleSelectionModel<>(parameter); - } - - public AttachmentSelectionModel(final String parameterName) { - this(new LongParameter(parameterName)); - } - - @Override - public boolean isSelected(final PageState state) { - return model.isSelected(state); - } - - @Override - public Long getSelectedKey(final PageState state) { - - final Object key = model.getSelectedKey(state); - if (key == null) { - return null; - } else if (key instanceof Long) { - return (Long) key; - } else if (key instanceof String) { - return Long.parseLong((String) key); - } else { - return Long.parseLong(key.toString()); - } - } - - @Override - public void setSelectedKey(final PageState state, final Long key) { - model.setSelectedKey(state, key); - } - - public ItemAttachment getSelectedAttachment(final PageState state) { - final Long key = getSelectedKey(state); - if (key == null) { - return null; - } else { - final ItemAttachmentManager manager = CdiUtil - .createCdiUtil() - .findBean(ItemAttachmentManager.class); - return manager.findById(key).get(); - } - } - - @Override - public void clearSelection(final PageState state) { - model.clearSelection(state); - } - - @Override - public void addChangeListener(final ChangeListener changeListener) { - model.addChangeListener(changeListener); - } - - @Override - public void removeChangeListener(final ChangeListener changeListener) { - model.removeChangeListener(changeListener); - } - - @Override - public ParameterModel getStateParameter() { - return model.getStateParameter(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/ItemAttachmentSelectionModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/ItemAttachmentSelectionModel.java deleted file mode 100644 index 4e1c0c4a1..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/ItemAttachmentSelectionModel.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.ParameterModel; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ItemAttachment; -import org.librecms.contentsection.ItemAttachmentManager; - -/** - * - * @author Jens Pelzetter - */ -public class ItemAttachmentSelectionModel implements SingleSelectionModel { - - private final SingleSelectionModel model; - - public ItemAttachmentSelectionModel(final LongParameter parameter) { - this.model = new ParameterSingleSelectionModel<>(parameter); - } - - public ItemAttachmentSelectionModel(final String parameterName) { - this(new LongParameter(parameterName)); - } - - @Override - public boolean isSelected(final PageState state) { - return model.isSelected(state); - } - - @Override - public Long getSelectedKey(final PageState state) { - final Object key = model.getSelectedKey(state); - if (key == null) { - return null; - } else if (key instanceof Long) { - return (Long) key; - } else if (key instanceof String) { - return Long.parseLong((String) key); - } else { - return Long.parseLong(key.toString()); - } - } - - @Override - public void setSelectedKey(final PageState state, final Long key) { - model.setSelectedKey(state, key); - } - - public ItemAttachment getSelectedAttachment(final PageState state) { - final Long key = getSelectedKey(state); - if (key == null) { - return null; - } else { - final ItemAttachmentManager manager = CdiUtil - .createCdiUtil() - .findBean(ItemAttachmentManager.class); - return manager.findById(key).get(); - } - } - - @Override - public void clearSelection(final PageState state) { - model.clearSelection(state); - } - - @Override - public void addChangeListener(final ChangeListener changeListener) { - model.addChangeListener(changeListener); - } - - @Override - public void removeChangeListener(final ChangeListener changeListener) { - model.removeChangeListener(changeListener); - } - - @Override - public ParameterModel getStateParameter() { - return model.getStateParameter(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AssignedImageTableRow.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AssignedImageTableRow.java deleted file mode 100644 index 6c95e2968..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AssignedImageTableRow.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.images; - -/** - * A container for the data shown in the table of assigned images. - * - * @author Jens Pelzetter - */ -class AssignedImageTableRow { - - private long attachmentId; - private String imageUuid; - private String filename; - private long width; - private long height; - private String type; - private String title; - private String caption; - - public long getAttachmentId() { - return attachmentId; - } - - public void setAttachmentId(final long attachmentId) { - this.attachmentId = attachmentId; - } - - public String getImageUuid() { - return imageUuid; - } - - public void setImageUuid(final String imageUuid) { - this.imageUuid = imageUuid; - } - - public String getFilename() { - return filename; - } - - public void setFilename(final String filename) { - this.filename = filename; - } - - public long getWidth() { - return width; - } - - public void setWidth(final long width) { - this.width = width; - } - - public long getHeight() { - return height; - } - - public void setHeight(final long height) { - this.height = height; - } - - public String getType() { - return type; - } - - public void setType(final String type) { - this.type = type; - } - - public String getTitle() { - return title; - } - - public void setTitle(final String title) { - this.title = title; - } - - public String getCaption() { - return caption; - } - - public void setCaption(final String caption) { - this.caption = caption; - } - - - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AssignedImagesTable.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AssignedImagesTable.java deleted file mode 100644 index 222830168..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AssignedImagesTable.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.images; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Image; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.TableActionEvent; -import com.arsdigita.bebop.event.TableActionListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableColumnModel; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.assets.ItemAttachmentSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ItemAttachment; - -/** - * - * @author Jens Pelzetter - */ -class AssignedImagesTable extends Table { - - protected static final int COL_PREVIEW = 0; - protected static final int COL_TITLE = 1; - protected static final int COL_IMAGE_DATA = 2; - protected static final int COL_CAPTION = 3; - protected static final int COL_MOVE = 4; - protected static final int COL_REMOVE = 5; - - private final ItemSelectionModel itemSelectionModel; - private final ItemAttachmentSelectionModel moveAttachmentModel; - private final StringParameter selectedLanguageParam; - - public AssignedImagesTable( - final ItemSelectionModel itemSelectionModel, - final ItemAttachmentSelectionModel moveAttachmentModel, - final StringParameter selectedLanguageParam) { - - super(); - this.itemSelectionModel = itemSelectionModel; - this.moveAttachmentModel = moveAttachmentModel; - this.selectedLanguageParam = selectedLanguageParam; - - final TableColumnModel columnModel = super.getColumnModel(); - columnModel.add(new TableColumn( - COL_PREVIEW, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.preview_header", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_TITLE, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.title_header", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_IMAGE_DATA, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.properties_header", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_CAPTION, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.caption_header", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_MOVE, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.move_header", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_REMOVE, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.remove_header", - CmsConstants.CMS_BUNDLE)))); - - super - .setModelBuilder(new AssignedImagesTableModelBuilder( - itemSelectionModel, - moveAttachmentModel, - selectedLanguageParam)); - - super - .getColumn(COL_PREVIEW) - .setCellRenderer(new ThumbnailCellRenderer()); - super - .getColumn(COL_IMAGE_DATA) - .setCellRenderer(new PropertiesCellRenderer()); - super - .getColumn(COL_MOVE) - .setCellRenderer(new MoveCellRenderer()); - super - .getColumn(COL_REMOVE) - .setCellRenderer(new RemoveCellRenderer()); - - super.addTableActionListener(new TableActionListener() { - - @Override - public void cellSelected(final TableActionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - final TableColumn column = getColumnModel() - .get(event.getColumn()); - - switch (column.getModelIndex()) { - case COL_MOVE: - if (moveAttachmentModel.getSelectedKey(state) == null) { - - moveAttachmentModel - .setSelectedKey(state, - Long.parseLong((String) event - .getRowKey())); - } else { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ImageStepController controller = cdiUtil - .findBean(ImageStepController.class); - - final ItemAttachment selectedAttachment - = moveAttachmentModel - .getSelectedAttachment(state); - - final Long destId = Long - .parseLong((String) event.getRowKey()); - - controller.moveAfter(selectedAttachment, destId); - moveAttachmentModel.clearSelection(state); - } - break; - case COL_REMOVE: - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ImageStepController controller = cdiUtil - .findBean(ImageStepController.class); - controller.deleteAttachment(Long - .parseLong((String) event.getRowKey())); - break; - } - } - - @Override - public void headSelected(final TableActionEvent event) { - //Nothing - } - - }); - - super.setEmptyView(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.none", - CmsConstants.CMS_BUNDLE))); - - } - - private class ThumbnailCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - if (value == null) { - return new Text(""); - } else { - final Image image = new Image((String) value, ""); - return image; - } - } - - } - - private class PropertiesCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - @SuppressWarnings("unchecked") - final ImageProperties properties = (ImageProperties) value; - final BoxPanel panel = new BoxPanel(BoxPanel.VERTICAL); - - panel.add(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.properties.filename", - CmsConstants.CMS_BUNDLE, - new Object[]{properties.getFilename()}))); - panel.add(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.properties.size", - CmsConstants.CMS_BUNDLE, - new Object[]{properties.getWidth(), properties.getHeight()}))); - panel.add(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.properties.type", - CmsConstants.CMS_BUNDLE, - new String[]{properties.getType()}))); - - return panel; - } - - } - - private class MoveCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - return new ControlLink((Component) value); - } - - } - - private class RemoveCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - return new ControlLink((Component) value); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AssignedImagesTableModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AssignedImagesTableModel.java deleted file mode 100644 index a22f392e9..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AssignedImagesTableModel.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.images; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.ui.authoring.assets.ItemAttachmentSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.web.CCMDispatcherServlet; - -import org.librecms.CmsConstants; - -import java.util.Iterator; -import java.util.List; - -/** - * - * @author Jens Pelzetter - */ -class AssignedImagesTableModel implements TableModel { - - private final PageState state; - private final ItemAttachmentSelectionModel moveAttachmentModel; - - private final Iterator iterator; - private AssignedImageTableRow currentRow; - - public AssignedImagesTableModel( - final List rows, - final PageState state, - final ItemAttachmentSelectionModel moveAttachmentModel) { - - this.iterator = rows.iterator(); - this.state = state; - this.moveAttachmentModel = moveAttachmentModel; - } - - @Override - public int getColumnCount() { - return 4; - } - - @Override - public boolean nextRow() { - if (iterator.hasNext()) { - currentRow = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - switch (columnIndex) { - case AssignedImagesTable.COL_PREVIEW: - return String - .format("%s/content-sections/%s/images/" - + "uuid-%s?width=150&height=100", - CCMDispatcherServlet.getContextPath(), - CMS.getContext().getContentSection().getLabel(), - currentRow.getImageUuid()); - case AssignedImagesTable.COL_IMAGE_DATA: { - final ImageProperties imageProperties = new ImageProperties(); - imageProperties.setFilename(currentRow.getFilename()); - imageProperties.setWidth(currentRow.getWidth()); - imageProperties.setHeight(currentRow.getHeight()); - imageProperties.setType(currentRow.getType()); - - return imageProperties; - } - case AssignedImagesTable.COL_TITLE: - return currentRow.getTitle(); - case AssignedImagesTable.COL_CAPTION: - return currentRow.getCaption(); - case AssignedImagesTable.COL_MOVE: - if (moveAttachmentModel.getSelectedKey(state) == null) { - return new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_image.link_move", - CmsConstants.CMS_BUNDLE)); - } else { - return new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_image.link_move_below_here", - CmsConstants.CMS_BUNDLE)); - } - case AssignedImagesTable.COL_REMOVE: - return new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.remove", - CmsConstants.CMS_BUNDLE)); - default: - throw new IllegalArgumentException(String.format( - "Illegal column index %d.", columnIndex)); - } - } - - @Override - public Object getKeyAt(final int columnIndex) { - return currentRow.getAttachmentId(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AssignedImagesTableModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AssignedImagesTableModelBuilder.java deleted file mode 100644 index b95ed6352..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AssignedImagesTableModelBuilder.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.images; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.assets.ItemAttachmentSelectionModel; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentItem; - -import java.util.List; -import java.util.Locale; - -/** - * Creates the {@link AssignedImagesTableModel} which is used in - * {@link ImageStep} for the table of assigned images. This - * {@link TableModelBuilder} takes the selected item and retrieves all retrieved - * images from the item. For each assigned image an instance - * {@link AssignedImageTableRow} is created. The resulting list (which might be - * empty) is than used to create the image model. This also means that all - * interaction with the database is done by this {@link TableModelBuilder}. - * - * @author Jens Pelzetter - */ -class AssignedImagesTableModelBuilder extends LockableImpl implements - TableModelBuilder { - - private final ItemSelectionModel itemSelectionModel; - private final ItemAttachmentSelectionModel moveAttachmentModel; - private final StringParameter selectedLanguageParam; - - /** - * Constructor for this {@link TableModelBuilder}. - * - * @param itemSelectionModel The model used to determine the selected - * {@link ContentItem}. - * @param selectedLanguageParam Parameter used to determine the selected - * language variant of the selected - * {@link ContentItem}. - */ - protected AssignedImagesTableModelBuilder( - final ItemSelectionModel itemSelectionModel, - final ItemAttachmentSelectionModel moveAttachmentModel, - final StringParameter selectedLanguageParam) { - - this.itemSelectionModel = itemSelectionModel; - this.moveAttachmentModel = moveAttachmentModel; - this.selectedLanguageParam = selectedLanguageParam; - } - - @Override - public TableModel makeModel(final Table table, final PageState state) { - - final ContentItem selectedItem = itemSelectionModel - .getSelectedItem(state); - final String selectedLanguage = (String) state - .getValue(selectedLanguageParam); - final Locale selectedLocale = new Locale(selectedLanguage); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ImageStepController controller = cdiUtil - .findBean(ImageStepController.class); - - final List rows = controller - .retrieveAssignedImagesRows(selectedItem, selectedLocale); - - return new AssignedImagesTableModel(rows, - state, - moveAttachmentModel); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AvailableImageTableRow.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AvailableImageTableRow.java deleted file mode 100644 index ca1411e7f..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AvailableImageTableRow.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.images; - -/** - * A container for the data shown in the table of assigned images. - * - * @author Jens Pelzetter - */ -class AvailableImageTableRow { - - private long imageId; - private String imageUuid; - private String title; - private String filename; - private long width; - private long height; - private String type; - private String caption; - - public long getImageId() { - return imageId; - } - - public void setImageId(final long imageId) { - this.imageId = imageId; - } - - public String getImageUuid() { - return imageUuid; - } - - public void setImageUuid(final String imageUuid) { - this.imageUuid = imageUuid; - } - - public String getTitle() { - return title; - } - - public void setTitle(final String title) { - this.title = title; - } - - public String getFilename() { - return filename; - } - - public void setFilename(final String filename) { - this.filename = filename; - } - - public long getWidth() { - return width; - } - - public void setWidth(final long width) { - this.width = width; - } - - public long getHeight() { - return height; - } - - public void setHeight(final long height) { - this.height = height; - } - - public String getType() { - return type; - } - - public void setType(final String type) { - this.type = type; - } - - public String getCaption() { - return caption; - } - - public void setCaption(final String caption) { - this.caption = caption; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AvailableImages.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AvailableImages.java deleted file mode 100644 index 8b70dbeff..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AvailableImages.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.images; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.PaginationModelBuilder; -import com.arsdigita.bebop.Paginator; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.TableActionEvent; -import com.arsdigita.bebop.event.TableActionListener; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableColumnModel; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; - -/** - * - * @author Jens Pelzetter - */ -class AvailableImages extends BoxPanel { - - protected static final int COL_PREVIEW = 0; - protected static final int COL_TITLE = 1; - protected static final int COL_PROPERTIES = 2; - protected static final int COL_CAPTION = 3; - protected static final int COL_ADD = 4; - - public AvailableImages(final ImageStep imageStep, - final ItemSelectionModel itemSelectionModel, - final StringParameter selectedLanguageParam) { - - super(BoxPanel.VERTICAL); - - final Form filterForm = new Form("filter_available_images_form", - new BoxPanel(BoxPanel.HORIZONTAL)); - final TextField filterField = new TextField("filter_available_images"); - filterField.setLabel(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.available_images.filter_label", - CmsConstants.CMS_BUNDLE)); - final Submit submitFilter = new Submit(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.available_images.submit_filter", - CmsConstants.CMS_BUNDLE)); - filterForm.add(filterField); - filterForm.add(submitFilter); - - super.add(filterForm); - - final Paginator paginator = new Paginator(new PaginationModelBuilder() { - - @Override - public int getTotalSize(final Paginator paginator, - final PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ImageStepController controller = cdiUtil - .findBean(ImageStepController.class); - - return (int) controller - .getNumberOfAvailableImages( - itemSelectionModel.getSelectedItem(state), - (String) filterField.getValue(state)); - } - - @Override - public boolean isVisible(final PageState state) { - return true; - } - - }, - 30); - - super.add(paginator); - - final Table table = new Table(); - final TableColumnModel columnModel = table.getColumnModel(); - columnModel.add(new TableColumn( - COL_PREVIEW, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.available_images.preview_header", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_TITLE, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.available_images.title_header", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_PROPERTIES, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.available_images.properties_header", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_CAPTION, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.available_images.caption_header", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_ADD, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.available_images.select_header", - CmsConstants.CMS_BUNDLE)))); - - table.setModelBuilder(new AvailableImagesTableModelBuilder( - itemSelectionModel, selectedLanguageParam, filterField, paginator)); - - table - .getColumn(COL_PREVIEW) - .setCellRenderer(new ThumbnailCellRenderer()); - table - .getColumn(COL_PROPERTIES) - .setCellRenderer(new PropertiesCellRenderer()); - table - .getColumn(COL_ADD) - .setCellRenderer(new AddCellRenderer()); - - table.setEmptyView(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.available_images.none", - CmsConstants.CMS_BUNDLE))); - - table.addTableActionListener(new TableActionListener() { - - @Override - public void cellSelected(final TableActionEvent event) - throws FormProcessException { - - final Object rowKey = event.getRowKey(); - final long imageId; - if (rowKey instanceof Long) { - imageId = (Long) event.getRowKey(); - } else if(rowKey instanceof String) { - imageId = Long.parseLong((String) rowKey); - } else { - imageId = Long.parseLong(rowKey.toString()); - } - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ImageStepController controller = cdiUtil - .findBean(ImageStepController.class); - controller - .attachImage(itemSelectionModel - .getSelectedItem(event.getPageState()), - imageId); - - imageStep.showAssignedImages(event.getPageState()); - } - - @Override - public void headSelected(final TableActionEvent event) { - //Nothing - } - - }); - - super.add(table); - } - - private class ThumbnailCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - if (value == null) { - return new Text(""); - } else { - final com.arsdigita.bebop.Image image - = new com.arsdigita.bebop.Image( - (String) value, ""); - return image; - } - } - - } - - private class PropertiesCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - @SuppressWarnings("unchecked") - final ImageProperties properties = (ImageProperties) value; - final BoxPanel panel = new BoxPanel(BoxPanel.VERTICAL); - - panel.add(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.properties.filename", - CmsConstants.CMS_BUNDLE, - new Object[]{properties.getFilename()}))); - panel.add(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.properties.size", - CmsConstants.CMS_BUNDLE, - new Object[]{properties.getWidth(), properties.getHeight()}))); - panel.add(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.properties.type", - CmsConstants.CMS_BUNDLE, - new String[]{properties.getType()}))); - - return panel; - } - - } - - private class AddCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - return new ControlLink((Component) value); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AvailableImagesTableModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AvailableImagesTableModel.java deleted file mode 100644 index acc3eb2ff..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AvailableImagesTableModel.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.images; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.cms.CMS; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.web.CCMDispatcherServlet; - -import org.librecms.CmsConstants; - -import java.util.Iterator; -import java.util.List; - -/** - * - * @author Jens Pelzetter - */ -class AvailableImagesTableModel implements TableModel { - - private final Iterator iterator; - private AvailableImageTableRow currentRow; - - public AvailableImagesTableModel(final List rows) { - iterator = rows.iterator(); - } - - @Override - public int getColumnCount() { - return 4; - } - - @Override - public boolean nextRow() { - if (iterator.hasNext()) { - currentRow = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - - switch (columnIndex) { - case AvailableImages.COL_PREVIEW: - return String - .format("%s/content-sections/%s/images/" - + "uuid-%s?width=150&height=100", - CCMDispatcherServlet.getContextPath(), - CMS.getContext().getContentSection().getLabel(), - currentRow.getImageUuid()); - case AvailableImages.COL_TITLE: - return currentRow.getTitle(); - case AvailableImages.COL_PROPERTIES: - final ImageProperties imageProperties = new ImageProperties(); - imageProperties.setFilename(currentRow.getFilename()); - imageProperties.setWidth(currentRow.getWidth()); - imageProperties.setHeight(currentRow.getHeight()); - imageProperties.setType(currentRow.getType()); - - return imageProperties; - case AvailableImages.COL_CAPTION: - return currentRow.getCaption(); - case AvailableImages.COL_ADD: - return new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.available_images.add", - CmsConstants.CMS_BUNDLE)); - default: - throw new IllegalArgumentException(String.format( - "Illegal column index %d.", columnIndex)); - } - - } - - @Override - public Object getKeyAt(final int columnIndex) { - return currentRow.getImageId(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AvailableImagesTableModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AvailableImagesTableModelBuilder.java deleted file mode 100644 index a2e98a427..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/AvailableImagesTableModelBuilder.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.images; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Paginator; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.assets.Image; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ItemAttachment; - -import java.util.List; -import java.util.Locale; -import java.util.stream.Collectors; - -/** - * - * @author Jens Pelzetter - */ -public class AvailableImagesTableModelBuilder - extends LockableImpl - implements TableModelBuilder { - - private final ItemSelectionModel itemSelectionModel; - private final StringParameter selectedLanguageParam; - private final TextField filterField; - private final Paginator paginator; - - public AvailableImagesTableModelBuilder( - final ItemSelectionModel itemSelectionModel, - final StringParameter selectedLanguageParam, - final TextField filterField, - final Paginator paginator) { - - this.itemSelectionModel = itemSelectionModel; - this.selectedLanguageParam = selectedLanguageParam; - this.filterField = filterField; - this.paginator = paginator; - } - - @Override - public TableModel makeModel(final Table table, - final PageState state) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ImageStepController controller = cdiUtil - .findBean(ImageStepController.class); - - final ContentItem selectedItem = itemSelectionModel - .getSelectedItem(state); - - final List> imageAttachments = controller - .retrieveAssignedImages(selectedItem); - - final List excludedImages = imageAttachments - .stream() - .map(attachment -> attachment.getAsset()) - .collect(Collectors.toList()); - - //Paginator count from 1, JPA from 0 - final int firstResult = paginator.getFirst(state) - 1; - final int maxResults = paginator.getPageSize(state); - - final Locale selectedLocale = new Locale((String) state.getValue(selectedLanguageParam)); - - final List rows = controller - .getAvailableImageRows(excludedImages, - selectedLocale, - (String) filterField.getValue(state), - firstResult, - maxResults); - - return new AvailableImagesTableModel(rows); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/ImageProperties.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/ImageProperties.java deleted file mode 100644 index a8b8581ea..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/ImageProperties.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.images; - -/** - * - * @author Jens Pelzetter - */ -class ImageProperties { - - protected static final String IMAGE_DATA_FILE_NAME = "filename"; - protected static final String IMAGE_DATA_WIDTH = "width"; - protected static final String IMAGE_DATA_HEIGHT = "height"; - protected static final String IMAGE_DATA_TYPE = "type"; - - private String filename; - - private long width; - - private long height; - - private String type; - - public String getFilename() { - return filename; - } - - public void setFilename(final String filename) { - this.filename = filename; - } - - public long getWidth() { - return width; - } - - public void setWidth(final long width) { - this.width = width; - } - - public long getHeight() { - return height; - } - - public void setHeight(final long height) { - this.height = height; - } - - public String getType() { - return type; - } - - public void setType(final String type) { - this.type = type; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/ImageStep.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/ImageStep.java deleted file mode 100644 index e045f90ac..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/ImageStep.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.images; - -import com.arsdigita.bebop.ActionLink; -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.ResettableContainer; -import com.arsdigita.cms.ui.authoring.assets.ItemAttachmentSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ItemAttachment; -import org.librecms.ui.authoring.ContentItemAuthoringStep; - -import java.util.Locale; - -/** - * - * @author Jens Pelzetter - */ -@ContentItemAuthoringStep( - labelBundle = CmsConstants.CMS_BUNDLE, - labelKey = "image_step.label", - descriptionBundle = CmsConstants.CMS_BUNDLE, - descriptionKey = "image_step.description") -public class ImageStep extends ResettableContainer { - - public static final String IMAGES_ATTACHMENT_LIST = ".images"; - - private final LongParameter moveAttachmentParam; - private final ItemAttachmentSelectionModel moveAttachmentModel; - - private final Label assignedImagesHeader; - private final ControlLink addImageLink; - private final ActionLink beginLink; - private final Table assignedImagesTable; - private final Label addImageHeader; - private final AvailableImages availableImages; - private final ControlLink cancelAddImage; - - public ImageStep(final ItemSelectionModel itemSelectionModel, - final AuthoringKitWizard authoringKitWizard, - final StringParameter selectedLanguageParam) { - - super(); - - moveAttachmentParam = new LongParameter("moveAttachment"); - moveAttachmentModel = new ItemAttachmentSelectionModel( - moveAttachmentParam); - - assignedImagesHeader = new Label(event -> { - final PageState state = event.getPageState(); - final Label target = (Label) event.getTarget(); - - final ContentItem selectedItem = itemSelectionModel - .getSelectedItem(state); - final String selectedLanguage = (String) state - .getValue(selectedLanguageParam); - final Locale selectedLocale = new Locale(selectedLanguage); - final String title; - if (selectedItem.getTitle().hasValue(selectedLocale)) { - title = selectedItem.getTitle().getValue(selectedLocale); - } else { - title = selectedItem.getTitle().getValue(KernelConfig - .getConfig() - .getDefaultLocale()); - } - - target.setLabel(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.heading", - CmsConstants.CMS_BUNDLE, - new String[]{title})); - }); - assignedImagesHeader.setClassAttr(""); - - addImageHeader = new Label(event -> { - final PageState state = event.getPageState(); - final Label target = (Label) event.getTarget(); - - final ContentItem selectedItem = itemSelectionModel - .getSelectedItem(state); - final String selectedLanguage = (String) state - .getValue(selectedLanguageParam); - final Locale selectedLocale = new Locale(selectedLanguage); - final String title; - if (selectedItem.getTitle().hasValue(selectedLocale)) { - title = selectedItem.getTitle().getValue(selectedLocale); - } else { - title = selectedItem.getTitle().getValue(KernelConfig - .getConfig() - .getDefaultLocale()); - } - - target.setLabel(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.add_heading", - CmsConstants.CMS_BUNDLE, - new String[]{title})); - }); - - addImageLink = new ActionLink(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.add_image", - CmsConstants.CMS_BUNDLE))); - addImageLink.addActionListener(event -> { - showAvailableImages(event.getPageState()); - }); - - beginLink = new ActionLink(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.move_to_beginning", - CmsConstants.CMS_BUNDLE)); - - beginLink.addActionListener(event -> { - final PageState state = event.getPageState(); - final ItemAttachment toMove = moveAttachmentModel - .getSelectedAttachment(state); - - final ImageStepController controller = CdiUtil - .createCdiUtil() - .findBean(ImageStepController.class); - - controller.moveToFirst(toMove); - - moveAttachmentModel.clearSelection(state); - }); - - assignedImagesTable = new AssignedImagesTable(itemSelectionModel, - moveAttachmentModel, - selectedLanguageParam); - - cancelAddImage = new ControlLink(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.imagestep.assigned_images.cancel_add_image", - CmsConstants.CMS_BUNDLE))); - cancelAddImage.addActionListener(event -> { - showAssignedImages(event.getPageState()); - }); - - availableImages = new AvailableImages(this, - itemSelectionModel, - selectedLanguageParam); - - final BoxPanel panel = new BoxPanel(BoxPanel.VERTICAL); - panel.add(assignedImagesHeader); - panel.add(addImageLink); - panel.add(beginLink); - panel.add(assignedImagesTable); - panel.add(addImageHeader); - panel.add(availableImages); - super.add(panel); - - moveAttachmentModel.addChangeListener(event -> { - - final PageState state = event.getPageState(); - - if (moveAttachmentModel.getSelectedKey(state) == null) { - addImageLink.setVisible(state, true); - beginLink.setVisible(state, false); - } else { - addImageLink.setVisible(state, false); - beginLink.setVisible(state, true); - } - }); - } - - @Override - public void register(final Page page) { - super.register(page); - - page.setVisibleDefault(assignedImagesHeader, true); - page.setVisibleDefault(addImageLink, true); - page.setVisibleDefault(beginLink, false); - page.setVisibleDefault(assignedImagesTable, true); - page.setVisibleDefault(addImageHeader, false); - page.setVisibleDefault(cancelAddImage, false); - page.setVisibleDefault(availableImages, false); - - page.addComponentStateParam(assignedImagesTable, moveAttachmentParam); - } - - protected void showAssignedImages(final PageState state) { - assignedImagesHeader.setVisible(state, true); - addImageLink.setVisible(state, true); - assignedImagesTable.setVisible(state, true); - addImageHeader.setVisible(state, false); - - availableImages.setVisible(state, false); - } - - protected void showAvailableImages(final PageState state) { - assignedImagesHeader.setVisible(state, false); - addImageLink.setVisible(state, false); - assignedImagesTable.setVisible(state, false); - addImageHeader.setVisible(state, true); - cancelAddImage.setVisible(state, true); - availableImages.setVisible(state, true); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/ImageStepController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/ImageStepController.java deleted file mode 100644 index c20818a36..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/images/ImageStepController.java +++ /dev/null @@ -1,474 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.images; - -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.l10n.LocalizedString; -import org.librecms.assets.Image; -import org.librecms.contentsection.AssetRepository; -import org.librecms.contentsection.AttachmentList; -import org.librecms.contentsection.AttachmentListManager; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ItemAttachment; -import org.librecms.contentsection.ItemAttachmentManager; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.stream.Collectors; - -import javax.annotation.PostConstruct; -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.persistence.EntityManager; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Join; -import javax.persistence.criteria.Root; -import javax.transaction.Transactional; - -/** - * Encapsulates all interaction between the {@link ImageStep} and associated - * classes like the {@link ImageStepTableModelBuilder} and CDI beans. - * - * @author Jens Pelzetter - */ -@RequestScoped -class ImageStepController { - - @Inject - private AssetRepository assetRepo; - - @Inject - private AttachmentListManager attachmentListManager; - - @Inject - private ItemAttachmentManager attachmentManager; - - @Inject - private ConfigurationManager confManager; - - @Inject - private EntityManager entityManager; - - @Inject - private ContentItemRepository itemRepo; - - private Locale defaultLocale; - - @PostConstruct - private void init() { - - final KernelConfig kernelConfig = confManager - .findConfiguration(KernelConfig.class); - defaultLocale = kernelConfig.getDefaultLocale(); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected List> retrieveAssignedImages( - final ContentItem fromContentItem) { - - Objects.requireNonNull(fromContentItem); - - final ContentItem item = itemRepo - .findById(fromContentItem.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with id %d in the database.", - fromContentItem.getObjectId()))); - - final List imageLists = attachmentListManager - .getAttachmentList(item, ImageStep.IMAGES_ATTACHMENT_LIST); - - if (imageLists.isEmpty()) { - return Collections.emptyList(); - } - - final List> attachments = new ArrayList<>(); - for (final AttachmentList imageList : imageLists) { - for (final ItemAttachment attachment : imageList.getAttachments()) { - attachments.add(attachment); - } - } - - @SuppressWarnings("unchecked") - final List> imageAttachments = attachments - .stream() - .sorted((attachment1, attachment2) -> { - return attachment1.compareTo(attachment2); - }) - .filter(attachment -> attachment.getAsset() instanceof Image) - .map(attachment -> (ItemAttachment) attachment) - .collect(Collectors.toList()); - - return imageAttachments; - } - - @Transactional(Transactional.TxType.REQUIRED) - protected List retrieveAssignedImagesRows( - final ContentItem fromContentItem, final Locale selectedLocale) { - -// Objects.requireNonNull(fromContentItem); -// Objects.requireNonNull(selectedLocale); -// -// final ContentItem item = itemRepo -// .findById(fromContentItem.getObjectId()) -// .orElseThrow(() -> new IllegalArgumentException(String -// .format("No ContentItem with id %d in the database.", -// fromContentItem.getObjectId()))); -// -// final List imageLists = attachmentListManager -// .getAttachmentList(item, ImageStep.IMAGES_ATTACHMENT_LIST); -// -// if (imageLists.isEmpty()) { -// return Collections.emptyList(); -// } -// -// final List> attachments = new ArrayList<>(); -// for (final AttachmentList imageList : imageLists) { -// for (final ItemAttachment attachment : imageList.getAttachments()) { -// attachments.add(attachment); -// } -// } - final List> imageAttachments - = retrieveAssignedImages( - fromContentItem); - -// @SuppressWarnings("unchecked") -// final List rows = attachments -// .stream() -// .sorted((attachment1, attachment2) -> { -// return attachment1.compareTo(attachment2); -// }) -// .filter(attachment -> attachment.getAsset() instanceof Image) -// .map(attachment -> (ItemAttachment) attachment) -// .map(imageAttachment -> buildAssignedImageTableRow(imageAttachment, -// selectedLocale)) -// .collect(Collectors.toList()); -// -// return rows; - return imageAttachments - .stream() - .map(imageAttachment -> buildAssignedImageTableRow(imageAttachment, - selectedLocale)) - .collect(Collectors.toList()); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void moveToFirst(final ItemAttachment attachmentToMove) { - - Objects.requireNonNull(attachmentToMove); - - final ItemAttachment toMove = attachmentManager - .findById(attachmentToMove.getAttachmentId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ItemAttachment with ID %d in the database.", - attachmentToMove.getAttachmentId()))); - - final AttachmentList attachmentList = toMove.getAttachmentList(); - final List> attachments = attachmentList - .getAttachments() - .stream() - .sorted((attachment1, attachment2) -> { - return attachment1.compareTo(attachment2); - }) - .collect(Collectors.toList()); - - toMove.setSortKey(0); - attachments - .stream() - .filter(current -> !current.equals(toMove)) - .forEach(current -> current.setSortKey(current.getSortKey() + 1)); - - attachments - .forEach(current -> entityManager.merge(current)); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void moveAfter(final ItemAttachment attachmentToMove, - final long destId) { - - Objects.requireNonNull(attachmentToMove); - - final ItemAttachment toMove = attachmentManager - .findById(attachmentToMove.getAttachmentId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ItemAttachment with ID %d in the database.", - attachmentToMove.getAttachmentId()))); - - final ItemAttachment after = attachmentManager - .findById(destId) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ItemAttachment with ID %d in the database.", - attachmentToMove.getAttachmentId()))); - - final AttachmentList attachmentList = toMove.getAttachmentList(); - final List> attachments = attachmentList - .getAttachments() - .stream() - .sorted((attachment1, attachment2) -> { - return attachment1.compareTo(attachment2); - }) - .collect(Collectors.toList()); - - if (!attachments.contains(toMove)) { - throw new IllegalArgumentException(String.format( - "ItemAttachment %d is not part of AttachmentList %d.", - toMove.getAttachmentId(), - attachmentList.getListId())); - } - - if (!attachments.contains(after)) { - throw new IllegalArgumentException(String.format( - "ItemAttachment %d is not part of AttachmentList %d.", - after.getAttachmentId(), - attachmentList.getListId())); - } - - final int afterIndex = attachments.indexOf(after); - for (int i = afterIndex + 1; i < attachments.size(); i++) { - final ItemAttachment current = attachments.get(i); - current.setSortKey(current.getSortKey() + 1); - entityManager.merge(current); - } - - toMove.setSortKey(afterIndex + 1); - entityManager.merge(toMove); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void deleteAttachment(final long attachmentId) { - - final ItemAttachment attachment = attachmentManager - .findById(attachmentId) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ItemAttachment with ID %d in the database.", - attachmentId))); - - deleteAttachment(attachment); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void deleteAttachment(final ItemAttachment attachment) { - - Objects.requireNonNull(attachment); - - final ItemAttachment toRemove = attachmentManager - .findById(attachment.getAttachmentId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ItemAttachment with ID %d in the database.", - attachment.getAttachmentId()))); - - entityManager.remove(toRemove); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected long getNumberOfAvailableImages(final ContentItem selectedItem, - final String filter) { - - Objects.requireNonNull(selectedItem); - - final ContentItem item = itemRepo - .findById(selectedItem.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", - selectedItem.getObjectId()))); - - final List> imageAttachments - = retrieveAssignedImages(item); - final List excluededImages = imageAttachments - .stream() - .map(imageAttachment -> imageAttachment.getAsset()) - .collect(Collectors.toList()); - - final CriteriaBuilder criteriaBuilder = entityManager - .getCriteriaBuilder(); - - final CriteriaQuery query = criteriaBuilder - .createQuery(Long.class); - final Root from = query.from(Image.class); - final Join titleJoin = from.join("title"); - final Join titleValuesJoin = titleJoin.join("values"); - - query - .select(criteriaBuilder.count(from)); - - if (filter == null || filter.trim().isEmpty()) { - if (excluededImages != null && !excluededImages.isEmpty()) { - query.where(criteriaBuilder.not(from.in(excluededImages))); - } - } else { - if (excluededImages == null || excluededImages.isEmpty()) { - query.where(criteriaBuilder.like(titleValuesJoin, - String.format("%s%%", filter))); - } else { - query.where(criteriaBuilder.and( - criteriaBuilder.not(from.in(excluededImages)), - criteriaBuilder.like(titleValuesJoin, - String.format("%s%%", filter)))); - } - } - - final long result = entityManager.createQuery(query) - .getSingleResult(); - return result; - } - - @Transactional(Transactional.TxType.REQUIRED) - protected List getAvailableImages(final List excludedImages, - final String filter, - final long firstImage, - final long maxImages) { - - final CriteriaBuilder criteriaBuilder = entityManager - .getCriteriaBuilder(); - - final CriteriaQuery criteriaQuery = criteriaBuilder - .createQuery(Image.class); - final Root from = criteriaQuery.from(Image.class); - final Join titleJoin = from.join("title"); - final Join titleValuesJoin = titleJoin.join("values"); - - if (filter == null || filter.trim().isEmpty()) { - if (excludedImages != null && !excludedImages.isEmpty()) { - criteriaQuery.where(criteriaBuilder.not(from.in( - excludedImages))); - } - } else { - if (excludedImages == null || excludedImages.isEmpty()) { - criteriaQuery - .where(criteriaBuilder.like(titleValuesJoin, - String.format("%s%%", filter))); - } else { - criteriaQuery.where(criteriaBuilder.and( - criteriaBuilder.not(from.in(excludedImages)), - criteriaBuilder.like(titleValuesJoin, - String.format("%s%%", filter)))); - } - } - - final TypedQuery query = entityManager - .createQuery(criteriaQuery); - query.setFirstResult((int) firstImage); - query.setMaxResults((int) maxImages); - - final List result = query.getResultList(); - return result; - - } - - @Transactional(Transactional.TxType.REQUIRED) - protected List getAvailableImageRows( - final List excludedImages, - final Locale selectedLocale, - final String filter, - final long firstImage, - final long lastImage - ) { - - return getAvailableImages(excludedImages, filter, firstImage, - lastImage) - .stream() - .map(image -> buildAvailableImageRow(image, selectedLocale)) - .collect(Collectors.toList()); - - } - - private AvailableImageTableRow buildAvailableImageRow( - final Image image, final Locale selectedLocale) { - final AvailableImageTableRow row = new AvailableImageTableRow(); - row.setImageId(image.getObjectId()); - row.setImageUuid(image.getUuid()); - if (image.getTitle().hasValue(selectedLocale)) { - row.setTitle(image.getTitle().getValue(selectedLocale)); - } else if (image.getTitle().hasValue(defaultLocale)) { - row.setTitle(image.getTitle().getValue(defaultLocale)); - } else { - row.setTitle(image.getTitle().getValue()); - } - row.setFilename(image.getFileName()); - row.setWidth(image.getWidth()); - row.setHeight(image.getHeight()); - row.setType(image.getMimeType().toString()); - - return row; - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void attachImage(final ContentItem contentItem, - final long imageId) { - - final ContentItem item = itemRepo - .findById(contentItem.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", - contentItem.getObjectId()))); - - final List list = attachmentListManager - .getAttachmentList(item, ImageStep.IMAGES_ATTACHMENT_LIST); - - final AttachmentList addTo; - if (list == null || list.isEmpty()) { - addTo = attachmentListManager - .createAttachmentList(item, ImageStep.IMAGES_ATTACHMENT_LIST); - } else { - addTo = list.get(0); - } - - final Image image = assetRepo - .findById(imageId, Image.class) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No Image with ID %d in the database.", - imageId))); - - attachmentManager.attachAsset(image, addTo); - } - - private AssignedImageTableRow buildAssignedImageTableRow( - final ItemAttachment imageAttachment, - final Locale selectedLocale) { - - final AssignedImageTableRow row = new AssignedImageTableRow(); - - row.setAttachmentId(imageAttachment.getAttachmentId()); - - final Image image = imageAttachment.getAsset(); - row.setImageUuid(image.getUuid()); - row.setFilename(image.getFileName()); - row.setWidth(image.getWidth()); - row.setHeight(image.getHeight()); - row.setType(image.getMimeType().toString()); - if (image.getTitle().hasValue(selectedLocale)) { - row.setTitle(image.getTitle().getValue(selectedLocale)); - } else if (image.getTitle().hasValue(defaultLocale)) { - row.setTitle(image.getTitle().getValue(defaultLocale)); - } else { - row.setTitle(image.getTitle().getValue()); - } - row.setCaption(image.getDescription().getValue(selectedLocale)); - - return row; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentListTableRow.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentListTableRow.java deleted file mode 100644 index a1a17a345..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentListTableRow.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.relatedinfo; - -/** - * - * @author Jens Pelzetter - */ -class AttachmentListTableRow { - - private long listId; - private String name; - private String title; - private String description; - - public long getListId() { - return listId; - } - - public void setListId(final long listId) { - this.listId = listId; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getTitle() { - return title; - } - - public void setTitle(final String title) { - this.title = title; - } - - public String getDescription() { - return description; - } - - public void setDescription(final String description) { - this.description = description; - } - - - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentTableRow.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentTableRow.java deleted file mode 100644 index 2b60a1bac..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentTableRow.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.relatedinfo; - -import org.librecms.contentsection.Asset; - -/** - * - * @author Jens Pelzetter - */ -class AttachmentTableRow { - - private long attachmentId; - private String title; - private Class type; - - public long getAttachmentId() { - return attachmentId; - } - - public void setAttachmentId(final long attachmentId) { - this.attachmentId = attachmentId; - } - - public String getTitle() { - return title; - } - - public void setTitle(final String title) { - this.title = title; - } - - public Class getType() { - return type; - } - - public void setType(final Class type) { - this.type = type; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentsTable.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentsTable.java deleted file mode 100644 index 792a7abff..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentsTable.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.relatedinfo; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.event.TableActionEvent; -import com.arsdigita.bebop.event.TableActionListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableColumnModel; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.assets.AttachmentListSelectionModel; -import com.arsdigita.cms.ui.authoring.assets.AttachmentSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ItemAttachment; - -/** - * - * @author Jens Pelzetter - */ -class AttachmentsTable extends Table { - - protected static final int COL_TITLE = 0; - protected static final int COL_TYPE = 1; - protected static final int COL_MOVE = 2; - protected static final int COL_REMOVE = 3; - - private final RelatedInfoStep relatedInfoStep; - private final ItemSelectionModel itemSelectionModel; - private final AttachmentListSelectionModel attachmentListSelectionModel; - private final AttachmentSelectionModel selectedAttachmentModel; - private final AttachmentSelectionModel moveAttachmentModel; - private final StringParameter selectedLanguageParam; - - public AttachmentsTable( - final RelatedInfoStep relatedInfoStep, - final ItemSelectionModel itemSelectionModel, - final AttachmentListSelectionModel attachmentListSelectionModel, - final AttachmentSelectionModel selectedAttachmentModel, - final AttachmentSelectionModel moveAttachmentModel, - final StringParameter selectedLanguageParam) { - - super(); - - this.relatedInfoStep = relatedInfoStep; - this.itemSelectionModel = itemSelectionModel; - this.attachmentListSelectionModel = attachmentListSelectionModel; - this.selectedAttachmentModel = selectedAttachmentModel; - this.moveAttachmentModel = moveAttachmentModel; - this.selectedLanguageParam = selectedLanguageParam; - - final TableColumnModel columnModel = super.getColumnModel(); - columnModel.add(new TableColumn( - COL_TITLE, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.attachment.title", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_TYPE, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.attachment.type", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_MOVE, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.attachment.move", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_REMOVE, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.attachment.remove", - CmsConstants.CMS_BUNDLE)))); - - super - .setModelBuilder(new AttachmentsTableModelBuilder( - itemSelectionModel, - attachmentListSelectionModel, - moveAttachmentModel, - selectedLanguageParam)); - - super - .getColumn(COL_MOVE) - .setCellRenderer(new ControlLinkCellRenderer()); - super - .getColumn(COL_REMOVE) - .setCellRenderer(new ControlLinkCellRenderer()); - - setEmptyView(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.attachment.none", - CmsConstants.CMS_BUNDLE))); - - super - .addTableActionListener(new TableActionListener() { - - @Override - public void cellSelected(final TableActionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - final TableColumn column = getColumnModel() - .get(event.getColumn()); - - switch (column.getModelIndex()) { - case COL_MOVE: { - if (moveAttachmentModel - .getSelectedKey(state) == null) { - moveAttachmentModel - .setSelectedKey(state, - Long.parseLong( - (String) event - .getRowKey())); - } else { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final RelatedInfoStepController controller - = cdiUtil - .findBean( - RelatedInfoStepController.class); - - final ItemAttachment attachment - = moveAttachmentModel - .getSelectedAttachment(state); - - final Long destId = Long.parseLong( - (String) event.getRowKey()); - - controller.moveAfter( - attachmentListSelectionModel - .getSelectedAttachmentList(state), - attachment, - destId); - moveAttachmentModel.clearSelection(state); - - } - break; - } - case COL_REMOVE: { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final RelatedInfoStepController controller = cdiUtil - .findBean(RelatedInfoStepController.class); - controller.removeAttachment(Long.parseLong( - (String) event.getRowKey())); - } - default: - throw new IllegalArgumentException(String - .format("Illegal column index: %d", - column.getModelIndex())); - } - - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public void headSelected(final TableActionEvent event) { - //Nothing - } - - }); - - } - - private class ControlLinkCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - return new ControlLink((Component) value); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentsTableModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentsTableModel.java deleted file mode 100644 index 2cf29ea01..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentsTableModel.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.relatedinfo; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.cms.ui.authoring.assets.AttachmentSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.CmsConstants; -import org.librecms.assets.AssetTypeInfo; -import org.librecms.assets.AssetTypesManager; - -import java.util.Iterator; -import java.util.List; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -/** - * - * @author Jens Pelzetter - */ -class AttachmentsTableModel implements TableModel { - - private final PageState state; - private final AttachmentSelectionModel moveAttachmentModel; - - private final Iterator iterator; - private AttachmentTableRow currentRow; - - AttachmentsTableModel( - final List rows, - final PageState state, - final AttachmentSelectionModel moveAttachmentModel) { - - this.state = state; - this.moveAttachmentModel = moveAttachmentModel; - this.iterator = rows.iterator(); - } - - @Override - public int getColumnCount() { - return 4; - } - - @Override - public boolean nextRow() { - if (iterator.hasNext()) { - currentRow = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - - switch (columnIndex) { - case AttachmentsTable.COL_TITLE: - return currentRow.getTitle(); - case AttachmentsTable.COL_TYPE: { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AssetTypesManager typesManager = cdiUtil - .findBean(AssetTypesManager.class); - final AssetTypeInfo typeInfo = typesManager - .getAssetTypeInfo(currentRow.getType()); - try { - final ResourceBundle bundle = ResourceBundle - .getBundle(typeInfo.getLabelBundle()); - return bundle.getString(typeInfo.getLabelKey()); - } catch (MissingResourceException ex) { - return typeInfo.getAssetClass().getName(); - } - } - case AttachmentsTable.COL_MOVE: - if (moveAttachmentModel.getSelectedAttachment(state) == null) { - return new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.attachment.move", - CmsConstants.CMS_BUNDLE)); - } else { - return new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.attachment.move_here", - CmsConstants.CMS_BUNDLE)); - } - case AttachmentsTable.COL_REMOVE: - return new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.attachment.remove", - CmsConstants.CMS_BUNDLE)); - default: - throw new IllegalArgumentException(String.format( - "Illegal column index %d.", columnIndex)); - } - } - - @Override - public Object getKeyAt(final int columnIndex) { - return currentRow.getAttachmentId(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentsTableModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentsTableModelBuilder.java deleted file mode 100644 index 33d15c893..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/AttachmentsTableModelBuilder.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.relatedinfo; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.assets.AttachmentListSelectionModel; -import com.arsdigita.cms.ui.authoring.assets.AttachmentSelectionModel; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.AttachmentList; -import org.librecms.contentsection.ContentItem; - -import java.util.List; -import java.util.Locale; - -/** - * - * @author Jens Pelzetter - */ -class AttachmentsTableModelBuilder - extends LockableImpl - implements TableModelBuilder { - - private final ItemSelectionModel itemSelectionModel; - private final AttachmentListSelectionModel listSelectionModel; - private final AttachmentSelectionModel moveAttachmentModel; - private final StringParameter selectedLanguageParam; - - public AttachmentsTableModelBuilder( - final ItemSelectionModel itemSelectionModel, - final AttachmentListSelectionModel listSelectionModel, - final AttachmentSelectionModel moveAttachmentModel, - final StringParameter selectedLanguageParam) { - - super(); - - this.itemSelectionModel = itemSelectionModel; - this.listSelectionModel = listSelectionModel; - this.moveAttachmentModel = moveAttachmentModel; - this.selectedLanguageParam = selectedLanguageParam; - } - - @Override - public TableModel makeModel(final Table table, final PageState state) { - - final ContentItem selectedItem = itemSelectionModel - .getSelectedItem(state); - final AttachmentList list = listSelectionModel.getSelectedAttachmentList(state); - final String selectedLanguage = (String) state - .getValue(selectedLanguageParam); - final Locale selectedLocale = new Locale(selectedLanguage); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final RelatedInfoStepController controller = cdiUtil - .findBean(RelatedInfoStepController.class); - - final List rows = controller - .retrieveAttachments(selectedItem, list, selectedLocale); - - return new AttachmentsTableModel(rows, state, moveAttachmentModel); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/InternalLinkAddForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/InternalLinkAddForm.java deleted file mode 100644 index be658950c..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/InternalLinkAddForm.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.relatedinfo; - -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.assets.ItemSearchWidget; -import com.arsdigita.cms.ui.authoring.assets.AttachmentListSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; - -/** - * - * @author Jens Pelzetter - */ -public class InternalLinkAddForm - extends Form - implements FormInitListener, - FormProcessListener, - FormSubmissionListener { - - private final RelatedInfoStep relatedInfoStep; - private final ItemSelectionModel itemSelectionModel; - private final AttachmentListSelectionModel listSelectionModel; - private final StringParameter selectedLanguageParam; - - private final TextField titleField; -// private final TextArea descriptionArea; - private final ItemSearchWidget itemSearchWidget; - private final SaveCancelSection saveCancelSection; - - public InternalLinkAddForm( - final RelatedInfoStep relatedInfoStep, - final ItemSelectionModel itemSelectionModel, - final AttachmentListSelectionModel listSelectionModel, - final StringParameter selectedLanguageParam) { - - super("relatedinfo-attach-internallink-form"); - - this.relatedInfoStep = relatedInfoStep; - this.itemSelectionModel = itemSelectionModel; - this.listSelectionModel = listSelectionModel; - this.selectedLanguageParam = selectedLanguageParam; - - final Label titleLabel = new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.internal_link.title", - CmsConstants.CMS_BUNDLE)); - titleField = new TextField("link-title"); - -// descriptionArea = new TextArea("link-description"); - final Label itemSearchLabel = new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.internal_link.target_item", - CmsConstants.CMS_BUNDLE)); - itemSearchWidget = new ItemSearchWidget("link-item-search"); - - saveCancelSection = new SaveCancelSection(); - - super.add(titleLabel); - super.add(titleField); - super.add(itemSearchLabel); - super.add(itemSearchWidget); - super.add(saveCancelSection); - - super.addProcessListener(this); - super.addSubmissionListener(this); - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - - } - - @Override - public void process(final FormSectionEvent event) throws - FormProcessException { - - final PageState state = event.getPageState(); - - if (saveCancelSection.getSaveButton().isSelected(state)) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final RelatedInfoStepController controller = cdiUtil - .findBean(RelatedInfoStepController.class); - - controller.createInternalLink( - listSelectionModel.getSelectedAttachmentList(state), - (Long) itemSearchWidget.getValue(state), - (String) titleField.getValue(state), - (String) state.getValue(selectedLanguageParam)); - - relatedInfoStep.showAttachmentsTable(state); - } - } - - @Override - public void submitted(final FormSectionEvent event) throws - FormProcessException { - - if (saveCancelSection.getCancelButton().isSelected(event.getPageState())) { - relatedInfoStep.showAttachmentsTable(event.getPageState()); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoAttachAssetForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoAttachAssetForm.java deleted file mode 100644 index f4a713bb1..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoAttachAssetForm.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.relatedinfo; - -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.assets.AssetSearchWidget; -import com.arsdigita.cms.ui.authoring.assets.AttachmentListSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.UnexpectedErrorException; -import org.librecms.CmsConstants; -import org.librecms.contentsection.AttachmentList; - -/** - * - * @author Jens Pelzetter - */ -class RelatedInfoAttachAssetForm - extends Form - implements FormInitListener, - FormProcessListener, - FormSubmissionListener { - - private final RelatedInfoStep relatedInfoStep; - private final ItemSelectionModel itemSelectionModel; - private final AttachmentListSelectionModel listSelectionModel; - private final StringParameter selectedLanguageParameter; - - private final AssetSearchWidget searchWidget; - private final SaveCancelSection saveCancelSection; - - public RelatedInfoAttachAssetForm( - final RelatedInfoStep relatedInfoStep, - final ItemSelectionModel itemSelectionModel, - final AttachmentListSelectionModel listSelectionModel, - final StringParameter selectedLangugeParam) { - - super("relatedinfo-attach-asset-form"); - - this.relatedInfoStep = relatedInfoStep; - this.itemSelectionModel = itemSelectionModel; - this.listSelectionModel = listSelectionModel; - this.selectedLanguageParameter = selectedLangugeParam; - - final Label label = new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.attach_asset.selected_asset", - CmsConstants.CMS_BUNDLE)); - super.add(label); - searchWidget = new AssetSearchWidget("asset-search-widget"); - super.add(searchWidget); - saveCancelSection = new SaveCancelSection(); - super.add(saveCancelSection); - - super.addInitListener(this); - super.addProcessListener(this); - super.addSubmissionListener(this); - } -// -// @Override -// public void register(final Page page) { -// super.register(page); -// -// page.addComponentStateParam(this, itemSelectionModel.getStateParameter()); -// page.addComponentStateParam(this, listSelectionModel.getStateParameter()); -// } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - if (listSelectionModel.getSelectedKey(event.getPageState()) == null) { - throw new UnexpectedErrorException("The selected list null. " - + "This should not happen."); - } - } - - @Override - public void process(final FormSectionEvent event) throws - FormProcessException { - - final PageState state = event.getPageState(); - - if (listSelectionModel.getSelectedKey(state) == null) { - throw new UnexpectedErrorException("The selected list null. " - + "This should not happen."); - } - - final Object value = searchWidget.getValue(state); - if (value != null) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); -// final ItemAttachmentManager attachmentManager = cdiUtil -// .findBean(ItemAttachmentManager.class); -// final AssetRepository assetRepo = cdiUtil -// .findBean(AssetRepository.class); -// final Asset asset = assetRepo -// .findById((long) value) -// .orElseThrow(() -> new UnexpectedErrorException(String -// .format("No Asset with ID %d in the database.", value))); - - final AttachmentList list = listSelectionModel - .getSelectedAttachmentList(state); - -// attachmentManager.attachAsset(asset, list); - final RelatedInfoStepController controller = cdiUtil - .findBean(RelatedInfoStepController.class); - controller.attachAsset(list, (long) value); - } - - relatedInfoStep.showAttachmentsTable(state); - } - - @Override - public void submitted(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (saveCancelSection.getCancelButton().isSelected(state)) { - relatedInfoStep.showAttachmentsTable(state); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoListForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoListForm.java deleted file mode 100644 index fc0a223d1..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoListForm.java +++ /dev/null @@ -1,405 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.relatedinfo; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.GlobalizedParameterListener; -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.assets.AttachmentListSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.UnexpectedErrorException; -import org.librecms.CmsConstants; -import org.librecms.contentsection.AttachmentList; -import org.librecms.contentsection.AttachmentListL10NManager; -import org.librecms.contentsection.AttachmentListManager; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Optional; -import java.util.TooManyListenersException; - -/** - * - * @author Jens Pelzetter - */ -class RelatedInfoListForm - extends Form - implements FormInitListener, - FormProcessListener, - FormSubmissionListener { - - private final RelatedInfoStep relatedInfoStep; - private final ItemSelectionModel itemSelectionModel; - private final AttachmentListSelectionModel listSelectionModel; - private final StringParameter selectedLanguage; - - private BoxPanel showLocalePanel; - private SingleSelect showLocaleSelect; - private Submit showLocaleSubmit; - - private BoxPanel addLocalePanel; - private SingleSelect addLocaleSelect; - private Submit addLocaleSubmit; - - private TextField nameField; - private TextField titleField; - private TextArea descriptionArea; - - private SaveCancelSection saveCancelSection; - - public RelatedInfoListForm( - final RelatedInfoStep relatedInfoStep, - final ItemSelectionModel itemSelectionModel, - final AttachmentListSelectionModel listSelectionModel, - final StringParameter selectedLanguageParam) { - - super("relatedinfo-list-form", new BoxPanel(BoxPanel.VERTICAL)); - - this.relatedInfoStep = relatedInfoStep; - this.itemSelectionModel = itemSelectionModel; - this.listSelectionModel = listSelectionModel; - this.selectedLanguage = selectedLanguageParam; - - showLocalePanel = new BoxPanel(BoxPanel.HORIZONTAL); - final Label showLocaleLabel = new Label(event -> { - - final PageState state = event.getPageState(); - final Optional selectedList = getSelectedList(state); - final Label target = (Label) event.getTarget(); - if (selectedList.isPresent()) { - target.setLabel(new GlobalizedMessage( - "cms.ui.assetlist.show_locale", - CmsConstants.CMS_BUNDLE)); - } else { - target.setLabel(new GlobalizedMessage( - "cms.ui.assetlist.initial_locale", - CmsConstants.CMS_BUNDLE)); - } - }); - showLocaleSelect = new SingleSelect("selected-locale"); - try { - showLocaleSelect.addPrintListener(event -> { - - final PageState state = event.getPageState(); - - final Optional selectedList = getSelectedList( - state); - if (selectedList.isPresent()) { - final SingleSelect target = (SingleSelect) event.getTarget(); - - target.clearOptions();; - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AttachmentListL10NManager l10NManager = cdiUtil - .findBean(AttachmentListL10NManager.class); - final List availableLocales = new ArrayList<>( - l10NManager.availableLocales(selectedList.get())); - availableLocales.sort((locale1, locale2) -> { - return locale1.toString().compareTo(locale2.toString()); - }); - availableLocales.forEach(locale -> target.addOption( - new Option(locale.toString(), - new Text(locale.toString())))); - } else { - final SingleSelect target = (SingleSelect) event - .getTarget(); - - target.clearOptions(); - - final List langs = new ArrayList<>( - KernelConfig.getConfig().getSupportedLanguages()); - langs.sort((lang1, lang2) -> lang1.compareTo(lang2)); - - langs.forEach(lang -> { - target.addOption(new Option(lang, new Text(lang))); - }); - - } - - }); - } catch (TooManyListenersException ex) { - throw new UnexpectedErrorException(ex); - } - showLocaleSubmit = new Submit(new GlobalizedMessage( - "cms.ui.assetlist.show_locale", - CmsConstants.CMS_BUNDLE)) { - - @Override - public boolean isVisible(final PageState state) { - return getSelectedList(state).isPresent(); - } - - }; - showLocalePanel.add(showLocaleLabel); - showLocalePanel.add(showLocaleSelect); - showLocalePanel.add(showLocaleSubmit); - super.add(showLocalePanel); - - addLocalePanel = new BoxPanel(BoxPanel.HORIZONTAL) { - - @Override - public boolean isVisible(final PageState state) { - return getSelectedList(state).isPresent(); - } - - }; - final Label addLocaleLabel = new Label( - new GlobalizedMessage("cms.ui.assetlist.add_locale", - CmsConstants.CMS_BUNDLE)); - addLocaleSelect = new SingleSelect("add-locale-select"); - try { - addLocaleSelect.addPrintListener(event -> { - - final PageState state = event.getPageState(); - final Optional selectedList = getSelectedList( - state); - if (selectedList.isPresent()) { - final SingleSelect target = (SingleSelect) event.getTarget(); - - target.clearOptions(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AttachmentListL10NManager l10nManager = cdiUtil - .findBean(AttachmentListL10NManager.class); - final List creatableLocales = new ArrayList<>( - l10nManager.creatableLocales(selectedList.get())); - creatableLocales.sort((locale1, locale2) -> { - return locale1 - .toString() - .compareTo(locale2.toString()); - }); - creatableLocales.forEach(locale -> target.addOption( - new Option(locale.toString(), - new Text(locale.toString())))); - - } - - }); - } catch (TooManyListenersException ex) { - throw new UnexpectedErrorException(ex); - } - addLocaleSubmit = new Submit(new GlobalizedMessage( - "cms.ui.assetlist.add_locale", - CmsConstants.CMS_BUNDLE)); - addLocalePanel.add(addLocaleLabel); - addLocalePanel.add(addLocaleSelect); - addLocalePanel.add(addLocaleSubmit); - super.add(addLocalePanel); - - super.add(new Label(new GlobalizedMessage("cms.ui.assetlist.name", - CmsConstants.CMS_BUNDLE))); - nameField = new TextField("attachmentListName"); - nameField.addValidationListener(new AssetListNameValidator()); - super.add(nameField); - - super.add(new Label(new GlobalizedMessage("cms.ui.assetlist.title", - CmsConstants.CMS_BUNDLE))); - titleField = new TextField("attachmentListTitle"); - super.add(titleField); - - super.add(new Label( - new GlobalizedMessage("cms.ui.assetlist.description", - CmsConstants.CMS_BUNDLE))); - descriptionArea = new TextArea("attachmentListDesc"); - super.add(descriptionArea); - - saveCancelSection = new SaveCancelSection(); - super.add(saveCancelSection); - - super.addInitListener(this); - super.addProcessListener(this); - super.addSubmissionListener(this); - } - - protected Optional getSelectedList(final PageState state) { - - if (listSelectionModel.getSelectedKey(state) == null) { - return Optional.empty(); - } else { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final AttachmentListManager manager = cdiUtil - .findBean(AttachmentListManager.class); - final AttachmentList list = manager - .getAttachmentList(listSelectionModel.getSelectedKey(state)) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No AttachmentList with ID %d in the database.", - listSelectionModel.getSelectedKey(state)))); - return Optional.of(list); - } - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - - final PageState state = event.getPageState(); - - final Optional selectedList = getSelectedList(state); - - if (selectedList.isPresent()) { - - nameField.setValue(state, selectedList.get().getName()); - - showLocaleSelect.setValue(state, - KernelConfig - .getConfig() - .getDefaultLocale() - .toString()); - - titleField.setValue(state, - selectedList - .get() - .getTitle() - .getValue(getSelectedLocale(state))); - - descriptionArea.setValue(state, - selectedList - .get() - .getTitle() - .getValue(getSelectedLocale(state))); - } else { - showLocaleSelect.setValue(state, - KernelConfig - .getConfig() - .getDefaultLocale() - .toString()); - } - } - - protected Locale getSelectedLocale(final PageState state) { - final String selected = (String) showLocaleSelect.getValue(state); - if (selected == null) { - return KernelConfig.getConfig().getDefaultLocale(); - } else { - return new Locale(selected); - } - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - - if (showLocaleSubmit.isSelected(state)) { - - return; - } - - if (addLocaleSubmit.isSelected(state)) { - final AttachmentListL10NManager l10nManager = cdiUtil - .findBean(AttachmentListL10NManager.class); - final Locale add = new Locale((String) addLocaleSelect - .getValue(state)); - final Optional selectedList = getSelectedList(state); - l10nManager.addLanguage(selectedList.get(), add); - } - - if (saveCancelSection.getSaveButton().isSelected(state)) { - - final RelatedInfoStepController controller = cdiUtil - .findBean(RelatedInfoStepController.class); - final AttachmentListManager attachmentListManager = cdiUtil - .findBean(AttachmentListManager.class); - - final Optional selectedList = getSelectedList(state); - final AttachmentList attachmentList; - if (selectedList.isPresent()) { - attachmentList = selectedList.get(); - } else { - attachmentList = attachmentListManager - .createAttachmentList(itemSelectionModel - .getSelectedItem(state), - (String) nameField.getValue(state)); - } - - attachmentList.setName((String) nameField.getValue(state)); - attachmentList - .getTitle() - .putValue(getSelectedLocale(state), - (String) titleField.getValue(state)); - attachmentList - .getDescription() - .putValue(getSelectedLocale(state), - (String) descriptionArea.getValue(state)); - - controller.saveAttachmentList(attachmentList); - } - - relatedInfoStep.showAttachmentListTable(state); - } - - @Override - public void submitted(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (saveCancelSection.getCancelButton().isSelected(state)) { - listSelectionModel.clearSelection(state); - relatedInfoStep.showAttachmentListTable(state); - } - } - - private class AssetListNameValidator extends GlobalizedParameterListener { - - public AssetListNameValidator() { - super.setError(new GlobalizedMessage( - "cms.ui.assetlist.name_cant_start_with_dot", - CmsConstants.CMS_BUNDLE)); - } - - @Override - public void validate(final ParameterEvent event) throws - FormProcessException { - - final ParameterData data = event.getParameterData(); - final String value = (String) data.getValue(); - - if (value.startsWith(".")) { - data.addError(getError()); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoListTable.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoListTable.java deleted file mode 100644 index b9837dd7a..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoListTable.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.relatedinfo; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.event.TableActionEvent; -import com.arsdigita.bebop.event.TableActionListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableColumnModel; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.assets.AttachmentListSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.AttachmentList; - -/** - * - * @author Jens Pelzetter - */ -class RelatedInfoListTable extends Table { - - protected static final int COL_NAME = 0; - protected static final int COL_TITLE = 1; - protected static final int COL_DESC = 2; - protected static final int COL_EDIT = 3; - protected static final int COL_MOVE = 4; - protected static final int COL_DELETE = 5; - - private final RelatedInfoStep relatedInfoStep; - private final ItemSelectionModel itemSelectionModel; - private final AttachmentListSelectionModel selectedListModel; - private final AttachmentListSelectionModel moveListModel; - private final StringParameter selectedLanguageParam; - - protected RelatedInfoListTable( - final RelatedInfoStep relatedInfoStep, - final ItemSelectionModel itemSelectionModel, - final AttachmentListSelectionModel selectedListModel, - final AttachmentListSelectionModel moveListModel, - final StringParameter selectedLanguageParam) { - - super(); - this.relatedInfoStep = relatedInfoStep; - this.itemSelectionModel = itemSelectionModel; - this.selectedListModel = selectedListModel; - this.moveListModel = moveListModel; - this.selectedLanguageParam = selectedLanguageParam; - - final TableColumnModel columnModel = super.getColumnModel(); - columnModel.add(new TableColumn( - COL_NAME, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.list.name", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_TITLE, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.list.title", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_DESC, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.list.description", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_EDIT, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.list.edit", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_MOVE, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.list.move", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_DELETE, - new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.list.delete", - CmsConstants.CMS_BUNDLE)))); - - super - .setModelBuilder(new RelatedInfoListTableModelBuilder( - itemSelectionModel, - moveListModel, - selectedLanguageParam)); - - super - .getColumn(COL_NAME) - .setCellRenderer(new ControlLinkCellRenderer()); - super - .getColumn(COL_EDIT) - .setCellRenderer(new ControlLinkCellRenderer()); - super - .getColumn(COL_MOVE) - .setCellRenderer(new ControlLinkCellRenderer()); - super - .getColumn(COL_DELETE) - .setCellRenderer(new ControlLinkCellRenderer()); - - super.setEmptyView(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.list.none", - CmsConstants.CMS_BUNDLE))); - - super - .addTableActionListener(new TableActionListener() { - - @Override - public void cellSelected(final TableActionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - final TableColumn column = getColumnModel() - .get(event.getColumn()); - - switch (column.getModelIndex()) { - case COL_NAME: - selectedListModel - .setSelectedKey(state, - Long.parseLong((String) event - .getRowKey())); - relatedInfoStep.showAttachmentsTable(state); - break; - case COL_EDIT: - selectedListModel - .setSelectedKey(state, - Long.parseLong((String) event - .getRowKey())); - relatedInfoStep.showListEditForm(state); - break; - case COL_MOVE: - if (moveListModel.getSelectedKey(state) == null) { - - moveListModel - .setSelectedKey(state, - Long.parseLong( - (String) event - .getRowKey())); - } else { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final RelatedInfoStepController controller - = cdiUtil - .findBean( - RelatedInfoStepController.class); - - final AttachmentList selectedList - = moveListModel - .getSelectedAttachmentList(state); - - final Long destId = Long - .parseLong((String) event.getRowKey()); - - controller.moveAfter(itemSelectionModel - .getSelectedItem(state), - selectedList, - destId); - moveListModel.clearSelection(state); - } - break; - case COL_DELETE: { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final RelatedInfoStepController controller = cdiUtil - .findBean(RelatedInfoStepController.class); - controller.deleteList(Long - .parseLong((String) event.getRowKey())); - break; - } - default: - throw new IllegalArgumentException(String - .format("Illegal column index: %d", - column.getModelIndex())); - } - } - - @Override - public void headSelected(final TableActionEvent event) { - //Nothing - } - - }); - } - - private class ControlLinkCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - return new ControlLink((Component) value); - } - - } -// -// private class MoveCellRenderer implements TableCellRenderer { -// -// @Override -// public Component getComponent(final Table table, -// final PageState state, -// final Object value, -// final boolean isSelected, -// final Object key, -// final int row, -// final int column) { -// -// return new ControlLink((Component) value); -// } -// -// } -// -// private class EditCellRenderer implements TableCellRenderer { -// -// @Override -// public Component getComponent(final Table table, -// final PageState state, -// final Object value, -// final boolean isSelected, -// final Object key, -// final int row, -// final int column) { -// -// return new ControlLink((Component) value); -// } -// -// } -// -// private class DeleteCellRenderer implements TableCellRenderer { -// -// @Override -// public Component getComponent(final Table table, -// final PageState state, -// final Object value, -// final boolean isSelected, -// final Object key, -// final int row, -// final int column) { -// -// return new ControlLink((Component) value); -// } -// -//} - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoListTableModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoListTableModel.java deleted file mode 100644 index 3651c9082..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoListTableModel.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.relatedinfo; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.cms.ui.authoring.assets.AttachmentListSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; - -import java.util.Iterator; -import java.util.List; - -/** - * - * @author Jens Pelzetter - */ -class RelatedInfoListTableModel implements TableModel { - - private final PageState state; - private final AttachmentListSelectionModel moveListModel; - - private final Iterator iterator; - private AttachmentListTableRow currentRow; - - RelatedInfoListTableModel( - final List rows, - final PageState state, - final AttachmentListSelectionModel moveListModel) { - - this.iterator = rows.iterator(); - this.state = state; - this.moveListModel = moveListModel; - } - - @Override - public int getColumnCount() { - return 6; - } - - @Override - public boolean nextRow() { - if (iterator.hasNext()) { - currentRow = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - - switch (columnIndex) { - case RelatedInfoListTable.COL_NAME: - return new Text(currentRow.getName()); - case RelatedInfoListTable.COL_TITLE: - return new Text(currentRow.getTitle()); - case RelatedInfoListTable.COL_DESC: - return new Text(currentRow.getDescription()); - case RelatedInfoListTable.COL_EDIT: - return new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.list.edit", - CmsConstants.CMS_BUNDLE)); - case RelatedInfoListTable.COL_MOVE: - if (moveListModel.getSelectedAttachmentList(state) == null) { - return new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.list.move", - CmsConstants.CMS_BUNDLE)); - } else { - return new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.list.move_here", - CmsConstants.CMS_BUNDLE)); - } - case RelatedInfoListTable.COL_DELETE: - return new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.list.delete", - CmsConstants.CMS_BUNDLE)); - default: - throw new IllegalArgumentException(String.format( - "Illegal column index %d.", columnIndex)); - } - } - - @Override - public Object getKeyAt(final int columnIndex) { - return currentRow.getListId(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoListTableModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoListTableModelBuilder.java deleted file mode 100644 index 9bf752d3c..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoListTableModelBuilder.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.relatedinfo; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.assets.AttachmentListSelectionModel; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentItem; - -import java.util.List; -import java.util.Locale; - -/** - * - * @author Jens Pelzetter - */ -class RelatedInfoListTableModelBuilder - extends LockableImpl - implements TableModelBuilder { - - private final ItemSelectionModel itemSelectionModel; - private final AttachmentListSelectionModel moveListModel; - private final StringParameter selectedLanguageParam; - - protected RelatedInfoListTableModelBuilder( - final ItemSelectionModel itemSelectionModel, - final AttachmentListSelectionModel moveListModel, - final StringParameter selectedLanguageParam) { - - super(); - - this.itemSelectionModel = itemSelectionModel; - this.moveListModel = moveListModel; - this.selectedLanguageParam = selectedLanguageParam; - } - - @Override - public TableModel makeModel(final Table table, final PageState state) { - - final ContentItem selectedItem = itemSelectionModel - .getSelectedItem(state); - final String selectedLanguage = (String) state - .getValue(selectedLanguageParam); - final Locale selectedLocale = new Locale(selectedLanguage); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final RelatedInfoStepController controller = cdiUtil - .findBean(RelatedInfoStepController.class); - - final List rows = controller - .retrieveAttachmentLists(selectedItem, selectedLocale); - - return new RelatedInfoListTableModel(rows, state, moveListModel); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoStep.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoStep.java deleted file mode 100644 index d761f228d..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoStep.java +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.relatedinfo; - -import com.arsdigita.bebop.ActionLink; -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.ResettableContainer; -import com.arsdigita.cms.ui.authoring.assets.AttachmentListSelectionModel; -import com.arsdigita.cms.ui.authoring.assets.AttachmentSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.AttachmentList; -import org.librecms.contentsection.ItemAttachment; -import org.librecms.ui.authoring.ContentItemAuthoringStep; - -/** - * - * @author Jens Pelzetter - */ -@ContentItemAuthoringStep( - labelBundle = CmsConstants.CMS_BUNDLE, - labelKey = "related_info_step.label", - descriptionBundle = CmsConstants.CMS_BUNDLE, - descriptionKey = "related_info_step.description") -public class RelatedInfoStep extends ResettableContainer { - - private final ItemSelectionModel itemSelectionModel; - private final AuthoringKitWizard authoringKitWizard; - private final StringParameter selectedLanguageParam; - - private final AttachmentListSelectionModel selectedListModel; - private final AttachmentListSelectionModel moveListModel; - - private final RelatedInfoListTable listTable; - private final RelatedInfoListForm listForm; - private final ActionLink addListLink; - private final ActionLink listToFirstLink; - - private final AttachmentSelectionModel selectedAttachmentModel; - private final AttachmentSelectionModel moveAttachmentModel; - - private final AttachmentsTable attachmentsTable; - private final RelatedInfoAttachAssetForm attachAssetForm; - private final InternalLinkAddForm internalLinkAddForm; - - private final ActionLink attachAssetLink; - private final ActionLink internalLinkAddLink; - private final ActionLink attachmentToFirstLink; - - public RelatedInfoStep(final ItemSelectionModel itemSelectionModel, - final AuthoringKitWizard authoringKitWizard, - final StringParameter selectedLanguage) { - - super(); - - this.itemSelectionModel = itemSelectionModel; - this.authoringKitWizard = authoringKitWizard; - this.selectedLanguageParam = selectedLanguage; - - selectedListModel = new AttachmentListSelectionModel( - "selected-attachment-list"); - moveListModel = new AttachmentListSelectionModel( - "move-attachment-list-model"); - - listTable = new RelatedInfoListTable(this, - itemSelectionModel, - selectedListModel, moveListModel, - selectedLanguageParam); - listForm = new RelatedInfoListForm(this, - itemSelectionModel, - selectedListModel, - selectedLanguageParam); - - addListLink = new ActionLink(new Label(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.add_list", - CmsConstants.CMS_BUNDLE))); - addListLink.addActionListener(event -> { - showListEditForm(event.getPageState()); - }); - - listToFirstLink = new ActionLink(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.attachment_list" - + ".move_to_beginning", - CmsConstants.CMS_BUNDLE)); - listToFirstLink.addActionListener(event -> { - final PageState state = event.getPageState(); - final AttachmentList toMove = moveListModel - .getSelectedAttachmentList(state); - - final RelatedInfoStepController controller = CdiUtil - .createCdiUtil() - .findBean(RelatedInfoStepController.class); - - controller.moveToFirst(itemSelectionModel.getSelectedItem(state), - toMove); - - moveListModel.clearSelection(state); - }); - - moveListModel.addChangeListener(event -> { - - final PageState state = event.getPageState(); - - if (moveListModel.getSelectedKey(state) == null) { - addListLink.setVisible(state, true); - listToFirstLink.setVisible(state, false); - } else { - addListLink.setVisible(state, false); - listToFirstLink.setVisible(state, true); - } - }); - - selectedAttachmentModel = new AttachmentSelectionModel( - "selected-attachment-model"); - moveAttachmentModel = new AttachmentSelectionModel( - "move-attachment-model"); - - attachmentsTable = new AttachmentsTable(this, itemSelectionModel, - selectedListModel, - selectedAttachmentModel, - moveAttachmentModel, - selectedLanguageParam); - attachAssetForm = new RelatedInfoAttachAssetForm(this, - itemSelectionModel, - selectedListModel, - selectedLanguageParam); - internalLinkAddForm = new InternalLinkAddForm(this, - itemSelectionModel, - selectedListModel, - selectedLanguageParam); - - - attachAssetLink = new ActionLink(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.attach_asset", - CmsConstants.CMS_BUNDLE)); - attachAssetLink.addActionListener(event -> { - showAttachAssetForm(event.getPageState()); - }); - - internalLinkAddLink = new ActionLink(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.add_internal_link", - CmsConstants.CMS_BUNDLE)); - internalLinkAddLink.addActionListener(event -> { - showAddInternalLinkForm(event.getPageState()); - }); - - attachmentToFirstLink = new ActionLink(new GlobalizedMessage( - "cms.ui.authoring.assets.related_info_step.attachment.move_to_first", - CmsConstants.CMS_BUNDLE)); - attachmentToFirstLink.addActionListener(event -> { - final PageState state = event.getPageState(); - final ItemAttachment toMove = moveAttachmentModel - .getSelectedAttachment(state); - - final RelatedInfoStepController controller = CdiUtil - .createCdiUtil() - .findBean(RelatedInfoStepController.class); - - controller.moveToFirst(selectedListModel - .getSelectedAttachmentList(state), toMove); - - moveAttachmentModel.clearSelection(state); - }); - - moveAttachmentModel.addChangeListener(event -> { - - final PageState state = event.getPageState(); - - if (moveAttachmentModel.getSelectedKey(state) == null) { - attachAssetLink.setVisible(state, true); - attachmentToFirstLink.setVisible(state, false); - } else { - attachAssetLink.setVisible(state, false); - attachmentToFirstLink.setVisible(state, true); - } - }); - - final SimpleContainer addLinks = new SimpleContainer(); - addLinks.add(addListLink); - addLinks.add(internalLinkAddLink); - - final BoxPanel panel = new BoxPanel(BoxPanel.VERTICAL); - - panel.add(addLinks); - panel.add(listToFirstLink); - panel.add(listTable); - panel.add(listForm); - - panel.add(attachAssetLink); - panel.add(attachmentToFirstLink); - panel.add(attachmentsTable); - panel.add(attachAssetForm); - panel.add(internalLinkAddForm); - - super.add(panel); - } - - @Override - public void register(final Page page) { - - super.register(page); - - page.addComponentStateParam(this, selectedListModel.getStateParameter()); - page.addComponentStateParam(this, moveListModel.getStateParameter()); - page.addComponentStateParam(this, - selectedAttachmentModel.getStateParameter()); - page.addComponentStateParam(this, - moveAttachmentModel.getStateParameter()); - - page.setVisibleDefault(listTable, true); - page.setVisibleDefault(listForm, false); - page.setVisibleDefault(addListLink, true); - page.setVisibleDefault(listToFirstLink, false); - page.setVisibleDefault(attachmentsTable, false); - page.setVisibleDefault(attachAssetForm, false); - page.setVisibleDefault(internalLinkAddForm, false); - page.setVisibleDefault(internalLinkAddLink, false); - page.setVisibleDefault(attachAssetLink, false); - page.setVisibleDefault(attachmentToFirstLink, false); - } - - protected void showAttachmentListTable(final PageState state) { - - listTable.setVisible(state, true); - addListLink.setVisible(state, true); - listForm.setVisible(state, false); - listToFirstLink.setVisible(state, false); - attachmentsTable.setVisible(state, false); - attachAssetForm.setVisible(state, false); - attachAssetLink.setVisible(state, false); - attachmentToFirstLink.setVisible(state, false); - internalLinkAddForm.setVisible(state, false); - internalLinkAddLink.setVisible(state, false); - } - - void showListEditForm(final PageState state) { - - listTable.setVisible(state, false); - listForm.setVisible(state, true); - addListLink.setVisible(state, false); - listToFirstLink.setVisible(state, false); - attachmentsTable.setVisible(state, false); - attachAssetForm.setVisible(state, false); - attachAssetLink.setVisible(state, false); - attachmentToFirstLink.setVisible(state, false); - internalLinkAddForm.setVisible(state, false); - internalLinkAddLink.setVisible(state, false); - } - - void showAttachmentsTable(final PageState state) { - - listTable.setVisible(state, false); - listForm.setVisible(state, false); - addListLink.setVisible(state, false); - listToFirstLink.setVisible(state, false); - attachmentsTable.setVisible(state, true); - attachAssetForm.setVisible(state, false); - attachAssetLink.setVisible(state, true); - attachmentToFirstLink.setVisible(state, false); - internalLinkAddForm.setVisible(state, false); - internalLinkAddLink.setVisible(state, true); - } - - void showAttachAssetForm(final PageState state) { - listTable.setVisible(state, false); - listForm.setVisible(state, false); - addListLink.setVisible(state, false); - listToFirstLink.setVisible(state, false); - attachmentsTable.setVisible(state, false); - attachAssetForm.setVisible(state, true); - attachAssetLink.setVisible(state, false); - attachmentToFirstLink.setVisible(state, false); - internalLinkAddForm.setVisible(state, false); - internalLinkAddLink.setVisible(state, false); - } - - void showAddInternalLinkForm(final PageState state) { - listTable.setVisible(state, false); - listForm.setVisible(state, false); - addListLink.setVisible(state, false); - listToFirstLink.setVisible(state, false); - attachmentsTable.setVisible(state, false); - attachAssetForm.setVisible(state, false); - attachAssetLink.setVisible(state, false); - attachmentToFirstLink.setVisible(state, false); - internalLinkAddForm.setVisible(state, true); - internalLinkAddLink.setVisible(state, false); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoStepController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoStepController.java deleted file mode 100644 index 43f47f0a1..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/assets/relatedinfo/RelatedInfoStepController.java +++ /dev/null @@ -1,411 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.assets.relatedinfo; - -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.core.UnexpectedErrorException; -import org.librecms.assets.RelatedLink; -import org.librecms.contentsection.Asset; -import org.librecms.contentsection.AssetRepository; -import org.librecms.contentsection.AttachmentList; -import org.librecms.contentsection.AttachmentListManager; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ItemAttachment; -import org.librecms.contentsection.ItemAttachmentManager; - -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.stream.Collectors; - -import javax.annotation.PostConstruct; -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.persistence.EntityManager; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class RelatedInfoStepController { - - @Inject - private AssetRepository assetRepo; - - @Inject - private AttachmentListManager attachmentListManager; - - @Inject - private ConfigurationManager confManager; - - @Inject - private ContentItemRepository itemRepo; - - @Inject - private EntityManager entityManager; - - @Inject - private ItemAttachmentManager itemAttachmentManager; - - private Locale defaultLocale; - - @PostConstruct - private void init() { - - final KernelConfig kernelConfig = confManager - .findConfiguration(KernelConfig.class); - defaultLocale = kernelConfig.getDefaultLocale(); - - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void saveAttachmentList(final AttachmentList attachmentList) { - - if (attachmentList.getListId() == 0) { - entityManager.persist(attachmentList); - } else { - entityManager.merge(attachmentList); - } - } - - @Transactional(Transactional.TxType.REQUIRED) - void moveToFirst(final ContentItem selectedItem, - final AttachmentList listToMove) { - - Objects.requireNonNull(selectedItem); - Objects.requireNonNull(listToMove); - - final ContentItem item = itemRepo - .findById(selectedItem.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", - selectedItem.getObjectId()))); - - final AttachmentList toMove = attachmentListManager - .getAttachmentList(listToMove.getListId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No AttachmentList with ID %d in the database.", - listToMove.getListId()))); - - final List lists = item - .getAttachments() - .stream() - .sorted((list1, list2) -> list1.compareTo(list2)) - .collect(Collectors.toList()); - - toMove.setListOrder(0); - lists - .stream() - .filter(current -> !current.equals(toMove)) - .forEach(current -> current.setListOrder(current.getListOrder() + 1)); - - lists.forEach(entityManager::merge); - } - - @Transactional(Transactional.TxType.REQUIRED) - void moveToFirst(final AttachmentList selectedList, - final ItemAttachment attachmentToMove) { - - Objects.requireNonNull(selectedList); - Objects.requireNonNull(attachmentToMove); - - final AttachmentList list = attachmentListManager - .getAttachmentList(selectedList.getListId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No AttachmentList with ID %d in the database.", - selectedList.getListId()))); - - final ItemAttachment toMove = itemAttachmentManager - .findById(attachmentToMove.getAttachmentId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ItemAttachment with ID %d in the database.", - attachmentToMove.getAttachmentId()))); - - final List> attachments = list - .getAttachments() - .stream() - .sorted((attachment1, attachment2) -> { - return attachment1.compareTo(attachment2); - }) - .collect(Collectors.toList()); - - toMove.setSortKey(0); - attachments - .stream() - .filter(current -> !current.equals(toMove)) - .forEach(current -> current.setSortKey(current.getSortKey() + 1)); - - attachments.forEach(entityManager::merge); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void moveAfter(final ContentItem selectedItem, - final AttachmentList listToMove, - final Long destId) { - - Objects.requireNonNull(selectedItem); - Objects.requireNonNull(listToMove); - - final ContentItem item = itemRepo - .findById(selectedItem.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", - selectedItem.getObjectId()))); - - final AttachmentList toMove = attachmentListManager - .getAttachmentList(listToMove.getListId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No AttachmentList with ID %d in the database.", - listToMove.getListId()))); - - final AttachmentList after = attachmentListManager - .getAttachmentList(destId) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No AttachmentList with ID %d in the database.", destId))); - - final List lists = item - .getAttachments() - .stream() - .sorted((list1, list2) -> list1.compareTo(list2)) - .collect(Collectors.toList()); - - if (!lists.contains(toMove)) { - throw new IllegalArgumentException(String - .format("AttachmentList %d is not part of ContentItem %d.", - toMove.getListId(), - item.getObjectId())); - } - - if (!lists.contains(after)) { - throw new IllegalArgumentException(String - .format("AttachmentList %d is not part of ContentItem %d.", - after.getListId(), - item.getObjectId())); - } - - final int afterIndex = lists.indexOf(after); - for (int i = afterIndex + 1; i < lists.size(); i++) { - final AttachmentList current = lists.get(i); - current.setListOrder(current.getListOrder() + 1); - entityManager.merge(current); - } - - toMove.setListOrder(afterIndex + 1); - entityManager.merge(toMove); - } - - protected void moveAfter(final AttachmentList list, - final ItemAttachment attachment, - final long destId) { - //ToDo - throw new UnsupportedOperationException(); - } - - protected void deleteList(final Long listId) { - - final AttachmentList list = attachmentListManager - .getAttachmentList(listId) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No AttachmentList with ID %d in the database.", - listId))); - - entityManager.remove(list); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void removeAttachment(final long attachmentId) { - - final ItemAttachment attachment = itemAttachmentManager - .findById(attachmentId) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ItemAttachment with ID %d in the database.", - attachmentId))); - - entityManager.remove(attachment); - - } - - @Transactional(Transactional.TxType.REQUIRED) - protected List retrieveAttachmentLists( - final ContentItem forContentItem, - final Locale selectedLocale) { - - final ContentItem item = itemRepo - .findById(forContentItem.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", - forContentItem.getObjectId()))); - - return item.getAttachments() - .stream() - .filter(list -> !list.getName().startsWith(".")) - .map(list -> buildAttachmentListTableRow(list, selectedLocale)) - .collect(Collectors.toList()); - - } - - @Transactional(Transactional.TxType.REQUIRED) - protected List retrieveAttachments( - final ContentItem selectedItem, - final AttachmentList fromList, - final Locale selectedLocale) { - - final AttachmentList list = attachmentListManager - .getAttachmentList(fromList.getListId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No AttachmentList with ID %d in the database.", - fromList.getListId()))); - - return list - .getAttachments() - .stream() - .map(attachment -> buildAttachmentTableRow(attachment, - selectedLocale)) - .collect(Collectors.toList()); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void createInternalLink(final AttachmentList attachmentList, - final long targetItemId, - final String title, - // final String description, - final String selectedLanguage) { - - final ContentItem targetItem = itemRepo - .findById(targetItemId) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", targetItemId))); - - final RelatedLink link = new RelatedLink(); - link.setTargetItem(targetItem); - final Locale selectedLocale = new Locale(selectedLanguage); - link.getTitle().putValue(selectedLocale, title); - - final AttachmentList list = attachmentListManager - .getAttachmentList(attachmentList.getListId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No AttachmentList with Id %d in the database.", - attachmentList.getListId()))); - - itemAttachmentManager.attachAsset(link, list); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void attachAsset(final AttachmentList attachmentList, - final long assetId) { - - final Asset asset = assetRepo - .findById(assetId) - .orElseThrow(() -> new UnexpectedErrorException(String - .format("No Asset with ID %d in the database.", assetId))); - - final AttachmentList list = attachmentListManager - .getAttachmentList(attachmentList.getListId()) - .orElseThrow(() -> new UnexpectedErrorException(String - .format("No AttachmentList with ID %d in the database.", - attachmentList.getListId()))); - - itemAttachmentManager.attachAsset(asset, list); - } - - private AttachmentListTableRow buildAttachmentListTableRow( - final AttachmentList attachmentList, - final Locale selectedLocale) { - - final AttachmentListTableRow row = new AttachmentListTableRow(); - - row.setListId(attachmentList.getListId()); - - row.setName(attachmentList.getName()); - if (attachmentList.getTitle().hasValue(selectedLocale)) { - row.setTitle(attachmentList.getTitle().getValue(selectedLocale)); - } else if (attachmentList.getTitle().hasValue(defaultLocale)) { - row.setTitle(attachmentList.getTitle().getValue(defaultLocale)); - } else { - row.setTitle(attachmentList.getTitle().getValue()); - } - - if (attachmentList.getDescription().hasValue(selectedLocale)) { - row.setDescription(shortenDescription(attachmentList - .getDescription() - .getValue(selectedLocale))); - } else if (attachmentList.getDescription().hasValue(defaultLocale)) { - row.setDescription(shortenDescription(attachmentList - .getDescription() - .getValue(defaultLocale))); - } else { - row.setDescription(shortenDescription(attachmentList - .getDescription() - .getValue())); - } - - return row; - } - - private AttachmentTableRow buildAttachmentTableRow( - final ItemAttachment attachment, - final Locale selectedLocale) { - - final AttachmentTableRow row = new AttachmentTableRow(); - - row.setAttachmentId(attachment.getAttachmentId()); - if (attachment.getAsset().getTitle().hasValue(selectedLocale)) { - row.setTitle(attachment - .getAsset() - .getTitle() - .getValue(selectedLocale)); - } else if (attachment.getAsset().getTitle().hasValue(defaultLocale)) { - row.setTitle(attachment - .getAsset() - .getTitle() - .getValue(defaultLocale)); - } else { - row.setTitle(attachment - .getAsset() - .getTitle() - .getValue()); - } - - row.setType(attachment.getAsset().getClass()); - - return row; - } - - private String shortenDescription(final String description) { - - if (description == null) { - return ""; - } else if (description.trim().length() < 140) { - return description.trim(); - } else { - final String tmp = description.trim().substring(0, 140); - - return String - .format("%s...", - tmp.substring(0, tmp.lastIndexOf(" "))); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/event/EventPropertiesStep.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/event/EventPropertiesStep.java deleted file mode 100755 index a26917db9..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/event/EventPropertiesStep.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.event; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.parameters.StringParameter; - -import com.arsdigita.cms.ItemSelectionModel; - -import org.librecms.contenttypes.Event; - -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.BasicPageForm; -import com.arsdigita.cms.ui.authoring.SimpleEditStep; -import com.arsdigita.cms.ui.workflow.WorkflowLockedComponentAccess; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ToolboxConstants; -import com.arsdigita.toolbox.ui.DomainObjectPropertySheet; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.CmsConstants; -import org.librecms.contenttypes.EventConfig; - -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.text.DateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.Optional; - -/** - * Authoring step to view/edit the simple attributes of the Event content type - * (and its subclasses). - * - * The attributes edited are {@code name}, {@code title}, {@code lead}, - * {@code startdate}, {@code starttime}, {@code end date}, - * {@code endtime},{@code event date} (literal description of date), - * {@code location}, {@code main contributor} {@code event type}, - * {@code map link}, and {@code cost}. - * - * This authoring step replaces the {@code com.arsdigita.ui.authoring.PageEdit} - * step for this type. - */ -public class EventPropertiesStep extends SimpleEditStep { - - /** - * The name of the editing sheet added to this step - */ - public static String EDIT_SHEET_NAME = "edit"; - - /** - * - * @param itemSelectionModel - * @param authoringKitWizard - * @param selectedLanguageParam - */ - public EventPropertiesStep(final ItemSelectionModel itemSelectionModel, - final AuthoringKitWizard authoringKitWizard, - final StringParameter selectedLanguageParam) { - - super(itemSelectionModel, authoringKitWizard, selectedLanguageParam); - - setDefaultEditKey(EDIT_SHEET_NAME); - BasicPageForm editSheet; - - editSheet = new EventPropertyForm(itemSelectionModel, - this, - selectedLanguageParam); - add(EDIT_SHEET_NAME, - new GlobalizedMessage("cms.ui.edit", CmsConstants.CMS_BUNDLE), - new WorkflowLockedComponentAccess(editSheet, itemSelectionModel), - editSheet.getSaveCancelSection().getCancelButton()); - - setDisplayComponent(getEventPropertySheet(itemSelectionModel, - selectedLanguageParam)); - } - - /** - * Returns a component that displays the properties of the Event specified - * by the ItemSelectionModel passed in. - * - * @param itemSelectionModel The ItemSelectionModel to use - * @param selectedLanguageParam - * - * @return A component to display the state of the basic properties of the - * release - * - */ - public static Component getEventPropertySheet( - final ItemSelectionModel itemSelectionModel, - final StringParameter selectedLanguageParam) { - - final DomainObjectPropertySheet sheet = new DomainObjectPropertySheet( - itemSelectionModel, - false, - selectedLanguageParam); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ConfigurationManager confManager = cdiUtil - .findBean(ConfigurationManager.class); - final EventConfig eventConfig = confManager - .findConfiguration(EventConfig.class); - - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.title", - CmsConstants.CMS_BUNDLE), - "title"); - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.name", - CmsConstants.CMS_BUNDLE), - "name"); - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.event.lead", - CmsConstants.CMS_BUNDLE), - "description"); - - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.event.start_time", - CmsConstants.CMS_BUNDLE), - "startDate", - new DateTimeAttributeFormatter()); - - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.event.end_time", - CmsConstants.CMS_BUNDLE), - "endDate", - new DateTimeAttributeFormatter()); - if (!eventConfig.isHideDateDescription()) { - sheet.add( - new GlobalizedMessage( - "cms.contenttypes.ui.event.date_description", - CmsConstants.CMS_BUNDLE), - "eventDate"); - } - - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.event.location", - CmsConstants.CMS_BUNDLE), - "location"); - - if (!eventConfig.isHideMainContributor()) { - sheet.add( - new GlobalizedMessage( - "cms.contenttypes.ui.event.main_contributor", - CmsConstants.CMS_BUNDLE), - "mainContributor"); - } - if (!eventConfig.isHideEventType()) { - sheet.add( - new GlobalizedMessage("cms.contenttypes.ui.event.event_type", - CmsConstants.CMS_BUNDLE), - "eventType"); - } - if (!eventConfig.isHideLinkToMap()) { - sheet.add( - new GlobalizedMessage("cms.contenttypes.ui.event.link_to_map", - CmsConstants.CMS_BUNDLE), - "mapLink"); - } - if (!eventConfig.isHideCost()) { - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.event.cost", - CmsConstants.CMS_BUNDLE), - "cost"); - } - return sheet; - } - - /** - * Private class which implements an AttributeFormatter interface for date - * values. Its format(...) class returns a string representation for either - * a false or a true value. - */ - private static class DateTimeAttributeFormatter - implements DomainObjectPropertySheet.AttributeFormatter { - - /** - * Constructor, does nothing. - */ - public DateTimeAttributeFormatter() { - } - - /** - * Formatter for the value of an attribute. - * - * It currently relays on the prerequisite that the passed in property - * attribute is in fact a date property. No type checking yet! - * - * Note: the format method has to be executed at each page request. Take - * care to properly adjust globalization and localization here! - * - * @param obj Object containing the attribute to format. - * @param attribute Name of the attribute to retrieve and format - * @param state PageState of the request - * - * @return A String representation of the retrieved boolean attribute of - * the domain object. - */ - @Override - public String format(final Object obj, - final String attribute, - final PageState state) { - - if (obj != null && obj instanceof Event) { - - final BeanInfo beanInfo; - try { - beanInfo = Introspector.getBeanInfo(Event.class); - } catch (IntrospectionException ex) { - throw new UnexpectedErrorException(ex); - } - final Optional propertyDescriptor = Arrays - .stream(beanInfo.getPropertyDescriptors()) - .filter(current -> attribute.equals(current.getName())) - .findAny(); - - if (propertyDescriptor.isPresent()) { - - final GlobalizationHelper globalizationHelper = CdiUtil - .createCdiUtil().findBean(GlobalizationHelper.class); - - final Method readMethod = propertyDescriptor - .get() - .getReadMethod(); - - final Object result; - try { - result = readMethod.invoke(obj); - } catch (IllegalAccessException - | IllegalArgumentException - | InvocationTargetException ex) { - throw new UnexpectedErrorException(ex); - } - - if (result == null) { - return (String) new GlobalizedMessage( - "toolbox.ui.na", ToolboxConstants.TOOLBOX_BUNDLE) - .localize(); - } else if (result instanceof Date) { - return DateFormat - .getDateTimeInstance( - DateFormat.LONG, - DateFormat.SHORT, - globalizationHelper.getNegotiatedLocale()) - .format((Date) result); - } else { - throw new IllegalArgumentException(String - .format( - "Value is not an instance of \"%s\" but is an " - + "instance of \"%s\".", - Date.class.getName(), - result.getClass().getName())); - } - - } else { - return (String) new GlobalizedMessage( - "toolbox.ui.na", - ToolboxConstants.TOOLBOX_BUNDLE) - .localize(); - } - - } else { - - return (String) new GlobalizedMessage( - "toolbox.ui.na", - ToolboxConstants.TOOLBOX_BUNDLE) - .localize(); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/event/EventPropertyForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/event/EventPropertyForm.java deleted file mode 100755 index a24b99f01..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/event/EventPropertyForm.java +++ /dev/null @@ -1,596 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.event; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.form.Time; -import com.arsdigita.bebop.parameters.DateParameter; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringInRangeValidationListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.parameters.TimeParameter; -import com.arsdigita.bebop.parameters.TrimmedStringParameter; -import com.arsdigita.cms.ItemSelectionModel; - -import org.librecms.contenttypes.Event; - -import com.arsdigita.cms.ui.CMSDHTMLEditor; -import com.arsdigita.cms.ui.authoring.BasicPageForm; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contenttypes.EventConfig; - -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.Locale; -import java.util.Objects; - -/** - * Form to edit the basic properties of an {@link Event} object. - * - * Used by {@link EventPropertiesStep} authoring kit step. - * - * This form can be extended to create forms for Event subclasses. - * - */ -public class EventPropertyForm - extends BasicPageForm - implements FormProcessListener, - FormInitListener, - FormSubmissionListener { - - private final static Logger LOGGER = LogManager - .getLogger(EventPropertyForm.class); - - /** - * Name of this form - */ - public static final String ID = "event_edit"; - - private EventPropertiesStep eventPropertiesStep; - /** - * event date parameter name - */ - public static final String START_DATE = "startDate"; - public static final String END_DATE = "endDate"; - public static final String START_TIME = "startTime"; - public static final String END_TIME = "endTime"; - public static final String EVENT_DATE = "eventDate"; - /** - * location parameter name - */ - public static final String LOCATION = "location"; - /** - * lead parameter name - */ - public static final String LEAD = "lead"; - /** - * Main contributor parameter name - */ - public static final String MAIN_CONTRIBUTOR = "main_contributor"; - /** - * Event type parameter name - */ - public static final String EVENT_TYPE = "event_type"; - /** - * Map link parameter name - */ - public static final String MAP_LINK = "map_link"; - /** - * cost parameter name - */ - public static final String COST = "cost"; - - private final StringParameter selectedLanguageParam; - - /* DateWidgets have to be accessible later on */ - private com.arsdigita.bebop.form.Date startDateField; - private com.arsdigita.bebop.form.Date endDateField; - - /** - * Creates a new form to edit the Event object specified by the item - * selection model passed in. - * - * @param itemSelectionModel The ItemSelectionModel to use to obtain the - * Event to work on - * @param selectedLanguageParam - * - */ - public EventPropertyForm(final ItemSelectionModel itemSelectionModel, - final StringParameter selectedLanguageParam) { - this(itemSelectionModel, null, selectedLanguageParam); - } - - /** - * Creates a new form to edit the Event object specified by the item - * selection model passed in. - * - * @param itemSelectionModel The ItemSelectionModel to use to obtain the - * Event to work on - * @param eventPropertiesStep The EventPropertiesStep which controls this - * form. - * @param selectedLanguageParam - * - */ - public EventPropertyForm(final ItemSelectionModel itemSelectionModel, - final EventPropertiesStep eventPropertiesStep, - final StringParameter selectedLanguageParam) { - - super(ID, itemSelectionModel, selectedLanguageParam); - - Objects.requireNonNull(selectedLanguageParam); - - this.eventPropertiesStep = eventPropertiesStep; - this.selectedLanguageParam = selectedLanguageParam; - addSubmissionListener(this); - } - - /** - * Adds widgets to the form. - * - */ - @Override - protected void addWidgets() { - - super.addWidgets(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ConfigurationManager confManager = cdiUtil - .findBean(ConfigurationManager.class); - final EventConfig eventConfig = confManager - .findConfiguration(EventConfig.class); - - /* Summary (lead) */ - final ParameterModel leadParam = new StringParameter(LEAD); - if (!eventConfig.isLeadTextOptional()) { - leadParam.addParameterListener(new NotNullValidationListener()); - } - final TextArea lead = new TextArea(leadParam); - lead.setLabel(new GlobalizedMessage("cms.contenttypes.ui.event.lead", - CmsConstants.CMS_BUNDLE)); - lead.setCols(50); - lead.setRows(5); - add(lead); - - /* Start date and time */ - final ParameterModel eventStartDateParam = new DateParameter(START_DATE); - eventStartDateParam - .addParameterListener(new NotNullValidationListener()); - // Use bebop date instead of java.util.date - startDateField = new com.arsdigita.bebop.form.Date(eventStartDateParam); - startDateField.setLabel(new GlobalizedMessage( - "cms.contenttypes.ui.event.start_date", - CmsConstants.CMS_BUNDLE)); - // Set the upper und lower boundary of the year select box - startDateField - .setYearRange( - eventConfig.getStartYear(), - GregorianCalendar.getInstance().get(Calendar.YEAR) - + eventConfig.getEndYearDelta()); - add(startDateField); - - final ParameterModel eventStartTimeParam = new TimeParameter(START_TIME); - if (!eventConfig.isStartTimeOptional()) { - eventStartTimeParam.addParameterListener( - new NotNullValidationListener()); - } - final Time startTime = new Time(eventStartTimeParam); - startTime - .setLabel( - new GlobalizedMessage("cms.contenttypes.ui.event.start_time", - CmsConstants.CMS_BUNDLE)); - add(startTime); - - /* End date and time */ - final ParameterModel eventEndDateParam = new DateParameter(END_DATE); - // Use bebop date instead of java.util.date - endDateField = new com.arsdigita.bebop.form.Date(eventEndDateParam); - endDateField - .setLabel( - new GlobalizedMessage("cms.contenttypes.ui.event.end_date", - CmsConstants.CMS_BUNDLE)); - endDateField - .setHint( - new GlobalizedMessage("cms.contenttypes.ui.event.end_date_hint", - CmsConstants.CMS_BUNDLE)); - endDateField - .setYearRange(eventConfig.getStartYear(), - GregorianCalendar.getInstance().get(Calendar.YEAR) - + eventConfig.getEndYearDelta()); - add(endDateField); - - final ParameterModel eventEndTimeParam = new TimeParameter(END_TIME); - final Time endTime = new Time(eventEndTimeParam); - endTime - .setLabel( - new GlobalizedMessage("cms.contenttypes.ui.event.end_time", - CmsConstants.CMS_BUNDLE)); - endTime - .setHint( - new GlobalizedMessage("cms.contenttypes.ui.event.end_time_hint", - CmsConstants.CMS_BUNDLE)); - add(endTime); - - - /* optional additional / literal date description */ - if (!eventConfig.isHideDateDescription()) { - final ParameterModel eventDateParam - = new StringParameter(EVENT_DATE); - if (eventConfig.isUseHtmlDateDescription()) { - CMSDHTMLEditor eventDate = new CMSDHTMLEditor(eventDateParam); - eventDate.setLabel( - new GlobalizedMessage( - "cms.contenttypes.ui.event.date_description", - CmsConstants.CMS_BUNDLE)); - eventDate.setHint(new GlobalizedMessage( - "cms.contenttypes.ui.event.date_description_hint", - CmsConstants.CMS_BUNDLE)); - eventDate.setCols(40); - eventDate.setRows(8); - add(eventDate); - } else { - eventDateParam.addParameterListener( - new StringInRangeValidationListener(0, 100)); - TextArea eventDate = new TextArea(eventDateParam); - eventDate - .setLabel(new GlobalizedMessage( - "cms.contenttypes.ui.event.date_description", - CmsConstants.CMS_BUNDLE)); - eventDate.setHint(new GlobalizedMessage( - "cms.contenttypes.ui.event.date_description_hint", - CmsConstants.CMS_BUNDLE)); - eventDate.setCols(50); - eventDate.setRows(2); - add(eventDate); - } - } - - - /* extensive description of location */ - final ParameterModel locationParam = new StringParameter(LOCATION); - final CMSDHTMLEditor location = new CMSDHTMLEditor(locationParam); - location - .setLabel( - new GlobalizedMessage("cms.contenttypes.ui.event.location", - CmsConstants.CMS_BUNDLE)); - location - .setHint(new GlobalizedMessage( - "cms.contenttypes.ui.event.location_hint", - CmsConstants.CMS_BUNDLE)); - location.setCols(40); - location.setRows(8); - add(location); - - - /* optional: main contributor */ - if (!eventConfig.isHideMainContributor()) { - final ParameterModel mainContributorParam - = new StringParameter(MAIN_CONTRIBUTOR); - final CMSDHTMLEditor mainContributor - = new CMSDHTMLEditor(mainContributorParam); - mainContributor.setLabel( - new GlobalizedMessage( - "cms.contenttypes.ui.event.main_contributor", - CmsConstants.CMS_BUNDLE)); - mainContributor.setHint( - new GlobalizedMessage( - "cms.contenttypes.ui.event.main_contributor_hint", - CmsConstants.CMS_BUNDLE)); - mainContributor.setCols(40); - mainContributor.setRows(10); - add(mainContributor); - } - - - /* optional: event type */ - if (!eventConfig.isHideEventType()) { - final ParameterModel eventTypeParam - = new StringParameter(EVENT_TYPE); - final TextField eventType = new TextField(eventTypeParam); - eventType.setLabel( - new GlobalizedMessage( - "cms.contenttypes.ui.event.event_type", - CmsConstants.CMS_BUNDLE)); - eventType.setHint( - new GlobalizedMessage( - "cms.contenttypes.ui.event.event_type_hint", - CmsConstants.CMS_BUNDLE)); - eventType.setSize(30); - eventType.setMaxLength(30); - add(eventType); - } - - - /* optional: link to map */ - if (!eventConfig.isHideLinkToMap()) { - final ParameterModel mapLinkParam = new StringParameter(MAP_LINK); - final TextArea mapLink = new TextArea(mapLinkParam); - mapLink.setLabel(new GlobalizedMessage( - "cms.contenttypes.ui.event.link_to_map", - CmsConstants.CMS_BUNDLE)); - mapLink.setHint(new GlobalizedMessage( - "cms.contenttypes.ui.event.link_to_map_hint", - CmsConstants.CMS_BUNDLE)); - mapLink.setCols(40); - mapLink.setRows(2); - add(mapLink); - } - - - /* optional: costs */ - if (!eventConfig.isHideCost()) { - final ParameterModel costParam = new TrimmedStringParameter(COST); - final TextField cost = new TextField(costParam); - cost.setLabel( - new GlobalizedMessage( - "cms.contenttypes.ui.event.cost", - CmsConstants.CMS_BUNDLE)); - cost.setHint(new GlobalizedMessage( - "cms.contenttypes.ui.event.cost_hint", - CmsConstants.CMS_BUNDLE)); - cost.setSize(30); - cost.setMaxLength(30); - add(cost); - } - - } - - /** - * - * @param event - * - * @throws FormProcessException - */ - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - - super.validate(event); - - final FormData data = event.getFormData(); - java.util.Date startDate = data.getDate(START_DATE); - java.util.Date endDate = data.getDate(END_DATE); - - if (endDate != null) { - if (startDate == null || startDate.compareTo(endDate) > 0) { - throw new FormProcessException( - "End date must be after start date", - new GlobalizedMessage( - "cms.contenttypes.ui.event.end_date_after_start_date", - CmsConstants.CMS_BUNDLE) - ); - } - } - } - - /** - * Form initialisation hook. Fills widgets with data. - * - * @param event - */ - @Override - public void init(final FormSectionEvent event) { - // Do some initialization hook stuff - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - final Event item = (Event) super.initBasicWidgets(event); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ConfigurationManager confManager = cdiUtil - .findBean(ConfigurationManager.class); - final EventConfig eventConfig = confManager - .findConfiguration(EventConfig.class); - - // Start date should always be set - final java.util.Date startDate; - if (item.getStartDate() == null) { - // new Date is initialised to current time - startDate = new java.util.Date(); - } else { - startDate = item.getStartDate(); - } - startDateField.addYear(startDate); - - // End date can be null - final java.util.Date endDate; - if (item.getEndDate() == null) { - // new Date is initialised to current time - endDate = new java.util.Date(); - } else { - endDate = item.getEndDate(); - } - endDateField.addYear(endDate); - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - data.put(LEAD, item.getDescription().getValue(selectedLocale)); - data.put(START_DATE, startDate); - data.put(START_TIME, startDate); - data.put(END_DATE, endDate); - data.put(END_TIME, endDate); - if (!eventConfig.isHideDateDescription()) { - data.put(EVENT_DATE, - item.getEventDate().getValue(selectedLocale)); - } - data.put(LOCATION, item.getLocation().getValue(selectedLocale)); - if (!eventConfig.isHideMainContributor()) { - data.put(MAIN_CONTRIBUTOR, - item.getMainContributor().getValue(selectedLocale)); - } - if (!eventConfig.isHideEventType()) { - data.put(EVENT_TYPE, - item.getEventType().getValue(selectedLocale)); - } - if (!eventConfig.isHideLinkToMap()) { - data.put(MAP_LINK, item.getMapLink()); - } - if (!eventConfig.isHideCost()) { - data.put(COST, - item.getCost().getValue(selectedLocale)); - } - } - - /** - * Cancels streamlined editing. - * - * @param event - */ - @Override - public void submitted(final FormSectionEvent event) { - if (eventPropertiesStep != null - && getSaveCancelSection() - .getCancelButton() - .isSelected(event.getPageState())) { - eventPropertiesStep.cancelStreamlinedCreation(event.getPageState()); - } - } - - /** - * Form processing hook. Saves Event object. - * - * @param event - */ - @Override - public void process(final FormSectionEvent event) { - - final FormData data = event.getFormData(); - - final Event item = (Event) super.processBasicWidgets(event); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ConfigurationManager confManager = cdiUtil - .findBean(ConfigurationManager.class); - final EventConfig eventConfig = confManager - .findConfiguration(EventConfig.class); - final PageState state = event.getPageState(); - - // save only if save button was pressed - if (item != null - && getSaveCancelSection().getSaveButton().isSelected(state)) { - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - final java.util.Date startDate = (java.util.Date) data - .get(START_DATE); - final java.util.Date startTime = (java.util.Date) data - .get(START_TIME); - final java.util.Date endDate = (java.util.Date) data.get(END_DATE); - final java.util.Date endTime = (java.util.Date) data.get(END_TIME); - - final Calendar startDateCal = Calendar.getInstance(); - final Calendar startTimeCal = Calendar.getInstance(); - final Calendar endDateCal = Calendar.getInstance(); - final Calendar endTimeCal = Calendar.getInstance(); - startDateCal.setTime(startDate); - startTimeCal.setTime(startTime); - endDateCal.setTime(endDate); - endTimeCal.setTime(endTime); - - final int startYear = startDateCal.get(Calendar.YEAR); - final int startMonth = startDateCal.get(Calendar.MONTH); - final int startDay = startDateCal.get(Calendar.DAY_OF_MONTH); - final int startHour = startTimeCal.get(Calendar.HOUR_OF_DAY); - final int startMinute = startTimeCal.get(Calendar.MINUTE); - - final int endYear = endDateCal.get(Calendar.YEAR); - final int endMonth = endDateCal.get(Calendar.MONTH); - final int endDay = endDateCal.get(Calendar.DAY_OF_MONTH); - final int endHour = endTimeCal.get(Calendar.HOUR_OF_DAY); - final int endMinute = endTimeCal.get(Calendar.MINUTE); - - final Calendar startDateTimeCal = Calendar.getInstance(); - final Calendar endDateTimeCal = Calendar.getInstance(); - - startDateTimeCal.set(Calendar.YEAR, startYear); - startDateTimeCal.set(Calendar.MONTH, startMonth); - startDateTimeCal.set(Calendar.DAY_OF_MONTH, startDay); - startDateTimeCal.set(Calendar.HOUR_OF_DAY, startHour); - startDateTimeCal.set(Calendar.MINUTE, startMinute); - - endDateTimeCal.set(Calendar.YEAR, endYear); - endDateTimeCal.set(Calendar.MONTH, endMonth); - endDateTimeCal.set(Calendar.DAY_OF_MONTH, endDay); - endDateTimeCal.set(Calendar.HOUR_OF_DAY, endHour); - endDateTimeCal.set(Calendar.MINUTE, endMinute); - - final java.util.Date startDateTime = startDateTimeCal.getTime(); - final java.util.Date endDateTime = endDateTimeCal.getTime(); - - item.setStartDate(startDateTime); - item.setEndDate(endDateTime); - //date_description - if (!eventConfig.isHideDateDescription()) { - item.getEventDate().putValue(selectedLocale, - (String) data.get(EVENT_DATE)); - } - - if (!eventConfig.isHideMainContributor()) { - item - .getMainContributor() - .putValue(selectedLocale, - (String) data.get(MAIN_CONTRIBUTOR)); - } - if (!eventConfig.isHideEventType()) { - item - .getEventType() - .putValue(selectedLocale, - (String) data.get(EVENT_TYPE)); - } - if (!eventConfig.isHideLinkToMap()) { - item.setMapLink((String) data.get(MAP_LINK)); - } - item.getLocation().putValue(selectedLocale, - (String) data.get(LOCATION)); - item.getDescription().putValue(selectedLocale, - (String) data.get(LEAD)); - if (!eventConfig.isHideCost()) { - item.getCost().putValue(selectedLocale, - (String) data.get(COST)); - } - - final ContentItemRepository itemRepo = cdiUtil - .findBean(ContentItemRepository.class); - - itemRepo.save(item); - } - if (eventPropertiesStep != null) { - eventPropertiesStep.maybeForwardToNextStep(event.getPageState()); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/event/EventTextBody.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/event/EventTextBody.java deleted file mode 100644 index 202de8a2e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/event/EventTextBody.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.ui.authoring.event; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.cms.ui.authoring.TextBody; -import com.arsdigita.cms.ui.workflow.WorkflowLockedComponentAccess; -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contenttypes.Event; - -import java.util.Locale; - -import static com.arsdigita.cms.ui.authoring.TextBody.*; - -/** - * - * @author Jens Pelzetter - */ -public class EventTextBody extends TextBody { - - private final ItemSelectionModel itemSelectionModel; - private final StringParameter selectedLanguageParam; - - public EventTextBody(final ItemSelectionModel itemSelectionModel, - final AuthoringKitWizard authoringKitWizard, - final StringParameter selectedLanguageParam) { - - super(itemSelectionModel, selectedLanguageParam); - - this.itemSelectionModel = itemSelectionModel; - this.selectedLanguageParam = selectedLanguageParam; - - // Rest the component when it is hidden - authoringKitWizard - .getList() - .addActionListener(event -> reset(event.getPageState())); - - // Set the right component access on the forms - final Component uploadComponent = getComponent(FILE_UPLOAD); - if (uploadComponent != null) { - setComponentAccess(FILE_UPLOAD, - new WorkflowLockedComponentAccess( - uploadComponent, itemSelectionModel)); - } - final Component textEntryComponent = getComponent(TEXT_ENTRY); - setComponentAccess(TEXT_ENTRY, - new WorkflowLockedComponentAccess( - textEntryComponent, itemSelectionModel)); - } - - /** - * Adds the options for the mime type select widget of - * GenericArticleForm and sets the default mime type. - * - * @param mimeSelect - */ - @Override - protected void setMimeTypeOptions(final SingleSelect mimeSelect) { - mimeSelect.addOption(new Option("text/html", "HTML Text")); - mimeSelect.setOptionSelected("text/html"); - } - - protected Event getSelectedEvent(final PageState state) { - - return (Event) itemSelectionModel.getSelectedItem(state); - } - - @Override - protected String getTextPropertyName() { - - return "text"; - } - - @Override - public String getText(final PageState state) { - - final Event event = getSelectedEvent(state); - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - return event.getText().getValue(selectedLocale); - - } - - @Override - protected void updateText(final PageState state, final String text) { - - final Event event = getSelectedEvent(state); - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - event.getText().putValue(selectedLocale, text); - final ContentItemRepository itemRepo = CdiUtil - .createCdiUtil() - .findBean(ContentItemRepository.class); - itemRepo.save(event); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleCreateForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleCreateForm.java deleted file mode 100644 index 19c964fda..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleCreateForm.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.multipartarticle; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.ApplyWorkflowFormSection; -import com.arsdigita.cms.ui.authoring.CreationComponent; -import com.arsdigita.cms.ui.authoring.CreationSelector; -import com.arsdigita.cms.ui.authoring.LanguageWidget; -import com.arsdigita.globalization.GlobalizedMessage; - -import java.util.Date; - -import org.librecms.CMSConfig; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.Folder; -import org.librecms.contenttypes.MultiPartArticle; - -import java.util.Locale; - -/** - * A form which will create a MultiPartArticle or one of its subclasses. - * - * @author Dave Turner - * @author Jens Pelzetter - */ -public class MultiPartArticleCreateForm - extends MultiPartArticleForm - implements FormInitListener, - FormProcessListener, - FormSubmissionListener, - FormValidationListener, - CreationComponent { - - private final CreationSelector creationSelector; - private ApplyWorkflowFormSection workflowSection; - - public MultiPartArticleCreateForm( - final ItemSelectionModel itemSelectionModel, - final CreationSelector creationSelector, - final StringParameter selectedLanguageParam) { - - super("MultiPartArticleCreate", - itemSelectionModel, - selectedLanguageParam); - - this.creationSelector = creationSelector; - workflowSection.setCreationSelector(creationSelector); - workflowSection.setContentType(itemSelectionModel.getContentType()); - addSubmissionListener(this); - getSaveCancelSection() - .getSaveButton() - .setButtonLabel(new GlobalizedMessage("cms.ui.create", - CmsConstants.CMS_BUNDLE)); - } - - @Override - protected void addWidgets() { - workflowSection = new ApplyWorkflowFormSection(); - add(workflowSection, ColumnPanel.INSERT); - add(new Label(new GlobalizedMessage("cms.ui.language.field", - CmsConstants.CMS_BUNDLE))); - add(new LanguageWidget(LANGUAGE)); - super.addWidgets(); - } - - /** - * Return the ApplyWorkflowFormSection associated with this - * CreationComponent. - * - * @return the ApplyWorkflowFormSection associated with this - * CreationComponent. - */ - @Override - public ApplyWorkflowFormSection getWorkflowSection() { - return workflowSection; - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - // this is currently a no-op - } - - @Override - public void submitted(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (getSaveCancelSection().getCancelButton().isSelected(state)) { - creationSelector.redirectBack(state); - throw new FormProcessException( - "Submission cancelled", - new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.submission_cancelled", - CmsConstants.CMS_BUNDLE) - ); - } - } - - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - - final Folder folder = creationSelector.getFolder(event.getPageState()); - if (!validateNameUniqueness(folder, event)) { - throw new FormProcessException( - "An item with this name already exists", - new GlobalizedMessage( - "cms.contenttypes.ui.mparticle." - + "an_item_with_this_name_already_exists", - CmsConstants.CMS_BUNDLE) - ); - } - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - final ContentSection section = creationSelector.getContentSection(state); - final Folder folder = creationSelector.getFolder(state); - - final Locale locale = new Locale((String) data.get(LANGUAGE)); - - final MultiPartArticle article = createArticle(state, - (String) data.get(NAME), - section, - folder, - locale); - article.getTitle().putValue(locale, (String) data.get(TITLE)); - if (!CMSConfig.getConfig().isHideLaunchDate()) { - article.setLaunchDate((Date) data.get(LAUNCH_DATE)); - } - article - .getSummary() - .putValue(locale, (String) data.get(SUMMARY)); - - workflowSection.applyWorkflow(state, article); - - final CdiUtil cdiUtil =CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil - .findBean(ContentItemRepository.class); - itemRepo.save(article); - - creationSelector.editItem(state, article); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleEdit.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleEdit.java deleted file mode 100755 index eb855dacb..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleEdit.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.multipartarticle; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.parameters.StringParameter; - - -import com.arsdigita.cms.ItemSelectionModel; - - -import com.arsdigita.toolbox.ui.DomainObjectPropertySheet; -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.SimpleEditStep; -import com.arsdigita.cms.ui.workflow.WorkflowLockedComponentAccess; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CMSConfig; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.librecms.CmsConstants; - - -/** - * A MultiPartArticle editing component. - * - * @author Dave Turner - * @author Jens Pelzetter - */ -public class MultiPartArticleEdit extends SimpleEditStep { - - - /** - * Constructor. - * - * @param itemSelectionModel the ItemSelectionModel which holds the - * current MutliPartArticle - * @param authoringKitWizard the parent wizard which contains the form - * @param selectedLanguageParam - */ - public MultiPartArticleEdit(final ItemSelectionModel itemSelectionModel, - final AuthoringKitWizard authoringKitWizard, - final StringParameter selectedLanguageParam) { - - super(itemSelectionModel, authoringKitWizard, selectedLanguageParam); - - setDefaultEditKey("edit"); - final MultiPartArticleForm form = new MultiPartArticleEditForm( - itemSelectionModel, - this, - selectedLanguageParam); - add("edit", - new GlobalizedMessage("cms.ui.edit", - CmsConstants.CMS_BUNDLE), - new WorkflowLockedComponentAccess(form, itemSelectionModel), - form.getSaveCancelSection().getCancelButton() - ); - - setDisplayComponent(getMultiPartArticlePropertiesSheet( - itemSelectionModel, - selectedLanguageParam)); - } - - public Component getMultiPartArticlePropertiesSheet( - final ItemSelectionModel itemSelectionModel, - final StringParameter selectedLanguageParam) { - - final DomainObjectPropertySheet sheet = new DomainObjectPropertySheet( - itemSelectionModel, - false, - selectedLanguageParam); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ConfigurationManager confManager = cdiUtil - .findBean(ConfigurationManager.class); - final CMSConfig cmsConfig = confManager - .findConfiguration(CMSConfig.class); - - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.title", - CmsConstants.CMS_BUNDLE), - "title"); - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.name", - CmsConstants.CMS_BUNDLE), - "name"); - if (!cmsConfig.isHideLaunchDate()) { - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.launch_date", - CmsConstants.CMS_BUNDLE), - "launchDate", - new LaunchDateAttributeFormatter()); - } - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.summary", - CmsConstants.CMS_BUNDLE), - "summary"); - - return sheet; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleEditForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleEditForm.java deleted file mode 100755 index a7c7fa2db..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleEditForm.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (C) 2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.multipartarticle; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.parameters.StringParameter; - -import org.librecms.contentsection.Folder; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; - -import org.librecms.contenttypes.MultiPartArticle; - -import com.arsdigita.cms.ui.authoring.SimpleEditStep; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.FolderManager; -import org.librecms.contentsection.FolderRepository; - -import java.util.Locale; -import java.util.Optional; - -/** - * Worker class to create the multipart article's edit form. - * - */ -public class MultiPartArticleEditForm extends MultiPartArticleForm - implements FormSubmissionListener { - - private final ItemSelectionModel itemSelectionModel; - private final SimpleEditStep editStep; - private final StringParameter selectedLanguageParam; - - /** - * Constructor. - * - * @param itemSelectionModel - * @param editStep - * @param selectedLanguageParam - */ - public MultiPartArticleEditForm(final ItemSelectionModel itemSelectionModel, - final SimpleEditStep editStep, - final StringParameter selectedLanguageParam) { - - super("MultiPartArticleEditForm", - itemSelectionModel, - selectedLanguageParam); - - addSubmissionListener(this); - this.itemSelectionModel = itemSelectionModel; - this.editStep = editStep; - this.selectedLanguageParam = selectedLanguageParam; - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - super.initBasicWidgets(event); - } - - /** - * Cancels streamlined editing. - * - * @param event - */ - @Override - public void submitted(final FormSectionEvent event) { - - if (getSaveCancelSection() - .getCancelButton() - .isSelected(event.getPageState())) { - editStep.cancelStreamlinedCreation(event.getPageState()); - } - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final MultiPartArticle article = super.processBasicWidgets(event); - - final PageState state = event.getPageState(); - -// final MultiPartArticle article = (MultiPartArticle) itemSelectionModel -// .getSelectedObject(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil - .findBean(ContentItemRepository.class); - itemRepo.save(article); - - editStep.maybeForwardToNextStep(event.getPageState()); - } - - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - - final MultiPartArticle article = (MultiPartArticle) itemSelectionModel - .getSelectedObject(state); - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - final String newName = (String) data.get(MultiPartArticleForm.NAME); - final MultiPartArticleFormController controller = CdiUtil - .createCdiUtil() - .findBean(MultiPartArticleFormController.class); - final String oldName = controller.getName(article, selectedLocale); - - final boolean valid; - if (newName.equalsIgnoreCase(oldName)) { - valid = true; - } else { - final Optional folder = controller.getArticleFolder(article); - if (folder.isPresent()) { - valid = validateNameUniqueness(folder.get(), event); - } else { - valid = true; - } - } - - if (!valid) { - throw new FormProcessException( - "An item with name already exists", - new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.an_item_with_name_already_exists", - CmsConstants.CMS_BUNDLE)); - } - } - - private Folder getParentFolder(final MultiPartArticle article) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderRepository folderRepo = cdiUtil - .findBean(FolderRepository.class); - final FolderManager folderManager = cdiUtil - .findBean(FolderManager.class); - - final ContentItemManager itemManager = cdiUtil - .findBean(ContentItemManager.class); - - final Optional folder = itemManager.getItemFolder(article); - - if (folder.isPresent()) { - return folder.get(); - } else { - return null; - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleForm.java deleted file mode 100644 index fa373a7c4..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleForm.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.multipartarticle; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Embedded; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.FormSection; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.DateParameter; -import com.arsdigita.bebop.parameters.NotEmptyValidationListener; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.parameters.TrimmedStringParameter; -import com.arsdigita.bebop.parameters.URLTokenValidationListener; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.web.Web; -import com.arsdigita.xml.Element; - -import java.util.Date; -import java.util.Locale; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.librecms.CMSConfig; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.Folder; -import org.librecms.contenttypes.MultiPartArticle; - -/** - * A form for editing MultiPartArticle and subclasses. - * - * @author Dave Turner - * @author Jens Pelzetter - */ -public abstract class MultiPartArticleForm - extends FormSection - implements FormInitListener, - FormProcessListener, - FormValidationListener { - - private final ItemSelectionModel itemSelectionModel; - private final StringParameter selectedLanguageParam; - private SaveCancelSection saveCancelSection; - /** - * Constant property, placeholder for a JavaScript element. - */ - private final Embedded m_script = new Embedded( - String.format("" - + "", - Web.getWebappContextPath()), - false); - - public static final String NAME = "name"; - public static final String TITLE = "title"; - public static final String SUMMARY = "summary"; - public static final String LAUNCH_DATE = "launch_date"; - public static final String LANGUAGE = "language"; - - private static final Logger LOGGER = LogManager.getLogger( - MultiPartArticleForm.class); - - public MultiPartArticleForm(final String formName, - final ItemSelectionModel itemSelectionModel, - final StringParameter selectedLanguageParam) { - - super(new ColumnPanel(2)); - - this.itemSelectionModel = itemSelectionModel; - this.selectedLanguageParam = selectedLanguageParam; - - ColumnPanel panel = (ColumnPanel) getPanel(); - panel.setBorder(false); - panel.setPadColor("#FFFFFF"); - panel.setColumnWidth(1, "20%"); - panel.setColumnWidth(2, "80%"); - panel.setWidth("100%"); - - addWidgets(); - - addSaveCancelSection(); - - addInitListener(this); - addProcessListener(this); - addValidationListener(this); - } - - public void addSaveCancelSection() { - saveCancelSection = new SaveCancelSection(); - add(saveCancelSection, ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - } - - public SaveCancelSection getSaveCancelSection() { - return saveCancelSection; - } - - protected void addWidgets() { - - // add(new Label(GlobalizationUtil - // .globalize("cms.contenttypes.ui.title"))); - final TextField titleWidget = new TextField(new TrimmedStringParameter( - TITLE)); - titleWidget.setLabel(new GlobalizedMessage("cms.contenttypes.ui.title", - CmsConstants.CMS_BUNDLE)); - titleWidget.addValidationListener(new NotNullValidationListener()); - titleWidget.setOnFocus(String.format( - "if (this.form.%s.value == '') { " - + " defaulting = true; this.form.%s.value = urlize(this.value); }", - NAME, NAME)); - titleWidget.setOnKeyUp(String.format( - "if (defaulting) { this.form.%s.value = urlize(this.value) }", - NAME)); - add(titleWidget); - - //add(new Label(GlobalizationUtil - // .globalize("cms.contenttypes.ui.name"))); - final TextField nameWidget = new TextField(new TrimmedStringParameter( - NAME)); - nameWidget.setLabel(new GlobalizedMessage("cms.contenttypes.ui.name", - CmsConstants.CMS_BUNDLE)); - nameWidget.addValidationListener(new NotNullValidationListener()); - nameWidget.addValidationListener(new URLTokenValidationListener()); - nameWidget.setOnFocus("defaulting = false"); - nameWidget.setOnBlur(String.format( - "if (this.value == '') { " - + "defaulting = true; this.value = urlize(this.form.%s.value) " - + "}", - TITLE)); - add(nameWidget); - - if (!CMSConfig.getConfig().isHideLaunchDate()) { - //add(new Label(GlobalizationUtil - // .globalize("cms.ui.authoring.page_launch_date"))); - final ParameterModel launchDateParam - = new DateParameter(LAUNCH_DATE); - com.arsdigita.bebop.form.Date launchDate - = new com.arsdigita.bebop.form.Date( - launchDateParam); - if (CMSConfig.getConfig().isRequireLaunchDate()) { - launchDate.addValidationListener(new NotNullValidationListener( - new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.no_launch_date", - CmsConstants.CMS_BUNDLE))); - // if launch date is required, help user by suggesting today's date - launchDateParam.setDefaultValue(new Date()); - } - launchDate.setLabel(new GlobalizedMessage( - "cms.ui.authoring.page_launch_date", - CmsConstants.CMS_BUNDLE)); - add(launchDate); - } - - //add(new Label(GlobalizationUtil - // .globalize("cms.contenttypes.ui.summary"))); - final TextArea summaryWidget = new TextArea( - new TrimmedStringParameter(SUMMARY)); - if (CMSConfig.getConfig().isMandatoryDescriptions()) { - summaryWidget - .addValidationListener(new NotEmptyValidationListener( - new GlobalizedMessage( - "cms.contenttypes.ui.description_missing", - CmsConstants.CMS_BUNDLE))); - } - summaryWidget.setLabel(new GlobalizedMessage( - "cms.contenttypes.ui.summary", - CmsConstants.CMS_BUNDLE)); - summaryWidget.setRows(5); - summaryWidget.setCols(30); - summaryWidget.setHint(new GlobalizedMessage( - "cms.contenttypes.ui.summary_hint", - CmsConstants.CMS_BUNDLE)); - add(summaryWidget); - } - - @Override - public abstract void init(final FormSectionEvent event) - throws FormProcessException; - - @Override - public abstract void process(final FormSectionEvent event) - throws FormProcessException; - - @Override - public abstract void validate(final FormSectionEvent event) - throws FormProcessException; - - /** - * Utility method to initialise the name/title/summary widgets. - * - * @param event - * - * @return - */ - public MultiPartArticle initBasicWidgets(final FormSectionEvent event) { - - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - final MultiPartArticle article = (MultiPartArticle) itemSelectionModel - .getSelectedObject(state); - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - final MultiPartArticleFormController controller = CdiUtil - .createCdiUtil() - .findBean(MultiPartArticleFormController.class); - - if (article != null) { - data.put(NAME, controller.getName(article, selectedLocale)); - data.put(TITLE, controller.getTitle(article, selectedLocale)); - if (!CMSConfig.getConfig().isHideLaunchDate()) { - data.put(LAUNCH_DATE, article.getLaunchDate()); - } - data.put(SUMMARY, controller.getSummary(article, selectedLocale)); - } - - return article; - } - - /** - * Utility method to process the name/title/summary widgets. - * - * @param event - * - * @return - */ - public MultiPartArticle processBasicWidgets(final FormSectionEvent event) { - - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - final MultiPartArticle article = (MultiPartArticle) itemSelectionModel - .getSelectedObject(state); - - if (article != null) { - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - article.getName().putValue(selectedLocale, - (String) data.get(NAME)); - article.getTitle().putValue(selectedLocale, - (String) data.get(TITLE)); - if (!CMSConfig.getConfig().isHideLaunchDate()) { - article.setLaunchDate((Date) data.get(LAUNCH_DATE)); - } - article.getSummary().putValue(selectedLocale, - (String) data.get(SUMMARY)); - } - - return article; - } - - /** - * Ensure that the name of an item is unique within a folder. - * - * @param folder the folder in which to check - * @param event the FormSectionEvent which was passed to the validation - * listener - * - * @return true if the name is not null and unique, false otherwise - */ - public boolean validateNameUniqueness(final Folder folder, - final FormSectionEvent event) { - - final FormData data = event.getFormData(); - final String name = (String) data.get(NAME); - - if (name != null) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil - .findBean(ContentItemRepository.class); - - final long result = itemRepo.countByNameInFolder(folder, name); - - return result == 0; - } - - // false if name == null - return false; - } - - /** - * Utility method to create a new MultiPartArticle and update the selected - * model. This can be called in the process method of a ProcessListener. - * - * @param state the current page state - * @param name - * @param section - * @param folder - * @param locale Initial locale of the article. - * - * @return the new content item (or a proper subclass) - * - * @throws com.arsdigita.bebop.FormProcessException - */ - public MultiPartArticle createArticle(final PageState state, - final String name, - final ContentSection section, - final Folder folder, - final Locale locale) - throws FormProcessException { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemManager itemManager = cdiUtil - .findBean(ContentItemManager.class); - - final MultiPartArticle article = itemManager - .createContentItem(name, - section, - folder, - MultiPartArticle.class, - locale); - - if (itemSelectionModel.getSelectedKey(state) == null) { - itemSelectionModel.setSelectedKey(state, article.getObjectId()); - } - - return article; - } - - @Override - public void generateXML(final PageState state, final Element parent) { - - m_script.generateXML(state, parent); - super.generateXML(state, parent); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleFormController.java deleted file mode 100644 index 001fecdac..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleFormController.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.multipartarticle; - -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.Folder; -import org.librecms.contenttypes.MultiPartArticle; - -import java.util.Locale; -import java.util.Objects; -import java.util.Optional; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -public class MultiPartArticleFormController { - - @Inject - private ContentItemRepository itemRepo; - - @Inject - private ContentItemManager itemManager; - - @Transactional(Transactional.TxType.REQUIRED) - protected Optional getArticleFolder(final MultiPartArticle article) { - - final Optional mpa = itemRepo.findById( - article.getObjectId() - ); - - if (mpa.isPresent()) { - return itemManager.getItemFolder(mpa.get()); - } else { - return Optional.empty(); - } - } - - @Transactional(Transactional.TxType.REQUIRED) - public String getName( - final MultiPartArticle fromMpa, final Locale forLocale - ) { - Objects.requireNonNull(fromMpa); - Objects.requireNonNull(forLocale); - final MultiPartArticle mpa = itemRepo - .findById(fromMpa.getObjectId(), MultiPartArticle.class) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No MultiPartArticle with ID %d available", - fromMpa.getObjectId() - ) - ) - ); - return mpa.getName().getValue(forLocale); - } - - @Transactional(Transactional.TxType.REQUIRED) - public String getTitle( - final MultiPartArticle fromMpa, final Locale forLocale - ) { - Objects.requireNonNull(fromMpa); - Objects.requireNonNull(forLocale); - final MultiPartArticle mpa = itemRepo - .findById(fromMpa.getObjectId(), MultiPartArticle.class) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No MultiPartArticle with ID %d available", - fromMpa.getObjectId() - ) - ) - ); - - return mpa.getTitle().getValue(forLocale); - } - - @Transactional(Transactional.TxType.REQUIRED) - public String getSummary( - final MultiPartArticle fromMpa, final Locale forLocale - ) { - Objects.requireNonNull(fromMpa); - Objects.requireNonNull(forLocale); - final MultiPartArticle mpa = itemRepo - .findById(fromMpa.getObjectId(), MultiPartArticle.class) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No MultiPartArticle with ID %d available", - fromMpa.getObjectId() - ) - ) - ); - return mpa.getSummary().getValue(forLocale); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleSectionStepController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleSectionStepController.java deleted file mode 100644 index 185fc0b63..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleSectionStepController.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.multipartarticle; - -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contenttypes.MultiPartArticle; -import org.librecms.contenttypes.MultiPartArticleSection; -import org.librecms.contenttypes.MultiPartArticleSectionManager; -import org.librecms.contenttypes.MultiPartArticleSectionRepository; - -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.stream.Collectors; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class MultiPartArticleSectionStepController { - - @Inject - private ContentItemRepository itemRepo; - - @Inject - private MultiPartArticleSectionRepository sectionRepo; - - @Inject - private MultiPartArticleSectionManager sectionManager; - - @Transactional(Transactional.TxType.REQUIRED) - protected List retrieveSections( - final MultiPartArticle forArticle) { - - final MultiPartArticle article = itemRepo - .findById(forArticle.getObjectId(), - MultiPartArticle.class) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No MultiPartArticle with ID %d in the database.", - forArticle.getObjectId()))); - - //Ensure that the sections are loaded - return article - .getSections() - .stream() - .sorted((section1, section2) -> { - return Integer.compare(section1.getRank(), section2.getRank()); - }) - .collect(Collectors.toList()); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void addSection(final MultiPartArticle article, - final MultiPartArticleSection section) { - - final MultiPartArticle theArticle = itemRepo - .findById(article.getObjectId(), - MultiPartArticle.class) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No MultiPartArticle with ID %d in the database.", - article.getObjectId()))); - - sectionManager.addSectionToMultiPartArticle(section, theArticle); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void removeSection(final MultiPartArticle article, - final MultiPartArticleSection section) { - - final MultiPartArticle theArticle = itemRepo - .findById(article.getObjectId(), - MultiPartArticle.class) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No MultiPartArticle with ID %d in the database.", - article.getObjectId()))); - - final MultiPartArticleSection theSection = sectionRepo - .findById(section.getSectionId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No MultiPartArticleSection with ID %d in the database.", - section.getSectionId()))); - - sectionManager.removeSectionFromMultiPartArticle(theSection, - theArticle); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void moveToFirst(final MultiPartArticle article, - final MultiPartArticleSection section) { - - final MultiPartArticle theArticle = itemRepo - .findById(article.getObjectId(), - MultiPartArticle.class) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No MultiPartArticle with ID %d in the database.", - article.getObjectId()))); - - final MultiPartArticleSection theSection = sectionRepo - .findById(section.getSectionId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No MultiPartArticleSection with ID %d in the database.", - section.getSectionId()))); - - sectionManager.moveToFirst(theArticle, theSection); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void moveAfter(final MultiPartArticle article, - final MultiPartArticleSection section, - final MultiPartArticleSection after) { - - final MultiPartArticle theArticle = itemRepo - .findById(article.getObjectId(), - MultiPartArticle.class) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No MultiPartArticle with ID %d in the database.", - article.getObjectId()))); - - sectionManager.moveSectionAfter(theArticle, section, after); - } - - @Transactional(Transactional.TxType.REQUIRED) - public String getSectionTitle( - final MultiPartArticleSection ofSection, final Locale forLocale - ) { - Objects.requireNonNull(ofSection); - Objects.requireNonNull(forLocale); - - final MultiPartArticleSection section = sectionRepo - .findById(ofSection.getSectionId()) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No section with ID %d available.", ofSection - .getSectionId() - ) - ) - ); - return section.getTitle().getValue(forLocale); - } - - @Transactional(Transactional.TxType.REQUIRED) - public String getSectionText( - final MultiPartArticleSection ofSection, final Locale forLocale - ) { - Objects.requireNonNull(ofSection); - Objects.requireNonNull(forLocale); - - final MultiPartArticleSection section = sectionRepo - .findById(ofSection.getSectionId()) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No section with ID %d available.", ofSection - .getSectionId() - ) - ) - ); - return section.getText().getValue(forLocale); - } - - @Transactional(Transactional.TxType.REQUIRED) - public void updateSection( - final MultiPartArticleSection section, - final String title, - final String text, - final boolean pageBreak, - final Locale locale - ) { - Objects.requireNonNull(section); - Objects.requireNonNull(locale); - - final MultiPartArticleSection update = sectionRepo - .findById(section.getSectionId()) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No section with ID %d available.", - section.getSectionId() - ) - ) - ); - update.getTitle().putValue(locale, title); - update.getText().putValue(locale, title); - update.setPageBreak(pageBreak); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleSectionsStep.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleSectionsStep.java deleted file mode 100644 index b4ff8fff1..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/MultiPartArticleSectionsStep.java +++ /dev/null @@ -1,403 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.multipartarticle; - -import com.arsdigita.bebop.ActionLink; -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Container; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.TableActionEvent; -import com.arsdigita.bebop.event.TableActionListener; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.ResettableContainer; -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.privileges.ItemPrivileges; -import org.librecms.contenttypes.MultiPartArticle; -import org.librecms.contenttypes.MultiPartArticleSection; - -import java.util.Locale; - -/** - * Authoring kit step to manage the sections of a MultiPartArticle. Process is - * implemented with three main components that manipulate the currently selected - * MultiPartArticle and sections. The visibility of these components is managed - * by this class. - * - * Note: This class was originally called {@code MultiPartArticleViewSections}. - * Starting with version 7.0.0 all authoring step classes should end with - * {@code Step} to make them easily identifiable. - * - * @author Dave Turner - * * @author Jens Pelzetter - */ -public class MultiPartArticleSectionsStep extends ResettableContainer { - - /* id keys for each editing panel */ - public static final String SECTION_TABLE = "sec_tbl"; - public static final String SECTION_EDIT = "sec_edt"; - public static final String SECTION_PREVIEW = "sec_prv"; - public static final String SECTION_DELETE = "sec_del"; - - public static final String DATA_TABLE = "dataTable"; - public static final String ACTION_LINK = "actionLink"; - - private final AuthoringKitWizard authoringKitWizard; - private final ItemSelectionModel selectedArticleModel; - private final StringParameter selectedLanguageParam; - private SectionSelectionModel selectedSectionModel; - private SectionSelectionModel moveSectionModel; - private LongParameter moveSectionParam; - - private SectionTable sectionTable; - private SectionEditForm sectionEditForm; - private SectionPreviewPanel sectionPreviewPanel; - private SectionDeleteForm sectionDeleteForm; - - private ActionLink beginLink; - private Label moveSectionLabel; - - private final String typeIdStr; - - public MultiPartArticleSectionsStep( - final ItemSelectionModel selectedArticleModel, - final AuthoringKitWizard authoringKitWizard, - final StringParameter selectedLanguageParam) { - - super(); - this.selectedArticleModel = selectedArticleModel; - this.authoringKitWizard = authoringKitWizard; - this.selectedLanguageParam = selectedLanguageParam; - - typeIdStr = authoringKitWizard - .getContentType() - .getContentItemClass() - .getName(); - - addWidgets(); - } - - private void addWidgets() { - // create the components and set default visibility - add(buildSectionTable(), true); - add(buildSectionEdit(), false); - add(buildSectionDelete(), false); - } - - /** - * Builds a {@link Container} to hold a {@link SectionTable} and a link to - * add a new {@link MultiPartArticleSection}. - * - * @return A {@link Container} for the table of sections. - */ - protected Container buildSectionTable() { - - final ColumnPanel panel = new ColumnPanel(1); - panel.setKey(SECTION_TABLE + typeIdStr); - panel.setBorderColor("#FFFFFF"); - panel.setPadColor("#FFFFFF"); - - moveSectionParam = new LongParameter("moveSection"); - moveSectionModel = new SectionSelectionModel<>(moveSectionParam); - - sectionTable = new SectionTable(selectedArticleModel, - moveSectionModel, - selectedLanguageParam); - sectionTable.setClassAttr(DATA_TABLE); - - // selected section is based on the selection in the SectionTable - @SuppressWarnings("unchecked") - final SingleSelectionModel rowSelectionModel = sectionTable - .getRowSelectionModel(); - selectedSectionModel = new SectionSelectionModel<>( - MultiPartArticleSection.class, rowSelectionModel); - - sectionTable.setSectionModel(selectedSectionModel); - - final Label emptyView = new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.no_sections_yet", - CmsConstants.CMS_BUNDLE)); - sectionTable.setEmptyView(emptyView); - - moveSectionLabel = new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.section.title", - CmsConstants.CMS_BUNDLE)); - moveSectionLabel.addPrintListener(event -> { - final PageState state = event.getPageState(); - final Label target = (Label) event.getTarget(); - - if (moveSectionModel.getSelectedKey(state) != null) { - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - final MultiPartArticleSectionStepController controller = CdiUtil - .createCdiUtil() - .findBean(MultiPartArticleSectionStepController.class); - - final Object[] parameterObj = { - controller.getSectionTitle( - moveSectionModel - .getSelectedSection(state), - selectedLocale - ) - }; - - target.setLabel(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.move_section_name", - CmsConstants.CMS_BUNDLE, - parameterObj)); - } - }); - panel.add(moveSectionLabel, ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - - beginLink = new ActionLink(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.move_to_beginning", - CmsConstants.CMS_BUNDLE)); - panel.add(beginLink); - - beginLink.addActionListener(event -> { - final PageState state = event.getPageState(); - final MultiPartArticle article - = (MultiPartArticle) selectedArticleModel - .getSelectedObject(state); - final MultiPartArticleSection section = moveSectionModel - .getSelectedSection(state); - - final MultiPartArticleSectionStepController controller = CdiUtil - .createCdiUtil() - .findBean(MultiPartArticleSectionStepController.class); - - controller.moveToFirst(article, section); - }); - - moveSectionModel.addChangeListener(event -> { - final PageState state = event.getPageState(); - - if (moveSectionModel.getSelectedKey(state) == null) { - beginLink.setVisible(state, false); - moveSectionLabel.setVisible(state, false); - } else { - beginLink.setVisible(state, true); - moveSectionLabel.setVisible(state, true); - -// final Locale selectedLocale = SelectedLanguageUtil -// .selectedLocale(state, selectedLanguageParam); -// -// final Object[] parameterObj = { -// moveSectionModel -// .getSelectedSection(state) -// .getTitle() -// .getValue(selectedLocale) -// }; -// -// moveSectionLabel -// .setLabel(new GlobalizedMessage( -// "cms.contenttypes.ui.mparticle.move_section_name", -// CmsConstants.CMS_BUNDLE, -// parameterObj), -// state); - } - }); - - // handle clicks to preview or delete a Section - sectionTable.addTableActionListener(new TableActionListener() { - - @Override - public void cellSelected(final TableActionEvent event) { - final PageState state = event.getPageState(); - final TableColumn column = sectionTable - .getColumnModel() - .get(event.getColumn() - .intValue()); - - if (column.getModelIndex() == SectionTable.COL_INDEX_DELETE) { - onlyShowComponent(state, SECTION_DELETE + typeIdStr); - } else if (column.getModelIndex() == SectionTable.COL_INDEX_EDIT) { - onlyShowComponent(state, SECTION_EDIT + typeIdStr); - } - } - - @Override - public void headSelected(final TableActionEvent event) { - //Nothing - } - - }); - - panel.add(sectionTable); - panel.add(buildAddLink()); - - return panel; - } - - /** - * Builds a container to hold a SectionEditForm and a link to return to the - * section list. - * - * @return - */ - protected Container buildSectionEdit() { - - final ColumnPanel panel = new ColumnPanel(1); - panel.setKey(SECTION_EDIT + typeIdStr); - panel.setBorderColor("#FFFFFF"); - panel.setPadColor("#FFFFFF"); - - // display an appropriate title - panel.add(new Label(event -> { - final PageState state = event.getPageState(); - final Label target = (Label) event.getTarget(); - - if (selectedSectionModel.getSelectedKey(state) == null) { - target.setLabel(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.add_section", - CmsConstants.CMS_BUNDLE)); - } else { - target.setLabel(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.edit_section", - CmsConstants.CMS_BUNDLE)); - } - })); - - sectionEditForm = new SectionEditForm(selectedArticleModel, - selectedSectionModel, - this, - selectedLanguageParam); - - panel.add(sectionEditForm); - panel.add(buildViewAllLink()); - panel.add(buildAddLink()); - - return panel; - } - - /** - * Builds a container to hold the component to confirm deletion of a - * section. - * - * @return - */ - protected Container buildSectionDelete() { - - final ColumnPanel panel = new ColumnPanel(1); - panel.setKey(SECTION_DELETE + typeIdStr); - panel.setBorderColor("#FFFFFF"); - panel.setPadColor("#FFFFFF"); - - panel.add(new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.delete_section", - CmsConstants.CMS_BUNDLE))); - sectionDeleteForm = new SectionDeleteForm(selectedArticleModel, - selectedSectionModel, - selectedLanguageParam); - sectionDeleteForm.addSubmissionListener(event -> { - - final PageState state = event.getPageState(); - onlyShowComponent(state, SECTION_TABLE + typeIdStr); - }); - - panel.add(sectionDeleteForm); - panel.add(buildViewAllLink()); - - return panel; - } - - /** - * Utility method to create a link to display the section list. - * - * @return - */ - protected ActionLink buildViewAllLink() { - final ActionLink viewAllLink = new ActionLink( - new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.view_all_sections", - CmsConstants.CMS_BUNDLE)); - viewAllLink.setClassAttr(ACTION_LINK); - viewAllLink.addActionListener(event -> { - onlyShowComponent(event.getPageState(), - SECTION_TABLE + typeIdStr); - }); - - return viewAllLink; - } - - /** - * Utility method to create a link to display the section list. - * - * @return - */ - protected ActionLink buildAddLink() { - final ActionLink addLink = new ActionLink( - new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.add_new_section", - CmsConstants.CMS_BUNDLE)) { - - @Override - public boolean isVisible(final PageState state) { - - final PermissionChecker permissionChecker = CdiUtil - .createCdiUtil() - .findBean(PermissionChecker.class); - final ContentItem item = selectedArticleModel - .getSelectedItem(state); - - return super.isVisible(state) - && permissionChecker.isPermitted(ItemPrivileges.EDIT, - item); - } - - }; - addLink.setClassAttr(ACTION_LINK); - addLink.addActionListener(event -> { - final PageState state = event.getPageState(); - selectedSectionModel.clearSelection(state); - onlyShowComponent(state, SECTION_EDIT + typeIdStr); - }); - - return addLink; - - } - - @Override - public void register(final Page page) { - - super.register(page); - - page.addGlobalStateParam(moveSectionParam); - page.setVisibleDefault(beginLink, false); - page.setVisibleDefault(moveSectionLabel, false); - } - - public String getTypeIDStr() { - return typeIdStr; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionDeleteForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionDeleteForm.java deleted file mode 100755 index b5707bdd5..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionDeleteForm.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.multipartarticle; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.contenttypes.MultiPartArticle; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contenttypes.MultiPartArticleSection; - -import java.util.Locale; - -/** - * A form to confirm deletion of a single section of a MultiPartArticle. - * - * @author Dave Turner - * @author Jens Pelzetter - */ -public class SectionDeleteForm extends Form - implements FormInitListener, FormSubmissionListener, FormProcessListener { - - private final static Logger LOGGER = LogManager - .getLogger(SectionDeleteForm.class.getName()); - - private final ItemSelectionModel selectedArticleModel; - private final SectionSelectionModel selectedSectionModel; - private final SaveCancelSection saveCancelSection; - private final Label sectionNameLabel; - - private final StringParameter selectedLanguageParam; - - public SectionDeleteForm( - final ItemSelectionModel selectedArticleModel, - final SectionSelectionModel selectedSectionModel, - final StringParameter selectedLanguageParam) { - - super("SectionDeleteForm", new ColumnPanel(2)); - this.selectedArticleModel = selectedArticleModel; - this.selectedSectionModel = selectedSectionModel; - this.selectedLanguageParam = selectedLanguageParam; - - final ColumnPanel panel = (ColumnPanel) super.getPanel(); - panel.setBorder(false); - panel.setPadColor("#FFFFFF"); - panel.setColumnWidth(1, "20%"); - panel.setColumnWidth(2, "80%"); - panel.setWidth("100%"); - - sectionNameLabel = new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.section_name")); - super.add(sectionNameLabel, ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - - saveCancelSection = new SaveCancelSection(); - saveCancelSection - .getSaveButton() - .setButtonLabel(new GlobalizedMessage("cms.ui.delete", - CmsConstants.CMS_BUNDLE)); - super.add(saveCancelSection, ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - - super.addInitListener(this); - super.addSubmissionListener(this); - super.addProcessListener(this); - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - - final PageState state = event.getPageState(); - - final MultiPartArticleSection section = selectedSectionModel - .getSelectedSection(state); - - if (section == null) { - LOGGER.error("No section selected"); - } else { - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - final MultiPartArticleSectionStepController controller = CdiUtil - .createCdiUtil() - .findBean(MultiPartArticleSectionStepController.class); - - sectionNameLabel.setLabel( - controller.getSectionTitle(section, selectedLocale), - state - ); - } - } - - @Override - public void submitted(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (saveCancelSection - .getCancelButton() - .isSelected(state)) { - - throw new FormProcessException( - "Submission cancelled", - new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.submission_cancelled", - CmsConstants.CMS_BUNDLE)); - } - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - final MultiPartArticle article = (MultiPartArticle) selectedArticleModel - .getSelectedObject(state); - final MultiPartArticleSection section = selectedSectionModel - .getSelectedSection(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final MultiPartArticleSectionStepController controller = cdiUtil - .findBean(MultiPartArticleSectionStepController.class); - - controller.removeSection(article, section); - - LOGGER.info("section {} deleted", - selectedSectionModel.getSelectedKey(state)); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionEditForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionEditForm.java deleted file mode 100755 index 6ac5140d7..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionEditForm.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.multipartarticle; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.form.CheckboxGroup; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.parameters.TrimmedStringParameter; -import com.arsdigita.cms.ItemSelectionModel; - -import org.librecms.contenttypes.MultiPartArticle; - -import com.arsdigita.cms.ui.CMSDHTMLEditor; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contenttypes.MultiPartArticleSection; -import org.librecms.contenttypes.MultiPartArticleSectionRepository; - -import java.util.Locale; - -/** - * Form to edit an ArticleSection for a MultiPartArticle. - * - * @author Dave Turner - * @author Jens Pelzetter - */ -public class SectionEditForm extends Form { - - public static final String TITLE = "title"; - public static final String TEXT = "text"; - public static final String IMAGE = "image"; - public static final String PAGE_BREAK = "pageBreak"; - - private static final String TEXT_PARAM = "textParam"; - private static final String IMAGE_PARAM = "imageParam"; - - private final ItemSelectionModel selectedArticleModel; - private final SectionSelectionModel selectedSectionModel; - private final StringParameter selectedLanguageParam; - - private MultiPartArticleSectionsStep sectionsStep; - - private SaveCancelSection saveCancelSection; - - public SectionEditForm( - final ItemSelectionModel selectedArticleModel, - final SectionSelectionModel selectedSectionModel, - final StringParameter selectedLanguageParam) { - - this(selectedArticleModel, - selectedSectionModel, - null, - selectedLanguageParam); - } - - public SectionEditForm( - final ItemSelectionModel selectedArticleModel, - final SectionSelectionModel selectedSectionModel, - final MultiPartArticleSectionsStep sectionsStep, - final StringParameter selectedLanguageParam) { - - super("SectionEditForm", new ColumnPanel(2)); - this.selectedArticleModel = selectedArticleModel; - this.selectedSectionModel = selectedSectionModel; - this.sectionsStep = sectionsStep; - this.selectedLanguageParam = selectedLanguageParam; - - super.setMethod(Form.POST); - super.setEncType("multipart/form-data"); - - final ColumnPanel panel = (ColumnPanel) super.getPanel(); - panel.setBorder(false); - panel.setPadColor("#FFFFFF"); - panel.setColumnWidth(1, "20%"); - panel.setColumnWidth(2, "80%"); - panel.setWidth("100%"); - - addWidgets(); - saveCancelSection = new SaveCancelSection(); - add(saveCancelSection, ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - - addInitListener(new SectionInitListener()); - addSubmissionListener(new SectionSubmissionListener()); - addProcessListener(new SectionProcessListener()); - } - - public SaveCancelSection getSaveCancelSection() { - return saveCancelSection; - } - - /** - * Add form widgets for a Section. - */ - private void addWidgets() { - - final TextField titleWidget = new TextField( - new TrimmedStringParameter(TITLE)); - titleWidget.addValidationListener(new NotNullValidationListener()); - titleWidget.setLabel( - new GlobalizedMessage("cms.contenttypes.ui.mparticle.section.title", - CmsConstants.CMS_BUNDLE)); - add(titleWidget); - - final CMSDHTMLEditor textWidget = new CMSDHTMLEditor( - new TrimmedStringParameter(TEXT)); - textWidget.setLabel( - new GlobalizedMessage("cms.contenttypes.ui.mparticle.section.text", - CmsConstants.CMS_BUNDLE)); - textWidget.setRows(40); - textWidget.setCols(70); - textWidget.setWrap(CMSDHTMLEditor.SOFT); - add(textWidget, ColumnPanel.LEFT | ColumnPanel.FULL_WIDTH); - - final CheckboxGroup pageBreak = new CheckboxGroup(PAGE_BREAK); - pageBreak.addOption( - new Option("true", - new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.section.create_break", - CmsConstants.CMS_BUNDLE)))); - add(pageBreak); - } - - /** - * Utility method to create a Section from the form data supplied. - * - * @param event - * @param article - * - * @return - */ - protected MultiPartArticleSection createSection(final FormSectionEvent event, - final MultiPartArticle article) { - - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - - final MultiPartArticleSection section = new MultiPartArticleSection(); - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - section.getTitle().putValue(selectedLocale, (String) data.get(TITLE)); - - return section; - } - - /** - * Initialise the form. If there is a selected section, ie. this is an - * 'edit' step rather than a 'create new' step, load the data into the form - * fields. - */ - private class SectionInitListener implements FormInitListener { - - @Override - public void init(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final MultiPartArticleSectionRepository sectionRepo = cdiUtil - .findBean(MultiPartArticleSectionRepository.class); - - if (selectedSectionModel.getSelectedKey(state) != null) { - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - final MultiPartArticleSectionStepController controller = CdiUtil - .createCdiUtil() - .findBean(MultiPartArticleSectionStepController.class); - - final MultiPartArticleSection section = selectedSectionModel - .getSelectedSection(state); - - data.put( - TITLE, controller.getSectionTitle(section, selectedLocale) - ); - data.put( - TEXT, controller.getSectionText(section, selectedLocale) - ); - - if (section.isPageBreak()) { - data.put(PAGE_BREAK, new Object[]{"true"}); - } - } - } - - } - - /** - * Called on form submission. Check to see if the user clicked the cancel - * button. If they did, don't continue with the form. - */ - private class SectionSubmissionListener implements FormSubmissionListener { - - @Override - public void submitted(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (saveCancelSection - .getCancelButton() - .isSelected(state) - && sectionsStep != null) { - - sectionsStep.onlyShowComponent( - state, - MultiPartArticleSectionsStep.SECTION_TABLE - + sectionsStep.getTypeIDStr()); - - throw new FormProcessException( - "Submission cancelled", - new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.submission_cancelled", - CmsConstants.CMS_BUNDLE) - ); - } - } - - } - - /** - * Called after form has been validated. Create the new ArticleSection and - * assign it to the current MultiPartArticle. - */ - private class SectionProcessListener implements FormProcessListener { - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final MultiPartArticleSectionStepController controller = cdiUtil - .findBean(MultiPartArticleSectionStepController.class); - final MultiPartArticleSectionRepository sectionRepo = cdiUtil - .findBean(MultiPartArticleSectionRepository.class); - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - final MultiPartArticle article - = (MultiPartArticle) selectedArticleModel - .getSelectedItem(state); - - // get the selected section to update or create a new one - final MultiPartArticleSection section; - if (selectedSectionModel.getSelectedKey(state) == null) { - section = new MultiPartArticleSection(); - - } else { - section = selectedSectionModel.getSelectedSection(state); - } - -// section.getTitle().putValue(selectedLocale, -// (String) data.get(TITLE)); - final Object[] pageBreakVal = (Object[]) data.get(PAGE_BREAK); - final boolean pageBreak; - if (pageBreakVal == null - || pageBreakVal.length == 0 - || !"true".equals(pageBreakVal[0])) { - pageBreak = false; - } else { - pageBreak = true; - } -// section.setPageBreak(pageBreak); - - final String text; - if (data.get(TEXT) == null) { - text = ""; - } else { - text = (String) data.get(TEXT); - } -// section.getText().putValue(selectedLocale, text); - -// sectionRepo.save(section); - if (selectedSectionModel.getSelectedKey(state) == null) { - section.getTitle().putValue(selectedLocale, - (String) data.get(TITLE)); - section.setPageBreak(pageBreak); - section.getText().putValue(selectedLocale, text); - - controller.addSection(article, section); - } else { - controller.updateSection( - section, - (String) data.get(TITLE), - text, - pageBreak, - selectedLocale - ); - } - - if (sectionsStep != null) { - sectionsStep - .onlyShowComponent(state, - MultiPartArticleSectionsStep.SECTION_TABLE - + sectionsStep.getTypeIDStr()); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionPreviewPanel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionPreviewPanel.java deleted file mode 100755 index d453033b8..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionPreviewPanel.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.multipartarticle; - -import com.arsdigita.bebop.BoxPanel; - -public class SectionPreviewPanel extends BoxPanel -{ - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionSelectionModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionSelectionModel.java deleted file mode 100644 index 41a4e6253..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionSelectionModel.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.multipartarticle; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.ParameterModel; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.UnexpectedErrorException; -import org.librecms.contenttypes.MultiPartArticleSection; -import org.librecms.contenttypes.MultiPartArticleSectionRepository; - -/** - * A {@link SingleSelectionModel} implementation for - * {@link MultiPartArticleSection}s. - * - * @param - * - * @author Jens Pelzetter - */ -public class SectionSelectionModel - implements SingleSelectionModel { - - private final Class clazz; - private final SingleSelectionModel model; - - public SectionSelectionModel(final LongParameter parameter) { - this(MultiPartArticleSection.class.getName(), parameter); - } - - public SectionSelectionModel(final String parameterName) { - this(MultiPartArticleSection.class.getName(), - new LongParameter(parameterName)); - } - - public SectionSelectionModel(final Class clazz, - final String parameterName) { - this(clazz, new LongParameter(parameterName)); - } - - @SuppressWarnings("unchecked") - public SectionSelectionModel(final String className, - final String parameterName) { - - try { - clazz = (Class) Class.forName(className); - } catch (ClassNotFoundException ex) { - throw new UnexpectedErrorException(ex); - } - - model = new ParameterSingleSelectionModel<>( - new LongParameter(parameterName)); - } - - public SectionSelectionModel(final Class clazz, - final LongParameter parameter) { - this(clazz, new ParameterSingleSelectionModel<>(parameter)); - } - - @SuppressWarnings("unchecked") - public SectionSelectionModel(final String className, - final LongParameter parameter) { - - try { - clazz = (Class) Class.forName(className); - } catch (ClassNotFoundException ex) { - throw new UnexpectedErrorException(ex); - } - model = new ParameterSingleSelectionModel<>(parameter); - } - - public SectionSelectionModel(final Class clazz, - final SingleSelectionModel model) { - this.clazz = clazz; - this.model = model; - } - - @SuppressWarnings("unchecked") - public SectionSelectionModel(final String className, - final SingleSelectionModel model) { - - try { - clazz = (Class) Class.forName(className); - } catch (ClassNotFoundException ex) { - throw new UnexpectedErrorException(ex); - } - this.model = model; - } - - @Override - public boolean isSelected(final PageState state) { - return model.isSelected(state); - } - - @Override - public Long getSelectedKey(final PageState state) { - final Object key = model.getSelectedKey(state); - if (key == null) { - return null; - } else if (key instanceof Long) { - return (Long) key; - } else if (key instanceof String) { - return Long.parseLong((String) key); - } else { - return Long.parseLong(key.toString()); - } - } - - @Override - public void setSelectedKey(final PageState state, final Long key) { - model.setSelectedKey(state, key); - } - - public T getSelectedSection(final PageState state) { - final Long key = getSelectedKey(state); - final MultiPartArticleSectionRepository sectionRepo = CdiUtil - .createCdiUtil() - .findBean(MultiPartArticleSectionRepository.class); - @SuppressWarnings("unchecked") - final T object = (T) sectionRepo.findById(key).get(); - return object; - } - - @Override - public void clearSelection(final PageState state) { - - model.clearSelection(state); - } - - @Override - public void addChangeListener(final ChangeListener changeListener) { - - model.addChangeListener(changeListener); - } - - @Override - public void removeChangeListener(final ChangeListener changeListener) { - - model.removeChangeListener(changeListener); - } - - @Override - public ParameterModel getStateParameter() { - - return model.getStateParameter(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionTable.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionTable.java deleted file mode 100755 index 0a5b3db7d..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionTable.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.multipartarticle; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.TableActionEvent; -import com.arsdigita.bebop.event.TableActionListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableColumnModel; - -import org.librecms.contentsection.ContentItem; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.contenttypes.MultiPartArticle; - -import com.arsdigita.util.LockableImpl; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.CmsConstants; -import org.librecms.contentsection.privileges.ItemPrivileges; -import org.librecms.contenttypes.MultiPartArticleSection; -import org.librecms.contenttypes.MultiPartArticleSectionRepository; - -import java.util.Objects; - -/** - * A table that displays the sections for the currently selected - * MultiPartArticle. - * - * @author Dave Turner - * @author Jens Pelzetter - */ -public class SectionTable extends Table { - - /** - * Index of the title column - */ - public static final int COL_INDEX_TITLE = 0; - /** - * Index of the page break column - */ - public static final int COL_PAGE_BREAK = 1; - /** - * Index of the edit column. - */ - public static final int COL_INDEX_EDIT = 2; - /** - * Index of the move column - */ - public static final int COL_INDEX_MOVE = 3; - /** - * Index of the delete column - */ - public static final int COL_INDEX_DELETE = 4; - - private ItemSelectionModel selectedArticleModel; - private SectionSelectionModel selectedSectionModel; - private SectionSelectionModel moveSectionModel; - - /** - * Constructor. Create an instance of this class. - * - * @param selectedArticleModel a selection model that returns the - * MultiPartArticle which holds the sections to - * display. - * @param moveSectionModel - * @param selectedLanguageParam - */ - public SectionTable( - final ItemSelectionModel selectedArticleModel, - final SectionSelectionModel moveSectionModel, - final StringParameter selectedLanguageParam) { - - super(); - this.selectedArticleModel = selectedArticleModel; - this.moveSectionModel = moveSectionModel; - - final TableColumnModel model = getColumnModel(); - model.add(new TableColumn( - COL_INDEX_TITLE, - new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.section_table.header_section", - CmsConstants.CMS_BUNDLE)))); - model.add(new TableColumn( - COL_PAGE_BREAK, - new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.section_table.header_page_break", - CmsConstants.CMS_BUNDLE)))); - model.add(new TableColumn( - COL_INDEX_EDIT, - new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.section_table.header_edit", - CmsConstants.CMS_BUNDLE)))); - model.add(new TableColumn( - COL_INDEX_MOVE, - new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.section_table.header_move", - CmsConstants.CMS_BUNDLE)))); - model.add(new TableColumn( - COL_INDEX_DELETE, - new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.section_table.header_delete", - CmsConstants.CMS_BUNDLE)))); - - model.get(COL_INDEX_EDIT).setCellRenderer(new SectionTableCellRenderer(true)); - model.get(COL_INDEX_MOVE).setCellRenderer(new SectionTableCellRenderer(true)); - model.get(COL_INDEX_DELETE).setCellRenderer(new SectionTableCellRenderer(true)); - - super.setModelBuilder( - new SectionTableModelBuilder(selectedArticleModel, - moveSectionModel, - selectedLanguageParam)); - - super.addTableActionListener(new TableActionListener() { - - @Override - public void cellSelected(final TableActionEvent event) { - - final PageState state = event.getPageState(); - - final TableColumn column = getColumnModel() - .get(event.getColumn()); - - if (column.getModelIndex() == COL_INDEX_MOVE) { - - if (moveSectionModel.getSelectedKey(state) == null) { - moveSectionModel.setSelectedKey( - state, - selectedSectionModel.getSelectedKey(state)); - } else { - final MultiPartArticle article - = (MultiPartArticle) selectedArticleModel - .getSelectedObject(state); - - final Long sectionId = moveSectionModel - .getSelectedKey(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final MultiPartArticleSectionRepository sectionRepo - = cdiUtil - .findBean( - MultiPartArticleSectionRepository.class); - final MultiPartArticleSectionStepController controller - = cdiUtil - .findBean( - MultiPartArticleSectionStepController.class); - final MultiPartArticleSection section = sectionRepo - .findById(sectionId) - .orElseThrow(() -> new IllegalArgumentException( - String - .format( - "No MultiPartArticleSection with ID %d in " - + "the database.", - sectionId))); - - final Long destId = Long - .parseLong((String) event.getRowKey()); - final MultiPartArticleSection destSection = sectionRepo - .findById(destId) - .orElseThrow(() -> new IllegalArgumentException( - String.format( - "No MultiPartArticleSection with ID %d in " - + "the database.", - destId))); - - controller.moveAfter(article, section, destSection); - -// // if sect is lower in rank than the dest -// // then move below is default behavior -// int rank = destSection.getRank(); -// if (section.getRank() > rank) { -// // otherwise, add one to get "move below" -// rank++; -// } -// -// section.setRank(rank); -// sectionRepo.save(section); - moveSectionModel.setSelectedKey(state, null); - } - } - } - - @Override - public void headSelected(final TableActionEvent event) { - // do nothing - } - - }); - } - - public void setSectionModel( - final SectionSelectionModel selectedSectionModel) { - - Objects.requireNonNull(selectedSectionModel); - - this.selectedSectionModel = selectedSectionModel; - } - - private class SectionTableCellRenderer - extends LockableImpl - implements TableCellRenderer { - - private boolean active; - - public SectionTableCellRenderer() { - this(false); - } - - public SectionTableCellRenderer(final boolean active) { - this.active = active; - } - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil - .findBean(PermissionChecker.class); - - final ContentItem article = selectedArticleModel.getSelectedObject( - state); - - boolean createLink = active - && permissionChecker - .isPermitted(ItemPrivileges.EDIT, article); - - final Component ret; - if (value instanceof Label) { - if (createLink) { - ret = new ControlLink((Component) value); - } else { - ret = (Component) value; - } - } else if (value instanceof String) { - // Backwards compatibility, should be removed asap! - if (createLink) { - ret = new ControlLink(value.toString()); - } else { - ret = new Text(value.toString()); - } - } else { - ret = new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.section_table.link_not_defined", - CmsConstants.CMS_BUNDLE), - false); - } - - return ret; - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionTableModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionTableModel.java deleted file mode 100644 index de8084d7a..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionTableModel.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.multipartarticle; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableColumnModel; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contenttypes.MultiPartArticle; -import org.librecms.contenttypes.MultiPartArticleSection; - -import java.util.Iterator; -import java.util.List; -import java.util.Locale; - -class SectionTableModel implements TableModel { - - private final TableColumnModel columnModel; - private final SectionTable sectionTable; - private final PageState pageState; - private final StringParameter selectedLanguageParam; - private final SectionSelectionModel moveSectionModel; - - private final Iterator iterator; - private MultiPartArticleSection currentSection; - - /** - * Constructor. - * - * @param sectionTable - * @param pageState - * @param article - * @param moveSectionModel - */ - public SectionTableModel( - final Table sectionTable, - final PageState pageState, - final StringParameter selectedLanguageParam, - final MultiPartArticle article, - final SectionSelectionModel moveSectionModel) { - - this.pageState = pageState; - this.selectedLanguageParam = selectedLanguageParam; - this.sectionTable = (SectionTable) sectionTable; - this.moveSectionModel = moveSectionModel; - - columnModel = sectionTable.getColumnModel(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final MultiPartArticleSectionStepController controller = cdiUtil - .findBean(MultiPartArticleSectionStepController.class); - - final List sections = controller - .retrieveSections(article); - iterator = sections.iterator(); - } - - /** - * Return the number of columns this TableModel has. - */ - @Override - public int getColumnCount() { - return columnModel.size(); - } - - /** - * Move to the next row and return true if the model is now positioned on a - * valid row. - */ - @Override - public boolean nextRow() { - - if (iterator.hasNext()) { - currentSection = iterator.next(); - return true; - } else { - return false; - } - } - - /** - * Return the data element for the given column and the current row. - */ - @Override - public Object getElementAt(final int columnIndex) { - - if (columnModel == null) { - return null; - } - - final MultiPartArticleSectionStepController controller = CdiUtil - .createCdiUtil() - .findBean(MultiPartArticleSectionStepController.class); - - switch (columnIndex) { - case SectionTable.COL_INDEX_TITLE: - return controller.getSectionTitle( - currentSection, - SelectedLanguageUtil.selectedLocale( - pageState, selectedLanguageParam - ) - ) - ; - case SectionTable.COL_PAGE_BREAK: - if (currentSection.isPageBreak()) { - return new Label( - new GlobalizedMessage("cms.ui.yes", - CmsConstants.CMS_BUNDLE)); - } else { - return new Label( - new GlobalizedMessage("cms.ui.no", - CmsConstants.CMS_BUNDLE)); - } - case SectionTable.COL_INDEX_EDIT: - return new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.section_table.link_edit", - CmsConstants.CMS_BUNDLE)); - case SectionTable.COL_INDEX_DELETE: - return new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.section_table.link_delete", - CmsConstants.CMS_BUNDLE)); - case SectionTable.COL_INDEX_MOVE: - if (moveSectionModel.getSelectedKey(pageState) == null) { - return new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.section_table.link_move", - CmsConstants.CMS_BUNDLE)); - } else { - return new Label(new GlobalizedMessage( - "cms.contenttypes.ui.mparticle.section_table.link_move_below", - CmsConstants.CMS_BUNDLE)); - } - default: - return null; - } - } - - /** - * Return the key for the given column and the current row. - */ - @Override - public Object getKeyAt(final int columnIndex) { - return currentSection.getSectionId(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionTableModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionTableModelBuilder.java deleted file mode 100644 index 030b9cffd..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/multipartarticle/SectionTableModelBuilder.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.multipartarticle; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.util.LockableImpl; - -import org.librecms.contenttypes.MultiPartArticle; -import org.librecms.contenttypes.MultiPartArticleSection; - -/** - * The model builder to generate a suitable model for the SectionTable - */ -class SectionTableModelBuilder extends LockableImpl implements TableModelBuilder { - - private final ItemSelectionModel selectedArticleModel; - private final SectionSelectionModel moveSectionModel; - - private final StringParameter selectedLanguageParam; - - /** - * Private class constructor. - * - * @param selectedArticleModel - * @param moveSectionModel - */ - public SectionTableModelBuilder( - final ItemSelectionModel selectedArticleModel, - final SectionSelectionModel moveSectionModel, - final StringParameter selectedLanguageParam) { - - this.selectedArticleModel = selectedArticleModel; - this.moveSectionModel = moveSectionModel; - this.selectedLanguageParam = selectedLanguageParam; - } - - /** - * - * @param table - * @param state - * - * @return - */ - @Override - public TableModel makeModel(final Table table, - final PageState state) { - - table.getRowSelectionModel().clearSelection(state); - MultiPartArticle article - = (MultiPartArticle) selectedArticleModel - .getSelectedObject(state); - return new SectionTableModel(table, - state, - selectedLanguageParam, - article, - moveSectionModel); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewItemForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewItemForm.java deleted file mode 100755 index 9e7a9f4d0..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewItemForm.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.news; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.OptionGroup; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.cms.ui.ItemSearch; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.xml.Element; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentType; -import org.librecms.contentsection.ContentTypeRepository; - -import java.util.List; -import java.util.TooManyListenersException; - -import org.librecms.contenttypes.ContentTypeInfo; -import org.librecms.contenttypes.ContentTypesManager; - -/** - * A form element which displays a select box of all content types available - * under the given content section, and forwards to the item creation UI when - * the user selects a content type to instantiate. - * - * @author Stanislav Freidin (sfreidin@arsdigtia.com) - * @author Jens Pelzetter - */ -public abstract class NewItemForm extends Form { - - public static final String TYPE_ID = "tid"; - - private final SingleSelect typeSelect; - private final Submit submit; - private final Label emptyLabel; - private final Label createLabel; - - public NewItemForm(final String name) { - this(name, BoxPanel.HORIZONTAL); - } - - /** - * Construct a new NewItemForm. It sets a vertical BoxPanel as the component - * container. - * - * @param name the name attribute of the form. - * @param orientation - */ - public NewItemForm(final String name, final int orientation) { - - super(name, new BoxPanel(BoxPanel.VERTICAL)); - setIdAttr("new_item_form"); - - final BoxPanel panel = new BoxPanel(orientation); - panel.setWidth("2%"); - panel.setBorder(0); - - // create and add an "empty" component - emptyLabel = new Label( - new GlobalizedMessage("cms.ui.authoring.no_types_registered", - CmsConstants.CMS_BUNDLE), - false); - emptyLabel.setIdAttr("empty_label"); - panel.add(emptyLabel); - - createLabel = new Label( - new GlobalizedMessage("cms.ui.authoring.create_new", - CmsConstants.CMS_BUNDLE), - false); - createLabel.setIdAttr("create_label"); - panel.add(createLabel); - - typeSelect = new SingleSelect(new LongParameter(TYPE_ID), - OptionGroup.SortMode.ALPHABETICAL_ASCENDING); - try { - typeSelect.addPrintListener(new PrintListener() { - - // Read the content section's content types and add them as options - @Override - public void prepare(final PrintEvent event) { - final OptionGroup target = (OptionGroup) event - .getTarget(); - target.clearOptions(); - final PageState state = event.getPageState(); - - // gather the content types of this section into a list - final ContentSection section = getContentSection(state); -// final ContentType parentType; - final List typesCollection; - final Long singleTypeID = (Long) state.getValue( - new LongParameter(ItemSearch.SINGLE_TYPE_PARAM)); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final NewItemFormController controller = cdiUtil.findBean( - NewItemFormController.class); - final ContentTypeRepository typeRepo = cdiUtil.findBean( - ContentTypeRepository.class); - final ContentTypesManager typesManager = cdiUtil.findBean( - ContentTypesManager.class); - final PermissionChecker permissionChecker = cdiUtil - .findBean(PermissionChecker.class); - - typesCollection = controller.getContentTypes(section); - - for (final ContentType type : typesCollection) { - final ContentTypeInfo typeInfo = typesManager - .getContentTypeInfo(type.getContentItemClass()); - final String value = Long.toString(type.getObjectId()); - final Label label = new Label( - new GlobalizedMessage(typeInfo.getLabelKey(), - typeInfo.getLabelBundle())); - target.addOption( - new Option(value, label)); - } - } - - }); - } catch (TooManyListenersException ex) { - throw new UncheckedWrapperException("Too many listeners.", ex); - } - - panel.add(typeSelect); - - submit = new Submit("new", - new GlobalizedMessage("cms.ui.authoring.go", - CmsConstants.CMS_BUNDLE)); - panel.add(submit); - - add(panel); - } - - public abstract ContentSection getContentSection(PageState state); - - /** - * - * @param state - * - * @return - */ - public Long getTypeID(final PageState state) { - return (Long) typeSelect.getValue(state); - } - - /** - * - * @return - */ - public final SingleSelect getTypeSelect() { - return typeSelect; - } - - /** - * Generate XML - show/hide labels/widgets - * - * @param state - * @param parent - */ - @Override - public void generateXML(final PageState state, final Element parent) { - - if (isVisible(state)) { - final ContentSection section = getContentSection(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final NewItemFormController controller = cdiUtil.findBean( - NewItemFormController.class); - boolean isEmpty = !controller.hasContentTypes(section); - - createLabel.setVisible(state, !isEmpty); - typeSelect.setVisible(state, !isEmpty); - submit.setVisible(state, !isEmpty); - emptyLabel.setVisible(state, isEmpty); - - super.generateXML(state, parent); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewItemFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewItemFormController.java deleted file mode 100644 index 478226cbb..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewItemFormController.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.authoring.news; - -import org.libreccm.l10n.GlobalizationHelper; - -import java.util.Collections; -import java.util.List; - -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionRepository; - -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.persistence.EntityManager; -import javax.persistence.TypedQuery; -import javax.transaction.Transactional; - -import org.libreccm.security.PermissionChecker; -import org.libreccm.security.Role; -import org.libreccm.security.RoleRepository; -import org.libreccm.security.Shiro; -import org.libreccm.security.User; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentType; -import org.librecms.contentsection.ContentTypeRepository; -import org.librecms.contenttypes.News; - -import java.util.Locale; - -/** - * Controller class for the {@link NewItemForm}. - * - * @author Jens Pelzetter - */ -@RequestScoped -class NewItemFormController { - - @Inject - private EntityManager entityManager; - - @Inject - private Shiro shiro; - - @Inject - private PermissionChecker permissionChecker; - - @Inject - private RoleRepository roleRepo; - - @Inject - private ContentSectionRepository sectionRepo; - - @Inject - private ContentTypeRepository typeRepo; - - @Transactional(Transactional.TxType.REQUIRED) - protected boolean hasContentTypes(final ContentSection section) { - Objects.requireNonNull(section, "Can't work with null for the section."); - - final Optional user = shiro.getUser(); - if (!user.isPresent()) { - return false; - } - - final List roles = user.get().getRoleMemberships().stream() - .map(membership -> membership.getRole()) - .collect(Collectors.toList()); - - final TypedQuery query = entityManager.createNamedQuery( - "ContentSection.hasUsableContentTypes", Boolean.class); - query.setParameter("section", section); - query.setParameter("roles", roles); - query.setParameter("isSysAdmin", permissionChecker.isPermitted("*")); - - return query.getSingleResult(); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected List getContentTypes(final ContentSection section) { - Objects.requireNonNull(section); - - final Optional user = shiro.getUser(); - if (!user.isPresent()) { - return Collections.EMPTY_LIST; - } - - final List roles = user.get().getRoleMemberships().stream() - .map(membership -> membership.getRole()) - .collect(Collectors.toList()); - - final TypedQuery query = entityManager.createNamedQuery( - "ContentSection.findUsableContentTypes", - ContentType.class); - query.setParameter("section", section); - query.setParameter("roles", roles); - query.setParameter("isSysAdmin", permissionChecker.isPermitted("*")); - - return query.getResultList(); - } - - - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewsController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewsController.java deleted file mode 100644 index 716cd2a8c..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewsController.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.ui.authoring.news; - -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contenttypes.News; - -import java.util.Date; -import java.util.Locale; -import java.util.Objects; - -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -public class NewsController { - - @Inject - private ContentItemRepository itemRepo; - - @Transactional - protected String getDescription( - final News fromNews, final Locale forLocale - ) { - Objects.requireNonNull(fromNews); - final News news = itemRepo - .findById(fromNews.getObjectId(), News.class) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No News with ID %d available.", fromNews.getObjectId() - ) - ) - ); - - return news.getDescription().getValue(forLocale); - } - - @Transactional - protected String getText(final News fromNews, final Locale forLocale) { - Objects.requireNonNull(fromNews); - final News news = itemRepo - .findById(fromNews.getObjectId(), News.class) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No News with ID %d available", - fromNews.getObjectId() - ) - ) - ); - - return news.getText().getValue(forLocale); - } - - @Transactional - protected void updateText( - final News ofNews, - final Locale forLocale, - final String text - ) { - Objects.requireNonNull(ofNews); - final News news = itemRepo - .findById(ofNews.getObjectId(), News.class) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No News with ID %d available", - ofNews.getObjectId() - ) - ) - ); - - news.getText().putValue(forLocale, text); - itemRepo.save(news); - } - - @Transactional - protected void update( - final News news, - final Date releaseDate, - final Locale locale, - final String description - ) { - Objects.requireNonNull(news); - final News update = itemRepo - .findById(news.getObjectId(), News.class) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No News with ID %d available", - news.getObjectId() - ) - ) - ); - - update.setReleaseDate(releaseDate); - update.getDescription().putValue(locale, description); - itemRepo.save(update); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewsPropertiesStep.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewsPropertiesStep.java deleted file mode 100755 index 021af1c9c..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewsPropertiesStep.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.news; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.parameters.StringParameter; - -import com.arsdigita.cms.ItemSelectionModel; - -import org.librecms.contenttypes.News; - -import com.arsdigita.toolbox.ui.DomainObjectPropertySheet; -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.BasicPageForm; -import com.arsdigita.cms.ui.authoring.SimpleEditStep; -import com.arsdigita.cms.ui.workflow.WorkflowLockedComponentAccess; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.CmsConstants; - -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.text.DateFormat; -import java.util.Arrays; -import java.util.Objects; -import java.util.Optional; - -/** - * Authoring step to edit the simple attributes of the News content type (and - * its subclasses). The attributes edited are {@code name}, {@code title}, - * {@code lead} and {@code item date}. This authoring step replaces the - * {@link com.arsdigita.ui.authoring.PageEdit} step for this type. - * - * @see com.arsdigita.cms.contenttypes.NewsItem - * - */ -public class NewsPropertiesStep extends SimpleEditStep { - - /** - * The name of the editing sheet added to this step - */ - public static String EDIT_SHEET_NAME = "edit"; - - public NewsPropertiesStep(final ItemSelectionModel itemModel, - final AuthoringKitWizard parent, - final StringParameter selectedLanguageParam) { - - super(itemModel, parent, selectedLanguageParam); - - Objects.requireNonNull(selectedLanguageParam); - - setDefaultEditKey(EDIT_SHEET_NAME); - BasicPageForm editSheet; - - editSheet = new NewsPropertyForm(itemModel, this, selectedLanguageParam); - add(EDIT_SHEET_NAME, - new GlobalizedMessage("cms.ui.edit", CmsConstants.CMS_BUNDLE), - new WorkflowLockedComponentAccess(editSheet, itemModel), - editSheet.getSaveCancelSection().getCancelButton()); - - setDisplayComponent(getNewsDomainObjectPropertySheet( - itemModel, - selectedLanguageParam)); - } - - /** - * Returns a component that displays the properties of the NewsItem - * specified by the ItemSelectionModel passed in. - * - * @param itemModel The ItemSelectionModel to use - * @param selectedLanguageParam - * - * @pre itemModel != null - * @return A component to display the state of the basic properties of the - * item - * - */ - public static Component getNewsDomainObjectPropertySheet( - final ItemSelectionModel itemModel, - final StringParameter selectedLanguageParam) { - - final DomainObjectPropertySheet sheet = new DomainObjectPropertySheet( - itemModel, - false, - selectedLanguageParam); - - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.title", - CmsConstants.CMS_BUNDLE), - "title"); - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.name", - CmsConstants.CMS_BUNDLE), - "name"); - sheet.add(new GlobalizedMessage("cms.contenttypes.ui.newsitem.lead", - CmsConstants.CMS_BUNDLE), - "description"); - - // Show news item on homepage? - sheet.add(new GlobalizedMessage( - "cms.contenttypes.ui.newsitem.date", - CmsConstants.CMS_BUNDLE), - "releaseDate", - new NewsItemDateAttributeFormatter()); - - return sheet; - } - - /** - * Private class which implements an AttributeFormatter interface for - * NewsItem's date values. Its format(...) class returns a string - * representation for either a false or a true value. - */ - private static class NewsItemDateAttributeFormatter - implements DomainObjectPropertySheet.AttributeFormatter { - - /** - * Constructor, does nothing. - */ - public NewsItemDateAttributeFormatter() { - } - - /** - * Formatter for the value of an attribute. - * - * It currently relays on the prerequisite that the passed in property - * attribute is in fact a date property. No type checking yet! - * - * Note: the format method has to be executed at each page request. Take - * care to properly adjust globalization and localization here! - * - * @param obj Object containing the attribute to format. - * @param attribute Name of the attribute to retrieve and format - * @param state PageState of the request - * - * @return A String representation of the retrieved boolean attribute of - * the domain object. - */ - public String format(final Object obj, - final String attribute, - final PageState state) { - - if (obj != null && obj instanceof News) { - - final News newsItem = (News) obj; - final BeanInfo beanInfo; - try { - beanInfo = Introspector.getBeanInfo(obj.getClass()); - } catch (IntrospectionException ex) { - throw new UnexpectedErrorException(ex); - } - final Optional propertyDescriptor = Arrays - .stream(beanInfo.getPropertyDescriptors()) - .filter(current -> attribute.equals(current.getName())) - .findAny(); - - if (propertyDescriptor.isPresent()) { - final GlobalizationHelper globalizationHelper = CdiUtil - .createCdiUtil().findBean(GlobalizationHelper.class); - - final Method readMethod = propertyDescriptor - .get() - .getReadMethod(); - - final Object result; - try { - result = readMethod.invoke(obj); - } catch (IllegalAccessException - | IllegalArgumentException - | InvocationTargetException ex) { - throw new UnexpectedErrorException(ex); - } - - return DateFormat - .getDateInstance( - DateFormat.LONG, - globalizationHelper.getNegotiatedLocale()) - .format(result); - - } else { - return (String) new GlobalizedMessage( - "cms.ui.unknown", - CmsConstants.CMS_BUNDLE) - .localize(); - } - - } else { - return (String) new GlobalizedMessage("cms.ui.unknown", - CmsConstants.CMS_BUNDLE) - .localize(); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewsPropertyForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewsPropertyForm.java deleted file mode 100755 index 0a6ae4515..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewsPropertyForm.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.authoring.news; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.parameters.DateParameter; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; - -import org.librecms.contenttypes.News; - -import com.arsdigita.cms.ui.authoring.BasicPageForm; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contenttypes.NewsConfig; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Locale; -import java.util.Objects; - -/** - * Form to edit the basic properties of a {@link News} item. These are name, - * title, item date and reference code. Used by {@link NewsPropertiesStep} - * authoring kit step. - * - * This form can be extended to create forms for NewsItem subclasses. - * - */ -public class NewsPropertyForm extends BasicPageForm - implements FormProcessListener, FormInitListener, FormSubmissionListener { - - private NewsPropertiesStep propertiesStep; - /** - * lead parameter name - */ - public static final String LEAD = "lead"; - /** - * Item date parameter name - */ - public static final String NEWS_DATE = "news_date"; - public static final String IS_HOMEPAGE = "isHomepage"; - /** - * Name of this form - */ - public static final String ID = "news_item_edit"; - - private final StringParameter selectedLanguageParam; - - private com.arsdigita.bebop.form.Date releaseDateSelector; - - /** - * Creates a new form to edit the NewsItem object specified by the item - * selection model passed in. - * - * @param itemSelectionModel The ItemSelectionModel to use to obtain the - * NewsItem to work on - * @param selectedLanguageParam - */ - public NewsPropertyForm(final ItemSelectionModel itemSelectionModel, - final StringParameter selectedLanguageParam) { - - this(itemSelectionModel, null, selectedLanguageParam); - } - - /** - * Creates a new form to edit the NewsItem object specified by the item - * selection model passed in. - * - * @param itemSelectionModel The ItemSelectionModel to use to obtain the - * NewsItem to work on - * @param propertiesStep The NewsPropertiesStep which controls this - * form. - * @param selectedLanguageParam - */ - public NewsPropertyForm(final ItemSelectionModel itemSelectionModel, - final NewsPropertiesStep propertiesStep, - final StringParameter selectedLanguageParam) { - - super(ID, itemSelectionModel, selectedLanguageParam); - - Objects.requireNonNull(selectedLanguageParam); - - this.propertiesStep = propertiesStep; - this.selectedLanguageParam = selectedLanguageParam; - addSubmissionListener(this); - } - - /** - * Adds widgets to the form. - */ - @Override - protected void addWidgets() { - - super.addWidgets(); - - final ParameterModel leadParam = new StringParameter(LEAD); - final TextArea lead = new TextArea(leadParam); - lead.setLabel(new GlobalizedMessage( - "cms.contenttypes.ui.newsitem.lead", - CmsConstants.CMS_BUNDLE)); - lead.setCols(50); - lead.setRows(5); - add(lead); - - final ConfigurationManager confManager = CdiUtil - .createCdiUtil() - .findBean(ConfigurationManager.class); - final NewsConfig newsConfig = confManager - .findConfiguration(NewsConfig.class); - - final int startYear = newsConfig.getStartYear(); - final int endYearDelta = newsConfig.getEndYearDelta(); - final int currentYear = GregorianCalendar - .getInstance() - .get(Calendar.YEAR); - final int endYear = currentYear + endYearDelta; - - final ParameterModel newsDateParam = new DateParameter(NEWS_DATE); - newsDateParam.addParameterListener(new NotNullValidationListener()); - releaseDateSelector = new com.arsdigita.bebop.form.Date(newsDateParam); - releaseDateSelector.setYearRange(startYear, endYear); - releaseDateSelector.setLabel(new GlobalizedMessage( - "cms.contenttypes.ui.newsitem.date", - CmsConstants.CMS_BUNDLE)); - add(releaseDateSelector); - } - - /** - * Form initialisation hook. Fills widgets with data. - * - * @param event - */ - @Override - public void init(final FormSectionEvent event) { - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - final News item = (News) super.initBasicWidgets(event); - - // set a default item date, if none set - final java.util.Date releaseDate; - if (item.getReleaseDate() == null) { - // new Date is initialised to current time - releaseDate = new java.util.Date(); - } else { - releaseDate = item.getReleaseDate(); - } - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - releaseDateSelector.addYear(releaseDate); - data.put(NEWS_DATE, releaseDate); - final NewsController controller = CdiUtil - .createCdiUtil() - .findBean(NewsController.class); - data.put(LEAD, controller.getDescription(item, selectedLocale)); - } - - /** - * Cancels streamlined editing. - * - * @param event - */ - @Override - public void submitted(final FormSectionEvent event) { - if (propertiesStep != null - && getSaveCancelSection() - .getCancelButton() - .isSelected(event.getPageState())) { - propertiesStep.cancelStreamlinedCreation(event.getPageState()); - } - } - - /** - * Form processing hook. Saves NewsItem object. - * - * @param event - */ - @Override - public void process(final FormSectionEvent event) { - - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - - final News item = (News) super.processBasicWidgets(event); - - // save only if save button was newsed - if (item != null - && getSaveCancelSection() - .getSaveButton() - .isSelected(event.getPageState())) { - - final NewsController controller = CdiUtil - .createCdiUtil() - .findBean(NewsController.class); - - final Date releaseDate = (java.util.Date) data.get(NEWS_DATE); - final String description = (String) data.get(LEAD); - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - controller.update(item, releaseDate, selectedLocale, description); - } - if (propertiesStep != null) { - propertiesStep.maybeForwardToNextStep(event.getPageState()); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewsTextBody.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewsTextBody.java deleted file mode 100644 index ca3d50771..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/authoring/news/NewsTextBody.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.arsdigita.cms.ui.authoring.news; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.AuthoringKitWizard; -import com.arsdigita.cms.ui.authoring.SelectedLanguageUtil; -import com.arsdigita.cms.ui.authoring.TextBody; -import com.arsdigita.cms.ui.workflow.WorkflowLockedComponentAccess; -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contenttypes.News; - -import java.util.Locale; - -import static com.arsdigita.cms.ui.authoring.TextBody.*; - -/** - * - * @author Jens Pelzetter - */ -public class NewsTextBody extends TextBody { - - private final ItemSelectionModel itemSelectionModel; - private final StringParameter selectedLanguageParam; - - public NewsTextBody(final ItemSelectionModel itemSelectionModel, - final AuthoringKitWizard authoringKitWizard, - final StringParameter selectedLanguageParam) { - - super(itemSelectionModel, selectedLanguageParam); - - this.itemSelectionModel = itemSelectionModel; - this.selectedLanguageParam = selectedLanguageParam; - - // Rest the component when it is hidden - authoringKitWizard - .getList() - .addActionListener(event -> reset(event.getPageState())); - - // Set the right component access on the forms - final Component uploadComponent = getComponent(FILE_UPLOAD); - if (uploadComponent != null) { - setComponentAccess(FILE_UPLOAD, - new WorkflowLockedComponentAccess( - uploadComponent, itemSelectionModel)); - } - final Component textEntryComponent = getComponent(TEXT_ENTRY); - setComponentAccess(TEXT_ENTRY, - new WorkflowLockedComponentAccess( - textEntryComponent, itemSelectionModel)); - } - - /** - * Adds the options for the mime type select widget of - * GenericArticleForm and sets the default mime type. - * - * @param mimeSelect - */ - @Override - protected void setMimeTypeOptions(final SingleSelect mimeSelect) { - mimeSelect.addOption(new Option("text/html", "HTML Text")); - mimeSelect.setOptionSelected("text/html"); - } - - protected News getSelectedNews(final PageState state) { - - return (News) itemSelectionModel.getSelectedItem(state); - } - - @Override - protected String getTextPropertyName() { - return "text"; - } - - @Override - public String getText(final PageState state) { - - final News news = getSelectedNews(state); - - final NewsController controller = CdiUtil - .createCdiUtil() - .findBean(NewsController.class); - return controller.getText( - news, - SelectedLanguageUtil.selectedLocale(state, selectedLanguageParam) - ); - } - - @Override - protected void updateText(final PageState state, final String text) { - - final News news = getSelectedNews(state); - - final Locale selectedLocale = SelectedLanguageUtil - .selectedLocale(state, selectedLanguageParam); - - final NewsController controller = CdiUtil - .createCdiUtil() - .findBean(NewsController.class); - controller.updateText(news, selectedLocale, text); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/AddUseContextForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/AddUseContextForm.java deleted file mode 100755 index 13914174a..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/AddUseContextForm.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (C) 2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.bebop.parameters.GlobalizedParameterListener; -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.ui.BaseForm; -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.categorization.Category; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.l10n.LocalizedString; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.privileges.AdminPrivileges; - - -/** - * TODO Needs a description. - * - * @author Scott Seago - * @author Yannick Bülter - */ -class AddUseContextForm extends BaseForm { - - private final SingleSelectionModel m_model; - - private final Name m_useContext; - private final Name m_rootName; - private final Description m_rootDescription; - - AddUseContextForm(final SingleSelectionModel model) { - super("useContext", gz("cms.ui.category.add_use_context")); - - m_model = model; - m_useContext = new Name("useContext", 200, true); - addField(gz("cms.ui.category.use_context"), m_useContext); - m_rootName = new Name("rootName", 200, true); - addField(gz("cms.ui.name"), m_rootName); - m_rootDescription = new Description("rootName", 200, true); - addField(gz("cms.ui.description"), m_rootDescription); - - addAction(new Finish()); - addAction(new Cancel()); - - addSecurityListener(AdminPrivileges.ADMINISTER_CATEGORIES); - m_useContext.addValidationListener(new ValidationListener()); - - addProcessListener(new ProcessListener()); - } - - private class ValidationListener extends GlobalizedParameterListener { - public ValidationListener() { - super(); - setError(GlobalizationUtil.globalize("cms.ui.category.use_context_must_be_unique")); - } - - public final void validate(final ParameterEvent e) - throws FormProcessException { - - ParameterData data = e.getParameterData(); - - final String name = (String) m_useContext.getValue(e.getPageState()); - - // XXX Do a dupe check ala commented code below - //if (true) {//Category.getRootForObject(CMS.getContext().getContentSection(), - //name) != null) { - // data.addError(getError()); - //} - } - } - private class ProcessListener implements FormProcessListener { - public final void process(final FormSectionEvent e) - throws FormProcessException { - final PageState state = e.getPageState(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ConfigurationManager manager = cdiUtil.findBean(ConfigurationManager.class); - final KernelConfig config = manager.findConfiguration(KernelConfig.class); - - final String useContext = (String) m_useContext.getValue(state); - - final String rootName = (String) m_rootName.getValue(state); - final LocalizedString rootDescription = new LocalizedString(); - rootDescription.putValue(config.getDefaultLocale(), (String) m_rootDescription.getValue(state)); - - Category root = new Category(); - root.setName(rootName); - root.setDescription(rootDescription); - root.setAbstractCategory(true); - - final ContentSection section = - CMS.getContext().getContentSection(); - - /* TODO Maybe trash - Category.setRootForObject(section, root, useContext); - PermissionService.setContext(root, section); - Category defaultRoot = Category.getRootForObject(section); - if (defaultRoot != null) { - ObjectPermissionCollection coll = - PermissionService.getDirectGrantedPermissions(defaultRoot.getOID()); - while (coll.next()) { - PermissionService.grantPermission(new PermissionDescriptor(coll.getPrivilege(), - root.getOID(), - coll.getGranteeOID())); - } - - }*/ - - //TODO Uncomment when CategoryUseContextModelBuilder works <--- Maybe obsolete? - //m_model.setSelectedKey(state, useContext == null ? - // CategoryUseContextModelBuilder.DEFAULT_USE_CONTEXT : - // useContext); - } - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/BaseCategoryForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/BaseCategoryForm.java deleted file mode 100755 index a9d49e42e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/BaseCategoryForm.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.bebop.event.ParameterListener; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.RadioGroup; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.form.Widget; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.parameters.TrimmedStringParameter; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.cms.ui.BaseForm; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.web.Web; -import com.arsdigita.xml.Element; - -import org.libreccm.categorization.Category; - -import java.util.Collection; - -/** - * A form which creates a new category. Extends the edit form for convenience. - * - * - * @author Michael Pih - * @author Stanislav Freidin <sfreidin@redhat.com> - * @author Justin Ross <jross@redhat.com> - * @author Yannick Bülter - * @author Jens Pelzetter - */ -class BaseCategoryForm extends BaseForm { - - private final static String NAME = "name"; - private final static String DESCRIPTION = "description"; - private final static String URL = "url"; - private final static String IS_ABSTRACT = "isAbstract"; - private final static String IS_VISIBLE = "isVisible"; - private final static String IS_ENABLED = "isEnabled"; - - private final CategoryRequestLocal categoryRequestLocal; - private final TextField nameField; - private final TextArea descriptionArea; - private final RadioGroup isAbstractRadioGroup; - private final RadioGroup isVisibleRadioGroup; - private final RadioGroup isEnabledRadioGroup; - private Label script = new Label(new GlobalizedMessage(String - .format("", - Web.getWebappContextPath())), - false); - - /** - * Constructor. - */ - protected BaseCategoryForm(final String key, - final GlobalizedMessage heading, - final CategoryRequestLocal parent) { - - super(key, heading); - - categoryRequestLocal = parent; - - nameField = new TextField(new TrimmedStringParameter(NAME)); - addField(gz("cms.ui.name"), nameField); - - nameField.setSize(30); - nameField.setMaxLength(200); - nameField.addValidationListener(new NotNullValidationListener()); - nameField.setOnFocus(String.format( - "" - + "if (this.form.%1$s.value == '') {" - + " defaulting = true;" - + " this.form.%1$s.value = urlize(this.value);" - + "}", - URL)); - nameField.setOnFocus(String.format( - "" - + "if (defaulting) {" - + " this.form.%1$s.value = urlize(this.value)" - + "}", - URL - )); - - // is abstract? - isAbstractRadioGroup = new RadioGroup(IS_ABSTRACT); - isAbstractRadioGroup.addOption(new Option("no", new Label( - gz("cms.ui.no")))); - isAbstractRadioGroup.addOption(new Option("yes", new Label(gz( - "cms.ui.yes")))); - addField(gz("cms.ui.category.is_not_abstract"), isAbstractRadioGroup); - - // is visible - isVisibleRadioGroup = new RadioGroup(IS_VISIBLE); - isVisibleRadioGroup.addOption(new Option("no", - new Label(gz("cms.ui.no")))); - isVisibleRadioGroup.addOption(new Option("yes", new Label(gz( - "cms.ui.yes")))); - addField(gz("cms.ui.category.is_visible"), isVisibleRadioGroup); - - // is enabled? - isEnabledRadioGroup = new RadioGroup(IS_ENABLED); - isEnabledRadioGroup.addOption(new Option("no", - new Label(gz("cms.ui.no")))); - isEnabledRadioGroup.addOption(new Option("yes", new Label(gz( - "cms.ui.yes")))); - addField(gz("cms.ui.category.is_enabled"), isEnabledRadioGroup); - - descriptionArea = new TextArea(new TrimmedStringParameter(DESCRIPTION)); - addField(gz("cms.ui.description"), descriptionArea); - - descriptionArea.setWrap(TextArea.SOFT); - descriptionArea.setRows(5); - descriptionArea.setCols(40); - - addAction(new Finish()); - addAction(new Cancel()); - } - - protected CategoryRequestLocal getCategoryRequestLocal() { - return categoryRequestLocal; - } - - protected TextField getNameField() { - return nameField; - } - - protected TextArea getDescriptionArea() { - return descriptionArea; - } - - protected RadioGroup getIsAbstractRadioGroup() { - return isAbstractRadioGroup; - } - - protected RadioGroup getIsVisibleRadioGroup() { - return isVisibleRadioGroup; - } - - protected RadioGroup getIsEnabledRadioGroup() { - return isEnabledRadioGroup; - } - - - @Override - public void generateXML(PageState ps, Element parent) { - script.generateXML(ps, parent); - super.generateXML(ps, parent); - } - - private class NameUniqueListener implements ParameterListener { - - private final CategoryRequestLocal m_category; - private final Widget m_widget; - private final int m_type; - final static int NAME_FIELD = 1; - - NameUniqueListener(final CategoryRequestLocal category) { - this(category, nameField, NAME_FIELD); - } - - NameUniqueListener(final CategoryRequestLocal category, - Widget widget, int type) { - m_category = category; - m_widget = widget; - m_type = type; - } - - @Override - public final void validate(final ParameterEvent e) - throws FormProcessException { - final PageState state = e.getPageState(); - final String title = (String) m_widget.getValue(state); - - final Category parent = categoryRequestLocal.getCategory(state); - - final Collection children = parent.getSubCategories(); - - for (final Category child : children) { - String compField = child.getName(); - if (compField.equalsIgnoreCase(title) - && (m_category == null - || !m_category.getCategory(state).equals(child))) { - throw new FormProcessException(GlobalizationUtil.globalize( - "cms.ui.category.name_not_unique")); - } - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategorizedObjectsList.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategorizedObjectsList.java deleted file mode 100755 index a32e3b147..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategorizedObjectsList.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.*; -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.cms.CMS; -import com.arsdigita.util.LockableImpl; -import com.arsdigita.xml.Element; -import org.libreccm.categorization.Categorization; -import org.libreccm.categorization.Category; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.contentsection.*; -import org.librecms.contentsection.privileges.AdminPrivileges; -import org.librecms.dispatcher.ItemResolver; - -import java.util.Collection; -import java.util.Iterator; -import javax.servlet.ServletException; - -/** - * A List of all objects currently categorized under this category - * - * @author Randy Graebner (randyg@redhat.com) - * @author Yannick Bülter - */ -public class CategorizedObjectsList extends SortableCategoryList { - - //public final static String CATEGORIZED_OBJECTS = "co"; - - public CategorizedObjectsList(final CategoryRequestLocal category) { - super(category); - - setModelBuilder(new CategorizedObjectsModelBuilder()); - Label label = new Label(GlobalizationUtil.globalize("cms.ui.category.item.none")); - label.setFontWeight(Label.ITALIC); - setEmptyView(label); - } - - /** - * This actually performs the sorting - */ - public void respond(PageState ps) throws ServletException { - /* TODO Reimplement sorting - final String event = ps.getControlEventName(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository contentItemRepository = cdiUtil.findBean(ContentItemRepository.class); - final ContentItemManager contentItemManager = cdiUtil.findBean(ContentItemManager.class); - final PermissionChecker permissionChecker = cdiUtil.findBean(PermissionChecker.class); - - - if (NEXT_EVENT.equals(event) || PREV_EVENT.equals(event)) { - final long selectedID = Long.parseLong(ps.getControlEventValue()); - final Category parent = getCategory(ps); - - final ContentItem selectedItem = contentItemRepository.findById(selectedID).get(); - final Long selectedDraftId = contentItemManager.getDraftVersion(selectedItem, ContentItem.class).getObjectId(); - - if (permissionChecker.isPermitted(AdminPrivileges.ADMINISTER_CATEGORIES)) { - final Long swapId = getSwapID(parent, selectedID, event); - parent.swapSortKeys(selectedID, swapId); - final ContentItem swapItem = new ContentItem(swapId); - final BigDecimal swapDraftId = swapItem.getDraftVersion().getID(); - - final BigDecimal sortKey1 = parent.getSortKey(selectedItem); - final BigDecimal sortKey2 = parent.getSortKey(swapItem); - - parent.setSortKey(new ContentItem(selectedDraftId), sortKey1); - parent.setSortKey(new ContentItem(swapDraftId), sortKey2); - - } - } else { - super.respond(ps); - }*/ - } - - - protected long getSwapID(Category category, long selectedID, String event) { - long priorID = -1; - long swapID = -1; - boolean foundSelectedID = false; - - if (category != null && !category.getObjects().isEmpty()) { - //items.addEqualsFilter(ContentItem.VERSION, ContentItem.LIVE); TODO - //items.sort(true); - for (Categorization categorization : category.getObjects()) { - long thisID = categorization.getCategorizationId(); - if (foundSelectedID && NEXT_EVENT.equals(event)) { - swapID = thisID; - break; - } - - if (thisID == selectedID) { - foundSelectedID = true; - if (PREV_EVENT.equals(event)) { - swapID = priorID; - break; - } - } - - priorID = thisID; - } - } - return swapID; - } - - @Override - protected void generateLabelXML(PageState state, Element parent, Label label, String key, Object element) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean(PermissionChecker.class); - final ContentSectionManager contentSectionManager = cdiUtil.findBean(ContentSectionManager.class); - - ContentItem item = (ContentItem) element; - - boolean canEdit = permissionChecker.isPermitted(AdminPrivileges.ADMINISTER_CATEGORIES); - - if (canEdit) { - ContentSection section = CMS.getContext().getContentSection(); - ItemResolver resolver = contentSectionManager.getItemResolver(section); - Link link = new Link( - new Text(item.getDisplayName()), - resolver.generateItemURL( - state, - item.getObjectId(), - item.getDisplayName(), - section, - item.getVersion().name() - ) - ); - Component c = link; - c.generateXML(state, parent); - } - } - - private class CategorizedObjectsModelBuilder extends LockableImpl - implements ListModelBuilder { - - public final ListModel makeModel(final List list, - final PageState state) { - final Category category = getCategory(state); - - if (category != null && !category.getObjects().isEmpty()) { - Collection items = category.getObjects(); - //items.addEqualsFilter(ContentItem.VERSION, ContentItem.LIVE); - //items.sort(true); - return new CategorizedCollectionListModel(items); - } else { - return List.EMPTY_MODEL; - } - } - } - - /** - * A {@link ListModel} that iterates over categorized objects via an - * iterator - */ - private static class CategorizedCollectionListModel implements ListModel { - - private Iterator m_objs; - private Categorization m_object; - - CategorizedCollectionListModel(Collection coll) { - m_objs = coll.iterator(); - m_object = null; - - } - - @Override - public boolean next() { - if (m_objs.hasNext()) { - m_object = m_objs.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElement() { - return m_object; - } - - @Override - public String getKey() { - return Long.toString(m_object.getCategorizationId()); - } - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryAddForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryAddForm.java deleted file mode 100755 index 9d5f56d37..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryAddForm.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.dispatcher.AccessDeniedException; -import com.arsdigita.util.Assert; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Category; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.contentsection.privileges.AdminPrivileges; - - -/** - * TODO Needs a description. - * - * @author Justin Ross <jross@redhat.com> - * @author Yannick Bülter - * @author Jens Pelzetter - */ -final class CategoryAddForm extends BaseCategoryForm { - - private static final Logger LOGGER = LogManager.getLogger( - CategoryAddForm.class); - - private final SingleSelectionModel categorySelectionModel; - - /** - * Constructor. - */ - public CategoryAddForm(final CategoryRequestLocal parent, - final SingleSelectionModel model) { - - super("AddSubcategories", gz("cms.ui.category.add"), parent); - - categorySelectionModel = model; - - addProcessListener(new ProcessListener()); - } - - private final class ProcessListener implements FormProcessListener { - - @Override - public final void process(final FormSectionEvent event) - throws FormProcessException { - - LOGGER.debug("Adding a category"); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil - .findBean(PermissionChecker.class); - final CategoryController controller = cdiUtil - .findBean(CategoryController.class); - - final PageState state = event.getPageState(); - - final Category parent = getCategoryRequestLocal() - .getCategory(state); - final String name = (String) getNameField().getValue(state); - final String description = (String) getDescriptionArea() - .getValue(state); - // this seems anti-intuitive but the question is "can you place - // items in this category. If the user says "yes" then the - // category is not abstract - final boolean isAbstract = !"yes" - .equals(getIsAbstractRadioGroup().getValue(state)); - - Assert.exists(parent, "Category parent"); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Using parent category " + parent + " to " - + "create new category"); - } - - if (permissionChecker - .isPermitted(AdminPrivileges.ADMINISTER_CATEGORIES, parent)) { - - final Category category = controller.createCategory(parent, - name, - description, - isAbstract); - - categorySelectionModel.setSelectedKey(state, - category.getUniqueId()); - } else { - // XXX user a better exception here. - // PermissionException doesn't work for this case. - throw new AccessDeniedException(); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryAdminContainer.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryAdminContainer.java deleted file mode 100755 index befb2c564..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryAdminContainer.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; -import com.arsdigita.kernel.ui.ACSObjectSelectionModel; -import com.arsdigita.toolbox.ui.SecurityContainer; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.Party; -import org.libreccm.security.PermissionChecker; - - -/** - * Container that wraps category admin access checks around UI components. - * - * @author Michael Pih (pihman@arsdigita.com) - * @author Yannick Bülter - */ -public class CategoryAdminContainer extends SecurityContainer { - - private final ACSObjectSelectionModel m_object; - private final String m_priv; - - public CategoryAdminContainer(Component c, - ACSObjectSelectionModel object, - String priv) { - super(c); - m_object = object; - m_priv = priv; - } - - public boolean canAccess(Party party, PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean(PermissionChecker.class); - return permissionChecker.isPermitted(m_priv, m_object.getSelectedObject(state)); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryAdminController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryAdminController.java deleted file mode 100644 index 71bac9d50..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryAdminController.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.category; - -import org.libreccm.categorization.Categorization; -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.categorization.CategoryRepository; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -import org.libreccm.categorization.DomainOwnership; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.ContentItemVersion; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionRepository; - -import java.util.stream.Collectors; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class CategoryAdminController { - - @Inject - private CategoryManager categoryManager; - - @Inject - private CategoryRepository categoryRepo; - - @Inject - private ContentItemManager itemManager; - - @Inject - private GlobalizationHelper globalizationHelper; - - @Inject - private ContentSectionRepository sectionRepo; - - @Transactional(Transactional.TxType.REQUIRED) - protected List retrieveDomains(final ContentSection section) { - - Objects.requireNonNull(section); - - final ContentSection contentSection = sectionRepo - .findById(section.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContentSection with ID %d in the database. " - + "Where did that ID come from?", - section.getObjectId()))); - - return new ArrayList<>(contentSection.getDomains()); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected List generateSubCategoryList( - final Category forCategory) { - - Objects.requireNonNull(forCategory); - - final Category category = categoryRepo - .findById(forCategory.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No Category with ID %d in the datbase.", - forCategory.getObjectId()))); - - return category - .getSubCategories() - .stream() - .map(this::createCategoryListItem) - .collect(Collectors.toList()); - } - - private CategoryListItem createCategoryListItem(final Category category) { - - final CategoryListItem item = new CategoryListItem(); - item.setCategoryId(category.getObjectId()); - - final String label = globalizationHelper - .getValueFromLocalizedString(category.getTitle(), category::getName); - item.setLabel(label); - - return item; - } - - @Transactional - protected List retrieveAssignedContentItems( - final Category fromCategory) { - - final Category category = categoryRepo - .findById(fromCategory.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No Category with ID %d in the datbase.", - fromCategory.getObjectId()))); - - return category - .getObjects() - .stream() - .map(Categorization::getCategorizedObject) - .filter(obj -> obj instanceof ContentItem) - .map(obj -> (ContentItem) obj) - .filter(item -> itemManager.isLive(item)) - .filter(item -> item.getVersion() == ContentItemVersion.LIVE) - .collect(Collectors.toList()); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryAdminPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryAdminPane.java deleted file mode 100755 index aa77f47a4..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryAdminPane.java +++ /dev/null @@ -1,504 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.ActionLink; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.List; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.Tree; -import com.arsdigita.bebop.event.ChangeEvent; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.ui.BaseAdminPane; -import com.arsdigita.cms.ui.BaseDeleteForm; -import com.arsdigita.cms.ui.BaseTree; -import com.arsdigita.cms.ui.VisibilityComponent; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.ActionGroup; -import com.arsdigita.toolbox.ui.Section; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Categorization; -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.categorization.Domain; -import org.libreccm.categorization.DomainOwnership; -import org.libreccm.categorization.DomainRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.security.PermissionChecker; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.privileges.AdminPrivileges; - -/** - * A split pane for the Category Administration UI. - * - * @author Justin Ross <jross@redhat.com> - * @author Yannick Bülter - * @author Jens Pelzetter - */ -public final class CategoryAdminPane extends BaseAdminPane { - - private static final Logger LOGGER = LogManager - .getLogger(CategoryAdminPane.class); - - public static final String CONTEXT_SELECTED = "sel_context"; -// private static final String DEFAULT_USE_CONTEXT = ""; - - private final Label noCategorySystemsLabel; - - private final SingleSelectionModel selectedCategorySystem; - private final SingleSelectionModel selectedCategory; - - private final Tree categoryTree; - - private final CategoryRequestLocal parentCategoryRequestLocal; - private final CategoryRequestLocal categoryRequestLocal; - - public CategoryAdminPane() { - super(); - - selectedCategorySystem = new UseContextSelectionModel( - new StringParameter( - CONTEXT_SELECTED)); - - // Left column - // Use context section - List list = new List(new CategoryUseContextModelBuilder()); - list.setSelectionModel(selectedCategorySystem); - list.addChangeListener(new ContextSelectionListener()); - - /* Category tree section */ - categoryTree = new BaseTree(new CategoryTreeModelBuilder( - selectedCategorySystem)); - categoryTree.addChangeListener(new SelectionListener()); - selectedCategory = categoryTree.getSelectionModel(); - - super.setSelectionModel(selectedCategory); - setSelector(categoryTree); - - /* setup use context form */ - final Section contextSection = new Section(); - contextSection.setHeading(new Label(gz("cms.ui.category.use_contexts"))); - ActionGroup contextGroup = new ActionGroup(); - contextSection.setBody(contextGroup); - contextGroup.setSubject(list); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - - if (permissionChecker.isPermitted(AdminPrivileges.ADMINISTER_CATEGORIES)) { - ActionLink addContextAction = new ActionLink(new Label(gz( - "cms.ui.category.add_use_context"))); - Form addContextForm = new AddUseContextForm(selectedCategorySystem); - getBody().add(addContextForm); - getBody().connect(addContextAction, addContextForm); - contextGroup - .addAction(new VisibilityComponent(addContextAction, - AdminPrivileges.ADMINISTER_CATEGORIES)); - } - - final Section categorySection = new Section(); - categorySection.setHeading(new Label(gz("cms.ui.categories"))); - ActionGroup categoryGroup = new ActionGroup(); - categorySection.setBody(categoryGroup); - categoryGroup.setSubject(categoryTree); - - final SimpleContainer leftContainer = new SimpleContainer(); - leftContainer.add(contextSection); - leftContainer.add(categorySection); - setLeft(leftContainer); - - parentCategoryRequestLocal = new ParentRequestLocal(); - categoryRequestLocal = new SelectionRequestLocal(); - - setAdd(gz("cms.ui.category.add"), - new CategoryAddForm(categoryRequestLocal, selectedCategory)); - - setEdit(gz("cms.ui.category.edit"), - new CategoryEditForm(parentCategoryRequestLocal, - categoryRequestLocal)); - - setDelete(new DeleteLink(new Label(gz("cms.ui.category.delete"))), - new DeleteForm( - new SimpleContainer())); - - setIntroPane(new Label(gz("cms.ui.category.intro"))); - setItemPane(new CategoryItemPane(selectedCategory, - selectedCategorySystem, - categoryRequestLocal, - getAddLink(), - getEditLink(), - getDeleteLink())); - - noCategorySystemsLabel = new Label(new GlobalizedMessage( - "cms.ui.category.no_category_systems_mapped", - CmsConstants.CMS_BUNDLE)); - } - - @Override - public void register(final Page page) { - super.register(page); - - //page.addActionListener(new RootListener()); - } - - @Override - public void generateXML(final PageState state, final Element parent) { - - if (isVisible(state)) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentSection section = CMS.getContext().getContentSection(); - final CategoryAdminController controller = cdiUtil - .findBean(CategoryAdminController.class); - final java.util.List ownerships - = controller - .retrieveDomains(section); - if (ownerships == null || ownerships.isEmpty()) { - final Element panelElem = parent - .newChildElement("bebop:layoutPanel", - BEBOP_XML_NS); - final Element bodyElem = panelElem.newChildElement("bebop:body", - BEBOP_XML_NS); - noCategorySystemsLabel.generateXML(state, bodyElem); - } else { - noCategorySystemsLabel.setVisible(state, false); - super.generateXML(state, parent); - } - } - } - -// @Override -// public boolean isVisible(final PageState state) { -// -// final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); -// final ContentSection section = CMS.getContext().getContentSection(); -// final CategoryAdminController controller = cdiUtil -// .findBean(CategoryAdminController.class); -// final java.util.List ownerships -// = controller -// .retrieveDomains(section); -// -// if (ownerships == null || ownerships.isEmpty()) { -// return false; -// } else { -// return super.isVisible(state); -// } -// } - private final class DeleteLink extends ActionLink { - - private final Label m_alternativeLabel; - - DeleteLink(Label label) { - super(label); - m_alternativeLabel = new Label(gz("cms.ui.category.undeletable")); - } - - @Override - public void generateXML(final PageState state, final Element parent) { - - if (isVisible(state)) { - super.generateXML(state, parent); - } - - //Category cat = m_category.getCategory(state); - //String context = getUseContext(state); - //boolean isDefaultContext = - // (context == null) || DEFAULT_USE_CONTEXT.equals(context); - //if (cat.isRoot() || !cat.getChildren().isEmpty()) { - // m_alternativeLabel.generateXML(state, parent); - //} else { -// - //} - } - - } - - private final class DeleteForm extends BaseDeleteForm { - - DeleteForm(final SimpleContainer prompt) { - super(prompt); - prompt.add(new Label(gz("cms.ui.category.delete_prompt"))); - Label catLabel = new Label(); - catLabel.addPrintListener(pe -> { - Label label = (Label) pe.getTarget(); - Category cat = categoryRequestLocal.getCategory(pe - .getPageState()); - java.util.List descendants = cat.getSubCategories(); - java.util.List catObjects = cat.getObjects(); - - final StringBuilder builder = new StringBuilder(" "); - if (descendants.size() > 0) { - builder.append("This category has "); - builder.append(descendants.size()); - builder.append(" descendant category(ies). "); - } - if (catObjects.size() > 0) { - builder.append("It has ").append(catObjects.size()); - builder.append(" descendant object(s). "); - } - if (descendants.size() > 0 || catObjects.size() > 0) { - builder.append( - "Descendants will be orphaned, if this category is removed."); - } - label.setLabel(gz(builder.toString())); - }); - prompt.add(catLabel); - } - - @Override - public final void process(final FormSectionEvent event) - throws FormProcessException { - final PageState state = event.getPageState(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - final CategoryRepository repository = cdiUtil.findBean( - CategoryRepository.class); - final Category category = categoryRequestLocal.getCategory(state); - if (category == null) { - return; - } - -// PermissionService.assertPermission(new PermissionDescriptor(PrivilegeDescriptor.DELETE, -// category, -// Kernel.getContext(). -// getParty())); - permissionChecker.checkPermission( - AdminPrivileges.ADMINISTER_CATEGORIES, category); - -// if (category.isRoot()) { -// Category root = -// Category.getRootForObject(CMS.getContext().getContentSection(), -// getUseContext(state)); -// if (category.equals(root)) { -// Category.clearRootForObject(CMS.getContext().getContentSection(), -// getUseContext(state)); -// } -// m_contextModel.setSelectedKey(state, DEFAULT_USE_CONTEXT); -// } else { - Category parent = category.getParentCategory(); - selectedCategory.setSelectedKey(state, parent.getUniqueId()); -// } - - //category.deleteCategoryAndOrphan(); - repository.delete(category); - } - - } - - private final class SelectionRequestLocal extends CategoryRequestLocal { - - @Override - protected final Object initialValue(final PageState state) { - - final String selectedCatetoryIdStr = selectedCategory - .getSelectedKey(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryRepository repository = cdiUtil.findBean( - CategoryRepository.class); - final Category category; - if (selectedCatetoryIdStr == null) { - category = null; - } else { - category = repository - .findById(Long.parseLong(selectedCatetoryIdStr)) - .orElseThrow(() -> new UnexpectedErrorException(String - .format("No Category with ID %s in the database.", - selectedCatetoryIdStr))); - } - return category; - } - - } - - private final class ParentRequestLocal extends CategoryRequestLocal { - - @Override - protected final Object initialValue(final PageState state) { - return categoryRequestLocal.getCategory(state).getParentCategory(); - } - - } - -// private final class RootListener implements ActionListener { -// -// public final void actionPerformed(final ActionEvent e) { -// final PageState state = e.getPageState(); -// -// if (!m_model.isSelected(state)) { -// final Category root = -// Category.getRootForObject(CMS.getContext().getContentSection(), -// getUseContext(state)); -// if (root != null) { -// m_model.setSelectedKey(state, root.getID()); -// } -// } -// } -// -// } - private class UseContextSelectionModel - extends ParameterSingleSelectionModel { - - public UseContextSelectionModel(final ParameterModel parameterModel) { - super(parameterModel); - } - - @Override - public String getSelectedKey(final PageState state) { - - String val = super.getSelectedKey(state); - if (val == null - || val.isEmpty() - || val.matches("\\s*")) { - - final ContentSection section = CMS - .getContext() - .getContentSection(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryAdminController controller = cdiUtil - .findBean(CategoryAdminController.class); - final java.util.List domainOwnerships - = controller - .retrieveDomains(section); - if (domainOwnerships == null || domainOwnerships.isEmpty()) { - val = null; - } else { - final Domain categorySystem = controller - .retrieveDomains(section).get(0).getDomain(); - val = Long.toString(categorySystem.getObjectId()); - - state.setValue(getStateParameter(), val); - fireStateChanged(state); - } - } - return val; - } - - } - - public String getUseContext(final PageState state) { - - final String selected = selectedCategorySystem.getSelectedKey(state); - return selected; -// if (DEFAULT_USE_CONTEXT.equals(selected)) { -// -// -// -// return null; -// } else { -// return selected; -// } - } - - private class ContextSelectionListener implements ChangeListener { - - @Override - public final void stateChanged(final ChangeEvent event) { - - LOGGER.debug("Selection state changed; I may change " - + "the body's visible pane"); - - final PageState state = event.getPageState(); - - getBody().reset(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final Category root; - if (selectedCategorySystem.isSelected(state)) { - final String categorySystemIdStr = selectedCategorySystem - .getSelectedKey(state); - - final DomainRepository domainRepo = cdiUtil - .findBean(DomainRepository.class); - final Domain categorySystem = domainRepo - .findById(Long.parseLong(categorySystemIdStr)) - .orElseThrow(() -> new UnexpectedErrorException(String - .format("No Domain with ID %s in the database.", - categorySystemIdStr))); - root = categorySystem.getRoot(); - -// final String rootCategoryId = selectedCategorySystem -// .getSelectedKey(state); -// -// -// final Category root; -// if (DEFAULT_USE_CONTEXT.equals(rootCategoryId)) { -// final ContentSection section = CMS -// .getContext() -// .getContentSection(); -// -// final CategoryAdminController controller = CdiUtil -// .createCdiUtil() -// .findBean(CategoryAdminController.class); -// final java.util.List ownerships -// = controller -// .retrieveDomains(section); -// root = ownerships.get(0).getDomain().getRoot(); -// } else { -// root = categoryRepo -// .findById(Long.parseLong(rootCategoryId)) -// .orElseThrow(() -> new UnexpectedErrorException(String -// .format("No Category with ID %s in the database.", -// rootCategoryId))); -// } - } else { - final ContentSection section = CMS - .getContext() - .getContentSection(); - - final CategoryAdminController controller = CdiUtil - .createCdiUtil() - .findBean(CategoryAdminController.class); - final java.util.List ownerships - = controller - .retrieveDomains(section); - root = ownerships.get(0).getDomain().getRoot(); - } - - if (root != null) { - selectedCategory.setSelectedKey(state, root.getUniqueId()); - categoryTree.reset(state); - } - if (selectedCategory.isSelected(state)) { - LOGGER.debug("The selection model is selected; displaying " - + "the item pane"); - - getBody().push(state, getItemPane()); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryBaseForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryBaseForm.java deleted file mode 100755 index 9d4bf3276..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryBaseForm.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.GridPanel; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.bebop.event.ParameterListener; -import com.arsdigita.bebop.form.FormErrorDisplay; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.parameters.TrimmedStringParameter; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.cms.ui.CMSForm; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.categorization.Category; - -/** - * A form which creates a new category. Extends the edit form for - * convenience. - * - * @author Michael Pih - * @author Stanislav Freidin <sfreidin@redhat.com> - */ -class CategoryBaseForm extends CMSForm { - - final CategoryRequestLocal m_parent; - - final FormErrorDisplay m_errors; - final TextField m_title; - final TextArea m_description; - final SaveCancelSection m_saveCancelSection; - - /** - * Constructor. - */ - CategoryBaseForm(final String string, final CategoryRequestLocal parent) { - super("AddSubcategories"); - - m_parent = parent; - - // Form header - Label header = new Label(gz("cms.ui.category.add")); - add(header, GridPanel.FULL_WIDTH); - - // Form errors - m_errors = new FormErrorDisplay(this); - add(m_errors, GridPanel.FULL_WIDTH); - - // Name - m_title = new TextField(new TrimmedStringParameter("name")); - m_title.setSize(30); - m_title.setMaxLength(30); - m_title.addValidationListener(new NotNullValidationListener()); - m_title.addValidationListener(new TitleUniqueListener()); - add(new Label(gz("cms.ui.name"))); - add(m_title); - - // Description - m_description = new TextArea(new TrimmedStringParameter("description")); - m_description.setWrap(TextArea.SOFT); - m_description.setRows(5); - m_description.setCols(40); - m_description.addValidationListener(new NotNullValidationListener()); - add(new Label(gz("cms.ui.description"))); - add(m_description); - - // Save and cancel buttons - m_saveCancelSection = new SaveCancelSection(); - add(m_saveCancelSection, GridPanel.FULL_WIDTH | GridPanel.LEFT); - } - - public final boolean isCancelled(final PageState state) { - return m_saveCancelSection.getCancelButton().isSelected(state); - } - - static GlobalizedMessage gz(final String key) { - return GlobalizationUtil.globalize(key); - } - - static String lz(final String key) { - return (String) gz(key).localize(); - } - - class TitleUniqueListener implements ParameterListener { - public final void validate(final ParameterEvent e) - throws FormProcessException { - - final PageState state = e.getPageState(); - final String title = (String) m_title.getValue(state); - - final Category parent = m_parent.getCategory(state); - final java.util.List children = parent.getSubCategories(); - - for (Category child : children) { - if (child.getName().equalsIgnoreCase(title)) { - throw new FormProcessException - (GlobalizationUtil.globalize("cms.ui.category.name_not_unique")); - } - } - } - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryComponentAccess.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryComponentAccess.java deleted file mode 100755 index ee1847014..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryComponentAccess.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.Component; -import com.arsdigita.toolbox.ui.ComponentAccess; - - -public class CategoryComponentAccess extends ComponentAccess { - // XXX implement me! - // TODO This seems pretty useless... - // FIXME - - public CategoryComponentAccess(Component c, - CategoryRequestLocal category) { - super(c); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryController.java deleted file mode 100644 index cb742b7a1..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryController.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2018 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 com.arsdigita.cms.ui.category; - -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.l10n.LocalizedString; - -import java.util.Objects; -import java.util.Optional; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * Service methods for the Category Admin Tab in the Content Center. - * - * @author Jens Pelzetter - */ -@RequestScoped -class CategoryController { - - @Inject - private CategoryManager categoryManager; - - @Inject - private CategoryRepository categoryRepo; - - @Inject - private ConfigurationManager confManager; - - /** - * Creates a new category. - * - * @param parentCategory The parent category of the new category. - * @param name The name of the new category (URL fragment). - * @param description A description of the new category- - * @param isAbstract Is the new category abstract? - * @return The new category. - */ - @Transactional(Transactional.TxType.REQUIRED) - protected Category createCategory(final Category parentCategory, - final String name, - final String description, - final boolean isAbstract) { - - Objects.requireNonNull(parentCategory); - Objects.requireNonNull(name); - - if (name.isEmpty() || name.matches("\\s*")) { - throw new IllegalArgumentException( - "The name of a category can't be empty."); - } - - final KernelConfig kernelConfig = confManager - .findConfiguration(KernelConfig.class); - - final Category category = new Category(); - category.setName(name); - final LocalizedString localizedDescription = new LocalizedString(); - localizedDescription.putValue(kernelConfig.getDefaultLocale(), - description); - category.setDescription(localizedDescription); - category.setAbstractCategory(isAbstract); - - categoryRepo.save(category); - categoryManager.addSubCategoryToCategory(category, parentCategory); - - return category; - } - - @Transactional(Transactional.TxType.REQUIRED) - protected Optional getParentCategory(final Category forCategory) { - - Objects.requireNonNull(forCategory); - - final Category category = categoryRepo - .findById(forCategory.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No category with ID %d in the database.", - forCategory.getObjectId()))); - - if (category.getParentCategory() == null) { - return Optional.empty(); - } else { - return categoryRepo - .findById(category.getParentCategory().getObjectId()); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryEditForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryEditForm.java deleted file mode 100755 index ebf470e7b..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryEditForm.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.dispatcher.AccessDeniedException; -import com.arsdigita.kernel.KernelConfig; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.l10n.GlobalizationHelper; -import org.libreccm.l10n.LocalizedString; -import org.libreccm.security.PermissionChecker; -import org.librecms.contentsection.privileges.AdminPrivileges; - -/** - * TODO Needs a description. - * - * @author Justin Ross <jross@redhat.com> - * @author Yannick Bülter - */ -final class CategoryEditForm extends BaseCategoryForm { - - private static final Logger LOGGER = LogManager.getLogger( - CategoryEditForm.class); - - private static final String NO = "no"; - private static final String YES = "yes"; - - private final CategoryRequestLocal selectedCategory; - - public CategoryEditForm(final CategoryRequestLocal parent, - final CategoryRequestLocal selectedCategory) { - super("EditCategory", gz("cms.ui.category.edit"), parent); - - this.selectedCategory = selectedCategory; - - super.addInitListener(new InitListener()); - super.addProcessListener(new ProcessListener()); - } - - private class InitListener implements FormInitListener { - - @Override - public final void init(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final Category category = selectedCategory.getCategory(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final GlobalizationHelper globalizationHelper = cdiUtil - .findBean(GlobalizationHelper.class); - - getNameField().setValue(state, category.getName()); - final LocalizedString description = category.getDescription(); - getDescriptionArea() - .setValue(state, - globalizationHelper - .getValueFromLocalizedString(description)); - // this seems anti-intuitive but the question is "can you place - // items in this category. If the user says "yes" then the - // category is not abstract - if (category.isAbstractCategory()) { - getIsAbstractRadioGroup().setValue(state, NO); - } else { - getIsAbstractRadioGroup().setValue(state, YES); - } - - if (category.isVisible()) { - getIsVisibleRadioGroup().setValue(state, YES); - } else { - getIsVisibleRadioGroup().setValue(state, NO); - } - - if (category.isEnabled()) { - getIsEnabledRadioGroup().setValue(state, YES); - } else { - getIsEnabledRadioGroup().setValue(state, NO); - } - } - - } - - private class ProcessListener implements FormProcessListener { - - @Override - public final void process(final FormSectionEvent event) - throws FormProcessException { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - final ConfigurationManager manager = cdiUtil.findBean( - ConfigurationManager.class); - final KernelConfig config = manager.findConfiguration( - KernelConfig.class); - final CategoryRepository categoryRepository = cdiUtil.findBean( - CategoryRepository.class); - - final PageState state = event.getPageState(); - final Category category = selectedCategory.getCategory(state); - - if (permissionChecker.isPermitted( - AdminPrivileges.ADMINISTER_CATEGORIES, category)) { - category.setName((String) getNameField().getValue(state)); - final LocalizedString localizedDescription - = new LocalizedString(); - localizedDescription - .putValue(config.getDefaultLocale(), - (String) getDescriptionArea().getValue(state)); - category.setDescription(localizedDescription); - - final String isAbstract = (String) getIsAbstractRadioGroup() - .getValue(state); - // this seems anti-intuitive but the question is "can you place - // items in this category. If the user says "yes" then the - // category is not abstract - if (YES.equals(isAbstract)) { - category.setAbstractCategory(false); - } else if (NO.equals(isAbstract)) { - category.setAbstractCategory(true); - } - - final String isVisible = (String) getIsVisibleRadioGroup() - .getValue(state); - if (YES.equals(isVisible)) { - category.setVisible(true); - } else { - category.setVisible(false); - } - - final String isEnabled = (String) getIsEnabledRadioGroup() - .getValue(state); - if (YES.equals(isEnabled)) { - category.setEnabled(true); - } else if (NO.equals(isEnabled)) { - category.setEnabled(false); - } - - categoryRepository.save(category); - - } else { - throw new AccessDeniedException(); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryItemPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryItemPane.java deleted file mode 100755 index afcc40d62..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryItemPane.java +++ /dev/null @@ -1,759 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.ActionLink; -import com.arsdigita.bebop.BaseLink; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Link; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.parameters.StringParameter; - -import com.arsdigita.cms.ui.BaseItemPane; -import com.arsdigita.cms.ui.CMSForm; -import com.arsdigita.cms.ui.ContentItemPage; -import com.arsdigita.cms.ui.VisibilityComponent; -import com.arsdigita.cms.ui.templates.CategoryTemplates; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.toolbox.ui.ActionGroup; -import com.arsdigita.toolbox.ui.Property; -import com.arsdigita.toolbox.ui.PropertyList; -import com.arsdigita.toolbox.ui.Section; -import com.arsdigita.xml.Element; - -import java.util.Optional; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryManager; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.core.CcmObject; -import org.libreccm.l10n.GlobalizationHelper; -import org.libreccm.security.PermissionChecker; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.privileges.AdminPrivileges; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.util.List; -import java.util.Objects; - -/** - * Edits a single category. - * - * @author Justin Ross <jross@redhat.com> - * @author Sören Bernstein - * @author Yannick Bülter - */ -class CategoryItemPane extends BaseItemPane { - - private static final Logger LOGGER = LogManager.getLogger( - CategoryItemPane.class); - private final SingleSelectionModel m_model; - private final CategoryRequestLocal m_category; - private final SimpleContainer m_detailPane; - - public CategoryItemPane(final SingleSelectionModel model, - final SingleSelectionModel contextModel, - final CategoryRequestLocal category, - final ActionLink addLink, - final ActionLink editLink, - final ActionLink deleteLink) { - m_model = model; - m_category = category; - - // Details - m_detailPane = new SimpleContainer(); - add(m_detailPane); - setDefault(m_detailPane); - - final ActionLink orderItemsLink = new ActionLink(new Label( - gz("cms.ui.category.categorized_objects"))) { - - @Override - public boolean isVisible(PageState state) { - // update for live items only - if (!super.isVisible(state)) { - return false; - } - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager categoryManager = cdiUtil - .findBean(CategoryManager.class); - final Category category = m_category.getCategory(state); - return categoryManager.hasObjects(category); - } - - }; - - final Form orderItemsForm = new OrderItemsForm(m_category); - final Form orderItemsForm2 = new OrderItemsForm(m_category); - add(orderItemsForm); - add(orderItemsForm2); - - // Change index item - final ActionLink indexLink = new ActionLink(new Label(gz( - "cms.ui.category.change_index_item"))); - final Form indexForm = new IndexItemSelectionForm(m_category); - add(indexForm); - - //Move link - final ActionLink moveLink = new MoveLink(new Label(gz( - "cms.ui.category.move"))); - final Form moveForm = new CategoryMoveForm(m_category, contextModel); - add(moveForm); - - ViewItemLink viewIndexLink = new ViewItemLink(new Label(gz( - "cms.ui.category.view_index_item")), ""); - EditItemLink editIndexLink = new EditItemLink(new Label(gz( - "cms.ui.category.edit_index_item")), ""); - - // Summary - m_detailPane.add(new SummarySection(editLink, - deleteLink, - indexLink, - moveLink, - viewIndexLink, - editIndexLink, - orderItemsLink)); - - // Quasimodo: BEGIN - // Localizations - ActionLink addCategoryLocalizationLink = new ActionLink(new Label(gz( - "cms.ui.category.localization_add"))) { - - @Override - public boolean isVisible(PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ConfigurationManager manager = cdiUtil.findBean( - ConfigurationManager.class); - final KernelConfig config = manager.findConfiguration( - KernelConfig.class); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - // Only show addLanguage button, if there are langauges to add - int countSupportedLanguages = config.getSupportedLanguages() - .size(); - final Category category = m_category.getCategory(state); - if (permissionChecker.isPermitted( - AdminPrivileges.ADMINISTER_CATEGORIES, - category)) { - if (category.getTitle().getAvailableLocales().size() - < countSupportedLanguages - || category.getDescription().getAvailableLocales() - .size() < countSupportedLanguages) { - return true; - } - } - return false; - } - - }; - - CategoryLocalizationAddForm addCategoryLocalizationForm - = new CategoryLocalizationAddForm( - m_category); - m_detailPane.add(new CategoryLocalizationSection( - addCategoryLocalizationLink)); - add(addCategoryLocalizationForm); - connect(addCategoryLocalizationLink, addCategoryLocalizationForm); - connect(addCategoryLocalizationForm); - // Quasimodo: END - - // Subcategories - m_detailPane.add(new SubcategorySection(addLink)); - - // Linked categories - final ActionLink linkAddLink = new ActionLink(new Label(gz( - "cms.ui.category.linked_add"))); - - final Form linkForm = new LinkForm(m_category); - add(linkForm); - - linkAddLink.addActionListener(new NavigationListener(linkForm)); - linkForm.addSubmissionListener(new CancelListener(linkForm)); - - m_detailPane.add(new LinkedCategorySection(linkAddLink)); - - // Templates -// m_detailPane.add(new AdminVisible(new CategoryTemplateSection())); - // Permissions - //m_detailPane.add(new PermissionsSection()); - //m_detailPane.add(new Text("PermissionSection Placeholder")); - connect(indexLink, indexForm); - connect(indexForm); - - connect(moveLink, moveForm); - connect(moveForm); - - connect(orderItemsLink, orderItemsForm); - connect(orderItemsForm); - - } - - private class EditVisible extends VisibilityComponent { - - EditVisible(final Component child) { - super(child, null); - } - - @Override - public boolean hasPermission(PageState ps) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - return permissionChecker.isPermitted( - AdminPrivileges.ADMINISTER_CATEGORIES); - } - - } - - private class AdminVisible extends VisibilityComponent { - - AdminVisible(final Component child) { - super(child, null); - } - - @Override - public boolean hasPermission(PageState ps) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - return permissionChecker.isPermitted( - AdminPrivileges.ADMINISTER_CATEGORIES); - } - - } - - private class SummarySection extends Section { - - SummarySection(final ActionLink editLink, - final ActionLink deleteLink, - final ActionLink indexLink, - final ActionLink moveLink, - final ActionLink orderItemsLink) { - setHeading(new Label(gz("cms.ui.category.details"))); - - final ActionGroup group = new ActionGroup(); - setBody(group); - - group.setSubject(new Properties()); - - group.addAction(new EditVisible(editLink), ActionGroup.EDIT); - group.addAction(new EditVisible(orderItemsLink)); - group.addAction(new EditVisible(moveLink)); - group.addAction(new EditVisible(indexLink)); - group.addAction(new AdminVisible(deleteLink), ActionGroup.DELETE); - } - - /* - * This alternative constructor sets two additional links, allowing - * the user to view and edit the content index item. - */ - SummarySection(final ActionLink editLink, - final ActionLink deleteLink, - final ActionLink indexLink, - final ActionLink moveLink, - final BaseLink viewIndexItem, - final BaseLink editIndexItem, - final ActionLink orderItemsLink) { - - setHeading(new Label(gz("cms.ui.category.details"))); - - final ActionGroup group = new ActionGroup(); - setBody(group); - - group.setSubject(new Properties()); - - group.addAction(new EditVisible(editLink), ActionGroup.EDIT); - group.addAction(new EditVisible(orderItemsLink)); - group.addAction(new EditVisible(indexLink)); - group.addAction(new EditVisible(moveLink)); - group.addAction(new EditVisible(viewIndexItem)); - group.addAction(new EditVisible(editIndexItem)); - group.addAction(new AdminVisible(deleteLink), ActionGroup.DELETE); - } - - private class Properties extends PropertyList { - - @Override - protected final java.util.List properties( - final PageState state) { - - final java.util.List properties = super.properties( - state); - final Category category = m_category - .getCategory(state); - - final String itemTitle; - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final GlobalizationHelper globalizationHelper = cdiUtil - .findBean(GlobalizationHelper.class); - if (category == null) { - itemTitle = "None"; - } else { - final CategoryManager categoryManager = cdiUtil - .findBean(CategoryManager.class); - final List indexObjects = categoryManager - .getIndexObject(category); - - final Optional indexItem = indexObjects - .stream() - .filter(obj -> obj instanceof ContentItem) - .map(obj -> (ContentItem) obj) - .findFirst(); - - if (indexItem.isPresent()) { - - final ContentItem item = indexItem.get(); - itemTitle = globalizationHelper - .getValueFromLocalizedString(item.getTitle(), - item::getDisplayName); - - } else if (indexObjects.isEmpty()) { - itemTitle = "None"; - } else { - final CcmObject indexObj = indexObjects.get(0); - itemTitle = Objects.toString(indexObj); - } - } - - properties.add(new Property(gz("cms.ui.name"), - category.getName())); - properties.add(new Property( - gz("cms.ui.description"), - globalizationHelper - .getValueFromLocalizedString(category.getDescription()))); - properties.add(new Property( - gz("cms.ui.category.is_not_abstract"), - category.isAbstractCategory() - ? gz("cms.ui.no") - : gz("cms.ui.yes"))); - properties.add(new Property(gz("cms.ui.cateogry.is_visible"), - category.isVisible() - ? gz("cms.ui.yes") - : gz("cms.ui.no"))); - properties.add(new Property(gz("cms.ui.category.is_enabled"), - category.isEnabled() - ? gz("cms.ui.yes") - : gz("cms.ui.no"))); - properties.add(new Property(gz("cms.ui.category.index_item"), - itemTitle)); - - return properties; - } - - } - - } - - // Quasimodo: BEGIN - // CategoryLocalizationSection - private class CategoryLocalizationSection extends Section { - - private CategoryLocalizationTable m_catLocalizationTable; - private CategoryLocalizationEditForm m_editCategoryLocalizationForm; - private StringParameter m_catLocaleParam; - private ParameterSingleSelectionModel m_catLocale; - - CategoryLocalizationSection(ActionLink addLink) { - setHeading(new Label(gz("cms.ui.category.localizations"))); - m_catLocaleParam = new StringParameter("catLocale"); - m_catLocale = new ParameterSingleSelectionModel(m_catLocaleParam); - - final ActionGroup group = new ActionGroup(); - setBody(group); - m_catLocalizationTable = new CategoryLocalizationTable(m_category, - m_model, - m_catLocale); - group.setSubject(m_catLocalizationTable); - group.addAction(new AdminVisible(addLink), ActionGroup.ADD); - - m_editCategoryLocalizationForm = new CategoryLocalizationEditForm( - m_category, - m_catLocale); - add(m_editCategoryLocalizationForm); - connect(m_editCategoryLocalizationForm); - connect(m_catLocalizationTable, 0, m_editCategoryLocalizationForm); - } - - @Override - public void register(Page page) { - super.register(page); - page.addComponentStateParam(m_editCategoryLocalizationForm, - m_catLocaleParam); - } - - } - - private class SubcategorySection extends Section { - - SubcategorySection(final ActionLink addLink) { - setHeading(new Label(gz("cms.ui.category.subcategories"))); - - final ActionGroup group = new ActionGroup(); - setBody(group); - - group.setSubject(new SubcategoryList(m_category, m_model)); - group.addAction(new AdminVisible(addLink), ActionGroup.ADD); - } - - } - - private class LinkedCategorySection extends Section { - - LinkedCategorySection(final ActionLink linkAddLink) { - setHeading(new Label(gz("cms.ui.category.linked"))); - - final ActionGroup group = new ActionGroup(); - setBody(group); - - group.setSubject(new CategoryLinks(m_category, m_model)); - group.addAction(new EditVisible(linkAddLink), ActionGroup.EDIT); - } - - @Override - public final boolean isVisible(final PageState state) { - - final Category category = m_category.getCategory(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryController controller = cdiUtil - .findBean(CategoryController.class); - final Optional parentCategory = controller - .getParentCategory(category); - if (parentCategory.isPresent()) { - return parentCategory.get().isVisible(); - } else { - return false; - } - } - - } - - private class CategoryTemplateSection extends Section { - - CategoryTemplateSection() { - setHeading(new Label(gz("cms.ui.category.templates"))); - - final ActionGroup group = new ActionGroup(); - setBody(group); - - group.setSubject(new CategoryTemplates(m_category)); - // XXX secvis - //group.addAction(link); - } - - } - -// private class PermissionsSection extends Section { -// -// @Override -// public boolean isVisible(PageState ps) { -// final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); -// final PermissionChecker permissionChecker = cdiUtil.findBean(PermissionChecker.class); -// Category cat = m_category.getCategory(ps); -// return cat.getParentCategory() != null && permissionChecker.isPermitted(AdminPrivileges.ADMINISTER_CATEGORIES); -// } -// -// PermissionsSection() { -// setHeading(new Label(gz("cms.ui.permissions"))); -// -// final ActionGroup group = new ActionGroup(); -// setBody(group); -// -//// PrivilegeDescriptor[] privs = new PrivilegeDescriptor[]{ -//// PrivilegeDescriptor.EDIT, -//// Category.MAP_DESCRIPTOR, -//// PrivilegeDescriptor.DELETE, -//// PrivilegeDescriptor.ADMIN -//// }; -//// -//// HashMap privMap = new HashMap(); -//// privMap.put("edit", "Edit"); -//// privMap.put("delete", "Delete"); -//// privMap.put(Category.MAP_DESCRIPTOR.getName(), "Categorize Items"); -//// privMap.put("admin", "Admin"); -//// -//// final CMSPermissionsPane permPane = new CMSPermissionsPane(privs, privMap, -//// new ACSObjectSelectionModel( -//// m_model)) { -//// @Override -//// public void showAdmin(PageState ps) { -//// Assert.exists(m_model.getSelectedKey(ps)); -//// -//// super.showAdmin(ps); -//// getAdminListingPanel().setVisible(ps, false); -//// } -//// -//// }; -//// -//// final ActionLink restoreDefault = new ActionLink(new Label(gz( -//// "cms.ui.restore_default_permissions"))) { -//// @Override -//// public boolean isVisible(PageState ps) { -//// Category cat = m_category.getCategory(ps); -//// return PermissionService.getContext(cat) == null; -//// } -//// -//// }; -//// -//// final ActionLink useCustom = new ActionLink(new Label(gz( -//// "cms.ui.use_custom_permissions"))) { -//// @Override -//// public boolean isVisible(PageState ps) { -//// Category cat = m_category.getCategory(ps); -//// return PermissionService.getContext(cat) != null; -//// } -//// -//// }; -//// -//// ActionListener al = new ActionListener() { -//// public void actionPerformed(ActionEvent event) { -//// PageState state = event.getPageState(); -//// // if this is the root then we cannot revert to anything -//// // since there is not a parent -//// Category cat = m_category.getCategory(state); -//// if (!cat.canAdmin()) { -//// throw new com.arsdigita.cms.dispatcher.AccessDeniedException(); -//// } -//// DataObject context = PermissionService.getContext(cat); -//// if (context != null) { -//// PermissionService.clonePermissions(cat); -//// } else { -//// ACSObject parent; -//// try { -//// parent = cat.getDefaultParentCategory(); -//// } catch (CategoryNotFoundException ce) { -//// throw new IllegalStateException( -//// "link shouldn't exist for root categories"); -//// } -//// PermissionService.setContext(cat, parent); -//// -//// // revoke all direct permissions so category will only -//// // have inherited permissions -//// ObjectPermissionCollection perms = -//// PermissionService.getDirectGrantedPermissions( -//// cat.getOID()); -//// while (perms.next()) { -//// PermissionService.revokePermission( -//// new PermissionDescriptor( -//// perms.getPrivilege(), cat.getOID(), -//// perms.getGranteeOID())); -//// } -//// } -//// permPane.reset(state); -//// } -//// -//// } -//// -//// restoreDefault.addActionListener(al); -//// useCustom.addActionListener(al); -//// -//// SimpleContainer links = new SimpleContainer(); -//// links.add(restoreDefault); -//// links.add(useCustom); -//// -//// group.setSubject(permPane); -//// group.addAction(links); -//// -//// m_model.addChangeListener(new ChangeListener() { -//// public void stateChanged(ChangeEvent e) { -//// PageState ps = e.getPageState(); -//// } -//// -//// }); -//// -// } -// -// } - private static class OrderItemsForm extends CMSForm { - - public OrderItemsForm(CategoryRequestLocal category) { - super("orderItems", new SimpleContainer()); - Label header = new Label(gz("cms.ui.category.categorized_objects")); - header.setFontWeight(Label.BOLD); - add(header); - add(new CategorizedObjectsList(category)); - - add(new Submit("Done")); - - } - - } - - /* - * This private class creates a link to the index item for a category. - */ - private class ViewItemLink extends Link { - - ViewItemLink(Component c, String s) { - super(c, s); - } - - // Build the preview link. This uses a standard redirect link to find - // the content. The prepareURL method is called by the printwriter - @Override - protected String prepareURL(final PageState state, String location) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager manager = cdiUtil.findBean( - CategoryManager.class); - final Category category = m_category.getCategory(state); - - final ContentItem indexItem = (ContentItem) manager - .getIndexObject(category) - .stream() - .findFirst() - .get(); - - return String.format("/redirect/?oid=%s", - Long.toString(indexItem.getObjectId())); - } - - // We only show this link when an index item exists for this category - @Override - public boolean isVisible(PageState state) { - if (!super.isVisible(state)) { - return false; - } - - final Category category = m_category.getCategory(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager categoryManager = cdiUtil - .findBean(CategoryManager.class); - return categoryManager.hasIndexObject(category); - } - - }; - - private class EditItemLink extends Link { - - EditItemLink(Component c, String s) { - super(c, s); - } - - /** - * Build the preview link. This is based on code in the - * ContentSoonExpiredPane class. The prepareURL method of the parent is - * overwritten. This method is called by the printwriter - */ - @Override - protected String prepareURL(final PageState state, String location) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager manager = cdiUtil.findBean( - CategoryManager.class); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - final ContentItemManager contentItemManager = cdiUtil.findBean( - ContentItemManager.class); - - Optional indexItem = manager - .getIndexObject(m_category.getCategory(state)) - .stream() - .findFirst(); - if (!indexItem.isPresent()) { - return ""; - } - if (!permissionChecker.isPermitted("", indexItem.get())) { - return ""; - } else { - Long draftID = contentItemManager - .getDraftVersion((ContentItem) indexItem.get(), - ContentItem.class) - .getObjectId(); - return "item.jsp?item_id=" + draftID + "&set_tab=" - + ContentItemPage.AUTHORING_TAB; - } - } - - /** - * We only show this link when an index item exists for this category - * and the user is allowed to edit this item. - * - * @param state - * - * @return - */ - @Override - public boolean isVisible(PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager manager = cdiUtil.findBean( - CategoryManager.class); - final ContentItemManager contentItemManager = cdiUtil.findBean( - ContentItemManager.class); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - if (!super.isVisible(state)) { - return false; - } - Optional indexItem = manager.getIndexObject(m_category - .getCategory(state)) - .stream() - .findFirst(); - if (!indexItem.isPresent()) { - return false; - } else { - return permissionChecker.isPermitted(ItemPrivileges.EDIT, - indexItem.get()); - } - } - - }; - - private class MoveLink extends ActionLink { - - private final Label alternativeLabel; - - public MoveLink(final Label label) { - super(label); - alternativeLabel = new Label(new GlobalizedMessage( - "cms.ui.category.cantmoved", - CmsConstants.CMS_BUNDLE)); - } - - @Override - public void generateXML(final PageState state, final Element parent) { - if (!isVisible(state)) { - return; - } - - final Category category = m_category.getCategory(state); - if (category.getParentCategory() == null) { - alternativeLabel.generateXML(state, parent); - } else { - super.generateXML(state, parent); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryItemsBrowser.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryItemsBrowser.java deleted file mode 100755 index 1b11b83d7..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryItemsBrowser.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - - -import com.arsdigita.bebop.*; -import com.arsdigita.bebop.List; -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.cms.CMS; - -import com.arsdigita.cms.ui.CMSContainer; -import com.arsdigita.kernel.ui.ACSObjectSelectionModel; -import com.arsdigita.util.Assert; -import com.arsdigita.util.LockableImpl; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Categorization; -import org.libreccm.categorization.Category; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.CcmObject; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionManager; -import org.librecms.dispatcher.ItemResolver; - -import java.util.*; -import java.util.stream.Collectors; - -/** - * Displays a list of items for the given category - * - * WARNING: The code to actually list the items is currently a travesty. - * It needs to be re-written from scratch, by using custom data queries. - * @version $Id: CategoryItemsBrowser.java 2090 2010-04-17 08:04:14Z pboy $ - */ -public class CategoryItemsBrowser extends Grid { - - private static final Logger LOGGER = LogManager.getLogger( - CategoryItemsBrowser.class); - - private RequestLocal m_resolver; - - private String m_context; - - /** - * Construct a new CategoryItemsBrowser - *

- * The {@link SingleSelectionModel} which will provide the - * current category - * - * @param sel the {@link ACSObjectSelectionModel} which will maintain - * the current category - * - * @param numCols the number of columns in the browser - * - * @param context the context for the retrieved items. Should be - * "draft" or "live" - */ - public CategoryItemsBrowser(ACSObjectSelectionModel sel, int numCols, - String context) { - super(null, numCols); - super.setModelBuilder(new CategoryItemModelBuilder(sel)); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentSectionManager sectionManager = cdiUtil.findBean(ContentSectionManager.class); - m_context = context; - - setRowSelectionModel(sel); - setEmptyView(new Label(GlobalizationUtil.globalize - ("cms.ui.category.item.none"))); - - // Cache the item resolver - m_resolver = new RequestLocal() { - public Object initialValue(PageState s) { - ContentSection section = - CMS.getContext().getContentSection(); - final ItemResolver itemResolver = sectionManager.getItemResolver(section); - LOGGER.warn("Item resolver is" + itemResolver.getClass()); - return itemResolver; - } - }; - - setDefaultCellRenderer(new ItemSummaryCellRenderer()); - } - - /** - * @return the current context - */ - public String getContext() { - return m_context; - } - - public void setContext(String context) { - Assert.isUnlocked(this); - m_context = context; - } - - /** - * Iterates through all the children of the given Category - */ - private class CategoryItemModelBuilder extends LockableImpl - implements ListModelBuilder { - - private ACSObjectSelectionModel m_sel; - - public CategoryItemModelBuilder(ACSObjectSelectionModel sel) { - m_sel = sel; - } - -// public DataQuery getDataQuery(PageState s) { -// Category cat = (Category)m_sel.getSelectedObject(s); -// -// ContentSection section = CMS.getContext().getContentSection(); -// User user = (User)Kernel.getContext().getParty(); -// OID oid = null; -// if (user != null) { -// oid = user.getOID(); -// } -// // If the category is the root, list all items -// if(cat == null || (cat.equals(section.getRootCategory()))) { -// return ContentPage.getPagesInSectionQuery -// (section, getContext(), oid); -// } else { -// return ContentPage.getPagesInSectionQuery -// (section, getContext(), cat, oid); -// } -// } - - @Override - public ListModel makeModel(List l, PageState state) { - Category category = (Category) m_sel.getSelectedObject(state); - java.util.List objects = category - .getObjects() - .stream().map(Categorization::getCategorizedObject) - .filter(x -> x instanceof ContentItem) - .map(x -> (ContentItem) x) - .collect(Collectors.toList()); - return new ContentItemListModel(objects); - } - - private class ContentItemListModel implements ListModel { - - private final Iterator iterator; - - private ContentItem current; - - public ContentItemListModel(java.util.List list) { - this.iterator = list.iterator(); - } - - @Override - public boolean next() { - if (iterator.hasNext()) { - current = iterator.next(); - return true; - } - return false; - } - - @Override - public Object getElement() { - return current; - } - - @Override - public String getKey() { - return current.getItemUuid(); - } - } - } - - /** - * Renders a ContentItem in preview mode - */ - private class ItemSummaryCellRenderer - implements TableCellRenderer { - - @Override - public Component getComponent(Table table, PageState state, Object value, - boolean isSelected, Object key, - int row, int column) { - -// if(value == null) - return new Label(GlobalizationUtil.globalize(" "), false); - -// DomainObject d = DomainObjectFactory.newInstance((DataObject)value); -// -// Assert.isTrue(d instanceof ContentPage); -// ContentPage p = (ContentPage)d; -// -// CMSContainer box = new CMSContainer(); -// Component c; -// -// ContentSection section = -// CMS.getContext().getContentSection(); -// -// ItemResolver resolver = (ItemResolver)m_resolver.get(state); -// -// final String url = resolver.generateItemURL -// (state, p.getID(), p.getName(), section, -// resolver.getCurrentContext(state)); -// c = new Link(p.getTitle(), url); -// -// c.setClassAttr("title"); -// box.add(c); -// -// String summary = p.getSearchSummary(); -// if(summary != null && summary.length() > 0) { -// c = new Label(summary); -// c.setClassAttr("summary"); -// box.add(c); -// } -// -// ContentType t = p.getContentType(); -// if(t != null) { -// c = new Label(t.getName()); -// } else { -// c = new Label(GlobalizationUtil.globalize("cms.ui.category.item")); -// } -// c.setClassAttr("type"); -// box.add(c); -// -// box.setClassAttr("itemSummary"); - -// return box; - } - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryIteratorListModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryIteratorListModel.java deleted file mode 100755 index f51c86ec3..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryIteratorListModel.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.list.ListModel; -import org.libreccm.categorization.Category; - -import java.util.Iterator; - -/** - * A {@link ListModel} that iterates over categories via an iterator - * - * @author Yannick Bülter - */ -public class CategoryIteratorListModel implements ListModel { - - private Iterator m_iter; - private Category m_cat; - - /** - * Construct a new CategoryIteratorListModel - * - * @param iter an {@link Iterator} over all the categories - * which this model will supply - */ - public CategoryIteratorListModel(Iterator iter) { - m_iter = iter; - m_cat = null; - } - - public boolean next() { - if(m_iter.hasNext()) { - m_cat = (Category)m_iter.next(); - return true; - } else { - return false; - } - } - - public Object getElement() { - return m_cat.getName(); - } - - public String getKey() { - return m_cat.getUniqueId(); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLinks.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLinks.java deleted file mode 100755 index e7a550231..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLinks.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.List; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.bebop.parameters.BigDecimalParameter; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.categorization.Category; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.CmsConstants; - -import java.util.ArrayList; - -/** - * A List of all secondary parents of the current category. - * - * @author Stanislav Freidin (stas@arsdigita.com) - * @author Michael Pih (pihman@arsdigita.com) - * @author Yannick Bülter - */ -public class CategoryLinks extends List { - - public final static String SUB_CATEGORY = "sc"; - - private final CategoryRequestLocal m_parent; - private final SingleSelectionModel m_model; - - public CategoryLinks(final CategoryRequestLocal parent, - final SingleSelectionModel model) { - super(new ParameterSingleSelectionModel(new BigDecimalParameter( - SUB_CATEGORY))); - setIdAttr("category_links_list"); - - m_parent = parent; - m_model = model; - - setModelBuilder(new LinkedCategoryModelBuilder()); - - // Select the category in the main tree when the - // user selects it here - addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent e) { - final PageState state = e.getPageState(); - final String id = (String) getSelectedKey(state); - - if (id != null) { - m_model.setSelectedKey(state, id); - } - } - - }); - - final Label label = new Label(new GlobalizedMessage( - "cms.ui.category.linked_none", - CmsConstants.CMS_BUNDLE)); - label.setFontWeight(Label.ITALIC); - setEmptyView(label); - } - - // Since this part is for non default parents, but there is only one... this is not needed anymore, i guess - private class LinkedCategoryModelBuilder extends LockableImpl - implements ListModelBuilder { - - @Override - public ListModel makeModel(List list, PageState state) { - final Category category = m_parent.getCategory(state); - - if (category != null && category.getParentCategory() != null) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryController controller = cdiUtil - .findBean(CategoryController.class); - final GlobalizationHelper globalizationHelper = cdiUtil - .findBean(GlobalizationHelper.class); - final Category parent = controller - .getParentCategory(category).get(); - - java.util.List categories = new ArrayList<>(); - final CategoryListItem parentItem = new CategoryListItem(); - parentItem.setCategoryId(parent.getObjectId()); - final String label = globalizationHelper - .getValueFromLocalizedString(parent.getTitle(), - parent::getName); - parentItem.setLabel(label); - - categories.add(parentItem); - - return new CategoryListModel( - categories, - parent.getObjectId()); - -// return new CategoryListModel(categories, -// category.getParentCategory() -// == null ? null : Long -// .parseLong( -// parent -// .getUniqueId())); - } else { - return List.EMPTY_MODEL; - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryListItem.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryListItem.java deleted file mode 100644 index 23594b1b9..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryListItem.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.category; - -import java.util.Objects; - -/** - * - * @author Jens Pelzetter - */ -class CategoryListItem implements Comparable { - - private long categoryId; - private String label; - - public long getCategoryId() { - return categoryId; - } - - public void setCategoryId(final long categoryId) { - this.categoryId = categoryId; - } - - public String getLabel() { - return label; - } - - public void setLabel(final String label) { - this.label = label; - } - - @Override - public int compareTo(final CategoryListItem other) { - - final int result = label.compareTo(other.getLabel()); - if (result == 0) { - return Long.compare(categoryId, other.getCategoryId()); - } else { - return result; - } - } - - @Override - public int hashCode() { - int hash = 7; - hash = 67 * hash + (int) (categoryId ^ (categoryId >>> 32)); - hash = 67 * hash + Objects.hashCode(label); - return hash; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof CategoryListItem)) { - return false; - } - final CategoryListItem other = (CategoryListItem) obj; - if (!other.canEqual(this)) { - return false; - } - - if (categoryId != other.getCategoryId()) { - return false; - } - return Objects.equals(label, other.getLabel()); - } - - public boolean canEqual(final Object obj) { - return obj instanceof CategoryListItem; - } - - @Override - public final String toString() { - return toString(""); - } - - public String toString(final String data) { - return String.format("%s{ " - + "categoryId = %d," - + "label = \"%s\"%s" - + " }", - super.toString(), - categoryId, - label, - data); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryListModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryListModel.java deleted file mode 100755 index 8b0217b58..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryListModel.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import java.util.List; - -import com.arsdigita.bebop.list.ListModel; - -import java.util.Iterator; - -/** - * A {@link ListModel} that iterates over categories via a cursor. - * - * @author Yannick Bülter - * @author Jens Pelzetter - */ -class CategoryListModel implements ListModel { - - private final Iterator iterator; - private CategoryListItem currentCategory; - private Long excludedCategoryId; - - /** - * Constructs a new CategoryListModel - * - * @param categories - */ - public CategoryListModel(final List categories) { - this(categories, null); - } - - /** - * Constructs a new CategoryListModel - */ - public CategoryListModel(final List categories, - final Long excludedCategoryId) { - - iterator = categories.iterator(); - this.excludedCategoryId = excludedCategoryId; - } - - @Override - public boolean next() { - if (iterator.hasNext()) { - - final CategoryListItem next = iterator.next(); - if (excludedCategoryId != null - && next.getCategoryId() == excludedCategoryId) { - - return next(); - } else { - currentCategory = next; - return true; - } - } else { - return false; - } - } - - /** - * Reads the label of the {@link CategoryListItem}. - * - * - */ - @Override - public Object getElement() { - return currentCategory.getLabel(); - } - - @Override - public String getKey() { - return Long.toString(currentCategory.getCategoryId()); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationAddForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationAddForm.java deleted file mode 100755 index e3a1bc353..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationAddForm.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (C) 2008 Sören Bernstein All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.dispatcher.AccessDeniedException; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.security.PermissionChecker; -import org.librecms.CmsConstants; -import org.librecms.contentsection.privileges.AdminPrivileges; - -import java.util.Collection; -import java.util.Locale; - -/** - * Generates a form for creating new localisations for the given category. - * - * This class is part of the admin GUI of CCM and extends the standard form in - * order to present forms for managing the multi-language categories. - * - * @author Sören Bernstein - * @author Yannick Bülter - */ -public class CategoryLocalizationAddForm extends CategoryLocalizationForm { - - private static final Logger LOGGER = LogManager.getLogger( - CategoryLocalizationAddForm.class); - - /** - * Creates a new instance of CategoryLocalizationAddForm - */ - public CategoryLocalizationAddForm(final CategoryRequestLocal category) { - - super("AddCategoryLocalization", - gz("cms.ui.category.localization_add"), category); - - super.addInitListener(new InitListener()); - super.addProcessListener(new ProcessListener()); - - } - - // Deaktivate this widget, if category is root -// public boolean isVisible(PageState state) { -// return !m_category.getCategory(state).isRoot(); -// } - private class InitListener implements FormInitListener { - - public final void init(final FormSectionEvent e) - throws FormProcessException { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ConfigurationManager manager = cdiUtil.findBean( - ConfigurationManager.class); - final KernelConfig config = manager.findConfiguration( - KernelConfig.class); - - final PageState state = e.getPageState(); - final Category category = m_category.getCategory(state); - - // Select one entry - m_locale.addOption(new Option("", - new Label(new GlobalizedMessage( - "cms.ui.select_one", - CmsConstants.CMS_BUNDLE))), - state); - final Collection locales = config.getSupportedLanguages(); - if (locales != null) { - for (String locale : locales) { - m_locale.addOption(new Option(locale, - new Text(new Locale(locale) - .getDisplayLanguage())), - state); - } - } - } - - } - - private final class ProcessListener implements FormProcessListener { - - public final void process(final FormSectionEvent e) - throws FormProcessException { - LOGGER.debug("Adding a categoryLocalization to category " - + m_category); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - final CategoryRepository categoryRepository = cdiUtil.findBean( - CategoryRepository.class); - - final PageState state = e.getPageState(); - - final Category category = m_category.getCategory(state); - final Locale locale = new Locale((String) m_locale.getValue(state)); - final String title = (String) m_title.getValue(state); - final String description = (String) m_description.getValue(state); -// final String url = (String) m_url.getValue(state); -// final String isEnabled = (String) m_isEnabled.getValue(state); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Adding localization for locale " + locale - + " to category " + category); - } - - if (permissionChecker.isPermitted( - AdminPrivileges.ADMINISTER_CATEGORIES, category)) { - category.getTitle().putValue(locale, title); - category.getDescription().putValue(locale, description); -// category.setEnabled(isEnabled.equals("yes")); - categoryRepository.save(category); - - } else { - // XXX user a better exception here. - // PermissionException doesn't work for this case. - throw new AccessDeniedException(); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationEditForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationEditForm.java deleted file mode 100755 index 51525a0f0..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationEditForm.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2008 Sören Bernstein All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.dispatcher.AccessDeniedException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.contentsection.privileges.AdminPrivileges; - -import java.util.Locale; - -/** - * Generates a form for editing an existing localisation for the given category. - * - * This class is part of the admin GUI of CCM and extends the standard form - * in order to present forms for managing the multi-language categories. - * - * @author Sören Bernstein - * @author Yannick Bülter - */ -public class CategoryLocalizationEditForm extends CategoryLocalizationForm { - - private static final Logger LOGGER = LogManager.getLogger( - CategoryLocalizationAddForm.class); - - private final SingleSelectionModel m_catLocale; - /** - * Creates a new instance of CategoryLocalizationEditForm - */ - public CategoryLocalizationEditForm(final CategoryRequestLocal category, SingleSelectionModel catLocale) { - - super("EditCategoryLocalization", gz( - "cms.ui.category.localization_edit"), category); - - m_catLocale = catLocale; - - addInitListener(new InitListener()); - addProcessListener(new ProcessListener()); - - } - - /** - * please add: purpose of this class - */ - private class InitListener implements FormInitListener { - public final void init(final FormSectionEvent e) - throws FormProcessException { - - final PageState state = e.getPageState(); - final Category category = m_category.getCategory(state); - - final String categoryLocalizationLocale = (String) m_catLocale.getSelectedKey(state); - final Locale locale = new Locale(categoryLocalizationLocale); - - // Hide Locale-Widget and lock it (read-only) - m_locale.addOption(new Option(categoryLocalizationLocale, - new Text(locale.getDisplayLanguage())), state); - m_locale.setValue(state, categoryLocalizationLocale); -// m_locale.setVisible(state, false); - m_locale.lock(); - - m_title.setValue(state, category.getTitle().getValue(locale)); - m_description.setValue(state, category.getDescription().getValue(locale)); -// m_url.setValue(state, category.getName()); - -// if (category.isEnabled()) { -// m_isEnabled.setValue(state, "yes"); -// } else { -// m_isEnabled.setValue(state, "no"); -// } - } - } - - /** - * ##todo: document purpose of this - */ - private class ProcessListener implements FormProcessListener { - public final void process(final FormSectionEvent e) - throws FormProcessException { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean(PermissionChecker.class); - final CategoryRepository categoryRepository = cdiUtil.findBean(CategoryRepository.class); - - final PageState state = e.getPageState(); - final Category category = m_category.getCategory(state); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Editing localization for locale " + m_locale + - " for category " + category); - } - - if (permissionChecker.isPermitted(AdminPrivileges.ADMINISTER_CATEGORIES, category)) { - final Locale locale = new Locale((String) m_locale.getValue(state)); - category.getTitle().putValue(locale, (String) m_title.getValue(state)); - category.getDescription().putValue(locale, (String) m_description.getValue(state)); -// category.setName((String) m_url.getValue(state)); -// category.setEnabled("yes".equals(m_isEnabled.getValue(state))); - categoryRepository.save(category); - } else { - throw new AccessDeniedException(); - } - } - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationForm.java deleted file mode 100755 index 6e4d39c69..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationForm.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (C) 2008 Sören Bernstein All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.Embedded; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.bebop.event.ParameterListener; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.Hidden; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.RadioGroup; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.form.Widget; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringInRangeValidationListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.parameters.TrimmedStringParameter; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.cms.ui.BaseForm; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.web.Web; -import com.arsdigita.xml.Element; -import org.apache.logging.log4j.LogManager; -import org.libreccm.categorization.Category; - -import java.util.List; -import java.util.TooManyListenersException; - -/** - * Base class for CategoryLocalizationAddForm and CategoryLocalizationEditForm. - * - * This class is part of the admin GUI of CCM and extends the standard form in order to present - * forms for managing the multi-language categories. - * - * @author Sören Bernstein - * @author Yannick Bülter - */ -public class CategoryLocalizationForm extends BaseForm { - - private static final org.apache.logging.log4j.Logger LOGGER = LogManager.getLogger( - CategoryLocalizationForm.class); - - final CategoryRequestLocal m_category; - final SingleSelect m_locale; - final TextField m_title; - final TextArea m_description; - //final TextField m_url; -// final Hidden m_url; -// final RadioGroup m_isEnabled; -// private Embedded m_script = new Embedded(String.format( -// "", -// Web.getWebappContextPath()), -// false); - - private final static String LOCALE = "locale"; - private final static String TITLE = "title"; - private final static String DESCRIPTION = "description"; - private final static String URL = "url"; - private final static String IS_ENABLED = "isEnabled"; - - /** - * Creates a new instance of CategoryLocalizationForm. - * - * @param key - * @param heading - * @param category - */ - public CategoryLocalizationForm(final String key, - final GlobalizedMessage heading, - final CategoryRequestLocal category) { - - super(key, heading); - - m_category = category; - - // Parameter-Model for SingleSelect - ParameterModel localeParam = new StringParameter(LOCALE); - localeParam.addParameterListener(new StringInRangeValidationListener(0, 2)); - - m_locale = new SingleSelect(localeParam); - m_locale.addValidationListener(e -> { - - // the --select one-- option is not allowed - ParameterData data = e.getParameterData(); - String code = (String) data.getValue(); - if (code == null || code.length() == 0) { - data.addError( - GlobalizationUtil.globalize( - "cms.ui.category.localization_error_locale")); - } - }); - - addField(gz("cms.ui.category.localization_locale"), m_locale); - - m_title = new TextField(new TrimmedStringParameter(TITLE)); - addField(gz("cms.ui.title"), m_title); - - m_title.setSize(30); - m_title.setMaxLength(200); - m_title.addValidationListener(new NotNullValidationListener()); - m_title.setOnFocus("if (this.form." + URL + ".value == '') { " - + " defaulting = true; this.form." + URL - + ".value = urlize(this.value); }"); - m_title.setOnKeyUp("if (defaulting) { this.form." + URL + ".value = urlize(this.value) }"); - - // is enabled? -// m_isEnabled = new RadioGroup(IS_ENABLED); -// m_isEnabled.addOption(new Option("no", new Label(gz("cms.ui.no")))); -// m_isEnabled.addOption(new Option("yes", new Label(gz("cms.ui.yes")))); -// addField(gz("cms.ui.category.is_enabled"), m_isEnabled); - - m_description = new TextArea(new TrimmedStringParameter(DESCRIPTION)); - addField(gz("cms.ui.description"), m_description); - - m_description.setWrap(TextArea.SOFT); - m_description.setRows(5); - m_description.setCols(40); - - // URL - // JavaScript auto-url generation is off by default. - // It is turned on under the following circumstances - // - // * If the url is null, upon starting edit of the title - // * If the url is null, upon finishing edit of name - // - // The rationale is that, auto-url generation is useful - // if the url is currently null, but once a name has been - // created you don't want to subsequently change it since - // it breaks URLs & potentially overwrites the user's - // customizations. -// m_url = new TextField(new TrimmedStringParameter(URL)); -// m_url.setSize(30); -// m_url.setMaxLength(200); -// m_url.addValidationListener(new NotNullValidationListener()); -// m_url.setOnFocus("defaulting = false"); -// m_url.setOnBlur("if (this.value == '') " -// + "{ defaulting = true; this.value = urlize(this.form." + TITLE -// + ".value) } " + "else { this.value = urlize(this.value); }"); -// addField(gz("cms.ui.category.url"), m_url); - //jensp 2014-09-16: Localisation of URLs is not useful but causes problems when resolving - //the URLs. Also, a category is the same resource for every language variant therefore - //the URL should be the same. - //Changed field to Hidden, initalised with URL of category itself. -// m_url = new Hidden(new TrimmedStringParameter(URL)); -// try { -// m_url.addPrintListener(new PrintListener() { -// -// @Override -// public void prepare(final PrintEvent event) { -// final Hidden target = (Hidden) event.getTarget(); -// final PageState state = event.getPageState(); -// -// final Category cat = m_category.getCategory(state); -// -// target.setValue(state, cat.getName()); -// } -// -// }); -// } catch (TooManyListenersException | IllegalArgumentException ex) { -// LOGGER.fatal(ex); -// } -// addField(gz("cms.ui.category.url"), m_url); - - addAction(new Finish()); - addAction(new Cancel()); - - } - - @Override - public void generateXML(PageState ps, Element parent) { -// m_script.generateXML(ps, parent); - super.generateXML(ps, parent); - } - - /** - * Purpose: - * - * XXXToDo: Should be extended with the function: Names have to be unambiguous in the selected - * language - */ - class NameUniqueListener implements ParameterListener { - - private final CategoryRequestLocal m_category; - private final Widget m_widget; - private final int m_type; - final static int NAME_FIELD = 1; - public final static int URL_FIELD = 2; - - NameUniqueListener(final CategoryRequestLocal category) { - this(category, m_title, NAME_FIELD); - } - - NameUniqueListener(final CategoryRequestLocal category, - Widget widget, int type) { - m_category = category; - m_widget = widget; - m_type = type; - } - - /** - * Purpose: - * - * XXX provisional, has to be adapted - * - * @param e - * - * @throws com.arsdigita.bebop.FormProcessException - */ - @Override - public final void validate(final ParameterEvent e) - throws FormProcessException { - final PageState state = e.getPageState(); - final String title = (String) m_widget.getValue(state); - - final Category category = m_category.getCategory(state); - - final List children = category.getSubCategories(); - - for (Category child : children) { - String compField = child.getName(); - if (compField.equalsIgnoreCase(title) - || !m_category.getCategory(state).equals(child)) { - throw new FormProcessException(GlobalizationUtil.globalize("cms.ui.category.name_not_unique")); - } - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationTable.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationTable.java deleted file mode 100755 index 600e01150..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationTable.java +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Copyright (C) 2008 Sören Bernstein All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.event.TableActionEvent; -import com.arsdigita.bebop.event.TableActionListener; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableColumnModel; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.categorization.Category; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.libreccm.l10n.GlobalizedMessagesUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.CmsConstants; -import org.librecms.contentsection.privileges.AdminPrivileges; - -import java.util.Iterator; -import java.util.List; - -/** - * Lists all existing localizations for a selected category. - * - * This class is part of the admin GUI of CCM and extends the standard form in - * order to present forms for managing the multi-language categories. - * - * @author Sören Bernstein - * @author Yannick Bülter - */ -public class CategoryLocalizationTable extends Table implements - TableActionListener { - - private static final String TABLE_COL_LANG = "table_col_lang"; - private static final String TABLE_COL_DEL = "table_col_del"; - - private static final int COL_LOCALE = 0; - private static final int COL_TITLE = 1; - private static final int COL_DESCRIPTION = 2; - private static final int COL_EDIT = 3; - private static final int COL_DEL = 4; - - private final CategoryRequestLocal m_category; - private final SingleSelectionModel m_model; - private final SingleSelectionModel m_catLocale; - - /** - * Creates a new instance of CategoryLocalizationTable - */ - public CategoryLocalizationTable(final CategoryRequestLocal category, - final SingleSelectionModel model, - final SingleSelectionModel catLocale) { - - super(); - - m_category = category; - m_model = model; - m_catLocale = catLocale; - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final GlobalizationHelper globalizationHelper = cdiUtil - .findBean(GlobalizationHelper.class); - final GlobalizedMessagesUtil messagesUtil = globalizationHelper - .getGlobalizedMessagesUtil(CmsConstants.CMS_BUNDLE); - - // if table is empty: - setEmptyView(new Label(messagesUtil - .getGlobalizedMessage("cms.ui.category.localization_none"))); - final TableColumnModel columnModel = getColumnModel(); - - // define columns - columnModel.add(new TableColumn( - COL_LOCALE, - messagesUtil.getGlobalizedMessage( - "cms.ui.category.localization.locale"), - TABLE_COL_LANG)); - columnModel.add(new TableColumn( - COL_TITLE, - messagesUtil - .getGlobalizedMessage("cms.ui.category.localization_title"))); - columnModel.add(new TableColumn( - COL_DESCRIPTION, - messagesUtil.getGlobalizedMessage( - "cms.ui.category.localization_description"))); - columnModel.add(new TableColumn( - COL_EDIT, - messagesUtil - .getGlobalizedMessage("cms.ui.category.localization_edit"))); - columnModel.add(new TableColumn( - COL_DEL, - messagesUtil - .getGlobalizedMessage("cms.ui.category.localization_action"), - TABLE_COL_DEL)); - - super.setModelBuilder(new CategoryLocalizationTableModelBuilder()); - - columnModel.get(0).setCellRenderer(new EditCellRenderer()); - columnModel.get(4).setCellRenderer(new DeleteCellRenderer()); - - super.addTableActionListener(this); - - } - - private class CategoryLocalizationTableModelBuilder extends LockableImpl - implements TableModelBuilder { - - @Override - public TableModel makeModel(final Table table, final PageState state) { - - final Category category = m_category.getCategory(state); - - if (category == null) { - return Table.EMPTY_MODEL; - } else { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryLocalizationTableController controller = cdiUtil - .findBean(CategoryLocalizationTableController.class); - - final List rows = controller - .getCategoryLocalizations(category); - return new CategoryLocalizationTableModel(table, rows); - } - } - - } - - private class CategoryLocalizationTableModel implements TableModel { - - private final Table table; - private final Iterator iterator; - private CategoryLocalizationTableRow currentRow; - - private CategoryLocalizationTableModel( - final Table table, - final List rows) { - - this.table = table; - iterator = rows.iterator(); - } - - @Override - public int getColumnCount() { - return table.getColumnModel().size(); - } - - @Override - public boolean nextRow() { - - if (iterator.hasNext()) { - currentRow = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - - switch (columnIndex) { - case COL_LOCALE: - return currentRow.getLocale(); - case COL_TITLE: - return currentRow.getTitle(); - case COL_DESCRIPTION: - return currentRow.getDescription(); - case COL_EDIT: - return new GlobalizedMessage("cms.ui.edit", - CmsConstants.CMS_BUNDLE); - case COL_DEL: - return new GlobalizedMessage("cms.ui.delete", - CmsConstants.CMS_BUNDLE); - default: - throw new IllegalArgumentException("Illegal Column Index"); - } - } - - /** - * - * @see com.arsdigita.bebop.table.TableModel#getKeyAt(int) - */ - @Override - public Object getKeyAt(final int columnIndex) { - return currentRow.getLocale(); - } - - } - - private class EditCellRenderer extends LockableImpl implements - TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - - if (permissionChecker.isPermitted( - AdminPrivileges.ADMINISTER_CATEGORIES, m_category.getCategory( - state))) { - return new ControlLink(value.toString()); - } else { - return new Label(GlobalizationUtil.globalize(value.toString())); - } - } - - } - - private class DeleteCellRenderer extends LockableImpl implements - TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - - if (permissionChecker.isPermitted( - AdminPrivileges.ADMINISTER_CATEGORIES, m_category.getCategory( - state))) { - ControlLink link = new ControlLink(value.toString()); - link.setConfirmation(GlobalizationUtil.globalize( - "cms.ui.category.localization_confirm_delete")); - return link; - } else { - return null; - } - } - - } - - /** - * Provide implementation to TableActionListener method. Code that comes - * into picture when a link on the table is clicked. Handles edit and delete - * event. - */ - @Override - public void cellSelected(final TableActionEvent event) { - - PageState state = event.getPageState(); - -// // Get selected CategoryLocalization -// CategoryLocalization categoryLocalization = -// new CategoryLocalization(new BigDecimal(evt.getRowKey().toString())); -// -// // Get Category -// Category category = m_category.getCategory(state); -// -// // Get selected column -// TableColumn col = getColumnModel().get(evt.getColumn().intValue()); -// -// // Edit -// if (col.getHeaderKey().toString().equals(TABLE_COL_LANG)) { -// m_catLocale.setSelectedKey(state, categoryLocalization.getLocale()); -// } -// -// // Delete -// if (col.getHeaderKey().toString().equals(TABLE_COL_DEL)) { -// category.delLanguage(categoryLocalization.getLocale()); -// } - } - - /** - * provide Implementation to TableActionListener method. Does nothing in our - * case. - */ - @Override - public void headSelected(final TableActionEvent event) { - //Nothing - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationTableController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationTableController.java deleted file mode 100644 index 2700dfa43..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationTableController.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2018 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 com.arsdigita.cms.ui.category; - -import org.libreccm.categorization.Category; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import javax.enterprise.context.RequestScoped; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class CategoryLocalizationTableController { - - @Transactional(Transactional.TxType.REQUIRED) - protected List getCategoryLocalizations( - final Category forCategory) { - - final Map localizations - = new HashMap<>(); - - final Set locales = new HashSet<>(); - locales.addAll(forCategory.getTitle().getAvailableLocales()); - locales.addAll(forCategory.getDescription().getAvailableLocales()); - - return locales - .stream() - .map(locale -> generateRow(locale, forCategory)) - .sorted() - .collect(Collectors.toList()); - } - - private CategoryLocalizationTableRow generateRow(final Locale locale, - final Category category) { - - final CategoryLocalizationTableRow row - = new CategoryLocalizationTableRow( - locale); - - if (category.getTitle().hasValue(locale)) { - row.setTitle(category.getTitle().getValue(locale)); - } - - if (category.getDescription().hasValue(locale)) { - row.setDescription(category.getDescription().getValue(locale)); - } - - return row; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationTableRow.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationTableRow.java deleted file mode 100644 index 7bf6bd3fd..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryLocalizationTableRow.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2018 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 com.arsdigita.cms.ui.category; - -import java.util.Locale; -import java.util.Objects; - -/** - * - * @author Jens Pelzetter - */ -class CategoryLocalizationTableRow - implements Comparable { - - private final Locale locale; - private String title; - private String description; - - public CategoryLocalizationTableRow(final Locale locale) { - this.locale = locale; - } - - public Locale getLocale() { - return locale; - } - - public String getTitle() { - return title; - } - - public void setTitle(final String title) { - this.title = title; - } - - public String getDescription() { - return description; - } - - public void setDescription(final String description) { - this.description = description; - } - - @Override - public int compareTo(final CategoryLocalizationTableRow other) { - return locale.toString().compareTo(other.getLocale().toString()); - } - - @Override - public int hashCode() { - int hash = 7; - hash = 53 * hash + Objects.hashCode(locale); - hash = 53 * hash + Objects.hashCode(title); - hash = 53 * hash + Objects.hashCode(description); - return hash; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof CategoryLocalizationTableRow)) { - return false; - } - final CategoryLocalizationTableRow other - = (CategoryLocalizationTableRow) obj; - if (!other.canEqual(this)) { - return false; - } - if (!Objects.equals(title, other.getTitle())) { - return false; - } - if (!Objects.equals(description, other.getDescription())) { - return false; - } - return Objects.equals(locale, other.getLocale()); - } - - public boolean canEqual(final Object obj) { - return obj instanceof CategoryLocalizationTableRow; - } - - @Override - public String toString() { - return toString(""); - } - - public String toString(final String data) { - return String.format("%s{ " - + "locale = \"%s\", " - + "title = \"%s\", " - + "description = \"%s\"%s" - + " }", - super.toString(), - Objects.toString(locale), - title, - description, - data); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryMoveForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryMoveForm.java deleted file mode 100644 index 3e908f7d1..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryMoveForm.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (C) 2013 Jens Pelzetter All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.*; -import com.arsdigita.bebop.event.ChangeEvent; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.cms.ui.BaseTree; -import com.arsdigita.cms.ui.CMSForm; -import com.arsdigita.cms.ui.FormSecurityListener; -import com.arsdigita.util.Assert; -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.privileges.AdminPrivileges; - -import java.math.BigDecimal; -import java.util.Optional; - -/** - * - * @author Jens Pelzetter - */ -public class CategoryMoveForm extends CMSForm { - - public static final String CONTEXT_SELECTED = "sel_context"; - //private static final String DEFAULT_USE_CONTEXT = - // CategoryUseContextModelBuilder.DEFAULT_USE_CONTEXT; - private final CategoryRequestLocal selectedCategory; - private final SaveCancelSection saveCancelSection; - private final ChangeListener changeListener; - private final SingleSelectionModel selectionModel; - private final Tree categoryTree; - - public CategoryMoveForm(final CategoryRequestLocal selectedCategory, - final SingleSelectionModel contextModel) { - - super("MoveCategory"); - setMethod(Form.POST); - this.selectedCategory = selectedCategory; - - final Label header = new Label(GlobalizationUtil.globalize("cms.ui.category.move")); - //final Label header = new Label(); - header.addPrintListener(new PrintListener() { - @Override - public void prepare(final PrintEvent event) { - final String[] args = new String[1]; - args[0] = selectedCategory.getCategory(event.getPageState()).getName(); - - final Label target = (Label) event.getTarget(); - target.setLabel(GlobalizationUtil.globalize("cms.ui.move.category", args)); - } - - }); - - header.setFontWeight(Label.BOLD); - add(header, ColumnPanel.FULL_WIDTH); - - changeListener = new TreeChangeListener(); - selectionModel = new ParameterSingleSelectionModel(new StringParameter("selectedCategory")); - categoryTree = new BaseTree(new CategoryTreeModelBuilder(contextModel)); - categoryTree.addChangeListener(changeListener); - - add(categoryTree); - - saveCancelSection = new SaveCancelSection(); - add(saveCancelSection); - - addInitListener(new InitListener()); - addProcessListener(new ProcessListener()); - addSubmissionListener(new FormSecurityListener(AdminPrivileges.ADMINISTER_CATEGORIES)); - - } - - protected Submit getCancelButton() { - return saveCancelSection.getCancelButton(); - } - - protected Category getCategory(final PageState state) { - final Category category = selectedCategory.getCategory(state); - Assert.exists(category); - return category; - } - - private class TreeChangeListener implements ChangeListener { - - public TreeChangeListener() { - //Nothing - } - - @Override - public void stateChanged(final ChangeEvent event) { - //Nothing for now - } - - } - - private class InitListener implements FormInitListener { - - public InitListener() { - //Nothing - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - //Nothing - } - - } - - private class ProcessListener implements FormProcessListener { - - public ProcessListener() { - //Nothing - } - - @Override - public void process(final FormSectionEvent event) throws FormProcessException { - final PageState state = event.getPageState(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryRepository categoryRepository = cdiUtil.findBean(CategoryRepository.class); - final CategoryManager categoryManager = cdiUtil.findBean(CategoryManager.class); - - if (saveCancelSection.getSaveButton().isSelected(state) - && !(categoryTree.getSelectedKey(state).equals(selectedCategory.getCategory(state).getUniqueId()))) { - - final Category categoryToMove = selectedCategory.getCategory(state); - final String targetKey = (String) categoryTree.getSelectedKey(state); - - final Optional categoryOptional = categoryRepository.findById(Long.parseLong(targetKey)); - if (categoryOptional.isPresent()) { - final Category target = categoryOptional.get(); - - final Category parent = categoryToMove.getParentCategory(); - - categoryManager.removeSubCategoryFromCategory(categoryToMove, parent); - categoryRepository.save(parent); - - categoryManager.addSubCategoryToCategory(categoryToMove, target); - categoryToMove.setParentCategory(target); - - categoryRepository.save(target); - categoryRepository.save(categoryToMove); - } else { - throw new FormProcessException(GlobalizationUtil.globalize("Category with id" + targetKey + " does not exist!")); - } - } - - categoryTree.clearSelection(state); - categoryTree.clearExpansionState(state); - } - - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryRequestLocal.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryRequestLocal.java deleted file mode 100755 index 9169018d0..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryRequestLocal.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; - -import org.libreccm.categorization.Category; - -public class CategoryRequestLocal extends RequestLocal { - - public final Category getCategory(final PageState state) { - return (Category) get(state); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryTreeModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryTreeModelBuilder.java deleted file mode 100755 index 5175a25cb..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryTreeModelBuilder.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.Tree; -import com.arsdigita.bebop.tree.TreeModel; -import com.arsdigita.bebop.tree.TreeModelBuilder; -import com.arsdigita.cms.CMS; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryTreeModelLite; -import org.libreccm.categorization.Domain; -import org.libreccm.categorization.DomainOwnership; -import org.libreccm.categorization.DomainRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentSection; - -/** - * Lists category tree. - * - * @author Tri Tran (tri@arsdigita.com) - * @author Yannick Bülter - */ -class CategoryTreeModelBuilder extends LockableImpl - implements TreeModelBuilder { - -// private static String DEFAULT_USE_CONTEXT = ""; - private final SingleSelectionModel selectedCategorySystem; - - public CategoryTreeModelBuilder() { - this(null); - } - - public CategoryTreeModelBuilder( - final SingleSelectionModel selectedCategorySystem) { - - super(); - this.selectedCategorySystem = selectedCategorySystem; - } - - @Override - public final TreeModel makeModel(final Tree tree, final PageState state) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final Category root; - - if (selectedCategorySystem.getSelectedKey(state) == null) { - final ContentSection section = CMS.getContext().getContentSection(); - final CategoryAdminController controller = cdiUtil - .findBean(CategoryAdminController.class); - final java.util.List ownerships - = controller - .retrieveDomains(section); - if (ownerships == null || ownerships.isEmpty()) { - root = null; - } else { - root = ownerships.get(0).getDomain().getRoot(); - } - } else { - final DomainRepository domainRepo = cdiUtil - .findBean(DomainRepository.class); - final Domain categorySystem = domainRepo - .findById(Long.parseLong(selectedCategorySystem - .getSelectedKey(state))) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No Domain with ID %s in the database.", - selectedCategorySystem.getSelectedKey(state)))); - - root = categorySystem.getRoot(); - } - -// if (DEFAULT_USE_CONTEXT.equals(selectedCategorySystem.getSelectedKey( -// state))) { -// final ContentSection section = CMS -// .getContext() -// .getContentSection(); -// -// final CategoryAdminController controller = cdiUtil -// .findBean(CategoryAdminController.class); -// final java.util.List ownerships -// = controller -// .retrieveDomains(section); -// root = ownerships.get(0).getDomain().getRoot(); -// } else { -// final CategoryRepository categoryRepo = cdiUtil -// .findBean(CategoryRepository.class); -// root = categoryRepo -// .findById(Long.parseLong((String) m_contextModel -// .getSelectedKey(state))) -// .orElseThrow(() -> new UnexpectedErrorException(String -// .format("No Category with ID %s in the database.", -// m_contextModel.getSelectedKey(state)))); -// } - return new CategoryTreeModelLite(root); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryUseContextModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryUseContextModelBuilder.java deleted file mode 100755 index b77ac0021..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/CategoryUseContextModelBuilder.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.List; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.list.AbstractListModelBuilder; -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.cms.CMS; - -import org.libreccm.categorization.Domain; -import org.libreccm.categorization.DomainOwnership; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.contentsection.ContentSection; - -import java.util.Iterator; - -/** - * Builds a list of category use contexts for the current content section. - * - * @author Yannick Bülter - * @author Scott Seago - */ -class CategoryUseContextModelBuilder extends AbstractListModelBuilder { - - @Override - public final ListModel makeModel(final List list, final PageState state) { - return new Model(); - } - - private class Model implements ListModel { - - private final Iterator roots; - private DomainOwnership current; - - public Model() { - final ContentSection section = CMS - .getContext() - .getContentSection(); - - final CategoryAdminController controller = CdiUtil - .createCdiUtil() - .findBean(CategoryAdminController.class); - - roots = controller.retrieveDomains(section).iterator(); - current = null; - } - - @Override - public boolean next() { - if (roots.hasNext()) { - current = roots.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElement() { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final GlobalizationHelper globalizationHelper = cdiUtil - .findBean(GlobalizationHelper.class); - final Domain categorySystem = current.getDomain(); - if (categorySystem - .getTitle() - .hasValue(globalizationHelper.getNegotiatedLocale())) { - - return globalizationHelper - .getValueFromLocalizedString(current.getDomain().getTitle()); - } else { - return categorySystem.getDomainKey(); - } - - } - - @Override - public String getKey() { - - return Long.toString(current.getDomain().getObjectId()); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/ContentItemListModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/ContentItemListModel.java deleted file mode 100755 index e4646a434..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/ContentItemListModel.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.list.ListModel; -import org.librecms.contentsection.ContentItem; - -import java.util.Iterator; -import java.util.List; - -/** - * A {@link ListModel} that iterates over content items via a cursor. - * - * @author Yannick Bülter - */ -public final class ContentItemListModel implements ListModel { - - private ContentItem m_contentItem; - private long m_excludedID; - private Iterator iterator; - - - /** - * Constructs a new ContentItemListModel - */ - public ContentItemListModel(List coll) { - this(coll, -1); //Hopefully a decent replacement for null in BigDecimal. Negative ids would be weird... - } - - /** - * Constructs a new ContentItemListModel - */ - public ContentItemListModel(List coll, - long excludedID) { - - m_excludedID = excludedID; - m_contentItem = null; - iterator = coll.iterator(); - } - - public boolean next() { - if (iterator.hasNext()) { - final ContentItem contentItem = iterator.next(); - if (Long.parseLong(contentItem.getItemUuid()) == m_excludedID) { - return next(); - } else { - m_contentItem = contentItem; - return true; - } - } else { - return false; - } - } - - private ContentItem getContentItem() { - if ( m_contentItem == null ) { - throw new IllegalStateException("call next() first"); - } - return m_contentItem; - } - - /** - * Reads the name of the content item. - * - */ - public Object getElement() { - return getContentItem().getName(); - } - - public String getKey() { - return getContentItem().getItemUuid(); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/IndexItemSelectionForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/IndexItemSelectionForm.java deleted file mode 100755 index c944e0062..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/IndexItemSelectionForm.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Link; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.form.FormErrorDisplay; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.RadioGroup; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.parameters.ParameterData; -import com.arsdigita.bebop.parameters.StringParameter; - -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.ui.CMSForm; -import com.arsdigita.cms.ui.FormSecurityListener; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.categorization.ObjectNotAssignedToCategoryException; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.CcmObject; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.l10n.GlobalizationHelper; -import org.libreccm.l10n.GlobalizedMessagesUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionManager; - -import org.librecms.contentsection.privileges.AdminPrivileges; -import org.librecms.dispatcher.ItemResolver; - -import java.util.List; -import java.util.Optional; -import java.util.TooManyListenersException; - -/** - * Allows the user to select an index item to display when the front end user is - * browsing by Category - * - * @author Randy Graebner (randyg@alum.mit.edu) - * @author Yannick Bülter - * @author Jens Pelzetter - */ -public class IndexItemSelectionForm extends CMSForm { - - private static final Logger LOGGER = LogManager.getLogger( - IndexItemSelectionForm.class); - - private static final String NULL_OPTION_VALUE = ""; - private static final String NONE_OPTION_VALUE = "None"; - - private final CategoryRequestLocal selectedCategory; - private RadioGroup optionsGroup; - private final SaveCancelSection saveCancelSection; - - public IndexItemSelectionForm(final CategoryRequestLocal selectedCategory) { - - super("EditCategory"); - super.setMethod(Form.POST); - - this.selectedCategory = selectedCategory; - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final GlobalizationHelper globalizationHelper = cdiUtil - .findBean(GlobalizationHelper.class); - final GlobalizedMessagesUtil messagesUtil = globalizationHelper - .getGlobalizedMessagesUtil(CmsConstants.CMS_BUNDLE); - - // Form header - final Label header = new Label(messagesUtil - .getGlobalizedMessage("cms.ui.category.select_index_item")); - header.setFontWeight(Label.BOLD); - super.add(header, ColumnPanel.FULL_WIDTH); - - // Form errors - final FormErrorDisplay errorsDisplay = new FormErrorDisplay(this); - super.add(errorsDisplay, ColumnPanel.FULL_WIDTH); - - // Option Group - optionsGroup = new RadioGroup(new StringParameter("items")); - try { - optionsGroup.addPrintListener(this::printOptionsGroup); - } catch (TooManyListenersException ex) { - LOGGER.error("Error adding init listener to Radio Group", ex); - throw new UnexpectedErrorException(ex); - } - optionsGroup.setLayout(RadioGroup.VERTICAL); - super.add(optionsGroup); - - // Save and cancel buttons - saveCancelSection = new SaveCancelSection(); - super.add(saveCancelSection, ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - - super.addSubmissionListener(new FormSecurityListener( - AdminPrivileges.ADMINISTER_CATEGORIES)); - - // Process listener - super.addProcessListener(this::process); - } - - private void printOptionsGroup(final PrintEvent event) { - - final RadioGroup group = (RadioGroup) event.getTarget(); - final PageState state = event.getPageState(); - final Category category = getCategory(event.getPageState()); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryAdminController controller = cdiUtil - .findBean(CategoryAdminController.class); - final ContentItemManager itemManager = cdiUtil - .findBean(ContentItemManager.class); - final CategoryManager categoryManager = cdiUtil - .findBean(CategoryManager.class); - final ContentSectionManager sectionManager = cdiUtil - .findBean(ContentSectionManager.class); - final GlobalizationHelper globalizationHelper = cdiUtil - .findBean(GlobalizationHelper.class); - final GlobalizedMessagesUtil messagesUtil = globalizationHelper - .getGlobalizedMessagesUtil(CmsConstants.CMS_BUNDLE); - - group.clearOptions(); - - // option for NO index Object - group.addOption( - new Option(NONE_OPTION_VALUE, - new Label(messagesUtil - .getGlobalizedMessage("cms.ui.category.non_option")))); - - // option for inheriting from the parent category - if (category.getParentCategory() != null) { - group.addOption( - new Option(NULL_OPTION_VALUE, - new Label(messagesUtil - .getGlobalizedMessage( - "cms.ui.category.inherit_parent")))); - } - - final ContentSection section = CMS.getContext() - .getContentSection(); - final ItemResolver itemResolver = sectionManager - .getItemResolver(section); - - final List assignedItems = controller - .retrieveAssignedContentItems(category); - for (final ContentItem item : assignedItems) { - - final Link link = new Link( - new Text(item.getDisplayName()), - itemResolver.generateItemURL( - state, - item.getObjectId(), - item.getDisplayName(), - section, - item.getVersion().name() - ) - ); - //add the option with the link - group.addOption(new Option(Long.toString(item.getObjectId()), link)); - } - - // get currently selected item - final Optional optionalIndexObject = categoryManager - .getIndexObject(category) - .stream() - .findFirst(); - if (optionalIndexObject.isPresent()) { - final ContentItem indexItem - = (ContentItem) optionalIndexObject - .get(); - final ContentItem liveItem = itemManager - .getLiveVersion(indexItem, ContentItem.class) - .get(); - group.setValue( - state, - Long.toString(liveItem.getObjectId())); - } else { - final String value; - if (category.getParentCategory() == null) { - value = NULL_OPTION_VALUE; - } else { - value = NONE_OPTION_VALUE; - } - group.setValue(state, value); - } - } - - private void process(final FormSectionEvent event) - throws FormProcessException { - - final FormData data = event.getFormData(); - final ParameterData param = data - .getParameter(optionsGroup.getParameterModel().getName()); - final String selectedValue = (String) param.getValue(); - - final Category category = getCategory(event.getPageState()); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager categoryManager = cdiUtil - .findBean(CategoryManager.class); - final CategoryRepository categoryRepository = cdiUtil - .findBean(CategoryRepository.class); - final ContentItemManager contentItemManager = cdiUtil - .findBean(ContentItemManager.class); - final ContentItemRepository contentItemRepository = cdiUtil - .findBean(ContentItemRepository.class); - - if (selectedValue != null) { - final Optional optionalItem = contentItemRepository - .findById(Long.parseLong(selectedValue)); - if (optionalItem.isPresent()) { - final ContentItem item = contentItemManager - .getLiveVersion(optionalItem.get(), - ContentItem.class) - .get(); - try { - categoryManager.setIndexObject(category, item); - categoryRepository.save(category); - } catch (ObjectNotAssignedToCategoryException ex) { - throw new FormProcessException(ex); - } - } - } - } - - /** - * Get the cancel button. - * - * @return The cancel button - */ - protected Submit getCancelButton() { - return saveCancelSection.getCancelButton(); - } - - /** - * Fetch the selected category. - * - * @param state The page state - * - * @return The selected category - * - * @pre ( state != null ) - */ - protected Category getCategory(final PageState state) { - return selectedCategory.getCategory(state); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/LinkForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/LinkForm.java deleted file mode 100755 index 3a89d6113..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/LinkForm.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.cms.ui.CategoryForm; -import com.arsdigita.cms.ui.FormSecurityListener; -import com.arsdigita.toolbox.ui.Cancellable; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.CcmObject; -import org.libreccm.security.PermissionChecker; -import org.librecms.contentsection.privileges.AdminPrivileges; - -/** - * A form which edits secondary parents - * - * @author Michael Pih - * @author Stanislav Freidin - * @author Yannick Bülter - */ -public class LinkForm extends CategoryForm implements Cancellable { - - private static final Logger LOGGER = LogManager.getLogger( - LinkForm.class); - - private final CategoryRequestLocal m_category; - private final Submit m_cancelButton; - - public LinkForm(final CategoryRequestLocal category) { - super("LinkForm"); - - m_category = category; - - m_cancelButton = new Submit("Finish"); - add(m_cancelButton, ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - - setAssignedCaption("Linked Categories"); - - addSubmissionListener - (new FormSecurityListener(AdminPrivileges.ADMINISTER_CATEGORIES)); - } - - public final boolean isCancelled(final PageState state) { - return m_cancelButton.isSelected(state); - } - - /** - * Load all categories which are assigned to the current item. - */ - protected void initAssignedCategories(PageState state, CategoryMap m) { - final Category category = m_category.getCategory(state); - m.add(category.getParentCategory()); - /*final BigDecimal parentID = category.getDefaultParentCategory().getID(); - CategoryCollection links = category.getParents(); - - while ( links.next() ) { - Category cat = links.getCategory(); - - if ( !cat.getID().equals(parentID) ) { - m.add(cat); - } - } - links.close();*/ - } - - /** - * Assign a secondary parent. - */ - public void assignCategory(PageState state, Category category) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean(PermissionChecker.class); - final CategoryManager categoryManager = cdiUtil.findBean(CategoryManager.class); - final Category child = m_category.getCategory(state); - if (permissionChecker.isPermitted(AdminPrivileges.ADMINISTER_CATEGORIES, category)) { - categoryManager.addSubCategoryToCategory(child, category); - } - } - - /** - * Unassign a secondary parent. - */ - public void unassignCategory(PageState state, Category category) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean(PermissionChecker.class); - final CategoryManager categoryManager = cdiUtil.findBean(CategoryManager.class); - final Category child = m_category.getCategory(state); - if (permissionChecker.isPermitted(AdminPrivileges.ADMINISTER_CATEGORIES, category)) { - categoryManager.removeSubCategoryFromCategory(child, category); - } - } - - /** - * The category cannot be its own parent. Its children cannot - * be parents either. - */ - @Override - public Category getExcludedCategory(PageState state) { - return m_category.getCategory(state); - } - - /** - * This method returns the URL for the given item to make sure that - * there are not two objects in the same category with the same URL. - */ - protected final String getItemURL(final PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager categoryManager = cdiUtil.findBean(CategoryManager.class); - return categoryManager.getCategoryPath(m_category.getCategory(state)); - } - - protected final CcmObject getObject(final PageState state) { - return (Category) m_category.getCategory(state); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/SortableCategoryList.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/SortableCategoryList.java deleted file mode 100755 index ea9ca199f..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/SortableCategoryList.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.parameters.BigDecimalParameter; - -import com.arsdigita.cms.ui.SortableList; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Category; - -import javax.servlet.ServletException; - - -/** - * This list offers the option for the code to provide the developer - * with links to sort the given categories. - * - * NOTE: This UI currently does not scale well with large numbers of - * items since it just lists all of them. It would probably be nice - * to integrate a paginator as well to as to allow the user to move an - * item in large distances and to insert an item in the middle. Right - * now, when you add an item it is just placed at the end. However, - * if you want the item to appear in the middle then you must hit the - * "up" arrow n/2 times where n is the number of items in the list. - * This clearly is not a good setup. - * - * @author Randy Graebner (randyg@alum.mit.edu) - * @author Yannick Bülter - */ -abstract class SortableCategoryList extends SortableList { - - private static final Logger LOGGER = LogManager.getLogger - (SortableCategoryList.class); - - public final static String CHILDREN = "ch"; - - private final CategoryRequestLocal m_parent; - - /** - * This just makes a standard - * {@link SortableList} - */ - public SortableCategoryList(final CategoryRequestLocal parent) { - super(new ParameterSingleSelectionModel - (new BigDecimalParameter(CHILDREN)), false); - - m_parent = parent; - - setIdAttr("categorized_objects_list"); - } - - protected final Category getCategory(final PageState state) { - return m_parent.getCategory(state); - } - - /** - * This actually performs the sorting - */ - public void respond(PageState ps) throws ServletException { - String event = ps.getControlEventName(); - /* TODO Do actual sorting - if (NEXT_EVENT.equals(event) || PREV_EVENT.equals(event)) { - try { - ACSObject child = - (ACSObject)DomainObjectFactory.newInstance - (new OID(ACSObject.BASE_DATA_OBJECT_TYPE, - new BigDecimal(ps.getControlEventValue()))); - Category parent = m_parent.getCategory(ps); - - if (CMS.getContext().getSecurityManager().canAccess - (SecurityManager.CATEGORY_ADMIN)) { - if (NEXT_EVENT.equals(event)) { - parent.swapWithNext(child); - } else { - parent.swapWithPrevious(child); - } - - parent.save(); - } - } catch (DataObjectNotFoundException e) { - s_log.error("Trying to create categories with state = " + ps, e); - throw new ServletException(e); - } - } else { - super.respond(ps); - }*/ - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/SubcategoryList.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/SubcategoryList.java deleted file mode 100755 index 561ed2111..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/category/SubcategoryList.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.category; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.List; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; - -/** - * A List of all subcategories of the current category. - * - * - * @author Stanislav Freidin (stas@arsdigita.com) - * @author Michael Pih (pihman@arsdigita.com) - * @author Yannick Bülter - * @author Jens Pelzetter - */ -public class SubcategoryList extends SortableCategoryList { - - private final CategoryRequestLocal parentCategory; - private final SingleSelectionModel selectedCategoryId; - - public SubcategoryList( - final CategoryRequestLocal parentCategory, - final SingleSelectionModel selectedCategoryId) { - - super(parentCategory); - - this.parentCategory = parentCategory; - this.selectedCategoryId = selectedCategoryId; - - super.setIdAttr("subcategories_list"); - - setModelBuilder(new SubcategoryModelBuilder()); - - // Select the category in the main tree when the - // user selects it here - super.addActionListener(this::actionPerformed); - - Label label = new Label(new GlobalizedMessage( - "cms.ui.category.subcategory.none", - CmsConstants.CMS_BUNDLE)); - label.setFontWeight(Label.ITALIC); - setEmptyView(label); - } - - /** - * Select the category in the main tree when the user selects it here - * - * @param event - */ - private void actionPerformed(final ActionEvent event) { - - final PageState state = event.getPageState(); - final String categoryId = (String) getSelectedKey(state); - - if (categoryId != null) { - selectedCategoryId.setSelectedKey(state, categoryId); - } - } - - public ListModel makeMake(final List list, final PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager categoryManager = cdiUtil - .findBean(CategoryManager.class); - final Category category = parentCategory.getCategory(state); - - if (category != null - && categoryManager.hasSubCategories(category)) { - - final CategoryAdminController controller = cdiUtil.findBean( - CategoryAdminController.class); - final java.util.List children = controller - .generateSubCategoryList(category); - - return new CategoryListModel(children); - } else { - return List.EMPTY_MODEL; - } - - } - - private class SubcategoryModelBuilder extends LockableImpl - implements ListModelBuilder { - - @Override - public ListModel makeModel(final List list, final PageState state) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager categoryManager = cdiUtil - .findBean(CategoryManager.class); - final Category category = parentCategory.getCategory(state); - - if (category != null - && categoryManager.hasSubCategories(category)) { - - final CategoryAdminController controller = cdiUtil.findBean( - CategoryAdminController.class); - final java.util.List children = controller - .generateSubCategoryList(category); - - return new CategoryListModel(children); - } else { - return List.EMPTY_MODEL; - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/ContentSectionContainer.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/ContentSectionContainer.java deleted file mode 100755 index 87a56b0cd..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/ContentSectionContainer.java +++ /dev/null @@ -1,637 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.contentcenter; - - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Embedded; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Link; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.parameters.BigDecimalParameter; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableColumnModel; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.PageLocations; -import com.arsdigita.cms.ui.CMSContainer; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.categorization.Category; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionRepository; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.util.List; -import java.util.stream.Collectors; - - -/** - * Displays all the content sections in table, with links to the admin (and in - * legacy mode to legacy public pages as well). Also displays a form for each - * content section to create an object of a given type (configurable). The list - * of available types retrieved for each content section. - * - *

- * This class is a container for two other components: a form and a table. The - * form represents the drop down list of the content types available in a - * particular content section. It is an extension of the - * {@link com.arsdigita.cms.ui.authoring.NewItemForm}. The table displays each - * content section in one row, along with the specified form. The same form is - * reused in every row of the table. - * - * @author Michael Bryzek - * @version $Id: ContentSectionContainer.java 287 2005-02-22 00:29:02Z sskracic$ - */ -public class ContentSectionContainer extends CMSContainer { - - private static final String CONTENT_SECTION_CLASS = "contentSections"; - - private final ContentSectionTable m_table; - private final FormContainer m_formContainer; - private final SingleSelectionModel m_typeSel; - private final SingleSelectionModel m_sectionSel; - - /** - * Constructs a new ContentSectionContainer which containts: - * - *

    - *
  • SimpleContainer (to contain the form) - *
      - *
    • Form (for creating a new content item in each section) - *
    - *
  • Table (Displays all content sections) - *
- * - * @param typeSel passthrough to {@link NewItemForm} - * @param sectionSel passthrough to {@link NewItemForm} - */ - public ContentSectionContainer(SingleSelectionModel typeSel, - SingleSelectionModel sectionSel) { - super(); - setClassAttr(CONTENT_SECTION_CLASS); - - m_typeSel = typeSel; - m_sectionSel = sectionSel; - - m_formContainer = new FormContainer(); - add(m_formContainer); - m_table = new ContentSectionTable(); - add(m_table); - } - - /** - * - * @param p - */ - @Override - public void register(Page p) { - super.register(p); - p.setVisibleDefault(m_formContainer, false); - } - - /** - * - */ - private class FormContainer extends CMSContainer { - -// private final StaticNewItemForm m_form; - private final BigDecimalParameter m_sectionIdParam; - - /** - * Constructor - */ - private FormContainer() { - super(); - m_sectionIdParam = new BigDecimalParameter("sectionId"); -// m_form = new StaticNewItemForm(m_sectionIdParam); - -// m_form.addSubmissionListener(new FormSubmissionListener() { -// -// /** -// * Cancels the form if the user lacks the "create new items" -// * privilege. -// */ -// @Override -// public void submitted(FormSectionEvent event) -// throws FormProcessException { -// PageState state = event.getPageState(); -// StaticNewItemForm form = (StaticNewItemForm) event -// .getSource(); -// -// ContentSection section = form.getContentSection(state); -// final PermissionChecker permissionChecker = CdiUtil -// .createCdiUtil().findBean(PermissionChecker.class); -// Category folder = null; -// //ToDo -//// User user = Web.getWebContext().getUser(); -//// if (user != null) { -//// folder = Folder.getUserHomeFolder(user, section); -//// } -//// if (folder == null) { -//// folder = section.getRootFolder(); -//// } -////ToDo End -// folder = section.getRootDocumentsFolder(); -// -// if (!permissionChecker.isPermitted( -// ItemPrivileges.CREATE_NEW, folder)) { -// throw new FormProcessException( -// (GlobalizationUtil.globalize( -// "cms.ui.insufficient_privileges"))); -// } -// } -// -// }); -// -// m_form.addProcessListener(new FormProcessListener() { -// -// /** -// * Process listener: redirects to the authoring kit to create a -// * new item. -// */ -// @Override -// public void process(FormSectionEvent e) throws -// FormProcessException { -// StaticNewItemForm form = (StaticNewItemForm) e.getSource(); -// PageState state = e.getPageState(); -// -// BigDecimal typeId = form.getTypeID(state); -// if (typeId != null) { -// Long sectionId = form.getContentSectionID(state); -// m_sectionSel.setSelectedKey(state, sectionId); -// m_typeSel.setSelectedKey(state, typeId); -// } -// } -// -// }); -// -// add(m_form); - } - - @Override - public void register(Page p) { - super.register(p); - p.addComponentStateParam(this, m_sectionIdParam); - } - -// public StaticNewItemForm getNewItemForm() { -//// return m_form; -// } - - } - -// private static class StaticNewItemForm extends NewItemForm { -// -// private final Hidden m_sectionIDParamWidget; -// -// public StaticNewItemForm(BigDecimalParameter sectionParam) { -// super("StaticNewItemForm", BoxPanel.VERTICAL); -// setClassAttr("static-new-item-form"); -// m_sectionIDParamWidget = new Hidden(sectionParam); -// add(m_sectionIDParamWidget); -// setProcessInvisible(true); -// } -// -// /** -// * Sets the id of the content section in this form. This ID is used to -// * generate a list of available content types in the section. -// * -// * @param state The current page state. -// * @param id The id of the ContentSection for which this form should -// * display a list of content types -// * -// * @pre ( state != null && id != null ) -// */ -// public void setSectionId(PageState state, BigDecimal id) { -// Assert.exists(id); -// m_sectionIDParamWidget.setValue(state, id); -// } -// -// /** -// * Retrieves the content section for this form given the specified page -// * state. This method will return null if there is no content section. -// * -// * @param state The current page state. -// * -// * @return The current content section or null if the section does not -// * exist -// * -// * @pre ( state != null ) -// */ -// @Override -// public ContentSection getContentSection(PageState state) { -// Long id = getContentSectionID(state); -// Assert.exists(id); -// ContentSection section; -// section = CdiUtil.createCdiUtil().findBean( -// ContentSectionRepository.class).findById(id); -// return section; -// } -// -// /** -// * Retrieves the ID of the content section for this form given the -// * specified page state. This method will return null if no content -// * section id has been set. -// * -// * @param state The current page state. -// * -// * @return The id of the content section or null if it has not been set. -// * -// * @pre ( state != null ) -// */ -// private Long getContentSectionID(PageState state) { -// return (Long) Long.parseLong((String) m_sectionIDParamWidget -// .getValue(state)); -// } -// -// } - - /** - * A table that displays all content sections, with links to their locations - * and admin pages and a {@link NewItemForm} next to each section. - * - * @author Michael Bryzek - * @version $Revision$ $DateTime: 2004/08/17 23:15:09 $ - * - */ - private class ContentSectionTable extends Table { - - // We will use a (symboloc) headerKey to match columns. Because the - // number of columns depends on configuration for the llocation column, - // the index varies and con not be used. - private static final String COLUMN_SECTION = "Section"; - private static final String COLUMN_LOCATION = "Public Site"; - private static final String COLUMN_ACTION = "Action"; - - /** - * Constructs a new ContentSectionTable, using a default table model - * builder. - */ - private ContentSectionTable() { - super(); - - // we must use symbolic keys (instead of symbolic column index as - // usual) to identify a column because their number is dynamic - // depending on configuration of the location column! - Integer colNo = 0; - - Label emptyView = new Label(new GlobalizedMessage( - "cms.ui.contentcenter.section", CmsConstants.CMS_BUNDLE)); - emptyView.setFontWeight(Label.ITALIC); - setEmptyView(emptyView); - - setClassAttr("dataTable"); - - // add columns to the table - TableColumnModel columnModel = getColumnModel(); - - // prepare column headers - Label sectionHead = new Label(new GlobalizedMessage( - "cms.ui.contentcenter.section", CmsConstants.CMS_BUNDLE)); - sectionHead.setHint(new GlobalizedMessage( - "cms.ui.contentcenter.section_hint", CmsConstants.CMS_BUNDLE)); - Label locationHead = new Label(new GlobalizedMessage( - "cms.ui.contentcenter.location", CmsConstants.CMS_BUNDLE)); - locationHead.setHint(new GlobalizedMessage( - "cms.ui.contentcenter.location_hint", CmsConstants.CMS_BUNDLE)); - Label actionHead = new Label(new GlobalizedMessage( - "cms.ui.contentcenter.action", CmsConstants.CMS_BUNDLE)); - actionHead.setHint(new GlobalizedMessage( - "cms.ui.contentcenter.action_hint", CmsConstants.CMS_BUNDLE)); - - //TableColumn contentSectionColumn = new TableColumn(colNo, COLUMN_SECTION); - TableColumn contentSectionColumn = new TableColumn( - colNo, - sectionHead, - COLUMN_SECTION); - contentSectionColumn - .setCellRenderer(new AdminURLTableCellRenderer()); - columnModel.add(contentSectionColumn); - - TableColumn actionColumn = new TableColumn( - colNo++, - actionHead, - COLUMN_ACTION); - actionColumn.setCellRenderer(new ActionTableCellRenderer()); - columnModel.add(actionColumn); - - setModelBuilder(new ContentSectionTableModelBuilder()); - } - - /** - * An ContentSections table model builder - * - * @author Michael Bryzek - * - */ - private class ContentSectionTableModelBuilder extends LockableImpl - implements TableModelBuilder { - - @Override - public TableModel makeModel(Table table, PageState state) { - table.getRowSelectionModel().clearSelection(state); - return new ContentSectionTableModel((ContentSectionTable) table, - state); - } - - } - - /** - * An ContentSections table model - * - * @author Michael Bryzek - * - */ - private class ContentSectionTableModel implements TableModel { - - private final ContentSectionTable m_table; - private final TableColumnModel m_columnModel; - private final PageState m_state; - private final List m_contentSections; - private ContentSection m_section; - private int index = -1; - - private ContentSectionTableModel(ContentSectionTable table, - PageState state) { - m_table = table; - m_columnModel = table.getColumnModel(); - m_state = state; - - // retrieve all Content Sections - m_contentSections = getContentSectionCollection(); - } - - /** - * Returns a collection of ContentSections to display in this table. - * This implementation orders the content sections by - * lower(label). They are also already filtered for the - * sections to which the current user has no access. - * - */ - private List getContentSectionCollection() { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - final List allSections = cdiUtil.findBean( - ContentSectionRepository.class).findAll(); - return allSections - .stream() - .filter(section -> permissionChecker - .isPermitted(ItemPrivileges.VIEW_PUBLISHED, - section)) - .collect(Collectors.toList()); - } - - @Override - public int getColumnCount() { - return m_columnModel.size(); - } - - @Override - public boolean nextRow() { - index++; - if (index < m_contentSections.size()) { - m_section = m_contentSections.get(index); - return true; - } else { - return false; - } - } - - /** - * By default, we return null. For the section, location, and action - * columns, we return the current Content Section if there is one. - * - * @param columnIndex The index of the current column - */ - @Override - public Object getElementAt(int columnIndex) { - if (m_columnModel == null || m_section == null) { - return null; - } - - TableColumn tc = m_columnModel.get(columnIndex); - String columnKey = (String) tc.getHeaderKey(); - - Object result = m_section; - if (columnKey.equals(COLUMN_SECTION) - || columnKey.equals(COLUMN_LOCATION) - || columnKey.equals( - COLUMN_ACTION)) { - result = m_section; - } - return result; - } - - @Override - public Object getKeyAt(int columnIndex) { - return m_section.getObjectId(); - } - - /** - * Returns the table associated with this table model. - * - */ - protected Table getTable() { - return m_table; - } - - /** - * Returns the current page state - * - */ - protected PageState getPageState() { - return m_state; - } - - } - - /** - * Sets the hidden parameter in the form containers form to the id of - * the current section. Then returns the form for display, but only if - * the user has permission to create new items in the current section. - * - * @author Michael Bryzek - * - */ - private class ActionTableCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(Table table, PageState state, - Object value, - boolean isSelected, Object key, - int row, int column) { - ContentSection section = (ContentSection) value; - Category folder = null; - //ToDo -// User user = Web.getWebContext().getUser(); -// if (user != null) { -// folder = Folder.getUserHomeFolder(user, section); -// } -// if (folder == null) { -// folder = section.getRootFolder(); -// } - - folder = section.getRootDocumentsFolder(); - // If the user has no access, return an empty Label - -// -// SecurityManager sm = new SecurityManager(section); -// -// if (!sm.canAccess(state.getRequest(), SecurityManager.NEW_ITEM, -// folder) -// || !ContentSection.getConfig() -// .getAllowContentCreateInSectionListing()) { -// // return null; // produces NPE here but works somewhere else. -// // It's a kind of a hack. Label is supposed not to accept -// // not-gloabalized data. Usually aou will return null here -// // and xmlgenerator takes care of it. Doesn't work here. -// return new Embedded( -// "   - -   "); -// } else { -// // set the value of the sectionIdParameter in the form -// // to this section -// m_formContainer.getNewItemForm().setSectionId(state, section -// .getID()); -// return m_formContainer.getNewItemForm(); -// } - //ToDo End - return new Embedded( - "   - -   "); - - } - - } - - } - - /** - * Generates the correct URL to the public pages for a content section. - * - * @author Michael Bryzek - * - */ - public static class URLTableCellRenderer implements TableCellRenderer { - - /** - * The object passed in is the current content section. This returns a - * Link whose name and target are the url to the public pages. - * - * @return Link whose name and target are the url to the public pages of - * the current (passed in) content section or a Label if current - * use does not habe acces priviledge for the content section - */ - @Override - public Component getComponent(Table table, - PageState state, - Object value, - boolean isSelected, - Object key, - int row, - int column) { - - /* cast to ContentSection for further processing */ - ContentSection section = (ContentSection) value; - String name = section.getLabel(); - String path = section.getPrimaryUrl(); // from Application - - // If the user has no access, return a Label instead of a Link - // Kind of a hack because Label is supposed not to accept - // "un-globalized" display data. Label had been abused here to - // to display a DataValue - return new Embedded("/" + name + "/", false); - // return null; // produces NPE here - - } - - } - - /** - * Generates the correct URL to the admin pages for a content section. - * - * @author Michael Bryzek - * - */ - public static class AdminURLTableCellRenderer extends URLTableCellRenderer { - - /** - * The object passed in is the current content section - * - * @param table - * @param state - * @param row - * @param value - * @param column - * @param isSelected - * @param key - * - * @return - * - */ - @Override - public Component getComponent(Table table, PageState state, Object value, - boolean isSelected, Object key, - int row, int column) { - ContentSection section = (ContentSection) value; - - final PermissionChecker permissionChecker = CdiUtil.createCdiUtil() - .findBean(PermissionChecker.class); - - // If the user has no access, return a Label instead of a Link - if (permissionChecker.isPermitted( - ItemPrivileges.EDIT, - section.getRootDocumentsFolder())) { - - return new Link(section.getLabel(), - generateURL(section.getPrimaryUrl())); - } else { - //return new Label(section.getName(), false); - // return null; // Produces a NPE although it shouldn't and - // indeed doesn't elsewhere - // Kind of a hack because Label is supposed not to accept - // "un-globalized" display data. Label had been abused here to - // to display a DataValue - return new Embedded(section.getLabel(), false); - } - } - - /** - * Generates the admin url for the specified prefix. Always returns - * something that does not start with a forward slash. - * - * @param prefix The prefix of the URL - * - * @return - */ - protected String generateURL(String prefix) { - return prefix + PageLocations.SECTION_PAGE; - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/MainPage.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/MainPage.java deleted file mode 100755 index 70e7cae5f..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/MainPage.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.contentcenter; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.TabbedPane; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.cms.ui.CMSApplicationPage; -import com.arsdigita.cms.ui.GlobalNavigation; -import com.arsdigita.cms.ui.WorkspaceContextBar; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.ui.CcmObjectSelectionModel; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentType; - -// //////////////////////////////////////////////////////////////////////////// -// -// Developer's Note: -// Replaces the (old) Dispatcher based Code cms.ui.CMSPageWorkspacePage -// Note should be removed as soon as the migration process is competed (in- -// cluding content section pages). -// -// //////////////////////////////////////////////////////////////////////////// -/** - *

- * The Content Center main page.

- * - * The page contains the general header and footer, the breadcrumb, and the - * complete content page including the tab bar, the sections/tasks page, the - * search page, and the listener to switch between the tabs. - * - * @author Jack Chung (flattop@arsdigita.com) - * @author Michael Pih (pihman@arsdigita.com) - * @author Peter Boy (pboy@barkhof.uni-bremen.de) - */ -public class MainPage extends CMSApplicationPage implements ActionListener { - - private final static String XSL_CLASS = "CMS Admin"; - - public static final String CONTENT_TYPE = "type_id"; - public static final String CONTENT_SECTION = "section_id"; - - private final CcmObjectSelectionModel typeSelection; - private final CcmObjectSelectionModel sectionSelection; - - private final TabbedPane tabbedPane; - - private TasksPane tasksPanel; -// private ItemSearch m_search; -// private IdSearchTab m_IdSearch; - - /** - * Construct a new MainPage. - * - * Creates the complete page ready to be included in the page cache of - * ContentCenterServlet. - */ - public MainPage() { - - super(new Label(new GlobalizedMessage("cms.ui.content_center", - CmsConstants.CMS_BUNDLE)), - new SimpleContainer()); - - - /* Set the class attribute value (down in SimpleComponent). */ - super.setClassAttr("cms-admin"); - - final LongParameter typeId = new LongParameter(CONTENT_TYPE); - super.addGlobalStateParam(typeId); - typeSelection = new CcmObjectSelectionModel<>(ContentType.class, typeId); - - final LongParameter sectionId = new LongParameter(CONTENT_SECTION); - super.addGlobalStateParam(sectionId); - sectionSelection = new CcmObjectSelectionModel<>(ContentSection.class, - sectionId - ); - - super.add(new WorkspaceContextBar()); - super.add(new GlobalNavigation()); - - tasksPanel = getTasksPane(typeSelection, sectionSelection); -// m_search = getSearchPane(); -// m_IdSearch = getIdSearchPane(); - - tabbedPane = createTabbedPane(); - tabbedPane.setIdAttr("page-body"); - super.add(tabbedPane); - -// add(new DebugPanel()); - } - - /** - * Creates, and then caches, the Tasks pane. Overriding this method to - * return null will prevent this tab from appearing. - * - * @param typeModel - * @param sectionModel - * - * @return - */ - protected TasksPane getTasksPane( - final CcmObjectSelectionModel typeModel, - final CcmObjectSelectionModel sectionModel) { - - if (tasksPanel == null) { - tasksPanel = new TasksPane(typeModel, sectionModel); - } - return tasksPanel; - } - -// /** -// * Creates, and then caches, the Search pane. Overriding this method to -// * return null will prevent this tab from appearing. -// * -// */ -// protected ItemSearch getSearchPane() { -// if (m_search == null) { -// m_search = new ItemSearch(ContentItem.DRAFT); -// } -// -// return m_search; -// } -// -// protected IdSearchTab getIdSearchPane() { -// if (m_IdSearch == null) { -// m_IdSearch = new IdSearchTab("idsearch"); -// } -// -// return m_IdSearch; -// } - /** - * Created the TabbedPane to use for this page. Sets the class attribute for - * this tabbed pane. The default implementation uses a - * {@link com.arsdigita.bebop.TabbedPane} and sets the class attribute to - * "CMS Admin." This implementation also adds tasks, content sections, and - * search panes. - * - * Developers can override this method to add only the tabs they want, or to - * add additional tabs after the default CMS tabs are added. - * - * @return - */ - protected TabbedPane createTabbedPane() { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil - .findBean(PermissionChecker.class); - - final TabbedPane pane = new TabbedPane(); - pane.setClassAttr(XSL_CLASS); - Label taskLabel = new Label(new GlobalizedMessage( - "cms.ui.contentcenter.mainpage.taskssections", - CmsConstants.CMS_BUNDLE)); - Label pagesLabel = new Label(new GlobalizedMessage( - "cms.ui.contentcenter.mainpage.pages", - CmsConstants.CMS_BUNDLE)); - Label searchLabel = new Label(new GlobalizedMessage( - "cms.ui.contentcenter.mainpage.search", CmsConstants.CMS_BUNDLE)); - Label IdsearchLabel = new Label("ID Search"); - - addToPane(pane, - taskLabel, - getTasksPane(typeSelection, sectionSelection)); - -// if (permissionChecker.isPermitted(PagesPrivileges.ADMINISTER_PAGES)) { - addToPane(pane, - pagesLabel, - new PagesPane()); -// } -// addToPane(tabbedPane, -// new Label(new GlobalizedMessage( -// "cms.ui.contentcenter.mainpage.search", -// CmsConstants.CMS_BUNDLE)), -// getSearchPane()); -// addToPane(tabbedPane, -// IdsearchLabel, -// getIdSearchPane()); - - pane.addActionListener(this); - return pane; - } - -// /** -// * Adds the specified component, with the specified tab name, to the -// * tabbed pane only if it is not null. -// * -// * @param pane The pane to which to add the tab -// * @param tabName The name of the tab if it's added -// * @param comp The component to add to the pane -// * @deprecated refactor to use addToPane(Label, Component) instead to -// * enable localized tab strips. -// */ -// protected void addToPane(TabbedPane pane, String tabName, Component comp) { -// if (comp != null) { -// pane.addTab(tabName, comp); -// } -// } - /** - * Adds the specified component, with the specified Label as tab name, to - * the tabbed pane only if it is not null. - * - * @param pane The pane to which to add the tab - * @param tabName The name of the tab if it's added - * @param component The component to add to the pane - */ - protected void addToPane(final TabbedPane pane, - final Label tabName, - final Component component) { - if (component != null) { - pane.addTab(tabName, component); - } - } - - /** - * When a new tab is selected, reset the state of the formerly-selected - * pane. - * - * @param event The event fired by selecting a tab - */ - @Override - public void actionPerformed(final ActionEvent event) { - - final PageState state = event.getPageState(); - final Component pane = tabbedPane.getCurrentPane(state); - - if (pane == tasksPanel) { - tasksPanel.reset(state); - } -// else if (pane == m_search) { -// m_search.reset(state); -// } else if (pane == m_IdSearch) { -// m_IdSearch.reset(state); -// } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/PagesForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/PagesForm.java deleted file mode 100644 index e35335fef..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/PagesForm.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.contentcenter; - -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.SingleSelect; - -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.categorization.Domain; -import org.libreccm.categorization.DomainRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.sites.Site; -import org.libreccm.sites.SiteRepository; -import org.librecms.CmsConstants; -import org.librecms.pages.Pages; -import org.librecms.pages.PagesRepository; - -import java.util.List; -import java.util.TooManyListenersException; - -/** - * - * @author Jens Pelzetter - */ -class PagesForm extends Form { - - private final static String PRIMARY_URL_FIELD = "primaryUrl"; - private final static String SITE_SELECT = "site"; - private final static String CATEGORY_DOMAIN_SELECT = "categoryDomain"; - - private final PagesPane pagesPane; - private final ParameterSingleSelectionModel selectedPages; - - private final TextField primaryUrlField; - private final SingleSelect siteSelect; - private final SingleSelect categoryDomainSelect; - private final SaveCancelSection saveCancelSection; - - PagesForm(final PagesPane pagesPane, - final ParameterSingleSelectionModel selectedPages) { - - super("pagesForm"); - - this.pagesPane = pagesPane; - this.selectedPages = selectedPages; - - primaryUrlField = new TextField(PRIMARY_URL_FIELD); - primaryUrlField.setLabel(new GlobalizedMessage( - "cms.ui.pages.form.primary_url_field.label", - CmsConstants.CMS_BUNDLE)); - super.add(primaryUrlField); - - siteSelect = new SingleSelect(SITE_SELECT); - try { - siteSelect.addPrintListener(this::populateSiteSelect); - } catch (TooManyListenersException ex) { - throw new UnexpectedErrorException(ex); - } - siteSelect.setLabel(new GlobalizedMessage( - "cms.ui.pages.form.site_select.label", - CmsConstants.CMS_BUNDLE)); - super.add(siteSelect); - - categoryDomainSelect = new SingleSelect(CATEGORY_DOMAIN_SELECT); - try { - categoryDomainSelect - .addPrintListener(this::populateCategoryDomainSelect); - } catch (TooManyListenersException ex) { - throw new UnexpectedErrorException(ex); - } - categoryDomainSelect.setLabel(new GlobalizedMessage( - "cms.ui.pages.form.category_domain_select.label", - CmsConstants.CMS_BUNDLE)); - super.add(categoryDomainSelect); - - saveCancelSection = new SaveCancelSection(); - super.add(saveCancelSection); - - super.addInitListener(this::init); - super.addValidationListener(this::validate); - super.addProcessListener(this::process); - } - - private void populateSiteSelect(final PrintEvent event) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final SiteRepository siteRepository = cdiUtil - .findBean(SiteRepository.class); - - final List sites = siteRepository.findAll(); - - final SingleSelect target = (SingleSelect) event.getTarget(); - target.clearOptions(); - - for (final Site site : sites) { - final Text label; - if (site.isDefaultSite()) { - label = new Text(String.format("%s *", site.getDomainOfSite())); - } else { - label = new Text(site.getDomainOfSite()); - } - - target.addOption(new Option(Long.toString(site.getObjectId()), - label)); - } - - if (selectedPages.getSelectedKey(event.getPageState()) != null) { - target.setDisabled(); - } - } - - private void populateCategoryDomainSelect(final PrintEvent event) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final DomainRepository domainRepo = cdiUtil - .findBean(DomainRepository.class); - - final List categoryDomains = domainRepo.findAll(); - - final SingleSelect target = (SingleSelect) event.getTarget(); - target.clearOptions(); - - for (final Domain domain : categoryDomains) { - - target.addOption(new Option(Long.toString(domain.getObjectId()), - new Text(domain.getDomainKey()))); - } - - if (selectedPages.getSelectedKey(event.getPageState()) != null) { - target.setDisabled(); - } - } - - private void init(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (selectedPages.getSelectedKey(state) != null) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PagesRepository pagesRepo = cdiUtil - .findBean(PagesRepository.class); - - final Pages pages = pagesRepo - .findById(Long.parseLong(selectedPages.getSelectedKey(state))) - .orElseThrow(() -> new UnexpectedErrorException(String - .format("No Pages with ID %s in the database.", - selectedPages.getSelectedKey(state)))); - - primaryUrlField.setValue(state, pages.getPrimaryUrl()); - - siteSelect.setValue(state, - Long.toString(pages.getSite().getObjectId())); - - categoryDomainSelect - .setValue(state, - Long.toString(pages.getCategoryDomain().getObjectId())); - } - } - - private void validate(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (saveCancelSection.getSaveButton().isSelected(state)) { - - final FormData data = event.getFormData(); - - final String primaryUrl = data.getString(PRIMARY_URL_FIELD); - if (primaryUrl == null - || primaryUrl.isEmpty() - || primaryUrl.matches("\\s*")) { - - data.addError(PRIMARY_URL_FIELD, - new GlobalizedMessage( - "cms.ui.pages.form.primary_url_field.error", - CmsConstants.CMS_BUNDLE)); - } - - final String selectedSite = data.getString(SITE_SELECT); - if (selectedSite == null - || selectedSite.isEmpty()) { - - data.addError(PRIMARY_URL_FIELD, - new GlobalizedMessage( - "cms.ui.pages.form.site_select.error", - CmsConstants.CMS_BUNDLE)); - } - - final String selectedDomain = data.getString(CATEGORY_DOMAIN_SELECT); - if (selectedDomain == null - || selectedDomain.isEmpty()) { - - data.addError(PRIMARY_URL_FIELD, - new GlobalizedMessage( - "cms.ui.pages.form.category_domain_select.error", - CmsConstants.CMS_BUNDLE)); - } - } - - } - - private void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (saveCancelSection.getSaveButton().isSelected(state)) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PagesPaneController controller = cdiUtil - .findBean(PagesPaneController.class); - - final FormData data = event.getFormData(); - - final String primaryUrl; - if (data.getString(PRIMARY_URL_FIELD).startsWith("/") - && data.getString(PRIMARY_URL_FIELD).endsWith("/")) { - primaryUrl = data.getString(PRIMARY_URL_FIELD); - } else if(data.getString(PRIMARY_URL_FIELD).startsWith("/")) { - primaryUrl = String.format("%s/", - data.getString(PRIMARY_URL_FIELD)); - } else if(data.getString(PRIMARY_URL_FIELD).endsWith("/")) { - primaryUrl = String.format("/%s", - data.getString(PRIMARY_URL_FIELD)); - } else { - primaryUrl = String.format("/%s/", - data.getString(PRIMARY_URL_FIELD)); - } - final String selectedSiteId = data.getString(SITE_SELECT); - final String selectedDomainId = data.getString( - CATEGORY_DOMAIN_SELECT); - - if (selectedPages.getSelectedKey(state) == null) { - controller.createPages(primaryUrl, - Long.parseLong(selectedSiteId), - Long.parseLong(selectedDomainId)); - } else { - controller - .updatePages( - Long.parseLong(selectedPages.getSelectedKey(state)), - primaryUrl); - } - } - - pagesPane.showPagesTable(state); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/PagesPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/PagesPane.java deleted file mode 100644 index 9e95408df..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/PagesPane.java +++ /dev/null @@ -1,398 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.contentcenter; - -import com.arsdigita.bebop.ActionLink; -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Link; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.TableActionEvent; -import com.arsdigita.bebop.event.TableActionListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableColumnModel; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.ui.CMSContainer; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.security.PermissionChecker; -import org.librecms.CmsConstants; -import org.librecms.pages.Pages; -import org.librecms.pages.PagesPrivileges; -import org.librecms.pages.PagesRepository; - -import java.util.Iterator; -import java.util.List; - -/** - * - * @author Jens Pelzetter - */ -class PagesPane extends CMSContainer { - - private final ParameterSingleSelectionModel selectedPages; - - private final ActionLink addPagesLink; - private final PagesTable pagesTable; - private final PagesForm pagesForm; - - PagesPane() { - - super(); - - selectedPages = new ParameterSingleSelectionModel<>( - new StringParameter("selectedPages")); - - addPagesLink = new ActionLink(new GlobalizedMessage( - "cms.ui.contentcenter.pages.add_link", - CmsConstants.CMS_BUNDLE)); - addPagesLink.addActionListener(event -> { - showPagesForm(event.getPageState()); - }); - pagesTable = new PagesTable(); - pagesForm = new PagesForm(this, selectedPages); - - final BoxPanel panel = new BoxPanel(BoxPanel.VERTICAL); - panel.add(addPagesLink); - panel.add(pagesTable); - panel.add(pagesForm); - - super.add(panel); - } - - @Override - public void register(final Page page) { - super.register(page); - - page.addGlobalStateParam(selectedPages.getStateParameter()); - - page.setVisibleDefault(addPagesLink, true); - page.setVisibleDefault(pagesTable, true); - page.setVisibleDefault(pagesForm, false); - } - - protected void showPagesForm(final PageState state) { - - addPagesLink.setVisible(state, false); - pagesTable.setVisible(state, false); - pagesForm.setVisible(state, true); - } - - protected void showPagesTable(final PageState state) { - - addPagesLink.setVisible(state, true); - pagesTable.setVisible(state, true); - pagesForm.setVisible(state, false); - - selectedPages.clearSelection(state); - } - - private class PagesTable extends Table { - - public static final int COL_SITE = 0; - public static final int COL_PAGES_INSTANCE = 1; - public static final int COL_EDIT = 2; - public static final int COL_DELETE = 3; - - public PagesTable() { - - super(); - - final TableColumnModel columnModel = super.getColumnModel(); - - columnModel - .add(new TableColumn( - COL_SITE, - new Label(new GlobalizedMessage( - "cms.ui.contentcenter.pagestable.columns.site.header", - CmsConstants.CMS_BUNDLE)))); - columnModel - .add(new TableColumn( - COL_SITE, - new Label(new GlobalizedMessage( - "cms.ui.contentcenter.pagestable.columns.pages_instance.header", - CmsConstants.CMS_BUNDLE)))); - columnModel - .add(new TableColumn( - COL_EDIT, - new Label(new GlobalizedMessage( - "cms.ui.contentcenter.pagestable.columns.edit.header", - CmsConstants.CMS_BUNDLE)))); - columnModel - .add(new TableColumn( - COL_DELETE, - new Label(new GlobalizedMessage( - "cms.ui.contentcenter.pagestable.columns.delete.header", - CmsConstants.CMS_BUNDLE)))); - - columnModel - .get(COL_SITE) - .setCellRenderer(new TableCellRenderer() { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil - .findBean(PermissionChecker.class); - -// return new ControlLink((String) value); - final Pages pages = (Pages) value; - if (permissionChecker.isPermitted( - PagesPrivileges.ADMINISTER_PAGES)) { - return new Link(pages.getSite().getDomainOfSite(), - pages.getPrimaryUrl()); - } else { - return new Text(pages.getSite().getDomainOfSite()); - } - } - }); - - columnModel - .get(COL_PAGES_INSTANCE) - .setCellRenderer(new TableCellRenderer() { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - final Pages pages = (Pages) value; - return new Text(pages.getPrimaryUrl()); - } - }); - - columnModel - .get(COL_EDIT) - .setCellRenderer(new TableCellRenderer() { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil - .findBean(PermissionChecker.class); - - if (permissionChecker.isPermitted( - PagesPrivileges.ADMINISTER_PAGES)) { - - final ControlLink link = new ControlLink( - (Component) value); - return link; - } else { - return new Text(""); - } - } - - }); - - columnModel - .get(COL_DELETE) - .setCellRenderer(new TableCellRenderer() { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil - .findBean(PermissionChecker.class); - - if (permissionChecker.isPermitted( - PagesPrivileges.ADMINISTER_PAGES)) { - - final ControlLink link = new ControlLink( - (Component) value); - link.setConfirmation(new GlobalizedMessage( - "cms.ui.contentcenter.pages.delete.confirm", - CmsConstants.CMS_BUNDLE)); - return link; - } else { - return new Text(""); - } - } - - }); - - super.addTableActionListener(new TableActionListener() { - - @Override - public void cellSelected(final TableActionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - final int column = event.getColumn(); - final String key = (String) event.getRowKey(); - - switch (column) { - case COL_EDIT: - selectedPages.setSelectedKey(state, key); - showPagesForm(state); - break; - case COL_DELETE: { - deletePages(key); - break; - } - default: - throw new UnexpectedErrorException( - "Illegal column index."); - } - - } - - @Override - public void headSelected(final TableActionEvent event) { - - //Nothing - } - - }); - - super.setModelBuilder(new PagesTableModelBuilder()); - - super.setEmptyView(new Label(new GlobalizedMessage( - "cms.ui.contentcenter.pages.none", CmsConstants.CMS_BUNDLE))); - } - - } - - private void deletePages(final String pagesId) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PagesRepository pagesRepo = cdiUtil - .findBean(PagesRepository.class); - - final Pages pages = pagesRepo - .findById(Long.parseLong(pagesId)) - .orElseThrow(() -> new UnexpectedErrorException(String - .format("No Pages with ID %d in the database.", - pagesId))); - - pagesRepo.delete(pages); - } - - private class PagesTableModelBuilder - extends LockableImpl - implements TableModelBuilder { - - @Override - public TableModel makeModel(final Table table, final PageState state) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PagesRepository pagesRepo = cdiUtil - .findBean(PagesRepository.class); - - final List pages = pagesRepo.findAll(); - return new PagesTableModel(pages); - } - - } - - private class PagesTableModel implements TableModel { - - private final Iterator iterator; - private Pages current; - - public PagesTableModel(final List pages) { - - iterator = pages.iterator(); - - } - - @Override - public int getColumnCount() { - return 3; - } - - @Override - public boolean nextRow() { - - if (iterator.hasNext()) { - current = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - - switch (columnIndex) { - case PagesTable.COL_SITE: - return current; - case PagesTable.COL_PAGES_INSTANCE: - return current; - case PagesTable.COL_EDIT: - return new Label(new GlobalizedMessage( - "cms.ui.contentcenter.pages.edit.label", - CmsConstants.CMS_BUNDLE)); - case PagesTable.COL_DELETE: - return new Label(new GlobalizedMessage( - "cms.ui.contentcenter.pages.delete.label", - CmsConstants.CMS_BUNDLE)); - default: - throw new IllegalArgumentException("Illegal column index."); - } - } - - @Override - public Object getKeyAt(final int columnIndex) { - - return current.getObjectId(); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/PagesPaneController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/PagesPaneController.java deleted file mode 100644 index 0bb6a530d..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/PagesPaneController.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.contentcenter; - -import org.libreccm.categorization.Domain; -import org.libreccm.categorization.DomainRepository; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.sites.Site; -import org.libreccm.sites.SiteManager; -import org.libreccm.sites.SiteRepository; -import org.librecms.pages.Pages; -import org.librecms.pages.PagesManager; -import org.librecms.pages.PagesRepository; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class PagesPaneController { - - @Inject - private DomainRepository domainRepo; - - @Inject - private PagesRepository pagesRepo; - - @Inject - private PagesManager pagesManager; - - @Inject - private SiteManager siteManager; - - @Inject - private SiteRepository siteRepo; - - @Transactional(Transactional.TxType.REQUIRED) - protected void createPages(final String primaryUrl, - final long siteId, - final long categoryDomainId) { - - final Site site = siteRepo - .findById(siteId) - .orElseThrow(() -> new UnexpectedErrorException(String - .format("No Site with ID %d in the database.", - siteId))); - - final Domain domain = domainRepo - .findById(categoryDomainId) - .orElseThrow(() -> new UnexpectedErrorException(String - .format("No (Category) Domain with ID %d in the database.", - categoryDomainId))); - - final Pages pages = pagesManager.createPages(primaryUrl, site, domain); - pages.setPrimaryUrl(primaryUrl); - - pagesRepo.save(pages); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void updatePages(final long pagesId, - final String primaryUrl) { - - final Pages pages = pagesRepo - .findById(pagesId) - .orElseThrow(() -> new UnexpectedErrorException(String - .format("No Pages with ID %d in the database.", - pagesId))); - - pages.setPrimaryUrl(primaryUrl); - - pagesRepo.save(pages); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/TasksPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/TasksPane.java deleted file mode 100755 index 20ffd04dc..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contentcenter/TasksPane.java +++ /dev/null @@ -1,762 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.contentcenter; - -import java.math.BigDecimal; - -import javax.servlet.ServletException; - -import com.arsdigita.bebop.ActionLink; -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.PaginationModelBuilder; -import com.arsdigita.bebop.Paginator; -import com.arsdigita.bebop.RequestLocal; -import com.arsdigita.bebop.SimpleComponent; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.ChangeEvent; -import com.arsdigita.bebop.event.ChangeListener; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.ui.CMSContainer; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.ui.CcmObjectSelectionModel; -import com.arsdigita.xml.Element; - -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentType; - -public class TasksPane extends CMSContainer { - - // The default number of rows to show - private static final int DEFAULT_MAX_ROWS = 15; - // Number of tasks to show - private final int m_maxRows; - private TaskList m_taskList; - // private ActionLink m_viewAllLink; - // private ActionLink m_viewShortLink; - private Paginator m_paginator; - private ActionLink m_viewLockLink; - private ActionLink m_viewUnlockLink; - private ActionLink m_viewAllLockLink; - private Label m_viewLockLabel; - private Label m_viewUnlockLabel; - private Label m_viewAllLockLabel; - private StringParameter m_sortDirectionParam; - private StringParameter m_sortTypeParam; - private StringParameter m_lockFilterParam; - // control link variable - private static final String TASK_PANEL_CLASS = "taskPanel"; - private static final String TASK_ACTION = "taskAction"; - private static final String SORT_DOWN = "sortActionUp"; - private static final String SORT_UP = "sortActionDown"; - private static final String LOCK_FILTER_TYPE = "lockFilterType"; - private static final String SORT_TYPE = "sortType"; - private static final String SORT_DIRECTION = "sortDirection"; - private static final String SORT_ACTION = "action"; - private static final String SORT_DATE = "date"; - private static final String SORT_STATUS = "status"; - private static final String SORT_TITLE = "title"; - private static final String SORT_USER = "user"; - private static final String SORT_WORKFLOW = "workflow"; - // IMAGES - public static final String UP_ARROW_IMAGE - = "/themes/heirfloom/images/gray-triangle-up.gif"; - public static final String DOWN_ARROW_IMAGE - = "/themes/heirfloom/images/gray-triangle-down.gif"; - // CREATION PANE CONSTANTS - private Label m_selectorLabel; -//ToDo -// private CreationSelector m_selector; - private ContentSectionContainer m_sections; -// ToDo End - private CcmObjectSelectionModel m_sectionSel; - private CcmObjectSelectionModel m_typeSel; - -// private RootFolderSelectionModel m_folderSel; - private BoxPanel m_creationPane; - - /** - * Constructs a new task panel that shows no more than 15 enabled tasks by - * default. - * - * @param typeModel - * @param sectionModel - * - */ - public TasksPane(CcmObjectSelectionModel typeModel, - CcmObjectSelectionModel sectionModel) { - this(DEFAULT_MAX_ROWS, typeModel, sectionModel); - } - - /** - * Constructs a new task panel that shows a specified number enabled tasks. - * - * @param maxRows the maximum number of rows to show by default - * @param typeModel - * @param sectionModel - * - * @pre maxRows != null - * - */ - public TasksPane(int maxRows, - CcmObjectSelectionModel typeModel, - CcmObjectSelectionModel sectionModel) { - super(); - - // Set class attribute - setClassAttr(TASK_PANEL_CLASS); - - m_maxRows = maxRows; - - m_typeSel = typeModel; - m_sectionSel = sectionModel; - - m_sortDirectionParam = new StringParameter(SORT_DIRECTION); - m_sortTypeParam = new StringParameter(SORT_TYPE); - m_lockFilterParam = new StringParameter(LOCK_FILTER_TYPE); - addComponents(); - } - - /** - * Adds the components to this tasks panel - */ - private void addComponents() { - m_creationPane = new BoxPanel(BoxPanel.VERTICAL); - - // A label that says "Create $content_type in $section" - m_selectorLabel = new Label(new PrintListener() { - - @Override - public void prepare(PrintEvent e) { - PageState s = e.getPageState(); - Label t = (Label) e.getTarget(); - - ContentType type = (ContentType) m_typeSel.getSelectedObject(s); - ContentSection sec = (ContentSection) m_sectionSel - .getSelectedObject(s); - - StringBuilder buf = new StringBuilder( - new GlobalizedMessage("cms.ui.create", - CmsConstants.CMS_BUNDLE).localize() - + " "); - buf.append(type.getLabel()); - buf.append(" in "); - buf.append(sec.getLabel()); - - t.setLabel(buf.toString()); - t.setFontWeight(Label.BOLD); - t.setClassAttr("creationLabel"); - } - - }); - m_selectorLabel.setClassAttr("creationLabel"); - m_creationPane.add(m_selectorLabel); - -//ToDo -// m_folderSel = new RootFolderSelectionModel(m_sectionSel); -// m_selector = new CreationSelector(m_typeSel, m_folderSel); -// m_creationPane.add(m_selector); -//ToDo End - m_creationPane.setClassAttr("itemCreationPane"); - add(m_creationPane); - - // The section list UIx -//ToDo - m_sections = new ContentSectionContainer(m_typeSel, m_sectionSel); - add(m_sections); -//ToDo End - // When a new type is selected, show the creation UI. - // When the selection is cleared, return to section list - m_typeSel.addChangeListener(new ChangeListener() { - - @Override - public void stateChanged(ChangeEvent e) { - PageState s = e.getPageState(); - boolean isSelected = m_typeSel.isSelected(s); - -//ToDo -// m_sections.setVisible(s, !isSelected); -//ToDo End - m_creationPane.setVisible(s, isSelected); - } - - }); - - m_viewLockLink = new ActionLink(new Label(new GlobalizedMessage( - "cms.ui.workflow.task.view_locked", CmsConstants.CMS_BUNDLE))); - m_viewLockLink.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - PageState ps = e.getPageState(); - ps.setValue(m_lockFilterParam, "lock"); - } - - }); - - m_viewUnlockLink = new ActionLink(new Label(new GlobalizedMessage( - "cms.ui.workflow.task.view_unlocked", CmsConstants.CMS_BUNDLE))); - m_viewUnlockLink.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - PageState ps = e.getPageState(); - ps.setValue(m_lockFilterParam, "unlock"); - } - - }); - - m_viewAllLockLink = new ActionLink(new Label(new GlobalizedMessage( - "cms.ui.workflow.task.view_all", CmsConstants.CMS_BUNDLE))); - m_viewAllLockLink.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - PageState ps = e.getPageState(); - ps.setValue(m_lockFilterParam, "all"); - } - - }); - - m_viewLockLabel = new Label(new GlobalizedMessage( - "cms.ui.workflow.task.view_locked", CmsConstants.CMS_BUNDLE)); - m_viewLockLabel.setFontWeight(Label.BOLD); - m_viewUnlockLabel = new Label(new GlobalizedMessage( - "cms.ui.workflow.task.view_unlocked", CmsConstants.CMS_BUNDLE)); - m_viewUnlockLabel.setFontWeight(Label.BOLD); - m_viewAllLockLabel = new Label(new GlobalizedMessage( - "cms.ui.workflow.task.view_all", CmsConstants.CMS_BUNDLE)); - m_viewAllLockLabel.setFontWeight(Label.BOLD); - - add(new Label("
", false)); - add(m_viewLockLink); - add(m_viewLockLabel); - add(new Label(" ", false)); - add(m_viewUnlockLink); - add(m_viewUnlockLabel); - add(new Label(" ", false)); - add(m_viewAllLockLink); - add(m_viewAllLockLabel); - add(new Label("
", false)); - add(new Label("
", false)); - - add(getTasksList()); - add(getPaginator()); - -// m_actionLabel = new Label(GlobalizationUtil.globalize("cms.ui.action")); -// m_actionLabel.setClassAttr("action"); - } - - /** - * - * @param p - */ - @Override - public void register(Page p) { - super.register(p); - - p.setVisibleDefault(m_creationPane, false); -//ToDo -// p.addComponentStateParam(this, m_folderSel.getStateParameter()); -//ToDo End - - p.addGlobalStateParam(m_lockFilterParam); - p.addGlobalStateParam(m_sortTypeParam); - p.addGlobalStateParam(m_sortDirectionParam); - - p.setVisibleDefault(m_viewLockLabel, false); - p.setVisibleDefault(m_viewUnlockLabel, false); - p.setVisibleDefault(m_viewAllLockLink, false); - - p.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - final PageState state = e.getPageState(); - - String lockFilterType = getLockFilterType(state); - - if (lockFilterType.equals("lock")) { - m_viewLockLabel.setVisible(state, true); - m_viewLockLink.setVisible(state, false); - m_viewUnlockLabel.setVisible(state, false); - m_viewUnlockLink.setVisible(state, true); - m_viewAllLockLabel.setVisible(state, false); - m_viewAllLockLink.setVisible(state, true); - } else if (lockFilterType.equals("unlock")) { - m_viewLockLabel.setVisible(state, false); - m_viewLockLink.setVisible(state, true); - m_viewUnlockLabel.setVisible(state, true); - m_viewUnlockLink.setVisible(state, false); - m_viewAllLockLabel.setVisible(state, false); - m_viewAllLockLink.setVisible(state, true); - } else { - m_viewLockLabel.setVisible(state, false); - m_viewLockLink.setVisible(state, true); - m_viewUnlockLabel.setVisible(state, false); - m_viewUnlockLink.setVisible(state, true); - m_viewAllLockLabel.setVisible(state, true); - m_viewAllLockLink.setVisible(state, false); - } - } - - }); - } - - public void reset(PageState state) { - m_typeSel.clearSelection(state); - m_sectionSel.clearSelection(state); - } - - protected Paginator getPaginator() { - if (m_paginator == null) { - m_paginator = new Paginator(new TasksPaginationModelBuilder(), - m_maxRows); - } - return m_paginator; - } - - /** - * Returns the bebop List component to display the tasks - * - */ - private TaskList getTasksList() { - if (m_taskList == null) { - m_taskList = new TaskList(true); - } - return m_taskList; - } - - /** - * Returns the number of enabled tasks for the specified user. - * - * @param state - * - * @return - * - */ - protected int numberTasksForUser(PageState state) { - return m_taskList.size(state); - } - - protected String getSortType(PageState state) { - String sortType = (String) state.getValue(m_sortTypeParam); - if (sortType == null) { - sortType = SORT_DATE; - } - return sortType; - } - - protected String getSortDirection(PageState state) { - String sortDirection = (String) state.getValue(m_sortDirectionParam); - if (sortDirection == null) { - sortDirection = SORT_UP; - } - return sortDirection; - } - - protected String getLockFilterType(PageState state) { - String lockFilterType = (String) state.getValue(m_lockFilterParam); - if (lockFilterType == null || lockFilterType.equals("")) { - lockFilterType = "lock"; - } - return lockFilterType; - } - - /* - * Adds filters to the task query - */ -//ToDo -// protected void addQueryFilters(DataQuery query, Party party, PageState state) { -// query.setParameter("userId", party.getID()); -// -// FilterFactory ff = query.getFilterFactory(); -// -// // TODO: remove this hard coding of "Author", "Edit", and "Deploy" -// // TODO: remove this hard coding of "Author", "Edit", and "Deploy" -// CompoundFilter authorFilter = ff.and(); -// //cg query changed to refer to task type id -// authorFilter.addFilter(ff.equals("taskType", CMSTaskType.AUTHOR)); -// authorFilter.addFilter(getTaskFilter(CMSTaskType.retrieve( -// CMSTaskType.AUTHOR), -// party, ff)); -// -// CompoundFilter approveFilter = ff.and(); -// approveFilter.addFilter(ff.equals("taskType", CMSTaskType.EDIT)); -// approveFilter.addFilter(getTaskFilter(CMSTaskType.retrieve( -// CMSTaskType.EDIT), -// party, ff)); -// -// CompoundFilter deployFilter = ff.and(); -// deployFilter.addFilter(ff.equals("taskType", CMSTaskType.DEPLOY)); -// deployFilter.addFilter(getTaskFilter(CMSTaskType.retrieve( -// CMSTaskType.DEPLOY), -// party, ff)); -// -// CompoundFilter permissionFilter = ff.or(); -// permissionFilter.addFilter(authorFilter); -// permissionFilter.addFilter(approveFilter); -// permissionFilter.addFilter(deployFilter); -// -// query.addFilter(permissionFilter); -// -// String lockFilterType = getLockFilterType(state); -// if (lockFilterType.equals("lock")) { -// query.addEqualsFilter("isLocked", "t"); -// query.addEqualsFilter("status", "1"); -// } else if (lockFilterType.equals("unlock")) { -// query.addEqualsFilter("isLocked", "f"); -// } // else show all -// } -// private static class RootFolderSelectionModel -// extends FolderSelectionModel { -// -// CcmObjectSelectionModel m_sectionSel; -// -// public RootFolderSelectionModel(CcmObjectSelectionModel sectionSel) { -// super("f"); -// m_sectionSel = sectionSel; -// } -// -// @Override -// protected BigDecimal getRootFolderID(PageState s) { -// ContentSection sec = (ContentSection) m_sectionSel -// .getSelectedObject(s); -// Assert.exists(sec); -// -// User user = Web.getWebContext().getUser(); -// if (user != null) { -// Folder folder = Folder.getUserHomeFolder(user, sec); -// if (folder != null) { -// return folder.getID(); -// } -// } -// return sec.getRootFolder().getID(); -// } -// -// } -//ToDo End - /** - * - */ - private class TasksPaginationModelBuilder implements PaginationModelBuilder { - - @Override - public int getTotalSize(Paginator paginator, - PageState state) { - return numberTasksForUser(state); - } - - @Override - public boolean isVisible(PageState state) { - return numberTasksForUser(state) > m_maxRows; - } - - } - - private class TaskList extends SimpleComponent { - - private final static String QUERY_NAME - = "com.arsdigita.cms.workflow.getEnabledUserTasks"; - private boolean m_paginate = false; - - public TaskList(boolean paginate) { - m_paginate = paginate; - } - -// private DataQuery makeQuery(PageState state) { -// User user = (User) Kernel.getContext().getParty(); -// -// DataQuery query = SessionManager.getSession() -// .retrieveQuery(QUERY_NAME); -// addQueryFilters(query, user, state); -// -// return query; -// } - public int size(PageState ps) { - return ((Integer)m_taskCount.get(ps)).intValue(); - } - - private RequestLocal m_taskCount = new RequestLocal() { - - @Override - public Object initialValue(PageState state) { -// DataQuery query = makeQuery(state); -// return new Long(query.size()); - return 0; - } - - }; - - @Override - public void generateXML(PageState state, - Element parent) { - Element content = parent.newChildElement("cms:tasksPanel", - CMS.CMS_XML_NS); - exportAttributes(content); - -// DataQuery query = makeQuery(state); - String lockFilterType = getLockFilterType(state); - content.addAttribute("lockFilterType", lockFilterType); - - if (m_paginate) { -// query.setRange(new Integer(m_paginator.getFirst(state)), -// new Integer(m_paginator.getLast(state) + 1)); - } - - String sortKey = getSortType(state); - String sortDirection = getSortDirection(state); - String sortPostfix = " asc"; - if (sortDirection.equals(SORT_DOWN)) { - sortPostfix = " desc"; - } - -// if (sortKey.equals(SORT_TITLE)) { -// query.setOrder("lower(pageTitle) " + sortPostfix -// + ", lower(status) asc, dueDate desc"); -// } else if (sortKey.equals(SORT_DATE)) { -// query.setOrder("dueDate " + sortPostfix -// + ", lower(status) asc, lower(pageTitle) asc"); -// } else if (sortKey.equals(SORT_USER)) { -// query.setOrder("lockingUserID " + sortPostfix -// + ", lower(status) asc, dueDate desc " -// + ", lower(pageTitle) asc"); -// } else if (sortKey.equals(SORT_STATUS)) { -// query.setOrder("lower(status) " + sortPostfix -// + ", dueDate desc " -// + ", lower(pageTitle) asc"); -// -// } else if (sortKey.equals(SORT_ACTION)) { -// query.setOrder("taskType " + sortPostfix -// + ", lower(status) asc, dueDate desc " -// + ", lower(pageTitle) asc"); -// } else if (sortKey.equals(SORT_WORKFLOW)) { -// query.setOrder("processLabel " + sortPostfix -// + ", lower(status) asc, dueDate desc " -// + ", lower(pageTitle) asc"); -// } -// -// HashMap sections = new HashMap(); -// -// while (query.next()) { -// BigDecimal sectionID = (BigDecimal) query.get("sectionID"); -// String sectionPath = (String) sections.get(sectionID); -// if (sectionPath == null) { -// try { -// ContentSection section -// = (ContentSection) DomainObjectFactory -// .newInstance(new OID( -// ContentSection.BASE_DATA_OBJECT_TYPE, -// sectionID)); -// sectionPath = section.getPath(); -// } catch (DataObjectNotFoundException ex) { -// throw new UncheckedWrapperException( -// "cannot find content section", ex); -// } -// sections.put(sectionID, sectionPath); -// } -// -// Element task = content.newChildElement("cms:tasksPanelTask", -// CMS.CMS_XML_NS); -// -// BigDecimal itemID = (BigDecimal) query.get("itemID"); -// String taskType = (String) query.get("taskType"); -// -// task.addAttribute("taskID", query.get("taskID").toString()); -// task -// .addAttribute("processID", query.get("processID").toString()); -// task.addAttribute("taskLabel", (String) query.get("taskLabel")); -// task.addAttribute("taskDescription", (String) query.get( -// "taskDescription")); -// task.addAttribute("processLabel", (String) query.get( -// "processLabel")); -// -// String isLocked = (String) query.get("isLocked"); -// task.addAttribute("isLocked", isLocked); -// if (query.get("dueDate") != null) { -// java.util.Date d = (java.util.Date) query.get("dueDate"); -// SimpleDateFormat df = new SimpleDateFormat( -// "EEE, MMM d, yyyy"); -// -// task.addAttribute("dueDate", df.format(d)); -// } -// -// task.addAttribute("itemID", itemID.toString()); -// task -// .addAttribute("sectionID", query.get("sectionID").toString()); -// task.addAttribute("sectionPath", sectionPath); -// task.addAttribute("pageName", (String) query.get("pageName")); -// task.addAttribute("pageTitle", (String) query.get("pageTitle")); -// -// BigDecimal lockingUserID = (BigDecimal) query.get( -// "lockingUserID"); -// if (lockingUserID != null) { -// task.addAttribute("lockingUserID", lockingUserID.toString()); -// if (!"f".equals(isLocked)) { -// User lockingUser = User.retrieve(lockingUserID); -// if (lockingUser != null) { -// task.addAttribute("assignee", lockingUser -// .getDisplayName()); -// } -// } -// } -// task.addAttribute("taskType", taskType); -// task.addAttribute("taskTypeClass", (String) query.get( -// "taskTypeClass")); -// task.addAttribute("status", query.get("status").toString()); -// -// // control event for locking a task -// try { -// state.setControlEvent(this, TASK_ACTION, itemID.toString()); -// task.addAttribute("actionURL", state.stateAsURL()); -// state.clearControlEvent(); -// } catch (java.io.IOException ex) { -// s_log.warn("Error: " + ex.getMessage()); -// } -// -// if ("Deploy".equals(taskType)) { -// task.addAttribute("editTabNumber", -// String.valueOf( -// ContentItemPage.PUBLISHING_TAB)); -// } else { -// task.addAttribute("editTabNumber", -// String.valueOf( -// ContentItemPage.AUTHORING_TAB)); -// } - } - - // m_actionLabel.generateXML(state, content); - String[][] sortableHeaders = {{SORT_TITLE, - "cms.ui.workflow.task.item_title"}, - {SORT_ACTION, "cms.ui.action"}, - {SORT_DATE, "cms.ui.tasks_due_date"}, - {SORT_STATUS, - "cms.ui.tasks_status_no_colon"}, - {SORT_USER, - "cms.ui.workflow.task.locking_user"}, - {SORT_WORKFLOW, "cms.ui.workflow"}}; -// for (int i = 0; i < sortableHeaders.length; i++) { -// String header = sortableHeaders[i][0]; -// String labelKey = sortableHeaders[i][1]; -// if (sortDirection.equals(SORT_UP) && header.equals(sortKey)) { -// state.setControlEvent(this, SORT_DOWN, header); -// } else { -// state.setControlEvent(this, SORT_UP, header); -// } -// SimpleContainer container = new SimpleContainer(); -// container.add(new Label(GlobalizationUtil.globalize(labelKey))); -// if (header.equals(sortKey)) { -// String imageURLStub = null; -// if (SORT_UP.equals(sortDirection)) { -// imageURLStub = UP_ARROW_IMAGE; -// } else { -// imageURLStub = DOWN_ARROW_IMAGE; -// } -// Image image = new Image(imageURLStub); -// image.setBorder("0"); -// container.add(image); -// } -// -// ControlLink link = new ControlLink(container); -// link.setHint(GlobalizationUtil -// .globalize("cms.ui.contentcenter.task_panel_control")); -// link.setClassAttr(header); -// link.generateXML(state, content); -// state.clearControlEvent(); -// } - - } - - @Override - public void respond(PageState state) throws ServletException { - String key = state.getControlEventName(); - String value = state.getControlEventValue(); - if (TASK_ACTION.equals(key)) { - BigDecimal itemID = new BigDecimal(value); -// -// try { -// ContentItem item = new ContentItem(itemID); -// Workflow wf = Workflow.getObjectWorkflow(item); -// int tabNumber = ContentItemPage.AUTHORING_TAB; -// String sectionPath = item.getContentSection().getPath(); -// -// if (wf != null) { -// User user = Web.getWebContext().getUser(); -// Engine engine = Engine.getInstance( -// CMSEngine.CMS_ENGINE_TYPE); -// Iterator i = engine.getEnabledTasks(user, wf.getID()) -// .iterator(); -// if (i.hasNext()) { -// CMSTask task = (CMSTask) i.next(); -// Integer taskType = task.getTaskType().getID(); -// -// if (taskType.equals(CMSTaskType.DEPLOY)) { -// tabNumber = ContentItemPage.PUBLISHING_TAB; -// } else // see if item is locked; if not, lock -// { -// if (!task.isLocked()) { -// task.lock(user); -// } -// } -// } -// } -// -// String redirectURL = Web.getConfig() -// .getDispatcherServletPath() -// + sectionPath -// + "/admin/item.jsp?item_id=" -// + itemID + "&set_tab=" + tabNumber; -// throw new RedirectSignal(redirectURL, true); -// } catch (DataObjectNotFoundException ex) { -// throw new ServletException("Unknown content ID" + itemID); -// } -// } else - if (SORT_UP.equals(key) || SORT_DOWN.equals(key)) { - state.setValue(m_sortTypeParam, value); - if (SORT_DOWN.equals(key)) { - state.setValue(m_sortDirectionParam, SORT_DOWN); - } else { - state.setValue(m_sortDirectionParam, SORT_UP); - } - } else { - throw new ServletException("Unknown control event: " + key); - } - } - - } - -// private static Filter getTaskFilter(CMSTaskType taskType, Party party, -// FilterFactory factory) { -// PrivilegeDescriptor privilege; -// String queryName; -// String queryType; -// OID partyOID = party.getOID(); -// privilege = taskType.getPrivilege(); -// -// return PermissionService.getFilterQuery(factory, "itemID", privilege, -// partyOID); -// } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contenttypes/AbstractTextUploadForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/contenttypes/AbstractTextUploadForm.java deleted file mode 100644 index 4839dbaae..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contenttypes/AbstractTextUploadForm.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.contenttypes; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.form.FormErrorDisplay; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.util.GlobalizationUtil; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.FileUploadSection; -import com.arsdigita.globalization.Globalization; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.UncheckedWrapperException; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.awt.image.Kernel; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; - -import javax.activation.MimeType; - -/** - * - * @author Jens Pelzetter - */ -/** - *

- * An abstract base form for uploading Texts. The code of this class has been - * extracted from {@link TextAssetBody}, the form for editing an TextAsset (used - * for example for Article). The TextAsset has the disadvantage of storing its - * information in a separate table, so that information of a content item is - * spread over several tables. - *

- *

- * To use this form, define a property for your object which has the Java type - * String and the database type CLOB, like this: - *

- *
- * String[0..1] text = ct_yourContenttype.text CLOB
- * 
- *

- * To use this form your have to overwrite three methods: - *

- *
    - *
  • {@link #getLabelText()}
  • - *
  • {@link #getMimeTypeLabel()}
  • - *
  • {@link #setText()}
  • - *
- *
  • - * Of course, you have to add your form to a property step also, and write a - * simple constructor, which takes an {@link ItemSelectionModel} as parameter - * and passes it to the constructor of this class. - *
  • - * - * - * @author Jens Pelzetter - */ -public abstract class AbstractTextUploadForm - extends Form - implements FormInitListener, - FormProcessListener, - FormValidationListener { - - private static final Logger LOGGER = LogManager - .getLogger(AbstractTextUploadForm.class); - - private ItemSelectionModel itemModel; - private FileUploadSection fileUploadSection; - private SaveCancelSection saveCancelSection; - private RequestLocal fileUploadContent; - private RequestLocal fileUploadContentUsedInso; - - public AbstractTextUploadForm(final ItemSelectionModel itemModel) { - super("sciprojectUploadDescFrom", new BoxPanel(BoxPanel.VERTICAL)); - this.itemModel = itemModel; - setMethod(Form.POST); - setEncType("multipart/form-data"); - this.fileUploadContent = new RequestLocal(); - this.fileUploadContentUsedInso = new RequestLocal(); - addWidgets(); - } - - //Abstract methods to overwrite - /** - * The return value of this method is used as label for the upload form. - * - * @return The label for the upload form. - */ - public abstract GlobalizedMessage getLabelText(); - - /** - * The return value of this method is used as label for the MimeType field. - * - * @return The label for the MimeType field. - */ - public abstract GlobalizedMessage getMimeTypeLabel(); - - /** - *

    - * This method is called to pass the uploaded text to the edited object. In - * the method, you have to retrieve the current selected object from the - * itemModel parameter and call the appropriate - * set of your class, and its save method. An simple example: - *

    - *
    -     * @Override
    -     * public void setText(ItemSelectionModel itemModel,
    -     *                     PageState state,
    -     *                     String text) {
    -     *   YourContentType obj = (YourContentType) itemModel.getSelectedObject(state);
    -     *   obj.setText(text);
    -     *   obj.save();
    -     * }
    -     * 
    - * - * @param itemModel The {@link ItemSelectionModel} used by the form. - * @param state The current {@link PageState}. - * @param text The uploaded text. - */ - public abstract void setText(ItemSelectionModel itemModel, - PageState state, - String text); - - protected void addWidgets() { - add(new Label(getLabelText())); - fileUploadSection = new FileUploadSection( - getMimeTypeLabel(), - "mime", - "text/plain"); - fileUploadSection.getFileUploadWidget().addValidationListener( - new NotNullValidationListener()); - fileUploadSection.getMimeTypeWidget().setDefaultValue( - FileUploadSection.GUESS_MIME); - add(fileUploadSection); - - saveCancelSection = new SaveCancelSection(); - add(saveCancelSection); - - add(new FormErrorDisplay(this)); - - addValidationListener(this); - addProcessListener(this); - } - - /** - * @return the save/cancel section for this form - */ - public SaveCancelSection getSaveCancelSection() { - return saveCancelSection; - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - final PageState state = event.getPageState(); - - setVisible(state, true); - } - - /** - * Validate file upload - * - * @param event - * - * @throws FormProcessException - */ - @Override - public void validate(final FormSectionEvent event) throws - FormProcessException { - - final MimeType mime = fileUploadSection.getMimeType(event); - boolean textType = mime.getPrimaryType().equals("text"); - - validateFileType(mime, textType); - - // Convert the file to HTML, if possible - final File file = fileUploadSection.getFile(event); - byte[] file_bytes = readFileBytes(file); - boolean[] used_inso = new boolean[1]; - String file_content = convertBytes(file_bytes, textType, used_inso); - - if ("text/html".equals(mime.toString())) { - file_content = extractHTMLBody(file_content); - } - - final PageState state = event.getPageState(); - fileUploadContent.set(state, file_content); - fileUploadContentUsedInso.set(state, used_inso[0]); - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - LOGGER.debug("Processing upload..."); - final PageState state = event.getPageState(); - //File file = fileUploadSection.getFile(fse); - //SciProject project = (SciProject) itemModel.getSelectedObject(state); - - final String uploadContent = (String) fileUploadContent.get(state); - //boolean usedInso = (Boolean) fileUploadContentUsedInso.get(state); - - LOGGER.debug(String.format("Setting project description to: %s", - uploadContent)); - //project.setProjectDescription(uploadContent); - LOGGER.debug("Saving project."); - //project.save(); - setText(itemModel, state, uploadContent); - } - - private void validateFileType(final MimeType mime, final boolean textType) - throws FormProcessException { - - boolean validType = textType; - - if (!validType) { - throw new FormProcessException(GlobalizationUtil.globalize( - "cms.ui.authoring.invalid_file_type")); - } - } - - /** - * read in the content of the file (in bytes). - */ - private byte[] readFileBytes(final File file) throws FormProcessException { - final byte[] fileBytes; - try (FileInputStream fileInputStream = new FileInputStream(file)) { - fileBytes = new byte[fileInputStream.available()]; - fileInputStream.read(fileBytes); - } catch (IOException ex) { - throw new FormProcessException(GlobalizationUtil.globalize( - "cms.ui.authoring.unable_to_load_file")); - } - return fileBytes; - } - - /** - * Convert bytes to String, possibly using INSO filter to convert to HTML - * type - */ - private String convertBytes(final byte[] fileBytes, - final boolean textType, - final boolean[] usedInso) - throws FormProcessException { - - return new String(fileBytes, StandardCharsets.UTF_8); - } - - /** - * Extract the contents of the html Body tag. (Done to prevent base and - * other header tags from interfering with page display). - */ - private String extractHTMLBody(final String htmlText) - throws FormProcessException { - - final String lc = htmlText.toLowerCase(); - final int bodyStart = lc.indexOf("", bodyStart); - final int bodyEnd = lc.indexOf("", bodyStart_v); - if (bodyStart == -1 || bodyEnd == -1) { - throw new FormProcessException(GlobalizationUtil.globalize( - "cms.ui.authoring.html_file_missing_body_tags")); - } - return htmlText.substring(bodyStart_v + 1, bodyEnd); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contenttypes/EventCreateForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/contenttypes/EventCreateForm.java deleted file mode 100644 index 2dcfe31bd..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contenttypes/EventCreateForm.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.contenttypes; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.form.Date; -import com.arsdigita.bebop.parameters.NotEmptyValidationListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.CreationSelector; -import com.arsdigita.cms.ui.authoring.PageCreateForm; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItemInitializer; -import org.librecms.contenttypes.Event; - -/** - * - * @author Jens Pelzetter - */ -public class EventCreateForm extends PageCreateForm { - - private static final String START_DATE = "startDate"; - - private Date startDate; - - public EventCreateForm(final ItemSelectionModel itemSelectionModel, - final CreationSelector creationSelector, - final StringParameter selectedLanguageParam) { - - super(itemSelectionModel, creationSelector, selectedLanguageParam); - } - - @Override - protected void addWidgets() { - - super.addWidgets(); - - add(new Label(new GlobalizedMessage( - "cms.contenttypes.ui.event.start_date", - CmsConstants.CMS_BUNDLE))); - startDate = new Date(START_DATE); - startDate.addValidationListener(new NotEmptyValidationListener()); - add(startDate); - } - - @Override - protected ContentItemInitializer getItemInitializer( - final FormData data, final PageState state) { - - return item -> ((Event) item) - .setStartDate((java.util.Date) startDate.getValue(state)); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contenttypes/NewsCreateForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/contenttypes/NewsCreateForm.java deleted file mode 100644 index 89f314ade..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/contenttypes/NewsCreateForm.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.contenttypes; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.form.Date; -import com.arsdigita.bebop.parameters.NotEmptyValidationListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.authoring.CreationSelector; -import com.arsdigita.cms.ui.authoring.PageCreateForm; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItemInitializer; -import org.librecms.contenttypes.News; - -/** - * - * @author Jens Pelzetter - */ -public class NewsCreateForm extends PageCreateForm { - - private static final String NEWS_DATE = "newsDate"; - - private Date newsDate; - - public NewsCreateForm(final ItemSelectionModel itemSelectionModel, - final CreationSelector creationSelector, - final StringParameter selectedLanguageParam) { - - super(itemSelectionModel, creationSelector, selectedLanguageParam); - } - - @Override - protected void addWidgets() { - - super.addWidgets(); - - add(new Label(new GlobalizedMessage("cms.contenttypes.ui.newsitem.date", - CmsConstants.CMS_BUNDLE))); - newsDate = new Date(NEWS_DATE); - newsDate.addValidationListener(new NotEmptyValidationListener()); - add(newsDate); - } - - @Override - protected ContentItemInitializer getItemInitializer( - final FormData data, final PageState state) { - - return item -> ((News) item) - .setReleaseDate((java.util.Date) newsDate.getValue(state)); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredPane.java deleted file mode 100755 index 791a16fcd..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredPane.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2002-2005 Runtime Collective Ltd. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -package com.arsdigita.cms.ui.cse; - -import com.arsdigita.bebop.SimpleContainer; - -/** - * A pane that contains details to soon to be expired content. - * - * @author Unknown - * @author Jens Pelzetter - */ -public class ContentSoonExpiredPane extends SimpleContainer { - - public ContentSoonExpiredPane() { - super(); - super.add(new ContentSoonExpiredTable()); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredPaneController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredPaneController.java deleted file mode 100644 index ccfe70630..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredPaneController.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.cse; - -import com.arsdigita.bebop.table.RowData; - -import org.librecms.CMSConfig; -import org.libreccm.auditing.CcmRevision; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.l10n.GlobalizationHelper; -import org.libreccm.security.PermissionChecker; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.text.DateFormat; -import java.util.Calendar; -import java.util.List; -import java.util.Locale; -import java.util.stream.Collectors; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.persistence.EntityManager; -import javax.persistence.TypedQuery; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -public class ContentSoonExpiredPaneController { - - @Inject - private EntityManager entityManager; - - @Inject - private ConfigurationManager confManager; - - @Inject - private ContentItemRepository itemRepo; - - @Inject - private GlobalizationHelper globalizationHelper; - - @Inject - private PermissionChecker permissionChecker; - - @Transactional(Transactional.TxType.REQUIRED) - public List> getSoonExpiredItems( - final ContentSection section) { - final TypedQuery query = entityManager.createQuery( - "SELECT i FROM ContentItem i " - + "WHERE i.contentType.contentSection = :section " - + "AND :endDateTime <= i.lifecycle.endDateTime", - ContentItem.class); - - final CMSConfig cmsConfig = confManager.findConfiguration( - CMSConfig.class); - final int months = cmsConfig.getSoonExpiredTimespanMonths(); - final int days = cmsConfig.getSoonExpiredTimespanDays(); - - final Calendar date = Calendar.getInstance(Locale.ROOT); - date.add(Calendar.DAY_OF_YEAR, days); - date.add(Calendar.MONTH, months); - query.setParameter("endDateTime", date.getTime()); - - query.setParameter("section", section); - - final List result = query.getResultList(); - - return result.stream() - .map(item -> createRow(item)) - .collect(Collectors.toList()); - - } - - private RowData createRow(final ContentItem item) { - final RowData row = new RowData<>(5); - row.setRowKey(item.getObjectId()); - - final CcmRevision current = itemRepo.retrieveCurrentRevision( - item, item.getObjectId()); - row.setColData(ContentSoonExpiredTable.COL_AUTHOR_NAME, - current.getUserName()); - - row.setColData(ContentSoonExpiredTable.COL_ITEM_NAME, - item.getDisplayName()); - - row.setColData(ContentSoonExpiredTable.COL_VIEW, - item.getUuid()); - - if (permissionChecker.isPermitted(ItemPrivileges.EDIT, item)) { - row.setColData(ContentSoonExpiredTable.COL_EDIT, - item.getUuid()); - } else { - row.setColData(ContentSoonExpiredTable.COL_EDIT, - "--"); - } - - final DateFormat dateFormat = DateFormat.getDateTimeInstance( - DateFormat.LONG, - DateFormat.LONG, - globalizationHelper.getNegotiatedLocale()); - row.setColData(ContentSoonExpiredTable.COL_END_DATE_TIME, - dateFormat.format(item.getLifecycle().getEndDateTime())); - - return row; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredTable.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredTable.java deleted file mode 100644 index 892d6f19f..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredTable.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.cse; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Link; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableColumnModel; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.ui.ContentItemPage; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.web.Web; - -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentSection; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; - -/** - * - * @author Jens Pelzetter - */ -public class ContentSoonExpiredTable extends Table { - - protected static final int COL_AUTHOR_NAME = 0; - protected static final int COL_ITEM_NAME = 1; - protected static final int COL_VIEW = 2; - protected static final int COL_EDIT = 3; - protected static final int COL_END_DATE_TIME = 4; - - public ContentSoonExpiredTable() { - - super(); - -// final ContentSection section = CMS.getContext().getContentSection(); - - super.setModelBuilder(new ContentSoonExpiredTableModelBuilder()); - - final TableColumnModel columnModel = getColumnModel(); - columnModel.add(new TableColumn( - COL_AUTHOR_NAME, - new Label(new GlobalizedMessage("cms.ui.cse.authorName", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_ITEM_NAME, - new Label(new GlobalizedMessage("cms.ui.cse.itemName", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_VIEW, - new Label(new GlobalizedMessage("cms.ui.cse.view", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_EDIT, - new Label(new GlobalizedMessage("cms.ui.cse.edit", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn( - COL_END_DATE_TIME, - new Label(new GlobalizedMessage("cms.ui.cse.endDateTime", - CmsConstants.CMS_BUNDLE)))); - - columnModel.get(COL_VIEW).setCellRenderer(new TableCellRenderer() { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - try { - final Link link = new Link( - new Label(new GlobalizedMessage( - "cms.ui.cse.viewLink", - CmsConstants.CMS_BUNDLE)), - String.format( - "%s/redirect/?oid=%s", - Web.getWebappContextPath(), - URLEncoder.encode( - (String) value, "UTF-8"))); - return link; - } catch (UnsupportedEncodingException ex) { - throw new UncheckedWrapperException(ex); - } - } - - }); - - columnModel.get(COL_EDIT).setCellRenderer(new TableCellRenderer() { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - if ("--".equals(value)) { - //No access for current user - return new Text(""); - } else { - return new Link(new Label(new GlobalizedMessage( - "cms.ui.cse.editLink", - CmsConstants.CMS_BUNDLE)), - ContentItemPage.getItemURL( - (Long) key, - ContentItemPage.AUTHORING_TAB)); - } - } - - }); - - setEmptyView(new Label(new GlobalizedMessage("cms.ui.cse.none", - CmsConstants.CMS_BUNDLE))); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredTableModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredTableModel.java deleted file mode 100644 index b7f4b5e33..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredTableModel.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.cse; - -import com.arsdigita.bebop.table.RowData; -import com.arsdigita.bebop.table.TableModel; - -import java.util.Iterator; -import java.util.List; - -/** - * - * @author Jens Pelzetter - */ -class ContentSoonExpiredTableModel implements TableModel { - - private final Iterator> iterator; - private RowData currentRow; - - protected ContentSoonExpiredTableModel(final List> rows) { - iterator = rows.iterator(); - } - - @Override - public int getColumnCount() { - return 5; - } - - @Override - public boolean nextRow() { - if (iterator.hasNext()) { - currentRow = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - switch (columnIndex) { - case ContentSoonExpiredTable.COL_AUTHOR_NAME: - return currentRow.getColData( - ContentSoonExpiredTable.COL_AUTHOR_NAME); - case ContentSoonExpiredTable.COL_ITEM_NAME: - return currentRow.getColData( - ContentSoonExpiredTable.COL_ITEM_NAME); - case ContentSoonExpiredTable.COL_VIEW: - return currentRow.getColData(ContentSoonExpiredTable.COL_VIEW); - case ContentSoonExpiredTable.COL_EDIT: - return currentRow.getColData(ContentSoonExpiredTable.COL_EDIT); - case ContentSoonExpiredTable.COL_END_DATE_TIME: - return currentRow.getColData( - ContentSoonExpiredTable.COL_END_DATE_TIME); - default: - throw new IllegalArgumentException("Invalid column index."); - } - } - - @Override - public Object getKeyAt(final int columnIndex) { - return currentRow.getRowKey(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredTableModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredTableModelBuilder.java deleted file mode 100644 index 197ef7509..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/cse/ContentSoonExpiredTableModelBuilder.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.cse; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.table.RowData; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.CMS; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentSection; - -import java.util.List; - -/** - * - * @author Jens Pelzetter - */ -class ContentSoonExpiredTableModelBuilder - extends LockableImpl - implements TableModelBuilder { - - @Override - public TableModel makeModel(final Table table, final PageState state) { - - final ContentSection section = CMS.getContext().getContentSection(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentSoonExpiredPaneController controller = cdiUtil.findBean( - ContentSoonExpiredPaneController.class); - - final List> rows = controller.getSoonExpiredItems(section); - - return new ContentSoonExpiredTableModel(rows); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/ChildUniqueValidationListener.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/ChildUniqueValidationListener.java deleted file mode 100755 index f6b3fce86..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/ChildUniqueValidationListener.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.bebop.event.ParameterListener; - -import org.libreccm.categorization.Category; - - -/** - * - * - */ -final class ChildUniqueValidationListener implements ParameterListener { - - private final FolderRequestLocal m_parent; - - /** - * Constructor. - * @param parent - */ - public ChildUniqueValidationListener(final FolderRequestLocal parent) { - m_parent = parent; - } - - /** - * - * @param e - * @throws FormProcessException - */ - @Override - public final void validate(final ParameterEvent e) - throws FormProcessException { - final PageState state = e.getPageState(); - final String name = (String) e.getParameterData().getValue(); - - if (name != null) { - validateNameUniqueness(m_parent.getFolder(state), name); - } - } - - /** - * - * @param parent - * @param name - * @throws FormProcessException - */ - private void validateNameUniqueness(final Category parent, - final String name) - throws FormProcessException { - - //ToDo - - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderAddForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderAddForm.java deleted file mode 100755 index df149db42..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderAddForm.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; - -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.cdi.utils.CdiUtil; - -class FolderAddForm extends FolderBaseForm { - - private final SingleSelectionModel m_model; - private final FolderRequestLocal m_parent; - - public FolderAddForm(final SingleSelectionModel model, - final FolderRequestLocal parent) { - super("folder-add"); - - m_model = model; - m_parent = parent; - - m_fragment.addValidationListener(new ChildUniqueValidationListener( - parent)); - - addProcessListener(new ProcessListener()); - } - - private class ProcessListener implements FormProcessListener { - - public final void process(final FormSectionEvent e) - throws FormProcessException { - final PageState state = e.getPageState(); - - final Category folder = new Category(); - - folder.setParentCategory(m_parent.getFolder(state)); - folder.setDisplayName((String) m_title.getValue(state)); - folder.setName((String) m_fragment.getValue(state)); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryRepository categoryRepo = cdiUtil.findBean( - CategoryRepository.class); - categoryRepo.save(folder); - - m_model.setSelectedKey(state, folder.getObjectId()); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderAdminPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderAdminPane.java deleted file mode 100755 index 5dfbbafb3..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderAdminPane.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.ActionLink; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.parameters.BigDecimalParameter; -import com.arsdigita.cms.CMS; - -import org.librecms.contentsection.ContentSection; - -import com.arsdigita.cms.ui.BaseDeleteForm; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.SelectionPanel; - -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.Folder; - - -/** - * A pane that contains a folder tree on the left and a folder manipulator on - * the right. - * - * @author Justin Ross <jross@redhat.com> - */ -public class FolderAdminPane extends SelectionPanel { - - private final FolderRequestLocal m_folder; - - private final BigDecimalParameter m_param; - - public static final String FOLDER_PARAMETER = "folder"; - - public FolderAdminPane() { - super(new Label(gz("cms.ui.folder.folders")), - new FolderTreeModelBuilder() { - - @Override - protected Folder getRootFolder(final PageState state) { - final ContentSection section = CMS - .getContext() - .getContentSection(); - - return section.getRootDocumentsFolder(); - } - - }); - - m_folder = new FolderRequestLocal(getSelectionModel()); - m_param = new BigDecimalParameter(FOLDER_PARAMETER); - - setAdd(new ActionLink(new Label(gz("cms.ui.folder.add"))), - new FolderAddForm(getSelectionModel(), m_folder)); - - setEdit(new ActionLink(new Label(gz("cms.ui.folder.edit"))), - new FolderEditForm(m_folder)); - - final BaseDeleteForm delete = new BaseDeleteForm(new Label(gz( - "cms.ui.folder.delete_prompt"))) { - - @Override - public final void process(final FormSectionEvent e) - throws FormProcessException { - final PageState state = e.getPageState(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryRepository categoryRepo = cdiUtil.findBean( - CategoryRepository.class); - - categoryRepo.delete(m_folder.getFolder(state)); - getSelectionModel().clearSelection(state); - } - - }; - - setDelete(new ActionLink(new Label(gz("cms.ui.folder.delete"))), - delete); - - setIntroPane(new Label(gz("cms.ui.folder.intro"))); - setItemPane(new Label("item XXX")); - - addAction(getAddLink()); - addAction(getEditLink()); - addAction(getDeleteLink()); - } - - @Override - public void register(final Page page) { - super.register(page); - - page.addGlobalStateParam(m_param); - page.addActionListener(new PreselectListener()); - } - - private class PreselectListener implements ActionListener { - - @Override - public final void actionPerformed(final ActionEvent e) { - final PageState state = e.getPageState(); - final SingleSelectionModel model = getSelectionModel(); - - if (!model.isSelected(state)) { - final Long value = (Long) state.getValue(m_param); - - if (value == null) { - final ContentSection section = CMS.getContext() - .getContentSection(); - - model.setSelectedKey(state, section.getRootDocumentsFolder() - .getObjectId()); - } else { - model.setSelectedKey(state, value); - } - } - } - - } - - private static GlobalizedMessage gz(final String key) { - return new GlobalizedMessage(key, CmsConstants.CMS_FOLDER_BUNDLE); - } - - private static String lz(final String key) { - return (String) gz(key).localize(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBaseForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBaseForm.java deleted file mode 100755 index 91902a319..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBaseForm.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.GridPanel; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.parameters.TrimmedStringParameter; - - -import com.arsdigita.cms.ui.CMSForm; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.web.Web; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.librecms.CmsConstants; - -/** - * Class FolderForm implements the basic form for creating or renaming folders. - * - * @author Jon Orris <jorris@redhat.com> - */ -abstract class FolderBaseForm extends CMSForm { - - private static Logger LOGGER = LogManager.getLogger(FolderBaseForm.class); - - public static final String NAME = "ContentItemName"; - public static final String TITLE = "ContentPageTitle"; - - private static final String TITLE_ON_FOCUS = "if (this.form." + NAME + ".value == '') {" - + " defaulting = true;" + " this.form." - + NAME + ".value = urlize(this.value);" + "}"; - - private static final String TITLE_ON_KEY_UP = "if (defaulting) {" + " this.form." + NAME - + ".value = urlize(this.value)" + "}"; - - private static final String FRAGMENT_ON_FOCUS = "defaulting = false"; - - private static final String FRAGMENT_ON_BLUR = "if (this.value == '') {" - + " defaulting = true;" - + " this.value = urlize(this.form." + TITLE - + ".value)" + "} else {" - + " this.value = urlize(this.value);" + "}"; - - private Label m_script = new Label( - String.format( - "", - Web.getWebappContextPath()), - false); - - final TextField m_title; - final TextField m_fragment; - final SaveCancelSection m_submits; - - public FolderBaseForm(final String name) { - super(name); - - add(m_script, GridPanel.FULL_WIDTH); - - // Title - add(new Label(gz("cms.ui.folder.name"))); - - m_title = new TextField(new TrimmedStringParameter(TITLE)); - add(m_title); - - m_title.addValidationListener(new NotNullValidationListener()); - m_title.setOnFocus(TITLE_ON_FOCUS); - - m_title.setOnFocus(TITLE_ON_FOCUS); - m_title.setOnKeyUp(TITLE_ON_KEY_UP); - - // Fragment - add(new Label(gz("cms.ui.folder.fragment"))); - - m_fragment = new TextField(new TrimmedStringParameter(NAME)); - add(m_fragment); - - m_fragment.addValidationListener(new NotNullValidationListener()); - - m_fragment.setOnFocus(FRAGMENT_ON_FOCUS); - m_fragment.setOnBlur(FRAGMENT_ON_BLUR); - - m_submits = new SaveCancelSection(); - add(m_submits, GridPanel.FULL_WIDTH); - } - - public final boolean isCancelled(final PageState state) { - return m_submits.getCancelButton().isSelected(state); - } - - private static GlobalizedMessage gz(final String key) { - return new GlobalizedMessage(key, CmsConstants.CMS_FOLDER_BUNDLE); - } - - private static String lz(final String key) { - return (String) gz(key).localize(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowser.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowser.java deleted file mode 100755 index abe4d03e4..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowser.java +++ /dev/null @@ -1,546 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.Image; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Link; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Paginator; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.TableActionAdapter; -import com.arsdigita.bebop.event.TableActionEvent; -import com.arsdigita.bebop.event.TableActionListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.DefaultTableCellRenderer; -import com.arsdigita.bebop.table.DefaultTableColumnModel; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableHeader; -import com.arsdigita.cms.CMS; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.util.Assert; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import javax.servlet.ServletException; - -import org.libreccm.categorization.Category; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionManager; -import org.librecms.contentsection.privileges.ItemPrivileges; -import org.librecms.dispatcher.ItemResolver; - -import java.util.Date; -import java.util.List; -import java.util.Locale; - -/** - * Browse folders and items. If the user clicks on a folder, the folder - * selection model is updated. If the user clicks on any other item, an separate - * item selection model is updated. - * - * @author David Lutterkort - * @author Sören Bernstein - * @author Jens Pelzetter - */ -public class FolderBrowser extends Table { - - private static final GlobalizedMessage[] HEADERS = { - globalize("cms.ui.folder.name"), - globalize("cms.ui.folder.languages"), - globalize("cms.ui.folder.title"), - // globalize("cms.ui.folder.additionalInfo"), - globalize("cms.ui.folder.type"), - globalize("cms.ui.folder.creation_date"), - globalize("cms.ui.folder.last_modified"), - globalize("cms.ui.folder.action")}; - protected static final String SORT_ACTION_UP = "sortActionUp"; - protected static final String SORT_ACTION_DOWN = "sortActionDown"; - protected final static String SORT_KEY_NAME = "name"; - protected final static String SORT_KEY_TITLE = "title"; - protected final static String SORT_KEY_TYPE = "type"; - protected final static String SORT_KEY_LAST_MODIFIED_DATE = "lastModified"; - protected final static String SORT_KEY_CREATION_DATE = "creationDate"; - - private final FolderSelectionModel folderSelectionModel; - private final TableActionListener folderChanger; - private final TableActionListener folderDeleter; -// private TableActionListener m_indexChanger; - private final TableColumn nameColumn; - private final TableColumn deleteColumn; -// private TableColumn m_indexColumn; - private final StringParameter sortTypeParameter = new StringParameter( - "sortType"); - private final StringParameter sortDirectionParameter = new StringParameter( - "sortDirn"); - - private StringParameter atozFilterParameter = null; - private StringParameter filterParameter = null; - private FolderManipulator folderManipulator; - private Paginator paginator; -// private FolderManipulator.FilterForm filterForm; - private long folderSize; - - public FolderBrowser(final FolderSelectionModel folderSelectionModel) { - super(); - sortTypeParameter.setDefaultValue(SORT_KEY_NAME); - sortDirectionParameter.setDefaultValue(SORT_ACTION_UP); - - setModelBuilder(new FolderBrowserTableModelBuilder()); - setColumnModel(new DefaultTableColumnModel(HEADERS)); - setHeader(new TableHeader(getColumnModel())); - - this.folderSelectionModel = folderSelectionModel; - - setClassAttr("dataTable"); - - getHeader().setDefaultRenderer( - new com.arsdigita.cms.ui.util.DefaultTableCellRenderer()); - - nameColumn = getColumn(0); - nameColumn.setCellRenderer(new NameCellRenderer()); - nameColumn.setHeaderRenderer(new HeaderCellRenderer(SORT_KEY_NAME)); - getColumn(1).setCellRenderer(new LanguagesCellRenderer()); - getColumn(4).setHeaderRenderer(new HeaderCellRenderer( - SORT_KEY_CREATION_DATE)); - - getColumn(4).setCellRenderer(new DateCellRenderer()); - getColumn(5).setCellRenderer(new DateCellRenderer()); - getColumn(5).setHeaderRenderer(new HeaderCellRenderer( - SORT_KEY_LAST_MODIFIED_DATE)); - - deleteColumn = getColumn(6); - deleteColumn.setCellRenderer(new ActionCellRenderer()); - deleteColumn.setAlign("center"); - folderChanger = new FolderChanger(); - addTableActionListener(folderChanger); - - folderDeleter = new ItemDeleter(); - addTableActionListener(folderDeleter); - - setEmptyView(new Label(globalize("cms.ui.folder.no_items"))); - - Assert.exists(folderSelectionModel.getStateParameter()); - } - - @Override - public void register(final Page page) { - super.register(page); - - page.addComponentStateParam(this, - folderSelectionModel.getStateParameter()); - page.addComponentStateParam(this, - sortTypeParameter); - page.addComponentStateParam(this, - sortDirectionParameter); - page.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(final ActionEvent event) { - final PageState state = event.getPageState(); - - if (state.isVisibleOnPage(FolderBrowser.this)) { - showHideFolderActions(state); - } - } - - }); - } - - private void showHideFolderActions(final PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - final Category folder = (Category) folderSelectionModel - .getSelectedObject(state); - - final boolean canDelete = permissionChecker.isPermitted( - ItemPrivileges.DELETE, folder); - deleteColumn.setVisible(state, canDelete); - } - - @Override - public void respond(final PageState state) throws ServletException { - final String key = state.getControlEventName(); - final String value = state.getControlEventValue(); - if (SORT_ACTION_UP.equals(key)) { - state.setValue(sortTypeParameter, value); - state.setValue(sortDirectionParameter, SORT_ACTION_UP); - } else if (SORT_ACTION_DOWN.equals(key)) { - state.setValue(sortTypeParameter, value); - state.setValue(sortDirectionParameter, SORT_ACTION_DOWN); - } else { - super.respond(state); - } - } - - public FolderSelectionModel getFolderSelectionModel() { - return folderSelectionModel; - } - - protected void setFolderManipulator( - final FolderManipulator folderManipulator) { - this.folderManipulator = folderManipulator; - } - -// protected void setFilterForm(final FolderManipulator.FilterForm filterForm) { -// this.filterForm = filterForm; -// } - protected void setAtoZfilterParameter( - final StringParameter atozFilterParameter) { - this.atozFilterParameter = atozFilterParameter; - } - - protected void setFilterParameter(final StringParameter filterParameter) { - this.filterParameter = filterParameter; - } - - protected long getFolderSize() { - return folderSize; - } - - protected Paginator getPaginator() { - return paginator; - } - - protected void setPaginator(final Paginator paginator) { - this.paginator = paginator; - } - - protected String getFilter(final PageState state) { - return (String) state.getValue(filterParameter); - } - - protected String getAtoZfilter(final PageState state) { - return (String) state.getValue(atozFilterParameter); - } - - protected String getSortType(final PageState state) { - return (String) state.getValue(sortTypeParameter); - } - - protected String getSortDirection(final PageState state) { - return (String) state.getValue(sortDirectionParameter); - } - - private class HeaderCellRenderer - extends com.arsdigita.cms.ui.util.DefaultTableCellRenderer { - - private final String headerKey; - - public HeaderCellRenderer(final String headerKey) { - super(true); - this.headerKey = headerKey; - } - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - final GlobalizedMessage headerName = (GlobalizedMessage) value; - final String sortKey = (String) state.getValue(sortTypeParameter); - final boolean isCurrentKey = sortKey.equals(key); - final String currentSortDirection = (String) state.getValue( - sortDirectionParameter); - final String imageURLStub; - - if (SORT_ACTION_UP.equals(currentSortDirection)) { - imageURLStub = "gray-triangle-up.gif"; - } else { - imageURLStub = "gray-triangle-down.gif"; - } - - final ControlLink link = new ControlLink(new Label(headerName)) { - - @Override - public void setControlEvent(final PageState state) { - String sortDirectionAction; - // by default, everything sorts "up" unless it - // is the current key and it is already pointing up - if (SORT_ACTION_UP.equals(currentSortDirection) - && isCurrentKey) { - sortDirectionAction = SORT_ACTION_DOWN; - } else { - sortDirectionAction = SORT_ACTION_UP; - } - state.setControlEvent(table, - sortDirectionAction, - headerKey); - } - - }; - final Label label = new Label(); - label.setLabel(headerName); - label.setClassAttr("folderBrowserLink"); - label.setOutputEscaping(false); - label.setFontWeight(Label.BOLD); - - final SimpleContainer container = new SimpleContainer(); - container.add(label); - if (isCurrentKey) { - Image image = new Image("/assets/" + imageURLStub); - image.setBorder("0"); - container.add(image); - } - link.setChild(container); - return link; - } - - } -// - - /** - * Produce links to view an item or control links for folders to change into - * the folder. - */ - private class NameCellRenderer extends DefaultTableCellRenderer { - - public NameCellRenderer() { - super(true); - } - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - final String name = (String) value; - final ContentSection section = CMS.getContext().getContentSection(); - final ContentSectionManager sectionManager = CdiUtil.createCdiUtil() - .findBean(ContentSectionManager.class); - final ItemResolver itemResolver = sectionManager.getItemResolver( - section); - - final boolean isFolder = ((FolderBrowserTableModel) table - .getTableModel(state)).isFolder(); - final long objectId = getObjectId(key); - - if (isFolder) { - //return new ControlLink(new Text(name)); - return super.getComponent(table, - state, - value, - isSelected, - objectId, - row, - column); - } else { - return new Link(new Text(name), - itemResolver.generateItemURL(state, - objectId, - name, - section, - "DRAFT")); - } - } - - } - - /** - * Added by: Sören Bernstein - * - * Produce links to view an item in a specific language and show all - * existing language version and the live status in the folder browser. - */ - private class LanguagesCellRenderer extends DefaultTableCellRenderer { - - public LanguagesCellRenderer() { - super(true); - } - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - final SimpleContainer container = new SimpleContainer(); - final ContentSection section = CMS.getContext().getContentSection(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentSectionManager sectionManager = cdiUtil.findBean( - ContentSectionManager.class); - final ItemResolver itemResolver = sectionManager.getItemResolver( - section); - - @SuppressWarnings("unchecked") - final List availableLocales = (List) value; - availableLocales.forEach(locale -> container.add(new Link( - new Text(locale.toString()), - itemResolver.generateItemURL( - state, - getObjectId(key), - locale.toString(), - section, - "DRAFT")))); - - return container; - } - - } - - private class DateCellRenderer implements TableCellRenderer { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - if (value instanceof Date) { - final Date date = (Date) value; - return new Text(String.format("%1$TF %1$TT", date)); - } else if (value == null) { - return new Text(""); - } else { - return new Text(value.toString()); - } - } - - } - - /** - * Produce delete links for items and non-empty folders. - */ - private static class ActionCellRenderer implements TableCellRenderer { - - private static final Logger LOGGER = LogManager.getLogger( - ActionCellRenderer.class); - - private static final Label noActionLabel; - private static final ControlLink link; - - static { - LOGGER.debug("Static initializer is starting..."); - noActionLabel = new Label(" ", false); - noActionLabel.lock(); - link = new ControlLink( - new Label(globalize("cms.ui.folder.delete"))); - link.setConfirmation( - globalize("cms.ui.folder.delete_confirmation")); - LOGGER.debug("Static initializer finished."); - } - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - if (((Boolean) value)) { - return link; - } else { - return noActionLabel; - } - } - - } - -// Deletes an item - private class ItemDeleter extends TableActionAdapter { - - @Override - public void cellSelected(final TableActionEvent event) { - int col = event.getColumn(); - - if (deleteColumn != getColumn(col)) { - return; - } - - final PageState state = event.getPageState(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderBrowserController controller = cdiUtil.findBean( - FolderBrowserController.class); - controller.deleteObject((String) event.getRowKey()); - - ((Table) event.getSource()).clearSelection(state); - } - - } - - private class FolderChanger extends TableActionAdapter { - - @Override - public void cellSelected(final TableActionEvent event) { - final PageState state = event.getPageState(); - final int col = event.getColumn(); - - if (nameColumn != getColumn(col)) { - return; - } - - clearSelection(state); - getFolderSelectionModel().setSelectedKey( - state, - getObjectId(event.getRowKey())); - } - - } - /** - * Getting the GlobalizedMessage using a CMS Class targetBundle. - * - * @param key The resource key - */ - private static GlobalizedMessage globalize(String key) { - return new GlobalizedMessage(key, CmsConstants.CMS_FOLDER_BUNDLE); - - } - - private long getObjectId(final Object key) { - - final String keyStr = (String) key; - - if (keyStr.startsWith("folder-")) { - return Long.parseLong(keyStr.substring("folder-".length())); - } else if (keyStr.startsWith("item-")) { - return Long.parseLong(keyStr.substring("item-".length())); - } else { - return Long.parseLong(keyStr); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserController.java deleted file mode 100644 index b4ae1fcd0..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserController.java +++ /dev/null @@ -1,955 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.folder; - -import com.arsdigita.kernel.KernelConfig; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Categorization; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.core.CcmObject; -import org.libreccm.core.CcmObjectRepository; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemL10NManager; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentItemVersion; -import org.librecms.contentsection.ContentType; -import org.librecms.contentsection.Folder; -import org.librecms.contentsection.FolderRepository; -import org.librecms.contenttypes.ContentTypeInfo; -import org.librecms.contenttypes.ContentTypesManager; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.Optional; - -import java.util.stream.Collectors; - -import javax.annotation.PostConstruct; -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.persistence.EntityManager; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Join; -import javax.persistence.criteria.Root; -import javax.transaction.Transactional; - -import javax.persistence.TypedQuery; -import javax.persistence.criteria.Order; -import javax.persistence.criteria.Path; - -import org.librecms.contentsection.FolderManager; - -import javax.persistence.criteria.Subquery; - -import static org.librecms.CmsConstants.*; - -/** - * The {@code FolderBrowserController} wraps all database operations (queries) - * required by the {@link FolderBrowser}, the - * {@link FolderBrowserTableModelBuilder} and the - * {@link FolderBrowserTableModel}. - * - * @author Jens Pelzetter - */ -@RequestScoped -public class FolderBrowserController { - - private static final Logger LOGGER = LogManager - .getLogger(FolderBrowserController.class); - - @Inject - private EntityManager entityManager; - - @Inject - private CcmObjectRepository ccmObjectRepo; - - @Inject - private CategoryManager categoryManager; - - @Inject - private CcmObjectRepository objectRepo; - - @Inject - private ConfigurationManager confManager; - - @Inject - private GlobalizationHelper globalizationHelper; - - @Inject - private ContentItemRepository itemRepo; - - @Inject - private ContentItemManager itemManager; - - @Inject - private ContentItemL10NManager itemL10NManager; - - @Inject - private ContentTypesManager typesManager; - - @Inject - private FolderRepository folderRepo; - - @Inject - private FolderManager folderManager; - - private Locale defaultLocale; - - /** - * Initialisation method called by the CDI-Container after an instance of - * this class has be created by the container. Sets the - * {@link #defaultLocale} property using the the value from the - * {@link KernelConfig}. - */ - @PostConstruct - private void init() { - final KernelConfig kernelConfig = confManager.findConfiguration( - KernelConfig.class); - defaultLocale = kernelConfig.getDefaultLocale(); - } - - /** - * Count the objects (subfolders and content items) in the provided folder. - * - * @param folder The folder. - * - * @return The number of objects (subfolders and content items) in the - * provided {@code folder}. - */ - public long countObjects(final Folder folder) { - return countObjects(folder, "%"); - } - - /** - * Count all objects (subfolders and content items) in the provided folder - * which match the provided filter term. - * - * @param folder The folder. - * @param filterTerm The filter term. - * - * @return The number of objects (subfolders and content items) in the - * provided {@code folder} which match the provided - * {@code filterTerm}. - */ - public long countObjects(final Folder folder, - final String filterTerm) { - - Objects.requireNonNull(folder, "Can't count objects in Folder null."); - Objects.requireNonNull(filterTerm, "Can't filter for 'null'."); - - final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = builder.createQuery(Long.class); - final Root from = criteriaQuery.from(CcmObject.class); - - criteriaQuery = criteriaQuery.select(builder.count(from)); - - final List subFolders = findSubFolders(folder, - filterTerm, - FolderBrowser.SORT_KEY_NAME, - FolderBrowser.SORT_ACTION_UP, - -1, - -1); - final List items = findItemsInFolder(folder, - filterTerm, - FolderBrowser.SORT_KEY_NAME, - FolderBrowser.SORT_ACTION_UP, - -1, - -1); - if (subFolders.isEmpty() && items.isEmpty()) { - return 0; - } else if (subFolders.isEmpty() && !items.isEmpty()) { - criteriaQuery = criteriaQuery.where(from.in(items)); - } else if (!subFolders.isEmpty() && items.isEmpty()) { - criteriaQuery = criteriaQuery.where(from.in(subFolders)); - } else { - criteriaQuery = criteriaQuery.where(builder.or( - from.in(subFolders), - from.in(items))); - } - - return entityManager.createQuery(criteriaQuery).getSingleResult(); - } - - /** - * Create {@link FolderBrowserTableRow} objects for all objects in the - * provided folder. - * - * @param folder The folder which contains the objects. - * @param orderBy The field used to order the objects. - * @param orderDirection The direction for ordering the objects. - * - * @return A list with {@link FolderBrowserTableRow} objects for each object - * in the provided {@code folder} ordered by the provided field and - * in the provided direction. - */ - @Transactional(Transactional.TxType.REQUIRED) - List getObjectRows(final Folder folder, - final String orderBy, - final String orderDirection) { - return getObjectRows(folder, "%", orderBy, orderDirection, -1, -1); - } - - /** - * Create {@link FolderBrowserTableRow} objects for all objects in the - * provided folder which match provided filter term. - * - * @param folder The folder which contains the objects. - * @param filterTerm The filter term. - * @param orderBy The field used to order the objects. - * @param orderDirection The direction for ordering the objects. - * - * @return A list with {@link FolderBrowserTableRow} objects for each object - * in the provided {@code folder} which matches the provided - * {@code filterTerm}, ordered by the provided field and in the - * provided direction. - */ - @Transactional(Transactional.TxType.REQUIRED) - List getObjectRows(final Folder folder, - final String filterTerm, - final String orderBy, - final String orderDirection) { - return getObjectRows(folder, - filterTerm, - orderBy, - orderDirection, - -1, - -1); - } - - /** - * Create {@link FolderBrowserTableRow} objects for the objects in the - * provided folder which are in the range provided by {@code firstResult} - * and {@code maxResult} - * - * @param folder The folder which contains the objects. - * @param orderBy The field used to order the objects. - * @param orderDirection The direction for ordering the objects. - * @param firstResult The index of the first object to use. - * @param maxResults The maximum number of objects to retrieve. - * - * @return A list with {@link FolderBrowserTableRow} objects for each object - * in the provided {@code folder} ordered by the provided field and - * in the provided direction. The list will start with the object - * with index provided as {@code firstResult} and contain at most - * {@code maxResults} items. - */ - @Transactional(Transactional.TxType.REQUIRED) - List getObjectRows(final Folder folder, - final String orderBy, - final String orderDirection, - final int firstResult, - final int maxResults) { - return getObjectRows(folder, - "%", - orderBy, - orderDirection, - firstResult, - maxResults); - } - - /** - * Create {@link FolderBrowserTableRow} objects for the objects in the - * provided folder which match the provided filter term and which are in the - * range provided by {@code firstResult} and {@code maxResult} - * - * @param folder The folder which contains the objects. - * @param filterTerm The filter term. - * @param orderBy The field used to order the objects. - * @param orderDirection The direction for ordering the objects. - * @param firstResult The index of the first object to use. - * @param maxResults The maximum number of objects to retrieve. - * - * @return A list with {@link FolderBrowserTableRow} objects for each object - * in the provided {@code folder} which matches the provided - * {@code filterTerm}, ordered by the provided field and in the - * provided direction. The list will start with the object with - * index provided as {@code firstResult} and contain at most - * {@code maxResults} items. - */ - @Transactional(Transactional.TxType.REQUIRED) - List getObjectRows(final Folder folder, - final String filterTerm, - final String orderBy, - final String orderDirection, - final int firstResult, - final int maxResults) { - - final List objects = findObjectsInFolder(folder, - filterTerm, - orderBy, - orderDirection, - firstResult, - maxResults); - LOGGER.debug("Found {} objects for folder \"{}\".", - objects.size(), - folder.getDisplayName()); - - final List rows = objects - .stream() - .map(object -> buildRow(object)) - .collect(Collectors.toList()); - - return rows; - -// final List subFolders = findSubFolders(folder, -// filterTerm, -// orderBy, -// orderDirection, -// firstResult, -// maxResults); -// final List subFolderRows = subFolders -// .stream() -// .map(subFolder -> buildRow(subFolder)) -// .collect(Collectors.toList()); -// -// if (subFolders.size() >= maxResults) { -// return subFolderRows; -// } else { -// final int maxItems = maxResults - subFolders.size(); -// final int firstItem = firstResult - subFolders.size(); -// -// final List items = findItemsInFolder(folder, -// filterTerm, -// orderBy, -// orderDirection, -// firstItem, -// maxItems); -// final List itemRows = items.stream() -// .map(item -> buildRow(item)) -// .collect(Collectors.toList()); -// -// final List rows = new ArrayList<>(); -// rows.addAll(subFolderRows); -// rows.addAll(itemRows); -// -// return rows; -// } - } - - private FolderBrowserTableRow buildRow(final CcmObject object) { - - if (object instanceof Folder) { - return buildRow((Folder) object); - } else if(object instanceof ContentItem) { - return buildRow((ContentItem) object); - } else{ - throw new IllegalArgumentException( - "Only Folders and ContentItems are supported."); - } - } - - /** - * Helper method for building a {@link FolderBrowserTableRow} from a - * {@link Folder}. - * - * @param folder The {@link Folder} to use for building the - * {@link FolderBrowserTableRow}. - * - * @return A {@link FolderBrowserTableRow} containing the data needed by the - * {@link FolderBrowser} to display the provided {@code folder}. - */ - private FolderBrowserTableRow buildRow(final Folder folder) { - - final FolderBrowserTableRow row = new FolderBrowserTableRow(); - - row.setObjectId(folder.getObjectId()); - row.setObjectUuid(folder.getUuid()); - row.setName(folder.getName()); - row.setLanguages(Collections.emptyList()); - if (folder.getTitle().hasValue(globalizationHelper - .getNegotiatedLocale())) { - row.setTitle(folder.getTitle().getValue(globalizationHelper - .getNegotiatedLocale())); - } else { - row.setTitle(folder.getTitle().getValue(defaultLocale)); - } - row.setFolder(true); - row.setDeletable(!categoryManager.hasSubCategories(folder) - && !categoryManager.hasObjects(folder)); - - return row; - } - - /** - * Helper method for building a {@link FolderBrowserTableRow} from a - * {@link ContentItem}. - * - * @param item The {@link ContentItem} to use for building the - * {@link FolderBrowserTableRow}. - * - * @return A {@link FolderBrowserTableRow} containing the data needed by the - * {@link FolderBrowser} to display the provided {@code item}. - */ - private FolderBrowserTableRow buildRow(final ContentItem item) { - - final FolderBrowserTableRow row = new FolderBrowserTableRow(); - - final Locale negotiatedLocale = globalizationHelper - .getNegotiatedLocale(); - - row.setObjectId(item.getObjectId()); - row.setObjectUuid(item.getItemUuid()); - - if (item.getName().hasValue(negotiatedLocale)) { - row.setName(item.getName().getValue(negotiatedLocale)); - } else { - row.setName(item.getName().getValue(defaultLocale)); - } - final List languages = new ArrayList<>(itemL10NManager - .availableLanguages(item)); - languages.sort((lang1, lang2) -> lang1.toString().compareTo( - lang2.toString())); - row.setLanguages(languages); - if (item.getTitle().hasValue(negotiatedLocale)) { - row.setTitle(item.getTitle().getValue(negotiatedLocale)); - } else { - row.setTitle(item.getTitle().getValue(defaultLocale)); - } - final ContentType type = item.getContentType(); - final ContentTypeInfo typeInfo = typesManager.getContentTypeInfo( - type); - row.setTypeLabelBundle(typeInfo.getLabelBundle()); - row.setTypeLabelKey(typeInfo.getLabelKey()); - - row.setDeletable(!itemManager.isLive(item)); - - row.setCreated(item.getCreationDate()); - row.setLastModified(item.getLastModified()); - - row.setFolder(false); - - return row; - } - - /** - * Called by the {@link FolderBrowser} to delete an object. - * - * @param objectId - */ - @Transactional(Transactional.TxType.REQUIRED) - protected void deleteObject(final String objectId) { - - Objects.requireNonNull(objectId); - - if (objectId.startsWith("folder-")) { - final long folderId = Long.parseLong( - objectId.substring("folder-".length())); - - folderRepo - .findById(folderId) - .ifPresent(folderRepo::delete); - } else if (objectId.startsWith("item-")) { - final long itemId = Long.parseLong( - objectId.substring("item-".length())); - - itemRepo - .findById(itemId) - .ifPresent(itemRepo::delete); - } else { - throw new IllegalArgumentException( - "The objectId is expected to start with 'folder-' or 'item.'."); - } - } - - private List findObjectsInFolder(final Folder folder, - final String filterTerm, - final String orderBy, - final String orderDirection, - final int firstResult, - final int maxResults) { - - final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - - final CriteriaQuery criteriaQuery = builder - .createQuery(CcmObject.class); - final Root from = criteriaQuery.from(CcmObject.class); - criteriaQuery.select(from); - - final Subquery folderCriteriaQuery = criteriaQuery - .subquery(Folder.class); - final Root fromFolder = folderCriteriaQuery.from(Folder.class); - folderCriteriaQuery.select(fromFolder); - folderCriteriaQuery.where( - builder.and( - builder.equal(fromFolder.get("parentCategory"), folder), - builder.like(builder.lower(fromFolder.get("name")), - filterTerm))); - - final Subquery itemCriteriaQuery = criteriaQuery - .subquery(ContentItem.class); - final Root fromItem = itemCriteriaQuery - .from(ContentItem.class); - itemCriteriaQuery.select(fromItem); - final Join itemCategoryJoin = fromItem - .join("categories"); - itemCriteriaQuery.where(builder - .and( - builder.equal(itemCategoryJoin.get("category"), folder), - builder.equal(itemCategoryJoin.get("type"), - CmsConstants.CATEGORIZATION_TYPE_FOLDER), - builder.equal(fromItem.get("version"), - ContentItemVersion.DRAFT), - builder.like(builder.lower(fromItem.get("displayName")), - filterTerm))); - - criteriaQuery.where( - builder.or( - builder.in(from).value(folderCriteriaQuery), - builder.in(from).value(itemCriteriaQuery) - )); - - criteriaQuery.orderBy(builder.asc(from.get("displayName"))); - - final TypedQuery query = entityManager - .createQuery(criteriaQuery); - - if (maxResults > 0) { - query.setMaxResults(maxResults); - } - if (firstResult > 0) { - query.setFirstResult(firstResult); - } - - return query.getResultList(); - } - - /** - * Retrieves all subfolders of a folder matching the provided filter term. - * Because {@link Folder} does not have any of the fields despite the name - * which can be used to order the objects ordering is done as follows: - * - * If {@code orderBy} has any value other than - * {@link FolderBrowser#SORT_KEY_NAME} the subfolders are ordered in - * ascending order by their name. If {@code orderBy} is - * {@link FolderBrowser#SORT_KEY_NAME} the subfolders are ordered by their - * name in ascending and descending order depending on the value of - * {@code orderDirection}. - * - * @param folder The folder which contains the subfolders. - * @param filterTerm The filter term. - * @param orderBy Field to use for ordering. If the value is negative - * the parameter is ignored. - * @param orderDirection Direction for ordering. If the value is negative - * the parameter is ignored. - * @param firstResult Index of the first result to retrieve. - * @param maxResults Maxium number of results to retrieve. - * - * - * @return A list of the subfolders of the provided {@code folder} which - * match the provided {@code filterTerm}. The list is ordered as - * described above. The list will contain at most {@code maxResults} - * starting with the result with the index provided as - * {@code firstResult}. - */ - private List findSubFolders(final Folder folder, - final String filterTerm, - final String orderBy, - final String orderDirection, - final int firstResult, - final int maxResults) { - - final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - - final CriteriaQuery criteria = builder - .createQuery(Folder.class); - final Root from = criteria.from(Folder.class); - - final Order order; - if (FolderBrowser.SORT_KEY_NAME.equals(orderBy) - && FolderBrowser.SORT_ACTION_DOWN.equals(orderDirection)) { - order = builder.desc(from.get("name")); - } else { - order = builder.asc(from.get("name")); - } - - final TypedQuery query = entityManager - .createQuery( - criteria.where( - builder.and( - builder.equal(from.get("parentCategory"), folder), - builder - .like(builder.lower(from.get("name")), - filterTerm) - ) - ) - .orderBy(order) - ); - - if (firstResult >= 0) { - query.setFirstResult(firstResult); - } - if (maxResults >= 0) { - query.setMaxResults(maxResults); - } - - return query.getResultList(); - } - - /** - * Retrieves all items of a folder matching the provided filter term. - * - * @param folder The folder which contains the subfolders. - * @param filterTerm The filter term. - * @param orderBy Field to use for ordering. If the value is negative - * the parameter is ignored. - * @param orderDirection Direction for ordering. If the value is negative - * the parameter is ignored. - * @param firstResult Index of the first result to retrieve. - * @param maxResults Maxium number of results to retrieve. - * - * - * @return A list of the subfolders of the provided {@code folder} which - * match the provided {@code filterTerm}. The list is ordered the - * field provided as {@code orderBy} in the direction provided by - * {@code orderDirection}. The list will contain at most - * {@code maxResults} starting with the result with the index - * provided as {@code firstResult}. - */ - private List findItemsInFolder(final Folder folder, - final String filterTerm, - final String orderBy, - final String orderDirection, - final int firstResult, - final int maxResults) { - - final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - - final CriteriaQuery criteria = builder - .createQuery(ContentItem.class); - final Root fromItem = criteria.from(ContentItem.class); - final Join join = fromItem - .join("categories"); - - final Path orderPath; - switch (orderBy) { - case FolderBrowser.SORT_KEY_NAME: - orderPath = fromItem.get("displayName"); - break; - case FolderBrowser.SORT_KEY_CREATION_DATE: - orderPath = fromItem.get("creationDate"); - break; - case FolderBrowser.SORT_KEY_LAST_MODIFIED_DATE: - orderPath = fromItem.get("lastModifed"); - break; - default: - orderPath = fromItem.get("displayName"); - break; - } - - final Order order; - if (FolderBrowser.SORT_ACTION_DOWN.equals(orderDirection)) { - order = builder.desc(orderPath); - } else { - order = builder.asc(orderPath); - } - - final TypedQuery query = entityManager - .createQuery( - criteria.select(fromItem) - .where( - builder.and( - builder.equal(join.get("category"), folder), - builder.equal(join.get("type"), - CmsConstants.CATEGORIZATION_TYPE_FOLDER), - builder.equal(fromItem.get("version"), - ContentItemVersion.DRAFT), - builder.like(builder.lower(fromItem.get( - "displayName")), - filterTerm) - ) - ) - .orderBy(order) - ); - - if (firstResult >= 0) { - query.setFirstResult(firstResult); - } - if (maxResults >= 0) { - query.setMaxResults(maxResults); - } - - return query.getResultList(); - } - - /** - * Check if a folder or its subfolders contains at least one live item. - * - * @param folder The folder to check for live items. - * - * @return {@code true} if the {@code folder} or on of its subfolders - * contains at least one live item, {@code false} otherwise. - */ - @Transactional(Transactional.TxType.REQUIRED) - public boolean hasLiveItems(final Folder folder) { - - Objects.requireNonNull(folder, - "Folder to check for live items can't be null."); - - //Ensure that we use an non detached entity. - final Folder theFolder = folderRepo.findById(folder.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No folder with id %s in the database. Where did that ID come from?", - folder.getObjectId()))); - - final boolean hasLiveItem = theFolder.getObjects() - .stream() - .map(categorization -> categorization.getCategorizedObject()) - .filter(object -> object instanceof ContentItem) - .map(object -> (ContentItem) object) - .filter(item -> itemManager.isLive(item)) - .anyMatch(item -> itemManager.isLive(item)); - - if (hasLiveItem) { - return true; - } else { - return theFolder.getSubFolders() - .stream() - .anyMatch(currentFolder -> hasLiveItems(currentFolder)); - } - } - - /** - * Get the IDs of the folders invalid for copy/move actions. - * - * @param sources - * - * @return - */ - @Transactional(Transactional.TxType.REQUIRED) - public List createInvalidTargetsList(final List sources) { - - Objects.requireNonNull(sources); - - final List sourceFolderIds = sources - .stream() - .filter(source -> source.startsWith( - FOLDER_BROWSER_KEY_PREFIX_FOLDER)) - .collect(Collectors.toList()); - final List parentFolderIds = sourceFolderIds - .stream() - .map(sourceFolderId -> findParentFolderId(sourceFolderId)) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toList()); - final List> subFolderIds = sourceFolderIds - .stream() - .map(sourceFolderId -> findSubFolderIds(sourceFolderId)) - .collect(Collectors.toList()); - - final List invalidTargetIds = new ArrayList<>(); - invalidTargetIds.addAll(sourceFolderIds); - invalidTargetIds.addAll(parentFolderIds); - for (final List subFolderIdList : subFolderIds) { - invalidTargetIds.addAll(subFolderIdList); - } - - return invalidTargetIds; - } - - private Optional findParentFolderId(final String folderId) { - - Objects.requireNonNull(folderId); - - if (!folderId.startsWith(FOLDER_BROWSER_KEY_PREFIX_FOLDER)) { - throw new IllegalArgumentException(String.format( - "Provided string '%s' is not an ID of a folder.", - folderId)); - } - - final long objectId = Long.parseLong(folderId.substring( - FOLDER_BROWSER_KEY_PREFIX_FOLDER.length())); - final Folder folder = folderRepo.findById(objectId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No folder with ID %d found in database. " - + "Where did that ID come form?", - objectId))); - final Optional parentFolder = folderManager.getParentFolder( - folder); - if (parentFolder.isPresent()) { - return Optional.empty(); - } else { - return Optional.ofNullable(String.format( - "%s%d", - FOLDER_BROWSER_KEY_PREFIX_FOLDER, - parentFolder.get().getObjectId())); - } - } - - private List findSubFolderIds(final String folderId) { - - Objects.requireNonNull(folderId); - - if (!folderId.startsWith(FOLDER_BROWSER_KEY_PREFIX_FOLDER)) { - throw new IllegalArgumentException(String.format( - "Provided string '%s' is not the ID of a folder.", - folderId)); - } - - final long objectId = Long.parseLong(folderId.substring( - FOLDER_BROWSER_KEY_PREFIX_FOLDER.length())); - final Folder folder = folderRepo.findById(objectId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No folder with ID %d found in database. " - + "Where did that ID come form?", - objectId))); - return findSubFolders(folder) - .stream() - .map(subFolder -> String.format("%s%d", - FOLDER_BROWSER_KEY_PREFIX_FOLDER, - subFolder.getObjectId())) - .collect(Collectors.toList()); - } - - private List findSubFolders(final Folder folder) { - - Objects.requireNonNull(folder); - - if (folder.getSubFolders() == null - || folder.getSubFolders().isEmpty()) { - return Collections.emptyList(); - } - - final List subFolders = new ArrayList<>(); - for (final Folder subFolder : folder.getSubFolders()) { - subFolders.add(subFolder); - subFolders.addAll(findSubFolders(subFolder)); - } - - return subFolders; - } - - @Transactional(Transactional.TxType.REQUIRED) - public void moveObjects(final Folder targetFolder, - final String[] objectIds) { - - Objects.requireNonNull(targetFolder); - Objects.requireNonNull(objectIds); - - for (final String objectId : objectIds) { - if (objectId.startsWith(FOLDER_BROWSER_KEY_PREFIX_FOLDER)) { - moveFolder(targetFolder, - Long.parseLong(objectId.substring( - FOLDER_BROWSER_KEY_PREFIX_FOLDER.length()))); - } else if (objectId.startsWith(FOLDER_BROWSER_KEY_PREFIX_ITEM)) { - moveItem(targetFolder, - Long.parseLong(objectId.substring( - FOLDER_BROWSER_KEY_PREFIX_ITEM.length()))); - } else { - throw new IllegalArgumentException(String.format( - "ID '%s' does not start with '%s' or '%s'.", - objectId, - FOLDER_BROWSER_KEY_PREFIX_FOLDER, - FOLDER_BROWSER_KEY_PREFIX_ITEM)); - } - } - } - - private void moveFolder(final Folder targetFolder, final long folderId) { - - Objects.requireNonNull(targetFolder); - - final Folder folder = folderRepo.findById(folderId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No folder with ID %d in the database. " - + "Where did that ID come from?", - folderId))); - - folderManager.moveFolder(folder, targetFolder); - } - - private void moveItem(final Folder targetFolder, final long itemId) { - - Objects.requireNonNull(targetFolder); - - final ContentItem item = itemRepo - .findById(itemId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No content item with ID %d in the database. " - + "Where did that ID come from?", - itemId))); - - itemManager.move(item, targetFolder); - } - - @Transactional(Transactional.TxType.REQUIRED) - public void copyObjects(final Folder targetFolder, - final String[] objectIds) { - - Objects.requireNonNull(targetFolder); - Objects.requireNonNull(objectIds); - - for (final String objectId : objectIds) { - if (objectId.startsWith(FOLDER_BROWSER_KEY_PREFIX_FOLDER)) { - copyFolder(targetFolder, - Long.parseLong(objectId.substring( - FOLDER_BROWSER_KEY_PREFIX_FOLDER.length()))); - } else if (objectId.startsWith(FOLDER_BROWSER_KEY_PREFIX_ITEM)) { - copyItem(targetFolder, - Long.parseLong(objectId.substring( - FOLDER_BROWSER_KEY_PREFIX_ITEM.length()))); - } else { - throw new IllegalArgumentException(String.format( - "ID '%s' does not start with '%s' or '%s'.", - objectId, - FOLDER_BROWSER_KEY_PREFIX_FOLDER, - FOLDER_BROWSER_KEY_PREFIX_ITEM)); - } - } - } - - private void copyFolder(final Folder targetFolder, - final long folderId) { - - Objects.requireNonNull(targetFolder); - - final Folder folder = folderRepo.findById(folderId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No folder with ID %d in the database. " - + "Where did that ID come from?", - folderId))); - - folderManager.copyFolder(folder, targetFolder); - } - - private void copyItem(final Folder targetFolder, - final long itemId) { - - Objects.requireNonNull(targetFolder); - - final ContentItem item = itemRepo - .findById(itemId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No content item with ID %d in the database. " - + "Where did that ID come from?", - itemId))); - - itemManager.copy(item, targetFolder); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserFilterFormModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserFilterFormModelBuilder.java deleted file mode 100644 index 557c6c112..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserFilterFormModelBuilder.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.PageState; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.Folder; - -/** - * - * @author Jens Pelzetter - */ -class FolderBrowserFilterFormModelBuilder - implements FolderManipulator.FilterFormModelBuilder{ - - private final FolderBrowser folderBrowser; - - public FolderBrowserFilterFormModelBuilder(final FolderBrowser folderBrowser) { - this.folderBrowser = folderBrowser; - } - - @Override - public long getFolderSize(final PageState state) { - final FolderSelectionModel folderSelectionModel = folderBrowser - .getFolderSelectionModel(); - final Folder folder = folderSelectionModel.getSelectedObject(state); - if (folder == null) { - return 0; - } else { - folderBrowser.getRowSelectionModel().clearSelection(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderBrowserController controller = cdiUtil.findBean( - FolderBrowserController.class); - final String filter = folderBrowser.getFilter(state); - final String atozFilter = folderBrowser.getAtoZfilter(state); - - final String filterTerm; - if (filter != null && !filter.trim().isEmpty()) { - filterTerm = filter.trim(); - } else if (atozFilter != null && !atozFilter.trim().isEmpty()) { - filterTerm = atozFilter.trim(); - } else { - filterTerm = null; - } - - if (filterTerm == null) { - return controller.countObjects(folder); - } else { - return controller.countObjects(folder); - } - } - } - - - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserPaginationModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserPaginationModelBuilder.java deleted file mode 100644 index 9e91909f8..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserPaginationModelBuilder.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.PaginationModelBuilder; -import com.arsdigita.bebop.Paginator; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.Folder; - -/** - * - * @author Jens Pelzetter - */ -class FolderBrowserPaginationModelBuilder implements PaginationModelBuilder { - - private final FolderBrowser folderBrowser; - - public FolderBrowserPaginationModelBuilder(final FolderBrowser folderBrowser) { - this.folderBrowser = folderBrowser; - } - - @Override - public int getTotalSize(final Paginator paginator, final PageState state) { - - final FolderSelectionModel folderSelectionModel = folderBrowser - .getFolderSelectionModel(); - final Folder folder = folderSelectionModel.getSelectedObject(state); - if (folder == null) { - return 0; - } else { - folderBrowser.getRowSelectionModel().clearSelection(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderBrowserController controller = cdiUtil.findBean( - FolderBrowserController.class); - final String filter = folderBrowser.getFilter(state); - final String atozFilter = folderBrowser.getAtoZfilter(state); - final int first = paginator.getFirst(state); - final int pageSize = paginator.getPageSize(state); - - final String filterTerm; - if (filter != null && !filter.trim().isEmpty()) { - filterTerm = filter.trim(); - } else if (atozFilter != null && !atozFilter.trim().isEmpty()) { - filterTerm = atozFilter.trim(); - } else { - filterTerm = null; - } - - if (filterTerm == null) { - return (int) controller.countObjects(folder); - } else { - return (int) controller.countObjects(folder, - filter); - } - } - } - - @Override - public boolean isVisible(final PageState state) { - return folderBrowser != null && folderBrowser.isVisible(state); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserTableModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserTableModel.java deleted file mode 100644 index a5a67f53b..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserTableModel.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; - -import java.util.Iterator; -import java.util.List; - - -/** - * Table model for the {@link FolderBrowser}. - * - * @see {FolderBrowserTableModelBuilder} - * - * @author Jens Pelzetter - */ -class FolderBrowserTableModel implements TableModel { - - private static final int COL_NAME = 0; - private static final int COL_LANGUAGES = 1; - private static final int COL_TITLE = 2; - private static final int COL_TYPE = 3; - private static final int COL_CREATION_DATE = 4; - private static final int COL_LAST_MODIFIED = 5; - private static final int COL_DELETEABLE = 6; - - private final Iterator iterator; - private FolderBrowserTableRow currentRow; - - public FolderBrowserTableModel(final List rows) { - iterator = rows.iterator(); - } - - @Override - public int getColumnCount() { - return 7; - } - - @Override - public boolean nextRow() { - if (iterator.hasNext()) { - currentRow = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - switch (columnIndex) { - case COL_NAME: - return currentRow.getName(); - case COL_LANGUAGES: - return currentRow.getLanguages(); - case COL_TITLE: - return currentRow.getTitle(); - case COL_TYPE: - final String typeLabelBundle = currentRow.getTypeLabelBundle(); - final String typeLabelKey = currentRow.getTypeLabelKey(); - if (typeLabelKey == null) { - return new GlobalizedMessage("empty_text", - CmsConstants.CMS_BUNDLE); - } else { - return new GlobalizedMessage(typeLabelKey, typeLabelBundle); - } - case COL_CREATION_DATE: - return currentRow.getCreated(); - case COL_LAST_MODIFIED: - return currentRow.getLastModified(); - case COL_DELETEABLE: - return currentRow.isDeletable(); - default: - throw new IllegalArgumentException(String.format( - "Illegal column index %d.", columnIndex)); - } - } - - @Override - public Object getKeyAt(final int columnIndex) { - if (currentRow.isFolder()) { - return String.format("folder-%d", currentRow.getObjectId()); - } else { - return String.format("item-%d", currentRow.getObjectId()); - } - - -// return currentRow.getObjectId(); - } - - public boolean isFolder() { - return currentRow.isFolder(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserTableModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserTableModelBuilder.java deleted file mode 100644 index 9ac9fb939..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserTableModelBuilder.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Paginator; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.util.LockableImpl; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.Folder; - -import java.util.List; - -/** - * Creates the {@link TableModel} for the {@link FolderBrowser}. - * - * @author Jens Pelzetter - */ -class FolderBrowserTableModelBuilder - extends LockableImpl - implements TableModelBuilder { - - private final static Logger LOGGER = LogManager.getLogger( - FolderBrowserTableModelBuilder.class); - - @Override - public TableModel makeModel(final Table table, - final PageState state) { - if (!(table instanceof FolderBrowser)) { - throw new IllegalArgumentException( - "The FolderBrowserTableModelBuilder can only be used for the " - + "FolderBrowser."); - } - final FolderBrowser folderBrowser = (FolderBrowser) table; - final FolderSelectionModel folderSelectionModel = folderBrowser - .getFolderSelectionModel(); - final Folder folder = folderSelectionModel.getSelectedObject(state); - if (folder == null) { - return Table.EMPTY_MODEL; - } else { - folderBrowser.getRowSelectionModel().clearSelection(state); - final Paginator paginator = folderBrowser.getPaginator(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderBrowserController controller = cdiUtil - .findBean(FolderBrowserController.class); - final String filter = folderBrowser.getFilter(state); - final String orderBy; - if (folderBrowser.getSortType(state) == null) { - orderBy = FolderBrowser.SORT_KEY_NAME; - } else { - orderBy = folderBrowser.getSortType(state); - } - final String orderDirection; - if (folderBrowser.getSortDirection(state) == null) { - orderDirection = FolderBrowser.SORT_ACTION_UP; - } else { - orderDirection = folderBrowser.getSortDirection(state); - } - final String atozFilter = folderBrowser.getAtoZfilter(state); - final int first = paginator.getFirst(state); - final int pageSize = paginator.getPageSize(state); - - final String filterTerm; - if (filter != null && !filter.trim().isEmpty()) { - filterTerm = String.format("%s%%", filter.trim()); - } else if (atozFilter != null && !atozFilter.trim().isEmpty()) { - filterTerm = String.format("%s%%", atozFilter.trim()); - } else { - filterTerm = null; - } - - final long start = System.currentTimeMillis(); - LOGGER.debug("Retrieving table rows..."); - final List rows; - if (filterTerm == null) { - rows = controller.getObjectRows(folder, - orderBy, - orderDirection, - first - 1, - pageSize); - } else { - rows = controller.getObjectRows(folder, - filterTerm, - orderBy, - orderDirection, - first - 1, - pageSize); - } - - LOGGER.debug("Retrieve table rows in {} ms.", - System.currentTimeMillis() - start); - return new FolderBrowserTableModel(rows); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserTableRow.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserTableRow.java deleted file mode 100644 index bcf58b128..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderBrowserTableRow.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.folder; - -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Locale; - -/** - * A simple data transfer object containing the data required by the - * {@link FolderBrowser} to display its rows. Used by the - * {@link FolderBrowserTableModelBuilder} to transfer the data from the - * {@link FolderBrowserController} to the {@link FolderBrowserTableModel}. - * - * @author Jens Pelzetter - */ -class FolderBrowserTableRow { - - private long objectId; - private String objectUuid; - private String name; - private List languages; - private String title; - private String typeLabelBundle; - private String typeLabelKey; - private Date created; - private Date lastModified; - private boolean deletable; - private boolean folder; - - public long getObjectId() { - return objectId; - } - - protected void setObjectId(final long objectId) { - this.objectId = objectId; - } - - public String getObjectUuid() { - return objectUuid; - } - - protected void setObjectUuid(final String objectUuid) { - this.objectUuid = objectUuid; - } - - public String getName() { - return name; - } - - protected void setName(String name) { - this.name = name; - } - - public List getLanguages() { - return Collections.unmodifiableList(languages); - } - - protected void setLanguages(final List languages) { - this.languages = languages; - } - - public String getTitle() { - return title; - } - - protected void setTitle(final String title) { - this.title = title; - } - - public String getTypeLabelBundle() { - return typeLabelBundle; - } - - protected void setTypeLabelBundle(final String typeLabelBundle) { - this.typeLabelBundle = typeLabelBundle; - } - - public String getTypeLabelKey() { - return typeLabelKey; - } - - protected void setTypeLabelKey(final String typeLabelKey) { - this.typeLabelKey = typeLabelKey; - } - - public Date getCreated() { - if (created == null) { - return null; - } else { - return new Date(created.getTime()); - } - } - - protected void setCreated(final Date created) { - if (created == null) { - this.created = null; - } else { - this.created = new Date(created.getTime()); - } - } - - public Date getLastModified() { - if (lastModified == null) { - return null; - } else { - return new Date(lastModified.getTime()); - } - } - - protected void setLastModified(final Date lastModified) { - if (lastModified == null) { - this.lastModified = null; - } else { - this.lastModified = new Date(lastModified.getTime()); - } - } - - public boolean isDeletable() { - return deletable; - } - - protected void setDeletable(final boolean deletable) { - this.deletable = deletable; - } - - public boolean isFolder() { - return folder; - } - - protected void setFolder(final boolean folder) { - this.folder = folder; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderCreateForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderCreateForm.java deleted file mode 100755 index 8495d2d27..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderCreateForm.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.categorization.CategoryManager; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.librecms.CmsConstants; -import org.librecms.contentsection.Folder; -import org.librecms.contentsection.FolderManager; -import org.librecms.contentsection.FolderRepository; - -import static com.arsdigita.cms.ui.folder.FolderForm.*; - -public class FolderCreateForm extends FolderForm { - - public FolderCreateForm(final String name, final FolderSelectionModel parent) { - super(name, parent); - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - final PageState state = event.getPageState(); - final FolderSelectionModel model = getFolderSelectionModel(); - } - - /** - * Validates the form. Checks for name uniqueness. - * - * @param event - * @throws com.arsdigita.bebop.FormProcessException - * - */ - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - - final Folder folder = getCurrentFolder(event.getPageState()); - final FormData data = event.getFormData(); - final String name = data.getString(NAME); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager categoryManager = cdiUtil.findBean( - CategoryManager.class); - - if (categoryManager.hasSubCategoryWithName(folder, name)) { - data.addError(new GlobalizedMessage( - "cms.ui.folderform.error.child.name_not_unique", - CmsConstants.CMS_BUNDLE, - new Object[]{name})); - } - - } - - @Override - public void process(final FormSectionEvent event) throws - FormProcessException { - - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - final Folder parent = getCurrentFolder(state); - - final String name = data.getString(NAME); - final String title = data.getString(TITLE); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderRepository folderRepo = cdiUtil.findBean( - FolderRepository.class); - final FolderManager folderManager = cdiUtil - .findBean(FolderManager.class); - final ConfigurationManager confManager = cdiUtil.findBean( - ConfigurationManager.class); - final KernelConfig kernelConfig = confManager.findConfiguration( - KernelConfig.class); - - final Folder folder = folderManager.createFolder(name, parent); - folder.getTitle().putValue(kernelConfig.getDefaultLocale(), title); - folderRepo.save(folder); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderEditForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderEditForm.java deleted file mode 100755 index 99cd04a80..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderEditForm.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.FolderManager; - -class FolderEditForm extends FolderBaseForm { - - private static Logger LOGGER = LogManager.getLogger(FolderEditForm.class); - - private final FolderRequestLocal folderRequestLocal; - - public FolderEditForm(final FolderRequestLocal folder) { - super("folder-edit"); - - folderRequestLocal = folder; - - // XXX need to do name uniqueness valdation on m_fragment here - // as well. - - addInitListener(new InitListener()); - addProcessListener(new ProcessListener()); - } - - private static FolderRequestLocal parent(final FolderRequestLocal folder) { - final FolderRequestLocal parent = new FolderRequestLocal(null) { - @Override - protected final Object initialValue(final PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderManager folderManager = cdiUtil.findBean( - FolderManager.class); - return folderManager.getParentFolder(getFolder(state)) - .orElse(null); - } - }; - - return parent; - } - - private class InitListener implements FormInitListener { - public final void init(final FormSectionEvent e) { - final PageState state = e.getPageState(); - - final Category folder = folderRequestLocal.getFolder(state); - - m_title.setValue(state, folder.getDisplayName()); - m_fragment.setValue(state, folder.getName()); - } - } - - private class ProcessListener implements FormProcessListener { - public final void process(final FormSectionEvent e) - throws FormProcessException { - final PageState state = e.getPageState(); - - final Category folder = folderRequestLocal.getFolder(state); - - folder.setDisplayName((String) m_title.getValue(state)); - folder.setName((String) m_fragment.getValue(state)); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryRepository categoryRepo = cdiUtil.findBean(CategoryRepository.class); - categoryRepo.save(folder); - } - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderEditorForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderEditorForm.java deleted file mode 100755 index 16de2c954..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderEditorForm.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.librecms.CmsConstants; -import org.librecms.contentsection.Folder; - -import static com.arsdigita.cms.ui.folder.FolderForm.*; - -/** - * Implements functionality for renaming a folder. Most code taken from - * FolderCreator. Need to refactor out base functionality of FolderEditorForm & - * Creator. - * - * @author Jon Orris - * @author Jens >Pelzetter - * - */ -public class FolderEditorForm extends FolderForm { - - public FolderEditorForm(final String name, final FolderSelectionModel folder) { - super(name, folder); - } - - /** - * Initialise the form with name & label of folder being edited. - * - * @param event - * - * @throws com.arsdigita.bebop.FormProcessException - */ - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - final Folder folder = getCurrentFolder(state); - data.put(NAME, folder.getName()); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderEditorFormController controller = cdiUtil.findBean( - FolderEditorFormController.class - ); - data.put(TITLE, controller.getFolderTitle(folder)); - } - - /** - * Validates the form. Checks for name uniqueness. - * - * @param event - * - * @throws com.arsdigita.bebop.FormProcessException - */ - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - final Category folder = getCurrentFolder(event.getPageState()) - .getParentCategory(); - final FormData data = event.getFormData(); - final String name = data.getString(NAME); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager categoryManager = cdiUtil.findBean( - CategoryManager.class); - - if (categoryManager.hasSubCategoryWithName(folder, name)) { - data.addError(new GlobalizedMessage( - "cms.ui.folderform.error.parent.name_not_unique", - CmsConstants.CMS_BUNDLE, - new Object[]{name})); - } - - } - - @Override - public void process(final FormSectionEvent event) throws - FormProcessException { - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - final Folder folder = getCurrentFolder(state); - - updateFolder(folder, (String) data.get(NAME), (String) data.get(TITLE)); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderEditorFormController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderEditorFormController.java deleted file mode 100644 index 86a7040b9..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderEditorFormController.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.ui.folder; - -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.configuration.ConfigurationManager; -import org.librecms.contentsection.Folder; -import org.librecms.contentsection.FolderRepository; - -import java.util.Objects; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -public class FolderEditorFormController { - - @Inject - private ConfigurationManager confManager; - - @Inject - private FolderRepository folderRepository; - - @Transactional(Transactional.TxType.REQUIRED) - public String getFolderTitle(final Folder ofFolder) { - final Folder folder = folderRepository - .findById(Objects.requireNonNull(ofFolder).getObjectId()) - .orElseThrow( - () -> new IllegalArgumentException( - String.format("No folder with ID %d available.", - ofFolder.getObjectId()) - ) - ); - - final KernelConfig kernelConfig = confManager.findConfiguration( - KernelConfig.class - ); - return folder.getTitle().getValue(kernelConfig.getDefaultLocale()); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderForm.java deleted file mode 100755 index f78943749..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderForm.java +++ /dev/null @@ -1,413 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.FormSection; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.form.Hidden; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.NotNullValidationListener; -import com.arsdigita.bebop.parameters.TrimmedStringParameter; -import com.arsdigita.bebop.parameters.URLTokenValidationListener; -import com.arsdigita.cms.ui.authoring.BasicItemForm; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.util.Assert; -import com.arsdigita.web.Web; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.CmsConstants; -import org.librecms.contentsection.Folder; -import org.librecms.contentsection.FolderManager; - -/** - * Class FolderForm implements the basic form for creating or editing folders. - * - * Originally folders were ContentItems. For CCM NG we changed that and now use - * Categories to provide the folder hierarchy. Thus this class originally - * extended the {@link BasicItemForm} class. Now this class is separate. Some - * parts have been created by simply coping the relevant parts from - * {@link BasicItemForm}. Therefore it is possible that comments etc still refer - * to {@link BasicItemForm}. - * - * @author Jon Orris - * @author Jens Pelzetter - */ -public abstract class FolderForm extends Form implements FormInitListener, - FormProcessListener, - FormValidationListener { - - public static final Logger LOGGER = LogManager.getLogger(FolderForm.class); - - public static final String FOLDER_ID = "FolderId"; - public static final String NAME = "FolderName"; - public static final String TITLE = "FolderTitle"; - public static final String DESC = "FolderDesc"; - - private final FolderSelectionModel currentFolder; - private final SaveCancelSection saveCancelSection; -// private final FormSection widgetSection; - -// /** -// * Currently, to insert javascript code the Label Widget is "abused". -// */ -// private final Label m_script = new Label(String.format( -// "", -// Web.getWebappContextPath()), -// false); - /** - * Create a new folder form. - * - * @param formName Name of the form - * @param currentFolder SelectionModel containing the current folder being - * operated on. - * - * @pre name != null && folder != null - */ - public FolderForm(final String formName, - final FolderSelectionModel currentFolder) { - super(formName, new ColumnPanel(2)); - -// widgetSection = new FormSection(new ColumnPanel(2, true)); -// super.add(widgetSection, ColumnPanel.INSERT); - this.currentFolder = currentFolder; - - final ColumnPanel panel = (ColumnPanel) getPanel(); - panel.setBorder(false); - panel.setPadColor("#FFFFFF"); - panel.setColumnWidth(1, "20%"); - panel.setColumnWidth(2, "80%"); - panel.setWidth("100%"); - - /* Add basic contents */ - addWidgets(); - - saveCancelSection = new SaveCancelSection(); - super.add(saveCancelSection, - ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - - addInitListener(this); - addProcessListener(this); - addValidationListener(this); - } - - /** - * Constructs a new {@code FolderForm} with a specified number of - * {@link ColumnPanel}s and without content. - * - * @param formName - * @param columnPanel - * @param currentFolder - */ - public FolderForm(final String formName, - final ColumnPanel columnPanel, - final FolderSelectionModel currentFolder) { - super(formName, columnPanel); - -// widgetSection = new FormSection( -// new ColumnPanel(columnPanel.getNumCols())); -// super.add(widgetSection, ColumnPanel.INSERT); - this.currentFolder = currentFolder; - - saveCancelSection = new SaveCancelSection(); - super.add(saveCancelSection, - ColumnPanel.FULL_WIDTH | ColumnPanel.LEFT); - } - - /** - * Add basic widgets to the form. - * - * Widgets added are 'title' and 'name (url)'. Child classes will override - * this method to perform all their widget-adding needs but are supposed to - * use super() to add the basic widgets. - */ - protected void addWidgets() { - final Hidden id = new Hidden(FOLDER_ID); - add(id); - - // JavaScript auto-name generation is off by default. - // It is turned on under the following circumstances - // - // * If the name is null, upon starting edit of the title - // * If the name is null, upon finishing edit of name - // - // The rationale is that, auto-name generation is useful - // if the name is currently null, but once a name has been - // created you don't want to subsequently change it since - // it breaks URLs & potentially overwrites the user's - // customizations. - final TextField titleWidget = new TextField(new TrimmedStringParameter( - TITLE)); - titleWidget.setLabel(getTitleLabel()); - titleWidget.setHint(getTitleHint()); - titleWidget.addValidationListener(new NotNullValidationListener()); - titleWidget.setOnFocus("if (this.form." + NAME + ".value == '') { " - + " defaulting = true; this.form." + NAME - + ".value = urlize(this.value); }"); - titleWidget.setOnKeyUp( - "if (defaulting) { this.form." + NAME - + ".value = urlize(this.value) }"); - add(titleWidget); - - final TextField nameWidget = new TextField(new TrimmedStringParameter( - NAME)); - nameWidget.setLabel(getNameLabel()); - nameWidget.setHint(getNameHint()); - - // We just check parameter specific properties here! Additionally, - // context properties as uniqueness in folder must be validated - // for the form es the whole (using the validate method required by - // implementing FormValidationListener in this form. - nameWidget.addValidationListener(new NotNullValidationListener()); - nameWidget.addValidationListener(new URLTokenValidationListener()); - nameWidget.setMaxLength(190); - nameWidget.setOnFocus("defaulting = false"); - nameWidget.setOnBlur( - "if (this.value == '') " - + "{ defaulting = true; this.value = urlize(this.form." - + TITLE - + ".value) } " - + " else { this.value = urlize(this.value); }"); - add(nameWidget); - } - - @Override - public void register(final Page page) { - super.register(page); - page.addComponentStateParam(this, currentFolder.getStateParameter()); - } - - @Override - public void generateXML(final PageState state, final Element parent) { -// m_script.generateXML(state, parent); - super.generateXML(state, parent); - } - - /** - * Perform form initialisation. Children should override this this method to - * pre-fill the widgets with data, instantiate the content item, etc. - * - * @param event - * - * @throws FormProcessException - */ - @Override - public abstract void init(final FormSectionEvent event) - throws FormProcessException; - - /** - * Process the form. Children have to override this method to save the - * user's changes to the database. - * - * @param event - * - * @throws FormProcessException - */ - @Override - public abstract void process(final FormSectionEvent event) - throws FormProcessException; - - /** - * Validates the form. Checks for name uniqueness. - * - * @param event - * - * @throws com.arsdigita.bebop.FormProcessException - */ - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - final Folder folder = getCurrentFolder(event.getPageState()); - final FormData data = event.getFormData(); - final String name = data.getString(NAME); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager categoryManager = cdiUtil.findBean( - CategoryManager.class); - - if (categoryManager.hasSubCategoryWithName(folder, name)) { - data.addError(new GlobalizedMessage( - "cms.ui.folderform.error.child.name_not_unique", - CmsConstants.CMS_BUNDLE, - new Object[]{name})); - } - - } - - /** - * Adds a component to this container. - * - * @param component the component to add to this FolderForm - * - */ -// @Override -// public void add(final Component component) { -// widgetSection.add(component); -// } - /** - * Adds a component with the specified layout constraints to this container. - * Layout constraints are defined in each layout container as static ints. - * Use a bitwise OR to specify multiple constraints. - * - * @param component the component to add to this container - * @param constraints layout constraints (a bitwise OR of static ints in the - * particular layout) - */ -// @Override -// public void add(final Component component, final int constraints) { -// widgetSection.add(component, constraints); -// } - /** - * This method can be overridden to change the label of the title field. To - * change to label of the title field can be useful for some content types. - * For example, for an organization the label "Title" for the field may be - * confusing for the normal user. For such a content type, the label would - * be changed to something like "Name of the organization". - * - * @return (Content for the) Label for the title field as string - */ - protected GlobalizedMessage getTitleLabel() { - return new GlobalizedMessage("cms.contenttypes.ui.title", - CmsConstants.CMS_BUNDLE); - } - - /** - * Provides the text for the user hint providing some detailed information - * how to use this widget. This method can be overwritten to adjust the text - * for some content types. {@link #getTitleLabel()} - * - * @return - */ - protected GlobalizedMessage getTitleHint() { - return new GlobalizedMessage("cms.contenttypes.ui.title_hint", - CmsConstants.CMS_BUNDLE); - } - - /** - * This method does the same as {@link #getTitleLabel() } for the labe l of - * the name (URL) field. - * - * @return (Content for the) Label for the name field as string - */ - protected GlobalizedMessage getNameLabel() { - return new GlobalizedMessage("cms.contenttypes.ui.name", - CmsConstants.CMS_BUNDLE); - } - - /** - * Provides the text for the user hint providing some detailed information - * how to use this widget. This method can be overwritten to adjust the text - * for some content types. {@link #getNameLabel()} - * - * @return - */ - protected GlobalizedMessage getNameHint() { - return new GlobalizedMessage("cms.contenttypes.ui.name_hint", - CmsConstants.CMS_BUNDLE); - } - - /** - * Returns true if the form submission was cancelled. - * - * @param state - * - * @return - */ - public boolean isCancelled(final PageState state) { - return saveCancelSection.getCancelButton().isSelected(state); - } - - /** - * Updates a folder with a new parent, name, and label. - * - * @param folder The folder to update - * @param parent The new parent folder. May be null. - * @param name The new name of the folder - * @param label The new label for the folder - */ - final protected void updateFolder(final Folder folder, - final Category parent, - final String name, - final String label) { - folder.setParentCategory(parent); - updateFolder(folder, name, label); - } - - /** - * Updates a folder with a new name and label. - * - * @param folder The folder to update - * @param name The new name of the folder - * @param label The new label for the folder - */ - final protected void updateFolder(final Folder folder, - final String name, - final String label) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ConfigurationManager confManager = cdiUtil.findBean( - ConfigurationManager.class); - final KernelConfig kernelConfig = confManager.findConfiguration( - KernelConfig.class); - - folder.setName(name); - folder.setDisplayName(name); - folder.getTitle().putValue(kernelConfig.getDefaultLocale(), label); - - final CategoryRepository categoryRepo = cdiUtil.findBean( - CategoryRepository.class); - categoryRepo.save(folder); - } - - /** - * Returns the current folder being operated on. - * - * @param state - * - * @return The current folder - * - */ - final protected Folder getCurrentFolder(final PageState state) { - final Folder folder = currentFolder.getSelectedObject(state); - return folder; - } - - final protected FolderSelectionModel getFolderSelectionModel() { - return currentFolder; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderManipulator.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderManipulator.java deleted file mode 100755 index 9c6897aee..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderManipulator.java +++ /dev/null @@ -1,1179 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.ActionLink; -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Container; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.GridPanel; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Paginator; -import com.arsdigita.bebop.RequestLocal; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.Tree; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.CheckboxGroup; -import com.arsdigita.bebop.form.FormErrorDisplay; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.OptionGroup; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.ArrayParameter; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.tree.TreeCellRenderer; -import com.arsdigita.cms.CMS; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.ActionGroup; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.Arrays; -import java.util.List; - -import org.librecms.CMSConfig; -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.CcmObject; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.security.PermissionChecker; -import org.libreccm.security.Shiro; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.Folder; -import org.librecms.contentsection.FolderManager; -import org.librecms.contentsection.FolderRepository; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.util.Objects; - -import static org.librecms.CmsConstants.*; - -/** - * Browse folders and manipulate them with various actions (move/copy/delete). - * - * @author David Lutterkort - */ -@SuppressWarnings("PMD.BeanMembersShouldSerialize") -public class FolderManipulator extends SimpleContainer implements - //FormProcessListener, - //FormValidationListener, - //FormSubmissionListener, - Resettable { - - //public static final String RESOURCE_BUNDLE = "com.arsdigita.cms.ui.folder.CMSFolderResources"; - private static final Logger LOGGER = LogManager.getLogger( - FolderManipulator.class); - - private static final String ATOZ_FILTER_PARAM = "aToZfilter"; - private static final String ACTION_PARAM = "act"; - private static final String FILTER_PARAM = "filter"; - - private static final String SOURCES_PARAM = "srcs"; - private static final String MOVE = "Move"; - private static final String COPY = "Copy"; - //private static final String PUBLISH = "Publish"; - //private static final String UNPUBLISH = "UnPublish"; - - private final ArrayParameter sourcesParam = new ArrayParameter( - new StringParameter(SOURCES_PARAM)); - private final StringParameter actionParam - = new StringParameter(ACTION_PARAM); - ; - /** - * The folder in which the source items live. - */ - private final FolderSelectionModel sourceFolderModel; - private final ItemView itemView; - private final TargetSelector targetSelector = new TargetSelector(); - //private final PublishDialog publishDialog = new PublishDialog(); - - private FilterForm filterForm; - private final StringParameter atozFilterParam = new StringParameter( - ATOZ_FILTER_PARAM); - private final StringParameter filterParam - = new StringParameter(FILTER_PARAM); - - public FolderManipulator(final FolderSelectionModel folderModel) { - - super(); - - sourceFolderModel = folderModel; - itemView = new ItemView(); - itemView.addProcessListener(new ItemViewProcessListener()); - itemView.addValidationListener(new ItemViewValidationListener()); - add(itemView); - - targetSelector.addProcessListener(new TargetSelectorProcessListener()); - targetSelector.addValidationListener( - new TargetSelectorValidationListener()); - targetSelector.addSubmissionListener( - new TargetSelectorSubmissionListener()); - add(targetSelector); - - //publishDialog.addProcessListener(new PublishDialogProcessListener()); - } - - @Override - public void register(final Page page) { - - super.register(page); - page.setVisibleDefault(targetSelector, false); - page.setVisibleDefault(filterForm, true); - page.addComponentStateParam(this, sourcesParam); - page.addComponentStateParam(this, actionParam); - page.addComponentStateParam(this, atozFilterParam); - page.addComponentStateParam(this, filterParam); - - } - - public final String[] getSources(final PageState state) { - - final String[] result = (String[]) state.getValue(sourcesParam); - - //Return empty array instead of null. - if (result == null) { - return new String[0]; - } else { - return result; - } - } - - public final FolderSelectionModel getSourceFolderModel() { - return sourceFolderModel; - } - - public final Category getTarget(final PageState state) { - return targetSelector.getTarget(state); - } - - protected final boolean isMove(final PageState state) { - return MOVE.equals(getAction(state)); - } - - protected final boolean isCopy(final PageState state) { - return COPY.equals(getAction(state)); - } - -// protected final boolean isPublish(final PageState state) { -// return PUBLISH.equals(getAction(state)); -// } -// -// protected final boolean isUnPublish(final PageState state) { -// return UNPUBLISH.equals(getAction(state)); -// } - private String getAction(final PageState state) { - return (String) state.getValue(actionParam); - } - - protected void moveObjects(final Folder target, final String[] objectIds) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderBrowserController controller = cdiUtil.findBean( - FolderBrowserController.class); - - controller.moveObjects(target, objectIds); - } - - protected void copyObjects(final Folder target, final String[] objectIds) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderBrowserController controller = cdiUtil.findBean( - FolderBrowserController.class); - - controller.copyObjects(target, objectIds); - } - -// protected void publishItems(final BigDecimal[] itemIds) { -// -// if (LOGGER.isDebugEnabled()) { -// LOGGER.debug("(Re-)Publishing items " + Arrays.asList(itemIds)); -// } -// -// for (BigDecimal itemId : itemIds) { -// -// final ContentItem item = retrieveSourceItem(itemId); -// -// if (item.isLive()) { -// //Republish -// //Ensure that we have the draft version -// //final ContentItem draftItem = item.getDraftVersion(); -// republish(itemId); -// } else { -// publish(itemId); -// } -// -// final LifecycleDefinition lifecycleDef = ContentTypeLifecycleDefinition -// .getLifecycleDefinition(item.getContentSection(), item.getContentType()); -// -// } -// } -// private void publish(final BigDecimal itemId) { -// -// } -// -// private void republish(final BigDecimal itemId) { -// -// final User user = Web.getWebContext().getUser(); -// -// final Thread thread = new Thread(new Runnable() { -// -// @Override -// public void run() { -// final ContentItem item = retrieveSourceItem(itemId); -// -// PublishLock.getInstance().lock(item); -// item.republish(false); -// Workflow workflow = Workflow.getObjectWorkflow(item); -// ItemLifecycleSelectForm.finish(workflow, item, user); -// PublishLock.getInstance().unlock(item); -// } -// -// }); -// thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { -// -// @Override -// public void uncaughtException(final Thread thread, -// final Throwable ex) { -// final StringWriter strWriter = new StringWriter(); -// final PrintWriter writer = new PrintWriter(strWriter); -// ex.printStackTrace(writer); -// final ContentItem item = retrieveSourceItem(itemId); -// -// PublishLock.getInstance().setError(item, strWriter.toString()); -// LOGGER.error(String.format( -// "An error occurred while " -// + "publishing the item '%s': ", -// item.getOID().toString()), -// ex); -// -// if ((CMSConfig.getInstanceOf(). -// getPublicationFailureSender() -// == null) -// && (CMSConfig.getInstanceOf(). -// getPublicationFailureReceiver() == null)) { -// return; -// } -// -// final PartyCollection receiverParties = Party.retrieveAllParties(); -// Party receiver = null; -// receiverParties.addEqualsFilter("primaryEmail", -// CMSConfig.getInstanceOf(). -// getPublicationFailureReceiver()); -// if (receiverParties.next()) { -// receiver = receiverParties.getParty(); -// } -// receiverParties.close(); -// -// final PartyCollection senderParties = Party.retrieveAllParties(); -// Party sender = null; -// senderParties.addEqualsFilter("primaryEmail", -// CMSConfig.getInstanceOf(). -// getPublicationFailureReceiver()); -// if (senderParties.next()) { -// sender = senderParties.getParty(); -// } -// senderParties.close(); -// -// if ((sender != null) && (receiver != null)) { -// final Writer traceWriter = new StringWriter(); -// final PrintWriter printWriter = new PrintWriter( -// traceWriter); -// ex.printStackTrace(printWriter); -// -// final Notification notification = new Notification( -// sender, -// receiver, -// String.format( -// "Failed to publish item '%s'", -// item.getOID().toString()), -// String.format("Publishing item '%s' failed " -// + "with error message: %s.\n\n" -// + "Stacktrace:\n%s", -// item.getOID().toString(), -// ex.getMessage(), -// traceWriter.toString())); -// notification.save(); -// } -// } -// -// }); -// -// thread.start(); -// } -// private ContentItem retrieveSourceItem(final BigDecimal itemToCopyId) { -// -// ContentItem source = (ContentItem) DomainObjectFactory.newInstance( -// new OID(ContentItem.BASE_DATA_OBJECT_TYPE, itemToCopyId)); -// Assert.exists(source, ContentItem.class); -// -// final ACSObject parent = source.getParent(); -// if (parent instanceof ContentBundle) { -// source = (ContentBundle) parent; -// } -// -// if (LOGGER.isDebugEnabled()) { -// LOGGER.debug("Copying item " + source); -// } -// -// return source; -// } - /** - * Returns the form that contains the folder browser and the move/copy - * dropdown. - * - * @return The form containing the folder browser and dropdown menu - */ - public final Form getItemView() { - return itemView; - } - - /** - * Returns the form to choose the target folder for move/copy - * - * @return - */ - public final Form getTargetSelector() { - return targetSelector; - } - - /** - * Return the browser contained in the ItemView form - * - * @return - */ - public final FolderBrowser getBrowser() { - return itemView.getBrowser(); - } - - private class ItemViewProcessListener implements FormProcessListener { - - public ItemViewProcessListener() { - //Nothing - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - itemView.setVisible(state, false); - targetSelector.setVisible(state, true); - targetSelector.expose(state); - } - - } - - private class TargetSelectorProcessListener implements FormProcessListener { - - public TargetSelectorProcessListener() { - //Nothing - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - itemView.setVisible(state, true); - targetSelector.setVisible(state, false); - - final Folder folder = targetSelector.getTarget(state); - final String[] itemIds = getSources(state); - - if (isCopy(state)) { - copyObjects(folder, itemIds); - } else if (isMove(state)) { - moveObjects(folder, itemIds); - } - - reset(state); - - } - - } - -// private class PublishDialogProcessListener implements FormProcessListener { -// -// public PublishDialogProcessListener() { -// //Nothing -// } -// -// @Override -// public void process(final FormSectionEvent event) throws FormProcessException { -// -// final PageState state = event.getPageState(); -// -// itemView.setVisible(state, true); -// publishDialog.setVisible(state, false); -// -// final BigDecimal[] itemIds = getSources(state); -// -// if (isPublish(state)) { -// publishItems(itemIds); -// } else if (isUnPublish(state)) { -// unpublishItems(itemIds); -// } -// -// reset(state); -// } -// -// } - private class ItemViewValidationListener implements FormValidationListener { - - public ItemViewValidationListener() { - //Nothing - } - - @Override - public void validate(final FormSectionEvent event) throws - FormProcessException { - - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - - if (getSources(state).length <= 0) { - data.addError("cms.ui.folder.must_select_item", - CmsConstants.CMS_FOLDER_BUNDLE); - } - } - - } - - private class TargetSelectorValidationListener - implements FormValidationListener { - - public TargetSelectorValidationListener() { - //Nothing - } - - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (getSources(state).length <= 0) { - throw new IllegalStateException("No source items specified"); - } - - final Folder target = targetSelector.getTarget(state); - final FormData data = event.getFormData(); - if (target == null) { - data.addError(new GlobalizedMessage( - "cms.ui.folder.need_select_target_folder", - CmsConstants.CMS_FOLDER_BUNDLE)); - //If the target is null, we can skip the rest of the checks - return; - } - - if (target.equals(sourceFolderModel.getSelectedObject(state))) { - data.addError(new GlobalizedMessage( - "cms.ui.folder.not_within_same_folder", - CmsConstants.CMS_FOLDER_BUNDLE)); - } - - // check create item permission - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - if (!permissionChecker.isPermitted( - ItemPrivileges.CREATE_NEW, target)) { - data.addError("cms.ui.folder.no_permission_for_item", - CmsConstants.CMS_FOLDER_BUNDLE); - } - - for (String source : getSources(state)) { - - validateItem(source, target, state, data); - - } - - } - - private void validateItem(final String objectId, - final Folder target, - final PageState state, - final FormData data) { - - Objects.requireNonNull(objectId, "objectId can't be null."); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderRepository folderRepo = cdiUtil.findBean( - FolderRepository.class); - final ContentItemRepository itemRepo = cdiUtil.findBean( - ContentItemRepository.class); - final ContentItemManager itemManager = cdiUtil.findBean( - ContentItemManager.class); - final FolderBrowserController controller = cdiUtil.findBean( - FolderBrowserController.class); - final FolderManager folderManager = cdiUtil.findBean( - FolderManager.class); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - - final CcmObject object; - final String name; - if (objectId.startsWith(FOLDER_BROWSER_KEY_PREFIX_FOLDER)) { - final long folderId = Long.parseLong(objectId.substring( - FOLDER_BROWSER_KEY_PREFIX_FOLDER.length())); - final Folder folder = folderRepo.findById(folderId).orElseThrow( - () -> new IllegalArgumentException(String.format( - "No folder with id %d in database.", folderId))); - - name = folder.getName(); - - //Check if folder or subfolder contains live items - if (isMove(state)) { - final FolderManager.FolderIsMovable movable = folderManager - .folderIsMovable(folder, target); - switch (movable) { - case DIFFERENT_SECTIONS: - addErrorMessage(data, - "cms.ui.folder.different_sections", - name); - break; - case HAS_LIVE_ITEMS: - addErrorMessage(data, - "cms.ui.folder.item_is_live", - name); - break; - case DIFFERENT_TYPES: - addErrorMessage(data, - "cms.ui.folder.different_folder_types", - name); - break; - case IS_ROOT_FOLDER: - addErrorMessage(data, - "cms.ui.folder.is_root_folder", - name); - break; - case SAME_FOLDER: - addErrorMessage(data, - "cms.ui.folder.same_folder", - name); - break; - case YES: - //Nothing - break; - default: - throw new UnexpectedErrorException(String.format( - "Unknown state '%s' for '%s'.", - movable, - FolderManager.FolderIsMovable.class. - getName())); - } - } - - object = folder; - - } else if (objectId.startsWith(FOLDER_BROWSER_KEY_PREFIX_ITEM)) { - final long itemId = Long.parseLong(objectId.substring( - FOLDER_BROWSER_KEY_PREFIX_ITEM.length())); - final ContentItem item = itemRepo - .findById(itemId) - .orElseThrow(() -> new IllegalArgumentException( - String.format( - "No content item with id %d in database.", - itemId))); - - name = item.getDisplayName(); - - if (isMove(state) && itemManager.isLive(item)) { - addErrorMessage(data, "cms.ui.folder.item_is_live", name); - } - - object = item; - } else { - throw new IllegalArgumentException(String.format( - "Provided objectId '%s' does not start with '%s' " - + "or '%s'.", - objectId, - FOLDER_BROWSER_KEY_PREFIX_FOLDER, - FOLDER_BROWSER_KEY_PREFIX_ITEM)); - } - - final long count = controller.countObjects(target, name); - if (count > 0) { - // there is an item or subfolder in the target folder that already has this name - addErrorMessage(data, "cms.ui.folder.item_already_exists", - name); - } - - if (!(permissionChecker.isPermitted( - ItemPrivileges.DELETE, object)) - && isMove(state)) { - addErrorMessage(data, - "cms.ui.folder.no_permission_for_item", - object.getDisplayName()); - } - } - - } - - private void addErrorMessage(final FormData data, - final String message, - final String itemName) { - data.addError(new GlobalizedMessage(message, - CmsConstants.CMS_FOLDER_BUNDLE, - new Object[]{itemName})); - } - -// @Override -// public void submitted(final FormSectionEvent event) throws FormProcessException { -// -// final PageState state = event.getPageState(); -// -// if (targetSelector.isCancelled(state)) { -// reset(state); -// throw new FormProcessException("cms.ui.folder.cancelled"); -// -// } -// } - private class TargetSelectorSubmissionListener implements - FormSubmissionListener { - - public TargetSelectorSubmissionListener() { - //Nothing - } - - @Override - public void submitted(final FormSectionEvent event) throws - FormProcessException { - - final PageState state = event.getPageState(); - - if (targetSelector.isCancelled(state)) { - reset(state); - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.folder.cancelled", - CmsConstants.CMS_FOLDER_BUNDLE)); - } - - } - - } - - @Override - public void reset(final PageState state) { - - itemView.setVisible(state, true); - itemView.reset(state); - targetSelector.setVisible(state, false); - targetSelector.reset(state); - //publishDialog.setVisible(state, false); - state.setValue(actionParam, null); - state.setValue(sourcesParam, null); - //s.setValue(m_aToZfilter, null); - state.setValue(filterParam, null); - - } - - // The form containing the tree to select the target folder from - private class TargetSelector extends Form implements Resettable { - - private final FolderSelectionModel targetModel; - private final FolderTree folderTree; - private final Submit cancelButton; - - public TargetSelector() { - super("targetSel", new BoxPanel()); - setMethod(GET); - targetModel = new FolderSelectionModel("target") { - - @Override - protected Long getRootFolderID(final PageState state) { - final ContentSection section = CMS - .getContext() - .getContentSection(); - return section.getRootDocumentsFolder().getObjectId(); - } - - }; - folderTree = new FolderTree(targetModel); - folderTree.setCellRenderer(new FolderTreeCellRenderer()); - - final Label label = new Label(new PrintListener() { - - @Override - public void prepare(final PrintEvent event) { - final PageState state = event.getPageState(); - final Label label = (Label) event.getTarget(); - final int numberOfItems = getSources(state).length; - final Category folder = (Category) sourceFolderModel - .getSelectedObject(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryManager categoryManager = cdiUtil. - findBean(CategoryManager.class); - - final String targetFolderPath; - if (targetModel.getSelectedObject(state) == null) { - targetFolderPath = ""; - } else { - targetFolderPath = categoryManager.getCategoryPath( - targetModel.getSelectedObject(state)); - } - - if (isMove(state)) { - label.setLabel(new GlobalizedMessage( - "cms.ui.folder.move", - CmsConstants.CMS_FOLDER_BUNDLE, - new Object[]{ - numberOfItems, - categoryManager.getCategoryPath(folder), - targetFolderPath - })); - } else if (isCopy(state)) { - label.setLabel(new GlobalizedMessage( - "cms.ui.folder.copy", - CMS_BUNDLE, - new Object[]{ - numberOfItems, - categoryManager.getCategoryPath(folder), - targetFolderPath - })); - } - } - - }); - - label.setOutputEscaping(false); - add(label); - add(folderTree); - add(new FormErrorDisplay(this)); - final SaveCancelSection saveCancelSection = new SaveCancelSection(); - cancelButton = saveCancelSection.getCancelButton(); - add(saveCancelSection); - } - - @Override - public void register(final Page page) { - super.register(page); - page.addComponentStateParam(this, targetModel.getStateParameter()); - } - - // Set things up the first time the selector gets visible - public void expose(final PageState state) { - final Folder folder = sourceFolderModel.getSelectedObject(state); - targetModel.clearSelection(state); - if (folder != null) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderManager folderManager = cdiUtil.findBean( - FolderManager.class); - if (!folderManager.getParentFolder(folder).isPresent()) { - folderTree.expand(Long.toString(folder.getObjectId()), - state); - } else { - final List parents = folderManager - .getParentFolders(folder); - parents - .stream() - .map(parent -> Long.toString(parent.getObjectId())) - .forEach(folderId -> folderTree.expand(folderId, - state)); - } - } - } - - @Override - public void reset(final PageState state) { - folderTree.clearSelection(state); - // FIXME: add a reset method to Tree and call that instead of this - // hack - state.setValue(folderTree.getSelectionModel().getStateParameter(), - null); - } - - public Folder getTarget(final PageState state) { - return targetModel.getSelectedObject(state); - } - - public boolean isCancelled(final PageState state) { - return cancelButton.isSelected(state); - } - - } - - //The form which is show for the publish and unpublish action -// private class PublishDialog extends Form { -// -// public PublishDialog() { -// super("PublishDialog", new BoxPanel()); -// -// final Label label = new Label(new PrintListener() { -// -// @Override -// public void prepare(final PrintEvent event) { -// -// final PageState state = event.getPageState(); -// final Label target = (Label) event.getTarget(); -// final int numberOfItems = getSources(state).length; -// final Folder folder = (Folder) sourceFolderModel.getSelectedObject(state); -// -// if (isPublish(state)) { -// target.setLabel(globalizationUtil.globalize( -// "cms.ui.folder.publish", -// new Object[]{numberOfItems, -// folder.getPathNoJsp()})); -// } else if (isUnPublish(state)) { -// target.setLabel(globalizationUtil.globalize( -// "cms.ui.folder.publish", -// new Object[]{numberOfItems, -// folder.getPathNoJsp()})); -// } -// } -// -// }); -// -// label.setOutputEscaping(false); -// add(label); -// add(new FormErrorDisplay(this)); -// add(new SaveCancelSection()); -// } -// -// } - // The form containing the browser and the drop down for selecting an - // action - private class ItemView extends Form implements Resettable { - - private static final String ITEM_VIEW = "itemView"; - - private final FolderBrowser folderBrowser; - private final Paginator paginator; - private final OptionGroup checkboxGroup; - private final SingleSelect actionSelect; - private final Submit submit; - - public ItemView() { - - super(ITEM_VIEW, new SimpleContainer()); - setMethod(GET); - - final ActionGroup group = new ActionGroup(); - add(group); - - final GridPanel panel = new GridPanel(1); - group.setSubject(panel); - - folderBrowser = new FolderBrowser(sourceFolderModel); - folderBrowser.setAtoZfilterParameter(atozFilterParam); - folderBrowser.setFilterParameter(filterParam); -// folderBrowser.setFilterForm(filterForm); - folderBrowser.setFolderManipulator(FolderManipulator.this); - paginator = new Paginator( - new FolderBrowserPaginationModelBuilder(folderBrowser), - CMSConfig.getConfig().getFolderBrowseListSize()); - folderBrowser.setPaginator(paginator); - panel.add(paginator); - panel.add(folderBrowser); - - LOGGER.debug("Adding filter form..."); - filterForm = new FilterForm(new FolderBrowserFilterFormModelBuilder( - folderBrowser)); - FolderManipulator.this.add(filterForm); - - checkboxGroup = new CheckboxGroup(sourcesParam); - panel.add(checkboxGroup); - - panel.add(new FormErrorDisplay(this)); - - final Container container = new SimpleContainer(); - group.addAction(container); - - container.add(new Label(new GlobalizedMessage( - "cms.ui.folder.edit_selection", - CmsConstants.CMS_FOLDER_BUNDLE))); - actionSelect = new SingleSelect(actionParam); - actionSelect.addOption( - new Option(COPY, - new Label(new GlobalizedMessage( - "cms.ui.folder.copy.action", - CmsConstants.CMS_FOLDER_BUNDLE)))); - actionSelect.addOption( - new Option(MOVE, - new Label(new GlobalizedMessage( - "cms.ui.folder.move.action", - CmsConstants.CMS_FOLDER_BUNDLE)))); - //Publishing in the folder browser only works if threaded publishing is active -// if (CMSConfig.getInstanceOf().getThreadedPublishing()) { -// actionSelect.addOption(new Option(PUBLISH, -// new Label(globalizationUtil.globalize( -// "cms.ui.folder.publish.action")))); -// actionSelect.addOption(new Option(UNPUBLISH, -// new Label(globalizationUtil.globalize( -// "cms.ui.folder.unpublish.action")))); -// } - container.add(actionSelect); - submit = new Submit("Go", - new GlobalizedMessage( - "cms.ui.folder.go", - CmsConstants.CMS_FOLDER_BUNDLE)); - container.add(submit); - - // Add a new first column to the table - final TableColumn column = new TableColumn(); - column.setHeaderValue(new GlobalizedMessage("empty_text", - CmsConstants.CMS_BUNDLE)); - column.setCellRenderer(new CheckboxRenderer()); - folderBrowser.getColumnModel().add(0, column); - } - - public final FolderBrowser getBrowser() { - return folderBrowser; - } - - public Paginator getPaginator() { - return paginator; - } - - @Override - public void reset(final PageState state) { - - checkboxGroup.setValue(state, null); - actionSelect.setValue(state, null); - paginator.reset(state); -// state.setValue(m_aToZfilter, null); - state.setValue(filterParam, null); - filterForm.getFilterField().setValue(state, null); - } - - // The renderer for the first column in the itemView table - private class CheckboxRenderer implements TableCellRenderer { - - public CheckboxRenderer() { - //Nothing to do - } - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - final Option result = new Option(key.toString(), - new Text("")); - result.setGroup(checkboxGroup); - return result; - } - - } - - } - - protected class FilterForm extends Form implements FormProcessListener, - FormInitListener, - FormSubmissionListener { - - private final SimpleContainer panel; - private boolean visible; - private final FilterFormModelBuilder modelBuilder; - private final TextField filterField; - - public FilterForm(final FilterFormModelBuilder modelBuilder) { - super("folderFilterForm"); - - LOGGER.debug("Creating filter form..."); - - this.modelBuilder = modelBuilder; - - addProcessListener(this); - addInitListener(this); - addSubmissionListener(this); - - panel = new BoxPanel(BoxPanel.HORIZONTAL); - - final ActionLink allLink = new ActionLink( - new GlobalizedMessage("cms.ui.folder.filter.all", - CmsConstants.CMS_FOLDER_BUNDLE)); - allLink.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(final ActionEvent event) { - //event.getPageState().setValue(m_aToZfilter, ""); - event.getPageState().setValue(filterParam, ""); - } - - }); - panel.add(allLink); - -// for (char c = 'A'; c <= 'Z'; c++) { -// final char lowerCaseChar = Character.toLowerCase(c); -// final ActionLink link = new ActionLink(Character.toString(c)); -// link.addActionListener(new ActionListener() { -// -// @Override -// public void actionPerformed(final ActionEvent event) { -// event.getPageState().setValue(m_aToZfilter, -// Character.toString(lowerCaseChar)); -// } -// }); -// panel.add(link); -// } - panel.add(new Label(new GlobalizedMessage( - "cms.ui.folder.filter", - CmsConstants.CMS_FOLDER_BUNDLE))); - filterField = new TextField(filterParam); - panel.add(filterField); - panel.add(new Submit("filterFolderSubmit", - new GlobalizedMessage( - "cms.ui.folder.filter_do", - CmsConstants.CMS_FOLDER_BUNDLE))); - - add(panel); - - } - - public TextField getFilterField() { - return filterField; - } - - @Override - public void process(final FormSectionEvent event) throws - FormProcessException { - //Nothing - } - - @Override - public void init(final FormSectionEvent event) throws - FormProcessException { - //fse.getPageState().setValue(FolderManipulator.this.m_filter, null); - //filterField.setValue(fse.getPageState(), null); - } - - @Override - public void submitted(final FormSectionEvent event) throws - FormProcessException { - } - - @Override - public boolean isVisible(PageState state) { - if (super.isVisible(state) - && (modelBuilder.getFolderSize(state) - >= CMSConfig.getConfig(). - getFolderAtoZShowLimit())) { - return true; - } else { - return false; - } - } - - } - - protected interface FilterFormModelBuilder { - - public long getFolderSize(PageState state); - - } - - /** - * Getting the GlobalizedMessage using a CMS Class targetBundle. - * - * @param key The resource key. May not null. - * - * @return The globalized message - */ -// public static GlobalizedMessage globalize(final String key) { -// return new GlobalizedMessage(key, RESOURCE_BUNDLE); -// } -// -// public static GlobalizedMessage globalize(final String key, final Object[] args) { -// return new GlobalizedMessage(key, RESOURCE_BUNDLE, args); -// } - private class FolderTreeCellRenderer implements TreeCellRenderer { - - private final RequestLocal invalidFoldersRequestLocal - = new RequestLocal(); - - /** - * Render the folders appropriately. The selected folder is a bold - * label. Invalid folders are plain labels. Unselected, valid folders - * are control links. Invalid folders are: the parent folder of the - * sources, any of the sources, and any subfolders of the sources. - */ - @Override - public Component getComponent(final Tree tree, - final PageState state, - final Object value, - final boolean isSelected, - final boolean isExpanded, - final boolean isLeaf, - final Object key) { - - // Get the list of invalid folders once per request. - final List invalidFolders; - if (invalidFoldersRequestLocal.get(state) == null) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderBrowserController controller = cdiUtil.findBean( - FolderBrowserController.class); - invalidFolders = controller.createInvalidTargetsList( - Arrays.asList(getSources(state))); - invalidFoldersRequestLocal.set(state, invalidFolders); - } else { - invalidFolders = (List) invalidFoldersRequestLocal - .get(state); - } - - final Label label = new Label(value.toString()); - - if (invalidFolders.contains(key.toString())) { - return label; - } - - // Bold if selected - if (isSelected) { - label.setFontWeight(Label.BOLD); - return label; - } - - return new ControlLink(label); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderPath.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderPath.java deleted file mode 100644 index af12367c0..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderPath.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.List; - -/** - * - * @author Jens Pelzetter - */ -public class FolderPath extends List { - - public FolderPath(final FolderSelectionModel folderSelectionModel) { - super(new FolderPathListModelBuilder(folderSelectionModel)); - setAttribute("type", "item-path"); - setSelectionModel(folderSelectionModel); - } - - - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderPathListModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderPathListModel.java deleted file mode 100644 index 1b03a5028..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderPathListModel.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.librecms.contentsection.Folder; -import org.librecms.contentsection.FolderManager; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; - -/** - * - * @author Jens Pelzetter - */ -class FolderPathListModel implements ListModel { - - private final Locale defaultLocale; - - private final Iterator pathFolders; - - private Folder currentFolder; - - public FolderPathListModel(final Folder folder) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderManager folderManager = cdiUtil - .findBean(FolderManager.class); - final List parentFolders = folderManager - .getParentFolders(folder); - final List path = new ArrayList<>(); - path.addAll(parentFolders); - path.add(folder); - pathFolders = path.iterator(); - - final ConfigurationManager confManager = cdiUtil.findBean( - ConfigurationManager.class); - final KernelConfig kernelConfig = confManager.findConfiguration( - KernelConfig.class); - defaultLocale = kernelConfig.getDefaultLocale(); - } - - @Override - public boolean next() { - if (pathFolders.hasNext()) { - currentFolder = pathFolders.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElement() { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderPathListModelController controller = cdiUtil - .findBean(FolderPathListModelController.class); - - return controller.getElement(currentFolder, defaultLocale); - } - - @Override - public String getKey() { - return Long.toString(currentFolder.getObjectId()); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderPathListModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderPathListModelBuilder.java deleted file mode 100644 index fcb6249a5..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderPathListModelBuilder.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.List; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.util.LockableImpl; - -import org.librecms.contentsection.Folder; - -/** - * - * @author Jens Pelzetter - */ -public class FolderPathListModelBuilder extends LockableImpl - implements ListModelBuilder { - - private final FolderSelectionModel folderSelectionModel; - - public FolderPathListModelBuilder( - final FolderSelectionModel folderSelectionModel) { - - this.folderSelectionModel = folderSelectionModel; - } - - @Override - public ListModel makeModel(final List list, final PageState state) { - - return new FolderPathListModel( - folderSelectionModel.getSelectedObject(state)); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderPathListModelController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderPathListModelController.java deleted file mode 100644 index bd65f232a..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderPathListModelController.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2019 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 com.arsdigita.cms.ui.folder; - -import org.librecms.contentsection.Folder; -import org.librecms.contentsection.FolderRepository; - -import java.util.Locale; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -public class FolderPathListModelController { - - @Inject - private FolderRepository folderRepository; - - @Transactional(Transactional.TxType.REQUIRED) - public String getElement(final Folder folder, final Locale locale) { - - final Folder result = folderRepository - .findById(folder.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No folder wit ID %d found.", folder.getObjectId()))); - - return result.getTitle().getValue(locale); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderRequestLocal.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderRequestLocal.java deleted file mode 100755 index cf7009068..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderRequestLocal.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.cms.ui.CcmObjectRequestLocal; - -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.Folder; - -import java.util.Optional; - - -public class FolderRequestLocal extends CcmObjectRequestLocal { - - private final SingleSelectionModel m_model; - - public FolderRequestLocal(final SingleSelectionModel model) { - m_model = model; - } - - public FolderRequestLocal() { - m_model = null; - } - - @Override - protected Object initialValue(final PageState state) { - if (m_model == null) { - return null; - } else { - final String id = m_model.getSelectedKey(state).toString(); - - return CdiUtil.createCdiUtil().findBean(CategoryRepository.class) - .findById(Long.parseLong(id)); - } - } - - public final Folder getFolder(final PageState state) { - final Object object = get(state); - final Object selected; - if (object instanceof Optional) { - selected = ((Optional) object).get(); - } else { - selected = object; - } - - return (Folder) selected; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderSelectionModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderSelectionModel.java deleted file mode 100755 index 82e46d7ae..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderSelectionModel.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; - -import com.arsdigita.ui.CcmObjectSelectionModel; - -import org.libreccm.categorization.Category; -import org.librecms.contentsection.Folder; - -/** - * Keeps track of the selection of an item in a folder. The objects that are - * selected by this model are all subclasses of {@link - * com.arsdigita.cms.Folder}. - * - * @author David Lutterkort - * @author Jens Pelzetter - */ -public abstract class FolderSelectionModel extends CcmObjectSelectionModel { - - public FolderSelectionModel(final String name) { - super(Category.class.getName(), name); - } - - public FolderSelectionModel(final SingleSelectionModel model) { - super(Category.class.getName(), model); - } - - @Override - public Long getSelectedKey(final PageState state) { - // FIXME: this code will go away once parameter models support init listeners - Long result = super.getSelectedKey(state); - if (result == null) { - result = getRootFolderID(state); - setSelectedKey(state, result); - } - return result; - } - - @Override - public void setSelectedKey(final PageState state, final Long key) { - super.setSelectedKey(state, key); - } - - /** - * Clear the selection by resetting it to the root folder id. - * - * @param state represents the current request. - */ - @Override - public void clearSelection(final PageState state) { - setSelectedKey(state, getRootFolderID(state)); - } - - /** - * Return the ID of the root folder. By default, this is the root folder of - * the content section in which the current request is made. If this model - * is to be used outside a content section, this method has to be overriden - * appropriately. - * - * @param state represents the current request - * @return the ID of the root folder - * - * @pre s != null - * @post return != null - */ - protected abstract Long getRootFolderID(final PageState state); -// { -// ContentSection sec = CMS.getContext().getContentSection(); -// return sec.getRootDocumentsFolder().getObjectId(); -// } - - /** - * Return true, since this selection model will always have a folder - * selected in it - * - * @param state - * @return - */ - @Override - public boolean isSelected(final PageState state) { - return true; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderTree.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderTree.java deleted file mode 100755 index ccc1687a7..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderTree.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Tree; -import com.arsdigita.cms.CMS; - -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.Folder; - -import static org.librecms.CmsConstants.*; - -public class FolderTree extends Tree { - - public FolderTree(final FolderSelectionModel folderSel) { - super(new FolderTreeModelBuilder() { - - @Override - protected Folder getRootFolder(final PageState state) { - final ContentSection section = CMS - .getContext() - .getContentSection(); - - return section.getRootDocumentsFolder(); - } - - }); - setSelectionModel(folderSel); - } - - @Override - public void setSelectedKey(final PageState state, final Object key) { - if (key instanceof String) { - final Long keyAsLong; - if (((String) key).startsWith( - FOLDER_BROWSER_KEY_PREFIX_FOLDER)) { - keyAsLong = Long.parseLong(((String) key).substring( - FOLDER_BROWSER_KEY_PREFIX_FOLDER.length())); - } else { - keyAsLong = Long.parseLong((String) key); - } - super.setSelectedKey(state, keyAsLong); - } else if (key instanceof Long) { - super.setSelectedKey(state, key); - } else { - //We know that a FolderSelectionModel only takes keys of type Long. - //Therefore we try to cast here - final Long keyAsLong = (Long) key; - super.setSelectedKey(state, keyAsLong); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderTreeModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderTreeModelBuilder.java deleted file mode 100755 index dd998bc17..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderTreeModelBuilder.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Tree; -import com.arsdigita.bebop.tree.TreeModel; -import com.arsdigita.bebop.tree.TreeModelBuilder; -import com.arsdigita.bebop.tree.TreeNode; -import com.arsdigita.cms.CMS; -import com.arsdigita.kernel.KernelConfig; - -import org.librecms.contentsection.ContentSection; - -import com.arsdigita.util.LockableImpl; - -import java.util.Collections; -import java.util.Iterator; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.contentsection.Folder; - -import java.util.List; -import java.util.Locale; -import java.util.stream.Collectors; -import org.libreccm.configuration.ConfigurationManager; - -/** - * A {@link com.arsdigita.bebop.tree.TreeModelBuilder} that produces trees - * containing the folder structure underneath a root folder. The root folder can - * be changed by overriding {@link #getRoot getRoot}. - * - * @author Tri Tran - * @author David Lutterkort - * @author Jens Pelzetter - */ -public abstract class FolderTreeModelBuilder - extends LockableImpl - implements TreeModelBuilder { - - /** - * Make a tree model that lists the hierarchy of folders underneath the - * folder returned by {@link #getRoot getRoot}. - * - * @param tree the tree in which the model is used - * @param state represents the current request - * - * @return a tree model that lists the hierarchy of folders underneath the - * folder returned by {@link #getRoot getRoot}. - */ - @Override - public TreeModel makeModel(final Tree tree, final PageState state) { - return new TreeModel() { - - @Override - public TreeNode getRoot(final PageState state) { - return new FolderTreeNode(getRootFolder(state)); - } - - @Override - public boolean hasChildren(final TreeNode node, - final PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderTreeModelController controller = cdiUtil.findBean( - FolderTreeModelController.class); - - return controller.hasChildren(node); - } - - @Override - public Iterator getChildren(final TreeNode node, - final PageState state) { - final String nodeKey = node.getKey().toString(); - - // Always expand root node - if (nodeKey.equals(getRoot(state).getKey().toString()) - && tree.isCollapsed(nodeKey, state)) { - tree.expand(nodeKey, state); - } - - if (tree.isCollapsed(nodeKey, state)) { - return Collections.emptyIterator(); - } - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final FolderTreeModelController controller = cdiUtil.findBean( - FolderTreeModelController.class); - - final List subFolders = controller.getChildren(node); - return subFolders.stream() - .map(folder -> generateTreeNode(folder)) - .sorted((node1, node2) -> { - return ((String) node1.getElement()) - .compareTo((String) node2.getElement()); - }) - .collect(Collectors.toList()) - .iterator(); - } - - private TreeNode generateTreeNode(final Folder folder) { - final FolderTreeNode node = new FolderTreeNode(folder); - - return node; - } - - }; - - } - -// /** -// * Return the root folder for the tree model in the current request. -// * -// * @param state represents the current request -// * -// * @return the root folder for the tree -// * -// */ -//// protected Folder getRootFolder(final PageState state) -// throws IllegalStateException { -// -// final ContentSection section = CMS.getContext().getContentSection(); -// return section.getRootDocumentsFolder(); -// } - /** - * Return the root folder for the tree model in the current request. - * - * @param state represents the current request - * - * @return the root folder for the tree - * - */ - protected abstract Folder getRootFolder(final PageState state); - - private class FolderTreeNode implements TreeNode { - - private final Folder folder; - - public FolderTreeNode(final Folder folder) { - this.folder = folder; - } - - @Override - public Object getKey() { - return folder.getObjectId(); - } - - @Override - public Object getElement() { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final GlobalizationHelper globalizationHelper = cdiUtil.findBean( - GlobalizationHelper.class); - final FolderTreeModelController controller = cdiUtil - .findBean(FolderTreeModelController.class); - final Locale locale = globalizationHelper.getNegotiatedLocale(); - if (controller.hasTitleValue(folder, locale)) { - return controller.getTitleValue(folder, locale); - } else { - final ConfigurationManager confManager = cdiUtil.findBean( - ConfigurationManager.class); - final KernelConfig kernelConfig = confManager.findConfiguration( - KernelConfig.class); - final String value = controller - .getTitleValue(folder, - kernelConfig.getDefaultLocale()); - if (value == null) { - return folder.getName(); - } else { - return value; - } - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderTreeModelController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderTreeModelController.java deleted file mode 100644 index 54ee070d9..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/FolderTreeModelController.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.tree.TreeNode; - -import org.libreccm.categorization.Category; -import org.libreccm.core.UnexpectedErrorException; -import org.librecms.contentsection.Folder; -import org.librecms.contentsection.FolderRepository; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.Optional; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -public class FolderTreeModelController { - - @Inject - private FolderRepository folderRepo; - - private Folder getCurrentFolder(final TreeNode node) { - if (node == null) { - throw new IllegalArgumentException( - "Can't get current folder from null."); - } - -// final Folder current = (Folder) node.getElement(); - final Optional folder = folderRepo - .findById((long) node.getKey()); - if (folder.isPresent()) { - return folder.get(); - } else { - throw new IllegalArgumentException(String.format( - "The provided TreeNode contains a folder (%s) which is not in " - + "the database.", - folder.toString())); - } - } - - @Transactional(Transactional.TxType.REQUIRED) - public boolean hasTitleValue(final Folder ofFolder, - final Locale forLocale) { - - final Folder folder = folderRepo - .findById(ofFolder.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No folder with Id %d found.", - ofFolder.getObjectId()))); - - return folder.getTitle().hasValue(forLocale); - } - - @Transactional(Transactional.TxType.REQUIRED) - public String getTitleValue(final Folder ofFolder, - final Locale forLocale) { - - final Folder folder = folderRepo - .findById(ofFolder.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No folder with Id %d found.", - ofFolder.getObjectId()))); - - return folder.getTitle().getValue(forLocale); - } - - @Transactional(Transactional.TxType.REQUIRED) - public boolean hasChildren(final TreeNode node) { - return !getCurrentFolder(node).getSubCategories().isEmpty(); - } - - @Transactional(Transactional.TxType.REQUIRED) - public List getChildren(final TreeNode node) { - return getCurrentFolder(node).getSubFolders(); - } - - @Transactional(Transactional.TxType.REQUIRED) - public List findAncestorIds(final Folder folder) { - Objects.requireNonNull(folder, - "Can't find ids of the ancestors of folder null."); - - final Optional theFolder = folderRepo.findById(folder - .getObjectId()); - if (!theFolder.isPresent()) { - throw new UnexpectedErrorException(String.format( - "The folder %s was not found in the database, but it should be there.", - Objects.toString(folder))); - } - final List ancestorIds = new ArrayList<>(); - Category current = theFolder.get(); - while (current != null) { - ancestorIds.add(current.getObjectId()); - current = current.getParentCategory(); - } - - return ancestorIds; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/ItemPath.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/ItemPath.java deleted file mode 100755 index f3034b8e0..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/ItemPath.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.List; -import com.arsdigita.cms.ItemSelectionModel; - -/** - * Produce a list of the items starting from the selected item's root down to - * the item itself. - * - * @author David Lutterkort - * @author Jens Pelzetter - */ -public class ItemPath extends List { - - public ItemPath(final ItemSelectionModel itemSelectionModel) { - super(new ItemPathListModelBuilder(itemSelectionModel)); - setAttribute("type", "item-path"); - setSelectionModel(itemSelectionModel); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/ItemPathListModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/ItemPathListModel.java deleted file mode 100644 index 3dd0c2458..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/ItemPathListModel.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.list.ListModel; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.Folder; - -import java.util.Iterator; - -/** - * Model for {@link ItemPath}. This was originally a inner class. - * - * @author David Lutterkort - * @author Jens Pelzetter - */ -class ItemPathListModel implements ListModel { - - private final Iterator pathFolders; - private Folder currentFolder; - - public ItemPathListModel(final ContentItem item) { - pathFolders = CdiUtil.createCdiUtil().findBean( - ContentItemManager.class).getItemFolders(item).iterator(); - } - - @Override - public boolean next() { - if (pathFolders.hasNext()) { - currentFolder = pathFolders.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElement() { - return currentFolder.getName(); - } - - @Override - public String getKey() { - return Long.toString(currentFolder.getObjectId()); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/ItemPathListModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/ItemPathListModelBuilder.java deleted file mode 100644 index 4bf4aa2c4..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/folder/ItemPathListModelBuilder.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.folder; - -import com.arsdigita.bebop.List; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.util.LockableImpl; - -/** - * ModelBuilder for {@link ItemPath}. This was originally an inner class. - * - * @author David Lutterkort - * @author Jens Pelzetter - */ -class ItemPathListModelBuilder extends LockableImpl implements ListModelBuilder { - - private final ItemSelectionModel itemSelectionModel; - - public ItemPathListModelBuilder( - final ItemSelectionModel itemSelectionModel) { - - this.itemSelectionModel = itemSelectionModel; - } - - @Override - public com.arsdigita.bebop.list.ListModel makeModel( - final List list, final PageState state) { - - return new ItemPathListModel(itemSelectionModel.getSelectedObject( - state)); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ContentItemRequestLocal.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ContentItemRequestLocal.java deleted file mode 100755 index f37cb5643..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ContentItemRequestLocal.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.item; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; - -import org.librecms.contentsection.ContentItem; - -import com.arsdigita.util.Assert; - -/** - * {@link RequestLocal} storing a content item. - */ -public abstract class ContentItemRequestLocal extends RequestLocal { - - public final ContentItem getContentItem(final PageState state) { - final ContentItem item = (ContentItem) get(state); - - Assert.exists(item, "ContentItem item"); - - return item; - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/CustomizedPreviewLink.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/CustomizedPreviewLink.java deleted file mode 100644 index a998672e6..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/CustomizedPreviewLink.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.arsdigita.cms.ui.item; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.cms.ui.ContentItemPage; - -/** - *

    - * This interface is implemented by "meta" content items which need to - * customise their preview link. An example is a content item which serves - * as an access point to an application. - *

    - *

    - * An implementation may return {@code null}. In this case - * {@link ContentItemPage} will use the default preview URL. - *

    - * - * @author Jens Pelzetter - * @version $Id$ - */ -public interface CustomizedPreviewLink { - - String getPreviewUrl(PageState state); - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemCreateForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemCreateForm.java deleted file mode 100644 index 938efc4da..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemCreateForm.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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 com.arsdigita.cms.ui.item; - -/** - * - * @author Jens Pelzetter - */ -public class ItemCreateForm { - - //Placeholder - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguages.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguages.java deleted file mode 100755 index b9088cb74..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguages.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.item; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.OptionGroup; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.parameters.StringParameter; - -import org.librecms.contentsection.ContentItem; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.ContentItemPage; -import com.arsdigita.cms.ui.authoring.LanguageWidget; - -import org.librecms.util.LanguageUtil; - -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.ActionGroup; -import com.arsdigita.toolbox.ui.LayoutPanel; -import com.arsdigita.toolbox.ui.Section; -import com.arsdigita.util.Pair; -import com.arsdigita.web.RedirectSignal; -import com.arsdigita.web.URL; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentItemL10NManager; - -import java.util.List; -import java.util.TooManyListenersException; -import java.util.stream.Collectors; - -import org.libreccm.core.UnexpectedErrorException; -import org.librecms.CmsConstants; - -/** - * Displays the "Language instances" pane, with all the language instances in - * the Bundle. - * - * @author Alan Pevec (apevec@redhat.com) - * @author Jens Pelzetter - */ -public class ItemLanguages extends LayoutPanel { - - private final ItemSelectionModel selectionModel; -// private final SingleSelectionModel selectedLanguage; - private final LanguageWidget languageWidget; - private final StringParameter selectedLanguageParam; - // private final Submit changeSubmit; - private final Submit createSubmit; - - /** - * Constructs a new ItemLanguages. - * - * @param selectionModel the {@link ItemSelectionModel} which will - * supply the current item - * @param selectedLanguage {@link SingleSelectionModel} for the - * selected language. - * @param selectedLanguageParam - */ - public ItemLanguages(final ItemSelectionModel selectionModel, - // final SingleSelectionModel selectedLanguage, - final StringParameter selectedLanguageParam) { - - this.selectionModel = selectionModel; -// this.selectedLanguage = selectedLanguage; - this.selectedLanguageParam = selectedLanguageParam; - - final Section section = new Section(gz("cms.ui.item.languages")); - setBody(section); - - final ActionGroup group = new ActionGroup(); - section.setBody(group); - - group.setSubject(new ItemLanguagesTable(selectionModel, - // selectedLanguage, - selectedLanguageParam)); - - final Form form = new Form("newLanguage", new BoxPanel( - BoxPanel.HORIZONTAL)) { - - @Override - public boolean isVisible(final PageState state) { - final ContentItem item = selectionModel.getSelectedItem(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemL10NManager l10NManager = cdiUtil.findBean( - ContentItemL10NManager.class); - return !l10NManager.creatableLocales(item).isEmpty(); - } - - }; - group.addAction(form); - - form.setRedirecting(true); - languageWidget = new LanguageWidget("language_widget") { - - @Override - protected void setupOptions() { - // Don't do anything. - } - - }; - - try { - languageWidget.addPrintListener(new OptionPrinter()); - } catch (TooManyListenersException ex) { - throw new UnexpectedErrorException(ex); - } - - form.add(languageWidget); -// changeSubmit = new Submit("change", gz("cms.ui.item.language.change")); -// form.add(changeSubmit); - createSubmit = new Submit("create", gz("cms.ui.item.language.add")); - form.add(createSubmit); - form.addProcessListener(new ProcessListener()); - } - - /** - * Offers only languages not yet present in the bundle. - */ - private class OptionPrinter implements PrintListener { - - @Override - public final void prepare(final PrintEvent event) { - final PageState state = event.getPageState(); - final OptionGroup target = (OptionGroup) event.getTarget(); - target.clearOptions(); - final ContentItem item = selectionModel.getSelectedItem(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final LanguageUtil languageUtil = cdiUtil.findBean( - LanguageUtil.class); - final ContentItemL10NManager l10NManager = cdiUtil.findBean( - ContentItemL10NManager.class); - - final List creatableLangs = l10NManager.creatableLocales( - item).stream() - .map(locale -> locale.toString()) - .collect(Collectors.toList()); - final List languages = languageUtil - .convertToG11N(creatableLangs); - - for (final Pair pair : languages) { - final String langCode = (String) pair.getKey(); - final GlobalizedMessage langName - = (GlobalizedMessage) pair - .getValue(); - target.addOption(new Option(langCode, new Label(langName))); - } - } - - } - - /** - * Adds a new language instance to the bundle. - */ - private class ProcessListener implements FormProcessListener { - - @Override - public final void process(final FormSectionEvent event) - throws FormProcessException { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - - final PageState state = event.getPageState(); - final String language = (String) languageWidget.getValue(state); - final ContentItem item = selectionModel.getSelectedItem(state); - - if (createSubmit.isSelected(state)) { - - final ItemLanguagesController controller = cdiUtil - .findBean(ItemLanguagesController.class); - - controller.addLanguage(item, language); - - // redirect to ContentItemPage.AUTHORING_TAB of the new instance - state.setValue(selectedLanguageParam, language); - final String langParam = String - .format("&%s=%s", - ContentItemPage.SELECTED_LANGUAGE, - language); - final String target = String.join( - "", - URL.getDispatcherPath(), - controller.getItemEditUrl(item), - langParam); - - throw new RedirectSignal(target, true); - } - } - - } - - protected static final GlobalizedMessage gz(final String key) { - return new GlobalizedMessage(key, CmsConstants.CMS_BUNDLE); - } - - protected static final String lz(final String key) { - return (String) gz(key).localize(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguagesController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguagesController.java deleted file mode 100644 index 411739f8e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguagesController.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * 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 com.arsdigita.cms.ui.item; - -import com.arsdigita.bebop.table.RowData; -import com.arsdigita.cms.ui.ContentItemPage; - -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemL10NManager; -import org.librecms.contentsection.ContentItemRepository; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class ItemLanguagesController { - - @Inject - private ContentItemRepository itemRepo; - - @Inject - private ContentItemL10NManager itemL10NManager; - - @Inject - private GlobalizationHelper globalizationHelper; - - protected List> retrieveLanguageVariants( - final ContentItem item) { - return retrieveLanguageVariants(item.getObjectId()); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected List> retrieveLanguageVariants(final long itemId) { - - final ContentItem item = itemRepo - .findById(itemId) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContentItem with ID %d in the database.", itemId))); - - final List availableLangs = new ArrayList<>(itemL10NManager - .availableLanguages(item)); - availableLangs.sort((locale1, locale2) -> { - return locale1.toString().compareTo(locale2.toString()); - }); - - return availableLangs.stream() - .map(lang -> createRow(item, lang)) - .collect(Collectors.toList()); - } - - private RowData createRow(final ContentItem item, - final Locale lang) { - final RowData row = new RowData<>(2); - row.setRowKey(lang.toString()); - row.setColData(0, lang.getDisplayName(globalizationHelper - .getNegotiatedLocale())); - row.setColData(1, item.getTitle().getValue(lang)); - - return row; - } - - @Transactional(Transactional.TxType.REQUIRED) - protected int countLanguageVariants(final ContentItem item) { - - final ContentItem contentItem = itemRepo - .findById(item.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContentItem with ID %d in the database.", - item.getObjectId()))); - - return itemL10NManager.availableLanguages(contentItem).size(); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void addLanguage(final ContentItem item, final String language) { - - final ContentItem contentItem = itemRepo - .findById(item.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContentItem with ID %d in the database.", - item.getObjectId()))); - - itemL10NManager.addLanguage(contentItem, new Locale(language)); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected void removeLanguage(final ContentItem item, - final String language) { - - final ContentItem contentItem = itemRepo - .findById(item.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContentItem with ID %d in the database.", - item.getObjectId()))); - - itemL10NManager.removeLanguage(contentItem, new Locale(language)); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected String getItemEditUrl(final ContentItem item) { - - final ContentItem contentItem = itemRepo - .findById(item.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContentItem with ID %d in the database.", - item.getObjectId()))); - - return ContentItemPage.getItemURL(contentItem, - ContentItemPage.AUTHORING_TAB); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguagesTable.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguagesTable.java deleted file mode 100755 index efff8f26e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguagesTable.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.item; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.TableActionEvent; -import com.arsdigita.bebop.event.TableActionListener; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.bebop.table.TableColumn; -import com.arsdigita.bebop.table.TableColumnModel; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.ui.ContentItemPage; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.web.RedirectSignal; -import com.arsdigita.web.URL; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.util.LanguageUtil; - -import java.util.Locale; - -/** - * Displays a list of all language instances of an item. - * - */ -public class ItemLanguagesTable extends Table { - - public static final int COL_LANGUAGE = 0; - public static final int COL_TITLE = 1; - public static final int COL_DELETE = 2; - - private final ItemSelectionModel itemSelectionModel; -// private final SingleSelectionModel langSelectionModel; - private final StringParameter selectedLanguageParam; -// private final TableColumn deleteColumn; - - /** - * Construct a new {@code ItemLanguagesTable} which shows all language - * variants of an item. - * - * @param itemSelectionModel the ItemSelectionModel that supplies the - * current item - * @param langSelectionModel the single selection model which stores the - * selected language. - */ - public ItemLanguagesTable(final ItemSelectionModel itemSelectionModel, - // final SingleSelectionModel langSelectionModel, - final StringParameter selectedLanguageParam) { - super(); - setIdAttr("item_languages_table"); - - this.itemSelectionModel = itemSelectionModel; -// this.langSelectionModel = langSelectionModel; - this.selectedLanguageParam = selectedLanguageParam; - setModelBuilder(new ItemLanguagesTableModelBuilder(itemSelectionModel)); - - final TableColumnModel columnModel = getColumnModel(); - columnModel.add(new TableColumn(COL_LANGUAGE, - new Label(new GlobalizedMessage( - "cms.ui.language.header", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn(COL_TITLE, - new Label(new GlobalizedMessage( - "cms.ui.language.title", - CmsConstants.CMS_BUNDLE)))); - columnModel.add(new TableColumn(COL_DELETE, - new Label(new GlobalizedMessage( - "cms.ui.action", - CmsConstants.CMS_BUNDLE)))); - - columnModel.get(COL_LANGUAGE).setCellRenderer(new TableCellRenderer() { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column) { - - final Locale locale = new Locale((String) value); - final String selectedLanguage = (String) state - .getValue(selectedLanguageParam); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final LanguageUtil langUtil = cdiUtil.findBean( - LanguageUtil.class); - - final Label label = new Label(langUtil.getLangFull(locale)); - -// if (langSelectionModel.getSelectedKey(state).equals(key)) { - if (selectedLanguage.equals(key)) { - // Current variant, no link - return label; - } else { - return new ControlLink(label); - -// final String target = ContentItemPage.getItemURL( -// itemSelectionModel.getSelectedItem(state), -// ContentItemPage.AUTHORING_TAB); -// return new Link(label, target); - } - - } - - } - ); - columnModel.get(COL_DELETE) - .setCellRenderer(new TableCellRenderer() { - - @Override - public Component getComponent(final Table table, - final PageState state, - final Object value, - final boolean isSelected, - final Object key, - final int row, - final int column - ) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ItemLanguagesController controller = cdiUtil - .findBean(ItemLanguagesController.class); - final ContentItem item = itemSelectionModel - .getSelectedItem(state); - - if (key - .equals(KernelConfig.getConfig().getDefaultLanguage()) - || controller.countLanguageVariants(item) <= 1) { - return new Text(" "); - } else { - final ControlLink link = new ControlLink(new Label( - new GlobalizedMessage("cms.ui.delete", - CmsConstants.CMS_BUNDLE))); - link.setConfirmation(new GlobalizedMessage( - "cms.ui.delete.confirmation", - CmsConstants.CMS_BUNDLE)); - - return link; - } - } - - } - ); - - addTableActionListener( - new TableActionListener() { - - @Override - public void cellSelected(final TableActionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final ContentItem item = itemSelectionModel - .getSelectedItem(state); - final String selectedLanguage = (String) event.getRowKey(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ItemLanguagesController controller = cdiUtil - .findBean(ItemLanguagesController.class); - - switch (event.getColumn()) { - case COL_LANGUAGE: { - state.setValue(selectedLanguageParam, selectedLanguage); - final String langParam = String - .format("&%s=%s", - ContentItemPage.SELECTED_LANGUAGE, - selectedLanguage); - final String target = String.join( - "", - URL.getDispatcherPath(), - controller.getItemEditUrl(item), - langParam); - throw new RedirectSignal(target, true); - } - case COL_DELETE: { - if (selectedLanguage.equals(state.getValue( - selectedLanguageParam))) { - state.setValue(selectedLanguageParam, - KernelConfig.getConfig() - .getDefaultLanguage()); - } - controller.removeLanguage(item, selectedLanguage); - } - default: - //Nothing to do - return; - } - } - - @Override - public void headSelected(final TableActionEvent event - ) { - //Nothing - } - - } - ); - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguagesTableModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguagesTableModel.java deleted file mode 100644 index 8ba74ad03..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguagesTableModel.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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 com.arsdigita.cms.ui.item; - -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.table.RowData; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CmsConstants; - -import java.util.Iterator; -import java.util.List; - -/** - * - * @author Jens Pelzetter - */ -class ItemLanguagesTableModel implements TableModel { - - private final Iterator> iterator; - private RowData curentRow; - - protected ItemLanguagesTableModel(final List> rows) { - iterator = rows.iterator(); - } - - @Override - public int getColumnCount() { - return 3; - } - - @Override - public boolean nextRow() { - if (iterator.hasNext()) { - curentRow = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - switch (columnIndex) { - case ItemLanguagesTable.COL_LANGUAGE: - return curentRow.getColData(0); - case ItemLanguagesTable.COL_TITLE: - return curentRow.getColData(1); - case ItemLanguagesTable.COL_DELETE: - return new Label(new GlobalizedMessage("cms.ui.delete", - CmsConstants.CMS_BUNDLE)); - default: - throw new IllegalArgumentException("Invalid column index."); - } - } - - @Override - public Object getKeyAt(final int columnIndex) { - return curentRow.getRowKey(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguagesTableModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguagesTableModelBuilder.java deleted file mode 100644 index 599700e33..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemLanguagesTableModelBuilder.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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 com.arsdigita.cms.ui.item; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.table.RowData; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.ContentItem; - -import java.util.List; - -/** - * - * @author Jens Pelzetter - */ -class ItemLanguagesTableModelBuilder - extends LockableImpl - implements TableModelBuilder { - - private final ItemSelectionModel itemSelectionModel; - - protected ItemLanguagesTableModelBuilder( - final ItemSelectionModel itemSelectionModel) { - this.itemSelectionModel = itemSelectionModel; - } - - @Override - public TableModel makeModel(final Table table, final PageState state) { - final ContentItem item = itemSelectionModel.getSelectedItem(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ItemLanguagesController controller = cdiUtil.findBean(ItemLanguagesController.class); - final List> rows = controller.retrieveLanguageVariants( - item); - - return new ItemLanguagesTableModel(rows); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemWorkflowRequestLocal.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemWorkflowRequestLocal.java deleted file mode 100755 index 003d717a8..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemWorkflowRequestLocal.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.item; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.cms.CMS; - -import org.librecms.contentsection.ContentItem; - -import com.arsdigita.cms.ui.workflow.WorkflowRequestLocal; - -import org.libreccm.cdi.utils.CdiUtil; - -public class ItemWorkflowRequestLocal extends WorkflowRequestLocal { - - @Override - protected final Object initialValue(final PageState state) { - - final ContentItem item = CMS.getContext().getContentItem(); - -// return item.getWorkflow(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ItemWorkflowRequestLocalHelper helper = cdiUtil - .findBean(ItemWorkflowRequestLocalHelper.class); - - return helper.findWorkflowForContentItem(item); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemWorkflowRequestLocalHelper.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemWorkflowRequestLocalHelper.java deleted file mode 100644 index d8f10b622..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/ItemWorkflowRequestLocalHelper.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.item; - -import org.hibernate.LazyInitializationException; -import org.libreccm.workflow.Workflow; -import org.libreccm.workflow.WorkflowRepository; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemRepository; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * Helper class for {@link ItemWorkflowRequestLocal} to avoid a - * {@link LazyInitializationException} when accessing the workflow of current - * content item. - * - * @author Jens Pelzetter - */ -@RequestScoped -class ItemWorkflowRequestLocalHelper { - - @Inject - private ContentItemRepository itemRepo; - - @Inject - private WorkflowRepository workflowRepo; - - @Transactional(Transactional.TxType.REQUIRED) - protected Workflow findWorkflowForContentItem(final ContentItem item) { - - final ContentItem contentItem = itemRepo - .findById(item.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", - item.getObjectId()))); - - final Workflow workflow; - if (contentItem.getWorkflow() == null) { - workflow = null; - } else { - workflow = workflowRepo - .findById(contentItem.getWorkflow().getWorkflowId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No Workflow with ID %d in the database.", - contentItem.getWorkflow().getWorkflowId()))); - } - - return workflow; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/Summary.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/Summary.java deleted file mode 100755 index 324b7d2c5..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/item/Summary.java +++ /dev/null @@ -1,372 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.item; - -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.List; - -import com.arsdigita.bebop.PageState; - -import org.libreccm.categorization.Category; - -import com.arsdigita.cms.CMS; - -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentSection; - -import com.arsdigita.cms.ItemSelectionModel; -import com.arsdigita.cms.dispatcher.CMSDispatcher; - -import org.librecms.lifecycle.Lifecycle; - -import com.arsdigita.cms.ui.CMSContainer; - -import org.libreccm.security.User; - -import com.arsdigita.toolbox.ui.FormatStandards; -import com.arsdigita.util.Assert; -import com.arsdigita.util.GraphSet; -import com.arsdigita.util.Graphs; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.web.Web; - -import org.libreccm.workflow.Task; -import org.libreccm.workflow.TaskComment; -import org.libreccm.workflow.Workflow; - -import com.arsdigita.xml.Element; - -import org.libreccm.auditing.CcmRevision; -import org.libreccm.categorization.CategoryManager; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.libreccm.security.Shiro; -import org.libreccm.workflow.TaskDependency; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentSectionManager; -import org.librecms.dispatcher.ItemResolver; - -import java.io.UnsupportedEncodingException; -import java.util.Date; -import java.util.Locale; -import java.util.stream.Collectors; - -/** - * This panel displays basic details about a content item such as attributes and - * associations. - * - * Container: {@link com.arsdigita.cms.ui.ContentItemPage} - * - * This panel uses an {@link com.arsdigita.cms.dispatcher.XMLGenerator} to - * convert content items into XML. - * - * @author Michael Pih - * @author Jens Pelzetter - */ -public class Summary extends CMSContainer { - - private static final String SUMMARY = "itemAdminSummary"; - private static final String RESTART_WORKFLOW = "restartWorkflow"; - - private final ItemSelectionModel itemSelectionModel; - - public Summary(final ItemSelectionModel itemSelectionModel) { - super(); - - this.itemSelectionModel = itemSelectionModel; - } - - /** - * Generate XML representation of an item summary. - * - * @param state The page state - * @param parent The parent DOM element - * - * @pre ( state != null ) - * @pre ( parent != null ) - */ - @Override - public void generateXML(PageState state, Element parent) { - if (isVisible(state)) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final GlobalizationHelper globalizationHelper = cdiUtil.findBean( - GlobalizationHelper.class); - final Locale language = globalizationHelper.getNegotiatedLocale(); - - // Determine the item's environment - final ContentItem item = getContentItem(state); - final ContentSection section = getContentSection(state); - - final Shiro shiro = cdiUtil.findBean(Shiro.class); - final User user = shiro.getUser().get(); - - // Setup xml element for item's properties - final Element itemElement = new Element("cms:itemSummary", - CMS.CMS_XML_NS); - - // Determine item's name / url stub - itemElement.addAttribute("name", item.getDisplayName()); - - // obviously getName() here gets the 'semantically meaningful name' - // from database using class DataType. It is not localizable! And - // it is not really 'semantically meaningful' - final String objectType = item.getClass().getName(); - - // Quasimodo: ObjectType for summary - itemElement.addAttribute("objectType", objectType); - itemElement.addAttribute("description", - item.getDescription().getValue(language)); - - itemElement.addAttribute("title", - item.getTitle().getValue(language)); - - // subject category - final Element subjectCategoriesElement = new Element( - "cms:subjectCategories", CMS.CMS_XML_NS); - itemElement.addContent(subjectCategoriesElement); - - // URL - final Element linkElement = new Element("cms:linkSummary", - CMS.CMS_XML_NS); - try { - linkElement.addAttribute( - "url", - String.format("%s/redirect?oid=%s", - Web.getWebappContextPath(), - URLEncoder.encode(item.getUuid(), "UTF-8"))); - } catch (UnsupportedEncodingException ex) { - throw new UncheckedWrapperException(ex); - } - - //"/redirect?oid=" + URLEncoder.encode(item.getDraftVersion().getOID().toString())); - // WORKFLOW - final Element workflowElement = new Element("cms:workflowSummary", - CMS.CMS_XML_NS); - final Workflow workflow = item.getWorkflow(); - if (workflow == null) { - workflowElement.addAttribute("noWorkflow", "1"); - } else { - workflowElement.addAttribute("name", - workflow.getName().getValue( - language)); - - final List tasks = workflow.getTasks(); - final GraphSet graph = new GraphSet(); - - for (final Task task : tasks) { - final List blockingTasks = task - .getBlockingTasks(); - final StringBuilder builder = new StringBuilder(); - for (final TaskDependency blocking : blockingTasks) { - graph.addEdge(task, blocking, null); - builder.append(blocking - .getBlockingTask() - .getLabel() - .getValue(language)); - } - - final int len = builder.length(); - if (len >= 2) { - builder.setLength(len - 2); - } else { - graph.addNode(task); - } - } - - final List taskList = new ArrayList<>(); - outer: - while (graph.nodeCount() > 0) { - @SuppressWarnings("unchecked") - final List list = Graphs.getSinkNodes(graph); - for (final Task task : list) { - taskList.add(0, task); - graph.removeNode(task); - continue outer; - } - // break loop if no nodes removed - break; - } - - for (final Task task : taskList) { - Element taskElement = new Element("cms:task", - CMS.CMS_XML_NS); - taskElement.addAttribute("name", - task.getLabel().getValue(language)); - taskElement.addAttribute("state", - task.getTaskState().toString()); - for (final TaskComment comment : task.getComments()) { - final Element commentElement = new Element( - "cms:taskComment", CMS.CMS_XML_NS); - final User author = comment.getAuthor(); - final String authorName; - if (author == null) { - authorName = "Anonymous"; - } else { - authorName = author.getName(); - } - - commentElement.addAttribute("author", authorName); - commentElement.addAttribute("comment", - comment.getComment()); - taskElement.addContent(commentElement); - } - - workflowElement.addContent(taskElement); - } - } - - // Revision History (we are using to "transaction" for XML elememts - // here because this used by the old API and we don't want to brake - // the XSL. - final Element revisionsElement = new Element( - "cms:transactionSummary", - CMS.CMS_XML_NS); - final ContentItemRepository itemRepo = cdiUtil.findBean( - ContentItemRepository.class); - final List revisions = itemRepo.retrieveRevisions( - item, item.getObjectId()); - if (revisions != null && !revisions.isEmpty()) { - revisionsElement.addAttribute( - "creationDate", - FormatStandards.formatDate(revisions.get(0) - .getRevisionDate())); - revisionsElement.addAttribute( - "lastModifiedDate", - FormatStandards - .formatDate(revisions.get(revisions.size() - 1) - .getRevisionDate())); - final ContentSectionManager sectionManager = cdiUtil.findBean( - ContentSectionManager.class); - final ItemResolver itemResolver = sectionManager - .getItemResolver(section); - for (final CcmRevision revision : revisions) { - final Element revisionElement = new Element( - "cms:transaction", CMS.CMS_XML_NS); - revisionElement.addAttribute( - "date", - FormatStandards.formatDate(revision.getRevisionDate())); - final String authorName; - if (revision.getUserName() == null - || revision.getUserName().trim().isEmpty()) { - authorName = "Anonymous"; - } else { - authorName = revision.getUserName(); - } - revisionElement.addAttribute("author", authorName); - - final String url = String.format( - "%s?revision=%d", - itemResolver.generateItemURL( - state, - item, - section, - CMSDispatcher.PREVIEW), - revision.getId()); - revisionElement.addAttribute("url", url); - revisionsElement.addContent(revisionElement); - } - } - - // CATEGORY - final Element categoriesElement = new Element( - "cms:categorySummary", CMS.CMS_XML_NS); - - final List categories = item.getCategories().stream() - .map(categorization -> categorization.getCategory()) - .collect(Collectors.toList()); - final CategoryManager categoryManager = cdiUtil.findBean( - CategoryManager.class); - for (final Category category : categories) { - final Element categoryElement = new Element("cms:category", - CMS.CMS_XML_NS); - categoryElement.setText(categoryManager - .getCategoryPath(category)); - categoriesElement.addContent(categoryElement); - } - - // LIFECYCLE - final Element lifecycleElement = new Element("cms:lifecycleSummary", - CMS.CMS_XML_NS); - - final Lifecycle lifecycle = item.getLifecycle(); - if (lifecycle == null) { - lifecycleElement.addAttribute("noLifecycle", "1"); - } else { - lifecycleElement.addAttribute( - "name", - lifecycle.getDefinition().getLabel().getValue(language)); - lifecycleElement.addAttribute( - "startDate", - FormatStandards.formatDate(lifecycle.getStartDateTime())); - - final Date endDate = lifecycle.getEndDateTime(); - if (endDate == null) { - lifecycleElement.addAttribute("endDateString", - "last forever"); - } else { - lifecycleElement.addAttribute( - "endDateString", - String.format("expire on %s", - FormatStandards.formatDate(endDate))); - lifecycleElement.addAttribute( - "endDate", FormatStandards.formatDate(endDate)); - } - - lifecycleElement.addAttribute( - "hasBegun", Boolean.toString(lifecycle.isStarted())); - lifecycleElement.addAttribute( - "hasEnded", Boolean.toString(lifecycle.isFinished())); - } - - parent.addContent(itemElement); - parent.addContent(categoriesElement); - parent.addContent(linkElement); - parent.addContent(lifecycleElement); - parent.addContent(workflowElement); - parent.addContent(revisionsElement); - } - } - - /** - * Fetch the selected content item. - * - * @param state The page state - * - * @return The selected item - */ - protected ContentItem getContentItem(final PageState state) { - final ContentItem item = itemSelectionModel.getSelectedObject(state); - Assert.exists(item); - return item; - } - - /** - * Fetch the current content section. - * - * @param state The page state - * - * @return The content section - */ - protected ContentSection getContentSection(final PageState state) { - return CMS.getContext().getContentSection(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/AddPhaseForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/AddPhaseForm.java deleted file mode 100755 index 556a6e210..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/AddPhaseForm.java +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.form.FormErrorDisplay; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.IntegerParameter; -import com.arsdigita.bebop.parameters.NotEmptyValidationListener; -import com.arsdigita.bebop.parameters.NumberInRangeValidationListener; -import com.arsdigita.bebop.parameters.StringLengthValidationListener; -import com.arsdigita.bebop.parameters.TrimmedStringParameter; - -import org.librecms.lifecycle.LifecycleDefinition; -import org.librecms.lifecycle.PhaseDefinition; - -import com.arsdigita.cms.ui.CMSForm; -import com.arsdigita.cms.ui.FormSecurityListener; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.librecms.CmsConstants; -import org.librecms.contentsection.privileges.AdminPrivileges; - -import java.util.List; -import java.util.Locale; -import java.util.Optional; - -/** - * This class contains a form component to add a lifecycle phase definition. - * - * @author Jack Chung - * @author Xixi D'Moon - * @author Michael Pih - * @author Jens Pelzetter - */ -class AddPhaseForm extends CMSForm { - - private final static String LABEL = "label"; - private final static String DESCRIPTION = "description"; - private final static String DELAY_DAYS = "delay_days"; - private final static String DELAY_HOURS = "delay_hours"; - private final static String DELAY_MINUTES = "delay_minutes"; - private final static String DURATION_DAYS = "duration_days"; - private final static String DURATION_HOURS = "duration_hours"; - private final static String DURATION_MINUTES = "duration_minutes"; - private final static String SUBMIT = "submit"; - private final static String CANCEL = "cancel"; - - private final LifecycleDefinitionRequestLocal selectedLifecycle; - - private final TextField phaseLabel; - private final TextArea phaseDescription; - private final TextField delayDays; - private final TextField delayHours; - private final TextField delayMinutes; - private final TextField durationDays; - private final TextField durationHours; - private final TextField durationMinutes; - private final Submit submit; - private final Submit cancel; - - /** - * Constructor. - * - * @param cycles The cycle selection model. This is to tell the form which - * cycle definition is selected since phase definitions are - * associated to cycle definitions - */ - public AddPhaseForm(final LifecycleDefinitionRequestLocal selectedLifecycle) { - super("LifecyclePhaseDefinition"); - - this.selectedLifecycle = selectedLifecycle; - - final Label heading = new Label(gz("cms.ui.lifecycle.phase_add")); - heading.setFontWeight(Label.BOLD); - add(heading, ColumnPanel.FULL_WIDTH); - add(new FormErrorDisplay(this), ColumnPanel.FULL_WIDTH); - - add(new Label(gz("cms.ui.lifecycle.phase.name"))); - phaseLabel = new TextField(new TrimmedStringParameter(LABEL)); - phaseLabel.addValidationListener(new NotEmptyValidationListener()); - phaseLabel.setSize(40); - phaseLabel.setMaxLength(1000); - add(phaseLabel); - - add(new Label(gz("cms.ui.lifecycle.phase.description"))); - phaseDescription = new TextArea(new TrimmedStringParameter(DESCRIPTION)); - phaseDescription.addValidationListener( - new StringLengthValidationListener( - 4000)); - phaseDescription.setCols(40); - phaseDescription.setRows(5); - phaseDescription.setWrap(TextArea.SOFT); - add(phaseDescription); - - // phase delay - add(new Label(gz("cms.ui.lifecycle.phase_start_delay"))); - delayDays = new TextField(new IntegerParameter(DELAY_DAYS)); - delayHours = new TextField(new IntegerParameter(DELAY_HOURS)); - delayMinutes = new TextField(new IntegerParameter(DELAY_MINUTES)); - - //max value: days: 60 years, hours: 7 days, minutes: 1 day - delayDays.addValidationListener( - new NumberInRangeValidationListener(0, 21900)); - delayHours.addValidationListener(new NumberInRangeValidationListener( - 0, 168)); - delayMinutes.addValidationListener( - new NumberInRangeValidationListener(0, 1440)); - delayDays.setSize(7); - delayHours.setSize(7); - delayMinutes.setSize(7); - delayDays.setClassAttr("DaysField"); - delayHours.setClassAttr("HoursField"); - delayMinutes.setClassAttr("MinutesField"); - - final SimpleContainer delayContainer = new SimpleContainer(); - delayContainer.add(new Label(gz("cms.ui.lifecycle.phase_days"))); - delayContainer.add(delayDays); - delayContainer.add(new Label(gz("cms.ui.lifecycle.phase_hours"))); - delayContainer.add(delayHours); - delayContainer.add(new Label(gz("cms.ui.lifecycle.phase_minutes"))); - delayContainer.add(delayMinutes); - add(delayContainer); - - // phase duration - add(new Label(gz("cms.ui.lifecycle.phase_duration"))); - durationDays = new TextField(new IntegerParameter(DURATION_DAYS)); - durationHours = new TextField(new IntegerParameter(DURATION_HOURS)); - durationMinutes = new TextField( - new IntegerParameter(DURATION_MINUTES)); - - //max value: days: 60 years, hours: 7 days, minutes: 1 day - durationDays.addValidationListener( - new NumberInRangeValidationListener(0, 21900)); - durationHours.addValidationListener( - new NumberInRangeValidationListener(0, 168)); - durationMinutes.addValidationListener( - new NumberInRangeValidationListener(0, 1440)); - durationDays.setSize(7); - durationHours.setSize(7); - durationMinutes.setSize(7); - durationDays.setClassAttr("DaysField"); - durationHours.setClassAttr("HoursField"); - durationMinutes.setClassAttr("MinutesField"); - - final SimpleContainer durationContainer = new SimpleContainer(); - durationContainer.add(new Label(gz("cms.ui.lifecycle.phase_days"))); - durationContainer.add(durationDays); - durationContainer.add(new Label(gz("cms.ui.lifecycle.phase_hours"))); - durationContainer.add(durationHours); - durationContainer.add(new Label(gz("cms.ui.lifecycle.phase_minutes"))); - durationContainer.add(durationMinutes); - add(durationContainer); - - final SimpleContainer submitCancel = new SimpleContainer(); - submit = new Submit(SUBMIT, gz("cms.ui.lifecycle.phase.add_submit")); - submitCancel.add(submit); - cancel = new Submit(CANCEL, gz("cms.ui.lifecycle.phase.add_cancel")); - submitCancel.add(cancel); - add(submitCancel, ColumnPanel.FULL_WIDTH | ColumnPanel.CENTER); - - addSubmissionListener(new FormSecurityListener( - AdminPrivileges.ADMINISTER_LIFECYLES)); - - addValidationListener(new FormValidationListener() { - - @Override - public final void validate(final FormSectionEvent event) - throws FormProcessException { - final PageState state = event.getPageState(); - validateDuration(state); - validateUniqueName(state); - } - - }); - - addProcessListener(new FormProcessListener() { - - @Override - public final void process(final FormSectionEvent event) - throws FormProcessException { - addPhase(event.getPageState()); - } - - }); - } - - /** - * Returns true if this form was cancelled. - * - * @param state The page state - * - * @return True if the form was cancelled, false otherwise - * - * @pre state != null - */ - @Override - public boolean isCancelled(final PageState state) { - return cancel.isSelected(state); - } - - /** - * Add a new phase using data from the form. - * - * @param state The page state - * - * @pre state != null - */ - protected void addPhase(final PageState state) throws FormProcessException { - final String label = (String) phaseLabel.getValue(state); - final String description = (String) phaseDescription.getValue(state); - final int delDays = (int) Optional - .ofNullable(delayDays.getValue(state)) - .orElseGet(() -> 0); - final int delHours = (int) Optional - .ofNullable(delayHours.getValue(state)) - .orElseGet(() -> 0); - final int delMinutes = (int) Optional - .ofNullable(delayMinutes.getValue(state)) - .orElseGet(() -> 0); - final int durDays = (int) Optional - .ofNullable(durationDays.getValue(state)) - .orElseGet(() -> 0); - final int durHours = (int) Optional - .ofNullable(durationHours.getValue(state)) - .orElseGet(() -> 0); - final int durMinutes = (int) Optional - .ofNullable(durationMinutes.getValue(state)) - .orElseGet(() -> 0); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final LifecycleAdminPaneController controller = cdiUtil - .findBean(LifecycleAdminPaneController.class); - controller.addPhaseDefinition( - selectedLifecycle.getLifecycleDefinition(state), - label, - description, - delDays, - delHours, - delMinutes, - durDays, - durHours, - durMinutes); - } - - /** - * Validate name uniqueness. - * - * @param state The page state - * - * @pre state != null - */ - protected void validateUniqueName(final PageState state) - throws FormProcessException { - - final String label = (String) phaseLabel.getValue(state); - - final LifecycleDefinition cycleDef = selectedLifecycle - .getLifecycleDefinition(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final LifecycleAdminPaneController controller = cdiUtil - .findBean(LifecycleAdminPaneController.class); - final List phaseDefs = controller - .getPhaseDefinitions(cycleDef); - - final ConfigurationManager confManager = cdiUtil.findBean( - ConfigurationManager.class); - final KernelConfig kernelConfig = confManager.findConfiguration( - KernelConfig.class); - final Locale defaultLocale = kernelConfig.getDefaultLocale(); - - final boolean duplicateLabel = phaseDefs - .stream() - .map(phaseDef -> phaseDef.getLabel().getValue(defaultLocale)) - .anyMatch(phaseDefLabel -> phaseDefLabel.equalsIgnoreCase(label)); - - if (duplicateLabel) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.lifecycle.phase_name_not_unique", - CmsConstants.CMS_BUNDLE)); - } - } - - /** - * Validate the phase duration. The duration cannot be 0. - * - * @param state The page state - * - * @pre state != null - */ - protected void validateDuration(final PageState state) - throws FormProcessException { - - final Integer durDays = (Integer) durationDays.getValue(state); - final Integer durHours = (Integer) durationHours.getValue(state); - final Integer durMinutes = (Integer) durationMinutes.getValue(state); - - // Phase duration is infinite, so the duration is valid. - if (durDays == null && durHours == null && durMinutes == null) { - return; - } - - int days, hours, minutes; - if (durDays != null) { - days = durDays; - } else { - days = 0; - } - - if (durHours != null) { - hours = durHours; - } else { - hours = 0; - } - - if (durMinutes != null) { - minutes = durMinutes; - } else { - minutes = 0; - } - - if ((days + hours + minutes) == 0) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.lifecycle.phase_duration_negative", - CmsConstants.CMS_BUNDLE)); - } - } - - private static GlobalizedMessage gz(final String key) { - return new GlobalizedMessage(key, - CmsConstants.CMS_BUNDLE); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/BaseLifecycleForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/BaseLifecycleForm.java deleted file mode 100755 index cf22948df..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/BaseLifecycleForm.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.NotEmptyValidationListener; -import com.arsdigita.bebop.parameters.StringLengthValidationListener; -import com.arsdigita.bebop.parameters.TrimmedStringParameter; - -import com.arsdigita.cms.ui.BaseForm; -import com.arsdigita.cms.ui.FormSecurityListener; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.contentsection.privileges.AdminPrivileges; - -/** - * @author Justin Ross - * @author Jens Pelzetter - */ -class BaseLifecycleForm extends BaseForm { - - private final TextField lifecycleName; - private final TextArea lifecycleDescription; - - BaseLifecycleForm(final String key, final GlobalizedMessage message) { - super(key, message); - - lifecycleName = new TextField(new TrimmedStringParameter("label")); - addField(gz("cms.ui.lifecycle.name"), lifecycleName); - - lifecycleName.addValidationListener(new NotEmptyValidationListener()); - lifecycleName.setSize(40); - lifecycleName.setMaxLength(1000); - - lifecycleDescription = new TextArea( - new TrimmedStringParameter("description")); - addField(gz("cms.ui.lifecycle.description"), lifecycleDescription); - - lifecycleDescription.addValidationListener( - new StringLengthValidationListener(4000)); - lifecycleDescription.setCols(40); - lifecycleDescription.setRows(5); - lifecycleDescription.setWrap(TextArea.SOFT); - - addAction(new Finish()); - addAction(new Cancel()); - - addSubmissionListener(new FormSecurityListener( - AdminPrivileges.ADMINISTER_LIFECYLES)); - } - - protected TextField getLifecycleName() { - return lifecycleName; - } - - protected TextArea getLifecycleDescription() { - return lifecycleDescription; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/DeletePhaseForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/DeletePhaseForm.java deleted file mode 100755 index 1014ea905..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/DeletePhaseForm.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.Hidden; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.parameters.LongParameter; -import com.arsdigita.bebop.parameters.NotNullValidationListener; - -import org.librecms.lifecycle.PhaseDefinition; - -import com.arsdigita.cms.ui.CMSForm; -import com.arsdigita.cms.ui.FormSecurityListener; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.privileges.AdminPrivileges; -import org.librecms.lifecycle.PhaseDefinititionRepository; - -/** - * This class handles the deleting of a phase definition. - * - * @author Jack Chung - * @author Jens Pelzetter - */ -class DeletePhaseForm extends CMSForm - implements FormProcessListener, FormInitListener { - - private final PhaseRequestLocal selectedPhaseDef; - - private final Hidden selectedPhaseDefId; - private final Submit deleteWidget; - private final Submit cancelWidget; - - /** - * @param m The phase selection model. This tells the form which phase - * definition is selected. - */ - public DeletePhaseForm(final PhaseRequestLocal selectedPhaseDef) { - super("PhaseDefinitionDelete"); - - this.selectedPhaseDef = selectedPhaseDef; - - selectedPhaseDefId = new Hidden(new LongParameter("id")); - add(selectedPhaseDefId); - selectedPhaseDefId - .addValidationListener(new NotNullValidationListener()); - - final BoxPanel buttons = new BoxPanel(BoxPanel.HORIZONTAL); - deleteWidget = new Submit("delete", - new GlobalizedMessage( - "cms.ui.lifecycle.phase.delete_submit", - CmsConstants.CMS_BUNDLE)); - deleteWidget.setClassAttr("deletePhase"); - buttons.add(deleteWidget); - - cancelWidget = new Submit("cancel", - new GlobalizedMessage( - "cms.ui.lifecycle.phase.delete_cancel", - CmsConstants.CMS_BUNDLE)); - cancelWidget.setClassAttr("canceldeletePhase"); - buttons.add(cancelWidget); - - add(buttons, ColumnPanel.CENTER | ColumnPanel.FULL_WIDTH); - - addInitListener(this); - - addSubmissionListener(new FormSecurityListener( - AdminPrivileges.ADMINISTER_LIFECYLES)); - - addProcessListener(this); - } - - /** - * Returns true if this form was cancelled. - * - * @param state The page state - * - * @return true if the form was cancelled, false otherwise - */ - @Override - public boolean isCancelled(final PageState state) { - return cancelWidget.isSelected(state); - } - - /** - * Form process listener. Deletes a phase definition - * - * @param event The form process event - * - * @exception FormProcessException - */ - @Override - public final void process(final FormSectionEvent event) - throws FormProcessException { - - final FormData data = event.getFormData(); - final Long key = (Long) data.get(selectedPhaseDefId.getName()); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PhaseDefinititionRepository phaseDefRepo = cdiUtil.findBean( - PhaseDefinititionRepository.class); - - // Check if the object is already deleted for double click - // protection. - final PhaseDefinition phaseDef = phaseDefRepo.findById(key).get(); - if (phaseDef != null) { - phaseDefRepo.delete(phaseDef); - } - - } - - /** - * Init listener. gets the id of the selected phase definition - * - * @param event The form init event - */ - @Override - public final void init(final FormSectionEvent event) { - final FormData data = event.getFormData(); - final PageState state = event.getPageState(); - - final Long phaseDefId = selectedPhaseDef.getPhase(state) - .getDefinitionId(); - - data.put(selectedPhaseDefId.getName(), phaseDefId); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/EditPhaseForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/EditPhaseForm.java deleted file mode 100755 index d92fd7ef7..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/EditPhaseForm.java +++ /dev/null @@ -1,435 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.ColumnPanel; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.form.FormErrorDisplay; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.IntegerParameter; -import com.arsdigita.bebop.parameters.NotEmptyValidationListener; -import com.arsdigita.bebop.parameters.NumberInRangeValidationListener; -import com.arsdigita.bebop.parameters.StringLengthValidationListener; -import com.arsdigita.bebop.parameters.TrimmedStringParameter; -import com.arsdigita.cms.lifecycle.Duration; - -import org.librecms.lifecycle.PhaseDefinition; - -import com.arsdigita.cms.ui.CMSForm; -import com.arsdigita.cms.ui.FormSecurityListener; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.librecms.CmsConstants; -import org.librecms.contentsection.privileges.AdminPrivileges; -import org.librecms.lifecycle.LifecycleDefinition; - -import java.util.List; -import java.util.Locale; -import java.util.Optional; - -/** - * This class contains a form component to edit a lifecycle phase definition. - * - * @author Jack Chung - * @author Xixi D'Moon - * @author Michael Pih - * @author Jens Pelzetter - */ -class EditPhaseForm extends CMSForm { - - private final static String LABEL = "label"; - private final static String DESCRIPTION = "description"; - private final static String DELAY_DAYS = "delay_days"; - private final static String DELAY_HOURS = "delay_hours"; - private final static String DELAY_MINUTES = "delay_minutes"; - private final static String DURATION_DAYS = "duration_days"; - private final static String DURATION_HOURS = "duration_hours"; - private final static String DURATION_MINUTES = "duration_minutes"; - private final static String SUBMIT = "submit"; - private final static String CANCEL = "cancel"; - - private final LifecycleDefinitionRequestLocal selectedLifecycle; - private final PhaseRequestLocal selectedPhase; - - private final TextField phaseLabel; - private final TextArea phaseDescription; - private final TextField delayDays; - private final TextField delayHours; - private final TextField delayMinutes; - private final TextField durationDays; - private final TextField durationHours; - private final TextField durationMinutes; - private final Submit submit; - private final Submit cancel; - - /** - * Constructor. - * - * @param m A single selection model for phase definitions. This is to tell - * the form which phase definition is selected for editing. - * - * @pre phases != null - */ - public EditPhaseForm( - final LifecycleDefinitionRequestLocal selectedLifecycle, - final PhaseRequestLocal selectedPhase) { - - super("EditPhaseDefinition"); - - this.selectedLifecycle = selectedLifecycle; - this.selectedPhase = selectedPhase; - - add(new Label()); - add(new FormErrorDisplay(this)); - - add(new Label(gz("cms.ui.lifecycle.phase.name"))); - phaseLabel = new TextField(new TrimmedStringParameter(LABEL)); - phaseLabel.addValidationListener(new NotEmptyValidationListener()); - phaseLabel.setSize(40); - phaseLabel.setMaxLength(1000); - add(phaseLabel); - - add(new Label(gz("cms.ui.lifecycle.phase.description"))); - phaseDescription = new TextArea(new TrimmedStringParameter(DESCRIPTION)); - phaseDescription.addValidationListener( - new StringLengthValidationListener( - 4000)); - phaseDescription.setCols(40); - phaseDescription.setRows(5); - phaseDescription.setWrap(TextArea.SOFT); - add(phaseDescription); - - // Phase duration - // Max value: days: 60 years, hours: 7 days, minutes: 1 day - delayDays = new TextField(new IntegerParameter(DELAY_DAYS)); - delayDays.addValidationListener(new NumberInRangeValidationListener(0, - 21900)); - delayDays.setSize(7); - delayDays.setClassAttr("DaysField"); - - delayHours = new TextField(new IntegerParameter(DELAY_HOURS)); - delayHours.addValidationListener( - new NumberInRangeValidationListener(0, 168)); - delayHours.setClassAttr("HoursField"); - delayHours.setSize(7); - - delayMinutes = new TextField(new IntegerParameter(DELAY_MINUTES)); - delayMinutes.addValidationListener( - new NumberInRangeValidationListener(0, 1440)); - delayMinutes.setSize(7); - delayMinutes.setClassAttr("MinutesField"); - - add(new Label( - new GlobalizedMessage("cms.ui.lifecycle.phase_start_delay", - CmsConstants.CMS_BUNDLE))); - final SimpleContainer delayContainer = new SimpleContainer(); - delayContainer.add(new Label(gz("cms.ui.lifecycle.phase_days"))); - delayContainer.add(delayDays); - delayContainer.add(new Label(gz("cms.ui.lifecycle.phase_hours"))); - delayContainer.add(delayHours); - delayContainer.add(new Label(gz("cms.ui.lifecycle.phase_minutes"))); - delayContainer.add(delayMinutes); - add(delayContainer); - - // Phase duration - // Max value: days: 60 years, hours: 7 days, minutes: 1 day - durationDays = new TextField(new IntegerParameter(DURATION_DAYS)); - durationDays.addValidationListener( - new NumberInRangeValidationListener(0, - 21900)); - durationDays.setSize(7); - durationDays.setClassAttr("DaysField"); - - durationHours = new TextField(new IntegerParameter(DURATION_HOURS)); - durationHours.addValidationListener(new NumberInRangeValidationListener( - 0, - 168)); - durationHours.setSize(7); - durationHours.setClassAttr("HoursField"); - - durationMinutes = new TextField(new IntegerParameter(DURATION_MINUTES)); - durationMinutes.addValidationListener( - new NumberInRangeValidationListener(0, 1440)); - durationMinutes.setSize(7); - durationMinutes.setClassAttr("MinutesField"); - - add(new Label(gz("cms.ui.lifecycle.phase_duration"))); - final SimpleContainer durationContainer = new SimpleContainer(); - durationContainer.add(new Label(gz("cms.ui.lifecycle.phase_days"))); - durationContainer.add(durationDays); - durationContainer.add(new Label(gz("cms.ui.lifecycle.phase_hours"))); - durationContainer.add(durationHours); - durationContainer.add(new Label(gz("cms.ui.lifecycle.phase_minutes"))); - durationContainer.add(durationMinutes); - add(durationContainer); - - // Submit and cancel buttons - final SimpleContainer submitCancelContainer = new SimpleContainer(); - submit = new Submit(SUBMIT, gz("cms.ui.lifecycle.phase.edit_submit")); - submitCancelContainer.add(submit); - cancel = new Submit(CANCEL, gz("cms.ui.lifecycle.phase.edit_cancel")); - submitCancelContainer.add(cancel); - add(submitCancelContainer, ColumnPanel.FULL_WIDTH | ColumnPanel.CENTER); - - // Add form listeners. - addInitListener(new FormInitListener() { - - @Override - public final void init(final FormSectionEvent event) - throws FormProcessException { - initializePhaseDefinition(event.getPageState()); - } - - }); - - addSubmissionListener(new FormSecurityListener( - AdminPrivileges.ADMINISTER_LIFECYLES)); - - addValidationListener(new FormValidationListener() { - - @Override - public final void validate(final FormSectionEvent event) - throws FormProcessException { - final PageState state = event.getPageState(); - - validateDuration(state); - validateUniqueName(state); - } - - }); - - addProcessListener(new FormProcessListener() { - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - updatePhaseDefinition(event.getPageState()); - } - - }); - } - - /** - * Returns true if this form was cancelled. - * - * @param state The page state - * - * @return True if the form was cancelled, false otherwise - * - * @pre state != null - */ - @Override - public boolean isCancelled(final PageState state) { - return cancel.isSelected(state); - } - - /** - * Populate the form fields with the current phase definition attribute - * values. - * - * @param state The page state - * - * @pre state != null - */ - private void initializePhaseDefinition(final PageState state) - throws FormProcessException { - - final Locale defaultLocale = KernelConfig.getConfig().getDefaultLocale(); - - final PhaseDefinition phaseDef = selectedPhase.getPhase(state); - phaseLabel.setValue(state, phaseDef.getLabel().getValue(defaultLocale)); - phaseDescription.setValue(state, - phaseDef - .getDescription() - .getValue(defaultLocale)); - - final long[] delay = Duration.formatDHM(phaseDef.getDefaultDelay()); - delayDays.setValue(state, delay[0]); - delayHours.setValue(state, delay[1]); - delayMinutes.setValue(state, delay[2]); - - final Long duration = phaseDef.getDefaultDuration(); - if (duration != 0) { - final Long[] dhm = Duration.formatDHM(duration); - durationDays.setValue(state, dhm[0]); - durationHours.setValue(state, dhm[1]); - durationMinutes.setValue(state, dhm[2]); - } - } - - /** - * Update the phase definition with values from the form. - * - * @param state The page state - * - * @pre state != null - */ - private void updatePhaseDefinition(final PageState state) - throws FormProcessException { - - final String label = (String) phaseLabel.getValue(state); - final String description = (String) phaseDescription.getValue(state); - final int delDays = (int) Optional - .ofNullable(delayDays.getValue(state)) - .orElseGet(() -> 0); - final int delHours = (int) Optional - .ofNullable(delayHours.getValue(state)) - .orElseGet(() -> 0);; - final int delMinutes = (int) Optional - .ofNullable(delayMinutes.getValue(state)) - .orElseGet(() -> 0);; - final int durDays = (int) Optional - .ofNullable(durationDays.getValue(state)) - .orElseGet(() -> 0);; - final int durHours = (int) Optional - .ofNullable(durationHours.getValue(state)) - .orElseGet(() -> 0);; - final int durMinutes = (int) Optional - .ofNullable(durationMinutes.getValue(state)) - .orElseGet(() -> 0);; - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final LifecycleAdminPaneController controller = cdiUtil - .findBean(LifecycleAdminPaneController.class); - - controller.updatePhaseDefinition(selectedPhase.getPhase(state), - label, - description, - delDays, - delHours, - delMinutes, - durDays, - durHours, - durMinutes); - } - - /** - * Ensures that the new name (if it has changed) is unique within the - * lifecycle definition. - * - * @param state The page state - * - * @pre state != null - */ - private void validateUniqueName(final PageState state) - throws FormProcessException { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ConfigurationManager confManager = cdiUtil.findBean( - ConfigurationManager.class); - final KernelConfig kernelConfig = confManager.findConfiguration( - KernelConfig.class); - final Locale defaultLocale = kernelConfig.getDefaultLocale(); - - final String oldLabel = selectedPhase - .getPhase(state) - .getLabel() - .getValue(defaultLocale); - final String newLabel = (String) phaseLabel.getValue(state); - - if (oldLabel.equals(newLabel)) { - //Label has node changed, no validation required. - return; - } - - final LifecycleDefinition cycleDef = selectedLifecycle - .getLifecycleDefinition(state); - final LifecycleAdminPaneController controller = cdiUtil - .findBean(LifecycleAdminPaneController.class); - final List phaseDefs = controller - .getPhaseDefinitions(cycleDef); - - - - final boolean duplicateLabel = phaseDefs - .stream() - .map(phaseDef -> phaseDef.getLabel().getValue(defaultLocale)) - .anyMatch(phaseDefLabel -> { - return phaseDefLabel.equalsIgnoreCase(newLabel); - }); - - if (duplicateLabel) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.lifecycle.phase_name_not_unique", - CmsConstants.CMS_BUNDLE)); - } - } - - /** - * Validate the phase duration. The duration cannot be 0. - * - * @param state The page state - * - * - */ - private void validateDuration(final PageState state) - throws FormProcessException { - - final Integer durDays = (Integer) durationDays.getValue(state); - final Integer durHours = (Integer) durationHours.getValue(state); - final Integer durMinutes = (Integer) durationMinutes.getValue(state); - - // Phase duration is infinite, so the duration is valid. - if (durDays == null && durHours == null && durMinutes == null) { - return; - } - - int days, hours, minutes; - if (durDays == null) { - days = 0; - } else { - days = durDays; - } - - if (durHours == null) { - hours = 0; - } else { - hours = durHours; - } - - if (durMinutes == null) { - minutes = 0; - } else { - minutes = durMinutes; - } - - if ((days + hours + minutes) == 0) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.phase.duration_negative", - CmsConstants.CMS_BUNDLE)); - } - } - - private static GlobalizedMessage gz(final String key) { - return new GlobalizedMessage(key, CmsConstants.CMS_BUNDLE); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemLifecycleAdminController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemLifecycleAdminController.java deleted file mode 100644 index 024c41c33..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemLifecycleAdminController.java +++ /dev/null @@ -1,350 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.cms.ui.ContentItemPage; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.librecms.CMSConfig; -import org.libreccm.categorization.Categorization; -import org.libreccm.categorization.Category; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.l10n.GlobalizationHelper; -import org.libreccm.security.User; -import org.libreccm.workflow.Task; -import org.libreccm.workflow.TaskManager; -import org.libreccm.workflow.TaskState; -import org.libreccm.workflow.Workflow; -import org.libreccm.workflow.WorkflowManager; -import org.libreccm.workflow.WorkflowRepository; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionRepository; -import org.librecms.lifecycle.Lifecycle; -import org.librecms.lifecycle.LifecycleDefinition; -import org.librecms.lifecycle.LifecycleDefinitionRepository; -import org.librecms.lifecycle.LifecycleManager; -import org.librecms.lifecycle.LifecycleRepository; -import org.librecms.lifecycle.Phase; -import org.librecms.lifecycle.PhaseDefinition; -import org.librecms.lifecycle.PhaseRepository; -import org.librecms.workflow.CmsTask; -import org.librecms.workflow.CmsTaskType; - -import java.io.Serializable; -import java.util.Date; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class ItemLifecycleAdminController implements Serializable { - - private static final Logger LOGGER = LogManager - .getLogger(ItemLifecycleAdminController.class); - private static final long serialVersionUID = -6482423583933975632L; - - @Inject - private ConfigurationManager confManager; - - @Inject - private GlobalizationHelper globalizationHelper; - - @Inject - private ContentItemRepository itemRepo; - - @Inject - private ContentItemManager itemManager; - - @Inject - private LifecycleDefinitionRepository lifecycleDefRepo; - - @Inject - private LifecycleManager lifecycleManager; - - @Inject - private LifecycleRepository lifecycleRepo; - - @Inject - private PhaseRepository phaseRepo; - - @Inject - private ContentSectionRepository sectionRepo; - - @Inject - private TaskManager taskManager; - - @Inject - private WorkflowManager workflowManager; - - @Inject - private WorkflowRepository workflowRepo; - - @Transactional(Transactional.TxType.REQUIRED) - public boolean isAssignedToAbstractCategory(final ContentItem item) { - - final ContentItem contentItem = itemRepo - .findById(item.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", - item.getObjectId()))); - - final long count = contentItem - .getCategories() - .stream() - .map(Categorization::getCategory) - .filter(Category::isAbstractCategory) - .count(); - - return count > 0; - } - - @Transactional(Transactional.TxType.REQUIRED) - public List getLifecycleDefinitions( - final ContentSection section) { - - final ContentSection contentSection = sectionRepo - .findById(section.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentSection with ID %d in the database.", - section.getObjectId()))); - - return contentSection - .getLifecycleDefinitions() - .stream() - .collect(Collectors.toList()); - } - - @Transactional(Transactional.TxType.REQUIRED) - public Optional getDefaultLifecycle( - final ContentItem item) { - - final ContentItem contentItem = itemRepo - .findById(item.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", - item.getObjectId()))); - - final LifecycleDefinition definition = contentItem - .getContentType() - .getDefaultLifecycle(); - - if (definition == null) { - return Optional.empty(); - } else { - return Optional - .of(lifecycleDefRepo - .findById(definition.getDefinitionId()) - .get()); - } - } - - @Transactional(Transactional.TxType.REQUIRED) - public LifecycleDefinition getDefinitionOfLifecycle(final ContentItem item) { - -// final ContentItem contentItem = itemRepo -// .findById(item.getObjectId()) -// .orElseThrow(() -> new IllegalArgumentException(String -// .format("No ContentItem with ID %d in the database.", -// item.getObjectId()))); - final ContentItem liveItem = itemManager - .getLiveVersion(item, ContentItem.class) - .get(); - - return liveItem.getLifecycle().getDefinition(); - } - - @Transactional(Transactional.TxType.REQUIRED) - protected List findPhasesOfLifecycle( - final Lifecycle lifecycle) { - - Objects.requireNonNull(lifecycle); - - final Lifecycle ofLifecycle = lifecycleRepo - .findById(lifecycle.getLifecycleId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No Lifecycle with ID %d in the database.", - lifecycle.getLifecycleId()))); - - return ofLifecycle - .getPhases() - .stream() - .map(this::buildItemPhaseTableRow) - .collect(Collectors.toList()); - - } - - private ItemPhaseTableRow buildItemPhaseTableRow(final Phase phase) { - - final PhaseDefinition definition = phase.getDefinition(); - - final ItemPhaseTableRow row = new ItemPhaseTableRow(); - row.setName(globalizationHelper - .getValueFromLocalizedString(definition.getLabel())); - row.setDescription(globalizationHelper - .getValueFromLocalizedString(definition.getDescription())); - row.setStartDate(phase.getStartDateTime()); - row.setEndDate(phase.getEndDateTime()); - - return row; - } - - @Transactional(Transactional.TxType.REQUIRED) - public String getPublishingTabUrl(final ContentItem item) { - - final ContentItem contentItem = itemRepo - .findById(item.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with ID %d in the database.", - item.getObjectId()))); - - return ContentItemPage.getItemURL(contentItem, - ContentItemPage.PUBLISHING_TAB); - } - - @Transactional(Transactional.TxType.REQUIRED) - public void repulish(final ContentItem item) { - - Objects.requireNonNull(item); - - final Optional liveItem = itemManager - .getLiveVersion(item, ContentItem.class); - if (liveItem.isPresent()) { - final ContentItem contentItem = itemRepo - .findById(item.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with Id %d in the database.", - item.getObjectId()))); - itemManager.publish(contentItem); - final Workflow workflow = contentItem.getWorkflow(); - if (workflow != null - && workflow.isActive() - && workflow.getTasksState() == TaskState.ENABLED) { - - workflowManager.finish(contentItem.getWorkflow()); - } - } - } - - @Transactional(Transactional.TxType.REQUIRED) - public void publish(final String itemUuid, - final long cycleDefId, - final Date endDate, - final String workflowUuid, - final User user) { - - final ContentItem contentItem = itemRepo - .findByUuid(itemUuid) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ContentItem with UUID %s in the database.", - itemUuid))); - - final LifecycleDefinition cycleDef = lifecycleDefRepo - .findById(cycleDefId) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No LifecycleDefinition with ID %d in the database.", - cycleDefId))); - - if (itemManager.isLive(contentItem)) { - contentItem.setLifecycle(null); - itemRepo.save(contentItem); - } - - final ContentItem pending = itemManager.publish(contentItem, cycleDef); - final Lifecycle lifecycle = pending.getLifecycle(); - - if (endDate != null) { - - // update individual phases - final List phases = lifecycle.getPhases(); - - for (final Phase phase : phases) { - final Date thisStart = phase.getStartDateTime(); - if (thisStart.compareTo(endDate) > 0) { - phase.setStartDateTime(endDate); - phaseRepo.save(phase); - } - } - } - - lifecycleManager.startLifecycle(lifecycle); - - if (workflowUuid != null) { - final Workflow workflow = workflowRepo - .findByUuid(workflowUuid) - .get(); - finish(workflow, contentItem, user); - } - } - - private void finish(final Workflow workflow, - final ContentItem item, - final User user) { - - if (workflow != null && user != null) { - - final List enabledTasks = workflowManager - .findEnabledTasks(workflow); - for (final Task task : enabledTasks) { - LOGGER.debug("Task is {}.", task.getUuid()); - if (task instanceof CmsTask) { - final CmsTask cmsTask = (CmsTask) task; - - if (cmsTask.getTaskType() == CmsTaskType.DEPLOY) { - LOGGER.debug("Found DEPLOY task."); - taskManager.finish(cmsTask); - } - } - } - - final CMSConfig cmsConfig = confManager - .findConfiguration(CMSConfig.class); - - if (cmsConfig.isDeleteWorkflowAfterPublication()) { - workflowRepo.delete(workflow); - } else { - // restart the workflow by recreating it - // from the same workflow template - final Workflow template = workflow.getTemplate(); - if (template == null) { - return; - } - workflowRepo.delete(workflow); - final Workflow restarted = workflowManager.createWorkflow( - template, item); - // Startring the workflow will probably do the wrong thing, because most of the time - // the current user would be a publisher, not an author - workflowRepo.save(restarted); - } - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemLifecycleAdminPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemLifecycleAdminPane.java deleted file mode 100755 index 10192347e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemLifecycleAdminPane.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; - -import org.librecms.contentsection.ContentItem; -import org.librecms.lifecycle.Lifecycle; - -import com.arsdigita.cms.ui.BaseItemPane; -import com.arsdigita.cms.ui.ContentItemPage; -import com.arsdigita.cms.ui.item.ContentItemRequestLocal; -import com.arsdigita.toolbox.ui.LayoutPanel; -import com.arsdigita.web.RedirectSignal; -import com.arsdigita.web.URL; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.util.Objects; -import java.util.Optional; - -/** - * @author Michael Pih - * @author Jack Chung - * @author Justin Ross <jross@redhat.com> - * @author Jens Pelzetter - */ -public class ItemLifecycleAdminPane extends BaseItemPane { - - private static final Logger LOGGER = LogManager.getLogger( - ItemLifecycleAdminPane.class); - private final ContentItemRequestLocal selectedItem; - private final LifecycleRequestLocal selectedLifecycle; - private final LayoutPanel introPane; - private final LayoutPanel detailPane; - private final LayoutPanel selectPane; - private final LayoutPanel lockedPane; - private final LayoutPanel errorPane; - private final LayoutPanel cantPublishPane; - - public ItemLifecycleAdminPane(final ContentItemRequestLocal selectedItem) { - this.selectedItem = selectedItem; - selectedLifecycle = new ItemLifecycleRequestLocal(); - - introPane = new LayoutPanel(); - add(introPane); - - final Label message = new Label(gz("cms.ui.item.lifecycle.intro")); - introPane.setBody(message); - - detailPane = new LayoutPanel(); - add(detailPane); - - final ItemLifecycleItemPane itemPane = new ItemLifecycleItemPane( - selectedItem, selectedLifecycle); - detailPane.setBody(itemPane); - - selectPane = new LayoutPanel(); - add(selectPane); - - final ItemLifecycleSelectForm selectForm = new ItemLifecycleSelectForm( - selectedItem); - selectPane.setBody(selectForm); - - lockedPane = new LayoutPanel(); - add(lockedPane); - - final Label lockedMsg = new Label(gz( - "cms.ui.item.lifecycle.publish_locked")); - lockedPane.setBody(lockedMsg); - final ControlLink lockedUpdateLink = new ControlLink(new Label(gz( - "cms.ui.item.lifecycle.publish_locked.update"))); - lockedUpdateLink.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(final ActionEvent event) { - throw new RedirectSignal( - URL.getDispatcherPath() - + ContentItemPage.getItemURL( - selectedItem.getContentItem(event.getPageState()), - ContentItemPage.PUBLISHING_TAB), - true); - } - - }); - lockedPane.setBottom(lockedUpdateLink); - - errorPane = new LayoutPanel(); - add(errorPane); - - final Label errorMsg = new Label(gz("cms.ui.lifecycle.publish.error")); - errorPane.setBody(errorMsg); - - cantPublishPane = new LayoutPanel(); - add(cantPublishPane); - - final Label cantPublish = new Label(gz( - "cms.ui.lifecycle.publish.not_possible_abstract_category")); - cantPublishPane.setBody(cantPublish); - - connect(selectForm, detailPane); - } - - private class ItemLifecycleRequestLocal extends LifecycleRequestLocal { - - @Override - protected final Object initialValue(final PageState state) { - final ContentItem item = selectedItem.getContentItem(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemManager itemManager = cdiUtil - .findBean(ContentItemManager.class); - final Optional liveItem = itemManager - .getLiveVersion(item, ContentItem.class); - if (liveItem.isPresent()) { - - final Lifecycle lifecycle = liveItem.get().getLifecycle(); - LOGGER.debug("Returning lifecycle {}", - Objects.toString(lifecycle)); - return lifecycle; - } else { - return null; - } - } - - } - - @Override - public final void register(final Page page) { - super.register(page); - - page.addActionListener(new VisibilityListener()); - } - - private class VisibilityListener implements ActionListener { - - @Override - public final void actionPerformed(final ActionEvent event) { - LOGGER.debug("Determining which pane to show"); - - final PageState state = event.getPageState(); - -// if (CMSConfig.getConfig().isThreadPublishing() -// && PublishLock.getInstance().isLocked(m_item.getContentItem( -// state))) { -// if (PublishLock.getInstance().hasError(m_item.getContentItem( -// state))) { -// push(state, m_errorPane); -// } else { -// push(state, m_lockedPane); -// state.getResponse().addIntHeader("Refresh", 5); -// } -// } else - if (isAssignedToAbstractCategory(selectedItem.getContentItem(state))) { - push(state, cantPublishPane); - } else { - if (state.isVisibleOnPage(ItemLifecycleAdminPane.this)) { - if (selectedLifecycle.getLifecycle(state) == null) { - if (hasPermission(state)) { - push(state, selectPane); - } else { - push(state, introPane); - } - } else { - push(state, detailPane); - } - } - } - } - - } - - private boolean hasPermission(final PageState state) { - final ContentItem item = selectedItem.getContentItem(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - - return permissionChecker.isPermitted(ItemPrivileges.PUBLISH, item); - } - - /** - * Checks if the item is assigned to an abstract category. - * - * A category is abstract if not items can assigned to it. - * - * @param item - * - * @return {@code true} if assigned to a abstract category, {@code false} if - * not. - */ - private boolean isAssignedToAbstractCategory(final ContentItem item) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ItemLifecycleAdminController controller = cdiUtil - .findBean(ItemLifecycleAdminController.class); - - return controller.isAssignedToAbstractCategory(item); - -// final long count = item.getCategories().stream() -// .filter(categorization -> { -// return categorization.getCategory().isAbstractCategory(); -// }) -// .count(); -// -// return count > 0; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemLifecycleItemPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemLifecycleItemPane.java deleted file mode 100755 index 5a7b1e15d..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemLifecycleItemPane.java +++ /dev/null @@ -1,956 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.ActionLink; -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.cms.ui.BaseItemPane; -import com.arsdigita.cms.ui.ContentItemPage; -import com.arsdigita.cms.ui.item.ContentItemRequestLocal; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.mail.Mail; -import com.arsdigita.toolbox.ui.ActionGroup; -import com.arsdigita.toolbox.ui.Property; -import com.arsdigita.toolbox.ui.PropertyList; -import com.arsdigita.toolbox.ui.Section; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.web.RedirectSignal; -import com.arsdigita.web.URL; -import com.arsdigita.xml.Element; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.librecms.CMSConfig; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.libreccm.security.PermissionChecker; -import org.libreccm.security.Shiro; -import org.libreccm.security.User; -import org.libreccm.security.UserRepository; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.contentsection.privileges.ItemPrivileges; -import org.librecms.lifecycle.Lifecycle; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.io.Writer; -import java.text.DateFormat; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Optional; - -import javax.mail.MessagingException; - -/** - * This class contains the component which displays the information for a - * particular lifecycle, with the ability to edit and delete. This information - * also includes the associated phases for this lifecycle, also with the ability - * to add, edit, and delete. - * - * @author Michael Pih - * @author Jack Chung - * @author Xixi D'Moon - * @author Justin Ross - * @author Jens Pelzetter - */ -class ItemLifecycleItemPane extends BaseItemPane { - - private static final Logger LOGGER = LogManager.getLogger( - ItemLifecycleItemPane.class); - private final ContentItemRequestLocal selectedItem; - private final LifecycleRequestLocal selectedLifecycle; - private final SimpleContainer detailPane; - - public ItemLifecycleItemPane(final ContentItemRequestLocal selectedItem, - final LifecycleRequestLocal selectedLifecycle) { - this.selectedItem = selectedItem; - this.selectedLifecycle = selectedLifecycle; - - detailPane = new SimpleContainer(); - add(detailPane); - setDefault(detailPane); - - detailPane.add(new SummarySection()); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil.findBean( - ContentItemRepository.class); - final ContentItemManager itemManager = cdiUtil.findBean( - ContentItemManager.class); - final GlobalizationHelper globalizationHelper = cdiUtil.findBean( - GlobalizationHelper.class); - - final Label lastPublishedLabel = new Label(); - lastPublishedLabel.addPrintListener(new PrintListener() { - - @Override - public void prepare(final PrintEvent event) { - final PageState state = event.getPageState(); - final Optional item = itemManager.getLiveVersion( - selectedItem.getContentItem(state), ContentItem.class); - final Label label = (Label) event.getTarget(); - final String dateStr; - if (item.isPresent()) { - final Date lastModifiedDate = itemRepo - .retrieveCurrentRevision(item.get(), - item.get().getObjectId()) - .getRevisionDate(); - dateStr = DateFormat.getDateTimeInstance( - DateFormat.LONG, - DateFormat.SHORT, - globalizationHelper.getNegotiatedLocale()) - .format(lastModifiedDate); - } else { - dateStr = ""; - } - - label.setLabel(new GlobalizedMessage( - "cms.ui.lifecycle.details.last_published", - CmsConstants.CMS_BUNDLE, - new Object[]{dateStr})); - } - - }); - detailPane.add(lastPublishedLabel); - - detailPane.add( - new PhaseSection()); - } - - private class SummarySection extends Section { - - public SummarySection() { - setHeading(new Label(gz("cms.ui.lifecycle.details"))); - - final ActionGroup group = new ActionGroup(); - setBody(group); - - if (CMSConfig.getConfig().isUseOldStyleItemLifecycleItemPane()) { - group.setSubject(new Properties()); - group.addAction(new UnpublishLink()); - group.addAction(new RepublishLink()); - group.addAction(new RepublishAndResetLink()); - } else { - group.addAction(new ActionForm()); - } - - } - - private class Properties extends PropertyList { - - @Override - protected final List properties(final PageState state) { - final List props = super.properties(state); - final Lifecycle cycle = selectedLifecycle.getLifecycle(state); - - final DateFormat format = DateFormat.getDateTimeInstance( - DateFormat.FULL, - DateFormat.FULL); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final GlobalizationHelper globalizationHelper = cdiUtil - .findBean(GlobalizationHelper.class); - final Locale language = globalizationHelper - .getNegotiatedLocale(); - - props.add(new Property( - gz("cms.ui.name"), - cycle.getDefinition().getLabel().getValue(language))); - props.add(new Property( - gz("cms.ui.item.lifecycle.start_date"), - format.format(cycle.getStartDateTime()))); - - final java.util.Date endDate = cycle.getEndDateTime(); - - if (endDate == null) { - props.add(new Property(gz("cms.ui.item.lifecycle.end_date"), - lz("cms.ui.none"))); - } else { - props.add(new Property(gz("cms.ui.item.lifecycle.end_date"), - format.format(endDate))); - } - - return props; - } - - } - - } - - private class PublishLink extends ActionLink { - - private final RequestLocal canPublishRequestLocal = new RequestLocal(); - - PublishLink(final Component component) { - super(component); - } - - @Override - public void generateXML(final PageState state, final Element parent) { - Boolean canPublish = (Boolean) canPublishRequestLocal.get(state); - if (null == canPublish) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - ContentItem item = selectedItem.getContentItem(state); - if (permissionChecker.isPermitted(ItemPrivileges.PUBLISH, item)) { - canPublish = true; - } else { - canPublish = false; - } - - canPublishRequestLocal.set(state, canPublish); - } - - if (canPublish) { - if (LOGGER.isDebugEnabled()) { - final ContentItem item = selectedItem.getContentItem(state); - LOGGER.debug("User can publish {}" + item.getUuid()); - } - - super.generateXML(state, parent); - } else if (LOGGER.isDebugEnabled()) { - final ContentItem item = selectedItem.getContentItem(state); - LOGGER.debug("User cannot publish {}", item.getUuid()); - } - } - - } - - private class UnpublishLink extends PublishLink { - - UnpublishLink() { - super(new Label(gz("cms.ui.item.lifecycle.unpublish"))); - - super.addActionListener(new Listener()); - } - - private class Listener implements ActionListener { - - @Override - public final void actionPerformed(final ActionEvent event) { - final PageState state = event.getPageState(); - final ContentItem item = selectedItem.getContentItem(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemManager itemManager = cdiUtil.findBean( - ContentItemManager.class); - - itemManager.unpublish(item); - - final String target = String.join( - "", - URL.getDispatcherPath(), - ContentItemPage.getItemURL(item, - ContentItemPage.AUTHORING_TAB)); - - throw new RedirectSignal(target, true); - } - - } - - } - - private static void republish(final ContentItem item, - final boolean reset, - final User user) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ItemLifecycleAdminController controller = cdiUtil - .findBean(ItemLifecycleAdminController.class); - - controller.repulish(item); - } - - private class RepublishLink extends PublishLink { - - RepublishLink() { - super(new Label(gz("cms.ui.item.lifecycle.republish"))); - - super.addActionListener(new Listener()); - } - - private class Listener implements ActionListener { - - @Override - public final void actionPerformed(final ActionEvent event) { - final PageState state = event.getPageState(); - final ContentItem item = selectedItem.getContentItem(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final Shiro shiro = cdiUtil.findBean(Shiro.class); - final User user = shiro.getUser().get(); - - /* - * jensp 2011-12-14: Check is threaded publishing is active. - * If yes, execute publishing in a thread. - */ - if (CMSConfig.getConfig().isThreadPublishing()) { - final Republisher republisher = new Republisher(item, user); - final Thread thread = new Thread(republisher); - thread.setUncaughtExceptionHandler( - new Thread.UncaughtExceptionHandler() { - - @Override - public void uncaughtException(final Thread thread, - final Throwable ex) { - final StringWriter strWriter = new StringWriter(); - final PrintWriter writer - = new PrintWriter(strWriter); - ex.printStackTrace(writer); - -// PublishLock.getInstance().setError(item, strWriter -// .toString()); - LOGGER.error(String.format( - "An error occurred while " - + "publishing the item '%s': ", - item.getUuid()), ex); - - if ((CMSConfig.getConfig() - .getPublishingFailureSender() - == null) - && (CMSConfig.getConfig() - .getPublishingFailureReceiver() - == null)) { - return; - } - - final UserRepository userRepo = cdiUtil.findBean( - UserRepository.class); - final User receiver = userRepo.findByEmailAddress( - CMSConfig.getConfig() - .getPublishingFailureReceiver()).get(); - final User sender = userRepo.findByEmailAddress( - CMSConfig.getConfig() - .getPublishingFailureSender()).get(); - - if ((sender != null) && (receiver != null)) { - final Writer traceWriter = new StringWriter(); - final PrintWriter printWriter = new PrintWriter( - traceWriter); - ex.printStackTrace(printWriter); - - final Mail notification = new Mail( - receiver.getPrimaryEmailAddress() - .getAddress(), - sender.getPrimaryEmailAddress().getAddress(), - String.format( - "Failed to publish item '%s'", - item.getUuid())); - notification.setBody(String.format( - "Publishing item '%s' failed " - + "with error message: %s.\n\n" - + "Stacktrace:\n%s", - item.getUuid(), - ex.getMessage(), - traceWriter.toString())); - try { - notification.send(); - } catch (MessagingException msgex) { - throw new UncheckedWrapperException(msgex); - } - } - } - - }); - - thread.start(); - - throw new RedirectSignal( - URL.getDispatcherPath() - + ContentItemPage.getItemURL(item, - ContentItemPage.PUBLISHING_TAB), - true); - /* - * jensp 2011-12-14 end - */ - } else { - republish(item, false, user); -// if (CMSConfig.getConfig().isUseStreamlinedCreation()) { -// throw new RedirectSignal( -// URL.there(state.getRequest(), -// CmsConstants.CONTENT_CENTER_URL), -// true); -// } - } - } - - } - - /** - * @author Jens Pelzetter - */ - private class Republisher implements Runnable { - - private final String itemUuid; - private final User user; - - private Republisher(final ContentItem item, User user) { - itemUuid = item.getUuid(); - this.user = user; - } - - @Override - public void run() { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil.findBean( - ContentItemRepository.class); - final ContentItem item = itemRepo.findByUuid(itemUuid).get(); - -// PublishLock.getInstance().lock(item); - republish(item, false, user); -// PublishLock.getInstance().unlock(item); - } - - } - - } - - private class RepublishAndResetLink extends PublishLink { - - RepublishAndResetLink() { - super(new Label(gz("cms.ui.item.lifecycle.republish_and_reset"))); - - super.addActionListener(new Listener()); - // warning gets a bit annoying, and link should be descriptive - // enough that it is not required - // setConfirmation("This will reset all your publication dates, are - // you sure you want to continue?"); - } - - private class Listener implements ActionListener { - - @Override - public final void actionPerformed(final ActionEvent e) { - final PageState state = e.getPageState(); - final ContentItem item = selectedItem.getContentItem(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final Shiro shiro = cdiUtil.findBean(Shiro.class); - final User user = shiro.getUser().get(); - - /** - * jensp 2011-12-14: Execute is a thread if threaded publishing - * is active. - */ - if (CMSConfig.getConfig().isThreadPublishing()) { - final Republisher republisher = new Republisher(item, user); - final Thread thread = new Thread(republisher); - thread.setUncaughtExceptionHandler( - new Thread.UncaughtExceptionHandler() { - - @Override - public void uncaughtException(final Thread thread, - final Throwable ex) { - final StringWriter strWriter = new StringWriter(); - final PrintWriter writer - = new PrintWriter(strWriter); - ex.printStackTrace(writer); - -// PublishLock.getInstance().setError(item, strWriter -// .toString()); - LOGGER.error(String.format( - "An error occurred while " - + "publishing the item '%s': ", - item.getUuid()), ex); - - if ((CMSConfig.getConfig(). - getPublishingFailureSender() == null) - && (CMSConfig.getConfig(). - getPublishingFailureReceiver() - == null)) { - return; - } - - final UserRepository userRepo = cdiUtil.findBean( - UserRepository.class); - final User receiver = userRepo.findByEmailAddress( - CMSConfig.getConfig() - .getPublishingFailureReceiver()).get(); - final User sender = userRepo.findByEmailAddress( - CMSConfig.getConfig() - .getPublishingFailureSender()).get(); - - if ((sender != null) && (receiver != null)) { - final Writer traceWriter = new StringWriter(); - final PrintWriter printWriter = new PrintWriter( - traceWriter); - ex.printStackTrace(printWriter); - - final Mail notification = new Mail( - receiver.getPrimaryEmailAddress() - .getAddress(), - sender.getPrimaryEmailAddress().getAddress(), - String.format( - "Failed to publish item '%s'", - item.getUuid())); - notification.setBody(String.format( - "Publishing item '%s' failed " - + "with error message: %s.\n\n" - + "Stacktrace:\n%s", - item.getUuid(), - ex.getMessage(), - traceWriter.toString())); - try { - notification.send(); - } catch (MessagingException msgex) { - throw new UncheckedWrapperException(msgex); - } - } - } - - }); - - thread.start(); - - throw new RedirectSignal( - URL.getDispatcherPath() - + ContentItemPage.getItemURL(item, - ContentItemPage.PUBLISHING_TAB), - true); - } else { - /** - * jensp 2011-12-14 end - */ - republish(item, true, user); -// if (CMSConfig.getConfig().isUseStreamlinedCreation()) { -// throw new RedirectSignal( -// URL.there(state.getRequest(), -// CmsConstants.CONTENT_CENTER_URL), -// true); -// } - } - } - - } - - /** - * @author Jens Pelzetter - */ - private class Republisher implements Runnable { - - private final String itemUuid; - private final User user; - - private Republisher(final ContentItem item, User user) { - itemUuid = item.getUuid(); - this.user = user; - } - - @Override - public void run() { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil.findBean( - ContentItemRepository.class); - final ContentItem item = itemRepo.findByUuid(itemUuid).get(); -// PublishLock.getInstance().lock(item); - republish(item, true, user); -// PublishLock.getInstance().unlock(item); - } - - } - - } - - private class PhaseSection extends Section { - - PhaseSection() { - super(gz("cms.ui.lifecycle.phases")); - - final ActionGroup group = new ActionGroup(); - setBody(group); - - group.setSubject(new PhaseTable()); - } - - } - - private class PhaseTable extends Table { - - PhaseTable() { - super(new ItemPhaseTableModelBuilder(selectedLifecycle), - new String[]{ - lz("cms.ui.name"), - lz("cms.ui.description"), - lz("cms.ui.item.lifecycle.start_date"), - lz("cms.ui.item.lifecycle.end_date") - }); - } - - } - - /** - * New style pane. Uses a select box for the action to avoid wrong clicks on - * unpublish. - * - * @author Jens Pelzetter - */ - private class ActionForm - extends Form - implements FormProcessListener, - FormInitListener { - - private static final String LIFECYCLE_ACTION - = "itemLifecycleItemPaneActionSelect"; - private static final String REPUBLISH = "republish"; - private static final String UNPUBLISH = "unpublish"; - private static final String REPUBLISH_AND_RESET = "republishAndReset"; - private final Submit submit; - private final Label notAuthorized; - - public ActionForm() { - super("itemLifecycleItemPaneActionForm"); - - final BoxPanel actionPanel = new BoxPanel(BoxPanel.HORIZONTAL); - final SingleSelect actionSelect = new SingleSelect( - LIFECYCLE_ACTION); - - actionSelect.addOption(new Option( - REPUBLISH, - new Label(new GlobalizedMessage( - "cms.ui.item.lifecycle.republish", - CmsConstants.CMS_BUNDLE)))); - if (!CMSConfig.getConfig().isHideResetLifecycleLink()) { - actionSelect.addOption(new Option( - REPUBLISH_AND_RESET, - new Label(new GlobalizedMessage( - "cms.ui.item.lifecycle.republish_and_reset", - CmsConstants.CMS_BUNDLE)))); - } - actionSelect.addOption(new Option( - UNPUBLISH, - new Label(gz("cms.ui.item.lifecycle.unpublish")))); - - submit = new Submit(gz("cms.ui.item.lifecycle.do")); - notAuthorized = new Label(gz( - "cms.ui.item.lifecycle.do.not_authorized")); - - actionPanel.add(actionSelect); - actionPanel.add(submit); - actionPanel.add(notAuthorized); - add(actionPanel); - - addInitListener(this); - addProcessListener(this); - } - - @Override - public void init(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final ContentItem item = selectedItem.getContentItem(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - - if (permissionChecker.isPermitted(ItemPrivileges.PUBLISH, item)) { - submit.setVisible(state, true); - notAuthorized.setVisible(state, false); - } else { - submit.setVisible(state, false); - notAuthorized.setVisible(state, true); - } - } - - @Override - public void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final Shiro shiro = cdiUtil.findBean(Shiro.class); - final User user = shiro.getUser().get(); - - String selected = (String) data.get(LIFECYCLE_ACTION); - final ContentItem item = selectedItem.getContentItem(state); - - /** - * Republish/Republish and Reset are executed in the thread if - * threaded publishing is active. - */ - if (REPUBLISH.equals(selected)) { - if (CMSConfig.getConfig().isThreadPublishing()) { - final RepublishRunner runner = new RepublishRunner(item, - user); - final Thread thread = new Thread(runner); - thread.setUncaughtExceptionHandler( - new Thread.UncaughtExceptionHandler() { - - @Override - public void uncaughtException(final Thread thread, - final Throwable ex) { - final StringWriter strWriter = new StringWriter(); - final PrintWriter writer - = new PrintWriter(strWriter); - ex.printStackTrace(writer); - -// PublishLock.getInstance().setError(item, strWriter -// .toString()); - LOGGER.error(String.format( - "An error occurred while " - + "publishing the item '%s': ", - item.getUuid()), ex); - - if ((CMSConfig.getConfig() - .getPublishingFailureSender() - == null) - && (CMSConfig.getConfig() - .getPublishingFailureReceiver() - == null)) { - return; - } - - final UserRepository userRepo = cdiUtil.findBean( - UserRepository.class); - final User receiver = userRepo.findByEmailAddress( - CMSConfig.getConfig() - .getPublishingFailureReceiver()).get(); - final User sender = userRepo.findByEmailAddress( - CMSConfig.getConfig() - .getPublishingFailureSender()).get(); - - if ((sender != null) && (receiver != null)) { - final Writer traceWriter = new StringWriter(); - final PrintWriter printWriter = new PrintWriter( - traceWriter); - ex.printStackTrace(printWriter); - - final Mail notification = new Mail( - receiver.getPrimaryEmailAddress() - .getAddress(), - sender.getPrimaryEmailAddress().getAddress(), - String.format( - "Failed to publish item '%s'", - item.getUuid())); - notification.setBody(String.format( - "Publishing item '%s' failed " - + "with error message: %s.\n\n" - + "Stacktrace:\n%s", - item.getUuid(), - ex.getMessage(), - traceWriter.toString())); - try { - notification.send(); - } catch (MessagingException msgex) { - throw new UncheckedWrapperException(msgex); - } - } - } - - }); - - thread.start(); - - throw new RedirectSignal( - URL.getDispatcherPath() - + ContentItemPage.getItemURL(item, - ContentItemPage.PUBLISHING_TAB), - true); - } else { - republish(item, false, user); - -// if (CMSConfig.getConfig().isUseStreamlinedCreation()) { -// throw new RedirectSignal( -// URL.there(state.getRequest(), -// CmsConstants.CONTENT_CENTER_URL), true); -// } - } - } else if (REPUBLISH_AND_RESET.equals(selected)) { - if (CMSConfig.getConfig().isThreadPublishing()) { - final RepublishAndResetRunner runner - = new RepublishAndResetRunner( - item, user); - final Thread thread = new Thread(runner); - thread.setUncaughtExceptionHandler( - new Thread.UncaughtExceptionHandler() { - - @Override - public void uncaughtException(final Thread thread, - final Throwable ex) { - final StringWriter strWriter = new StringWriter(); - final PrintWriter writer - = new PrintWriter(strWriter); - ex.printStackTrace(writer); - -// PublishLock.getInstance().setError(item, strWriter -// .toString()); - LOGGER.error(String.format( - "An error occurred while " - + "publishing the item '%s': ", - item.getUuid()), ex); - - if ((CMSConfig.getConfig() - .getPublishingFailureSender() - == null) - && (CMSConfig.getConfig() - .getPublishingFailureReceiver() - == null)) { - return; - } - - final UserRepository userRepo = cdiUtil.findBean( - UserRepository.class); - final User receiver = userRepo.findByEmailAddress( - CMSConfig.getConfig() - .getPublishingFailureReceiver()).get(); - final User sender = userRepo.findByEmailAddress( - CMSConfig.getConfig() - .getPublishingFailureSender()).get(); - - if ((sender != null) && (receiver != null)) { - final Writer traceWriter = new StringWriter(); - final PrintWriter printWriter = new PrintWriter( - traceWriter); - ex.printStackTrace(printWriter); - - final Mail notification = new Mail( - receiver.getPrimaryEmailAddress() - .getAddress(), - sender.getPrimaryEmailAddress().getAddress(), - String.format( - "Failed to publish item '%s'", - item.getUuid())); - notification.setBody(String.format( - "Publishing item '%s' failed " - + "with error message: %s.\n\n" - + "Stacktrace:\n%s", - item.getUuid(), - ex.getMessage(), - traceWriter.toString())); - try { - notification.send(); - } catch (MessagingException msgex) { - throw new UncheckedWrapperException(msgex); - } - } - } - - }); - - thread.start(); - - throw new RedirectSignal( - URL.getDispatcherPath() - + ContentItemPage.getItemURL(item, - ContentItemPage.PUBLISHING_TAB), - true); - } else { - republish(item, true, user); - -// if (CMSConfig.getConfig().isUseStreamlinedCreation()) { -// throw new RedirectSignal( -// URL.there(state.getRequest(), -// CmsConstants.CONTENT_CENTER_URL), true); -// } - } - } else if (UNPUBLISH.equals(selected)) { - final ContentItemManager itemManager = cdiUtil.findBean( - ContentItemManager.class); - itemManager.unpublish(item); - } else { - throw new IllegalArgumentException("Illegal selection"); - } - } - - private class RepublishRunner implements Runnable { - - private final String itemUuid; - private final User user; - - private RepublishRunner(final ContentItem item, - final User user) { - itemUuid = item.getUuid(); - this.user = user; - } - - private void doRepublish() { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil.findBean( - ContentItemRepository.class); - final ContentItem item = itemRepo.findByUuid(itemUuid).get(); - republish(item, false, user); - } - - @Override - public void run() { -// PublishLock.getInstance().lock(item); - doRepublish(); -// PublishLock.getInstance().unlock(item); - } - - } - - private class RepublishAndResetRunner implements Runnable { - - private final String itemUuid; - private final User user; - - private RepublishAndResetRunner(final ContentItem item, - final User user) { - itemUuid = item.getUuid(); - this.user = user; - } - - private void doRepublishAndReset() { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil.findBean( - ContentItemRepository.class); - final ContentItem item = itemRepo.findByUuid(itemUuid).get(); - republish(item, true, user); - } - - @Override - public void run() { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil.findBean( - ContentItemRepository.class); - final ContentItem item = itemRepo.findByUuid(itemUuid).get(); -// PublishLock.getInstance().lock(item); - doRepublishAndReset(); -// PublishLock.getInstance().unlock(item); - } - - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemLifecycleSelectForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemLifecycleSelectForm.java deleted file mode 100755 index 8262fe089..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemLifecycleSelectForm.java +++ /dev/null @@ -1,1060 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormValidationListener; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.Date; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.bebop.parameters.BigDecimalParameter; -import com.arsdigita.bebop.parameters.DateParameter; -import com.arsdigita.bebop.parameters.IntegerParameter; -import com.arsdigita.bebop.parameters.NumberInRangeValidationListener; -import com.arsdigita.cms.CMS; -import com.arsdigita.cms.ui.BaseForm; -import com.arsdigita.cms.ui.item.ContentItemRequestLocal; -import com.arsdigita.cms.ui.item.ItemWorkflowRequestLocal; -import com.arsdigita.cms.ui.workflow.WorkflowRequestLocal; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.mail.Mail; -import com.arsdigita.util.UncheckedWrapperException; -import com.arsdigita.web.RedirectSignal; -import com.arsdigita.web.URL; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.librecms.CMSConfig; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.libreccm.security.Shiro; -import org.libreccm.security.User; -import org.libreccm.security.UserRepository; -import org.libreccm.workflow.Task; -import org.libreccm.workflow.TaskManager; -import org.libreccm.workflow.Workflow; -import org.libreccm.workflow.WorkflowManager; -import org.libreccm.workflow.WorkflowRepository; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemManager; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.privileges.ItemPrivileges; -import org.librecms.lifecycle.LifecycleDefinition; -import org.librecms.workflow.CmsTask; -import org.librecms.workflow.CmsTaskManager; -import org.librecms.workflow.CmsTaskType; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.io.Writer; -import java.math.BigDecimal; -import java.util.Calendar; -import java.util.List; -import java.util.Locale; -import java.util.Optional; -import java.util.TimeZone; -import java.util.TooManyListenersException; - -import javax.mail.MessagingException; -import javax.servlet.http.HttpServletRequest; - -/** - *

    - * A form to select and apply a lifecycle to a content item.

    - * - * @author Michael Pih - * @author Xixi D'moon <xdmoon@redhat.com> - * @author Justin Ross <jross@redhat.com> - * @author Jens Pelzetter - */ -class ItemLifecycleSelectForm extends BaseForm { - - private static final Logger LOGGER = LogManager.getLogger( - ItemLifecycleSelectForm.class); - - private final static String LIFECYCLE = "lifecycle"; - private final static String START_DATE = "start_date"; - private final static String END_DATE = "end_date"; - private final static String NOTIFICATION_DAYS = "notifyDays"; - private final static String NOTIFICATION_HOURS = "notifyHours"; - - private final ContentItemRequestLocal itemRequestLocal; - private final WorkflowRequestLocal workflowRequestLocal; - - // Form widgets - private final SingleSelect cycleSelect; - private final Date startDateField; - private final TextField startHourField; - private final TextField startMinuteField; - private final SingleSelect startAmpmSelect; - private final Date endDateField; - private final TextField endHourField; - private final TextField endMinuteField; - private final SingleSelect endAmpmSelect; - private final TextField notificationDaysField; - private final TextField notificationHoursField; - - public ItemLifecycleSelectForm(final ContentItemRequestLocal item) { - super("PublishItem", gz("cms.ui.item.lifecycle.apply")); - - this.itemRequestLocal = item; - workflowRequestLocal = new ItemWorkflowRequestLocal(); - - cycleSelect = new SingleSelect(new BigDecimalParameter(LIFECYCLE)); - try { - cycleSelect.addPrintListener(new OptionPrinter()); - } catch (TooManyListenersException tmle) { - throw new UncheckedWrapperException(tmle); - } - addField(gz("cms.ui.item.lifecycle"), cycleSelect); - - // Start date - startDateField = new Date(new DateParameter(START_DATE) { - - @Override - protected final Calendar getCalendar(final HttpServletRequest sreq) { - final Calendar cal = super.getCalendar(sreq); - - cal.setLenient(false); - - return cal; - } - - }); - addField(gz("cms.ui.item.lifecycle.start_date"), startDateField); - - // Start time - final BoxPanel startTime = new BoxPanel(BoxPanel.HORIZONTAL); - addField(gz("cms.ui.item.lifecycle.start_time"), startTime); - - // Hour - startHourField = new TextField(new IntegerParameter("start_hour")); - startTime.add(startHourField); - - startHourField.setSize(3); - startHourField.addValidationListener( - new NumberInRangeValidationListener(1, 12)); - - // Minute - startMinuteField = new TextField(new IntegerParameter("start_minute")); - startTime.add(startMinuteField); - - startMinuteField.setSize(3); - startMinuteField.addValidationListener( - new NumberInRangeValidationListener( - 0, 59)); - - // AM/PM - startAmpmSelect = new SingleSelect(new IntegerParameter("start_ampm")); - startTime.add(startAmpmSelect); - - startAmpmSelect.addOption(new Option("0", "am")); - startAmpmSelect.addOption(new Option("1", "pm")); - - // Time zone - startTime.add(new Label(new TimeZonePrinter())); - - // Expiration date - endDateField = new Date(new DateParameter(END_DATE) { - - @Override - protected final Calendar getCalendar(final HttpServletRequest sreq) { - final Calendar cal = super.getCalendar(sreq); - - cal.setLenient(false); - - return cal; - } - - }); - addField(gz("cms.ui.item.lifecycle.end_date"), endDateField); - - // End time - final BoxPanel endTime = new BoxPanel(BoxPanel.HORIZONTAL); - addField(gz("cms.ui.item.lifecycle.end_time"), endTime); - - // Hour - endHourField = new TextField(new IntegerParameter("end_hour")); - endTime.add(endHourField); - - endHourField.setSize(3); - endHourField.addValidationListener( - new NumberInRangeValidationListener(1, - 12)); - - // Minute - endMinuteField = new TextField(new IntegerParameter("end_minute")); - endTime.add(endMinuteField); - - endMinuteField.setSize(3); - endMinuteField.addValidationListener( - new NumberInRangeValidationListener(0, 59)); - - // AM/PM - endAmpmSelect = new SingleSelect(new IntegerParameter("end_ampm")); - endTime.add(endAmpmSelect); - - endAmpmSelect.addOption(new Option("0", "am")); - endAmpmSelect.addOption(new Option("1", "pm")); - - endTime.add(new Label(new TimeZonePrinter())); - - notificationDaysField = new TextField(new IntegerParameter( - NOTIFICATION_DAYS)); - notificationDaysField.setSize(4); - notificationHoursField = new TextField(new IntegerParameter( - NOTIFICATION_HOURS)); - notificationHoursField.setSize(4); - SimpleContainer cont = new SimpleContainer(); - cont.add(notificationDaysField); - cont.add(new Label(new GlobalizedMessage("cms.ui.item.days", - CmsConstants.CMS_BUNDLE), - false)); - cont.add(notificationHoursField); - cont.add(new Label(new GlobalizedMessage("cms.ui.item.hours", - CmsConstants.CMS_BUNDLE), - false)); - - addField(gz("cms.ui.item.notification_period"), cont); - - // A hidden field that checks to see if the user wants publish - // with a start time earlier than current time. - addAction(new Submit("finish", gz("cms.ui.item.lifecycle.publish"))); - - // Form listeners - super.addValidationListener(new ValidationListener()); - super.addSecurityListener(ItemPrivileges.PUBLISH, item); - super.addInitListener(new InitListener()); - super.addProcessListener(new ProcessListener()); - } - - private class OptionPrinter implements PrintListener { - - @Override - public final void prepare(final PrintEvent event) { - final ContentSection section = CMS.getContext().getContentSection(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ItemLifecycleAdminController controller = cdiUtil - .findBean(ItemLifecycleAdminController.class); - - final List definitions = controller - .getLifecycleDefinitions(section); - - final SingleSelect target = (SingleSelect) event.getTarget(); - target.clearOptions(); - - final GlobalizationHelper globalizationHelper = cdiUtil.findBean( - GlobalizationHelper.class); - final Locale locale = globalizationHelper.getNegotiatedLocale(); - - for (final LifecycleDefinition definition : definitions) { -// final List phaseDefinitions = definition -// .getPhaseDefinitions(); -// -// if (!phaseDefinitions.isEmpty()) { - target.addOption( - new Option( - Long.toString(definition.getDefinitionId()), - new Text(globalizationHelper - .getValueFromLocalizedString(definition.getLabel())))); -// } - } - } - - } - - private class InitListener implements FormInitListener { - - @Override - public final void init(final FormSectionEvent event) { - - final PageState state = event.getPageState(); - - final ContentItem item = itemRequestLocal.getContentItem(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemManager itemManager = cdiUtil - .findBean(ContentItemManager.class); - final ItemLifecycleAdminController controller = cdiUtil - .findBean(ItemLifecycleAdminController.class); - - if (itemManager.isLive(item)) { - // If the item is published, select the currently - // associated lifecycle. - - final LifecycleDefinition definition = controller - .getDefinitionOfLifecycle(item); -// final LifecycleDefinition definition = item -// .getLifecycle() -// .getDefinition(); - cycleSelect.setValue(state, definition.getDefinitionId()); - } else { - // Set the default lifecycle (if it exists). - controller - .getDefaultLifecycle(item) - .ifPresent(definition -> cycleSelect.setValue(state, - definition)); - } - - // Set the default start date. - // XXX Isn't just new Date() sufficient? - final java.util.Date start = new java.util.Date(); - startDateField.setValue(state, start); - - final Calendar calendar = Calendar.getInstance(); - calendar.setTime(start); - - // If the hour is 12, then Calendar.get(Calendar.HOUR) - // returns 0 (from the 24 hour time - 12). We want it to - // return 12. - if (calendar.get(Calendar.HOUR) == 0) { - startHourField.setValue(state, 12); - } else { - startHourField.setValue(state, calendar.get(Calendar.HOUR)); - } - - final Integer min = calendar.get(Calendar.MINUTE); - - if (min < 10) { - startMinuteField.setValue(state, "0" + min.toString()); - } else { - startMinuteField.setValue(state, min.toString()); - } - - startAmpmSelect.setValue(state, calendar.get(Calendar.AM_PM)); - - final int defaultIime = CMSConfig.getConfig() - .getDefaultNotificationTime(); - final int defaultTimeDays = defaultIime / 24; - final int defaultTimeHours = defaultIime % 24; - - notificationDaysField.setValue(state, defaultTimeDays); - notificationHoursField.setValue(state, defaultTimeHours); - } - - } - - /** - * jensp 2011-12-14: Some larger changes to the behavior of the process - * listener. The real action has been moved to the - * @link{Publisher} class. If threaded publishing is active, the publish - * process runs in a separate thread (the item is locked before using - * {@link PublishLock}. If threaded publishing is not active, nothing has - * changed. - */ - private class ProcessListener implements FormProcessListener { - - @Override - public final void process(final FormSectionEvent event) - throws FormProcessException { - final PageState state = event.getPageState(); - final ContentItem item = itemRequestLocal.getContentItem(state); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ItemLifecycleAdminController controller = cdiUtil - .findBean(ItemLifecycleAdminController.class); - - final Publisher publisher = new Publisher(state); - if (CMSConfig.getConfig().isThreadPublishing()) { - final Runnable threadAction = new Runnable() { - - @Override - public void run() { -// PublishLock.getInstance().lock(item); - publisher.publish(); -// PublishLock.getInstance().unlock(item); - } - - }; - final Thread thread = new Thread(threadAction); - thread.setUncaughtExceptionHandler( - new Thread.UncaughtExceptionHandler() { - - @Override - public void uncaughtException(final Thread thread, - final Throwable ex) { - final StringWriter strWriter = new StringWriter(); - final PrintWriter writer = new PrintWriter(strWriter); - ex.printStackTrace(writer); - -// PublishLock.getInstance().setError(item, strWriter -// .toString()); - LOGGER.error(String.format( - "An error occurred while " - + "publishing the item '%s': ", - item.getUuid()), ex); - - if ((CMSConfig.getConfig() - .getPublishingFailureSender() == null) - && (CMSConfig.getConfig() - .getPublishingFailureReceiver() - == null)) { - return; - } - - final UserRepository userRepo = cdiUtil.findBean( - UserRepository.class); - final User receiver = userRepo.findByEmailAddress( - CMSConfig.getConfig() - .getPublishingFailureReceiver()).get(); - final User sender = userRepo.findByEmailAddress( - CMSConfig.getConfig() - .getPublishingFailureSender()).get(); - - if ((sender != null) && (receiver != null)) { - final Writer traceWriter = new StringWriter(); - final PrintWriter printWriter = new PrintWriter( - traceWriter); - ex.printStackTrace(printWriter); - - final Mail notification = new Mail( - receiver.getPrimaryEmailAddress() - .getAddress(), - sender.getPrimaryEmailAddress().getAddress(), - String.format( - "Failed to publish item '%s'", - item.getUuid())); - notification.setBody(String.format( - "Publishing item '%s' failed " - + "with error message: %s.\n\n" - + "Stacktrace:\n%s", - item.getUuid(), - ex.getMessage(), - traceWriter.toString())); - try { - notification.send(); - } catch (MessagingException msgex) { - throw new UncheckedWrapperException(msgex); - } - } - } - - }); - thread.start(); - } else { - publisher.publish(); - } - - if (CMSConfig.getConfig().isThreadPublishing()) { - throw new RedirectSignal( - URL.getDispatcherPath() - + controller.getPublishingTabUrl(item), - true); - } else { - if (CMSConfig.getConfig().isUseStreamlinedCreation()) { - throw new RedirectSignal( - URL.there(state.getRequest(), - CmsConstants.CONTENT_CENTER_URL), true); - } - } - - /* - * final Integer startHour = (Integer) m_startHour.getValue(state); - * Integer startMinute = (Integer) m_startMinute.getValue(state); - * - * if (startMinute == null) { startMinute = new Integer(0); } - * - * final Integer startAmpm = (Integer) m_startAmpm.getValue(state); - * - * final Integer endHour = (Integer) m_endHour.getValue(state); - * Integer endMinute = (Integer) m_endMinute.getValue(state); - * - * if (endMinute == null) { endMinute = new Integer(0); } - * - * final Integer endAmpm = (Integer) m_endAmpm.getValue(state); - * - * // Instantiate the instance of the content type. final - * ContentItem item = m_item.getContentItem(state); - * - * final BigDecimal defID = (BigDecimal) - * m_cycleSelect.getValue(state); Assert.exists(defID); final - * LifecycleDefinition cycleDef = new LifecycleDefinition(defID); - * - * java.util.Date startDate = (java.util.Date) - * m_startDate.getValue(state); - * - * final Calendar start = Calendar.getInstanceOf(); - * start.setTime(startDate); start.set(Calendar.AM_PM, - * startAmpm.intValue()); start.set(Calendar.MINUTE, - * startMinute.intValue()); start.set(Calendar.AM_PM, - * startAmpm.intValue()); if (startHour.intValue() != 12) { - * start.set(Calendar.HOUR_OF_DAY, 12 * startAmpm.intValue() + - * startHour.intValue()); start.set(Calendar.HOUR, - * startHour.intValue()); } else { if (startAmpm.intValue() == 0) { - * start.set(Calendar.HOUR_OF_DAY, 0); start.set(Calendar.HOUR, 0); - * } else { start.set(Calendar.HOUR_OF_DAY, 12); - * start.set(Calendar.HOUR, 0); } } startDate = start.getTime(); - * - * java.util.Date endDate = (java.util.Date) - * m_endDate.getValue(state); - * - * if (endDate != null) { final Calendar end = - * Calendar.getInstanceOf(); - * - * end.setTime(endDate); end.set(Calendar.AM_PM, - * endAmpm.intValue()); end.set(Calendar.MINUTE, - * endMinute.intValue()); end.set(Calendar.AM_PM, - * endAmpm.intValue()); - * - * if (endHour.intValue() != 12) { end.set(Calendar.HOUR_OF_DAY, 12 - * * endAmpm.intValue() + endHour.intValue()); - * end.set(Calendar.HOUR, endHour.intValue()); } else { if - * (endAmpm.intValue() == 0) { end.set(Calendar.HOUR_OF_DAY, 0); - * end.set(Calendar.HOUR, 0); } else { end.set(Calendar.HOUR_OF_DAY, - * 12); end.set(Calendar.HOUR, 0); } } endDate = end.getTime(); } - * - * // If the item is already published, remove the current - * lifecycle. // Do not touch the live version. if - * (item.isPublished()) { item.removeLifecycle(item); item.save(); } - * - * // Apply the new lifecycle. ContentItem pending = - * item.publish(cycleDef, startDate); final Lifecycle lifecycle = - * pending.getLifecycle(); - * - * // XXX domlay Whoa. This must be broken for multiphase // - * lifecycles. - * - * if (endDate != null) { - * - * // update individual phases final PhaseCollection phases = - * lifecycle.getPhases(); - * - * while (phases.next()) { final Phase phase = phases.getPhase(); - * java.util.Date thisEnd = phase.getEndDate(); java.util.Date - * thisStart = phase.getStartDate(); if - * (thisStart.compareTo(endDate) > 0) { phase.setStartDate(endDate); - * phase.save(); } - * - * if (thisEnd == null || thisEnd.compareTo(endDate) > 0) { - * phase.setEndDate(endDate); phase.save(); } } } - * - * // endOfCycle may be the original date according to lifecycle - * phase definitions, or endDate if that was before // natural end - * of lifecycle java.util.Date endOfCycle = lifecycle.getEndDate(); - * if (endOfCycle != null) { - * - * // if advance notification is requested (!= 0) // add another - * phase at the start of which the user is notified Integer - * notificationDays = (Integer) m_notificationDays.getValue(state); - * Integer notificationHours = (Integer) - * m_notificationHours.getValue(state); java.util.Date - * notificationDate = null; - * - * int notificationPeriod = 0; if (notificationDays != null) { - * notificationPeriod += notificationDays.intValue() * 24; } if - * (notificationHours != null) { notificationPeriod += - * notificationHours.intValue(); } - * - * if (notificationPeriod > 0) { notificationDate = - * computeNotificationDate(endOfCycle, notificationPeriod); - * s_log.debug("adding custom phase"); Phase expirationImminentPhase - * = lifecycle.addCustomPhase("expirationImminent", new - * Long(notificationDate. getTime()), new - * Long(endOfCycle.getTime())); - * expirationImminentPhase.setListenerClassName( - * "org.librecms.lifecycle.NotifyLifecycleListener"); - * expirationImminentPhase.save(); } } - * - * // Force the lifecycle scheduler to run to avoid any // - * scheduler delay for items that should be published // - * immediately. pending.getLifecycle().start(); - * - * item.save(); - * - * final Workflow workflow = m_workflow.getWorkflow(state); try { - * finish(workflow, item, Web.getWebContext().getUser()); } catch - * (TaskException te) { throw new FormProcessException(te); } // - * redirect to /content-center if streamlined creation mode is - * active. if - * (ContentSection.getConfig().getUseStreamlinedCreation()) { throw - * new RedirectSignal(URL.there(state.getRequest(), - * Utilities.getWorkspaceURL()), true); } - */ - } - - } - - /** - * This class contains the real publish action. - */ - private class Publisher { - - private final Integer startHour; - private final Integer startMinute; - private final Integer startAmpm; - private final Integer endHour; - private final Integer endMinute; - private final Integer endAmpm; - private final String itemUuid; - private final Long defID; - private final java.util.Date startDate; - private final java.util.Date endDate; - private final Integer notificationDays; - private final Integer notificationHours; - private final String workflowUuid; - private final User user; - - /** - * The constructor collects all necessary data and stores them. - * - * @param state - */ - public Publisher(final PageState state) { - startHour = (Integer) startHourField.getValue(state); - if (startMinuteField.getValue(state) == null) { - startMinute = 0; - } else { - startMinute = (Integer) startMinuteField.getValue(state); - } - startAmpm = (Integer) startAmpmSelect.getValue(state); - - endHour = (Integer) endHourField.getValue(state); - if (endMinuteField.getValue(state) == null) { - endMinute = 0; - } else { - endMinute = (Integer) endMinuteField.getValue(state); - } - endAmpm = (Integer) endAmpmSelect.getValue(state); - - //item = m_item.getContentItem(state); - itemUuid = itemRequestLocal.getContentItem(state).getItemUuid(); - - if (cycleSelect.getValue(state) instanceof BigDecimal) { - defID = ((Number) cycleSelect.getValue(state)).longValue(); - } else if (cycleSelect.getValue(state) instanceof Long) { - defID = (Long) cycleSelect.getValue(state); - } else { - defID = Long.parseLong(cycleSelect.getValue(state).toString()); - } - - final Calendar start = Calendar.getInstance(); - start.setTime((java.util.Date) startDateField.getValue(state)); - start.set(Calendar.AM_PM, startAmpm); - start.set(Calendar.MINUTE, startMinute); - start.set(Calendar.AM_PM, startAmpm); - if (startHour != 12) { - start.set(Calendar.HOUR_OF_DAY, - 12 * startAmpm + startHour); - start.set(Calendar.HOUR, startHour); - } else { - if (startAmpm == 0) { - start.set(Calendar.HOUR_OF_DAY, 0); - start.set(Calendar.HOUR, 0); - } else { - start.set(Calendar.HOUR_OF_DAY, 12); - start.set(Calendar.HOUR, 0); - } - } - startDate = start.getTime(); - - if (endDateField.getValue(state) == null) { - endDate = null; - } else { - final Calendar end = Calendar.getInstance(); - - end.setTime((java.util.Date) endDateField.getValue(state)); - end.set(Calendar.AM_PM, endAmpm); - end.set(Calendar.MINUTE, endMinute); - end.set(Calendar.AM_PM, endAmpm); - - if (endHour != 12) { - end.set(Calendar.HOUR_OF_DAY, - 12 * endAmpm + endHour); - end.set(Calendar.HOUR, endHour); - } else { - if (endAmpm == 0) { - end.set(Calendar.HOUR_OF_DAY, 0); - end.set(Calendar.HOUR, 0); - } else { - end.set(Calendar.HOUR_OF_DAY, 12); - end.set(Calendar.HOUR, 0); - } - } - endDate = end.getTime(); - } - - notificationDays = (Integer) notificationDaysField.getValue(state); - notificationHours = (Integer) notificationHoursField.getValue(state); - - if (workflowRequestLocal.getWorkflow(state) != null) { - workflowUuid = workflowRequestLocal.getWorkflow(state).getUuid(); - } else { - workflowUuid = null; - } - - user = CdiUtil.createCdiUtil().findBean(Shiro.class).getUser().get(); - } - - /** - * Published the item - */ - public void publish() { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ItemLifecycleAdminController controller = cdiUtil - .findBean(ItemLifecycleAdminController.class); - - controller.publish(itemUuid, defID, endDate, workflowUuid, user); - -// final ContentItemRepository itemRepo = cdiUtil.findBean( -// ContentItemRepository.class); -// final ContentItemManager itemManager = cdiUtil.findBean( -// ContentItemManager.class); -// final PhaseRepository phaseRepo = cdiUtil.findBean( -// PhaseRepository.class); -// final LifecycleDefinitionRepository lifecycleDefRepo = cdiUtil -// .findBean(LifecycleDefinitionRepository.class); -// final LifecycleManager lifecycleManager = cdiUtil.findBean( -// LifecycleManager.class); -// -// final ContentItem item = itemRepo.findByUuid(itemUuid).get(); -// -// // If the item is already published, remove the current lifecycle. -// // Do not touch the live version. -// if (itemManager.isLive(item)) { -// item.setLifecycle(null); -// itemRepo.save(item); -// } -// -// ContentItem pending; -// final LifecycleDefinition cycleDef; -// final Lifecycle lifecycle; -// // Apply the new lifecycle. -// cycleDef = lifecycleDefRepo.findById(defID).get(); -// pending = itemManager.publish(item, cycleDef); -// lifecycle = pending.getLifecycle(); -// -// if (endDate != null) { -// -// // update individual phases -// final List phases = lifecycle.getPhases(); -// -// for (final Phase phase : phases) { -// final java.util.Date thisEnd = phase.getEndDateTime(); -// final java.util.Date thisStart = phase.getStartDateTime(); -// if (thisStart.compareTo(endDate) > 0) { -// phase.setStartDateTime(endDate); -// phaseRepo.save(phase); -// } -// } -// } -// -// // endOfCycle may be the original date according to lifecycle phase definitions, or endDate if that was before -// // natural end of lifecycle -// final java.util.Date endOfCycle = lifecycle.getEndDateTime(); -// if (endOfCycle != null) { -// -// // if advance notification is requested (!= 0) -// // add another phase at the start of which the user is notified -// java.util.Date notificationDate; -// -// int notificationPeriod = 0; -// if (notificationDays != null) { -// notificationPeriod += notificationDays * 24; -// } -// if (notificationHours != null) { -// notificationPeriod += notificationHours; -// } -// } -// -// // Force the lifecycle scheduler to run to avoid any -// // scheduler delay for items that should be published -// // immediately. -// lifecycleManager.startLifecycle(pending.getLifecycle()); -// -// if (workflowUuid != null) { -// final WorkflowRepository workflowRepo = cdiUtil.findBean( -// WorkflowRepository.class); -// final Workflow workflow = workflowRepo.findByUuid(workflowUuid) -// .get(); -// finish(workflow, item, user); -// } - } - - } - - static void finish(final Workflow workflow, - final ContentItem item, - final User user) { - if ((workflow != null) && (user != null)) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final WorkflowRepository workflowRepo = cdiUtil.findBean( - WorkflowRepository.class); - final WorkflowManager workflowManager = cdiUtil.findBean( - WorkflowManager.class); - final TaskManager taskManager = cdiUtil.findBean(TaskManager.class); - final CmsTaskManager cmsTaskManager = cdiUtil.findBean( - CmsTaskManager.class); - - final List enabledTasks = workflowManager.findEnabledTasks( - workflow); - for (final Task task : enabledTasks) { - LOGGER.debug("Task is {}.", task.getUuid()); - if (task instanceof CmsTask) { - final CmsTask cmsTask = (CmsTask) task; - - if (cmsTask.getTaskType() == CmsTaskType.DEPLOY) { - LOGGER.debug("Found DEPLOY task."); - taskManager.finish(cmsTask); - } - } - } - - if (CMSConfig.getConfig().isDeleteWorkflowAfterPublication()) { - workflowRepo.delete(workflow); - } else { - // restart the workflow by recreating it - // from the same workflow template - final Workflow template = workflow.getTemplate(); - workflowRepo.delete(workflow); - final Workflow restarted = workflowManager.createWorkflow( - template, item); - // Startring the workflow will probably do the wrong thing, because most of the time - // the current user would be a publisher, not an author - workflowRepo.save(restarted); - } - } - } - - private class ValidationListener implements FormValidationListener { - - @Override - public void validate(final FormSectionEvent event) throws - FormProcessException { - final PageState state = event.getPageState(); - - final Integer startHour = (Integer) startHourField.getValue(state); - if (startHour == null) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.item.start_time_incomplete", - CmsConstants.CMS_BUNDLE)); - } - - final Integer startMinute; - if (startMinuteField.getValue(state) == null) { - startMinute = 0; - } else { - startMinute = (Integer) startMinuteField.getValue(state); - } - - final Integer startAmpm = (Integer) startAmpmSelect.getValue(state); - - java.util.Date startDate = (java.util.Date) startDateField.getValue( - state); - if (startDate == null) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.item.lifecycle.start_date_invalid", - CmsConstants.CMS_BUNDLE)); - } - - final java.util.Date nowDate = new java.util.Date(); - - final Calendar cStart = Calendar.getInstance(); - final Calendar cNow = Calendar.getInstance(); - cStart.setTime(startDate); - cNow.setTime(nowDate); - - if (startHour != 12) { - cStart.set(Calendar.HOUR_OF_DAY, - 12 * startAmpm + startHour); - cStart.set(Calendar.HOUR, startHour); - } else { - if (startAmpm == 0) { - cStart.set(Calendar.HOUR_OF_DAY, 0); - cStart.set(Calendar.HOUR, 0); - } else { - cStart.set(Calendar.HOUR_OF_DAY, 12); - cStart.set(Calendar.HOUR, 0); - } - } - - // Give the user extra 5 minutes before form complains - // start time's in the past. - cStart.set(Calendar.MINUTE, startMinute + 5); - cStart.set(Calendar.AM_PM, startAmpm); - cStart.set(Calendar.SECOND, cNow.get(Calendar.SECOND)); - cStart.set(Calendar.MILLISECOND, cNow.get(Calendar.MILLISECOND)); - - if (cNow.after(cStart)) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.item.lifecycle.start_date_in_past", - CmsConstants.CMS_BUNDLE)); - } - - final Integer endHour = (Integer) endHourField.getValue(state); - final Integer endMinuteTmp = (Integer) endMinuteField - .getValue(state); - final java.util.Date endDate = (java.util.Date) endDateField - .getValue(state); - - if (endHour == null && (endMinuteTmp != null || endDate != null)) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.item.lifecycle.end_time_incomplete", - CmsConstants.CMS_BUNDLE)); - } - - final Integer endMinute; - if (endMinuteTmp == null && endHour != null) { - endMinute = 0; - } else { - endMinute = endMinuteTmp; - } - - boolean timeBlank = (endHour == null) && (endMinute == null); - - final Integer endAmpm = (Integer) endAmpmSelect.getValue(state); - - if (endDate == null && !timeBlank) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.item.lifecycle.end_date_invalid", - CmsConstants.CMS_BUNDLE)); - } - - if (endDate != null) { - final Calendar cEnd = Calendar.getInstance(); - cEnd.setTime(endDate); - - if (endHour != 12) { - cEnd.set(Calendar.HOUR_OF_DAY, - 12 * endAmpm + endHour); - cEnd.set(Calendar.HOUR, endHour); - } else { - if (endAmpm == 0) { - cEnd.set(Calendar.HOUR_OF_DAY, 0); - cEnd.set(Calendar.HOUR, 0); - } else { - cEnd.set(Calendar.HOUR_OF_DAY, 12); - cEnd.set(Calendar.HOUR, 0); - } - } - - // Give the user extra 5 minutes before form complains - // end time's in the past. - cEnd.set(Calendar.MINUTE, endMinute + 5); - cEnd.set(Calendar.AM_PM, endAmpm); - cEnd.set(Calendar.SECOND, cNow.get(Calendar.SECOND)); - cEnd.set(Calendar.MILLISECOND, cNow.get(Calendar.MILLISECOND)); - - //check if the end date is prior to the start date - if (cStart.after(cEnd)) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.item.lifecycle.end_date_before_start_date", - CmsConstants.CMS_BUNDLE)); - } - - final Integer notificationDays = (Integer) notificationDaysField - .getValue(state); - final Integer notificationHours - = (Integer) notificationHoursField - .getValue(state); - - int notificationPeriod = 0; - if (notificationDays != null) { - notificationPeriod += notificationDays * 24; - } - if (notificationHours != null) { - notificationPeriod += notificationHours; - } - - if (notificationPeriod > 0) { - // point in time for notification == end date - notificationPeriod - final java.util.Date notificationDate - = computeNotificationDate( - cEnd.getTime(), - notificationPeriod); - LOGGER.debug("cStart (Date): {}", cStart.getTime()); - LOGGER.debug("notificationDate: {}", notificationDate); - // complain if date for notification is before the start date - if (notificationDate.before(cStart.getTime())) { - LOGGER.debug("notification date is before start date!"); - - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.item.notification_period_before_start", - CmsConstants.CMS_BUNDLE)); - } else { - LOGGER.debug( - "notification date is after start date, OK"); - } - } - } - } - - } - - public class TimeZonePrinter implements PrintListener { - - @Override - public void prepare(final PrintEvent event) { - final Label target = (Label) event.getTarget(); - if (CMSConfig.getConfig().isHideTimezone()) { - target.setLabel(""); - } else { - final PageState state = event.getPageState(); - final Calendar mStart = Calendar.getInstance(); - final java.util.Date startDate = (java.util.Date) startDateField - .getValue(state); - - if (startDate != null) { - mStart.setTime((java.util.Date) startDateField.getValue( - state)); - } - - final String zone = mStart.getTimeZone().getDisplayName(true, - TimeZone.SHORT); - - target.setLabel(zone); - } - } - - } - - /** - * Find out at which date a notification (about an item that is about to - * expire) should be sent, based on the endDate (== date at which the item - * is unpublished) and the notification period. - * - * @param endDate the endDate of the lifecycle, i.e. the date when the - * item is going to be unpublished - * @param notification how many hours the users shouls be notified in - * advance - */ - private java.util.Date computeNotificationDate(final java.util.Date endDate, - final int notificationPeriod) { - if (endDate == null) { - return null; - } - - return new java.util.Date( - endDate.getTime() - notificationPeriod * 3600000L); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemPhaseTableModel.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemPhaseTableModel.java deleted file mode 100644 index e197029c4..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemPhaseTableModel.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.CMSConfig; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.l10n.GlobalizationHelper; -import org.librecms.CmsConstants; - -import java.text.DateFormat; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; - -/** - * - * @author Jens Pelzetter - */ -class ItemPhaseTableModel implements TableModel { - - private final Iterator iterator; - private ItemPhaseTableRow currentRow; - - public ItemPhaseTableModel(final List rows) { - iterator = rows.iterator(); - } - - @Override - public int getColumnCount() { - return 4; - } - - @Override - public boolean nextRow() { - - if (iterator.hasNext()) { - currentRow = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElementAt(final int columnIndex) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final GlobalizationHelper globalizationHelper = cdiUtil - .findBean(GlobalizationHelper.class); - final Locale locale = globalizationHelper.getNegotiatedLocale(); - final DateFormat format; - if (CMSConfig.getConfig().isHideTimezone()) { - format = DateFormat.getDateTimeInstance( - DateFormat.FULL, DateFormat.SHORT, locale); - } else { - format = DateFormat.getDateTimeInstance( - DateFormat.FULL, DateFormat.FULL, locale); - } - - switch (columnIndex) { - case 0: - return currentRow.getName(); - case 1: - return currentRow.getDescription(); - case 2: - if (currentRow.getStartDate() == null) { - return ""; - } else { - return format.format(currentRow.getStartDate()); - } - case 3: - if (currentRow.getEndDate() == null) { - return new GlobalizedMessage("cms.ui.lifecycle.forever", - CmsConstants.CMS_BUNDLE) - .localize(); - } else { - return currentRow.getEndDate(); - } - default: - throw new IllegalArgumentException("Illegal Column Index"); - } - - } - - @Override - public Object getKeyAt(final int columnIndex) { - - return currentRow.getPhaseId(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemPhaseTableModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemPhaseTableModelBuilder.java deleted file mode 100755 index 8eafe3d04..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemPhaseTableModelBuilder.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.table.AbstractTableModelBuilder; -import com.arsdigita.bebop.table.TableModel; - -import org.libreccm.cdi.utils.CdiUtil; - -import java.util.List; - -/** - * @author Xixi D'Moon <xdmoon@arsdigita.com> - * @author Michael Pih - * @author Justin Ross <jross@redhat.com> - * @author Jens Pelzetter - */ -class ItemPhaseTableModelBuilder extends AbstractTableModelBuilder { - - private final LifecycleRequestLocal lifecycle; - - public ItemPhaseTableModelBuilder(final LifecycleRequestLocal lifecycle) { - this.lifecycle = lifecycle; - } - - @Override - public final TableModel makeModel(final Table table, - final PageState state) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ItemLifecycleAdminController controller = cdiUtil - .findBean(ItemLifecycleAdminController.class); - - final List rows = controller - .findPhasesOfLifecycle(lifecycle.getLifecycle(state)); - - return new ItemPhaseTableModel(rows); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemPhaseTableRow.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemPhaseTableRow.java deleted file mode 100644 index 8a56b9700..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/ItemPhaseTableRow.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.lifecycle; - -import java.io.Serializable; -import java.util.Date; - -/** - * - * @author Jens Pelzetter - */ -class ItemPhaseTableRow implements Serializable { - - private static final long serialVersionUID = -8947185134493863779L; - - private long phaseId; - private String name; - private String description; - private Date startDate; - private Date endDate; - - public long getPhaseId() { - return phaseId; - } - - public void setPhaseId(final long phaseId) { - this.phaseId = phaseId; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(final String description) { - this.description = description; - } - - public Date getStartDate() { - if (startDate == null) { - return null; - } else { - return new Date(startDate.getTime()); - } - } - - public void setStartDate(final Date startDate) { - if (startDate == null) { - this.startDate = startDate; - } else { - this.startDate = new Date(startDate.getTime()); - } - } - - public Date getEndDate() { - if (endDate == null) { - return null; - } else { - return new Date(endDate.getTime()); - } - } - - public void setEndDate(final Date endDate) { - if (endDate == null) { - this.endDate = endDate; - } else { - this.endDate = new Date(endDate.getTime()); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleAddForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleAddForm.java deleted file mode 100755 index 85dd00c5e..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleAddForm.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.cms.CMS; - -import org.librecms.lifecycle.LifecycleDefinition; -import org.libreccm.cdi.utils.CdiUtil; - -/** - * @author Michael Pih - * @author Jack Chung - * @author Xixi D'Moon - * @author Justin Ross - * @author Jens Pelzetter - */ -class LifecycleAddForm extends BaseLifecycleForm { - - private final SingleSelectionModel selectedLifecycle; - - LifecycleAddForm(final SingleSelectionModel selectedLifecycle) { - super("LifecycleDefinition", gz("cms.ui.lifecycle.add")); - - this.selectedLifecycle = selectedLifecycle; - - getLifecycleName().addValidationListener( - new LifecycleNameUniqueListener(this)); - - addProcessListener(new ProcessListener()); - } - - private class ProcessListener implements FormProcessListener { - - @Override - public final void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final LifecycleAdminPaneController controller = cdiUtil - .findBean(LifecycleAdminPaneController.class); - - final LifecycleDefinition definition = controller - .createLifecycleDefinition( - CMS.getContext().getContentSection(), - (String) getLifecycleName().getValue(state), - (String) getLifecycleDescription().getValue(state)); - - selectedLifecycle.setSelectedKey(state, - definition.getDefinitionId()); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleAdminContainer.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleAdminContainer.java deleted file mode 100755 index 151ad4491..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleAdminContainer.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.PageState; - -import org.libreccm.security.Party; - -import com.arsdigita.toolbox.ui.SecurityContainer; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionChecker; -import org.librecms.contentsection.privileges.AdminPrivileges; - -/** - * Security container that wraps the canAdministerLifecycles access check around - * its components. - * - * @author Michael Pih - * @author Jens Pelzetter - */ -public class LifecycleAdminContainer extends SecurityContainer { - - /** - * This default constructor should be followed by calls to add. - */ - public LifecycleAdminContainer() { - super(); - } - - /** - * Create a SecurityContainer around a child component. - * - * @param component The child component - */ - public LifecycleAdminContainer(final Component component) { - super(component); - } - - /** - * Returns true if the current user can access the child component. - * - * @param state The page state - * - * @return true if the access checks pass, false otherwise - */ - @Override - protected boolean canAccess(final Party party, final PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - - return permissionChecker.isPermitted( - AdminPrivileges.ADMINISTER_LIFECYLES); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleAdminPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleAdminPane.java deleted file mode 100755 index 1cb636a61..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleAdminPane.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SingleSelectionModel; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.cms.CMS; - -import org.librecms.contentsection.ContentSection; -import org.librecms.lifecycle.LifecycleDefinition; - -import com.arsdigita.cms.ui.BaseAdminPane; -import com.arsdigita.cms.ui.BaseDeleteForm; -import com.arsdigita.cms.ui.FormSecurityListener; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.contentsection.privileges.AdminPrivileges; -import org.librecms.lifecycle.LifecycleDefinitionRepository; - -/** - * This class contains the split pane for the lifecycle administration - * interface. - * - * - * @author Michael Pih - * @author Jack Chung - * @author Justin Ross - * @author Jens Pelzetter - */ -public class LifecycleAdminPane extends BaseAdminPane { - - private final SingleSelectionModel selectionModel; - private final LifecycleDefinitionRequestLocal selectionLifecycleDefinition; - - public LifecycleAdminPane() { - super(new Label(gz("cms.ui.lifecycles")), - new LifecycleListModelBuilder()); - - selectionModel = getSelectionModel(); - selectionLifecycleDefinition = new SelectionRequestLocal(); - - // XXX secvis - //add(new LifecycleAdminContainer(m_addLink)); - setAdd(gz("cms.ui.lifecycle.add"), - new LifecycleAddForm(selectionModel)); - setEdit(gz("cms.ui.lifecycle.edit"), - new LifecycleEditForm(selectionLifecycleDefinition)); - setDelete(gz("cms.ui.lifecycle.delete"), new DeleteForm()); - - setIntroPane(new Label(gz("cms.ui.lifecycle.intro"))); - setItemPane(new LifecycleItemPane(selectionLifecycleDefinition, - getEditLink(), - getDeleteLink())); - - addAction(new LifecycleAdminContainer(getAddLink())); - } - - private class SelectionRequestLocal - extends LifecycleDefinitionRequestLocal { - - @Override - protected final Object initialValue(final PageState state) { - final String id = selectionModel.getSelectedKey(state).toString(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final LifecycleDefinitionRepository lifecycleDefRepo = cdiUtil - .findBean(LifecycleDefinitionRepository.class); - - return lifecycleDefRepo.findById(Long.parseLong(id)); - } - - } - - private final class DeleteForm extends BaseDeleteForm { - - DeleteForm() { - super(new Label(gz("cms.ui.lifecycle.delete_prompt"))); - - addSubmissionListener(new FormSecurityListener( - AdminPrivileges.ADMINISTER_LIFECYLES)); - } - - @Override - public final void process(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final ContentSection section = CMS.getContext().getContentSection(); - final LifecycleDefinition definition = selectionLifecycleDefinition - .getLifecycleDefinition(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final LifecycleAdminPaneController controller = cdiUtil - .findBean(LifecycleAdminPaneController.class); - controller.deleteLifecycleDefinition(definition, section); - - selectionModel.clearSelection(state); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleAdminPaneController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleAdminPaneController.java deleted file mode 100644 index 6a321dd75..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleAdminPaneController.java +++ /dev/null @@ -1,407 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.toolbox.ui.Property; - -import org.libreccm.configuration.ConfigurationManager; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentSection; -import org.librecms.contentsection.ContentSectionManager; -import org.librecms.contentsection.ContentSectionRepository; -import org.librecms.lifecycle.LifecycleDefinition; -import org.librecms.lifecycle.LifecycleDefinitionRepository; -import org.librecms.lifecycle.PhaseDefinition; -import org.librecms.lifecycle.PhaseDefinititionRepository; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class LifecycleAdminPaneController { - - @Inject - private ConfigurationManager confManager; - - @Inject - private ContentSectionRepository sectionRepo; - - @Inject - private ContentSectionManager sectionManager; - - @Inject - private LifecycleDefinitionRepository lifecycleDefRepo; - - @Inject - private PhaseDefinititionRepository phaseDefRepo; - - @Transactional(Transactional.TxType.REQUIRED) - public List getLifecyclesForContentSection( - final ContentSection section) { - - final ContentSection contentSection = sectionRepo - .findById(section.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContentSection with ID %d in the database. " - + "Where did that ID come from?", - section.getObjectId()))); - - return new ArrayList<>(contentSection.getLifecycleDefinitions()); - } - - @Transactional - public List> listLifecyclesForContentSection( - final ContentSection section - ) { - return getLifecyclesForContentSection(section) - .stream() - .map(this::buildLifecycleListItem) - .collect(Collectors.toList()); - } - - private Map buildLifecycleListItem( - final LifecycleDefinition lifecycleDefinition) { - final Map item = new HashMap<>(); - item.put( - LifecycleListModelBuilder.LIFECYCLE_DEF_ID, - Long.toString(lifecycleDefinition.getDefinitionId()) - ); - item.put( - LifecycleListModelBuilder.LIFECYCLE_DEF_LABEL, - lifecycleDefinition - .getLabel() - .getValue(KernelConfig.getConfig().getDefaultLocale()) - ); - return item; - } - - @Transactional(Transactional.TxType.REQUIRED) - public List getLifecycleProperties( - final LifecycleDefinition ofLifecycleDefinition - ) { - final LifecycleDefinition definition = lifecycleDefRepo - .findById(ofLifecycleDefinition.getDefinitionId()) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No LifecycleDefinition with ID %d found.", - ofLifecycleDefinition.getDefinitionId() - ) - ) - ); - - final KernelConfig kernelConfig = confManager - .findConfiguration(KernelConfig.class); - final Locale defaultLocale = kernelConfig.getDefaultLocale(); - - final List properties = new ArrayList<>(); - properties.add( - new Property( - new GlobalizedMessage( - "cms.ui.lifecycle.name", - CmsConstants.CMS_BUNDLE - ), - definition.getLabel().getValue(defaultLocale) - ) - ); - properties.add( - new Property( - new GlobalizedMessage( - "cms.ui.lifecycle.description", - CmsConstants.CMS_BUNDLE - ), - definition.getDescription().getValue(defaultLocale) - ) - ); - return properties; - } - - /** - * Create a new lifecycle definition - * - * @param section The content section which the - * {@link LifecycleDefinition} is created. - * @param name The name of the new lifecycle definition. - * @param description The description of the new lifecycle definition. - */ - @Transactional(Transactional.TxType.REQUIRED) - public LifecycleDefinition createLifecycleDefinition( - final ContentSection section, - final String name, - final String description) { - - Objects.requireNonNull(section, "ContentSection can't be null."); - Objects.requireNonNull(name, "Name can't be null"); - if (name.trim().isEmpty()) { - throw new IllegalArgumentException("Name can't be empty."); - } - - final KernelConfig kernelConfig = confManager - .findConfiguration(KernelConfig.class); - final Locale defaultLocale = kernelConfig.getDefaultLocale(); - - final ContentSection contentSection = sectionRepo - .findById(section.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContentSection with ID %d in the database. " - + "Where did that ID come from?", - section.getObjectId()))); - - final LifecycleDefinition definition = new LifecycleDefinition(); - - definition.getLabel().putValue(defaultLocale, name); - definition.getDescription().putValue(defaultLocale, description); - lifecycleDefRepo.save(definition); - - sectionManager.addLifecycleDefinitionToContentSection(definition, - contentSection); - - return definition; - } - - /** - * Update the name and/or description of a {@link LifecycleDefinition}. - * - * @param definition The definition to update. - * @param name The new name. - * @param description The new description. - */ - @Transactional(Transactional.TxType.REQUIRED) - public void updateLifecycleDefinition(final LifecycleDefinition definition, - final String name, - final String description) { - - Objects.requireNonNull(definition, "definition can't be null."); - Objects.requireNonNull(name, "name can't be null"); - if (name.trim().isEmpty()) { - throw new IllegalArgumentException("Name can't be empty."); - } - - final LifecycleDefinition lifecycleDefinition = lifecycleDefRepo - .findById(definition.getDefinitionId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No LifecycleDefinition with ID %d in the database. " - + "Where did that ID come from?", - definition.getDefinitionId()))); - - final KernelConfig kernelConfig = confManager - .findConfiguration(KernelConfig.class); - final Locale defaultLocale = kernelConfig.getDefaultLocale(); - - if (!lifecycleDefinition.getLabel().getValue(defaultLocale).equals(name)) { - lifecycleDefinition.getLabel().putValue(defaultLocale, name); - } - - if (!lifecycleDefinition.getDescription().getValue(defaultLocale) - .equals(description)) { - lifecycleDefinition.getDescription().putValue(defaultLocale, - description); - } - - lifecycleDefRepo.save(lifecycleDefinition); - } - - @Transactional(Transactional.TxType.REQUIRED) - public void deleteLifecycleDefinition( - final LifecycleDefinition definition, - final ContentSection section) { - - Objects.requireNonNull(definition, "definition can't be null."); - - final LifecycleDefinition lifecycleDefinition = lifecycleDefRepo - .findById(definition.getDefinitionId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No LifecycleDefinition with ID %d in the database. " - + "Where did that ID come from?", - definition.getDefinitionId()))); - final ContentSection contentSection = sectionRepo - .findById(section.getObjectId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No ContentSection with ID %d in the database. " - + "Where did that ID come from?", - section.getObjectId()))); - - sectionManager.removeLifecycleDefinitionFromContentSection( - lifecycleDefinition, - contentSection); - lifecycleDefRepo.delete(lifecycleDefinition); - } - - @Transactional(Transactional.TxType.REQUIRED) - public List getPhaseDefinitions( - final LifecycleDefinition definition) { - - Objects.requireNonNull(definition); - - final LifecycleDefinition lifecycleDefinition = lifecycleDefRepo - .findById(definition.getDefinitionId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No LifecycleDefinition with ID %d in the database. " - + "Where did that ID come from?", - definition.getDefinitionId()))); - - return new ArrayList<>(lifecycleDefinition.getPhaseDefinitions()); - } - - @Transactional(Transactional.TxType.REQUIRED) - public void addPhaseDefinition(final LifecycleDefinition definition, - final String label, - final String description, - final int delayDays, - final int delayHours, - final int delayMinutes, - final int durationDays, - final int durationHours, - final int durationMinutes) { - - Objects.requireNonNull(definition, "definition can't be null"); - Objects.requireNonNull(label, "label can't be null"); - if (label.trim().isEmpty()) { - throw new IllegalArgumentException(String.format( - "label can't be empty.")); - } - - final LifecycleDefinition lifecycleDefinition = lifecycleDefRepo - .findById(definition.getDefinitionId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No LifecycleDefinition with ID %d in the database. " - + "Where did that ID come from?", - definition.getDefinitionId()))); - - final KernelConfig kernelConfig = confManager - .findConfiguration(KernelConfig.class); - final Locale defaultLocale = kernelConfig.getDefaultLocale(); - - final PhaseDefinition phaseDefinition = new PhaseDefinition(); - lifecycleDefinition.addPhaseDefinition(phaseDefinition); - - phaseDefinition.getLabel().putValue(defaultLocale, label); - phaseDefinition.getDescription().putValue(defaultLocale, description); - int delay = delayDays * 24 * 60 * 60; - delay += delayHours * 60 * 60; - delay += delayMinutes * 60; - phaseDefinition.setDefaultDelay(delay); - int duration = durationDays * 24 * 60 * 60; - duration += durationHours * 60 * 60; - duration += durationMinutes * 60; - phaseDefinition.setDefaultDuration(duration); - - phaseDefRepo.save(phaseDefinition); - lifecycleDefRepo.save(lifecycleDefinition); - } - - @Transactional(Transactional.TxType.REQUIRED) - public void updatePhaseDefinition(final PhaseDefinition definition, - final String label, - final String description, - final int delayDays, - final int delayHours, - final int delayMinutes, - final int durationDays, - final int durationHours, - final int durationMinutes) { - - Objects.requireNonNull(definition, "definition can't be null"); - Objects.requireNonNull(label, "label can't be null"); - if (label.trim().isEmpty()) { - throw new IllegalArgumentException(String.format( - "label can't be empty.")); - } - - final PhaseDefinition phaseDefinition = phaseDefRepo - .findById(definition.getDefinitionId()) - .orElseThrow(() -> new IllegalArgumentException(String.format( - "No PhaseDefinition with ID %d in the database. " - + "Where did that ID come from?", - definition.getDefinitionId()))); - - final KernelConfig kernelConfig = confManager - .findConfiguration(KernelConfig.class); - final Locale defaultLocale = kernelConfig.getDefaultLocale(); - - phaseDefinition.getLabel().putValue(defaultLocale, label); - phaseDefinition.getDescription().putValue(defaultLocale, description); - int delay = delayDays * 24 * 60 * 60; - delay += delayHours * 60 * 60; - delay += delayMinutes * 60; - phaseDefinition.setDefaultDelay(delay); - int duration = durationDays * 24 * 60 * 60; - duration += durationHours * 60 * 60; - duration += durationMinutes * 60; - phaseDefinition.setDefaultDuration(duration); - - phaseDefRepo.save(phaseDefinition); - } - - @Transactional(Transactional.TxType.REQUIRED) - public String getLifecycleDefinitionName( - final LifecycleDefinition ofCycle - ) { - final LifecycleDefinition cycle = lifecycleDefRepo.findById( - Objects.requireNonNull(ofCycle).getDefinitionId() - ).orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No LifecycleDefinition with ID %d available", - ofCycle.getDefinitionId() - ) - ) - ); - final KernelConfig kernelConfig = confManager.findConfiguration( - KernelConfig.class - ); - return cycle.getLabel().getValue(kernelConfig.getDefaultLocale()); - } - - @Transactional(Transactional.TxType.REQUIRED) - public String getLifecycleDefinitionDescription( - final LifecycleDefinition ofCycle - ) { - final LifecycleDefinition cycle = lifecycleDefRepo.findById( - Objects.requireNonNull(ofCycle).getDefinitionId() - ).orElseThrow( - () -> new IllegalArgumentException( - String.format( - "No LifecycleDefinition with ID %d available", - ofCycle.getDefinitionId() - ) - ) - ); - final KernelConfig kernelConfig = confManager.findConfiguration( - KernelConfig.class - ); - return cycle.getDescription().getValue(kernelConfig.getDefaultLocale()); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleDefinitionRequestLocal.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleDefinitionRequestLocal.java deleted file mode 100755 index 4f4a6c91a..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleDefinitionRequestLocal.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; - -import org.librecms.lifecycle.LifecycleDefinition; - -import java.util.Optional; - -public abstract class LifecycleDefinitionRequestLocal extends RequestLocal { - - public final LifecycleDefinition getLifecycleDefinition( - final PageState state) { - - @SuppressWarnings("unchecked") - final Optional definition - = (Optional) get( - state); - - return definition.get(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleEditForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleEditForm.java deleted file mode 100755 index 7ddbfce34..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleEditForm.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.FormInitListener; -import com.arsdigita.bebop.event.FormProcessListener; -import com.arsdigita.bebop.event.FormSectionEvent; - -import org.librecms.lifecycle.LifecycleDefinition; -import org.libreccm.cdi.utils.CdiUtil; - -/** - * This class contains a form component to edit a lifecycle definition. - * - * @author Jack Chung - * @author Xixi D'Moon <xdmoon@redhat.com> - * @author Justin Ross <jross@redhat.com> - * @author Jens Pelzetter - */ -class LifecycleEditForm extends BaseLifecycleForm { - - private final LifecycleDefinitionRequestLocal selectedDefinition; - - LifecycleEditForm(final LifecycleDefinitionRequestLocal selectedDefinition) { - super("LifecycleEdit", gz("cms.ui.lifecycle.edit")); - - this.selectedDefinition = selectedDefinition; - - getLifecycleName().addValidationListener( - new LifecycleNameUniqueListener(this, selectedDefinition)); - - addInitListener(new InitListener()); - addProcessListener(new ProcessListener()); - } - - private class InitListener implements FormInitListener { - - @Override - public final void init(final FormSectionEvent event) { - final PageState state = event.getPageState(); - final LifecycleDefinition cycle = selectedDefinition - .getLifecycleDefinition(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final LifecycleAdminPaneController controller = cdiUtil.findBean( - LifecycleAdminPaneController.class - ); - - getLifecycleName().setValue( - state, controller.getLifecycleDefinitionName(cycle) - ); - getLifecycleDescription().setValue( - state, controller.getLifecycleDefinitionDescription(cycle) - ); - } - - } - - private class ProcessListener implements FormProcessListener { - - @Override - public final void process(final FormSectionEvent event) - throws FormProcessException { - final PageState state = event.getPageState(); - final LifecycleDefinition definition = selectedDefinition - .getLifecycleDefinition(state); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final LifecycleAdminPaneController controller = cdiUtil - .findBean(LifecycleAdminPaneController.class); - - controller.updateLifecycleDefinition( - definition, - (String) getLifecycleName().getValue(state), - (String) getLifecycleDescription().getValue(state)); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleItemPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleItemPane.java deleted file mode 100755 index e3aa87f81..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleItemPane.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.ActionLink; -import com.arsdigita.bebop.Container; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.table.DefaultTableCellRenderer; - -import org.librecms.lifecycle.LifecycleDefinition; - -import com.arsdigita.cms.ui.BaseItemPane; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.toolbox.ui.ActionGroup; -import com.arsdigita.toolbox.ui.Property; -import com.arsdigita.toolbox.ui.PropertyList; -import com.arsdigita.toolbox.ui.Section; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.libreccm.security.PermissionChecker; -import org.librecms.contentsection.privileges.AdminPrivileges; -import org.librecms.lifecycle.PhaseDefinititionRepository; - -import java.util.Locale; - -/** - * This class contains the component which displays the information for a - * particular lifecycle, with the ability to edit and delete. This information - * also includes the associated phases for this lifecycle, also with the ability - * to add, edit, and delete. - * - * @author Jens Pelzetter - * @author Michael Pih - * @author Jack Chung - * @author Xixi D'Moon - * @author Justin Ross - */ -class LifecycleItemPane extends BaseItemPane { - - private final LifecycleDefinitionRequestLocal selectedLifecycle; - - private final PhaseRequestLocal selectedPhase; - - private final Container detailPane; - - private final Table phasesTable; - - public LifecycleItemPane( - final LifecycleDefinitionRequestLocal selectedLifecycle, - final ActionLink editLink, - final ActionLink deleteLink) { - - this.selectedLifecycle = selectedLifecycle; - selectedPhase = new SelectionRequestLocal(); - - phasesTable = new PhaseTable(); - - detailPane = new SimpleContainer(); - add(detailPane); - setDefault(detailPane); - - detailPane.add(new SummarySection(editLink, deleteLink)); - - final ActionLink phaseAddLink = new ActionLink(new Label(gz( - "cms.ui.lifecycle.phase_add"))); - - detailPane.add(new PhaseSection(phaseAddLink)); - - final AddPhaseForm phaseAddForm = new AddPhaseForm(selectedLifecycle); - final EditPhaseForm phaseEditForm = new EditPhaseForm(selectedLifecycle, - selectedPhase); - final DeletePhaseForm phaseDeleteForm = new DeletePhaseForm( - selectedPhase); - - add(phaseAddForm); - add(phaseEditForm); - add(phaseDeleteForm); - - connect(phaseAddLink, phaseAddForm); - connect(phaseAddForm); - connect(phasesTable, 4, phaseEditForm); - connect(phaseEditForm, phasesTable.getRowSelectionModel()); - connect(phasesTable, 5, phaseDeleteForm); - connect(phaseDeleteForm, phasesTable.getRowSelectionModel()); - } - - private class SelectionRequestLocal extends PhaseRequestLocal { - - @Override - protected final Object initialValue(final PageState state) { - final String id = phasesTable.getRowSelectionModel().getSelectedKey( - state).toString(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PhaseDefinititionRepository phaseDefRepo = cdiUtil.findBean( - PhaseDefinititionRepository.class); - - return phaseDefRepo.findById(Long.parseLong(id)); - } - - } - - private class SummarySection extends Section { - - public SummarySection(final ActionLink editLink, - final ActionLink deleteLink) { - setHeading(new Label(gz("cms.ui.lifecycle.details"))); - - final ActionGroup group = new ActionGroup(); - setBody(group); - - group.setSubject(new Properties()); - group.addAction(new LifecycleAdminContainer(editLink), - ActionGroup.EDIT); - group.addAction(new LifecycleAdminContainer(deleteLink), - ActionGroup.DELETE); - } - - private class Properties extends PropertyList { - - @Override - protected final java.util.List properties( - final PageState state) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); -// final ConfigurationManager confManager = cdiUtil.findBean( -// ConfigurationManager.class); -// final KernelConfig kernelConfig = confManager.findConfiguration( -// KernelConfig.class); -// final Locale defaultLocale = kernelConfig.getDefaultLocale(); - - final LifecycleAdminPaneController controller = cdiUtil - .findBean(LifecycleAdminPaneController.class); - - final java.util.List props = super.properties(state); - final LifecycleDefinition cycle = selectedLifecycle - .getLifecycleDefinition(state); - - props.addAll(controller.getLifecycleProperties(cycle)); - -// props.add(new Property( -// gz("cms.ui.lifecycle.name"), -// cycle.getLabel().getValue(defaultLocale))); -// props.add(new Property( -// gz("cms.ui.lifecycle.description"), -// cycle.getDescription().getValue(defaultLocale))); - return props; - } - - } - - } - - private class PhaseSection extends Section { - - public PhaseSection(final ActionLink addLink) { - setHeading(new Label(gz("cms.ui.lifecycle.phases"))); - - final ActionGroup group = new ActionGroup(); - setBody(group); - - group.setSubject(phasesTable); - group.addAction(new LifecycleAdminContainer(addLink), - ActionGroup.ADD); - } - - } - - // XXX fix this - private static final String[] HEADERS = { - lz("cms.ui.lifecycle.phase.name"), - lz("cms.ui.lifecycle.phase.description"), - lz("cms.ui.lifecycle.phase_delay"), - lz("cms.ui.lifecycle.phase_duration"), - "", - "" - }; - - private class PhaseTable extends Table { - - public PhaseTable() { - super(new PhaseTableModelBuilder(selectedLifecycle), HEADERS); - - setEmptyView(new Label(gz("cms.ui.lifecycle.phase_none"))); - - getColumn(4).setCellRenderer(new DefaultTableCellRenderer(true)); - - getColumn(5).setCellRenderer(new DefaultTableCellRenderer(true)); - } - - @Override - public final void register(final Page page) { - super.register(page); - - // Hide the action columns if the user does not have - // proper access. - page.addActionListener(new ActionListener() { - - @Override - public final void actionPerformed(final ActionEvent e) { - final PageState state = e.getPageState(); - - final boolean hasLifecycleAdmin = hasAdmin(state); - getColumn(4).setVisible(state, hasLifecycleAdmin); - getColumn(5).setVisible(state, hasLifecycleAdmin); - } - - }); - } - - } - - private boolean hasAdmin(final PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionChecker permissionChecker = cdiUtil.findBean( - PermissionChecker.class); - - return permissionChecker.isPermitted( - AdminPrivileges.ADMINISTER_LIFECYLES); - } - - @Override - public final void reset(final PageState state) { - super.reset(state); - - phasesTable.clearSelection(state); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleListModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleListModelBuilder.java deleted file mode 100755 index 255c01ad6..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleListModelBuilder.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.list.ListModel; -import com.arsdigita.bebop.list.ListModelBuilder; -import com.arsdigita.cms.CMS; -import com.arsdigita.kernel.KernelConfig; - -import org.librecms.contentsection.ContentSection; - -import com.arsdigita.util.LockableImpl; - -import org.libreccm.cdi.utils.CdiUtil; - -import java.util.List; - -import java.util.NoSuchElementException; - -import org.librecms.lifecycle.LifecycleDefinition; - -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; - -/** - * Loads all the current lifecycles from the database so that they may be - * displayed in a list. - * - * @author Michael Pih - * @author Jack Chung - * @author Jens Pelzetter - */ -public final class LifecycleListModelBuilder extends LockableImpl - implements ListModelBuilder { - - protected static final String LIFECYCLE_DEF_ID = "lifecycleDefId"; - - protected static final String LIFECYCLE_DEF_LABEL = "lifecycleDefLabel"; - - @Override - public final ListModel makeModel(final com.arsdigita.bebop.List list, - final PageState state) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final LifecycleAdminPaneController controller = cdiUtil - .findBean(LifecycleAdminPaneController.class); - final ContentSection section = CMS.getContext().getContentSection(); - return new Model(controller.listLifecyclesForContentSection(section)); - } - - private class Model implements ListModel { - - private final Iterator> iterator; - - private Map currentLifecycleDef; - - public Model(final List> lifecycles) { - iterator = lifecycles.iterator(); - } - - @Override - public boolean next() throws NoSuchElementException { - if (iterator.hasNext()) { - currentLifecycleDef = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public Object getElement() { - return currentLifecycleDef.get(LIFECYCLE_DEF_LABEL); - } - - @Override - public String getKey() { - return currentLifecycleDef.get(LIFECYCLE_DEF_ID); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleNameUniqueListener.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleNameUniqueListener.java deleted file mode 100644 index 68f98a238..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleNameUniqueListener.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.ParameterEvent; -import com.arsdigita.bebop.event.ParameterListener; -import com.arsdigita.cms.CMS; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.configuration.ConfigurationManager; -import org.librecms.CmsConstants; -import org.librecms.lifecycle.LifecycleDefinition; - -import java.util.Locale; - -/** - * - * @author Jens Pelzetter - */ -class LifecycleNameUniqueListener implements ParameterListener { - - private final BaseLifecycleForm form; - private final LifecycleDefinitionRequestLocal selectedDefinition; - - protected LifecycleNameUniqueListener(final BaseLifecycleForm form) { - this.form = form; - selectedDefinition = null; - } - - protected LifecycleNameUniqueListener( - final BaseLifecycleForm form, - final LifecycleDefinitionRequestLocal selectedDefinition) { - - this.form = form; - this.selectedDefinition = selectedDefinition; - } - - @Override - public final void validate(final ParameterEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ConfigurationManager confManager = cdiUtil - .findBean(ConfigurationManager.class); - final LifecycleAdminPaneController controller = cdiUtil - .findBean(LifecycleAdminPaneController.class); - final KernelConfig kernelConfig = confManager - .findConfiguration(KernelConfig.class); - final Locale defaultLocale = kernelConfig.getDefaultLocale(); - final String label = (String) form.getLifecycleName().getValue(state); - - final java.util.List definitions = controller - .getLifecyclesForContentSection(CMS.getContext().getContentSection()); - - for (final LifecycleDefinition definition : definitions) { - if (definition.getLabel().getValue(defaultLocale) - .equalsIgnoreCase(label) - && (selectedDefinition == null - || !selectedDefinition.getLifecycleDefinition(state) - .equals(definition))) { - throw new FormProcessException(new GlobalizedMessage( - "cms.ui.lifecycle.name_not_unique", - CmsConstants.CMS_BUNDLE)); - } - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleRequestLocal.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleRequestLocal.java deleted file mode 100755 index 3d3c9066d..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/LifecycleRequestLocal.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; - -import org.librecms.lifecycle.Lifecycle; - -public abstract class LifecycleRequestLocal extends RequestLocal { - - public final Lifecycle getLifecycle(final PageState state) { - return (Lifecycle) get(state); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/PhaseRequestLocal.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/PhaseRequestLocal.java deleted file mode 100755 index 94179a569..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/PhaseRequestLocal.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; - -import org.librecms.lifecycle.PhaseDefinition; - -import java.util.Optional; - -public abstract class PhaseRequestLocal extends RequestLocal { - - - public final PhaseDefinition getPhase(final PageState state) { - @SuppressWarnings("unchecked") - final Optional phaseDef = (Optional) get(state); - return phaseDef.get(); - } -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/PhaseTableModelBuilder.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/PhaseTableModelBuilder.java deleted file mode 100755 index 9a09655e1..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/lifecycle/PhaseTableModelBuilder.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.lifecycle; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.table.TableModel; -import com.arsdigita.bebop.table.TableModelBuilder; -import com.arsdigita.cms.lifecycle.Duration; - -import org.librecms.lifecycle.LifecycleDefinition; -import org.librecms.lifecycle.PhaseDefinition; - -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.kernel.KernelConfig; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; - -import java.util.Iterator; -import java.util.List; - -class PhaseTableModelBuilder extends LockableImpl - implements TableModelBuilder { - - private final LifecycleDefinitionRequestLocal selectedLifecycle; - - public PhaseTableModelBuilder( - final LifecycleDefinitionRequestLocal selectedLifecycle) { - this.selectedLifecycle = selectedLifecycle; - } - - @Override - public final TableModel makeModel(final Table table, - final PageState state) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final LifecycleAdminPaneController controller = cdiUtil - .findBean(LifecycleAdminPaneController.class); - final LifecycleDefinition definition = selectedLifecycle - .getLifecycleDefinition(state); - - return new PhaseTableModel(controller.getPhaseDefinitions(definition)); - } - - private static class PhaseTableModel implements TableModel { - - private final Iterator iterator; - private PhaseDefinition currentPhaseDef; - - public PhaseTableModel(final List phaseDefinitions) { - iterator = phaseDefinitions.iterator(); - } - - @Override - public final int getColumnCount() { - return 6; - } - - @Override - public final boolean nextRow() { - if (iterator.hasNext()) { - currentPhaseDef = iterator.next(); - return true; - } else { - return false; - } - } - - @Override - public final Object getElementAt(final int column) { - - switch (column) { - case 0: - return currentPhaseDef - .getLabel() - .getValue(KernelConfig.getConfig().getDefaultLocale()); - case 1: - return currentPhaseDef - .getDescription() - .getValue(KernelConfig.getConfig().getDefaultLocale()); - case 2: - return Duration.formatDuration(currentPhaseDef - .getDefaultDelay()); - case 3: - final Long duration = currentPhaseDef.getDefaultDuration(); - - if (duration == 0) { - return lz("cms.ui.lifecycle.forever"); - } else { - return Duration.formatDuration(duration); - } - case 4: - return lz("cms.ui.lifecycle.phase_edit"); - case 5: - return lz("cms.ui.lifecycle.phase_delete"); - default: - throw new IllegalStateException(); - } - } - - @Override - public Object getKeyAt(final int columnIndex) { - if (currentPhaseDef == null) { - throw new IllegalStateException(); - } else { - return currentPhaseDef.getDefinitionId(); - } - } - - } - - private static GlobalizedMessage gz(final String key) { - return new GlobalizedMessage(key, CmsConstants.CMS_BUNDLE); - } - - private static String lz(final String key) { - return (String) gz(key).localize(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/AbstractContentItemComponentForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/AbstractContentItemComponentForm.java deleted file mode 100644 index b5d5f4bbf..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/AbstractContentItemComponentForm.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.pagemodel; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.ui.admin.pagemodels.AbstractComponentModelForm; -import com.arsdigita.ui.admin.pagemodels.PageModelsTab; - -import org.librecms.CmsConstants; -import org.librecms.pagemodel.ContentItemComponent; - -/** - * Basic form for all subclasses of {@link ContentItemComponent}. - * - * @param - * - * @author Jens Pelzetter - * - */ -public abstract class AbstractContentItemComponentForm - extends AbstractComponentModelForm { - - /** - * Constant for the name of the {@link #modeField}. - */ - private static final String ITEM_MODE = "itemMode"; - - /** - * Text field for {@link ContentItemComponent#mode}. - */ - private TextField modeField; - - public AbstractContentItemComponentForm( - final String name, - final PageModelsTab pageModelTab, - final ParameterSingleSelectionModel selectedModelId, - final ParameterSingleSelectionModel selectedComponentId) { - - super(name, pageModelTab, selectedModelId, selectedComponentId); - } - - @Override - protected void addWidgets() { - - modeField = new TextField(ITEM_MODE); - modeField.setLabel(new GlobalizedMessage( - "cms.ui.pagemodel.contentitem_component_form.mode.label", - CmsConstants.CMS_BUNDLE)); - add(modeField); - } - - @Override - public void updateComponentModel(final ContentItemComponent componentModel, - final PageState state, - final FormData data) { - - final String modeValue = data.getString(ITEM_MODE); - componentModel.setMode(modeValue); - } - - @Override - public void init(final FormSectionEvent event) - throws FormProcessException { - - super.init(event); - - final PageState state = event.getPageState(); - final ContentItemComponent component = getComponentModel(); - - if (getComponentModel() != null) { - modeField.setValue(state, component.getMode()); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/CategorizedItemComponentForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/CategorizedItemComponentForm.java deleted file mode 100644 index a48e89e32..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/CategorizedItemComponentForm.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.pagemodel; - -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.ui.admin.pagemodels.PageModelsTab; - -import org.librecms.pagemodel.CategorizedItemComponent; - -/** - * Form for editing/creating a {@link CategorizedItemComponent}. - * - * @author Jens Pelzetter - */ -public class CategorizedItemComponentForm - extends AbstractContentItemComponentForm { - - public CategorizedItemComponentForm( - final PageModelsTab pageModelTab, - final ParameterSingleSelectionModel selectedModelId, - final ParameterSingleSelectionModel selectedComponentId) { - - super("CategorizedItemComponentForm", - pageModelTab, - selectedModelId, - selectedComponentId); - } - - @Override - public CategorizedItemComponent createComponentModel() { - return new CategorizedItemComponent(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/CategoryTreeComponentForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/CategoryTreeComponentForm.java deleted file mode 100644 index de7c52a12..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/CategoryTreeComponentForm.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.pagemodel; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.CheckboxGroup; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.ui.admin.pagemodels.AbstractComponentModelForm; -import com.arsdigita.ui.admin.pagemodels.PageModelsTab; - -import org.librecms.CmsConstants; -import org.librecms.pagemodel.CategoryTreeComponent; - -/** - * Form for creating/editing a {@link CategoryTreeComponent}. - * - * @author Jens Pelzetter - */ -public class CategoryTreeComponentForm extends AbstractComponentModelForm { - - private final static String SHOW_FULL_TREE_BOX = "showFullTreeBox"; - private final static String SHOW_FULL_TREE = "showFullTree"; - - private CheckboxGroup showFullTreeCheckbox; - - public CategoryTreeComponentForm( - final PageModelsTab pageModelTab, - final ParameterSingleSelectionModel selectedModelId, - final ParameterSingleSelectionModel selectedComponentId) { - - super("CategoryTreeComponentForm", pageModelTab, selectedModelId, - selectedComponentId); - } - - @Override - protected void addWidgets() { - - showFullTreeCheckbox = new CheckboxGroup(SHOW_FULL_TREE_BOX); - showFullTreeCheckbox.addOption(new Option( - SHOW_FULL_TREE, - new Label(new GlobalizedMessage( - "cms.ui.pagemodel.category_tree_component_form.show_full_tree.label", - CmsConstants.CMS_BUNDLE)))); - add(showFullTreeCheckbox); - } - - @Override - protected CategoryTreeComponent createComponentModel() { - return new CategoryTreeComponent(); - } - - @Override - protected void updateComponentModel( - final CategoryTreeComponent componentModel, - final PageState state, - final FormData data) { - - final Object[] value = (Object[]) data.get(SHOW_FULL_TREE_BOX); - if (value != null - && value.length != 0 - && SHOW_FULL_TREE.equals(value[0])) { - - componentModel.setShowFullTree(true); - } else { - componentModel.setShowFullTree(false); - } - } - - @Override - public void init(final FormSectionEvent event) - throws FormProcessException { - - super.init(event); - - final PageState state = event.getPageState(); - - final CategoryTreeComponent component = getComponentModel(); - - final Object[] showFullTreeValue; - if (component != null && component.isShowFullTree()) { - showFullTreeValue = new Object[]{SHOW_FULL_TREE}; - } else { - showFullTreeValue = new Object[]{}; - } - - showFullTreeCheckbox.setValue(state, showFullTreeValue); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/FixedContentItemComponentForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/FixedContentItemComponentForm.java deleted file mode 100644 index a806129b7..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/FixedContentItemComponentForm.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.pagemodel; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.cms.ui.assets.ItemSearchWidget; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.ui.admin.pagemodels.PageModelsTab; - -import org.libreccm.cdi.utils.CdiUtil; -import org.librecms.CmsConstants; -import org.librecms.contentsection.ContentItem; -import org.librecms.contentsection.ContentItemRepository; -import org.librecms.pagemodel.FixedContentItemComponent; - -/** - * Form for creating/editing a {@link FixedContentItemComponent}. - * - * @author Jens Pelzetter - */ -public class FixedContentItemComponentForm - extends AbstractContentItemComponentForm { - - private final static String ITEM_SEARCH = "itemSearch"; - - private ItemSearchWidget itemSearchWidget; - - public FixedContentItemComponentForm( - final PageModelsTab pageModelTab, - final ParameterSingleSelectionModel selectedModelId, - final ParameterSingleSelectionModel selectedComponentId) { - - super("FixedContentItemComponentForm", - pageModelTab, - selectedModelId, - selectedComponentId); - } - - @Override - protected void addWidgets() { - - itemSearchWidget = new ItemSearchWidget(ITEM_SEARCH); - itemSearchWidget.setLabel(new GlobalizedMessage( - "cms.ui.pagemodel.fixed_contentitem_component_form.itemsearch.label", - CmsConstants.CMS_BUNDLE)); - add(itemSearchWidget); - } - - @Override - protected FixedContentItemComponent createComponentModel() { - return new FixedContentItemComponent(); - } - - @Override - protected void updateComponentModel( - final FixedContentItemComponent component, - final PageState state, - final FormData data) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ContentItemRepository itemRepo = cdiUtil - .findBean(ContentItemRepository.class); - - final long itemId = (long) itemSearchWidget.getValue(state); - - final ContentItem item = itemRepo - .findById(itemId) - .orElseThrow(() -> new IllegalArgumentException()); - - component.setContentItem(item); - } - - @Override - public void init(final FormSectionEvent event) - throws FormProcessException { - - super.init(event); - - final PageState state = event.getPageState(); - final FixedContentItemComponent component = getComponentModel(); - - if (component != null) { - itemSearchWidget.setValue(state, component.getContentItem()); - } - } - - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - - super.validate(event); - - final FormData data = event.getFormData(); - final Object value = data.get(ITEM_SEARCH); - - if (value == null) { - data.addError(new GlobalizedMessage( - "cms.ui.pagemodel.fixed_contentitem_component_form.error.no_item_selected", - CmsConstants.CMS_BUNDLE)); - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/GreetingItemComponentForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/GreetingItemComponentForm.java deleted file mode 100644 index 994643ecf..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/GreetingItemComponentForm.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.pagemodel; - -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.ui.admin.pagemodels.PageModelsTab; - -import org.librecms.pagemodel.GreetingItemComponent; - -/** - * Form for creating/editing a {@link GreetingItemComponent}. - * - * @author Jens Pelzetter - */ -public class GreetingItemComponentForm - extends AbstractContentItemComponentForm { - - public GreetingItemComponentForm( - final PageModelsTab pageModelTab, - final ParameterSingleSelectionModel selectedModelId, - final ParameterSingleSelectionModel selectedComponentId) { - - super("GreetingItemComponentForm", - pageModelTab, - selectedModelId, - selectedComponentId); - } - - @Override - public GreetingItemComponent createComponentModel() { - return new GreetingItemComponent(); - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/ItemListComponentForm.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/ItemListComponentForm.java deleted file mode 100644 index 06f89bc05..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pagemodel/ItemListComponentForm.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.pagemodel; - -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.form.CheckboxGroup; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.TextArea; -import com.arsdigita.bebop.form.TextField; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.ui.admin.pagemodels.AbstractComponentModelForm; -import com.arsdigita.ui.admin.pagemodels.PageModelsTab; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.pagemodel.ComponentModelRepository; -import org.librecms.CmsConstants; -import org.librecms.pagemodel.ItemListComponent; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -/** - * Form for adding/editing a {@link ItemListComponent}. - * - * @author Jens Pelzetter - */ -public class ItemListComponentForm - extends AbstractComponentModelForm { - - private static final String DESCENDING_BOX = "descendingBox"; - private static final String DESCENDING = "descending"; - private static final String LIMIT_TO_TYPE = "limitToType"; - private static final String PAGE_SIZE = "pageSize"; - private static final String LIST_ORDER = "listOrder"; - - private CheckboxGroup descendingBox; - private TextField limitToTypeField; - private TextField pageSizeField; - private TextArea listOrderArea; - - public ItemListComponentForm( - final PageModelsTab pageModelTab, - final ParameterSingleSelectionModel selectedModelId, - final ParameterSingleSelectionModel selectedComponentId) { - - super("ItemListComponentForm", - pageModelTab, - selectedModelId, - selectedComponentId); - } - - @Override - protected void addWidgets() { - - descendingBox = new CheckboxGroup(DESCENDING_BOX); - descendingBox.addOption(new Option( - DESCENDING, new Label( - new GlobalizedMessage( - "cms.ui.pagemodel.itemlist_component_form.descending.label", - CmsConstants.CMS_BUNDLE)))); - add(descendingBox); - - limitToTypeField = new TextField(LIMIT_TO_TYPE); - limitToTypeField.setLabel(new GlobalizedMessage( - "cms.ui.pagemodel.itemlist_component_form.limit_to_type.label", - CmsConstants.CMS_BUNDLE)); - add(limitToTypeField); - - pageSizeField = new TextField(PAGE_SIZE); - pageSizeField.setLabel(new GlobalizedMessage( - "cms.ui.pagemodel.itemlist_component_form.page_size.label", - CmsConstants.CMS_BUNDLE)); - add(pageSizeField); - - listOrderArea = new TextArea(LIST_ORDER); - listOrderArea.setLabel(new GlobalizedMessage( - "cms.ui.pagemodel.itemlist_component_form.list_order.label", - CmsConstants.CMS_BUNDLE)); - add(listOrderArea); - } - - @Override - protected ItemListComponent createComponentModel() { - return new ItemListComponent(); - } - - @Override - protected void updateComponentModel(final ItemListComponent componentModel, - final PageState state, - final FormData data) { - - final Object[] descendingValues = (Object[]) data.get(DESCENDING_BOX); - final String limitToTypeValue = data.getString(LIMIT_TO_TYPE); - final String pageSizeValue = data.getString(PAGE_SIZE); - final String listOrderValue = data.getString(LIST_ORDER); - - final boolean descendingValue = isDescending(descendingValues); - final List listOrder = Arrays - .stream(listOrderValue.split("\n")) - .collect(Collectors.toList()); - - componentModel.setDescending(descendingValue); - componentModel.setLimitToType(limitToTypeValue); - componentModel.setPageSize(Integer.parseInt(pageSizeValue)); - - componentModel.setListOrder(listOrder); - } - - private boolean isDescending(final Object[] descendingValues) { - return descendingValues != null - && descendingValues.length != 0 - && DESCENDING.equals(descendingValues[0]); - } - - @Override - public void init(final FormSectionEvent event) throws FormProcessException { - - super.init(event); - - final PageState state = event.getPageState(); - - final ItemListComponent component = getComponentModel(); - - if (component == null) { - pageSizeField.setValue(state, "30"); - } else { - final Object[] descendingValue; - if (component.isDescending()) { - descendingValue = new Object[]{DESCENDING}; - } else { - descendingValue = new Object[]{}; - } - descendingBox.setValue(state, descendingValue); - - limitToTypeField.setValue(state, component.getLimitToType()); - - pageSizeField.setValue(state, Integer.toString(component - .getPageSize())); - - listOrderArea.setValue(state, - String.join("\n", component.getListOrder())); - } - } - - @Override - protected ItemListComponent loadSelectedComponent(final long componentId) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ComponentModelRepository componentModelRepo = cdiUtil - .findBean(ComponentModelRepository.class); - - return componentModelRepo.findById(componentId, - ItemListComponent.class, - new String[]{"listOrder"}) - .orElseThrow(() -> new IllegalArgumentException(String - .format("No ComponentModel with ID %d in the database.", - componentId))); - } - - @Override - public void validate(final FormSectionEvent event) - throws FormProcessException { - - super.validate(event); - - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - - if (getSaveCancelSection().getSaveButton().isSelected(state)) { - - final String pageSizeValue = data.getString(PAGE_SIZE); - if (pageSizeValue != null - && !pageSizeValue.isEmpty() - && !pageSizeValue.matches("\\d*")) { - - data.addError( - PAGE_SIZE, - new GlobalizedMessage( - "cms.ui.pagemodel.itemlist_component_form.page_size.error.not_a_number", - CmsConstants.CMS_BUNDLE)); - } - } - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pages/PageModelAdminPageController.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/pages/PageModelAdminPageController.java deleted file mode 100644 index cfa46aad8..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pages/PageModelAdminPageController.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.ui.pages; - -import org.libreccm.l10n.GlobalizationHelper; -import org.libreccm.pagemodel.PageModel; -import org.libreccm.pagemodel.PageModelRepository; -import org.librecms.pages.Pages; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.transaction.Transactional; - -/** - * - * @author Jens Pelzetter - */ -@RequestScoped -class PageModelAdminPageController { - - @Inject - private GlobalizationHelper globalizationHelper; - - @Inject - private PageModelRepository pageModelRepository; - - @Transactional(Transactional.TxType.REQUIRED) - protected List findDraftPageModelsByApplication( - final Pages pages - ) { - final List pageModels = pageModelRepository - .findDraftByApplication(pages); - return pageModels.stream().map(this::buildPageModelData).collect( - Collectors.toList() - ); - } - - private PageModelData buildPageModelData(final PageModel fromPageModel) { - final PageModelData result = new PageModelData(); - result.setPageModelId(fromPageModel.getPageModelId()); - result.setTitle(globalizationHelper.getValueFromLocalizedString( - fromPageModel.getTitle())); - return result; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pages/PageModelData.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/pages/PageModelData.java deleted file mode 100644 index 218eae658..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pages/PageModelData.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2021 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 com.arsdigita.cms.ui.pages; - -/** - * - * @author Jens Pelzetter - */ -class PageModelData { - - private long pageModelId; - - private String title; - - public long getPageModelId() { - return pageModelId; - } - - public void setPageModelId(long pageModelId) { - this.pageModelId = pageModelId; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pages/PagesAdminPage.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/pages/PagesAdminPage.java deleted file mode 100644 index 98b7c56e3..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pages/PagesAdminPage.java +++ /dev/null @@ -1,447 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.pages; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.ParameterSingleSelectionModel; -import com.arsdigita.bebop.SaveCancelSection; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.TabbedPane; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.Tree; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ChangeEvent; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.SingleSelect; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.tree.TreeModel; -import com.arsdigita.bebop.tree.TreeModelBuilder; -import com.arsdigita.cms.ui.CMSApplicationPage; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.LayoutPanel; -import com.arsdigita.ui.ReactApp; -import com.arsdigita.ui.admin.categories.CategoriesTreeModel; -import com.arsdigita.util.LockableImpl; - -import org.libreccm.categorization.Category; -import org.libreccm.categorization.CategoryRepository; -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.pagemodel.PageModel; -import org.libreccm.pagemodel.PageModelRepository; -import org.librecms.CmsConstants; -import org.librecms.pages.PageManager; -import org.librecms.pages.PageRepository; -import org.librecms.pages.Pages; - -import java.util.List; -import java.util.Optional; -import java.util.TooManyListenersException; - - -/** - * - * @author Jens Pelzetter - */ -public class PagesAdminPage extends CMSApplicationPage { - - private static final String INDEX_PAGE_MODEL_SELECT = "indexPageModelSelect"; - - private static final String ITEM_PAGE_MODEL_SELECT = "itemPageModelSelect"; - - private static final String INHERIT_PAGEMODEL = "--inherit--"; - - private final ParameterSingleSelectionModel selectedCategory; - - private final Tree categoryTree; - - private final Label nothingSelectedLabel; - - private final Form pageModelForm; - - private final SingleSelect indexPageModelSelect; - - private final SingleSelect itemPageModelSelect; - - private final SaveCancelSection saveCancelSection; - - private Pages pagesInstance; - - private PagesContextBar pagesContextBar; - - public PagesAdminPage() { - - super("", new SimpleContainer()); - - super.setAttribute("application", "admin"); - super.setClassAttr("cms-admin"); -// super.setTitle(new Label(new GlobalizedMessage("cms.ui.pages.title", -// CmsConstants.CMS_BUNDLE))); - - selectedCategory = new ParameterSingleSelectionModel<>( - new StringParameter("selectedCategory")); - super.addGlobalStateParam(selectedCategory.getStateParameter()); - - categoryTree = new Tree(new CategoryTreeModelBuilder()); - categoryTree.addChangeListener(this::categoryTreeStateChanged); - - final LayoutPanel panel = new LayoutPanel(); - panel.setLeft(categoryTree); - - nothingSelectedLabel = new Label(new GlobalizedMessage( - "cms.ui.pages.no_category_selected", - CmsConstants.CMS_BUNDLE)); -// nothingSelectedLabel.addPrintListener(this::printNothingSelectedLabel); - super.setVisibleDefault(nothingSelectedLabel, true); - - pageModelForm = new Form("pageModelForm"); - super.setVisibleDefault(pageModelForm, false); - - final Label heading = new Label(); - heading.addPrintListener(this::printPageModelFormHeading); - heading.setClassAttr("heading"); - pageModelForm.add(heading); - - indexPageModelSelect = new SingleSelect(INDEX_PAGE_MODEL_SELECT); - indexPageModelSelect - .setLabel(new GlobalizedMessage("cms.ui.pages.index_page_model", - CmsConstants.CMS_BUNDLE)); - try { - indexPageModelSelect.addPrintListener(this::populatePageModelSelect); - } catch (TooManyListenersException ex) { - throw new UnexpectedErrorException(ex); - } - pageModelForm.add(indexPageModelSelect); -// super.setVisibleDefault(indexPageModelSelect, false); - - itemPageModelSelect = new SingleSelect(ITEM_PAGE_MODEL_SELECT); - itemPageModelSelect - .setLabel(new GlobalizedMessage("cms.ui.pages.item_page_model", - CmsConstants.CMS_BUNDLE)); - try { - itemPageModelSelect.addPrintListener(this::populatePageModelSelect); - } catch (TooManyListenersException ex) { - throw new UnexpectedErrorException(ex); - } - pageModelForm.add(itemPageModelSelect); -// super.setVisibleDefault(itemPageModelSelect, false); - - saveCancelSection = new SaveCancelSection(); - pageModelForm.add(saveCancelSection); -// super.setVisibleDefault(saveCancelSection, false); - - pageModelForm.addInitListener(this::initPageModelForm); - pageModelForm.addValidationListener(this::validatePageModelForm); - pageModelForm.addProcessListener(this::processPageModelForm); - - final BoxPanel rightPanel = new BoxPanel(BoxPanel.VERTICAL); - rightPanel.setClassAttr("right-panel"); - rightPanel.add(nothingSelectedLabel); - rightPanel.add(pageModelForm); - panel.setRight(rightPanel); - -// final SimpleContainer pageModelsManager = new SimpleContainer( -// "admin:pageModelsManager", AdminUiConstants.ADMIN_XML_NS); -// pageModelsManager.add(new Text("Placeholder page models editor")); - final ReactApp pageModelsManager = new ReactApp( - "page-models-editor", "scripts/dist/ccm-cms-pagemodelseditor.js"); - - pagesContextBar = new PagesContextBar(); - super.add(pagesContextBar); - - final TabbedPane tabbedPane = new TabbedPane(); - tabbedPane.addTab(new Label(new GlobalizedMessage( - "cms.ui.pages.tab.pages", CmsConstants.CMS_BUNDLE)), - panel); - tabbedPane - .addTab(new Label(new GlobalizedMessage( - "cms.ui.pages.tab.page_models", CmsConstants.CMS_BUNDLE)), - pageModelsManager); - super.add(tabbedPane); - - super.addActionListener(this::initPage); - - super.lock(); - } - - public Pages getPagesInstance() { - return pagesInstance; - } - - public void setPagesInstance(final Pages pagesInstance) { - this.pagesInstance = pagesInstance; - pagesContextBar.setPagesInstance(pagesInstance); - } - -// @Override -// public void register(final Page page) { -// -// super.register(page); -// -// page.setVisibleDefault(nothingSelectedLabel, true); -// page.setVisibleDefault(pageModelForm, false); -// -// page.addGlobalStateParam(selectedCategory.getStateParameter()); -// -// } - private void initPage(final ActionEvent event) { - - final PageState state = event.getPageState(); - - if (selectedCategory.isSelected(state)) { - nothingSelectedLabel.setVisible(state, false); - pageModelForm.setVisible(state, true); - } else { - nothingSelectedLabel.setVisible(state, true); - pageModelForm.setVisible(state, false); - } - - } - -// private void printNothingSelectedLabel(final PrintEvent event) { -// -// final PageState state = event.getPageState(); -// final Label target = (Label) event.getTarget(); -// -// target.setVisible(state, !selectedCategory.isSelected(state)); -// } - private void printPageModelFormHeading(final PrintEvent event) { - - final PageState state = event.getPageState(); - final Label target = (Label) event.getTarget(); - -// target.setVisible(state, !selectedCategory.isSelected(state)); - if (selectedCategory.isSelected(state)) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryRepository categoryRepo = cdiUtil - .findBean(CategoryRepository.class); - - final Category category = categoryRepo - .findById(Long.parseLong(selectedCategory.getSelectedKey(state))) - .orElseThrow(() -> new UnexpectedErrorException(String - .format("No Category with ID %s in the database.", - selectedCategory.getSelectedKey(state)))); - - target.setLabel(new GlobalizedMessage( - "cms.ui.pages.page_config_for_category", - CmsConstants.CMS_BUNDLE, - new Object[]{category.getName()})); - } - } - - private void populatePageModelSelect(final PrintEvent event) { - -// final PageState state = event.getPageState(); - final SingleSelect target = (SingleSelect) event.getTarget(); - -// if (!selectedCategory.isSelected(state)) { -// target.setVisible(state, false); -// return; -// } - target.clearOptions(); - - target.addOption(new Option(INHERIT_PAGEMODEL, - new Label(new GlobalizedMessage( - "cms.ui.pages.assigned_page_model.inherit", - CmsConstants.CMS_BUNDLE)))); - -// final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); -// final PageModelRepository pageModelRepo = cdiUtil.findBean( -// PageModelRepository.class -// ); -// final List pageModels = pageModelRepo -// .findDraftByApplication(pagesInstance); -// final GlobalizationHelper globalizationHelper = cdiUtil -// .findBean(GlobalizationHelper.class); -// for (final PageModel pageModel : pageModels) { -// target.addOption( -// new Option( -// Long.toString(pageModel.getPageModelId()), -// new Text( -// globalizationHelper.getValueFromLocalizedString( -// pageModel.getTitle() -// ) -// ) -// ) -// ); -// } - final PageModelAdminPageController controller = CdiUtil.createCdiUtil() - .findBean(PageModelAdminPageController.class); - final List pageModels = controller - .findDraftPageModelsByApplication(pagesInstance); - for (final PageModelData pageModel : pageModels) { - target.addOption( - new Option( - Long.toString(pageModel.getPageModelId()), - new Text(pageModel.getTitle()) - ) - ); - } - } - - private void categoryTreeStateChanged(final ChangeEvent event) { - - final PageState state = event.getPageState(); - - final String selectedKey = (String) categoryTree.getSelectedKey(state); - selectedCategory.setSelectedKey(state, selectedKey); - } - - private void initPageModelForm(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - -// pageModelForm.setVisible(state, selectedCategory.isSelected(state)); - saveCancelSection.setVisible(state, selectedCategory.isSelected(state)); - - if (!selectedCategory.isSelected(state)) { - return; - } - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryRepository categoryRepo = cdiUtil - .findBean(CategoryRepository.class); - final PageRepository pageRepo = cdiUtil - .findBean(PageRepository.class); - - final Category category = categoryRepo - .findById(Long.parseLong(selectedCategory.getSelectedKey(state))) - .orElseThrow(() -> new UnexpectedErrorException(String - .format("No Category with ID %s in the database.", - selectedCategory.getSelectedKey(state)))); - - final Optional page = pageRepo - .findPageForCategory(category); - - if (page.isPresent()) { - -// if (page.get().getIndexPageModel() == null) { -// indexPageModelSelect.setValue(state, INHERIT_PAGEMODEL); -// } else { -// indexPageModelSelect.setValue(state, -// Long.toString(page -// .get() -// .getIndexPageModel() -// .getPageModelId())); -// } -// -// if (page.get().getItemPageModel() == null) { -// itemPageModelSelect.setValue(state, INHERIT_PAGEMODEL); -// } else { -// itemPageModelSelect.setValue(state, -// Long.toString(page -// .get() -// .getItemPageModel() -// .getPageModelId())); -// } - } else { - indexPageModelSelect.setValue(state, INHERIT_PAGEMODEL); - itemPageModelSelect.setValue(state, INHERIT_PAGEMODEL); - } - } - - private void validatePageModelForm(final FormSectionEvent event) - throws FormProcessException { - - //Nothing for now - } - - private void processPageModelForm(final FormSectionEvent event) - throws FormProcessException { - - final PageState state = event.getPageState(); - - if (saveCancelSection.getSaveButton().isSelected(state)) { - - final FormData data = event.getFormData(); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final CategoryRepository categoryRepo = cdiUtil - .findBean(CategoryRepository.class); - final PageManager pageManager = cdiUtil - .findBean(PageManager.class); - final PageRepository pageRepo = cdiUtil - .findBean(PageRepository.class); - final PageModelRepository pageModelRepo = cdiUtil - .findBean(PageModelRepository.class); - - final Category category = categoryRepo - .findById(Long.parseLong(selectedCategory.getSelectedKey(state))) - .orElseThrow(() -> new UnexpectedErrorException(String - .format("No Category with ID %s in the database.", - selectedCategory.getSelectedKey(state)))); - - final org.librecms.pages.Page page = pageRepo - .findPageForCategory(category) - .orElse(pageManager.createPageForCategory(category)); - - final String selectedIndexPageModelId = data - .getString(INDEX_PAGE_MODEL_SELECT); - final String selectedItemPageModelId = data - .getString(ITEM_PAGE_MODEL_SELECT); - -// if (!INHERIT_PAGEMODEL.equals(selectedIndexPageModelId)) { -// final PageModel model = pageModelRepo -// .findById(Long.parseLong(selectedIndexPageModelId)) -// .orElseThrow(() -> new UnexpectedErrorException(String -// .format("No PageModel with ID %s in the database.", -// selectedIndexPageModelId))); -// page.setIndexPageModel(model); -// } -// -// if (!INHERIT_PAGEMODEL.equals(selectedItemPageModelId)) { -// final PageModel model = pageModelRepo -// .findById(Long.parseLong(selectedItemPageModelId)) -// .orElseThrow(() -> new UnexpectedErrorException(String -// .format("No PageModel with ID %s in the database.", -// selectedItemPageModelId))); -// page.setItemPageModel(model); -// } - - pageRepo.save(page); - } - - categoryTree.clearSelection(state); - selectedCategory.clearSelection(state); - } - - private class CategoryTreeModelBuilder - extends LockableImpl - implements TreeModelBuilder { - - @Override - public TreeModel makeModel(final Tree tree, - final PageState state) { - - return new CategoriesTreeModel(tree, - pagesInstance.getCategoryDomain()); - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pages/PagesContextBar.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/pages/PagesContextBar.java deleted file mode 100644 index d24a9e49f..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/pages/PagesContextBar.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2018 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 com.arsdigita.cms.ui.pages; - -import com.arsdigita.bebop.PageState; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.toolbox.ui.ContextBar; -import com.arsdigita.web.URL; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.web.ApplicationRepository; -import org.libreccm.web.CcmApplication; -import org.librecms.CmsConstants; -import org.librecms.pages.Pages; - -import java.util.List; - -/** - * - * @author Jens Pelzetter - */ -class PagesContextBar extends ContextBar { - - private Pages pagesInstance; - - @Override - public List entries(final PageState state) { - - final List entries = super.entries(state); - - final String centerTitle = (String) new GlobalizedMessage( - "cms.ui.content_center", CmsConstants.CMS_BUNDLE).localize(); - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final ApplicationRepository appRepo = cdiUtil.findBean( - ApplicationRepository.class); - final List apps = appRepo.findByType( - CmsConstants.CONTENT_CENTER_APP_TYPE); - - final String centerPath = apps.get(0).getPrimaryUrl(); - final URL url = URL.there(state.getRequest(), centerPath); - entries.add(new Entry(centerTitle, url)); - - final URL pagesUrl = URL.there( - state.getRequest(), - pagesInstance.getPrimaryUrl()); - entries.add(new Entry(String.format("Pages:: %s", - pagesInstance.getPrimaryUrl()), - pagesUrl)); - - return entries; - - } - - protected Pages getPagesInstance() { - return pagesInstance; - } - - protected void setPagesInstance(final Pages pagesInstance) { - this.pagesInstance = pagesInstance; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSDirectPermissionsTableRow.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSDirectPermissionsTableRow.java deleted file mode 100644 index 7eb91b9dd..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSDirectPermissionsTableRow.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2017 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 com.arsdigita.cms.ui.permissions; - -/** - * - * @author Jens Pelzetter - */ -class CMSDirectPermissionsTableRow { - - private long granteeKey; - - private String granteeName; - - private boolean permitted; - - private UserPrivilegeKey userPrivilegeKey; - - public long getGranteeKey() { - return granteeKey; - } - - protected void setGranteeKey(final long granteeKey) { - this.granteeKey = granteeKey; - } - - public String getGranteeName() { - return granteeName; - } - - protected void setGranteeName(final String granteeName) { - this.granteeName = granteeName; - } - - public boolean isPermitted() { - return permitted; - } - - protected void setPermitted(final boolean permitted) { - this.permitted = permitted; - } - - public UserPrivilegeKey getUserPrivilegeKey() { - return userPrivilegeKey; - } - - protected void setUserPrivilegeKey(final UserPrivilegeKey userPrivilegeKey) { - this.userPrivilegeKey = userPrivilegeKey; - } - - - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSPermissionsConstants.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSPermissionsConstants.java deleted file mode 100755 index f8f0c07a6..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSPermissionsConstants.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.permissions; - -import com.arsdigita.globalization.GlobalizedMessage; - -import org.librecms.contentsection.privileges.ItemPrivileges; - -/** - * This interface is used to centralise constants and labels used in the - * Permissions UI package. - * - * @author Stefan Deusch (stefan@arsdigita.com) - * @author Jens Pelzetter - */ -class CMSPermissionsConstants { - - private CMSPermissionsConstants() { - //Nothing - } - - /** - * These are our five default privileges. - */ - public static final String[] DEFAULT_PRIVILEGES = new String[]{ - ItemPrivileges.VIEW_PUBLISHED, - ItemPrivileges.EDIT, - ItemPrivileges.CREATE_NEW, - ItemPrivileges.DELETE,}; - - public static final String BUNDLE_NAME - = "com.arsdigita.ui.permissions.PermissionsResources"; - - public static final GlobalizedMessage SEARCH_LABEL = new GlobalizedMessage( - "permissions.userSearchForm.label", BUNDLE_NAME); - - public static final GlobalizedMessage SEARCH_BUTTON = new GlobalizedMessage( - "permissions.button.search", BUNDLE_NAME); - - public static final GlobalizedMessage SAVE_BUTTON = new GlobalizedMessage( - "permissions.button.save", BUNDLE_NAME); - - public static final GlobalizedMessage NO_RESULTS = new GlobalizedMessage( - "permissions.userSearchForm.noResults", BUNDLE_NAME); - - // Direct / Indirect permissions - public static final GlobalizedMessage PERM_TABLE_DIRECT_HEADING - = new GlobalizedMessage( - "permissions.directPermissions.heading", BUNDLE_NAME); - - public static final GlobalizedMessage PERM_TABLE_DIRECT_EXPLANATION - = new GlobalizedMessage( - "permissions.directPermissions.explanation", BUNDLE_NAME); - - public static final GlobalizedMessage PERM_TABLE_INDIRECT_HEADING - = new GlobalizedMessage( - "permissions.indirectPermissions.heading", BUNDLE_NAME); - - public static final GlobalizedMessage PERM_TABLE_INDIRECT_EXPLANATION - = new GlobalizedMessage( - "permissions.indirectPermissions.explanation", BUNDLE_NAME); - - public static final GlobalizedMessage PERM_TABLE_INDIRECT_CONTEXT - = new GlobalizedMessage( - "permissions.indirectPermissions.context", BUNDLE_NAME); - - public static final GlobalizedMessage PERM_TABLE_GRANTEE - = new GlobalizedMessage( - "permissions.table.grantee", BUNDLE_NAME); - - public static final GlobalizedMessage PERM_TABLE_ACTIONS - = new GlobalizedMessage( - "permissions.table.actions", BUNDLE_NAME); - - public static final GlobalizedMessage REMOVE_ALL_CONFIRM - = new GlobalizedMessage( - "permissions.table.actions.removeAll", BUNDLE_NAME); - - public static final GlobalizedMessage PERM_TABLE_INHERITED - = new GlobalizedMessage( - "permissions.table.inherited", BUNDLE_NAME); - - public static final GlobalizedMessage PERM_TABLE_NO_PARENT_CONTEXT - = new GlobalizedMessage( - "permissions.table.parent.context.null", BUNDLE_NAME); - - // Permissions header - public static final GlobalizedMessage PAGE_TITLE = new GlobalizedMessage( - "permissions.one.title", BUNDLE_NAME); - - public static final GlobalizedMessage MAIN_SITE = new GlobalizedMessage( - "permissions.main.site", BUNDLE_NAME); - - public static final GlobalizedMessage PERSONAL_SITE = new GlobalizedMessage( - "permissions.personal.site", BUNDLE_NAME); - - public static final GlobalizedMessage PERMISSIONS_INDEX - = new GlobalizedMessage( - "permissions.index.title", BUNDLE_NAME); - - public static final GlobalizedMessage PERMISSIONS_INDEX_NAVBAR - = new GlobalizedMessage( - "permissions.index.navbarItem", BUNDLE_NAME); - - // Permissions grant form - public static final GlobalizedMessage PAGE_GRANT_TITLE - = new GlobalizedMessage( - "permissions.one.grant.title", BUNDLE_NAME); - - public static final GlobalizedMessage PAGE_GRANT_LEFT - = new GlobalizedMessage( - "permissions.one.grant.explanation.left", BUNDLE_NAME); - - public static final GlobalizedMessage PAGE_GRANT_RIGHT - = new GlobalizedMessage( - "permissions.one.grant.explanation.right", BUNDLE_NAME); - - // Access denied page - public static final GlobalizedMessage PAGE_DENIED_TITLE - = new GlobalizedMessage( - "permissions.denied.title", BUNDLE_NAME); - - // Index page - public static final GlobalizedMessage PAGE_OBJECT_INDEX - = new GlobalizedMessage( - "permissions.index.adminObjects", BUNDLE_NAME); - - public static final GlobalizedMessage PAGE_OBJECT_PANEL_TITLE - = new GlobalizedMessage( - "permissions.index.panelTitle", BUNDLE_NAME); - - public static final GlobalizedMessage PAGE_OBJECT_NONE - = new GlobalizedMessage( - "permissions.index.noAdminObjects", BUNDLE_NAME); - - // Flats for permission types - public static final int DIRECT = 0; - public static final int INHERITED = 1; - - // Form constants - public static final String OBJECT_ID = "po_id"; - public static final String DIRECT_PERMISSIONS = "direct"; - public static final String INDIRECT_PERMISSIONS = "indirect"; - public static final String SEARCH_QUERY = "query"; - public static final String PRIV_SET = "privs_set"; - - // shared query - public static final String RETRIEVE_USERS - = "com.arsdigita.kernel.RetrieveUsers"; - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSPermissionsGrant.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSPermissionsGrant.java deleted file mode 100755 index bd7c042df..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSPermissionsGrant.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.permissions; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormData; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.SegmentedPanel; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.FormSectionEvent; -import com.arsdigita.bebop.event.FormSubmissionListener; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; -import com.arsdigita.bebop.form.CheckboxGroup; -import com.arsdigita.bebop.form.Option; -import com.arsdigita.bebop.form.OptionGroup; -import com.arsdigita.bebop.form.Submit; -import com.arsdigita.bebop.parameters.ArrayParameter; -import com.arsdigita.bebop.parameters.StringParameter; - -import com.arsdigita.util.StringUtils; -import com.arsdigita.util.UncheckedWrapperException; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.security.PermissionManager; -import org.libreccm.security.Role; -import org.libreccm.security.RoleRepository; - -import java.util.List; -import java.util.TooManyListenersException; - -import static com.arsdigita.cms.ui.permissions.CMSPermissionsConstants.*; - -/** - * Permissions Grant container for permissions assignment. Widgets are currently - * organised on a bebop SegmentedPanel. - * - * @author Stefan Deusch (sdeusch@arsdigita.com) - * @author Jens Pelzetter - */ -class CMSPermissionsGrant { - - private final static String PARTIES_CBG = "parties_cbg"; - private final static String PRIVILEGES_CBG = "privs_cbg"; - - // data keys - private static final String USER_ID = "userID"; - private static final String SCREEN_NAME = "screenName"; - private static final String FIRST_NAME = "firstName"; - private static final String LAST_NAME = "lastName"; - - private final CMSPermissionsPane parent; - private final SegmentedPanel grantPanel; - private CheckboxGroup partiesCheckboxGroup; - private CheckboxGroup privilegesCheckboxGroup; - private Form form; - private Submit saveSubmit; - - /** - * Creates a PermissionsGrant object that will be contained with another - * component. This is currently used inside the permissions pane. - * - * @param parent the enclosing container - */ - public CMSPermissionsGrant(final CMSPermissionsPane parent) { - this.parent = parent; - makeForm(); - grantPanel = new SegmentedPanel(); - grantPanel.addSegment(new Label(PAGE_GRANT_TITLE), form); - } - - /** - * Builds the form used to grant pivileges to users and groups. - */ - private void makeForm() { - form = new Form("GrantPrivileges", new BoxPanel()); - form.setMethod(Form.POST); - form.addSubmissionListener(new GrantFormSubmissionListener()); - form.add(new Label(PAGE_GRANT_LEFT)); - partiesCheckboxGroup = new CheckboxGroup(PARTIES_CBG); - try { - partiesCheckboxGroup.addPrintListener(new UserSearchPrintListener()); - } catch (TooManyListenersException e) { - throw new UncheckedWrapperException("TooManyListeners: " + e - .getMessage(), e); - } - form.add(partiesCheckboxGroup); - - form.add(new Label(PAGE_GRANT_RIGHT)); - privilegesCheckboxGroup = new CheckboxGroup(PRIVILEGES_CBG); - try { - privilegesCheckboxGroup.addPrintListener( - new PrivilegePrintListener()); - } catch (TooManyListenersException e) { - throw new UncheckedWrapperException("TooManyListeners: " + e - .getMessage(), e); - } - form.add(privilegesCheckboxGroup); - - saveSubmit = new Submit("save", SAVE_BUTTON); - form.add(saveSubmit); - } - - /** - * Returns the SegmentedPanel with the permissions grant Form - * - * @return the SegmentedPanel with the permissions grant form - */ - public SegmentedPanel getPanel() { - return grantPanel; - } - - private class GrantFormSubmissionListener - implements FormSubmissionListener { - - @Override - public void submitted(FormSectionEvent event) throws - FormProcessException { - final PageState state = event.getPageState(); - final FormData data = event.getFormData(); - final String[] gids = (String[]) data.get(PARTIES_CBG); - final String[] privs = (String[]) data.get(PRIVILEGES_CBG); - if (privs != null && gids != null) { - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionManager permissionManager = cdiUtil.findBean( - PermissionManager.class); - - final Long oID = parent.getObject(state).getObjectId(); - for (String gid : gids) { - final Long gID = Long.parseLong(gid); - final CMSUserObjectStruct userObjectStruct - = new CMSUserObjectStruct(gID, - oID); - for (String priv : privs) { - permissionManager.grantPrivilege( - priv, - userObjectStruct.getRole(), - userObjectStruct.getObject()); - } - } - } -// parent.showAdmin(state); - } - - } - - private class UserSearchPrintListener implements PrintListener { - - @Override - public void prepare(final PrintEvent event) { - final PageState state = event.getPageState(); - final OptionGroup target = (OptionGroup) event.getTarget(); - - // get query string - final String search = StringUtils.stripWhiteSpace((String) state. - getValue(new StringParameter(SEARCH_QUERY))); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final RoleRepository roleRepo = cdiUtil.findBean( - RoleRepository.class); - - final List roles = roleRepo.searchByName(search); - - roles.forEach(role -> target.addOption(new Option( - Long.toString(role.getRoleId()), - new Text(role.getName())))); - } - - } - - private class PrivilegePrintListener implements PrintListener { - - @Override - public void prepare(final PrintEvent event) { - final PageState state = event.getPageState(); - final OptionGroup target = (OptionGroup) event.getTarget(); - - // get privileges from page state - final Object[] privileges = (Object[]) state.getValue( - new ArrayParameter( - PRIV_SET)); - - // print ceckbox group with privileges - for (Object privilege : privileges) { - target.addOption(new Option((String) privilege, - new Text(parent.getPrivilegeName( - (String) privilege)))); - } - } - - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSPermissionsHeader.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSPermissionsHeader.java deleted file mode 100755 index d481f4e67..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSPermissionsHeader.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.permissions; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.DimensionalNavbar; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Link; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.event.PrintEvent; -import com.arsdigita.bebop.event.PrintListener; - -import org.libreccm.core.CcmObject; - -import static com.arsdigita.cms.ui.permissions.CMSPermissionsConstants.*; - -/** - * - * Component that Renders the Header of the Permissions Admin pages - * - * @author sdeusch@arsdigita.com - * @author Jens Pelzetter - */ -class CMSPermissionsHeader extends BoxPanel { - - private final CMSPermissionsPane parent; - private final Label title; - - /** - * Constructor - */ - CMSPermissionsHeader(final CMSPermissionsPane parent) { - this.parent = parent; - title = new Label(); - title.addPrintListener(new PrintListener() { - - @Override - public void prepare(final PrintEvent event) { - final Label target = (Label) event.getTarget(); - target.setLabel(PAGE_TITLE); - } - - }); - title.setClassAttr("heading"); - add(title); - - // Used to render the object name in the navbar - final Label objectName = new Label(); - objectName.addPrintListener(new PrintListener() { - - public void prepare(final PrintEvent event) { - final Label target = (Label) event.getTarget(); - target.setLabel(getObjectName(event)); - } - - }); - - final DimensionalNavbar navbar = new DimensionalNavbar(); - navbar.add(new Link(new Label(PERSONAL_SITE), "/pvt/home")); - navbar.add(new Link(new Label(MAIN_SITE), "/")); - navbar.add(new Link(new Label(PERMISSIONS_INDEX), "/permissions/")); - navbar.add(objectName); - navbar.setClassAttr("permNavBar"); - add(navbar); - } - - private String getObjectName(final PrintEvent event) { - final PageState state = event.getPageState(); - final CcmObject object = parent.getObject(state); - final String objectName = String.format("%s (ID %d)", - object.getDisplayName(), - object.getObjectId()); - return objectName; - } - - /** - * Returns the object used to render the title of the panel. - */ - Label getTitle() { - return title; - } - -} diff --git a/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSPermissionsPane.java b/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSPermissionsPane.java deleted file mode 100755 index b140a2a6d..000000000 --- a/ccm-cms/src/main/java/com/arsdigita/cms/ui/permissions/CMSPermissionsPane.java +++ /dev/null @@ -1,686 +0,0 @@ -/* - * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved. - * - * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -package com.arsdigita.cms.ui.permissions; - -import com.arsdigita.bebop.BoxPanel; -import com.arsdigita.bebop.Component; -import com.arsdigita.bebop.ControlLink; -import com.arsdigita.bebop.Form; -import com.arsdigita.bebop.FormProcessException; -import com.arsdigita.bebop.Label; -import com.arsdigita.bebop.Page; -import com.arsdigita.bebop.PageState; -import com.arsdigita.bebop.RequestLocal; -import com.arsdigita.bebop.Resettable; -import com.arsdigita.bebop.SegmentedPanel; -import com.arsdigita.bebop.SimpleComponent; -import com.arsdigita.bebop.SimpleContainer; -import com.arsdigita.bebop.Table; -import com.arsdigita.bebop.Text; -import com.arsdigita.bebop.event.ActionEvent; -import com.arsdigita.bebop.event.ActionListener; -import com.arsdigita.bebop.event.RequestEvent; -import com.arsdigita.bebop.event.RequestListener; -import com.arsdigita.bebop.event.TableActionEvent; -import com.arsdigita.bebop.event.TableActionListener; -import com.arsdigita.bebop.parameters.ArrayParameter; -import com.arsdigita.bebop.parameters.ParameterModel; -import com.arsdigita.bebop.parameters.StringParameter; -import com.arsdigita.bebop.table.TableCellRenderer; -import com.arsdigita.dispatcher.DispatcherHelper; -import com.arsdigita.globalization.GlobalizedMessage; -import com.arsdigita.ui.CcmObjectSelectionModel; - -import com.arsdigita.util.UncheckedWrapperException; - -import org.libreccm.cdi.utils.CdiUtil; -import org.libreccm.core.CcmObject; -import org.libreccm.core.UnexpectedErrorException; -import org.libreccm.security.PermissionChecker; -import org.libreccm.security.PermissionManager; -import org.libreccm.security.Role; -import org.libreccm.security.RoleRepository; -import org.librecms.CmsConstants; -import org.librecms.contentsection.privileges.ItemPrivileges; - -import java.io.IOException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -/** - * A pane used to administer the permissions of one {@link - * ACSObject}. This is a reusable component that can be embedded into a page to - * provide a generic UI. The page must have the "?po_id=" parameter to supply to - * ACSObject id of the item one is managing permissions for. - * - * @author sdeusch@arsdigita.com - * @authro Jens Pelzetter - */ -public class CMSPermissionsPane extends SimpleContainer implements Resettable, - ActionListener, - RequestListener { - - // non-shared parameter models; leave package scope for access from its members. - private ParameterModel searchString = new StringParameter( - CMSPermissionsConstants.SEARCH_QUERY); - private ParameterModel privilegeArray = new ArrayParameter( - CMSPermissionsConstants.PRIV_SET); - - private String[] privileges; - private Map privilegeNameMap; - private SimpleContainer permissionsTable; - private CMSPermissionsTables allPermissions; - private CMSPermissionsHeader PermissionsHeader; - private SimpleContainer directPermissions; - private Form roleSearchForm; - private SimpleContainer inheritedPermissions; - private SimpleComponent contextPanel; - private SimpleContainer permissionsGrantPanel; - private SimpleContainer noResultsPanel; - private ObjectAdminListing adminListing; - private CcmObjectSelectionModel selectionModel; - - private RequestLocal userObjectInfo; - - /** - * Default constructor creates components that show the default privileges - * as defined in PermissionsConstants interface - * - * @param model - */ - public CMSPermissionsPane(final CcmObjectSelectionModel model) { - this(CMSPermissionsConstants.DEFAULT_PRIVILEGES, new HashMap<>(), model); - privilegeNameMap.put("read", "Read"); - privilegeNameMap.put("write", "Write"); - privilegeNameMap.put("create", "Create"); - privilegeNameMap.put("delete", "Delete"); - privilegeNameMap.put("admin", "Admin"); - } - - /** - * Creates a PermissionsPane with components showing the privileges that are - * passed in as argument. - * - * @param privileges - * @param privilegeNameMap - * @param selectionModel - */ - public CMSPermissionsPane( - final String[] privileges, - final Map privilegeNameMap, - final CcmObjectSelectionModel selectionModel) { - - userObjectInfo = new RequestLocal() { - - @Override - protected Object initialValue(final PageState state) { - return new CMSUserObjectStruct(state, selectionModel); - } - - }; - - this.privileges = privileges; - this.selectionModel = selectionModel; - this.privilegeNameMap = privilegeNameMap; - } - - public CMSPermissionsPane( - final Class privilegesClass, - final CcmObjectSelectionModel selectionModel) { - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionManager permissionManager = cdiUtil.findBean( - PermissionManager.class); - final List privilegesFromClass = permissionManager - .listDefiniedPrivileges(privilegesClass); - - final Map nameMap = new HashMap<>(); - for(final String privilege: privilegesFromClass) { - nameMap.put(privilege, privilege); - } - - this.privileges = privilegesFromClass.toArray(new String[]{}); - this.selectionModel = selectionModel; - this.privilegeNameMap = nameMap; - } - - /** - * Overwrite this method to construct your default Permissions Pane with the - * components you need. You can subclass anonymously overwriting just the - * register method. Note: the getXXX methods are lazy instantiators, i.e. - * they produce the components only if not already there. (You can even - * overwrite the getXXX components with your own implementation, e.g., if - * you want to show a List instead of a Table for the direct permissions, - * but still use a Table for the inherited permissions. - * - * @param page - */ - @Override - public void register(final Page page) { - super.register(page); - - // add permissions components to this specific implementation - // add(getPermissionsHeader()); -// add(getContextPanel()); - add(getPermissionsTable()); -// add(getDirectPermissionsPanel()); -// add(getUserSearchForm()) -// add(getInheritedPermissionsPanel()); -// add(getPermissionGrantPanel()); -// add(getNoSearchResultPanel()); -// add(getAdminListingPanel()); - - // set initial visibility of components - // p.setVisibleDefault(getPermissionsHeader(), true); - page.setVisibleDefault(getPermissionsTable(), true); -// page.setVisibleDefault(getDirectPermissionsPanel(), true); -// page.setVisibleDefault(getUserSearchForm(), true); -// page.setVisibleDefault(getInheritedPermissionsPanel(), true); -// page.setVisibleDefault(getContextPanel(), true); -// page.setVisibleDefault(getPermissionGrantPanel(), false); -// page.setVisibleDefault(getNoSearchResultPanel(), false); -// page.setVisibleDefault(getAdminListingPanel(), false); - - // p.addActionListener(this); - // p.addRequestListener(this); - // add state parameters - page.addGlobalStateParam(searchString); - page.addGlobalStateParam(privilegeArray); - - } - - /** - * Implementation of interface bebop.Resettable. Use {@code reset} to reset - * permissions component to initial state, e.g. if you embed it into another - * container. - */ - @Override - public void reset(final PageState state) { -// showAdmin(state); - } - - /** - * Utility method to get the authenticated user or group - * - * @param state - * - * @return - */ - public Role getRequestingRole(final PageState state) { - return ((CMSUserObjectStruct) userObjectInfo.get(state)).getRole(); - } - - /** - * Utility method to get the ACSObject from the page state - * - * @param state - * - * @return - */ - public CcmObject getObject(final PageState state) { - return ((CMSUserObjectStruct) userObjectInfo.get(state)).getObject(); - } - - /** - * Returns the title "Permissions on object articles", e.g. - * - * @return - */ - public Label getTitle() { - return ((CMSPermissionsHeader) getPermissionsHeader()).getTitle(); - } - - /** - * Returns a string array of privilege names as defined in the constructor - * - * @return - */ - public String[] getPrivileges() { - return Arrays.copyOf(privileges, privileges.length); - } - - private SimpleContainer getPermissionsTable() { - if (permissionsTable != null) { - return permissionsTable; - } - - final BoxPanel panel = new BoxPanel(BoxPanel.VERTICAL); - final Label header = new Label(new GlobalizedMessage( - "cms.ui.permissions.table.header", - CmsConstants.CMS_BUNDLE)); - panel.add(header); - - final CdiUtil cdiUtil = CdiUtil.createCdiUtil(); - final PermissionManager permissionManager = cdiUtil.findBean( - PermissionManager.class); -// final List privileges = permissionManager -// .listDefiniedPrivileges(ItemPrivileges.class); -// final List