file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
UIDriveManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/drives/UIDriveManager.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.drives; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.jcr.RepositoryException; import org.exoplatform.ecm.webui.component.admin.UIECMAdminPortlet; import org.exoplatform.ecm.webui.selector.UIAnyPermission; import org.exoplatform.ecm.webui.selector.UIPermissionSelector; import org.exoplatform.ecm.webui.tree.selectone.UIOneNodePathSelector; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIBreadcumbs; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.UITree; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; import org.exoplatform.webui.ext.manager.UIAbstractManager; /** * Created by The eXo Platform SARL * Author : Tran The Trong * trongtt@exoplatform.com * Sep 19, 2006 * 11:45:11 AM */ @ComponentConfig(lifecycle = UIContainerLifecycle.class) public class UIDriveManager extends UIAbstractManager { public UIDriveManager() throws Exception { addChild(UIDriveList.class, null, null) ; } public void refresh() throws Exception { update(); } public void update() throws Exception { UIDriveList uiDriveList = getChild(UIDriveList.class); uiDriveList.refresh(1); } public void initPopup(String id) throws Exception { UIDriveForm uiDriveForm ; UIPopupWindow uiPopup = getChildById(id) ; if(uiPopup == null) { uiPopup = addChild(UIPopupWindow.class, null, id) ; uiPopup.setShowMask(true); uiPopup.setWindowSize(590,420) ; uiDriveForm = createUIComponent(UIDriveForm.class, null, null) ; } else { uiDriveForm = uiPopup.findFirstComponentOfType(UIDriveForm.class) ; uiPopup.setRendered(true) ; } uiPopup.setUIComponent(uiDriveForm) ; uiPopup.setShow(true) ; uiPopup.setResizable(true) ; } public void initPopupPermission(String membership) throws Exception { removeChildById(UIDriveForm.POPUP_DRIVEPERMISSION) ; UIPopupWindow uiPopup = addChild(UIPopupWindow.class, null, UIDriveForm.POPUP_DRIVEPERMISSION); uiPopup.setShowMask(true); uiPopup.setWindowSize(580, 300); UIPermissionSelector uiECMPermission = createUIComponent(UIPermissionSelector.class, null, "UIDrivePermissionSelector") ; uiECMPermission.setSelectedMembership(true); uiECMPermission.getChild(UIAnyPermission.class).setId("UIMDriveAnyPermission"); uiECMPermission.getChild(UIBreadcumbs.class).setId("DriveBreadcumbGroupSelector"); uiECMPermission.getChild(UITree.class).setId("UIDriveTreeGroupSelector"); if(membership != null && membership.indexOf(":/") > -1) { String[] arrMember = membership.split(":/") ; uiECMPermission.setCurrentPermission("/" + arrMember[1]) ; } uiPopup.setUIComponent(uiECMPermission); UIDriveForm uiDriveForm = findFirstComponentOfType(UIDriveForm.class) ; uiECMPermission.setSourceComponent(uiDriveForm, new String[] {UIDriveInputSet.FIELD_PERMISSION}) ; uiPopup.setShow(true) ; } public void initPopupNodeTypeSelector(String nodeTypes) throws Exception { removeChildById(UIDriveForm.POPUP_NODETYPE_SELECTOR) ; UIPopupWindow uiPopup = addChild(UIPopupWindow.class, null, UIDriveForm.POPUP_NODETYPE_SELECTOR); uiPopup.setShowMask(true); uiPopup.setWindowSize(580, 300); uiPopup.setResizable(true); UINodeTypeSelector uiNodeTypeSelector = createUIComponent(UINodeTypeSelector.class, null, null) ; uiNodeTypeSelector.setRepositoryName(getAncestorOfType(UIECMAdminPortlet.class).getPreferenceRepository()); List<String> nodeList = new ArrayList<String>(); if (nodeTypes != null) { if(nodeTypes.indexOf(",") > -1) { nodeList = Arrays.asList(nodeTypes.split(",")); } else { nodeList.add(nodeTypes); } } uiNodeTypeSelector.init(1, nodeList); uiPopup.setUIComponent(uiNodeTypeSelector); UIDriveForm uiDriveForm = findFirstComponentOfType(UIDriveForm.class) ; uiNodeTypeSelector.setSourceComponent(uiDriveForm, new String[] {UIDriveInputSet.FIELD_ALLOW_NODETYPES_ON_TREE}) ; uiPopup.setShow(true) ; } private String getSystemWorkspaceName() throws RepositoryException { RepositoryService repositoryService = getApplicationComponent(RepositoryService.class); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); return manageableRepository.getConfiguration().getSystemWorkspaceName(); } public void initPopupJCRBrowser(String workspace, boolean isDisable) throws Exception { removeChildById("JCRBrowser") ; removeChildById("JCRBrowserAssets") ; String repository = getAncestorOfType(UIECMAdminPortlet.class).getPreferenceRepository() ; UIPopupWindow uiPopup = addChild(UIPopupWindow.class, null, "JCRBrowser"); uiPopup.setShowMask(true); uiPopup.setWindowSize(610, 300); UIOneNodePathSelector uiOneNodePathSelector = createUIComponent(UIOneNodePathSelector.class, null, null); uiOneNodePathSelector.setIsDisable(workspace, isDisable) ; uiOneNodePathSelector.setShowRootPathSelect(true) ; uiOneNodePathSelector.setRootNodeLocation(repository, workspace, "/"); if(WCMCoreUtils.isAnonim()) { uiOneNodePathSelector.init(WCMCoreUtils.createAnonimProvider()) ; } else { uiOneNodePathSelector.init(WCMCoreUtils.getSystemSessionProvider()) ; } uiPopup.setUIComponent(uiOneNodePathSelector); UIDriveForm uiDriveForm = findFirstComponentOfType(UIDriveForm.class) ; uiOneNodePathSelector.setSourceComponent(uiDriveForm, new String[] {UIDriveInputSet.FIELD_HOMEPATH}) ; uiPopup.setShow(true) ; } public void initPopupJCRBrowserAssets(String workspace) throws Exception { removeChildById("JCRBrowserAssets") ; removeChildById("JCRBrowser") ; UIPopupWindow uiPopup = addChild(UIPopupWindow.class, null, "JCRBrowserAssets"); uiPopup.setShowMask(true); uiPopup.setWindowSize(610, 300); UIOneNodePathSelector uiOneNodePathSelector = createUIComponent(UIOneNodePathSelector.class, null, null); UIDriveForm uiDriveForm = findFirstComponentOfType(UIDriveForm.class) ; String repository = getAncestorOfType(UIECMAdminPortlet.class).getPreferenceRepository() ; uiOneNodePathSelector.setAcceptedNodeTypesInPathPanel(new String[] {Utils.NT_FILE}) ; uiOneNodePathSelector.setAcceptedNodeTypesInTree(new String[] {Utils.NT_UNSTRUCTURED, Utils.NT_FOLDER}); uiOneNodePathSelector.setAcceptedMimeTypes(new String[] {"image/jpeg", "image/gif", "image/png"}) ; uiOneNodePathSelector.setRootNodeLocation(repository, workspace, "/"); if(WCMCoreUtils.isAnonim()) { uiOneNodePathSelector.init(WCMCoreUtils.createAnonimProvider()) ; } else { uiOneNodePathSelector.init(WCMCoreUtils.getSystemSessionProvider()) ; } uiOneNodePathSelector.setSourceComponent(uiDriveForm, new String[] {UIDriveInputSet.FIELD_WORKSPACEICON}) ; uiPopup.setUIComponent(uiOneNodePathSelector); uiPopup.setShow(true) ; } }
8,007
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDriveInputSet.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/drives/UIDriveInputSet.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.drives; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; import javax.jcr.Node; import javax.jcr.Session; import javax.jcr.nodetype.NodeType; import org.exoplatform.ecm.webui.comparator.ItemOptionNameComparator; import org.exoplatform.ecm.webui.form.UIFormInputSetWithAction; import org.exoplatform.ecm.webui.form.validator.DrivePermissionValidator; import org.exoplatform.ecm.webui.form.validator.ECMNameValidator; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.impl.Constants; import org.exoplatform.services.jcr.impl.core.nodetype.NodeTypeImpl; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.web.application.RequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.form.UIFormSelectBox; import org.exoplatform.webui.form.UIFormStringInput; import org.exoplatform.webui.form.input.UICheckBoxInput; import org.exoplatform.webui.form.validator.MandatoryValidator; /** * Created by The eXo Platform SARL * Author : Tran The Trong * trongtt@gmail.com * Jun 28, 2006 */ @ComponentConfig(template = "classpath:groovy/ecm/webui/form/UIFormInputSetWithAction.gtmpl") public class UIDriveInputSet extends UIFormInputSetWithAction { final static public String FIELD_NAME = "name"; final static public String FIELD_WORKSPACE = "workspace"; final static public String FIELD_HOMEPATH = "homePath"; final static public String FIELD_WORKSPACEICON = "icon"; final static public String FIELD_PERMISSION = "permissions"; final static public String FIELD_ALLOW_NODETYPES_ON_TREE = "allowNodeTypesOnTree"; final static public String FIELD_VIEWPREFERENCESDOC = "viewPreferences"; final static public String FIELD_VIEWNONDOC = "viewNonDocument"; final static public String FIELD_VIEWSIDEBAR = "viewSideBar"; final static public String FIELD_FOLDER_ONLY = "Folder"; final static public String FIELD_BOTH = "Both"; final static public String FIELD_UNSTRUCTURED_ONLY = "Unstructured folder"; final static public String FIELD_ALLOW_CREATE_FOLDERS = "allowCreateFolders"; final static public String SHOW_HIDDEN_NODE = "showHiddenNode"; private final static Log LOG = ExoLogger.getLogger(UIDriveInputSet.class.getName()); public String bothLabel_; public String folderOnlyLabel_; public String unstructuredFolderLabel_; protected Set<String> setFoldertypes; protected TemplateService templateService; public UIDriveInputSet(String name) throws Exception { super(name); setComponentConfig(getClass(), null); addUIFormInput(new UIFormStringInput(FIELD_NAME, FIELD_NAME, null). addValidator(MandatoryValidator.class).addValidator(ECMNameValidator.class)); addUIFormInput(new UIFormSelectBox(FIELD_WORKSPACE, FIELD_WORKSPACE, null)); UIFormStringInput homePathField = new UIFormStringInput(FIELD_HOMEPATH, FIELD_HOMEPATH, null); homePathField.setValue("/"); homePathField.setDisabled(true); addUIFormInput(homePathField); addUIFormInput(new UIFormStringInput(FIELD_WORKSPACEICON, FIELD_WORKSPACEICON, null).setDisabled(true)); UIFormStringInput permissonSelectField = new UIFormStringInput(FIELD_PERMISSION , FIELD_PERMISSION , null); permissonSelectField.addValidator(MandatoryValidator.class); permissonSelectField.addValidator(DrivePermissionValidator.class); permissonSelectField.setDisabled(false); addUIFormInput(permissonSelectField); addUIFormInput(new UICheckBoxInput(FIELD_VIEWPREFERENCESDOC, FIELD_VIEWPREFERENCESDOC, null)); addUIFormInput(new UICheckBoxInput(FIELD_VIEWNONDOC, FIELD_VIEWNONDOC, null)); addUIFormInput(new UICheckBoxInput(FIELD_VIEWSIDEBAR, FIELD_VIEWSIDEBAR, null)); addUIFormInput(new UICheckBoxInput(SHOW_HIDDEN_NODE, SHOW_HIDDEN_NODE, null)); addUIFormInput(new UIFormSelectBox(FIELD_ALLOW_CREATE_FOLDERS, FIELD_ALLOW_CREATE_FOLDERS, null)); UIFormStringInput filterNodeTypes = new UIFormStringInput(FIELD_ALLOW_NODETYPES_ON_TREE , FIELD_ALLOW_NODETYPES_ON_TREE , null); addUIFormInput(filterNodeTypes); setActionInfo(FIELD_ALLOW_NODETYPES_ON_TREE, new String[] {"ChooseNodeType", "RemoveNodeType"}); setActionInfo(FIELD_PERMISSION, new String[] {"AddPermission", "RemovePermission"}); setActionInfo(FIELD_HOMEPATH, new String[] {"AddPath"}); setActionInfo(FIELD_WORKSPACEICON, new String[] {"AddIcon"}); templateService = getApplicationComponent(TemplateService.class); setFoldertypes = templateService.getAllowanceFolderType(); } public void update(DriveData drive) throws Exception { String[] wsNames = getApplicationComponent(RepositoryService.class) .getCurrentRepository().getWorkspaceNames(); List<SelectItemOption<String>> workspace = new ArrayList<SelectItemOption<String>>(); List<SelectItemOption<String>> foldertypeOptions = new ArrayList<SelectItemOption<String>>(); for(String wsName : wsNames) { workspace.add(new SelectItemOption<String>(wsName, wsName)); } RequestContext context = RequestContext.getCurrentInstance(); ResourceBundle res = context.getApplicationResourceBundle(); for (String foldertype : setFoldertypes) { try { foldertypeOptions.add(new SelectItemOption<String>(res.getString(getId() + ".label." + foldertype.replace(":", "_")), foldertype)); } catch (MissingResourceException mre) { foldertypeOptions.add(new SelectItemOption<String>(foldertype, foldertype)); } } getUIFormSelectBox(FIELD_WORKSPACE).setOptions(workspace); Collections.sort(foldertypeOptions, new ItemOptionNameComparator()); getUIFormSelectBox(FIELD_ALLOW_CREATE_FOLDERS).setOptions(foldertypeOptions); getUIFormSelectBox(FIELD_ALLOW_CREATE_FOLDERS).setMultiple(true); if(drive != null) { // Begin of update UIDriveForm uiDriveForm = getAncestorOfType(UIDriveForm.class); String selectedWorkspace = drive.getWorkspace(); String wsInitRootNodeType = uiDriveForm.getWorkspaceEntries(selectedWorkspace); // End of update invokeGetBindingField(drive); //Set value for multi-value select box String foldertypes = drive.getAllowCreateFolders(); String selectedFolderTypes[]; if (foldertypes.contains(",")) { selectedFolderTypes = foldertypes.split(","); } else { selectedFolderTypes = new String[] {foldertypes}; } List<SelectItemOption<String>> folderOptions = new ArrayList<SelectItemOption<String>>(); if(wsInitRootNodeType != null && wsInitRootNodeType.equals(Utils.NT_FOLDER)) { folderOptions.add(new SelectItemOption<String>(UIDriveInputSet.FIELD_FOLDER_ONLY, Utils.NT_FOLDER)); } else { folderOptions.addAll(foldertypeOptions); } Collections.sort(folderOptions, new ItemOptionNameComparator()); getUIFormSelectBox(FIELD_ALLOW_CREATE_FOLDERS).setOptions(folderOptions); getUIFormSelectBox(FIELD_ALLOW_CREATE_FOLDERS).setSelectedValues(selectedFolderTypes); getUIStringInput(FIELD_NAME).setDisabled(true); return; } getUIStringInput(FIELD_NAME).setDisabled(false); reset(); getUICheckBoxInput(FIELD_VIEWPREFERENCESDOC).setChecked(false); getUICheckBoxInput(FIELD_VIEWNONDOC).setChecked(false); getUICheckBoxInput(FIELD_VIEWSIDEBAR).setChecked(false); getUICheckBoxInput(SHOW_HIDDEN_NODE).setChecked(false); } public void updateFolderAllowed(String path) { UIFormSelectBox sltWorkspace = getChildById(UIDriveInputSet.FIELD_WORKSPACE); String strWorkspace = sltWorkspace.getSelectedValues()[0]; SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); try { Session session = sessionProvider.getSession(strWorkspace, getApplicationComponent(RepositoryService.class).getCurrentRepository()); Node rootNode = (Node)session.getItem(path); List<SelectItemOption<String>> foldertypeOptions = new ArrayList<SelectItemOption<String>>(); RequestContext context = RequestContext.getCurrentInstance(); ResourceBundle res = context.getApplicationResourceBundle(); for (String foldertype : setFoldertypes) { if (isChildNodePrimaryTypeAllowed(rootNode, foldertype) ){ try { foldertypeOptions.add(new SelectItemOption<String>(res.getString(getId() + ".label." + foldertype.replace(":", "_")), foldertype)); } catch (MissingResourceException mre) { foldertypeOptions.add(new SelectItemOption<String>(foldertype, foldertype)); } } } Collections.sort(foldertypeOptions, new ItemOptionNameComparator()); getUIFormSelectBox(FIELD_ALLOW_CREATE_FOLDERS).setOptions(foldertypeOptions); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected problem occurs while updating", e); } } } private boolean isChildNodePrimaryTypeAllowed(Node parent, String childNodeTypeName) throws Exception{ NodeType childNodeType = parent.getSession().getWorkspace().getNodeTypeManager().getNodeType(childNodeTypeName); //In some cases, the child node is mixins type of a nt:file example if(childNodeType.isMixin()) return true; List<NodeType> allNodeTypes = new ArrayList<NodeType>(); allNodeTypes.add(parent.getPrimaryNodeType()); for(NodeType mixin: parent.getMixinNodeTypes()) { allNodeTypes.add(mixin); } for (NodeType nodetype:allNodeTypes) { if (((NodeTypeImpl)nodetype).isChildNodePrimaryTypeAllowed(Constants.JCR_ANY_NAME, ((NodeTypeImpl)childNodeType).getQName())) { return true; } } return false; } }
11,103
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UINodeTypeSelector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/drives/UINodeTypeSelector.java
/*************************************************************************** * Copyright 2001-2010 The eXo Platform SARL All rights reserved. * * Please look at license.txt in info directory for more license detail. * **************************************************************************/ package org.exoplatform.ecm.webui.component.admin.drives; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.exoplatform.ecm.webui.selector.ComponentSelector; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIPageIterator; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.Event.Phase; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIFormStringInput; import org.exoplatform.webui.form.input.UICheckBoxInput; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Apr 19, 2010 */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "app:/groovy/webui/component/admin/drives/UINodeTypeSelector.gtmpl", events = { @EventConfig(listeners = UINodeTypeSelector.SearchNodeTypeActionListener.class), @EventConfig(listeners = UINodeTypeSelector.SaveActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UINodeTypeSelector.RefreshActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UINodeTypeSelector.SelectedAllNodeTypesActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UINodeTypeSelector.ShowPageActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UINodeTypeSelector.OnChangeActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UINodeTypeSelector.CloseActionListener.class, phase = Phase.DECODE) } ) public class UINodeTypeSelector extends org.exoplatform.ecm.webui.nodetype.selector.UINodeTypeSelector implements ComponentSelector { private static final String ALL_DOCUMENT_TYPES = "ALL_DOCUMENT_TYPES"; public UINodeTypeSelector() throws Exception { } public static class SearchNodeTypeActionListener extends EventListener<UINodeTypeSelector> { public void execute(Event<UINodeTypeSelector> event) throws Exception { UINodeTypeSelector uiNodeTypeSelector = event.getSource(); UIFormStringInput uiInputNodeType = (UIFormStringInput)uiNodeTypeSelector.findComponentById("NodeTypeText"); String nodeTypeName = uiInputNodeType.getValue(); if (nodeTypeName == null || nodeTypeName.length() == 0) return; if (nodeTypeName.contains("*") && !nodeTypeName.contains(".*")) { nodeTypeName = nodeTypeName.replace("*", ".*"); } Pattern p = Pattern.compile(".*".concat(nodeTypeName.trim()).concat(".*"), Pattern.CASE_INSENSITIVE); if (uiNodeTypeSelector.getLSTNodetype() == null) uiNodeTypeSelector.setLSTNodetype(uiNodeTypeSelector.getAllNodeTypes()); List<NodeTypeBean> lstNodetype = new ArrayList<NodeTypeBean>(); for (NodeTypeBean nodeType : uiNodeTypeSelector.getLSTNodetype()) { if (p.matcher(nodeType.getName()).find()) { lstNodetype.add(nodeType); } } uiNodeTypeSelector.init(1, uiNodeTypeSelector.getSelectedNodetypes(), lstNodetype); UIPopupWindow uiPopup = event.getSource().getAncestorOfType(UIPopupWindow.class); uiPopup.setShowMask(true); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopup); } } public static class OnChangeActionListener extends EventListener<UINodeTypeSelector> { private void updateCheckBox(List<String> selectedNodetypes, UICheckBoxInput uiCheckBox) { if (uiCheckBox.isChecked()) { if (!selectedNodetypes.contains(uiCheckBox.getName().toString())) selectedNodetypes.add(uiCheckBox.getName().toString()); } else { selectedNodetypes.remove(uiCheckBox.getName().toString()); } } public void execute(Event<UINodeTypeSelector> event) throws Exception { UINodeTypeSelector uiNodeTypeSelect = event.getSource(); List<String> selectedNodetypes = uiNodeTypeSelect.getSelectedNodetypes(); List<String> preSelectedNodetypes = new ArrayList<String>(); preSelectedNodetypes.addAll(selectedNodetypes); List<NodeTypeBean> lstNodeType = uiNodeTypeSelect.getNodeTypeList(); UICheckBoxInput uiCheckBox = (UICheckBoxInput)uiNodeTypeSelect.getChildById(ALL_DOCUMENT_TYPES); updateCheckBox(selectedNodetypes, uiCheckBox); for (NodeTypeBean nodetype : lstNodeType) { uiCheckBox = (UICheckBoxInput) uiNodeTypeSelect.getChildById(nodetype.getName()); updateCheckBox(selectedNodetypes, uiCheckBox); } // if at this times, check box 'ALL_DOCUMENT_TYPES' change if (selectedNodetypes.contains(ALL_DOCUMENT_TYPES) && !preSelectedNodetypes.contains(ALL_DOCUMENT_TYPES)) { for(String nodeTypeName : uiNodeTypeSelect.getDocumentNodetypes()) { ((UICheckBoxInput) uiNodeTypeSelect.getChildById(nodeTypeName)).setChecked(true); if (!selectedNodetypes.contains(nodeTypeName)) selectedNodetypes.add(nodeTypeName); } } else if (!selectedNodetypes.contains(ALL_DOCUMENT_TYPES) && preSelectedNodetypes.contains(ALL_DOCUMENT_TYPES)) { if (selectedNodetypes.containsAll(uiNodeTypeSelect.getDocumentNodetypes())) for (String nodeTypeName : uiNodeTypeSelect.getDocumentNodetypes()) { ((UICheckBoxInput) uiNodeTypeSelect.getChildById(nodeTypeName)).setChecked(false); selectedNodetypes.remove(nodeTypeName); } } UIPopupWindow uiPopup = event.getSource().getAncestorOfType(UIPopupWindow.class); uiPopup.setShowMask(true); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopup); } } public static class SaveActionListener extends EventListener<UINodeTypeSelector> { public void execute(Event<UINodeTypeSelector> event) throws Exception { UINodeTypeSelector uiNodeTypeSelector = event.getSource(); String returnField = uiNodeTypeSelector.getReturnFieldName(); List<String> selectedNodetypes = uiNodeTypeSelector.getSelectedNodetypes(); if (selectedNodetypes.contains(UINodeTypeSelector.ALL_DOCUMENT_TYPES)) { selectedNodetypes.remove(UINodeTypeSelector.ALL_DOCUMENT_TYPES); for (String docNodeType : uiNodeTypeSelector.getDocumentNodetypes()) { if (!selectedNodetypes.contains(docNodeType) && ((UICheckBoxInput) uiNodeTypeSelector.findComponentById(docNodeType)).isChecked()) { selectedNodetypes.add(docNodeType); } } } StringBuffer sb = new StringBuffer(""); int index=0; for (String strNodeType : selectedNodetypes) { if (index == 0) { sb.append(strNodeType); } else { sb.append(",").append(strNodeType); } index++; } String nodeTypeString = sb.toString(); ((UISelectable)uiNodeTypeSelector.getSourceComponent()).doSelect(returnField, nodeTypeString); selectedNodetypes.clear(); UIPopupWindow uiPopup = uiNodeTypeSelector.getParent(); uiPopup.setShow(false); UIComponent component = uiNodeTypeSelector.getSourceComponent().getParent(); if (component != null) event.getRequestContext().addUIComponentToUpdateByAjax(component); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopup); } } public static class RefreshActionListener extends EventListener<UINodeTypeSelector> { public void execute(Event<UINodeTypeSelector> event) throws Exception { UINodeTypeSelector uiNodeTypeSelector = event.getSource(); List<UICheckBoxInput> listCheckbox = new ArrayList<UICheckBoxInput>(); uiNodeTypeSelector.findComponentOfType(listCheckbox, UICheckBoxInput.class); for (int i = 0; i < listCheckbox.size(); i++) { listCheckbox.get(i).setChecked(false); uiNodeTypeSelector.getSelectedNodetypes().clear(); } UIPopupWindow uiPopup = event.getSource().getAncestorOfType(UIPopupWindow.class); uiPopup.setShowMask(true); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopup); } } public static class SelectedAllNodeTypesActionListener extends EventListener<UINodeTypeSelector> { public void execute(Event<UINodeTypeSelector> event) throws Exception { UINodeTypeSelector uiNodeTypeSelector = event.getSource(); String returnField = uiNodeTypeSelector.getReturnFieldName(); String value = "*"; ((UISelectable)uiNodeTypeSelector.getSourceComponent()).doSelect(returnField, value); UIPopupWindow uiPopup = uiNodeTypeSelector.getParent(); uiPopup.setShow(false); event.getRequestContext().addUIComponentToUpdateByAjax(uiNodeTypeSelector.getSourceComponent().getParent()); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopup); } } public static class ShowPageActionListener extends EventListener<UIPageIterator> { public void execute(Event<UIPageIterator> event) throws Exception { UINodeTypeSelector uiNodeTypeSelector = event.getSource().getAncestorOfType(UINodeTypeSelector.class); List<String> selectedNodetypes = uiNodeTypeSelector.getSelectedNodetypes(); List<UICheckBoxInput> listCheckbox = new ArrayList<UICheckBoxInput>(); uiNodeTypeSelector.findComponentOfType(listCheckbox, UICheckBoxInput.class); for (UICheckBoxInput uiCheckBox : listCheckbox) { if (selectedNodetypes.contains(uiCheckBox.getValue().toString())) { uiCheckBox.setChecked(true); } else { uiCheckBox.setChecked(false); } } } } public static class CloseActionListener extends EventListener<UINodeTypeSelector> { public void execute(Event<UINodeTypeSelector> event) throws Exception { UINodeTypeSelector uiNodeTypeSelector = event.getSource(); UIPopupWindow uiPopup = uiNodeTypeSelector.getAncestorOfType(UIPopupWindow.class); uiPopup.setShow(false); uiPopup.setRendered(false); UIComponent component = uiNodeTypeSelector.getSourceComponent().getParent(); if (component != null) event.getRequestContext().addUIComponentToUpdateByAjax(component); } } }
10,923
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDriveList.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/drives/UIDriveList.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.drives; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.jcr.PathNotFoundException; import javax.jcr.Session; import org.exoplatform.commons.utils.LazyPageList; import org.exoplatform.commons.utils.ListAccessImpl; import org.exoplatform.container.xml.PortalContainerInfo; import org.exoplatform.ecm.webui.component.admin.UIECMAdminPortlet; import org.exoplatform.ecm.webui.core.UIPagingGridDecorator; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.web.application.RequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Nov 23, 2006 * 11:39:49 AM */ @ComponentConfig( template = "app:/groovy/webui/component/admin/drives/UIDriveList.gtmpl", events = { @EventConfig(listeners = UIDriveList.DeleteActionListener.class, confirm = "UIDriveList.msg.confirm-delete"), @EventConfig(listeners = UIDriveList.EditInfoActionListener.class), @EventConfig(listeners = UIDriveList.AddDriveActionListener.class) } ) public class UIDriveList extends UIPagingGridDecorator { final static public String[] ACTIONS = {"AddDrive"} ; final static public String ST_ADD = "AddDriveManagerPopup" ; final static public String ST_EDIT = "EditDriveManagerPopup" ; public UIDriveList() throws Exception { getUIPageIterator().setId("UIDriveListIterator"); } public String[] getActions() { return ACTIONS ; } public void refresh(int currentPage) throws Exception { LazyPageList<DriveData> dataPageList = new LazyPageList<DriveData>(new ListAccessImpl<DriveData>(DriveData.class, getDrives()), getUIPageIterator().getItemsPerPage()); getUIPageIterator().setPageList(dataPageList); if (currentPage > getUIPageIterator().getAvailablePage()) getUIPageIterator().setCurrentPage(getUIPageIterator().getAvailablePage()); else getUIPageIterator().setCurrentPage(currentPage); } public List<DriveData> getDriveList() throws Exception { return getUIPageIterator().getCurrentPageData() ; } public String getRequestContextName() { return WCMCoreUtils.getRestContextName(); } public List<DriveData> getDrives() throws Exception { RepositoryService rservice = getApplicationComponent(RepositoryService.class) ; ManageDriveService driveService = getApplicationComponent(ManageDriveService.class) ; ManageableRepository repository = rservice.getCurrentRepository() ; List<DriveData> driveList = new ArrayList<DriveData>() ; Session session = null ; List<DriveData> drives = driveService.getAllDrives(true) ; if(drives != null && drives.size() > 0) { for(DriveData drive : drives) { if(drive.getIcon() != null && drive.getIcon().length() > 0) { try { String[] iconPath = drive.getIcon().split(":/") ; session = repository.getSystemSession(iconPath[0]) ; session.getItem("/" + iconPath[1]) ; session.logout() ; } catch(PathNotFoundException pnf) { drive.setIcon("") ; } } if(isExistWorkspace(repository, drive)) driveList.add(drive) ; } } Collections.sort(driveList) ; return driveList ; } /** * Get Drive Views Labels from resource Bundle. * * @param driveData DriveData * @return Views Labels */ public String getDriveViews(DriveData driveData) { ResourceBundle res = RequestContext.getCurrentInstance().getApplicationResourceBundle(); String[] viewNames = driveData.getViews().split(","); StringBuilder strBuilder = new StringBuilder(); String viewName = null; for (int i = 0; i < viewNames.length; i++) { viewName = viewNames[i].trim(); String label = null; try { label = res.getString("Views.label." + viewName); } catch (MissingResourceException e) { label = viewName; } if (strBuilder.length() > 0) { strBuilder.append(", "); } strBuilder.append(label); } return strBuilder.toString(); } public String getPortalName() { PortalContainerInfo containerInfo = WCMCoreUtils.getService(PortalContainerInfo.class); return containerInfo.getContainerName(); } public String getRepository() throws Exception { return getAncestorOfType(UIECMAdminPortlet.class).getPreferenceRepository() ; } private boolean isExistWorkspace(ManageableRepository repository, DriveData drive) { for(String ws: repository.getWorkspaceNames()) { if(ws.equals(drive.getWorkspace())) return true ; } return false ; } static public class DriveComparator implements Comparator<DriveData> { public int compare(DriveData o1, DriveData o2) throws ClassCastException { String name1 = o1.getName() ; String name2 = o2.getName() ; return name1.compareToIgnoreCase(name2) ; } } static public class AddDriveActionListener extends EventListener<UIDriveList> { public void execute(Event<UIDriveList> event) throws Exception { UIDriveManager uiDriveManager = event.getSource().getParent() ; uiDriveManager.removeChildById(UIDriveList.ST_EDIT); uiDriveManager.initPopup(UIDriveList.ST_ADD) ; UIDriveForm uiForm = uiDriveManager.findFirstComponentOfType(UIDriveForm.class) ; uiForm.refresh(null) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiDriveManager) ; } } static public class DeleteActionListener extends EventListener<UIDriveList> { public void execute(Event<UIDriveList> event) throws Exception { String name = event.getRequestContext().getRequestParameter(OBJECTID) ; UIDriveList uiDriveList = event.getSource(); ManageDriveService driveService = uiDriveList.getApplicationComponent(ManageDriveService.class) ; driveService.removeDrive(name) ; uiDriveList.refresh(uiDriveList.getUIPageIterator().getCurrentPage()) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiDriveList.getParent()) ; } } static public class EditInfoActionListener extends EventListener<UIDriveList> { public void execute(Event<UIDriveList> event) throws Exception { UIDriveManager uiDriveManager = event.getSource().getParent() ; uiDriveManager.removeChildById(UIDriveList.ST_ADD); uiDriveManager.initPopup(UIDriveList.ST_EDIT) ; String driveName = event.getRequestContext().getRequestParameter(OBJECTID) ; uiDriveManager.findFirstComponentOfType(UIDriveForm.class).refresh(driveName) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiDriveManager) ; } } public String standardizeGroupName(String groupName) throws Exception { groupName = groupName.replaceAll("-", " "); char[] stringArray = groupName.toCharArray(); stringArray[0] = Character.toUpperCase(stringArray[0]); groupName = new String(stringArray); return groupName; } }
8,450
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIViewsInputSet.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/drives/UIViewsInputSet.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.drives; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.MissingResourceException; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.views.ManageViewService; import org.exoplatform.services.cms.views.ViewConfig; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.exception.MessageException; import org.exoplatform.webui.form.UIFormInputSet; import org.exoplatform.webui.form.input.UICheckBoxInput; /** * Created by The eXo Platform SARL * Author : Tran The Trong * trongtt@gmail.com * Jun 28, 2006 */ public class UIViewsInputSet extends UIFormInputSet { public UIViewsInputSet(String name) throws Exception { super(name); } public String getViewsSelected() throws Exception { StringBuilder selectedView = new StringBuilder() ; List<ViewConfig> views_ = getApplicationComponent(ManageViewService.class).getAllViews(); for(ViewConfig view : views_){ String viewName= view.getName() ; boolean checked = getUICheckBoxInput(viewName).isChecked() ; if(checked){ if(selectedView.length() > 0) selectedView.append(", ") ; selectedView.append(viewName) ; } } if(selectedView.length() < 1 ) { throw new MessageException(new ApplicationMessage("UIDriveForm.msg.drive-views-invalid", null, ApplicationMessage.WARNING)) ; } return selectedView.toString() ; } private void clear() throws Exception { List<ViewConfig> views_ = getApplicationComponent(ManageViewService.class).getAllViews(); Collections.sort(views_, new ViewComparator()); for(ViewConfig view : views_){ String viewName = view.getName() ; if(getUICheckBoxInput(viewName) != null) { getUICheckBoxInput(viewName).setChecked(false) ; }else{ addUIFormInput(new UICheckBoxInput(viewName, viewName, null)) ; } } } static public class ViewComparator implements Comparator<ViewConfig> { public int compare(ViewConfig v1, ViewConfig v2) throws ClassCastException { WebuiRequestContext webReqContext = WebuiRequestContext.getCurrentInstance(); String displayName1, displayName2; try { displayName1 = webReqContext.getApplicationResourceBundle().getString("UIDriveForm.label." + v1.getName()); } catch(MissingResourceException mre) { displayName1 = v1.getName(); } try { displayName2 = webReqContext.getApplicationResourceBundle().getString("UIDriveForm.label." + v2.getName()); } catch(MissingResourceException mre) { displayName2 = v2.getName(); } return displayName1.compareToIgnoreCase(displayName2); } } public void update(DriveData drive) throws Exception { clear() ; if( drive == null) return ; String views = drive.getViews() ; String[] array = views.split(",") ; for(String view: array){ getUICheckBoxInput(view.trim()).setChecked(true) ; } } }
3,961
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISEOToolbarForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-seo/src/main/java/org/exoplatform/wcm/webui/seo/UISEOToolbarForm.java
/* * Copyright (C) 2003-2019 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.seo; import org.apache.commons.lang3.StringUtils; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.mop.SiteKey; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.jcr.util.Text; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.seo.PageMetadataModel; import org.exoplatform.services.seo.SEOService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.reader.ContentReader; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Locale; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Jul 4, 2011 */ @ComponentConfig(lifecycle = UIFormLifecycle.class, template = "classpath:groovy/webui/seo/UISEOPortletToolbar.gtmpl", events = { @EventConfig(listeners = UISEOToolbarForm.AddSEOActionListener.class) }) public class UISEOToolbarForm extends UIForm { private static final Log LOG = ExoLogger.getLogger(UISEOToolbarForm.class.getName()); /** The Constant SEO_POPUP_WINDOW. */ public static final String SEO_POPUP_WINDOW = "UISEOPopupWindow"; private ArrayList<String> paramsArray = null; private String pageReference = null; private PageMetadataModel metaModel = null; private String fullStatus = "Empty"; private String lang = null; public UISEOToolbarForm() { } public ArrayList<String> getParamsArray() { return paramsArray; } public String getPageReference() { return pageReference; } public PageMetadataModel getMetaModel() { return metaModel; } public void setMetaModel(PageMetadataModel metaModel) { this.metaModel = metaModel; } public static class AddSEOActionListener extends EventListener<UISEOToolbarForm> { public void execute(Event<UISEOToolbarForm> event) throws Exception { UISEOToolbarForm uiSEOToolbar = event.getSource(); PortalRequestContext portalRequestContext = Util.getPortalRequestContext(); UISEOForm uiSEOForm = uiSEOToolbar.createUIComponent(UISEOForm.class, null, null); SEOService seoService = WCMCoreUtils.getService(SEOService.class); ArrayList<String> paramsArray = uiSEOToolbar.getParamsArray(); if(paramsArray != null) { for(int i = 0; i < paramsArray.size(); i++) { Node contentNode = seoService.getContentNode(paramsArray.get(i)); if(contentNode != null) { uiSEOForm.setOnContent(true); uiSEOForm.setContentPath(paramsArray.get(i)); uiSEOForm.setContentURI(contentNode.getUUID()); break; } } uiSEOToolbar.setMetaModel(seoService.getContentMetadata(paramsArray, uiSEOToolbar.lang)); } else { uiSEOForm.setContentPath(uiSEOToolbar.getPageReference()); uiSEOForm.setOnContent(false); uiSEOToolbar.setMetaModel(seoService.getPageMetadata(uiSEOToolbar.getPageReference(), uiSEOToolbar.lang)); } uiSEOForm.setParamsArray(paramsArray); if(uiSEOToolbar.getMetaModel() == null) { //If have node seo data for default language, displaying seo data for the first language in the list List<Locale> seoLocales = seoService.getSEOLanguages(portalRequestContext.getPortalOwner(), uiSEOForm.getContentPath(), uiSEOForm.getOnContent()); if(seoLocales.size()> 0) { Locale locale = seoLocales.get(0); StringBuffer sb = new StringBuffer(); sb.append(locale.getLanguage()); String country = locale.getCountry(); if(StringUtils.isNotEmpty(country)) sb.append("_").append(country); String lang = sb.toString(); uiSEOToolbar.setMetaModel(seoService.getMetadata(uiSEOForm.getParamsArray(), uiSEOToolbar.getPageReference(), lang)); uiSEOForm.setSelectedLanguage(lang); } } uiSEOForm.initSEOForm(uiSEOToolbar.getMetaModel()); Utils.createPopupWindow(uiSEOToolbar, uiSEOForm, SEO_POPUP_WINDOW, true, 640); } } public void processRender(WebuiRequestContext context) throws Exception { PortalRequestContext pcontext = Util.getPortalRequestContext(); StringBuffer sb = new StringBuffer(); sb.append(pcontext.getLocale().getLanguage()); if(StringUtils.isNotEmpty(pcontext.getLocale().getCountry())) sb.append("_").append(pcontext.getLocale().getCountry()); lang = sb.toString(); String portalName = pcontext.getPortalOwner(); metaModel = null; fullStatus = "Empty"; if (!pcontext.useAjax()) { paramsArray = null; String contentParam; Enumeration params = pcontext.getRequest().getParameterNames(); if(params.hasMoreElements()) { paramsArray = new ArrayList<>(); while(params.hasMoreElements()) { contentParam = params.nextElement().toString(); String contentValue; try { contentValue = Text.unescape(pcontext.getRequestParameter(contentParam)); } catch(Exception ex) { contentValue = pcontext.getRequestParameter(contentParam); } contentValue = ContentReader.getXSSCompatibilityContent(contentValue); if(paramsArray != null) { paramsArray.add(Text.escapeIllegalJcrChars(contentValue)); } } } } SEOService seoService = WCMCoreUtils.getService(SEOService.class); pageReference = Util.getUIPortal().getSelectedUserNode().getPageRef().format(); if(pageReference != null) { SiteKey siteKey = Util.getUIPortal().getSelectedUserNode().getNavigation().getKey(); SiteKey portalKey = SiteKey.portal(portalName); if(siteKey != null && siteKey.equals(portalKey)) { metaModel = seoService.getPageMetadata(pageReference, lang); if(paramsArray != null) { PageMetadataModel tmpModel = null; try{ tmpModel = seoService.getContentMetadata(paramsArray,lang); }catch(PathNotFoundException ex) { if (LOG.isErrorEnabled()) { LOG.error("Cannot found the content metadata", ex); } } if(tmpModel != null) { metaModel = tmpModel; } else { try { for(int i = 0;i < paramsArray.size();i++) { Node contentNode = seoService.getContentNode(paramsArray.get(i).toString()); if(contentNode != null ) { metaModel = null; break; } } }catch(PathNotFoundException ex) { metaModel = null; } } } } else fullStatus = "Disabled"; } if(metaModel != null) fullStatus = metaModel.getFullStatus(); super.processRender(context); } public String getFullStatus() { return this.fullStatus; } }
8,218
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISEOToolbarPortlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-seo/src/main/java/org/exoplatform/wcm/webui/seo/UISEOToolbarPortlet.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.seo; import java.util.Date; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.UIPortletApplication; import org.exoplatform.webui.core.lifecycle.UIApplicationLifecycle; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Jul 4, 2011 */ @ComponentConfig(lifecycle = UIApplicationLifecycle.class) public class UISEOToolbarPortlet extends UIPortletApplication { public UISEOToolbarPortlet() throws Exception { addChild(UIPopupContainer.class, null, "UIPopupContainer-" + new Date().getTime()); addChild(UISEOToolbarForm.class, null, null); } @Override public void processRender(WebuiRequestContext context) throws Exception { super.processRender(context); } }
1,641
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISEOForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-seo/src/main/java/org/exoplatform/wcm/webui/seo/UISEOForm.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.seo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.apache.commons.lang3.StringUtils; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.portal.webui.workspace.UIPortalApplication; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.resources.LocaleConfig; import org.exoplatform.services.resources.LocaleConfigService; import org.exoplatform.services.seo.PageMetadataModel; import org.exoplatform.services.seo.SEOService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.validator.FloatNumberValidator; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.web.url.navigation.NavigationResource; import org.exoplatform.web.url.navigation.NodeURL; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.Event.Phase; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormSelectBox; import org.exoplatform.webui.form.UIFormStringInput; import org.exoplatform.webui.form.UIFormTextAreaInput; import org.exoplatform.webui.form.input.UICheckBoxInput; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Jun 17, 2011 */ @ComponentConfig(lifecycle = UIFormLifecycle.class, template = "classpath:groovy/webui/seo/UISEOForm.gtmpl", events = { @EventConfig(listeners = UISEOForm.SaveActionListener.class), @EventConfig(phase=Phase.DECODE, listeners = UISEOForm.RefreshActionListener.class), @EventConfig(phase=Phase.DECODE, listeners = UISEOForm.UpdateActionListener.class), @EventConfig(listeners = UISEOForm.RemoveActionListener.class, confirm = "UISEOForm.msg.confirm-delete"), @EventConfig(phase=Phase.DECODE, listeners = UISEOForm.CancelActionListener.class) }) public class UISEOForm extends UIForm{ public static final String TITLE = "title"; public static final String DESCRIPTION = "description"; public static final String KEYWORDS = "keywords"; final static public String LANGUAGE_TYPE = "language" ; public static final String ROBOTS = "robots"; public static final String SITEMAP = "sitemap"; public static final String ISINHERITED = "isInherited"; public static final String SITEMAP_VISIBLE = "sitemapvisible"; public static final String PRIORITY = "priority"; public static final String FREQUENCY = "frequency"; public static final String ROBOTS_INDEX = "INDEX"; public static final String ROBOTS_FOLLOW = "FOLLOW"; public static final String FREQUENCY_DEFAULT_VALUE = "Always"; String title = ""; String description = ""; String keywords = ""; String priority = ""; String frequency = ""; String index = ""; String follow = ""; boolean sitemap = true; boolean inherited = false; private static String contentPath = null; private static String contentURI = null; private boolean onContent = false; private boolean isInherited = false; private ArrayList<String> paramsArray = null; public List<Locale> seoLocales; public List<String> seoLanguages; private String selectedLanguage; private String defaultLanguage; private boolean isAddNew = true; private static final Log LOG = ExoLogger.getLogger(UISEOForm.class.getName()); public String getContentPath() { return this.contentPath; } public void setContentPath(String contentPath) { this.contentPath = contentPath; } public String getContentURI() { return this.contentURI; } public void setContentURI(String contentURI) { this.contentURI = contentURI; } public boolean getOnContent() { return this.onContent; } public void setOnContent(boolean onContent) { this.onContent = onContent; } public boolean getIsInherited() { return this.isInherited; } public void setIsInherited(boolean isInherited) { this.isInherited = isInherited; } public ArrayList<String> getParamsArray() { return this.paramsArray; } public void setSEOLocales(List<Locale> seoLocales) { this.seoLocales = seoLocales; } public List<Locale> getSEOLocales() { return this.seoLocales; } public List<String> getSeoLanguages() { return seoLanguages; } public void setSeoLanguages(List<String> seoLanguages) { this.seoLanguages = seoLanguages; } public void setParamsArray(ArrayList<String> params) { this.paramsArray = params; } public String getSelectedLanguage() { return selectedLanguage; } public void setSelectedLanguage(String selectedLanguage) { this.selectedLanguage = selectedLanguage; } public void setIsAddNew(boolean isAddNew) { this.isAddNew = isAddNew; } public boolean getIsAddNew() { return this.isAddNew; } public UISEOForm() throws Exception { PortalRequestContext portalRequestContext = Util.getPortalRequestContext(); ExoContainer container = ExoContainerContext.getCurrentContainer() ; SEOService seoService = container.getComponentInstanceOfType(SEOService.class); UIFormTextAreaInput uiTitle = new UIFormTextAreaInput(TITLE, TITLE, null); uiTitle.setValue(title); addUIFormInput(uiTitle); UIFormTextAreaInput uiDescription = new UIFormTextAreaInput(DESCRIPTION, DESCRIPTION, null); uiDescription.setValue(description); addUIFormInput(uiDescription); UIFormTextAreaInput uiKeywords = new UIFormTextAreaInput(KEYWORDS, KEYWORDS, null); uiKeywords.setValue(keywords); addUIFormInput(uiKeywords); seoLocales = seoService.getSEOLanguages(portalRequestContext.getPortalOwner(), contentPath, onContent); seoLanguages = new ArrayList<>(); if(seoLocales != null && seoLocales.size() > 0) { for (Locale locale : seoLocales) { StringBuffer sb = new StringBuffer(); sb.append(locale.getLanguage()); String country = locale.getCountry(); if(StringUtils.isNotEmpty(country)) sb.append("_").append(country); seoLanguages.add(sb.toString()); } } if(seoLanguages != null) Collections.sort(seoLanguages); UIFormSelectBox uiSelectForm = new UIFormSelectBox(LANGUAGE_TYPE, LANGUAGE_TYPE, getLanguages()) ; uiSelectForm.setOnChange("Refresh"); defaultLanguage = portalRequestContext.getLocale().getLanguage(); if(StringUtils.isNotEmpty(portalRequestContext.getLocale().getCountry())) defaultLanguage += "_" + portalRequestContext.getLocale().getCountry(); selectedLanguage = defaultLanguage; if(seoLanguages == null || !seoLanguages.contains(defaultLanguage)) uiSelectForm.setValue(defaultLanguage); addUIFormInput(uiSelectForm) ; if(!onContent) { List<SelectItemOption<String>> robotIndexItemOptions = new ArrayList<>(); List<String> robotsindexOptions = seoService.getRobotsIndexOptions(); List<String> robotsfollowOptions = seoService.getRobotsFollowOptions(); List<String> frequencyOptions = seoService.getFrequencyOptions(); if(robotsindexOptions != null && robotsindexOptions.size() > 0) { for(int i = 0; i < robotsindexOptions.size(); i++) { robotIndexItemOptions.add(new SelectItemOption<>((robotsindexOptions.get(i).toString()))); } } UIFormSelectBox robots_index = new UIFormSelectBox(ROBOTS_INDEX, null, robotIndexItemOptions); if(index != null && index.length() > 0) robots_index.setValue(index); else robots_index.setValue(ROBOTS_INDEX); addUIFormInput(robots_index); List<SelectItemOption<String>> robotFollowItemOptions = new ArrayList<>(); if(robotsfollowOptions != null && robotsfollowOptions.size() > 0) { for(int i = 0; i < robotsfollowOptions.size(); i++) { robotFollowItemOptions.add(new SelectItemOption<>((robotsfollowOptions.get(i).toString()))); } } UIFormSelectBox robots_follow = new UIFormSelectBox(ROBOTS_FOLLOW, null, robotFollowItemOptions); if(follow != null && follow.length() > 0) robots_follow.setValue(follow); else robots_follow.setValue(ROBOTS_FOLLOW); addUIFormInput(robots_follow); UICheckBoxInput visibleSitemapCheckbox = new UICheckBoxInput(SITEMAP, SITEMAP, sitemap); addUIFormInput(visibleSitemapCheckbox); UIFormStringInput uiPrority = new UIFormStringInput(PRIORITY, null); if(!StringUtils.isEmpty(priority)) uiPrority.setValue(priority); addUIFormInput(uiPrority.addValidator(FloatNumberValidator.class)); List<SelectItemOption<String>> frequencyItemOptions = new ArrayList<>(); if (frequencyOptions != null && frequencyOptions.size() > 0) { for (int i = 0; i < frequencyOptions.size(); i++) { frequencyItemOptions.add(new SelectItemOption<>(frequencyOptions.get(i).toString(), (frequencyOptions.get(i).toString()))); } } UIFormSelectBox frequencySelectbox = new UIFormSelectBox(FREQUENCY, null, frequencyItemOptions); if(frequency != null && frequency.length() > 0) frequencySelectbox.setValue(frequency); else frequencySelectbox.setValue(FREQUENCY_DEFAULT_VALUE); addUIFormInput(frequencySelectbox); } setActions(new String[]{"Save", "Cancel"}); } public void initSEOForm(PageMetadataModel pageModel) throws Exception{ PortalRequestContext portalRequestContext = Util.getPortalRequestContext(); if(pageModel != null) { title = pageModel.getTitle(); description = pageModel.getDescription(); keywords = pageModel.getKeywords(); frequency = pageModel.getFrequency(); if(pageModel.getPriority() >= 0) priority = String.valueOf(pageModel.getPriority()); else priority = null; if(pageModel.getRobotsContent() != null && pageModel.getRobotsContent().length() > 0) { index = pageModel.getRobotsContent().split(",")[0].trim(); follow = pageModel.getRobotsContent().split(",")[1].trim(); } sitemap = pageModel.getSitemap(); } else { if(!onContent) title = portalRequestContext.getTitle(); else title = ""; description = ""; keywords = ""; priority = ""; frequency = ""; index = ""; follow = ""; sitemap = true; } ExoContainer container = ExoContainerContext.getCurrentContainer() ; SEOService seoService = (SEOService)container.getComponentInstanceOfType(SEOService.class); UIFormTextAreaInput uiTitle = this.getUIFormTextAreaInput(TITLE); if(uiTitle != null) uiTitle.setValue(title); UIFormTextAreaInput uiDescription = this.getUIFormTextAreaInput(DESCRIPTION); if(uiDescription != null) uiDescription.setValue(description); UIFormTextAreaInput uiKeywords = this.getUIFormTextAreaInput(KEYWORDS); if(uiKeywords != null) uiKeywords.setValue(keywords); UIFormSelectBox uiSelectForm = this.getUIFormSelectBox(LANGUAGE_TYPE); uiSelectForm.setSelectedValues(new String[] {"language"}); if(uiSelectForm != null) { seoLocales = seoService.getSEOLanguages(portalRequestContext.getPortalOwner(), contentPath, onContent); seoLanguages = new ArrayList<>(); if(seoLocales != null && seoLocales.size() > 0) { for (Locale locale : seoLocales) { StringBuffer sb = new StringBuffer(); sb.append(locale.getLanguage()); String country = locale.getCountry(); if(StringUtils.isNotEmpty(country)) sb.append("_").append(country); seoLanguages.add(sb.toString()); } } if(seoLanguages.size() <= 0) setSelectedLanguage(null); List<SelectItemOption<String>> languages = getLanguages(); if(languages.size() == 1) this.setIsAddNew(false); else this.setIsAddNew(true); uiSelectForm.setOptions(languages); uiSelectForm.setValue(selectedLanguage); } if(!onContent) { List<SelectItemOption<String>> robotIndexItemOptions = new ArrayList<>(); List<String> robotsindexOptions = seoService.getRobotsIndexOptions(); List<String> robotsfollowOptions = seoService.getRobotsFollowOptions(); List<String> frequencyOptions = seoService.getFrequencyOptions(); if(robotsindexOptions != null && robotsindexOptions.size() > 0) { for(int i = 0; i < robotsindexOptions.size(); i++) { robotIndexItemOptions.add(new SelectItemOption<>((robotsindexOptions.get(i).toString()))); } } UIFormSelectBox robots_index = this.getUIFormSelectBox(ROBOTS_INDEX); if(robots_index != null) { if(index != null && index.length() > 0) robots_index.setValue(index); else robots_index.setValue(ROBOTS_INDEX); } List<SelectItemOption<String>> robotFollowItemOptions = new ArrayList<>(); if(robotsfollowOptions != null && robotsfollowOptions.size() > 0) { for(int i = 0; i < robotsfollowOptions.size(); i++) { robotFollowItemOptions.add(new SelectItemOption<>((robotsfollowOptions.get(i).toString()))); } } UIFormSelectBox robots_follow = this.getUIFormSelectBox(ROBOTS_FOLLOW); if(robots_follow != null) { if(follow != null && follow.length() > 0) robots_follow.setValue(follow); else robots_follow.setValue(ROBOTS_FOLLOW); } UICheckBoxInput visibleSitemapCheckbox = this.getUICheckBoxInput(SITEMAP); if(visibleSitemapCheckbox != null) visibleSitemapCheckbox.setChecked(sitemap); UIFormStringInput uiPrority = this.getUIStringInput(PRIORITY); if(uiPrority != null) { if(!StringUtils.isEmpty(priority)) uiPrority.setValue(priority); else uiPrority.setValue(""); } List<SelectItemOption<String>> frequencyItemOptions = new ArrayList<>(); if (frequencyOptions != null && frequencyOptions.size() > 0) { for (int i = 0; i < frequencyOptions.size(); i++) { frequencyItemOptions.add(new SelectItemOption<>(frequencyOptions.get(i).toString(), (frequencyOptions.get(i).toString()))); } } UIFormSelectBox frequencySelectbox = this.getUIFormSelectBox(FREQUENCY); if(frequencySelectbox != null) { if(frequency != null && frequency.length() > 0) frequencySelectbox.setValue(frequency); else frequencySelectbox.setValue(FREQUENCY_DEFAULT_VALUE); } } } public static class SaveActionListener extends EventListener<UISEOForm> { public void execute(Event<UISEOForm> event) throws Exception { UISEOForm uiForm = event.getSource(); UIApplication uiApp = uiForm.getAncestorOfType(UIApplication.class) ; String description = uiForm.getUIFormTextAreaInput(DESCRIPTION).getValue(); String keywords = uiForm.getUIFormTextAreaInput(KEYWORDS).getValue() ; PortalRequestContext portalRequestContext = Util.getPortalRequestContext(); String lang = null; if(uiForm.getSelectedLanguage() != null) lang = uiForm.getSelectedLanguage(); else { lang = uiForm.getUIFormSelectBox(LANGUAGE_TYPE).getValue() ; StringBuffer sb = new StringBuffer(); if(lang == null || lang.equals(LANGUAGE_TYPE)) { lang = portalRequestContext.getLocale().getLanguage(); sb.append(portalRequestContext.getLocale().getLanguage()); if(StringUtils.isNotEmpty(portalRequestContext.getLocale().getCountry())) sb.append("_").append(portalRequestContext.getLocale().getCountry()); lang = sb.toString(); } } uiForm.setSelectedLanguage(lang); String portalName = portalRequestContext.getPortalOwner(); String uri = portalRequestContext.createURL(NodeURL.TYPE, new NavigationResource(Util.getUIPortal().getSelectedUserNode())).toString(); String fullStatus = null; String pageReference = Util.getUIPortal().getSelectedUserNode().getPageRef().format(); if(!uiForm.onContent) { String title = uiForm.getUIFormTextAreaInput(TITLE).getValue(); String robots_index = uiForm.getUIFormSelectBox(ROBOTS_INDEX).getValue() ; String robots_follow = uiForm.getUIFormSelectBox(ROBOTS_FOLLOW).getValue() ; String rebots_content = robots_index + ", " + robots_follow; boolean isVisibleSitemap = uiForm.getUICheckBoxInput(SITEMAP).isChecked(); float priority = -1; if(uiForm.getUIStringInput(PRIORITY).getValue() != null && uiForm.getUIStringInput(PRIORITY).getValue().length() > 0) { priority = Float.parseFloat(uiForm.getUIStringInput(PRIORITY).getValue()) ; if(priority < 0.0 || priority > 1.0) { uiApp.addMessage(new ApplicationMessage("FloatNumberValidator.msg.Invalid-number", null, ApplicationMessage.WARNING)); return; } } String frequency = uiForm.getUIFormSelectBox(FREQUENCY).getValue() ; try { PageMetadataModel metaModel = new PageMetadataModel(); metaModel.setTitle(title); metaModel.setDescription(description); metaModel.setFrequency(frequency); metaModel.setKeywords(keywords); metaModel.setPriority(priority); metaModel.setRobotsContent(rebots_content); metaModel.setSiteMap(isVisibleSitemap); metaModel.setUri(uri); metaModel.setPageReference(pageReference); if(description!= null && keywords != null && priority != -1) fullStatus = "Full"; else fullStatus = "Partial"; metaModel.setFullStatus(fullStatus); SEOService seoService = uiForm.getApplicationComponent(SEOService.class); seoService.storeMetadata(metaModel, portalName, uiForm.onContent, uiForm.getSelectedLanguage()); uiForm.initSEOForm(metaModel); if(uiForm.getAncestorOfType(UISEOToolbarPortlet.class) != null) event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UISEOToolbarPortlet.class)) ; else { event.getRequestContext().addUIComponentToUpdateByAjax(uiForm); event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupContainer.class).getParent()); } } catch (Exception ex) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error ", ex); } uiApp.addMessage(new ApplicationMessage("UISEOForm.msg.repository-exception", null, ApplicationMessage.ERROR)); return; } } else { try { PageMetadataModel metaModel = new PageMetadataModel(); metaModel.setDescription(description); metaModel.setKeywords(keywords); metaModel.setUri(uri); metaModel.setPageReference(pageReference); if(description != null && keywords != null) fullStatus = "Full"; else fullStatus = "Partial"; metaModel.setFullStatus(fullStatus); SEOService seoService = uiForm.getApplicationComponent(SEOService.class); Node contentNode = null; for(int i=0;i<uiForm.paramsArray.size(); i++) { String contentPath = uiForm.paramsArray.get(i).toString(); contentNode = seoService.getContentNode(contentPath); if(contentNode != null) break; } metaModel.setUri(contentNode.getUUID()); seoService.storeMetadata(metaModel, portalName, uiForm.onContent, uiForm.getSelectedLanguage()); uiForm.initSEOForm(metaModel); if(uiForm.getAncestorOfType(UISEOToolbarPortlet.class) != null) event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UISEOToolbarPortlet.class)) ; else { event.getRequestContext().addUIComponentToUpdateByAjax(uiForm); event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupContainer.class).getParent()); } } catch (RepositoryException ex) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error ", ex); } uiApp.addMessage(new ApplicationMessage("UISEOForm.msg.repository-exception", null, ApplicationMessage.ERROR)); return; } } } } public static class CancelActionListener extends EventListener<UISEOForm> { public void execute(Event<UISEOForm> event) throws Exception { UISEOForm uiSEO = event.getSource(); UIPopupContainer uiSEOToolbar = uiSEO.getAncestorOfType(UIPopupContainer.class); if(uiSEOToolbar != null) uiSEOToolbar.removeChildById(UISEOToolbarForm.SEO_POPUP_WINDOW); } } public static class RefreshActionListener extends EventListener<UISEOForm> { public void execute(Event<UISEOForm> event) throws Exception { PortalRequestContext portalRequestContext = Util.getPortalRequestContext(); UISEOForm uiForm = event.getSource(); String portalName = portalRequestContext.getPortalOwner(); String lang = uiForm.getUIFormSelectBox(LANGUAGE_TYPE).getValue(); if(lang.equals("language")) return; uiForm.setSelectedLanguage(lang); String pageReference = Util.getUIPortal().getSelectedUserNode().getPageRef().format(); SEOService seoService = uiForm.getApplicationComponent(SEOService.class); PageMetadataModel seoData = new PageMetadataModel(); PageMetadataModel metaModel = seoService.getMetadata(uiForm.paramsArray, pageReference, uiForm.defaultLanguage); if(metaModel == null) metaModel = new PageMetadataModel(); if(uiForm.onContent) { seoData.setUri(uiForm.getContentURI()); metaModel.setUri(uiForm.getContentURI()); } else { seoData.setPageReference(pageReference); seoData.setTitle(portalRequestContext.getTitle()); metaModel.setTitle(portalRequestContext.getTitle()); } seoData.setFullStatus("Empty"); seoService.storeMetadata(seoData, portalName, uiForm.onContent, lang); uiForm.initSEOForm(metaModel); event.getRequestContext().addUIComponentToUpdateByAjax(uiForm) ; } } public static class UpdateActionListener extends EventListener<UISEOForm> { public void execute(Event<UISEOForm> event) throws Exception { UISEOForm uiForm = event.getSource(); String lang = event.getRequestContext().getRequestParameter(OBJECTID) ; uiForm.setSelectedLanguage(lang); SEOService seoService = uiForm.getApplicationComponent(SEOService.class); String pageReference = Util.getUIPortal().getSelectedUserNode().getPageRef().format(); PageMetadataModel metaModel = seoService.getMetadata(uiForm.paramsArray, pageReference, lang); if(metaModel == null || (metaModel != null && metaModel.getFullStatus().equals("Empty"))) { metaModel = seoService.getMetadata(uiForm.paramsArray, pageReference, uiForm.defaultLanguage); } uiForm.initSEOForm(metaModel); event.getRequestContext().addUIComponentToUpdateByAjax(uiForm) ; } } public static class RemoveActionListener extends EventListener<UISEOForm> { public void execute(Event<UISEOForm> event) throws Exception { UISEOForm uiForm = event.getSource(); PortalRequestContext portalRequestContext = Util.getPortalRequestContext(); String lang = event.getRequestContext().getRequestParameter(OBJECTID) ; SEOService seoService = uiForm.getApplicationComponent(SEOService.class); PageMetadataModel metaModel = new PageMetadataModel(); String pageReference = Util.getUIPortal().getSelectedUserNode().getPageRef().format(); metaModel.setPageReference(pageReference); if(uiForm.onContent) { Node contentNode = null; for(int i=0;i<uiForm.paramsArray.size(); i++) { String contentPath = uiForm.paramsArray.get(i).toString(); contentNode = seoService.getContentNode(contentPath); if(contentNode != null) break; } if(contentNode != null) metaModel.setUri(contentNode.getUUID()); } String portalName = portalRequestContext.getPortalOwner(); seoService.removePageMetadata(metaModel, portalName, uiForm.onContent, lang); uiForm.setSEOLocales(seoService.getSEOLanguages(portalRequestContext.getPortalOwner(), contentPath, uiForm.onContent)); List<String> seoLanguages = new ArrayList<>(); for (Locale locale : uiForm.getSEOLocales()) { StringBuffer sb = new StringBuffer(); sb.append(locale.getLanguage()); String country = locale.getCountry(); if(StringUtils.isNotEmpty(country)) sb.append("_").append(country); seoLanguages.add(sb.toString()); } uiForm.setSeoLanguages(seoLanguages); String laguageFocus = uiForm.defaultLanguage; if(seoLanguages.size()> 0 && !seoLanguages.contains(uiForm.defaultLanguage)) laguageFocus = seoLanguages.get(0); metaModel = seoService.getMetadata(uiForm.paramsArray, pageReference, laguageFocus); if(metaModel != null) uiForm.setSelectedLanguage(laguageFocus); else uiForm.getUIFormSelectBox(LANGUAGE_TYPE).setValue(uiForm.defaultLanguage); uiForm.initSEOForm(metaModel); if(uiForm.getAncestorOfType(UISEOToolbarPortlet.class) != null) event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UISEOToolbarPortlet.class)) ; else { event.getRequestContext().addUIComponentToUpdateByAjax(uiForm); event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getAncestorOfType(UIPopupContainer.class).getParent()); } } } public List<SelectItemOption<String>> getLanguages() throws Exception { WebuiRequestContext rc = WebuiRequestContext.getCurrentInstance(); Locale inLocale = WebuiRequestContext.getCurrentInstance().getLocale(); // Get default locale Locale defaultLocale = Locale.getDefault(); // set default locale to current user selected language Locale.setDefault(Util.getUIPortal().getAncestorOfType(UIPortalApplication.class).getLocale()); LocaleConfigService localService = WCMCoreUtils.getService(LocaleConfigService.class) ; List<SelectItemOption<String>> languages = new ArrayList<>() ; Iterator<LocaleConfig> iter = localService.getLocalConfigs().iterator() ; ResourceBundle resourceBundle = rc.getApplicationResourceBundle(); while (iter.hasNext()) { LocaleConfig localConfig = iter.next() ; Locale locale = localConfig.getLocale(); StringBuffer sb = new StringBuffer(); sb.append(locale.getLanguage()); String country = locale.getCountry(); if(StringUtils.isNotEmpty(country)) sb.append("_").append(country); String lang = sb.toString(); if(seoLanguages == null || !seoLanguages.contains(lang)) { try { languages.add(new SelectItemOption<>(CapitalFirstLetters(locale.getDisplayName(inLocale)), lang)) ; } catch(MissingResourceException mre) { languages.add(new SelectItemOption<>(lang, lang)) ; } } } // Set back to the default locale Locale.setDefault(defaultLocale); Collections.sort(languages, new ItemOptionComparator()); languages.add(0,new SelectItemOption<>(getLabel(resourceBundle, "select-language"), "language")) ; return languages ; } public String CapitalFirstLetters(String str) { str = Character.toString(str.charAt(0)).toUpperCase()+str.substring(1); return str; } class ItemOptionComparator implements Comparator<SelectItemOption<String>> { @Override public int compare(SelectItemOption<String> o1, SelectItemOption<String> o2) { return o1.getLabel().compareTo(o2.getLabel()); } } class SEOItemComparator implements Comparator<Locale> { @Override public int compare(Locale locale1, Locale locale2) { return locale1.getDisplayLanguage().compareTo(locale2.getDisplayLanguage()); } } }
29,883
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIAdminToolbarPortlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/toolbar/UIAdminToolbarPortlet.java
/** * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.wcm.webui.toolbar; import org.exoplatform.portal.mop.user.UserNavigation; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.webui.application.WebuiApplication; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIPortletApplication; import org.exoplatform.webui.core.lifecycle.UIApplicationLifecycle; @ComponentConfig(lifecycle = UIApplicationLifecycle.class, template = "app:/groovy/Toolbar/UIAdminToolbarPortlet.gtmpl") public class UIAdminToolbarPortlet extends UIPortletApplication { // Minh Hoang TO // TODO: Add a ThreadLocal cache to avoid double invocation of editPermission // check ( one in processRender method, and one in Groovy template ) public UIAdminToolbarPortlet() throws Exception { } public UserNavigation getSelectedNavigation() throws Exception { return Utils.getSelectedNavigation(); } public boolean hasEditPermissionOnPortal() throws Exception { return Utils.hasEditPermissionOnPortal(); } public boolean hasEditPermissionOnNavigation() throws Exception { return Utils.hasEditPermissionOnNavigation(); } public boolean hasEditPermissionOnPage() throws Exception { return Utils.hasEditPermissionOnPage(); } @Override public void processRender(WebuiApplication app, WebuiRequestContext context) throws Exception { // A user could view the toolbar portlet iff he/she has edit permission // either on // 'active' page, 'active' portal or 'active' navigation if (hasEditPermissionOnNavigation() || hasEditPermissionOnPage() || hasEditPermissionOnPortal()) { super.processRender(app, context); } } }
2,620
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICategoryNavigationTree.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/category/UICategoryNavigationTree.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.category; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.nodetype.NodeType; import javax.portlet.PortletPreferences; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.container.UIContainer; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.cms.taxonomy.TaxonomyService; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.wcm.webui.category.config.UICategoryNavigationConfig; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UITree; import org.exoplatform.webui.core.lifecycle.Lifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Jun 19, 2009 */ @ComponentConfig( lifecycle = Lifecycle.class, template = "app:/groovy/CategoryNavigation/UICategoryNavigationTree.gtmpl", events = { @EventConfig(listeners = UICategoryNavigationTree.QuickEditActionListener.class), @EventConfig(listeners = UICategoryNavigationTree.ChangeNodeActionListener.class) } ) public class UICategoryNavigationTree extends UIContainer { private static final Log LOG = ExoLogger.getLogger(UICategoryNavigationTree.class.getName()); /** The allow publish. */ private boolean allowPublish = false; /** The publication service_. */ private PublicationService publicationService_ = null; /** The templates_. */ private List<String> templates_ = null; /** The accepted node types. */ private String[] acceptedNodeTypes = {}; /** The root tree node. */ protected NodeLocation rootTreeNode; /** The current node. */ protected NodeLocation currentNode; /** * Checks if is allow publish. * * @return true, if is allow publish */ public boolean isAllowPublish() { return allowPublish; } /** * Sets the allow publish. * * @param allowPublish the allow publish * @param publicationService the publication service * @param templates the templates */ public void setAllowPublish(boolean allowPublish, PublicationService publicationService, List<String> templates) { this.allowPublish = allowPublish; publicationService_ = publicationService; templates_ = templates; } /** * Instantiates a new uI node tree builder. * * @throws Exception the exception */ public UICategoryNavigationTree() throws Exception { PortletPreferences portletPreferences = UICategoryNavigationUtils.getPortletPreferences(); String preferenceTreeName = portletPreferences.getValue(UICategoryNavigationConstant.PREFERENCE_TREE_NAME, ""); TaxonomyService taxonomyService = getApplicationComponent(TaxonomyService.class); Node rootTreeNode = null; try { rootTreeNode = taxonomyService.getTaxonomyTree(preferenceTreeName); } catch (RepositoryException e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } setRootTreeNode(rootTreeNode); setAcceptedNodeTypes(new String[] {"nt:folder", "nt:unstructured", "nt:file", "exo:taxonomy"}); UITree tree = addChild(UICategoryNavigationTreeBase.class, null, null); tree.setBeanLabelField("name"); tree.setBeanIdField("path"); } /** * Gets the root tree node. * * @return the root tree node */ public Node getRootTreeNode() { return NodeLocation.getNodeByLocation(rootTreeNode); } /** * Sets the root tree node. * * @param node the new root tree node * * @throws Exception the exception */ public final void setRootTreeNode(Node node) throws Exception { this.rootTreeNode = NodeLocation.getNodeLocationByNode(node); this.currentNode = NodeLocation.getNodeLocationByNode(node); } /** * Gets the current node. * * @return the current node */ public Node getCurrentNode() { return NodeLocation.getNodeByLocation(currentNode); } /** * Sets the current node. * * @param currentNode the new current node */ public void setCurrentNode(Node currentNode) { this.currentNode = NodeLocation.getNodeLocationByNode(currentNode); } /** * Gets the accepted node types. * * @return the accepted node types */ public String[] getAcceptedNodeTypes() { return acceptedNodeTypes; } /** * Sets the accepted node types. * * @param acceptedNodeTypes the new accepted node types */ public void setAcceptedNodeTypes(String[] acceptedNodeTypes) { this.acceptedNodeTypes = acceptedNodeTypes; } /* (non-Javadoc) * @see org.exoplatform.webui.core.UIComponent#processRender(org.exoplatform.webui.application.WebuiRequestContext) */ public void processRender(WebuiRequestContext context) throws Exception { String parameters = null; try { parameters = URLDecoder.decode(StringUtils.substringAfter(Util.getPortalRequestContext() .getNodePath(), Util.getUIPortal() .getSelectedUserNode() .getURI() + "/"), "UTF-8"); } catch (UnsupportedEncodingException e) { org.exoplatform.wcm.webui.Utils.createPopupMessage(this, "UICategoryNavigationConfig.msg.not-support-encoding", null, ApplicationMessage.ERROR); } PortletPreferences portletPreferences = UICategoryNavigationUtils.getPortletPreferences(); String preferenceTreeName = portletPreferences.getValue(UICategoryNavigationConstant.PREFERENCE_TREE_NAME, ""); TaxonomyService taxonomyService = getApplicationComponent(TaxonomyService.class); Node treeNode = null; try { treeNode = taxonomyService.getTaxonomyTree(preferenceTreeName); } catch (RepositoryException e) { currentNode = null; super.processRender(context); return; } String categoryPath = parameters.substring(parameters.indexOf("/") + 1); if (preferenceTreeName.equals(categoryPath)) categoryPath = ""; currentNode = NodeLocation.getNodeLocationByNode(treeNode.getNode(categoryPath)); super.processRender(context); } /** * Builds the tree. * * @throws Exception the exception */ public void buildTree() throws Exception { NodeIterator sibbling = null; NodeIterator children = null; UICategoryNavigationTreeBase tree = getChild(UICategoryNavigationTreeBase.class); Node selectedNode = NodeLocation.getNodeByLocation(currentNode); tree.setSelected(selectedNode); if (selectedNode == null) { return; } if (Utils.getNodeSymLink(selectedNode).getDepth() > 0) { tree.setParentSelected(selectedNode.getParent()); sibbling = Utils.getNodeSymLink(selectedNode).getNodes(); children = Utils.getNodeSymLink(selectedNode).getNodes(); } else { tree.setParentSelected(selectedNode); sibbling = Utils.getNodeSymLink(selectedNode).getNodes(); children = null; } if (sibbling != null) { tree.setSibbling(filter(sibbling)); } if (children != null) { tree.setChildren(filter(children)); } } /** * Adds the node publish. * * @param listNode the list node * @param node the node * @param publicationService the publication service * * @throws Exception the exception */ private void addNodePublish(List<Node> listNode, Node node, PublicationService publicationService) throws Exception { if (isAllowPublish()) { NodeType nt = node.getPrimaryNodeType(); if (templates_.contains(nt.getName())) { Node nodecheck = publicationService.getNodePublish(node, null); if (nodecheck != null) { listNode.add(nodecheck); } } else { listNode.add(node); } } else { listNode.add(node); } } /** * Filter. * * @param iterator the iterator * * @return the list< node> * * @throws Exception the exception */ private List<Node> filter(final NodeIterator iterator) throws Exception { List<Node> list = new ArrayList<Node>(); if (acceptedNodeTypes.length > 0) { for (; iterator.hasNext();) { Node sibbling = iterator.nextNode(); if (sibbling.isNodeType("exo:hiddenable")) continue; for (String nodetype : acceptedNodeTypes) { if (sibbling.isNodeType(nodetype)) { list.add(sibbling); break; } } } List<Node> listNodeCheck = new ArrayList<Node>(); for (Node node : list) { addNodePublish(listNodeCheck, node, publicationService_); } return listNodeCheck; } for (; iterator.hasNext();) { Node sibbling = iterator.nextNode(); if (sibbling.isNodeType("exo:hiddenable")) continue; list.add(sibbling); } List<Node> listNodeCheck = new ArrayList<Node>(); for (Node node : list) addNodePublish(listNodeCheck, node, publicationService_); return listNodeCheck; } /** * When a node is change in tree. This method will be rerender the children and sibbling nodes of * current node and broadcast change node event to other uicomponent * * @param path the path * @param context the context * * @throws Exception the exception */ public void changeNode(String path, Object context) throws Exception { NodeFinder nodeFinder_ = getApplicationComponent(NodeFinder.class); String rootPath = rootTreeNode.getPath(); if (rootPath.equals(path) || !path.startsWith(rootPath)) { currentNode = rootTreeNode; } else { if (path.startsWith(rootPath)) path = path.substring(rootPath.length()); if (path.startsWith("/")) path = path.substring(1); currentNode = NodeLocation.getNodeLocationByNode(nodeFinder_.getNode(NodeLocation.getNodeByLocation(rootTreeNode), path)); } } /** * The listener interface for receiving changeNodeAction events. The class * that is interested in processing a changeNodeAction event implements this * interface, and the object created with that class is registered with a * component using the component's * <code>addChangeNodeActionListener</code> method. When * the changeNodeAction event occurs, that object's appropriate * method is invoked. */ static public class ChangeNodeActionListener extends EventListener<UITree> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UITree> event) throws Exception { UICategoryNavigationTree categoryNavigationTree = event.getSource().getParent(); String uri = event.getRequestContext().getRequestParameter(OBJECTID); categoryNavigationTree.changeNode(uri, event.getRequestContext()); event.getRequestContext().addUIComponentToUpdateByAjax(categoryNavigationTree.getParent()); } } /** * The listener interface for receiving quickEditAction events. The class * that is interested in processing a quickEditAction event implements this * interface, and the object created with that class is registered with a * component using the component's * <code>addQuickEditActionListener</code> method. When * the quickEditAction event occurs, that object's appropriate * method is invoked. */ public static class QuickEditActionListener extends EventListener<UICategoryNavigationTree> { /* * (non-Javadoc) * * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICategoryNavigationTree> event) throws Exception { UICategoryNavigationTree uiContainer = event.getSource(); UICategoryNavigationConfig configForm = uiContainer.createUIComponent(UICategoryNavigationConfig.class, null, null); org.exoplatform.wcm.webui.Utils.createPopupWindow(uiContainer, configForm, UICategoryNavigationPortlet.CONFIG_POPUP_WINDOW, 600); } } }
14,646
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICategoryNavigationUtils.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/category/UICategoryNavigationUtils.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.category; import javax.portlet.PortletPreferences; import javax.portlet.PortletRequest; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Jun 29, 2009 */ public class UICategoryNavigationUtils { /** * Gets the portlet preferences. * * @return the portlet preferences */ public static PortletPreferences getPortletPreferences() { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); PortletRequest request = portletRequestContext.getRequest(); return request.getPreferences(); } }
1,546
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICategoryNavigationTreeBase.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/category/UICategoryNavigationTreeBase.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.category; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.portlet.PortletPreferences; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.resolver.JCRResourceResolver; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.mop.SiteType; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.services.cms.taxonomy.TaxonomyService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.friendly.FriendlyService; import org.exoplatform.services.wcm.portal.LivePortalManagerService; import org.exoplatform.web.url.navigation.NavigationResource; import org.exoplatform.web.url.navigation.NodeURL; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIRightClickPopupMenu; import org.exoplatform.webui.core.UITree; import jakarta.servlet.http.HttpServletRequestWrapper; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Comment: Change objId from node's path to category's path * Jun 30, 2009 */ @ComponentConfig( events = @EventConfig(listeners = UITree.ChangeNodeActionListener.class) ) public class UICategoryNavigationTreeBase extends UITree { private static final Log LOG = ExoLogger.getLogger(UICategoryNavigationTreeBase.class.getName()); /* (non-Javadoc) * @see org.exoplatform.webui.core.UITree#renderNode(java.lang.Object) */ public String renderNode(Object obj) throws Exception { Node node = (Node) obj; String nodeTypeIcon = Utils.getNodeTypeIcon(node,"16x16Icon"); String nodeIcon = this.getExpandIcon(); String iconGroup = this.getIcon(); String note = "" ; if(isSelected(obj)) { nodeIcon = getColapseIcon(); iconGroup = getSelectedIcon(); note = " NodeSelected" ; } String beanIconField = getBeanIconField(); if(beanIconField != null && beanIconField.length() > 0) { if(getFieldValue(obj, beanIconField) != null) iconGroup = (String)getFieldValue(obj, beanIconField); } renderCategoryLink(node); String objId = String.valueOf(getId(obj)); StringBuilder builder = new StringBuilder(); if (nodeIcon.equals(getExpandIcon())) { builder.append(" <a class=\"") .append(nodeIcon) .append(" ") .append(nodeTypeIcon) .append("\" href=\"") .append(objId) .append("\">"); } else { builder.append(" <a class=\"") .append(nodeIcon) .append(" ") .append(nodeTypeIcon) .append("\" onclick=\"eXo.portal.UIPortalControl.collapseTree(this)") .append("\">"); } UIRightClickPopupMenu popupMenu = getUiPopupMenu(); String beanLabelField = getBeanLabelField(); String className="NodeIcon"; boolean flgSymlink = false; if (Utils.isSymLink(node)) { flgSymlink = true; className = "NodeIconLink"; } if (popupMenu == null) { builder.append(" <div class=\"") .append(className) .append(" ") .append(iconGroup) .append(" ") .append(nodeTypeIcon) .append(note) .append("\"") .append(" title=\"") .append(getFieldValue(obj, beanLabelField)) .append("\"") .append(">"); if (flgSymlink) { builder.append(" <div class=\"LinkSmall\">") .append(getFieldValue(obj, beanLabelField)) .append("</div>"); } else { builder.append(getFieldValue(obj, beanLabelField)); } builder.append("</div>"); } else { builder.append(" <div class=\"") .append(className) .append(" ") .append(iconGroup) .append(" ") .append(nodeTypeIcon) .append(note) .append("\" ") .append(popupMenu.getJSOnclickShowPopup(objId, null)) .append(" title=\"") .append(getFieldValue(obj, beanLabelField)) .append("\"") .append(">"); if (flgSymlink) { builder.append(" <div class=\"LinkSmall\">") .append(getFieldValue(obj, beanLabelField)) .append("</div>"); } else { builder.append(getFieldValue(obj, beanLabelField)); } builder.append("</div>"); } builder.append(" </a>"); return builder.toString(); } /* (non-Javadoc) * @see org.exoplatform.webui.core.UIComponent#getTemplate() */ public String getTemplate() { return UICategoryNavigationUtils.getPortletPreferences() .getValue(UICategoryNavigationConstant.PREFERENCE_TEMPLATE_PATH, null); } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIComponent#getTemplateResourceResolver(org. * exoplatform.webui.application.WebuiRequestContext, java.lang.String) */ public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context, String template) { DMSConfiguration dmsConfiguration = getApplicationComponent(DMSConfiguration.class); String workspace = dmsConfiguration.getConfig().getSystemWorkspace(); return new JCRResourceResolver(workspace); } /* (non-Javadoc) * @see org.exoplatform.webui.core.UITree#getActionLink() */ public String getActionLink() throws Exception { PortletRequestContext porletRequestContext = (PortletRequestContext) WebuiRequestContext.getCurrentInstance(); HttpServletRequestWrapper requestWrapper = (HttpServletRequestWrapper) porletRequestContext.getRequest(); String requestURI = requestWrapper.getRequestURI(); PortletPreferences portletPreferences = UICategoryNavigationUtils.getPortletPreferences(); String preferenceTreeName = portletPreferences.getValue(UICategoryNavigationConstant.PREFERENCE_TREE_NAME, ""); String preferenceTargetPage = portletPreferences.getValue(UICategoryNavigationConstant.PREFERENCE_TARGET_PAGE, ""); String backPath = requestURI.substring(0, requestURI.lastIndexOf("/")); if (backPath.endsWith(preferenceTargetPage) || requestURI.endsWith(Util.getUIPortal().getSelectedUserNode().getURI())) backPath = "javascript:void(0)"; else if (backPath.endsWith(preferenceTreeName)) backPath = backPath.substring(0, backPath.lastIndexOf("/")); return backPath; } /* (non-Javadoc) * @see org.exoplatform.webui.core.UITree#isSelected(java.lang.Object) */ public boolean isSelected(Object obj) throws Exception { Node selectedNode = this.getSelected(); Node node = (Node) obj; if(selectedNode == null) return false; return selectedNode.getPath().equals(node.getPath()); } public boolean isMovedTreeToTrash(String rootCategory) throws Exception { Node categoryNode = getCategoryNode(rootCategory); if (Utils.isInTrash(categoryNode)) return true; return false; } /** * Gets the subcategories. * * @param categoryPath the category path * * @return the subcategories * * @throws Exception the exception */ public List<Node> getSubcategories(String categoryPath) throws Exception { Node categoryNode = getCategoryNode(categoryPath); NodeIterator nodeIterator = categoryNode.getNodes(); List<Node> subcategories = new ArrayList<Node>(); while (nodeIterator.hasNext()) { Node subcategory = nodeIterator.nextNode(); if (subcategory.isNodeType("exo:taxonomy")) subcategories.add(subcategory); } return subcategories; } /** * Resolve category path by uri. * * @param context the context * * @return the string */ public String resolveCategoryPathByUri(WebuiRequestContext context) throws Exception { String parameters = null; try { // parameters: Classic/News/France/Blah/Bom parameters = URLDecoder.decode(StringUtils.substringAfter(Util.getPortalRequestContext() .getNodePath(), Util.getUIPortal() .getSelectedUserNode() .getURI()), "UTF-8"); } catch (UnsupportedEncodingException e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } // categoryPath: /News/France/Blah/Bom String categoryPath = parameters.indexOf("/") >= 0 ? parameters.substring(parameters.indexOf("/")) : ""; String gpath = Util.getPortalRequestContext().getRequestParameter("path"); if (gpath != null) { PortletPreferences portletPreferences = UICategoryNavigationUtils.getPortletPreferences(); String preferenceTreeName = portletPreferences.getValue(UICategoryNavigationConstant.PREFERENCE_TREE_NAME, ""); categoryPath = gpath.substring(gpath.indexOf(preferenceTreeName) + preferenceTreeName.length()); } return categoryPath; } /** * Gets the categories by uri. * * @param categoryUri the category uri * * @return the categories by uri * * @throws Exception the exception */ public List<String> getCategoriesByUri(String categoryUri) throws Exception { PortletPreferences portletPreferences = UICategoryNavigationUtils.getPortletPreferences(); String preferenceTreeName = portletPreferences.getValue(UICategoryNavigationConstant.PREFERENCE_TREE_NAME, ""); if (preferenceTreeName.equals(categoryUri)) categoryUri = ""; // categories: {"/", "News", "News/France", "News/France/Blah", "News/France/Blah/Bom"} List<String> categories = new ArrayList<String>(); String[] tempCategories = categoryUri.split("/"); StringBuffer tempCategory = new StringBuffer(); for (int i = 0; i < tempCategories.length; i++) { if (i == 0) tempCategory = new StringBuffer(""); else if (i == 1) tempCategory = new StringBuffer(tempCategories[1]); else tempCategory.append("/").append(tempCategories[i]); categories.add(tempCategory.toString()); } return categories; } /** * Render category link. * * @param node the node * * @return the string * * @throws Exception the exception */ public String renderCategoryLink(Node node) throws Exception { // preferenceTargetPage: products/presentation/pclv PortletPreferences portletPreferences = UICategoryNavigationUtils.getPortletPreferences(); String preferenceTargetPage = portletPreferences.getValue(UICategoryNavigationConstant.PREFERENCE_TARGET_PAGE, ""); LivePortalManagerService livePortalManagerService = getApplicationComponent(LivePortalManagerService.class); Node portalNode = livePortalManagerService.getLivePortalByChild(node); String preferenceTreeName = portletPreferences.getValue(UICategoryNavigationConstant.PREFERENCE_TREE_NAME, ""); String categoryPath = node.getPath().replaceFirst(portalNode.getPath(), ""); // categoryPath = categoryPath.substring(categoryPath.indexOf(preferenceTreeName) + preferenceTreeName.length()); categoryPath = categoryPath.substring(categoryPath.indexOf(preferenceTreeName)-1); NodeURL nodeURL = Util.getPortalRequestContext().createURL(NodeURL.TYPE); NavigationResource resource = new NavigationResource(SiteType.PORTAL, Util.getPortalRequestContext() .getPortalOwner(), preferenceTargetPage); nodeURL.setResource(resource).setQueryParameterValue("path", categoryPath); String link = nodeURL.toString(); FriendlyService friendlyService = getApplicationComponent(FriendlyService.class); link = friendlyService.getFriendlyUri(link); return link; } /** * get content's title if exists (from exo:title property) * * @param node The node * @return the title * @throws Exception */ public String getTitle(Node node) throws Exception { if (node.hasProperty("exo:title")) return node.getProperty("exo:title").getString(); else return node.getName(); } public String getTreeTitle() { return UICategoryNavigationUtils.getPortletPreferences().getValue(UICategoryNavigationConstant.PREFERENCE_TREE_TITLE, ""); } private Node getCategoryNode(String categoryPath) throws Exception { TaxonomyService taxonomyService = getApplicationComponent(TaxonomyService.class); PortletPreferences portletPreferences = UICategoryNavigationUtils.getPortletPreferences(); String preferenceTreeName = portletPreferences.getValue(UICategoryNavigationConstant.PREFERENCE_TREE_NAME, ""); Node treeNode = taxonomyService.getTaxonomyTree(preferenceTreeName); Node categoryNode = null; if ("".equals(categoryPath)) categoryNode = treeNode; else categoryNode = treeNode.getNode(categoryPath); return categoryNode; } }
14,853
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICategoryNavigationPortlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/category/UICategoryNavigationPortlet.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.category; import java.util.Date; import javax.portlet.PortletMode; import org.exoplatform.wcm.webui.category.config.UICategoryNavigationConfig; import org.exoplatform.webui.application.WebuiApplication; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.UIPortletApplication; import org.exoplatform.webui.core.lifecycle.UIApplicationLifecycle; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Jun 19, 2009 */ @ComponentConfig( lifecycle = UIApplicationLifecycle.class ) public class UICategoryNavigationPortlet extends UIPortletApplication { /** The Constant MANAGEMENT_PORTLET_POPUP_WINDOW. */ public static final String CONFIG_POPUP_WINDOW = "UICNConfigPopupWindow"; /** The mode. */ private PortletMode mode = PortletMode.VIEW; /** * Instantiates a new uI category navigation portlet. * * @throws Exception the exception */ public UICategoryNavigationPortlet() throws Exception { activateMode(mode); } /** * Activate mode. * * @param mode the mode * * @throws Exception the exception */ public void activateMode(PortletMode mode) throws Exception { getChildren().clear(); addChild(UIPopupContainer.class, null, "UIPopupContainer-" + new Date().getTime()); if (PortletMode.VIEW.equals(mode)) { addChild(UICategoryNavigationTree.class, null, null); } else if (PortletMode.EDIT.equals(mode)) { addChild(UICategoryNavigationConfig.class, null, null); } } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIPortletApplication#processRender(org.exoplatform * .webui.application.WebuiApplication, * org.exoplatform.webui.application.WebuiRequestContext) */ public void processRender(WebuiApplication app, WebuiRequestContext context) throws Exception { PortletRequestContext pContext = (PortletRequestContext) context; PortletMode newMode = pContext.getApplicationMode(); if (!mode.equals(newMode)) { activateMode(newMode); mode = newMode; } super.processRender(app, context); } }
3,185
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICategoryNavigationConstant.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/category/UICategoryNavigationConstant.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.category; /** * Created by The eXo Platform SAS Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com Jun 29, 2009 */ public class UICategoryNavigationConstant { /** The Constant PREFERENCE_PORTLET_NAME. */ public static final String PREFERENCE_PORTLET_NAME = "portletName"; /** The Constant PREFERENCE_REPOSITORY. */ public static final String PREFERENCE_REPOSITORY = "repository"; /** The Constant PREFERENCE_TREE_TITLE. */ public static final String PREFERENCE_TREE_TITLE = "treeTitle"; /** The Constant PREFERENCE_TREE_NAME. */ public static final String PREFERENCE_TREE_NAME = "treeName"; /** The Constant PREFERENCE_TEMPLATE_CATEGORY. */ public static final String PREFERENCE_TEMPLATE_CATEGORY = "templateCategory"; /** The Constant PREFERENCE_TEMPLATE_PATH. */ public static final String PREFERENCE_TEMPLATE_PATH = "templatePath"; /** The Constant PREFERENCE_TARGET_PAGE. */ public static final String PREFERENCE_TARGET_PAGE = "targetPath"; /** The Constant REPOSITORY_FORM_SELECTBOX. */ public static final String REPOSITORY_FORM_SELECTBOX = "UICategoryNavigationRepositoryFormSelectBox"; /** The Constant WORKSPACE_FORM_SELECTBOX. */ public static final String WORKSPACE_FORM_SELECTBOX = "UICategoryNavigationWorkspaceFormSelectBox"; /** The Constant TREE_NAME_FORM_SELECTBOX. */ public static final String TREE_NAME_FORM_SELECTBOX = "UICategoryNavigationTreeNameFormSelectBox"; /** The Constant TEMPLATE_FORM_SELECTBOX. */ public static final String TEMPLATE_FORM_SELECTBOX = "UICategoryNavigationTemplateFormSelectBox"; /** The Constant TREE_TITLE_FORM_STRING_INPUT. */ public static final String TREE_TITLE_FORM_STRING_INPUT = "UICategoryNavigationTreeTitleFormStringInput"; /** The Constant TARGET_PATH_FORM_INPUT_SET. */ public static final String TARGET_PATH_FORM_INPUT_SET = "UICategoryNavigationTargetPathFormInputSet"; /** The Constant TARGET_PATH_FORM_STRING_INPUT. */ public static final String TARGET_PATH_FORM_STRING_INPUT = "UICategoryNavigationTargetPathFormStringInput"; /** The Constant TARGET_PATH_SELECTOR_POPUP_WINDOW. */ public static final String TARGET_PATH_SELECTOR_POPUP_WINDOW = "UICategoryNavigationTargetPathPopupWindow"; public static final String PREFERENCE_TREE_PATH = "treePath"; public static final String PREFERENCE_HEADER = "header"; public static final String PREFERENCE_AUTOMATIC = "automatic"; public static final String PREFERENCE_WITH_CLV = "with"; public static final String TREE_PATH_FORM_INPUT_SET = "UICategoryNavigationTreePathFormInputSet"; public static final String TREE_PATH_FORM_STRING_INPUT = "UICategoryNavigationTreePathFormStringInput"; public static final String HEADER_FORM_STRING_INPUT = "UICategoryNavigationHeaderFormStringInput"; public static final String AUTOMATIC_DETECTION_CHECKBOX_INPUT = "UICategoryNavigationAutomaticDetectionCheckBoxInput"; public static final String DYNAMIC_NAVIGATION_LABEL = "UICategoryNavigationDynamicNavigationLabel"; public static final String WITH_CLV_FORM_STRING_INPUT = "UICategoryNavigationWithClvFormStringInput"; public static final String DEFAULT_WITH_CLV_VALUE = "folder-id"; public static final String TREE_PATH_SELECTOR_POPUP_WINDOW = "UICategoryNavigationTreepathPopupWindow"; }
4,427
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICategoryNavigationConfig.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/category/config/UICategoryNavigationConfig.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.category.config; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.portlet.PortletMode; import javax.portlet.PortletPreferences; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.webui.portal.UIPortal; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.taxonomy.TaxonomyService; import org.exoplatform.services.cms.views.ApplicationTemplateManagerService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.config.RepositoryEntry; import org.exoplatform.services.wcm.portal.LivePortalManagerService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.category.UICategoryNavigationConstant; import org.exoplatform.wcm.webui.category.UICategoryNavigationPortlet; import org.exoplatform.wcm.webui.category.UICategoryNavigationUtils; import org.exoplatform.wcm.webui.selector.page.UIPageSelector; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.web.application.RequireJS; import org.exoplatform.web.url.navigation.NodeURL; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormSelectBox; import org.exoplatform.webui.form.UIFormStringInput; import org.exoplatform.webui.form.ext.UIFormInputSetWithAction; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Jun 28, 2009 */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "system:/groovy/webui/form/UIForm.gtmpl", events = { @EventConfig(listeners = UICategoryNavigationConfig.SaveActionListener.class), @EventConfig(listeners = UICategoryNavigationConfig.CancelActionListener.class), @EventConfig(listeners = UICategoryNavigationConfig.ChangeRepositoryActionListener.class), @EventConfig(listeners = UICategoryNavigationConfig.SelectTargetPathActionListener.class) } ) public class UICategoryNavigationConfig extends UIForm implements UISelectable { /** The popup id. */ private String popupId; /** * Instantiates a new uI category navigation config. * * @throws Exception the exception */ public UICategoryNavigationConfig() throws Exception { PortletPreferences preferences = UICategoryNavigationUtils.getPortletPreferences(); String preferenceRepository = preferences.getValue(UICategoryNavigationConstant.PREFERENCE_REPOSITORY, ""); RepositoryService repositoryService = getApplicationComponent(RepositoryService.class) ; List<SelectItemOption<String>> repositories = new ArrayList<SelectItemOption<String>>() ; RepositoryEntry repositoryEntry = repositoryService.getCurrentRepository().getConfiguration(); repositories.add(new SelectItemOption<String>(repositoryEntry.getName())) ; UIFormSelectBox repositoryFormSelectBox = new UIFormSelectBox(UICategoryNavigationConstant.REPOSITORY_FORM_SELECTBOX, UICategoryNavigationConstant.REPOSITORY_FORM_SELECTBOX, repositories); repositoryFormSelectBox.setValue(preferenceRepository); repositoryFormSelectBox.setOnChange("ChangeRepository"); addUIFormInput(repositoryFormSelectBox); String preferenceTreeTitle = preferences.getValue(UICategoryNavigationConstant.PREFERENCE_TREE_TITLE, ""); addUIFormInput(new UIFormStringInput(UICategoryNavigationConstant.TREE_TITLE_FORM_STRING_INPUT, UICategoryNavigationConstant.TREE_TITLE_FORM_STRING_INPUT, preferenceTreeTitle)); String preferenceTreeName = preferences.getValue(UICategoryNavigationConstant.PREFERENCE_TREE_NAME, ""); List<SelectItemOption<String>> trees = getTaxonomyTrees(); UIFormSelectBox treeNameFormSelectBox = new UIFormSelectBox(UICategoryNavigationConstant.TREE_NAME_FORM_SELECTBOX, UICategoryNavigationConstant.TREE_NAME_FORM_SELECTBOX, trees); treeNameFormSelectBox.setValue(preferenceTreeName); addUIFormInput(treeNameFormSelectBox); String preferencePortletName = preferences.getValue(UICategoryNavigationConstant.PREFERENCE_PORTLET_NAME, ""); String preferenceTemplateCategory = preferences.getValue(UICategoryNavigationConstant.PREFERENCE_TEMPLATE_CATEGORY, ""); String preferenceTemplatePath = preferences.getValue(UICategoryNavigationConstant.PREFERENCE_TEMPLATE_PATH, ""); List<SelectItemOption<String>> templates = getTemplateList(preferencePortletName, preferenceTemplateCategory); UIFormSelectBox templateFormSelectBox = new UIFormSelectBox(UICategoryNavigationConstant.TEMPLATE_FORM_SELECTBOX, UICategoryNavigationConstant.TEMPLATE_FORM_SELECTBOX, templates); templateFormSelectBox.setValue(preferenceTemplatePath); addUIFormInput(templateFormSelectBox); String preferenceTargetPath = preferences.getValue(UICategoryNavigationConstant.PREFERENCE_TARGET_PAGE, ""); UIFormInputSetWithAction targetPathFormInputSet = new UIFormInputSetWithAction(UICategoryNavigationConstant.TARGET_PATH_FORM_INPUT_SET); UIFormStringInput targetPathFormStringInput = new UIFormStringInput(UICategoryNavigationConstant.TARGET_PATH_FORM_STRING_INPUT, UICategoryNavigationConstant.TARGET_PATH_FORM_STRING_INPUT, preferenceTargetPath); targetPathFormStringInput.setReadOnly(true); targetPathFormInputSet.setActionInfo(UICategoryNavigationConstant.TARGET_PATH_FORM_STRING_INPUT, new String[] { "SelectTargetPath" }); targetPathFormInputSet.addUIFormInput(targetPathFormStringInput); addChild(targetPathFormInputSet); setActions(new String[] {"Save", "Cancel"}); } /** * Gets the popup id. * * @return the popup id */ public String getPopupId() { return popupId; } /** * Sets the popup id. * * @param popupId the new popup id */ public void setPopupId(String popupId) { this.popupId = popupId; } /** * Gets the template list. * * @param portletName the portlet name * @param templateCategory the template category * * @return the template list * * @throws Exception the exception */ private List<SelectItemOption<String>> getTemplateList(String portletName, String templateCategory) throws Exception { List<SelectItemOption<String>> templates = new ArrayList<SelectItemOption<String>>(); ApplicationTemplateManagerService appTemplateMngService = getApplicationComponent(ApplicationTemplateManagerService.class); List<Node> templateNodes = appTemplateMngService.getTemplatesByCategory(portletName, templateCategory, WCMCoreUtils.getUserSessionProvider()); for (Node templateNode : templateNodes) { String templateName = templateNode.getName(); String templatePath = templateNode.getPath(); templates.add(new SelectItemOption<String>(templateName, templatePath)); } return templates; } /** * Gets the taxonomy trees. * * @param repository the repository * * @return the taxonomy trees * * @throws Exception the exception */ private List<SelectItemOption<String>> getTaxonomyTrees() throws Exception { TaxonomyService taxonomyService = getApplicationComponent(TaxonomyService.class); LivePortalManagerService livePortalManagerService = getApplicationComponent(LivePortalManagerService.class); List<Node> taxonomyNodes = taxonomyService.getAllTaxonomyTrees(); List<SelectItemOption<String>> taxonomyTrees = new ArrayList<SelectItemOption<String>>(); for(Node taxonomyNode : taxonomyNodes) { Node portalNode = livePortalManagerService.getLivePortalByChild(taxonomyNode); if (portalNode != null) taxonomyTrees.add(new SelectItemOption<String>(taxonomyNode.getName(), taxonomyNode.getName())); } return taxonomyTrees; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.selector.UISelectable#doSelect(java.lang.String, java.lang.Object) */ public void doSelect(String selectField, Object value) throws Exception { UIFormStringInput formStringInput = findComponentById(selectField); formStringInput.setValue(value.toString()) ; UICategoryNavigationPortlet categoryNavigationPortlet = getAncestorOfType(UICategoryNavigationPortlet.class); UIPopupContainer popupContainer = categoryNavigationPortlet.getChild(UIPopupContainer.class); Utils.closePopupWindow(popupContainer, popupId); } /** * The listener interface for receiving saveAction events. * The class that is interested in processing a saveAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSaveActionListener</code> method. When * the saveAction event occurs, that object's appropriate * method is invoked. */ public static class SaveActionListener extends EventListener<UICategoryNavigationConfig> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICategoryNavigationConfig> event) throws Exception { UICategoryNavigationConfig categoryNavigationConfig = event.getSource(); String preferenceRepository = categoryNavigationConfig. getUIFormSelectBox(UICategoryNavigationConstant.REPOSITORY_FORM_SELECTBOX).getValue(); String preferenceTreeName = categoryNavigationConfig. getUIFormSelectBox(UICategoryNavigationConstant.TREE_NAME_FORM_SELECTBOX).getValue(); String preferenceTreeTitle = categoryNavigationConfig. getUIStringInput(UICategoryNavigationConstant.TREE_TITLE_FORM_STRING_INPUT).getValue(); if (preferenceTreeTitle == null) preferenceTreeTitle = ""; String preferenceTargetPath = categoryNavigationConfig. getUIStringInput(UICategoryNavigationConstant.TARGET_PATH_FORM_STRING_INPUT).getValue(); String preferenceTemplate = categoryNavigationConfig. getUIFormSelectBox(UICategoryNavigationConstant.TEMPLATE_FORM_SELECTBOX).getValue(); PortletPreferences portletPreferences = UICategoryNavigationUtils.getPortletPreferences(); portletPreferences.setValue(UICategoryNavigationConstant.PREFERENCE_REPOSITORY, preferenceRepository); portletPreferences.setValue(UICategoryNavigationConstant.PREFERENCE_TREE_NAME, preferenceTreeName); portletPreferences.setValue(UICategoryNavigationConstant.PREFERENCE_TREE_TITLE, preferenceTreeTitle); portletPreferences.setValue(UICategoryNavigationConstant.PREFERENCE_TARGET_PAGE, preferenceTargetPath); portletPreferences.setValue(UICategoryNavigationConstant.PREFERENCE_TEMPLATE_PATH, preferenceTemplate); portletPreferences.store(); if (!Utils.isEditPortletInCreatePageWizard()) { PortalRequestContext portalRequestContext = Util.getPortalRequestContext(); UIPortal uiPortal = Util.getUIPortal(); NodeURL nodeURL = portalRequestContext.createURL(NodeURL.TYPE); String uri = nodeURL.setNode(uiPortal.getSelectedUserNode()).toString(); ((PortletRequestContext)event.getRequestContext()).setApplicationMode(PortletMode.VIEW); Utils.closePopupWindow(categoryNavigationConfig, UICategoryNavigationPortlet.CONFIG_POPUP_WINDOW); RequireJS requireJS = event.getRequestContext().getJavascriptManager().getRequireJS(); requireJS.require("SHARED/ecm-utils", "ecmutil").addScripts("ecmutil.ECMUtils.ajaxRedirect('" + uri + "');"); } else { if (Utils.isQuickEditMode(categoryNavigationConfig, UICategoryNavigationPortlet.CONFIG_POPUP_WINDOW)) { Utils.closePopupWindow(categoryNavigationConfig, UICategoryNavigationPortlet.CONFIG_POPUP_WINDOW); } else { Utils.createPopupMessage(categoryNavigationConfig, "UICategoryNavigationConfig.msg.saving-success", null, ApplicationMessage.INFO); } } } } /** * The listener interface for receiving cancelAction events. * The class that is interested in processing a cancelAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addCancelActionListener</code> method. When * the cancelAction event occurs, that object's appropriate * method is invoked. */ public static class CancelActionListener extends EventListener<UICategoryNavigationConfig> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICategoryNavigationConfig> event) throws Exception { UICategoryNavigationConfig viewerManagementForm = event.getSource(); Utils.closePopupWindow(viewerManagementForm, UICategoryNavigationPortlet.CONFIG_POPUP_WINDOW); ((PortletRequestContext)event.getRequestContext()).setApplicationMode(PortletMode.VIEW); } } /** * The listener interface for receiving changeRepositoryAction events. * The class that is interested in processing a changeRepositoryAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addChangeRepositoryActionListener</code> method. When * the changeRepositoryAction event occurs, that object's appropriate * method is invoked. */ public static class ChangeRepositoryActionListener extends EventListener<UICategoryNavigationConfig> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICategoryNavigationConfig> event) throws Exception { } } /** * The listener interface for receiving selectTargetPathAction events. * The class that is interested in processing a selectTargetPathAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSelectTargetPathActionListener</code> method. When * the selectTargetPathAction event occurs, that object's appropriate * method is invoked. */ public static class SelectTargetPathActionListener extends EventListener<UICategoryNavigationConfig> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICategoryNavigationConfig> event) throws Exception { UICategoryNavigationConfig categoryNavigationConfig = event.getSource(); UICategoryNavigationPortlet categoryNavigationPortlet = categoryNavigationConfig. getAncestorOfType(UICategoryNavigationPortlet.class); UIPopupContainer popupContainer = categoryNavigationPortlet.getChild(UIPopupContainer.class); UIPageSelector pageSelector = popupContainer.createUIComponent(UIPageSelector.class, null, null); pageSelector.setSourceComponent(categoryNavigationConfig, new String[] { UICategoryNavigationConstant.TARGET_PATH_FORM_STRING_INPUT }); Utils.createPopupWindow(popupContainer, pageSelector, UICategoryNavigationConstant.TARGET_PATH_SELECTOR_POPUP_WINDOW, 700); categoryNavigationConfig.setPopupId(UICategoryNavigationConstant.TARGET_PATH_SELECTOR_POPUP_WINDOW); } } }
17,988
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
Utils.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/utils/Utils.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.utils; import java.util.List; import javax.jcr.Node; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.wcm.extensions.publication.PublicationManager; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.Lifecycle; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Created by The eXo Platform SAS * Author : Dang Viet Ha * hadv@exoplatform.com * 22-06-2011 */ public class Utils { /** * This method check whether to show the publish button for the current node or not * @param currentNode the input current node * @return <code>true</code> if the current node can be published, * otherwise <code>false</code> * @throws Exception */ public static boolean isShowFastPublish(Node currentNode) throws Exception { if (currentNode.hasProperty("publication:currentState") && currentNode.hasProperty("publication:lifecycle")) { String currentState = currentNode.getProperty("publication:currentState").getString(); if (!"published".equals(currentState)) { String userId; try { userId = Util.getPortalRequestContext().getRemoteUser(); } catch (Exception e) { userId = currentNode.getSession().getUserID(); } String nodeLifecycle = currentNode.getProperty("publication:lifecycle").getString(); PublicationManager publicationManager = WCMCoreUtils.getService(PublicationManager.class); List<Lifecycle> lifecycles = publicationManager.getLifecyclesFromUser(userId, "published"); for (Lifecycle lifecycle : lifecycles) { if (nodeLifecycle.equals(lifecycle.getName())) { return true; } } } } return false; } }
2,535
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIPresentation.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/scv/UIPresentation.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.scv; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.portlet.PortletPreferences; import javax.portlet.PortletRequest; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.resolver.JCRResourceResolver; import org.exoplatform.ecm.webui.presentation.AbstractActionComponent; import org.exoplatform.ecm.webui.presentation.NodePresentation; import org.exoplatform.ecm.webui.presentation.UIBaseNodePresentation; import org.exoplatform.ecm.webui.presentation.removeattach.RemoveAttachmentComponent; import org.exoplatform.ecm.webui.presentation.removecomment.RemoveCommentComponent; import org.exoplatform.portal.mop.SiteType; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.friendly.FriendlyService; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.web.application.Parameter; import org.exoplatform.web.application.RequireJS; import org.exoplatform.web.url.navigation.NavigationResource; import org.exoplatform.web.url.navigation.NodeURL; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.UIPortletApplication; import org.exoplatform.webui.core.lifecycle.Lifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS * Author : DANG TAN DUNG * dzungdev@gmail.com * Jun 9, 2008 */ @ComponentConfig( lifecycle = Lifecycle.class, events = { @EventConfig(listeners = UIPresentation.DownloadActionListener.class), @EventConfig(listeners = UIPresentation.SwitchToAudioDescriptionActionListener.class), @EventConfig(listeners = UIPresentation.SwitchToOriginalActionListener.class), @EventConfig(listeners = UIBaseNodePresentation.OpenDocInDesktopActionListener.class) } ) public class UIPresentation extends UIBaseNodePresentation { private static final Log LOG = ExoLogger.getLogger(UIPresentation.class.getName()); private NodeLocation originalNodeLocation; private NodeLocation viewNodeLocation; String templatePath = null; /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.UIBaseNodePresentation#getOriginalNode() */ public Node getOriginalNode() throws Exception { return originalNodeLocation == null ? null : Utils.getViewableNodeByComposer(originalNodeLocation.getRepository(), originalNodeLocation.getWorkspace(), originalNodeLocation.getPath(), WCMComposer.BASE_VERSION); } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.UIBaseNodePresentation#getNode() */ public void setOriginalNode(Node node) throws Exception{ originalNodeLocation = NodeLocation.getNodeLocationByNode(node); } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.UIBaseNodePresentation#getNode() */ public Node getNode() throws Exception { Node ret = getDisplayNode(); if (NodePresentation.MEDIA_STATE_DISPLAY.equals(getMediaState()) && (ret.isNodeType(NodetypeConstant.EXO_ACCESSIBLE_MEDIA) || (ret.isNodeType(NodetypeConstant.NT_FROZEN_NODE) && NodetypeConstant.EXO_ACCESSIBLE_MEDIA.equals(ret.getProperty("jcr:frozenPrimaryType").getString())))) { Node audioDescription = org.exoplatform.services.cms.impl.Utils.getChildOfType(ret, NodetypeConstant.EXO_AUDIO_DESCRIPTION); if (audioDescription != null) { return audioDescription; } } return ret; } public String getFastPublicLink(Node viewNode) { String fastPublishLink = null; try { UIPresentationContainer container = (UIPresentationContainer)this.getParent(); fastPublishLink = container.event("FastPublish", NodeLocation.getExpressionByNode(viewNode)); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } return fastPublishLink; } public Node getDisplayNode() throws Exception { if (viewNodeLocation == null) return null; PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); PortletPreferences preferences = portletRequestContext.getRequest().getPreferences(); String sharedCache = preferences.getValue(UISingleContentViewerPortlet.ENABLE_CACHE, "true"); sharedCache = "true".equals(sharedCache) ? WCMComposer.VISIBILITY_PUBLIC:WCMComposer.VISIBILITY_USER; Node ret = Utils.getViewableNodeByComposer(viewNodeLocation.getRepository(), viewNodeLocation.getWorkspace(), viewNodeLocation.getPath(), null, sharedCache); return ret; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#setNode(javax.jcr.Node) */ public void setNode(Node node) { viewNodeLocation = NodeLocation.getNodeLocationByNode(node); } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.UIBaseNodePresentation#getRepositoryName() */ public String getRepositoryName() { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); PortletPreferences portletPreferences = portletRequestContext.getRequest().getPreferences(); return originalNodeLocation != null ? originalNodeLocation.getRepository() : portletPreferences.getValue(UISingleContentViewerPortlet.REPOSITORY, "repository"); } /* (non-Javadoc) * @see org.exoplatform.portal.webui.portal.UIPortalComponent#getTemplate() */ public String getTemplate() { return templatePath; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.UIBaseNodePresentation#getTemplatePath() */ public String getTemplatePath() throws Exception { return templatePath; } public void setTemplatePath(String templatePath) { this.templatePath = templatePath; } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIComponent#getTemplateResourceResolver(org. * exoplatform.webui.application.WebuiRequestContext, java.lang.String) */ public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context, String template) { DMSConfiguration dmsConfiguration = getApplicationComponent(DMSConfiguration.class); String workspace = dmsConfiguration.getConfig().getSystemWorkspace(); return new JCRResourceResolver(workspace); } public ResourceResolver getTemplateResourceResolver() { DMSConfiguration dmsConfiguration = getApplicationComponent(DMSConfiguration.class); String workspace = dmsConfiguration.getConfig().getSystemWorkspace(); return new JCRResourceResolver(workspace); } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getNodeType() */ public String getNodeType() throws Exception { return null; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#isNodeTypeSupported() */ public boolean isNodeTypeSupported() { return false; } /** * Checks if allow render fast publish link for the inline editting * * @return true, if need to render fast publish link */ public boolean isFastPublishLink() { return true ; } public String getFastPublishLink() throws Exception { UIPresentationContainer container = (UIPresentationContainer)getParent(); return container.event("FastPublish"); } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getCommentComponent() */ public UIComponent getCommentComponent() { return null; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getCommentComponent() */ public UIComponent getRemoveAttach() throws Exception { removeChild(RemoveAttachmentComponent.class); UIComponent uicomponent = addChild(RemoveAttachmentComponent.class, null, "PresentationRemoveAttach"); ((AbstractActionComponent) uicomponent).setLstComponentupdate(Arrays.asList(new Class[] { UIPresentationContainer.class })); return uicomponent; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getCommentComponent() */ public UIComponent getRemoveComment() throws Exception { removeChild(RemoveCommentComponent.class); UIComponent uicomponent = addChild(RemoveCommentComponent.class, null, "PresentationRemoveComment"); ((AbstractActionComponent)uicomponent).setLstComponentupdate(Arrays.asList(new Class[] {UIPresentationContainer.class})); return uicomponent; } public UIComponent getUIComponent(String mimeType) throws Exception { return org.exoplatform.ecm.webui.utils.Utils.getUIComponent(mimeType, this); } /** * Gets the viewable link (attachment link, relation document link) * * @param node the node * @return the attachment URL * @throws Exception the exception */ public String getViewableLink(Node node, Parameter[] params) throws Exception { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); PortletRequest portletRequest = portletRequestContext.getRequest(); NodeLocation nodeLocation = NodeLocation.getNodeLocationByNode(node); String baseURI = portletRequest.getScheme() + "://" + portletRequest.getServerName() + ":" + String.format("%s", portletRequest.getServerPort()); String basePath = Utils.getPortletPreference(UISingleContentViewerPortlet.PREFERENCE_TARGET_PAGE); String scvWith = Utils.getPortletPreference(UISingleContentViewerPortlet.PREFERENCE_SHOW_SCV_WITH); if (scvWith == null || scvWith.length() == 0) scvWith = UISingleContentViewerPortlet.DEFAULT_SHOW_SCV_WITH; StringBuffer param = new StringBuffer(); param.append("/") .append(nodeLocation.getRepository()) .append("/") .append(nodeLocation.getWorkspace()); if (node.isNodeType("nt:frozenNode")) { String uuid = node.getProperty("jcr:frozenUuid").getString(); Node originalNode = node.getSession().getNodeByUUID(uuid); param.append(originalNode.getPath()); } else { param.append(node.getPath()); } NodeURL nodeURL = Util.getPortalRequestContext().createURL(NodeURL.TYPE); NavigationResource resource = new NavigationResource(SiteType.PORTAL, Util.getPortalRequestContext() .getPortalOwner(), basePath); nodeURL.setResource(resource).setQueryParameterValue(scvWith, param.toString()); String link = baseURI + nodeURL.toString(); FriendlyService friendlyService = getApplicationComponent(FriendlyService.class); link = friendlyService.getFriendlyUri(link); return link; } /** * Gets the attachment nodes. * * @return the attachment Nodes * @throws Exception the exception */ public List<Node> getAttachments() throws Exception { List<Node> attachments = new ArrayList<Node>() ; Node parent = getOriginalNode(); NodeIterator childrenIterator = parent.getNodes();; TemplateService templateService = getApplicationComponent(TemplateService.class) ; while (childrenIterator.hasNext()) { Node childNode = childrenIterator.nextNode(); String nodeType = childNode.getPrimaryNodeType().getName(); List<String> listCanCreateNodeType = org.exoplatform.ecm.webui.utils.Utils.getListAllowedFileType(parent, templateService); if (listCanCreateNodeType.contains(nodeType)) attachments.add(childNode); } return attachments; } @Override public boolean isDisplayAlternativeText() { try { Node node = this.getNode(); return ( node.isNodeType(NodetypeConstant.EXO_ACCESSIBLE_MEDIA) || (node.isNodeType(NodetypeConstant.NT_FROZEN_NODE) && NodetypeConstant.EXO_ACCESSIBLE_MEDIA.equals(node.getProperty("jcr:frozenPrimaryType").getString()))) && node.hasProperty(NodetypeConstant.EXO_ALTERNATIVE_TEXT) && StringUtils.isNotEmpty(node.getProperty(NodetypeConstant.EXO_ALTERNATIVE_TEXT).getString()); } catch (Exception e) { return false; } } @Override public boolean playAudioDescription() { try { Node node = this.getNode(); return ( node.isNodeType(NodetypeConstant.EXO_ACCESSIBLE_MEDIA) || (node.isNodeType(NodetypeConstant.NT_FROZEN_NODE) && NodetypeConstant.EXO_ACCESSIBLE_MEDIA.equals(node.getProperty("jcr:frozenPrimaryType").getString()))) && org.exoplatform.services.cms.impl.Utils.hasChild(node, NodetypeConstant.EXO_AUDIO_DESCRIPTION); } catch (Exception e) { return false; } } @Override public boolean switchBackAudioDescription() { try { Node node = this.getNode(); Node parent = node.getParent(); return node.isNodeType(NodetypeConstant.EXO_AUDIO_DESCRIPTION) && ( parent.isNodeType(NodetypeConstant.EXO_ACCESSIBLE_MEDIA) || (parent.isNodeType(NodetypeConstant.NT_FROZEN_NODE) && NodetypeConstant.EXO_ACCESSIBLE_MEDIA.equals(parent.getProperty("jcr:frozenPrimaryType").getString()))); } catch (Exception e) { return false; } } @Override public UIPopupContainer getPopupContainer() throws Exception { return this.getAncestorOfType(UIPortletApplication.class).getChild(UIPopupContainer.class); } static public class DownloadActionListener extends EventListener<UIPresentation> { public void execute(Event<UIPresentation> event) throws Exception { UIPresentation uiComp = event.getSource(); try { String downloadLink = Utils.getDownloadLink(Utils.getFileLangNode(uiComp.getNode())); RequireJS requireJS = event.getRequestContext().getJavascriptManager().getRequireJS(); requireJS.require("SHARED/ecm-utils", "ecmutil").addScripts("ecmutil.ECMUtils.ajaxRedirect('" + downloadLink + "');"); } catch(RepositoryException e) { if (LOG.isErrorEnabled()) { LOG.error("Repository cannot be found", e); } } } } static public class SwitchToAudioDescriptionActionListener extends EventListener<UIPresentation> { public void execute(Event<UIPresentation> event) throws Exception { UIPresentation uiPresentation = event.getSource(); UIPresentationContainer uiContainer = uiPresentation.getAncestorOfType(UIPresentationContainer.class); uiPresentation.switchMediaState(); event.getRequestContext().addUIComponentToUpdateByAjax(uiContainer); } } static public class SwitchToOriginalActionListener extends EventListener<UIPresentation> { public void execute(Event<UIPresentation> event) throws Exception { UIPresentation uiPresentation = event.getSource(); UIPresentationContainer uiContainer = uiPresentation.getAncestorOfType(UIPresentationContainer.class); uiPresentation.switchMediaState(); event.getRequestContext().addUIComponentToUpdateByAjax(uiContainer); } } }
17,463
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIPresentationContainer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/scv/UIPresentationContainer.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.scv; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.utils.lock.LockUtil; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.mop.SiteType; import org.exoplatform.portal.webui.application.UIPortlet; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.util.Text; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.reader.ContentReader; import org.exoplatform.web.url.navigation.NavigationResource; import org.exoplatform.web.url.navigation.NodeURL; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.lifecycle.Lifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.ValueFormatException; import javax.portlet.PortletPreferences; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.*; /** * Author : Do Ngoc Anh * * Email: anh.do@exoplatform.com * * May 14, 2008 */ @ComponentConfig( lifecycle=Lifecycle.class, template="app:/groovy/SingleContentViewer/UIPresentationContainer.gtmpl", events = { @EventConfig(listeners=UIPresentationContainer.PreferencesActionListener.class), @EventConfig(listeners=UIPresentationContainer.FastPublishActionListener.class) } ) public class UIPresentationContainer extends UIContainer{ public final static String PARAMETER_REGX = "(.*)/(.*)"; private static final Log LOG = ExoLogger.getLogger(UIPresentationContainer.class.getName()); private boolean isPrint = false; private PortletPreferences portletPreferences; private String contentParameter = null; /** * Instantiates a new uI presentation container. * * @throws Exception the exception */ public UIPresentationContainer() throws Exception{ PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); addChild(UIPresentation.class, null, UIPresentation.class.getSimpleName() + portletRequestContext.getWindowId()); portletPreferences = portletRequestContext.getRequest().getPreferences(); } /** * Gets the bar info show. * * @return the value for info bar setting * * @throws Exception the exception */ public boolean isShowInfoBar() throws Exception { if (UIPortlet.getCurrentUIPortlet().getShowInfoBar()) return true; return false; } /** * Gets the title. * * @param node the node * * @return the title * * @throws Exception the exception */ public String getTitle(Node node) throws Exception { String title = null; if (node.hasProperty("exo:title")) { title = node.getProperty("exo:title").getValue().getString().trim(); } if (title == null || title.equals("")) { if (node.hasNode("jcr:content")) { Node content = node.getNode("jcr:content"); if (content.hasProperty("dc:title")) { try { title = content.getProperty("dc:title").getValues()[0].getString().trim(); } catch (ValueFormatException e) { title = null; } catch (IllegalStateException e) { title = null; } catch (RepositoryException e) { title = null; } } } } if (title == null || title.equals("")) { title = Utils.getRealNode(node).getName(); } return ContentReader.getXSSCompatibilityContent(title); } public boolean isPrinting() { return this.isPrint; } public boolean isShowTitle() { return Boolean.parseBoolean(portletPreferences.getValue(UISingleContentViewerPortlet.SHOW_TITLE, "false")); } public boolean isShowDate() { return Boolean.parseBoolean(portletPreferences.getValue(UISingleContentViewerPortlet.SHOW_DATE, "false")); } public boolean isShowOptionBar() { return Boolean.parseBoolean(portletPreferences.getValue(UISingleContentViewerPortlet.SHOW_OPTIONBAR, "false")); } public boolean isContextual() { return Boolean.parseBoolean(portletPreferences.getValue(UISingleContentViewerPortlet.CONTEXTUAL_MODE, "false")); } public String getCurrentState() throws Exception { UIPresentation presentation = getChild(UIPresentation.class); Node node = presentation.getOriginalNode(); PublicationService publicationService = WCMCoreUtils.getService(PublicationService.class); if(node == null || !publicationService.isNodeEnrolledInLifecycle(node)) return StringUtils.EMPTY; return publicationService.getCurrentState(node); } /** * Gets the created date. * * @param node the node * * @return the created date * * @throws Exception the exception */ public String getCreatedDate(Node node) throws Exception { if (node.hasProperty("exo:dateCreated")) { Calendar calendar = node.getProperty("exo:dateCreated").getValue().getDate(); return new SimpleDateFormat("dd.MM.yyyy '|' hh'h'mm").format(calendar.getTime()); } return null; } /** * Gets the node. * * @return the node */ public Node getNodeView() { UIPresentation presentation = getChild(UIPresentation.class); try { Node viewNode; //Check for the saved parameter viewNode = getParameterizedNode(); if (viewNode!= null) { if (viewNode.isNodeType("nt:frozenNode")) { try { String nodeUUID = viewNode.getProperty("jcr:frozenUuid").getString(); presentation.setOriginalNode(viewNode.getSession().getNodeByUUID(nodeUUID)); presentation.setNode(viewNode); } catch (Exception ex) { return viewNode; } } return viewNode; } PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); portletPreferences = portletRequestContext.getRequest().getPreferences(); String repository = portletPreferences.getValue(UISingleContentViewerPortlet.REPOSITORY, null); String workspace = portletPreferences.getValue(UISingleContentViewerPortlet.WORKSPACE, null); String nodeIdentifier = portletPreferences.getValue(UISingleContentViewerPortlet.IDENTIFIER, null); String sharedCache = portletPreferences.getValue(UISingleContentViewerPortlet.ENABLE_CACHE, "true"); sharedCache = "true".equals(sharedCache) ? WCMComposer.VISIBILITY_PUBLIC:WCMComposer.VISIBILITY_USER; viewNode = Utils.getRealNode(repository, workspace, nodeIdentifier, false, sharedCache); if (viewNode!=null) { boolean isDocumentType = false; if (viewNode.isNodeType("nt:frozenNode")) isDocumentType = true; // check node is a document node TemplateService templateService = getApplicationComponent(TemplateService.class); List<String> documentTypes = templateService.getDocumentTemplates(); for (String documentType : documentTypes) { if (viewNode.isNodeType(documentType)) { isDocumentType = true; break; } } if (!isDocumentType) return null; if (viewNode != null && viewNode.isNodeType("nt:frozenNode")) { String nodeUUID = viewNode.getProperty("jcr:frozenUuid").getString(); presentation.setOriginalNode(viewNode.getSession().getNodeByUUID(nodeUUID)); presentation.setNode(viewNode); } else { presentation.setOriginalNode(viewNode); presentation.setNode(viewNode); } } return viewNode; } catch (Exception e) { return null; } } /** * Gets the node. * * @return the node * * @throws Exception the exception */ public Node getParameterizedNode() throws Exception { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); PortletPreferences preferences = portletRequestContext.getRequest().getPreferences(); String sharedCache = preferences.getValue(UISingleContentViewerPortlet.ENABLE_CACHE, "false"); sharedCache = "true".equals(sharedCache) ? WCMComposer.VISIBILITY_PUBLIC:WCMComposer.VISIBILITY_USER; PortalRequestContext preq = Util.getPortalRequestContext(); if (!preq.useAjax()) { contentParameter = getRequestParameters(); } if (contentParameter == null) return null; UIPresentation presentation = getChild(UIPresentation.class); Node nodeView = Utils.getViewableNodeByComposer(null, null, contentParameter, null, sharedCache); if (nodeView!=null) { boolean isDocumentType = false; if (nodeView.isNodeType("nt:frozenNode")) isDocumentType = true; // check node is a document node if (!isDocumentType) { TemplateService templateService = getApplicationComponent(TemplateService.class); List<String> documentTypes = templateService.getDocumentTemplates(); for (String documentType : documentTypes) { if (nodeView.isNodeType(documentType)) { isDocumentType = true; break; } } } if (!isDocumentType) return null; if (nodeView != null && nodeView.isNodeType("nt:frozenNode")) { String nodeUUID = nodeView.getProperty("jcr:frozenUuid").getString(); presentation.setOriginalNode(nodeView.getSession().getNodeByUUID(nodeUUID)); presentation.setNode(nodeView); } else { presentation.setOriginalNode(nodeView); presentation.setNode(nodeView); } isPrint = Boolean.parseBoolean(Util.getPortalRequestContext().getRequestParameter("isPrint")); } return nodeView; } /** * Gets the request parameters. * * @return the request parameters */ private String getRequestParameters() throws Exception { String parameters = null; if (!Boolean.parseBoolean(portletPreferences.getValue(UISingleContentViewerPortlet.CONTEXTUAL_MODE, "false"))) { return null; } try { parameters = URLDecoder.decode(StringUtils.substringAfter(Util.getPortalRequestContext() .getNodePath(), Util.getUIPortal() .getSelectedUserNode() .getURI() + "/"), "UTF-8"); } catch (UnsupportedEncodingException e) { return null; } String parameterName = portletPreferences.getValue(UISingleContentViewerPortlet.PARAMETER, ""); if (!parameters.matches(PARAMETER_REGX)) { String path = Util.getPortalRequestContext().getRequestParameter(parameterName); if (path == null){ return null; } parameters = Text.unescape(Util.getPortalRequestContext().getRequestParameter(parameterName)); return parameters.substring(1); } return Text.unescape(parameters); } /** * Get the print's page URL * * @return <code>true</code> if the Quick Print is shown. Otherwise, <code>false</code> */ public String getPrintUrl(Node node) throws RepositoryException{ String printParameterName; Node tempNode = node; if (tempNode==null) { tempNode = getNodeView(); } String strPath = tempNode.getPath(); String repository = ((ManageableRepository)tempNode.getSession().getRepository()).getConfiguration().getName(); String workspace = tempNode.getSession().getWorkspace().getName(); String printPageUrl = portletPreferences.getValue(UISingleContentViewerPortlet.PRINT_PAGE, ""); printParameterName = portletPreferences.getValue(UISingleContentViewerPortlet.PRINT_PARAMETER, ""); String paramName = "/" + repository + "/" + workspace + strPath; NodeURL nodeURL = Util.getPortalRequestContext().createURL(NodeURL.TYPE); NavigationResource resource = new NavigationResource(SiteType.PORTAL, Util.getPortalRequestContext() .getPortalOwner(), printPageUrl); nodeURL.setResource(resource); nodeURL.setQueryParameterValue(printParameterName, paramName); nodeURL.setQueryParameterValue("isPrint", "true"); nodeURL.setQueryParameterValue("noadminbar", "true"); return nodeURL.toString(); } /** * Get the quick edit url * * @param node * @return */ public String getQuickEditLink(Node node){ Node tempNode = node; if (tempNode==null) { tempNode = getNodeView(); } return Utils.getEditLink(tempNode, true, false); } public Node getOriginalNode() { UIPresentation presentation = getChild(UIPresentation.class); if (presentation == null) return null; try { return presentation.getOriginalNode(); } catch (Exception e) { return null; } } public boolean isViewMode() { return Utils.getCurrentMode().equals(WCMComposer.MODE_LIVE); } public String getInlineEditingMsg() { StringBuffer sb = new StringBuffer(); sb.append("new Array("); sb.append("'") .append(Text.escapeIllegalJcrChars(getResourceBundle("UIPresentationContainer.msg.internal-server-error"))) .append("', '") .append(Text.escapeIllegalJcrChars(getResourceBundle("UIPresentationContainer.msg.empty-title-error"))) .append("')"); return sb.toString(); } private String getResourceBundle(String key) { try { ResourceBundle rs = WebuiRequestContext.getCurrentInstance().getApplicationResourceBundle(); return rs.getString(key); } catch(MissingResourceException e) { return key; } } /** * The listener interface for receiving preferencesAction events. * The class that is interested in processing a preferencesAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addPreferencesActionListener</code> method. When * the preferencesAction event occurs, that object's appropriate * method is invoked. */ public static class PreferencesActionListener extends EventListener<UIPresentationContainer>{ /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIPresentationContainer> event) throws Exception { UIPresentationContainer presentationContainer = event.getSource(); UISCVPreferences pcvConfigForm = presentationContainer.createUIComponent(UISCVPreferences.class, null, null); Utils.createPopupWindow(presentationContainer, pcvConfigForm, UISingleContentViewerPortlet.UIPreferencesPopupID, 600); } } public static class FastPublishActionListener extends EventListener<UIPresentationContainer> { /* * (non-Javadoc) * @see * org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui * .event.Event) */ public void execute(Event<UIPresentationContainer> event) throws Exception { UIPresentationContainer uiContainer = event.getSource(); PublicationService publicationService = WCMCoreUtils.getService(PublicationService.class); Node node = uiContainer.getNodeView(); if (node.isLocked()) { node.getSession().addLockToken(LockUtil.getLockToken(node)); } HashMap<String, String> context = new HashMap<String, String>(); publicationService.changeState(node, "published", context); event.getRequestContext().getJavascriptManager().getRequireJS().addScripts("location.reload(true);"); } } public String getInlineEditingField(Node orgNode, String propertyName, String defaultValue, String inputType, String idGenerator, String cssClass, boolean isGenericProperty, String... arguments) throws Exception { return org.exoplatform.ecm.webui.utils.Utils.getInlineEditingField(orgNode, propertyName, defaultValue, inputType, idGenerator, cssClass, isGenericProperty, arguments); } public String getInlineEditingField(Node orgNode, String propertyName) throws Exception{ return org.exoplatform.ecm.webui.utils.Utils.getInlineEditingField(orgNode, propertyName); } }
18,276
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISingleContentViewerPortlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/scv/UISingleContentViewerPortlet.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.scv; import java.util.Collection; import java.util.Date; import javax.jcr.Node; import javax.portlet.MimeResponse; import javax.portlet.PortletMode; import javax.portlet.PortletPreferences; import javax.portlet.RenderResponse; import javax.portlet.ResourceRequest; import javax.portlet.ResourceURL; import org.exoplatform.portal.mop.navigation.Scope; import org.exoplatform.portal.mop.Visibility; import org.exoplatform.portal.mop.user.UserNavigation; import org.exoplatform.portal.mop.user.UserNode; import org.exoplatform.portal.mop.user.UserNodeFilterConfig; import org.exoplatform.portal.mop.user.UserPortal; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.security.ConversationRegistry; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.wcm.core.WCMService; import org.exoplatform.portal.webui.util.NavigationUtils; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.web.application.RequireJS; import org.exoplatform.webui.application.WebuiApplication; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.UIPortletApplication; import org.exoplatform.webui.core.lifecycle.UIApplicationLifecycle; import org.gatein.portal.controller.resource.ResourceScope; import org.json.JSONArray; import org.json.JSONObject; import org.w3c.dom.Element; /** * Created by The eXo Platform SAS * Author : DANG TAN DUNG * dzungdev@gmail.com * Jun 9, 2008 */ @ComponentConfig( lifecycle = UIApplicationLifecycle.class, template = "system:/groovy/SingleContentViewer/UISingleContentView.gtmpl" ) public class UISingleContentViewerPortlet extends UIPortletApplication { /** The REPOSITORY. */ public static String REPOSITORY = "repository" ; /** The WORKSPACE. */ public static String WORKSPACE = "workspace" ; /** The IDENTIFIER. */ public static String IDENTIFIER = "nodeIdentifier" ; /** The DRIVE. */ public static String DRIVE = "nodeDrive"; /** The Parameterized String **/ public static String PARAMETER = "ParameterName"; /** The ShowDate **/ public static String SHOW_DATE = "ShowDate"; /** The ShowTitle **/ public static String SHOW_TITLE = "ShowTitle"; /** The ShowOptionBar **/ public static String SHOW_OPTIONBAR = "ShowOptionBar"; /** The is ContextualMode **/ public static String CONTEXTUAL_MODE= "ContextEnable"; /** The Parameterized String for printing**/ public static String PRINT_PARAMETER= "PrintParameterName"; /** The Page that show the print viewer **/ public static String PRINT_PAGE = "PrintPage"; /** The mode_. */ /** The Constant PREFERENCE_TARGET_PAGE. */ public final static String PREFERENCE_TARGET_PAGE = "basePath"; /** The Constant PREFERENCE_SHOW_SCL_WITH. */ public final static String PREFERENCE_SHOW_SCV_WITH = "showScvWith"; public static final String DEFAULT_SHOW_SCV_WITH = "content-id"; /** The Cache */ public static final String ENABLE_CACHE = "sharedCache"; public static final String NAVIGATION_SCOPE = "NavigationScope"; public static final String NAVIGATION_SCOPE_SINGLE = "single"; public static final String NAVIGATION_SCOPE_CHILDREN = "children"; public static final String NAVIGATION_SCOPE_GRAND_CHILDREN = "grandChildren"; public static final String NAVIGATION_SCOPE_ALL = "all"; private PortletMode mode = null;//PortletMode.VIEW ; public static final String UIPreferencesPopupID = "UIPreferencesPopupWindows"; private UISCVPreferences popPreferences; private UIPresentationContainer uiPresentation; PortletPreferences preferences; /** * Instantiates a new uI single content viewer portlet. * * @throws Exception the exception */ public UISingleContentViewerPortlet() throws Exception { addChild(UIPopupContainer.class, null, "UIPopupContainer-" + new Date().getTime()); PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); preferences = portletRequestContext.getRequest().getPreferences(); } /** * Activate mode. * * @param newMode the mode * * @throws Exception the exception */ public void activateMode(PortletMode newMode) throws Exception{ if (getChild(UIPresentationContainer.class) !=null) { removeChild(UIPresentationContainer.class); } if (getChild(UISCVPreferences.class) != null) { removeChild(UISCVPreferences.class); } if(PortletMode.VIEW.equals(newMode)) { PortletRequestContext pContext = (PortletRequestContext) WebuiRequestContext.getCurrentInstance(); uiPresentation = addChild(UIPresentationContainer.class, null, UIPresentationContainer.class.getSimpleName() + pContext.getWindowId()); } else if (PortletMode.EDIT.equals(newMode)) { popPreferences = addChild(UISCVPreferences.class, null, null); popPreferences.setInternalPreferencesMode(true); } } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIPortletApplication#processRender(org.exoplatform * .webui.application.WebuiApplication, * org.exoplatform.webui.application.WebuiRequestContext) */ public void processRender(WebuiApplication app, WebuiRequestContext context) throws Exception { PortletRequestContext pContext = (PortletRequestContext) context ; PortletMode newMode = pContext.getApplicationMode() ; PortletPreferences preferences = pContext.getRequest().getPreferences(); Boolean sharedCache = "true".equals(preferences.getValue(ENABLE_CACHE, "true")); if ((context.getRemoteUser() == null && !Boolean.parseBoolean(preferences.getValue(UISingleContentViewerPortlet.CONTEXTUAL_MODE, "false"))) || (Utils.isLiveMode() && sharedCache && !Utils.isPortalEditMode() && Utils.isPortletViewMode(pContext))) { WCMService wcmService = getApplicationComponent(WCMService.class); pContext.getResponse().setProperty(MimeResponse.EXPIRATION_CACHE, ""+wcmService.getPortletExpirationCache()); if (log.isTraceEnabled()) log.trace("SCV rendering : cache set to "+wcmService.getPortletExpirationCache()); } if(!newMode.equals(mode)) { activateMode(newMode) ; mode = newMode ; } Node nodeView = null; if (uiPresentation!=null) { nodeView = uiPresentation.getNodeView(); if (nodeView != null) { TemplateService templateService = getApplicationComponent(TemplateService.class); uiPresentation.getChild(UIPresentation.class).setTemplatePath(templateService.getTemplatePath(nodeView, false)); } } // if (uiPresentation!=null && uiPresentation.isContextual() && nodeView!=null) { // RenderResponse response = context.getResponse(); // Element title = response.createElement("title"); // title.setTextContent(uiPresentation.getTitle(nodeView)); // response.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT, title); // } if (context.getRemoteUser() != null && WCMComposer.MODE_EDIT.equals(Utils.getCurrentMode())) { pContext.getJavascriptManager().loadScriptResource(ResourceScope.SHARED, "content-selector"); pContext.getJavascriptManager().loadScriptResource(ResourceScope.SHARED, "quick-edit"); } setId(UISingleContentViewerPortlet.class.getSimpleName() + pContext.getWindowId()); super.processRender(app, context) ; } public void changeToViewMode() throws Exception{ PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); portletRequestContext.setApplicationMode(PortletMode.VIEW); } @Override public void serveResource(WebuiRequestContext context) throws Exception { super.serveResource(context); ResourceRequest req = context.getRequest(); String nodeURI = req.getResourceID(); JSONArray jsChilds = getChildrenAsJSON(nodeURI); if (jsChilds == null) { return; } MimeResponse res = context.getResponse(); res.setContentType("text/json"); res.getWriter().write(jsChilds.toString()); } public JSONArray getChildrenAsJSON(String nodeURI) throws Exception { WebuiRequestContext context = WebuiRequestContext.getCurrentInstance(); Collection<UserNode> children = null; UserPortal userPortal = Util.getPortalRequestContext().getUserPortalConfig().getUserPortal(); // make filter UserNodeFilterConfig.Builder filterConfigBuilder = UserNodeFilterConfig.builder(); filterConfigBuilder.withReadWriteCheck().withVisibility(Visibility.DISPLAYED, Visibility.TEMPORAL); filterConfigBuilder.withTemporalCheck(); UserNodeFilterConfig filterConfig = filterConfigBuilder.build(); // get user node & update children UserNavigation userNav = userPortal.getNavigation(Util.getUIPortal().getSiteKey()); UserNode userNode = userPortal.resolvePath(userNav, filterConfig, nodeURI); if (userNode != null) { userPortal.updateNode(userNode, NavigationUtils.ECMS_NAVIGATION_SCOPE, null); children = userNode.getChildren(); } // build JSON result JSONArray jsChildren = new JSONArray(); if (children == null) { return null; } MimeResponse res = context.getResponse(); for (UserNode child : children) { jsChildren.put(toJSON(child, res)); } return jsChildren; } private JSONObject toJSON(UserNode node, MimeResponse res) throws Exception { JSONObject json = new JSONObject(); String nodeId = node.getId(); json.put("label", node.getEncodedResolvedLabel()); json.put("hasChild", node.getChildrenCount() > 0); UserNode selectedNode = Util.getUIPortal().getNavPath(); json.put("isSelected", nodeId.equals(selectedNode.getId())); json.put("icon", node.getIcon()); String nodeURI = ""; if(node.getPageRef() != null){ nodeURI = node.getURI(); } json.put("uri", nodeURI); ResourceURL rsURL = res.createResourceURL(); rsURL.setResourceID(res.encodeURL(node.getURI())); json.put("getNodeURL", rsURL.toString()); JSONArray jsonChildren = new JSONArray(); for (UserNode child : node.getChildren()) { jsonChildren.put(toJSON(child, res)); } json.put("childs", jsonChildren); return json; } public String getNavigationScope() throws Exception { PortletPreferences preferences = ((PortletRequestContext)WebuiRequestContext.getCurrentInstance()). getRequest().getPreferences(); String navigationScope = preferences.getValue(NAVIGATION_SCOPE, NAVIGATION_SCOPE_CHILDREN); return navigationScope; } public String getNavigation() throws Exception { String userName = ConversationState.getCurrent().getIdentity().getUserId(); String portalName = Util.getPortalRequestContext().getPortalOwner(); PortletPreferences preferences = ((PortletRequestContext)WebuiRequestContext.getCurrentInstance()). getRequest().getPreferences(); String navigationScope = preferences.getValue(NAVIGATION_SCOPE, NAVIGATION_SCOPE_CHILDREN); Scope scope = Scope.CHILDREN; switch (navigationScope) { case NAVIGATION_SCOPE_SINGLE: scope = Scope.SINGLE; break; case NAVIGATION_SCOPE_CHILDREN: scope = Scope.CHILDREN; break; case NAVIGATION_SCOPE_GRAND_CHILDREN: scope = Scope.GRANDCHILDREN; break; case NAVIGATION_SCOPE_ALL: scope = Scope.ALL; break; } return NavigationUtils.getNavigationAsJSON(portalName, userName, scope, navigationScope); } }
12,943
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISCVPreferences.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/scv/UISCVPreferences.java
/*************************************************************************** * Copyright 2001-2010 The eXo Platform SARL All rights reserved. * * Please look at license.txt in info directory for more license detail. * **************************************************************************/ package org.exoplatform.wcm.webui.scv; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.reader.ContentReader; import org.exoplatform.wcm.webui.selector.content.UIContentSelector; import org.exoplatform.wcm.webui.selector.content.one.UIContentBrowsePanelOne; import org.exoplatform.wcm.webui.selector.content.one.UIContentSelectorOne; import org.exoplatform.wcm.webui.selector.page.UIPageSelector; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.Event.Phase; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIFormInputSet; import org.exoplatform.webui.form.UIFormRadioBoxInput; import org.exoplatform.webui.form.UIFormStringInput; import org.exoplatform.webui.form.UIFormTabPane; import org.exoplatform.webui.form.ext.UIFormInputSetWithAction; import org.exoplatform.webui.form.input.UICheckBoxInput; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.portlet.PortletPreferences; import java.util.ArrayList; import java.util.List; /** * Created by The eXo Platform SARL * Author : Nguyen The Vinh * vinh.nguyen@exoplatform.com * Jul 16, 2010 */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "app:/groovy/SingleContentViewer/UISCVPreferences.gtmpl", events = { @EventConfig(listeners = UISCVPreferences.SaveActionListener.class), @EventConfig(listeners = UISCVPreferences.AddPathActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UISCVPreferences.CancelActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UISCVPreferences.SelectTabActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UISCVPreferences.SelectTargetPageActionListener.class, phase = Phase.DECODE) } ) public class UISCVPreferences extends UIFormTabPane implements UISelectable{ /** The Constant ITEM_PATH_FORM_INPUT_SET. */ public final static String ITEM_PATH_FORM_INPUT_SET = "UISCVConfigItemPathFormInputSet"; public final static String CONTENT_FORM_INPUT_SET = "UISCVConfigContentFormInputSet"; public final static String DISPLAY_FORM_INPUT_SET = "UISCVConfigDisplayFormInputSet"; public final static String PRINT_FORM_INPUT_SET = "UISCVConfigPrintFormInputSet"; public final static String ADVANCED_FORM_INPUT_SET = "UISCVConfigAdvancedFormInputSet"; public static final String CONTENT_PATH_INPUT = "UISCVContentPathConfigurationInputBox"; public static final String SHOW_TITLE_CHECK_BOX = "UISCVShowTitleConfigurationCheckBox"; public static final String SHOW_DATE_CHECK_BOX = "UISCVShowDateConfigurationCheckBox"; public static final String SHOW_OPION_BAR_CHECK_BOX = "UISCVShowOptionBarConfigurationCheckBox"; public static final String CONTEXTUAL_SELECT_RADIO_BOX = "UISCVContextualRadioBox"; public static final String PARAMETER_INPUT_BOX = "UISCVParameterInputBox"; public static final String CACHE_ENABLE_SELECT_RADIO_BOX = "UISCVCacheRadioBox"; public final static String PRINT_PAGE_FORM_INPUT_SET = "UISCVConfigPrintPageFormInputSet"; public static final String PRINT_VIEW_PAGE_INPUT = "UISCVPrintViewPageInput"; /** The Constant PRINT_PAGE_SELECTOR_POPUP. */ public final static String PRINT_PAGE_SELECTOR_POPUP = "UISCVConfigPrintPageSelectorPopupWindow"; public static final String PRINT_PAGE_PARAMETER_INPUT = "UISCVPrintPageParameter"; public static final String ENABLE_STRING = "Enable"; public static final String DISABLE_STRING = "Disable"; protected PortletPreferences portletPreferences; protected String contentSelectorID; protected String selectedNodeUUID =null; protected String selectedNodeReporitory =null; protected String selectedNodeWorkspace =null; protected String selectedNodeDrive = null; protected String selectedNodePath = null; private UIFormStringInput txtContentPath, txtPrintPage, txtPrintPageParameter; private UICheckBoxInput chkShowTitle; private UICheckBoxInput chkShowDate; private UICheckBoxInput chkShowOptionBar; private UIFormRadioBoxInput contextOptionsRadioInputBox; private UIFormRadioBoxInput cacheOptionsRadioInputBox; public UISCVPreferences() throws Exception{ super("UISCVPreferences"); portletPreferences = ((PortletRequestContext) WebuiRequestContext.getCurrentInstance()).getRequest().getPreferences(); initComponent(); setActions(new String[] { "Save", "Cancel" }); } /** * Initialize the preferences setting form * * @throws Exception */ public void initComponent() throws Exception{ /** Content name **/ String strNodeName = getNodeNameByPreferences(); txtContentPath = new UIFormStringInput(CONTENT_PATH_INPUT, CONTENT_PATH_INPUT, strNodeName); txtContentPath.setReadOnly(true); UIFormInputSetWithAction itemPathInputSet = new UIFormInputSetWithAction(ITEM_PATH_FORM_INPUT_SET); itemPathInputSet.setActionInfo(CONTENT_PATH_INPUT, new String[] { "AddPath" }) ; itemPathInputSet.addUIFormInput(txtContentPath); UIFormInputSetWithAction contentInputSet = new UIFormInputSetWithAction(CONTENT_FORM_INPUT_SET); contentInputSet.addUIFormInput((UIFormInputSet)itemPathInputSet); setSelectedTab(CONTENT_FORM_INPUT_SET); /** Option Show Title/Show Date/Show OptionBar **/ boolean blnShowTitle = Boolean.parseBoolean(portletPreferences.getValue(UISingleContentViewerPortlet.SHOW_TITLE, null)); chkShowTitle = new UICheckBoxInput(SHOW_TITLE_CHECK_BOX, SHOW_TITLE_CHECK_BOX, null); chkShowTitle.setChecked(blnShowTitle); boolean blnShowDate = Boolean.parseBoolean(portletPreferences.getValue(UISingleContentViewerPortlet.SHOW_DATE, null)); chkShowDate = new UICheckBoxInput(SHOW_DATE_CHECK_BOX, SHOW_DATE_CHECK_BOX, null); chkShowDate.setChecked(blnShowDate); boolean blnShowOptionBar = Boolean.parseBoolean(portletPreferences.getValue(UISingleContentViewerPortlet.SHOW_OPTIONBAR, null)); chkShowOptionBar = new UICheckBoxInput(SHOW_OPION_BAR_CHECK_BOX, SHOW_OPION_BAR_CHECK_BOX, null); chkShowOptionBar.setChecked(blnShowOptionBar); UIFormInputSetWithAction displayInputSet = new UIFormInputSetWithAction(DISPLAY_FORM_INPUT_SET); displayInputSet.addChild(chkShowTitle); displayInputSet.addChild(chkShowDate); displayInputSet.addChild(chkShowOptionBar); /** CONTEXTUAL MODE */ boolean isShowContextOption = Boolean.parseBoolean(portletPreferences.getValue(UISingleContentViewerPortlet.CONTEXTUAL_MODE, "false")); List<SelectItemOption<String>> contextOptions = new ArrayList<SelectItemOption<String>>(); contextOptions.add(new SelectItemOption<String>(ENABLE_STRING, ENABLE_STRING)); contextOptions.add(new SelectItemOption<String>(DISABLE_STRING, DISABLE_STRING)); contextOptionsRadioInputBox = new UIFormRadioBoxInput(CONTEXTUAL_SELECT_RADIO_BOX, CONTEXTUAL_SELECT_RADIO_BOX, contextOptions); contextOptionsRadioInputBox.setValue(isShowContextOption?ENABLE_STRING:DISABLE_STRING); String strParameterName = portletPreferences.getValue(UISingleContentViewerPortlet.PARAMETER, null); UIFormStringInput txtParameterName = new UIFormStringInput(PARAMETER_INPUT_BOX, strParameterName); /** CACHE MANAGEMENT */ boolean isCacheEnabled = Boolean.parseBoolean(portletPreferences.getValue(UISingleContentViewerPortlet.ENABLE_CACHE, "false")); List<SelectItemOption<String>> cacheOptions = new ArrayList<SelectItemOption<String>>(); cacheOptions.add(new SelectItemOption<String>(ENABLE_STRING, ENABLE_STRING)); cacheOptions.add(new SelectItemOption<String>(DISABLE_STRING, DISABLE_STRING)); cacheOptionsRadioInputBox = new UIFormRadioBoxInput(CACHE_ENABLE_SELECT_RADIO_BOX, CACHE_ENABLE_SELECT_RADIO_BOX, cacheOptions); cacheOptionsRadioInputBox.setValue(isCacheEnabled ? ENABLE_STRING : DISABLE_STRING); UIFormInputSetWithAction advancedInputSet = new UIFormInputSetWithAction(ADVANCED_FORM_INPUT_SET); advancedInputSet.addChild(cacheOptionsRadioInputBox); advancedInputSet.addChild(txtParameterName); advancedInputSet.addChild(contextOptionsRadioInputBox); /** PRINT PAGE */ String strPrintParameterName = portletPreferences.getValue(UISingleContentViewerPortlet.PRINT_PARAMETER, null); txtPrintPageParameter = new UIFormStringInput(PRINT_PAGE_PARAMETER_INPUT, strPrintParameterName); /** TARGET PAGE */ String strPrintPageName = portletPreferences.getValue(UISingleContentViewerPortlet.PRINT_PAGE, null); UIFormInputSetWithAction targetPageInputSet = new UIFormInputSetWithAction(PRINT_PAGE_FORM_INPUT_SET); txtPrintPage = new UIFormStringInput(PRINT_VIEW_PAGE_INPUT, PRINT_VIEW_PAGE_INPUT, strPrintPageName); txtPrintPage.setValue(strPrintPageName); txtPrintPage.setReadOnly(true); targetPageInputSet.setActionInfo(PRINT_VIEW_PAGE_INPUT, new String[] {"SelectTargetPage"}) ; targetPageInputSet.addUIFormInput(txtPrintPage); UIFormInputSetWithAction printInputSet = new UIFormInputSetWithAction(PRINT_FORM_INPUT_SET); printInputSet.addChild(txtPrintPageParameter); printInputSet.addChild(targetPageInputSet); addChild(contentInputSet); addChild(displayInputSet); addChild(printInputSet); addChild(advancedInputSet); } /** * ActionListener: save preferences action * @author exo.VinhNT * */ public static class SaveActionListener extends EventListener<UISCVPreferences> { public void execute(Event<UISCVPreferences> event) throws Exception { WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); UISCVPreferences uiSCVPref = event.getSource(); PortletPreferences portletPreferences = ((PortletRequestContext) event.getRequestContext()).getRequest() .getPreferences(); UIFormInputSetWithAction displayInputSet = uiSCVPref.findComponentById(DISPLAY_FORM_INPUT_SET); String strShowTitle = displayInputSet.getUICheckBoxInput(SHOW_TITLE_CHECK_BOX).isChecked() ? "true" : "false"; String strShowDate = displayInputSet.getUICheckBoxInput(SHOW_DATE_CHECK_BOX).isChecked() ? "true" : "false"; String strShowOptionBar = displayInputSet.getUICheckBoxInput(SHOW_OPION_BAR_CHECK_BOX) .isChecked() ? "true" : "false"; String strIsContextEnable = ((UIFormRadioBoxInput) uiSCVPref.findComponentById(CONTEXTUAL_SELECT_RADIO_BOX)).getValue(); UIFormInputSetWithAction advancedInputSet = uiSCVPref.findComponentById(ADVANCED_FORM_INPUT_SET); strIsContextEnable = strIsContextEnable.equals(ENABLE_STRING) ? "true":"false"; String strParameterName = advancedInputSet.getUIStringInput(PARAMETER_INPUT_BOX).getValue(); String strIsCacheEnabled = ((UIFormRadioBoxInput) advancedInputSet.getChildById(CACHE_ENABLE_SELECT_RADIO_BOX)).getValue(); strIsCacheEnabled = ENABLE_STRING.equals(strIsCacheEnabled) ? "true" : "false"; UIFormInputSetWithAction printInputSet = uiSCVPref.findComponentById(PRINT_FORM_INPUT_SET); String strPrintPageName = printInputSet.getUIStringInput(PRINT_VIEW_PAGE_INPUT).getValue(); String strPrintParameterName = printInputSet.getUIStringInput(PRINT_PAGE_PARAMETER_INPUT).getValue(); if (!Boolean.parseBoolean(strIsContextEnable)) { if (uiSCVPref.getSelectedNodeUUID() != null) { if (uiSCVPref.getSelectedNodeUUID().length() == 0) { Utils.createPopupMessage(uiSCVPref, "UISCVPreferences.msg.not-valid-path", null, ApplicationMessage.WARNING); requestContext.addUIComponentToUpdateByAjax(uiSCVPref); return; } } else { Utils.createPopupMessage(uiSCVPref, "UISCVPreferences.msg.not-valid-path", null, ApplicationMessage.WARNING); requestContext.addUIComponentToUpdateByAjax(uiSCVPref); return; } } portletPreferences.setValue(UISingleContentViewerPortlet.REPOSITORY, uiSCVPref.getSelectedNodeRepository()); portletPreferences.setValue(UISingleContentViewerPortlet.WORKSPACE, uiSCVPref.getSelectedNodeWorkspace()); portletPreferences.setValue(UISingleContentViewerPortlet.IDENTIFIER, uiSCVPref.getSelectedNodeUUID()) ; portletPreferences.setValue(UISingleContentViewerPortlet.DRIVE, uiSCVPref.getSelectedNodeDrive()); portletPreferences.setValue(UISingleContentViewerPortlet.SHOW_TITLE, strShowTitle); portletPreferences.setValue(UISingleContentViewerPortlet.SHOW_DATE, strShowDate); portletPreferences.setValue(UISingleContentViewerPortlet.SHOW_OPTIONBAR, strShowOptionBar); portletPreferences.setValue(UISingleContentViewerPortlet.CONTEXTUAL_MODE, strIsContextEnable); portletPreferences.setValue(UISingleContentViewerPortlet.PARAMETER, strParameterName); portletPreferences.setValue(UISingleContentViewerPortlet.PRINT_PAGE, strPrintPageName); portletPreferences.setValue(UISingleContentViewerPortlet.PRINT_PARAMETER, strPrintParameterName); portletPreferences.setValue(UISingleContentViewerPortlet.ENABLE_CACHE, strIsCacheEnabled); portletPreferences.store(); if (uiSCVPref.getInternalPreferencesMode()) { if (!Utils.isPortalEditMode()) { uiSCVPref.getAncestorOfType(UISingleContentViewerPortlet.class).changeToViewMode(); } } else { Utils.closePopupWindow(uiSCVPref, UISingleContentViewerPortlet.UIPreferencesPopupID); } } } public static class CancelActionListener extends EventListener<UISCVPreferences> { public void execute(Event<UISCVPreferences> event) throws Exception { UISCVPreferences uiSCVPref = event.getSource(); if (uiSCVPref.getInternalPreferencesMode()) { if (!Utils.isPortalEditMode()) { uiSCVPref.getAncestorOfType(UISingleContentViewerPortlet.class).changeToViewMode(); } } else { Utils.closePopupWindow(uiSCVPref, UISingleContentViewerPortlet.UIPreferencesPopupID); } } } /** * setSelectedNodeInfo: Save temporary data when user select a node from ContentSelector * @param nodeUUID * @param nodeRepo * @param nodeWS */ public void setSelectedNodeInfo(String nodeUUID, String nodeRepo, String nodeWS, String nodeDrive) { this.selectedNodeUUID = nodeUUID; this.selectedNodeReporitory = nodeRepo; this.selectedNodeWorkspace = nodeWS; this.selectedNodeDrive = nodeDrive; } public void setSelectedNodePath(String path) { this.selectedNodePath = path; } public String getSelectedNodePath() { return this.selectedNodePath; } /** * Get the temporary node UUID * @return */ public String getSelectedNodeUUID() { return this.selectedNodeUUID; } /** * Get the temporary Node Repository string * @return */ public String getSelectedNodeRepository() { return this.selectedNodeReporitory; } /** * Get the temporary node Workspace string * @return */ public String getSelectedNodeWorkspace() { return this.selectedNodeWorkspace; } /** * Get the temporary node Drive string * @return */ public String getSelectedNodeDrive() { return this.selectedNodeDrive; } /** * The listener interface for receiving selectTabAction events. * The class that is interested in processing a selectTabAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSelectTabActionListener</code> method. When * the selectTabAction event occurs, that object's appropriate * method is invoked. */ static public class SelectTabActionListener extends EventListener<UISCVPreferences> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UISCVPreferences> event) throws Exception { WebuiRequestContext context = event.getRequestContext(); String renderTab = context.getRequestParameter(UIComponent.OBJECTID); if (renderTab == null) { return; } event.getSource().setSelectedTab(renderTab); event.getRequestContext().addUIComponentToUpdateByAjax(event.getSource()); } } public static class AddPathActionListener extends EventListener<UISCVPreferences> { public void execute(Event<UISCVPreferences> event) throws Exception { UISCVPreferences uiSCVPref = event.getSource(); UIContentSelectorOne contentSelector = uiSCVPref.createUIComponent(UIContentSelectorOne.class, null, null); Node node = Utils.getViewableNodeByComposer(uiSCVPref.getSelectedNodeRepository(), uiSCVPref.getSelectedNodeWorkspace(), uiSCVPref.getSelectedNodeUUID()); contentSelector.init(uiSCVPref.getSelectedNodeDrive(), fixPath(node == null ? "" : node.getPath(), uiSCVPref)); contentSelector.getChild(UIContentBrowsePanelOne.class) .setSourceComponent(uiSCVPref, new String[] { UISCVPreferences.CONTENT_PATH_INPUT }); Utils.createPopupWindow(uiSCVPref, contentSelector, UIContentSelector.CORRECT_CONTENT_SELECTOR_POPUP_WINDOW, 800); uiSCVPref.setContentSelectorID(UIContentSelector.CORRECT_CONTENT_SELECTOR_POPUP_WINDOW); } private String fixPath(String path, UISCVPreferences uiScvPref) throws Exception { if (path == null || path.length() == 0 || uiScvPref.getSelectedNodeDrive() == null || uiScvPref.getSelectedNodeDrive().length() == 0 || uiScvPref.getSelectedNodeRepository() == null || uiScvPref.getSelectedNodeRepository().length() == 0) return ""; ManageDriveService managerDriveService = uiScvPref.getApplicationComponent(ManageDriveService.class); DriveData driveData = managerDriveService.getDriveByName(uiScvPref.getSelectedNodeDrive()); if (!path.startsWith(driveData.getHomePath())) return ""; if ("/".equals(driveData.getHomePath())) return path; return path.substring(driveData.getHomePath().length()); } } /** * * @return A string point to the node from preferences */ protected String getNodeNameByPreferences(){ String repository = WCMCoreUtils.getRepository().getConfiguration().getName(); String workspace = portletPreferences.getValue(UISingleContentViewerPortlet.WORKSPACE, null); String nodeIdentifier = portletPreferences.getValue(UISingleContentViewerPortlet.IDENTIFIER, null); String nodeDrive = portletPreferences.getValue(UISingleContentViewerPortlet.DRIVE, null); try { Node savedNode = Utils.getRealNode(repository, workspace, nodeIdentifier, false); if (savedNode==null) return null; this.setSelectedNodeInfo(savedNode.getUUID(), repository, workspace, nodeDrive); this.setSelectedNodePath(savedNode.getPath()); return getTitle(savedNode); }catch (RepositoryException re) { return null; } } /** * Gets the title. * * @param node the node * * @return the title * * @throws Exception the exception */ private String getTitle(Node node) throws RepositoryException { String title = null; if (node.hasProperty("exo:title")) { title = node.getProperty("exo:title").getValue().getString(); } if (node.hasNode("jcr:content")) { Node content = node.getNode("jcr:content"); if (content.hasProperty("dc:title")) { try { title = content.getProperty("dc:title").getValues()[0].getString(); } catch (Exception e) { title = null; } } } if (title==null) title = node.getName(); return ContentReader.getUnescapeIllegalJcrContent(title); } public void setContentSelectorID(String id) { this.contentSelectorID = id; } public String getContetSelectorID() { return this.contentSelectorID; } public boolean isContextualEnable() { return Boolean.parseBoolean(portletPreferences.getValue(UISingleContentViewerPortlet.CONTEXTUAL_MODE, "false")); } public void doSelect(String selectField, Object value) throws Exception { String strRepository, strWorkspace, strDrive, strIdentifier, strNodeUUID; int driveIndex; String strPath = (String) value; if (CONTENT_PATH_INPUT.equals(selectField) ) { String[] splits = strPath.split(":"); driveIndex = (splits.length == 4) ? 1 : 0; strRepository = splits[driveIndex]; strWorkspace = splits[driveIndex + 1]; strIdentifier = splits[driveIndex + 2]; strDrive= (driveIndex == 1) ? splits[0] : ""; strIdentifier = Text.escapeIllegalJcrChars(strIdentifier); Node selectedNode = Utils.getRealNode(strRepository, strWorkspace, strIdentifier, false); if (selectedNode==null) return; strNodeUUID = selectedNode.getUUID(); this.setSelectedNodeInfo(strNodeUUID, strRepository, strWorkspace, strDrive); this.setSelectedNodePath(selectedNode.getPath()); getUIStringInput(selectField).setValue(getTitle(selectedNode)); }else if (PRINT_VIEW_PAGE_INPUT.equals(selectField)) { getUIStringInput(selectField).setValue(strPath); } Utils.closePopupWindow(this, contentSelectorID); } /** * The listener interface for receiving selectTargetPageAction events. * The class that is interested in processing a selectTargetPageAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSelectTargetPageActionListener</code> method. When * the selectTargetPageAction event occurs, that object's appropriate * method is invoked. */ public static class SelectTargetPageActionListener extends EventListener<UISCVPreferences> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UISCVPreferences> event) throws Exception { UISCVPreferences uiscv = event.getSource(); UIPageSelector pageSelector = uiscv.createUIComponent(UIPageSelector.class, null, null); pageSelector.setSourceComponent(uiscv, new String[] {PRINT_VIEW_PAGE_INPUT}); Utils.createPopupWindow(uiscv, pageSelector, PRINT_PAGE_SELECTOR_POPUP, 800); uiscv.setContentSelectorID(PRINT_PAGE_SELECTOR_POPUP); } } public void setInternalPreferencesMode(boolean isInternal) { this.isInternal = isInternal; } public boolean getInternalPreferencesMode() { return this.isInternal; } boolean isInternal = false; }
25,528
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICLVPresentation.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/clv/UICLVPresentation.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.clv; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.MissingResourceException; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.portlet.PortletPreferences; import javax.portlet.PortletRequest; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.utils.PageList; import org.exoplatform.container.PortalContainer; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.ecm.utils.lock.LockUtil; import org.exoplatform.portal.mop.SiteType; import org.exoplatform.portal.webui.container.UIContainer; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.documents.TrashService; import org.exoplatform.services.cms.folksonomy.NewFolksonomyService; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.core.WebSchemaConfigService; import org.exoplatform.services.wcm.friendly.FriendlyService; import org.exoplatform.services.wcm.publication.PublicationDefaultStates; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.services.wcm.webcontent.WebContentSchemaHandler; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.administration.UIEditingForm; import org.exoplatform.wcm.webui.paginator.UICustomizeablePaginator; import org.exoplatform.wcm.webui.reader.ContentReader; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.web.application.JavascriptManager; import org.exoplatform.web.url.navigation.NavigationResource; import org.exoplatform.web.url.navigation.NodeURL; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.ComponentConfigs; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIPageIterator; import org.exoplatform.webui.core.lifecycle.Lifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /* * Created by The eXo Platform SAS Author : Anh Do Ngoc anh.do@exoplatform.com * Oct 21, 2008 */ /** * The Class UICLVPresentation. */ @SuppressWarnings("deprecation") @ComponentConfigs( { @ComponentConfig(lifecycle = Lifecycle.class, events = { @EventConfig(listeners = UICLVPresentation.RefreshActionListener.class), @EventConfig(listeners = UICLVPresentation.DeleteContentActionListener.class, confirm = "UICLVPresentation.msg.confirm-delete"), @EventConfig(listeners = UICLVPresentation.FastPublishActionListener.class) }), @ComponentConfig(type = UICustomizeablePaginator.class, events = @EventConfig(listeners = UICustomizeablePaginator.ShowPageActionListener.class)) }) public class UICLVPresentation extends UIContainer { public static final String defaultScvParam = "content-id"; private static final Log LOG = ExoLogger.getLogger(UICLVPresentation.class.getName()); /** The template path. */ private String templatePath; /** The resource resolver. */ private ResourceResolver resourceResolver; /** The ui paginator. */ private UICustomizeablePaginator uiPaginator; /** The date formatter. */ private DateFormat dateFormatter = null; /** Generic TagStyles configurable in ECM Administration */ private Map<String, String> tagStyles = null; /** * Instantiates a new uICLV presentation. */ public UICLVPresentation() { } /** * Init portlet information. * * @param resourceResolver the resource resolver * @param dataPageList the data page list * @throws Exception the exception */ public void init(ResourceResolver resourceResolver, PageList dataPageList) throws Exception { String paginatorTemplatePath = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_PAGINATOR_TEMPLATE); this.templatePath = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_DISPLAY_TEMPLATE); this.resourceResolver = resourceResolver; uiPaginator = addChild(UICustomizeablePaginator.class, null, null); uiPaginator.setTemplatePath(paginatorTemplatePath); uiPaginator.setResourceResolver(resourceResolver); uiPaginator.setPageList(dataPageList); Locale locale = Util.getPortalRequestContext().getLocale(); dateFormatter = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM, SimpleDateFormat.MEDIUM, locale); } public List<CategoryBean> getCategories() throws Exception { String fullPath = this.getAncestorOfType(UICLVPortlet.class).getFolderPath(); return getCategories(fullPath, "exo:taxonomy", 0); } public List<CategoryBean> getCategories(String primaryType) throws Exception { String fullPath = this.getAncestorOfType(UICLVPortlet.class).getFolderPath(); return getCategories(fullPath, primaryType, 0); } public List<CategoryBean> getCategories(boolean withChildren) throws Exception { String fullPath = this.getAncestorOfType(UICLVPortlet.class).getFolderPath(); return getCategories(fullPath, "exo:taxonomy", 0, withChildren); } public List<CategoryBean> getCategories(String fullPath, String primaryType, int depth) throws Exception { return getCategories(fullPath, primaryType, depth, true); } public List<CategoryBean> getCategories(String fullPath, String primaryType, int depth, boolean withChildren) throws Exception { if (fullPath == null || fullPath.length() == 0) { return null; } WCMComposer wcmComposer = getApplicationComponent(WCMComposer.class); HashMap<String, String> filters = new HashMap<String, String>(); filters.put(WCMComposer.FILTER_MODE, Utils.getCurrentMode()); String orderType = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_ORDER_TYPE); String orderBy = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_ORDER_BY); // orderType = "ASC"; // orderBy = "jcr:path"; filters.put(WCMComposer.FILTER_ORDER_BY, orderBy); filters.put(WCMComposer.FILTER_ORDER_TYPE, orderType); filters.put(WCMComposer.FILTER_LANGUAGE, Util.getPortalRequestContext() .getLocale() .getLanguage()); // filters.put(WCMComposer.FILTER_RECURSIVE, "true"); filters.put(WCMComposer.FILTER_PRIMARY_TYPE, primaryType); String clvBy = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_SHOW_CLV_BY); /* Allows us to know the current selected node */ String paramPath = Util.getPortalRequestContext().getRequestParameter(clvBy); NodeLocation nodeLocation = NodeLocation.getNodeLocationByExpression(fullPath); List<Node> nodes = wcmComposer.getContents(nodeLocation.getWorkspace(), nodeLocation.getPath(), filters, WCMCoreUtils.getUserSessionProvider()); List<CategoryBean> categories = new LinkedList<CategoryBean>(); for (Node node : nodes) { String title = getTitle(node); String url = getCategoryURL(node); String path = node.getPath(); long total = (node.hasProperty("exo:total")) ? node.getProperty("exo:total") .getValue() .getLong() : 0; boolean isSelected = paramPath != null && paramPath.endsWith(path); CategoryBean cat = new CategoryBean(node.getName(), node.getPath(), title, url, isSelected, depth, total); NodeLocation catLocation = NodeLocation.getNodeLocationByNode(node); if (withChildren) { List<CategoryBean> childs = getCategories(catLocation.toString(), primaryType, depth + 1); if (childs != null && childs.size() > 0) cat.setChilds(childs); } // System.out.println(cat.getName()+"::"+cat.getPath()+"::"+cat.getTitle()+"::"+cat.isSelected()+"::"+cat.getDepth()); categories.add(cat); } return categories; } public String getTagHtmlStyle(long tagCount) throws Exception { for (Entry<String, String> entry : getTagStyles().entrySet()) { if (checkTagRate(tagCount, entry.getKey())) return entry.getValue(); } return ""; } private Map<String, String> getTagStyles() throws Exception { if (tagStyles == null) { NewFolksonomyService folksonomyService = getApplicationComponent(NewFolksonomyService.class); String workspace = "dms-system"; tagStyles = new HashMap<String, String>(); for (Node tag : folksonomyService.getAllTagStyle(workspace)) { tagStyles.put(tag.getProperty("exo:styleRange").getValue().getString(), tag.getProperty("exo:htmlStyle").getValue().getString()); } } return tagStyles; } private boolean checkTagRate(long numOfDocument, String range) throws Exception { String[] vals = StringUtils.split(range, ".."); int minValue = Integer.parseInt(vals[0]); int maxValue; if (vals[1].equals("*")) { maxValue = Integer.MAX_VALUE; } else { maxValue = Integer.parseInt(vals[1]); } if (minValue <= numOfDocument && numOfDocument < maxValue) return true; return false; } /** * Gets the uRL. * * @param node the node * @return the uRL * @throws Exception the exception */ public String getCategoryURL(Node node) throws Exception { String link = null; PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); PortletRequest portletRequest = portletRequestContext.getRequest(); NodeLocation nodeLocation = NodeLocation.getNodeLocationByNode(node); String baseURI = portletRequest.getScheme() + "://" + portletRequest.getServerName() + ":" + String.format("%s", portletRequest.getServerPort()); String basePath = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_TARGET_PAGE); String clvBy = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_SHOW_CLV_BY); if (clvBy == null || clvBy.length() == 0) clvBy = UICLVPortlet.DEFAULT_SHOW_CLV_BY; String params = nodeLocation.getRepository() + ":" + nodeLocation.getWorkspace() +":"+ node.getPath(); NodeURL nodeURL = Util.getPortalRequestContext().createURL(NodeURL.TYPE); NavigationResource resource = new NavigationResource(SiteType.PORTAL, Util.getPortalRequestContext() .getPortalOwner(), basePath); nodeURL.setResource(resource).setQueryParameterValue(clvBy, params); link = baseURI + nodeURL.toString(); FriendlyService friendlyService = getApplicationComponent(FriendlyService.class); link = friendlyService.getFriendlyUri(link); return link; } /** * Checks if is show field. * * @param field the field * @return true, if is show field */ public boolean isShowField(String field) { String visible = Utils.getPortletPreference(field); return (visible != null) ? Boolean.parseBoolean(visible) : false; } /** * Show paginator. * * @return true, if successful * @throws Exception the exception */ public boolean showPaginator() throws Exception { String itemsPerPage = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_ITEMS_PER_PAGE); int totalItems = uiPaginator.getTotalItems(); if (totalItems > Integer.parseInt(itemsPerPage)) { return true; } return false; } /* * (non-Javadoc) * @see org.exoplatform.portal.webui.portal.UIPortalComponent#getTemplate() */ public String getTemplate() { return templatePath; } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIComponent#getTemplateResourceResolver(org. * exoplatform.webui.application.WebuiRequestContext, java.lang.String) */ public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context, String template) { return resourceResolver; } /** * Gets the title. * * @param node the node * @return the title * @throws Exception the exception */ public String getTitle(Node node) throws Exception { String title = null; if (node.hasProperty("exo:title")) { title = node.getProperty("exo:title").getValue().getString(); } else if (node.hasNode("jcr:content")) { Node content = node.getNode("jcr:content"); if (content.hasProperty("dc:title")) { try { title = content.getProperty("dc:title").getValues()[0].getString(); } catch (Exception ex) { // Do nothing } } } if (title == null) { if (node.isNodeType("nt:frozenNode")) { String uuid = node.getProperty("jcr:frozenUuid").getString(); Node originalNode = node.getSession().getNodeByUUID(uuid); title = originalNode.getName(); } else { title = node.getName(); } } return ContentReader.getXSSCompatibilityContent(title); } /** * Gets the summary. * * @param node the node * @return the summary * @throws Exception the exception */ public String getSummary(Node node) throws Exception { String desc = null; if (node.hasProperty("exo:summary")) { desc = node.getProperty("exo:summary").getValue().getString(); } else if (node.hasNode("jcr:content")) { Node content = node.getNode("jcr:content"); if (content.hasProperty("dc:description")) { try { desc = ContentReader.getXSSCompatibilityContent(content.getProperty("dc:description").getValues()[0].getString()); } catch (Exception ex) { return null; } } } return desc; } public static String getInlineEditingField(Node orgNode, String propertyName, String defaultValue, String inputType, String idGenerator, String cssClass, boolean isGenericProperty, String... arguments) throws Exception { return org.exoplatform.ecm.webui.utils.Utils.getInlineEditingField(orgNode, propertyName, defaultValue, inputType, idGenerator, cssClass, isGenericProperty, arguments); } public String getSummaryField(Node node) throws Exception { String desc = null; if (node.hasProperty("exo:summary")) { return "exo:summary"; } else if (node.hasNode("jcr:content")) { Node content = node.getNode("jcr:content"); if (content.hasProperty("dc:description")) { try { desc = content.getProperty("dc:description").getValues()[0].getString(); return "jcr:content/dc:description"; } catch (Exception ex) { return null; } } } return desc; } /** * Gets the uRL. * * @param node the node * @return the uRL * @throws Exception the exception */ public String getURL(Node node) throws Exception { String link = null; NodeLocation nodeLocation = NodeLocation.getNodeLocationByNode(node); String basePath = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_TARGET_PAGE); String scvWith = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_SHOW_SCV_WITH); if (scvWith == null || scvWith.length() == 0) scvWith = UICLVPortlet.DEFAULT_SHOW_SCV_WITH; StringBuffer sb = new StringBuffer(); sb.append("/") .append(nodeLocation.getRepository()) .append("/") .append(nodeLocation.getWorkspace()); if (node.isNodeType("nt:frozenNode")) { String uuid = node.getProperty("jcr:frozenUuid").getString(); Node originalNode = node.getSession().getNodeByUUID(uuid); sb.append(originalNode.getPath()); } else { sb.append(node.getPath()); } String param = sb.toString(); param = Text.escapeIllegalJcrChars(param); NodeURL nodeURL = Util.getPortalRequestContext().createURL(NodeURL.TYPE); NavigationResource resource = new NavigationResource(SiteType.PORTAL, Util.getPortalRequestContext() .getPortalOwner(), basePath); nodeURL.setResource(resource).setQueryParameterValue(scvWith, param); String fullPath = this.getAncestorOfType(UICLVPortlet.class).getFolderPathParamValue(); if (fullPath != null) { String clvBy = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_SHOW_CLV_BY); nodeURL.setQueryParameterValue(clvBy, fullPath); } link = nodeURL.toString(); FriendlyService friendlyService = getApplicationComponent(FriendlyService.class); link = friendlyService.getFriendlyUri(link); return link; } /** * Gets the webdav url. * * @param node the node * @return the webdav url * @throws Exception the exception */ public String getWebdavURL(Node node) throws Exception { NodeLocation nodeLocation = NodeLocation.getNodeLocationByNode(node); String repository = nodeLocation.getRepository(); String workspace = nodeLocation.getWorkspace(); FriendlyService friendlyService = getApplicationComponent(FriendlyService.class); String link = "#";// friendlyService.getFriendlyUri(link); String portalName = PortalContainer.getCurrentPortalContainerName(); String restContextName = PortalContainer.getCurrentRestContextName(); if (node.isNodeType("nt:frozenNode")) { String uuid = node.getProperty("jcr:frozenUuid").getString(); Node originalNode = node.getSession().getNodeByUUID(uuid); link = "/" + portalName + "/" + restContextName + "/jcr/" + repository + "/" + workspace + originalNode.getPath() + "?version=" + node.getParent().getName(); } else { link = "/" + portalName + "/" + restContextName + "/jcr/" + repository + "/" + workspace + node.getPath(); } return encodeURI(friendlyService.getFriendlyUri(link)); } /** * Gets the author. * * @param node the node * @return the author * @throws Exception the exception */ public String getAuthor(Node node) throws Exception { if (node.hasProperty("exo:owner")) { String ownerId = node.getProperty("exo:owner").getValue().getString(); return ownerId; } return null; } /** * Gets the created date. * * @param node the node * @return the created date * @throws Exception the exception */ public String getCreatedDate(Node node) throws Exception { if (node.hasProperty("exo:dateCreated")) { Calendar calendar = node.getProperty("exo:dateCreated").getValue().getDate(); if (calendar!=null) { return dateFormatter.format(calendar.getTime()); } } return null; } /** * Gets the modified date. * * @param node the node * @return the modified date * @throws Exception the exception */ public String getModifiedDate(Node node) throws Exception { if (node.hasProperty("exo:dateModified")) { Calendar calendar = node.getProperty("exo:dateModified").getValue().getDate(); return dateFormatter.format(calendar.getTime()); } return null; } /** * Gets the content icon. * * @param node the node * @return the content icon */ public String getContentIcon(Node node) { try { if (node.isNodeType("nt:frozenNode")) { String uuid = node.getProperty("jcr:frozenUuid").getString(); Node originalNode = node.getSession().getNodeByUUID(uuid); return org.exoplatform.ecm.webui.utils.Utils.getNodeTypeIcon(originalNode, "uiIcon16x16"); } return org.exoplatform.ecm.webui.utils.Utils.getNodeTypeIcon(node, "uiIcon16x16"); } catch (RepositoryException e) { Utils.createPopupMessage(this, "UIMessageBoard.msg.get-content-icon", null, ApplicationMessage.ERROR); } return null; } public String getHeader() { String header = this.getAncestorOfType(UICLVPortlet.class).getHeader(); if(header == null) header = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_HEADER); return header; } public UIPageIterator getUIPageIterator() { return uiPaginator; } public List getCurrentPageData() throws Exception { return NodeLocation.getNodeListByLocationList(uiPaginator.getCurrentPageData()); } public void setDateTimeFormat(String format) { ((SimpleDateFormat) dateFormatter).applyPattern(format); } public String getEditLink(Node node, boolean isEditable, boolean isNew) { return Utils.getEditLink(node, isEditable, isNew); } public boolean isShowEdit(Node node) { if (Utils.isShowQuickEdit()) { try { Node parent = node.getParent(); ((ExtendedNode) node).checkPermission(PermissionType.SET_PROPERTY); ((ExtendedNode) parent).checkPermission(PermissionType.ADD_NODE); } catch (Exception e) { return false; } return true; } return false; } public boolean isViewMode() { return Utils.getCurrentMode().equals(WCMComposer.MODE_LIVE); } /** * Gets the illustrative image. * * @param node the node * @return the illustrative image */ public String getIllustrativeImage(Node node) { WebSchemaConfigService schemaConfigService = getApplicationComponent(WebSchemaConfigService.class); WebContentSchemaHandler contentSchemaHandler = schemaConfigService.getWebSchemaHandlerByType(WebContentSchemaHandler.class); Node illustrativeImage = null; String uri = null; try { illustrativeImage = contentSchemaHandler.getIllustrationImage(node); uri = WCMCoreUtils.generateImageURI(illustrativeImage, null); } catch (PathNotFoundException ex) { // We don't do anything here because so many documents doesn't have // illustration image } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage(), e); } } return uri; } public boolean isShowRssLink() { if (getUIPageIterator().getAvailable() == 0) { return false; } PortletPreferences portletPreferences = Utils.getAllPortletPreferences(); String currentApplicationMode = portletPreferences.getValue(UICLVPortlet.PREFERENCE_APPLICATION_TYPE, null); if (currentApplicationMode.equals(UICLVPortlet.APPLICATION_CLV_BY_QUERY)) return false; return isShowField(UICLVPortlet.PREFERENCE_SHOW_RSSLINK) && (this.getAncestorOfType(UICLVPortlet.class).getFolderPathParamValue() != null || UICLVPortlet.DISPLAY_MODE_AUTOMATIC.equals(Utils.getPortletPreference(UICLVPortlet.PREFERENCE_DISPLAY_MODE))); } public String getFastPublicLink(Node viewNode) { String fastPublishLink = null; try { fastPublishLink = event("FastPublish", NodeLocation.getExpressionByNode(viewNode)); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } return fastPublishLink; } /** * Gets the rss link. * * @return the rss link */ public String getRssLink() { String portal = PortalContainer.getCurrentPortalContainerName(); String rest = PortalContainer.getCurrentRestContextName(); String server = Util.getPortalRequestContext().getRequest().getRequestURL().toString(); int lastIndex = server.indexOf(portal); server = server.substring(0, lastIndex-1) + Util.getPortalRequestContext().getPortalURI(); String fullPath = this.getAncestorOfType(UICLVPortlet.class).getFolderPathParamValue(); if (fullPath == null || fullPath.length() == 0) fullPath = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_ITEM_PATH); if (fullPath == null) return "/" + portal + "/" + rest + "&siteName=" + Util.getUIPortal().getSiteKey().getName() + "&orderBy=" + Utils.getPortletPreference(UICLVPortlet.PREFERENCE_ORDER_BY) + "&orderType=" + Utils.getPortletPreference(UICLVPortlet.PREFERENCE_ORDER_TYPE) + "&detailPage=" + Utils.getPortletPreference(UICLVPortlet.PREFERENCE_TARGET_PAGE) + "&detailParam=" + Utils.getPortletPreference(UICLVPortlet.PREFERENCE_SHOW_SCV_WITH); String[] repoWsPath = fullPath.split(":"); return "/" + portal + "/" + rest + "/feed/rss?repository=" + repoWsPath[0] + "&workspace=" + repoWsPath[1] + "&server=" + server + "&siteName=" + Util.getUIPortal().getSiteKey().getName() + "&folderPath=" + repoWsPath[2] + "&orderBy=" + Utils.getPortletPreference(UICLVPortlet.PREFERENCE_ORDER_BY) + "&orderType=" + Utils.getPortletPreference(UICLVPortlet.PREFERENCE_ORDER_TYPE) + // "&title=" // "&desc="My%20description "&detailPage=" + Utils.getPortletPreference(UICLVPortlet.PREFERENCE_TARGET_PAGE) + "&detailParam=" + Utils.getPortletPreference(UICLVPortlet.PREFERENCE_SHOW_SCV_WITH); } /** * This method will put the mandatory html code to manage QuickEdit mode * * @param cssClass * @param viewNode * @return * @throws Exception */ public String addQuickEditDiv(String cssClass, Node viewNode) throws Exception { StringBuffer sb = new StringBuffer(); String id = this.getClass().getSimpleName() + System.currentTimeMillis(); PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); sb.append("<div id=\""+id+"\" class=\"" + cssClass + " \">"); if (Utils.isShowQuickEdit()) { sb.append(" <div class=\"edittingContent\" style=\" z-index: 5\">"); sb.append(" <div class=\"edittingToolBar clearfix\" >"); sb.append(" <div class=\"btn-group\" >"); if (isShowEdit(viewNode) && !LockUtil.isLocked(viewNode)) { String strEditBundle = "Edit in the Content Explorer"; try { strEditBundle = portletRequestContext.getApplicationResourceBundle() .getString("UICLVPresentation.action.edit"); } catch (MissingResourceException e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } if (org.exoplatform.wcm.webui.utils.Utils.isShowFastPublish(viewNode)) { String fastPublishLink = event("FastPublish", NodeLocation.getExpressionByNode(viewNode)); String strFastPublishBundle = "Publish"; try { strFastPublishBundle = portletRequestContext.getApplicationResourceBundle() .getString("UICLVPresentation.action.publish"); } catch (MissingResourceException e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } sb.append(" <a class=\"btn\" href=\"" + fastPublishLink + "\" rel=\"tooltip\" data-placement=\"left\" title=\"" + strFastPublishBundle + "\">"); sb.append(" <i class=\"uiIconEcmsPublish\" ></i>"); sb.append(" </a>"); } String contentEditLink = getEditLink(viewNode, true, false); sb.append(" <a class=\"btn\" onclick = 'eXo.ecm.CLV.addURL(this)' href=\"" + contentEditLink + "\" rel=\"tooltip\" data-placement=\"left\" title=\"" + strEditBundle + "\">"); sb.append(" <i class=\"uiIconEdit\"></i>"); sb.append(" </a>"); } else { sb.append(" <a class=\"btn\" >"); sb.append(" <i class=\"uiIconEcmsLock\" ></i>"); sb.append(" </a>"); } if (Utils.isShowDelete(viewNode)) { String contentDeleteLink = event("DeleteContent", NodeLocation.getExpressionByNode(viewNode)); String strDeleteBundle = "Delete"; try { strDeleteBundle = portletRequestContext.getApplicationResourceBundle() .getString("UICLVPresentation.action.delete"); } catch (MissingResourceException e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } sb.append(" <a class=\"btn\" href=\"" + contentDeleteLink + "\" rel=\"tooltip\" data-placement=\"left\" title=\"" + strDeleteBundle + "\">"); sb.append(" <i class=\"uiIconRemove\"></i>"); sb.append(" </a>"); } sb.append(" </div>"); if (viewNode.hasProperty("publication:currentState")) { PublicationService publicationService = WCMCoreUtils.getService(PublicationService.class); String state = publicationService.getCurrentState(viewNode); String stateLabel=""; try { stateLabel = portletRequestContext.getApplicationResourceBundle() .getString("PublicationStates." + state); } catch (MissingResourceException e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } sb.append("<div class=\"edittingCurrentState pull-left\">"); sb.append("<span class=\""+state+"Text\">"); if(PublicationDefaultStates.PUBLISHED.equals(state)) sb.append("<i class=\"uiIconTick\"></i>"); sb.append(stateLabel + "</span>"); sb.append(" </div>"); } sb.append(" </div>"); sb.append(" </div>"); } String className = cssClass + " " + this.getAncestorOfType(UICLVPortlet.class).getName(); String hoverClass = Utils.isShowQuickEdit() ? " containerHoverClassInner" : ""; JavascriptManager jsManager = portletRequestContext.getJavascriptManager(); jsManager.getRequireJS() .require("SHARED/jquery", "gj") .addScripts("gj('#" + id + "').mouseenter( function() {eXo.ecm.WCMUtils.changeStyleClass('" + id + "','" + className + " " + hoverClass + "');});") .addScripts("gj('#" + id + "').mouseleave( function() {eXo.ecm.WCMUtils.changeStyleClass('" + id + "'," + "'" + className + "');});"); return sb.toString(); } public String getBackLink (String currentPath) { String preferencePath = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_ITEM_PATH); String targetPage = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_TARGET_PAGE); NodeURL nodeURL = Util.getPortalRequestContext().createURL(NodeURL.TYPE); NavigationResource resource = new NavigationResource(SiteType.PORTAL, Util.getPortalRequestContext() .getPortalOwner(), targetPage); nodeURL.setResource(resource); if (currentPath.contains(preferencePath)) { String treePath = currentPath.substring(preferencePath.length() + 1); String[] treeNodes = treePath.split("/"); if (treeNodes.length > 1) { String paramPath = currentPath.substring(0, currentPath.lastIndexOf("/")); String clvBy = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_SHOW_CLV_BY); nodeURL.setQueryParameterValue(clvBy, paramPath); } } return nodeURL.toString(); } /** * The listener interface for receiving refreshAction events. The class that * is interested in processing a refreshAction event implements this * interface, and the object created with that class is registered with a * component using the component's * <code>addRefreshActionListener</code> method. When * the refreshAction event occurs, that object's appropriate * method is invoked. */ public static class RefreshActionListener extends EventListener<UICLVPresentation> { /* * (non-Javadoc) * @see * org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui * .event.Event) */ public void execute(Event<UICLVPresentation> event) throws Exception { UICLVPresentation clvPresentation = event.getSource(); clvPresentation.getAncestorOfType(UICLVContainer.class).onRefresh(event); } } public static class DeleteContentActionListener extends EventListener<UICLVPresentation> { /* * (non-Javadoc) * @see * org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui * .event.Event) */ public void execute(Event<UICLVPresentation> event) throws Exception { String itemPath = event.getRequestContext().getRequestParameter(OBJECTID); Node node = NodeLocation.getNodeByExpression(itemPath); Node parent = node.getParent(); TrashService trashService = WCMCoreUtils.getService(TrashService.class); trashService.moveToTrash(node, WCMCoreUtils.getUserSessionProvider()); parent.getSession().save(); event.getRequestContext().getJavascriptManager().getRequireJS().addScripts("location.reload(true);"); } } public static class FastPublishActionListener extends EventListener<UICLVPresentation> { /* * (non-Javadoc) * @see * org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui * .event.Event) */ public void execute(Event<UICLVPresentation> event) throws Exception { UICLVPresentation contentListPresentation = event.getSource(); String nodePath = event.getRequestContext().getRequestParameter(OBJECTID); Node node = NodeLocation.getNodeByExpression(Text.escapeIllegalJcrChars(nodePath)); PublicationService publicationService = WCMCoreUtils.getService(PublicationService.class); if (node.isLocked()) { node.getSession().addLockToken(LockUtil.getLockToken(node)); } HashMap<String, String> context = new HashMap<String, String>(); publicationService.changeState(node, "published", context); event.getRequestContext().getJavascriptManager().getRequireJS().addScripts("location.reload(true);"); } } public String encodeURLComponent(String s) { String result = null; try { result = URLEncoder.encode(s, "UTF-8") .replaceAll("\\+", "%20") .replaceAll("\\%21", "!") .replaceAll("\\%28", "(") .replaceAll("\\%29", ")") .replaceAll("\\%7E", "~"); } catch (UnsupportedEncodingException e) { result = s; } return result; } public String encodeURI(String url) { return encodeURLComponent(url) .replaceAll("%3A", ":") .replaceAll("%2F", "/") .replaceAll("%3F", "?") .replaceAll("%3D", "=") .replaceAll("%26", "&"); } }
37,488
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICLVManualMode.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/clv/UICLVManualMode.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.clv; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import javax.jcr.Node; import javax.jcr.query.Query; import javax.portlet.PortletPreferences; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.ecm.utils.comparator.PropertyValueComparator; import org.exoplatform.portal.webui.application.UIPortlet; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.publication.PaginatedResultIterator; import org.exoplatform.services.wcm.publication.Result; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.services.wcm.search.base.AbstractPageList; import org.exoplatform.services.wcm.search.base.PageListFactory; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.scv.UISingleContentViewerPortlet; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.Lifecycle; /** * Created by The eXo Platform SAS * Author : anh.do * anh.do@exoplatform.com, anhdn86@gmail.com * Feb 23, 2009 */ @ComponentConfig( lifecycle = Lifecycle.class, template = "system:/groovy/ContentListViewer/UICLVContainer.gtmpl", events = { @EventConfig(listeners = UICLVManualMode.PreferencesActionListener.class) } ) @SuppressWarnings("deprecation") public class UICLVManualMode extends UICLVContainer { /** The log. */ private static final Log LOG = ExoLogger.getLogger(UICLVManualMode.class.getName()); /* (non-Javadoc) * @see org.exoplatform.wcm.webui.clv.UICLVContainer#init() */ @SuppressWarnings("unchecked") public void init() throws Exception { PortletPreferences portletPreferences = Utils.getAllPortletPreferences(); String query = portletPreferences.getValue(UICLVPortlet.PREFERENCE_CONTENTS_BY_QUERY, ""); String contextualMode = portletPreferences.getValue(UICLVPortlet.PREFERENCE_CONTEXTUAL_FOLDER, null); String workspace = portletPreferences.getValue(UICLVPortlet.PREFERENCE_WORKSPACE, null); List<Node> nodes = new ArrayList<Node>(); String folderPath=""; HashMap<String, String> filters = new HashMap<String, String>(); if (UICLVPortlet.PREFERENCE_CONTEXTUAL_FOLDER_ENABLE.equals(contextualMode)) { String folderParamName = portletPreferences.getValue(UICLVPortlet.PREFERENCE_SHOW_CLV_BY, null); if (folderParamName == null || folderParamName.length() == 0) folderParamName = UICLVPortlet.DEFAULT_SHOW_CLV_BY; folderPath = Util.getPortalRequestContext().getRequestParameter(folderParamName); } String sharedCache = portletPreferences.getValue(UISingleContentViewerPortlet.ENABLE_CACHE, "true"); sharedCache = "true".equals(sharedCache) ? WCMComposer.VISIBILITY_PUBLIC:WCMComposer.VISIBILITY_USER; int itemsPerPage = Integer.parseInt(portletPreferences.getValue(UICLVPortlet.PREFERENCE_ITEMS_PER_PAGE, null)); String strQuery = this.getAncestorOfType(UICLVPortlet.class).getQueryStatement(query); if (strQuery != null) strQuery = strQuery.replaceAll("\"", "'"); String[] contentList = null; if (portletPreferences.getValue(UICLVPortlet.PREFERENCE_ITEM_PATH, null) != null) { contentList = portletPreferences.getValue(UICLVPortlet.PREFERENCE_ITEM_PATH, null).split(";"); } if (this.getAncestorOfType(UICLVPortlet.class).isQueryApplication() && UICLVPortlet.PREFERENCE_CONTEXTUAL_FOLDER_ENABLE.equals(contextualMode) && org.exoplatform.wcm.webui.Utils.checkQuery(workspace, strQuery, Query.SQL)) { if (contentList != null && contentList.length != 0) { for (String itemPath : contentList) { itemPath = itemPath.replace("{siteName}", Util.getPortalRequestContext().getSiteName()); Node currentNode = NodeLocation.getNodeByExpression(itemPath); NodeLocation nodeLocation = new NodeLocation(); if (currentNode != null) { String path = currentNode.getPath(); nodeLocation.setPath(path); nodeLocation.setWorkspace(workspace); nodeLocation.setSystemSession(false); } filters.put(WCMComposer.FILTER_QUERY_FULL, strQuery); Result rNodes = WCMCoreUtils.getService(WCMComposer.class) .getPaginatedContents(nodeLocation, filters, WCMCoreUtils.getUserSessionProvider()); if (rNodes.getNumTotal() == 0) messageKey = "UICLVContainer.msg.non-contents"; PaginatedResultIterator paginatedResultIterator = new PaginatedResultIterator(rNodes, itemsPerPage); getChildren().clear(); ResourceResolver resourceResolver = getTemplateResourceResolver(); PortletRequestContext pContext = (PortletRequestContext) WebuiRequestContext.getCurrentInstance(); UICLVPresentation clvPresentation = addChild(UICLVPresentation.class, null, UICLVPresentation.class.getSimpleName() + "_" + pContext.getWindowId() ); clvPresentation.init(resourceResolver, paginatedResultIterator); return; } } } else { LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class); //get node to sort List<Node> originalList = new ArrayList<Node>(); if (contentList != null && contentList.length != 0) { for (String itemPath : contentList) { itemPath = itemPath.replace("{siteName}", Util.getPortalRequestContext().getSiteName()); Node currentNode = NodeLocation.getNodeByExpression(itemPath); if(currentNode != null){ try { linkManager.updateSymlink(currentNode); currentNode = NodeLocation.getNodeByExpression(itemPath); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Can not update symlink: " + currentNode.getPath(), e); } } originalList.add(currentNode); } } } //sort nodes String orderBy = portletPreferences.getValue(UICLVPortlet.PREFERENCE_ORDER_BY, NodetypeConstant.EXO_TITLE); String orderType = portletPreferences.getValue(UICLVPortlet.PREFERENCE_ORDER_TYPE, "ASC"); Collections.sort(originalList, new PropertyValueComparator(orderBy, "ASC".equals(orderType) ? "Ascending" : "Descending")); //get real node by portlet mode for (Node node : originalList) { Node viewNode = Utils.getViewableNodeByComposer(WCMCoreUtils.getRepository().getConfiguration().getName(), Text.escapeIllegalJcrChars(node.getSession().getWorkspace().getName()), Text.escapeIllegalJcrChars(node.getPath()), null, sharedCache); if (viewNode != null) nodes.add(viewNode); } } if (nodes.size() == 0) { messageKey = "UICLVContainer.msg.non-contents"; } getChildren().clear(); AbstractPageList<NodeLocation> pageList = PageListFactory.createPageList(nodes, itemsPerPage, null, new CLVNodeCreator()); ResourceResolver resourceResolver = getTemplateResourceResolver(); PortletRequestContext pContext = (PortletRequestContext) WebuiRequestContext.getCurrentInstance(); UICLVPresentation clvPresentation = addChild(UICLVPresentation.class, null, UICLVPresentation.class.getSimpleName() + "_" + pContext.getWindowId() ); clvPresentation.init(resourceResolver, pageList); } /** * Gets the bar info show. * * @return the value for info bar setting * * @throws Exception the exception */ public boolean isShowInfoBar() throws Exception { if (UIPortlet.getCurrentUIPortlet().getShowInfoBar()) return true; return false; } /** * Get portlet name. * * @throws Exception the exception */ public String getPortletName() throws Exception { return UICLVManualMode.class.getSimpleName(); } }
9,854
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICLVConfig.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/clv/UICLVConfig.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.clv; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.portlet.PortletPreferences; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.views.ApplicationTemplateManagerService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.reader.ContentReader; import org.exoplatform.wcm.webui.selector.content.UIContentSelector; import org.exoplatform.wcm.webui.selector.content.folder.UIContentBrowsePanelFolder; import org.exoplatform.wcm.webui.selector.content.folder.UIContentSelectorFolder; import org.exoplatform.wcm.webui.selector.content.multi.UIContentBrowsePanelMulti; import org.exoplatform.wcm.webui.selector.content.multi.UIContentSelectorMulti; import org.exoplatform.wcm.webui.selector.page.UIPageSelector; import org.exoplatform.wcm.webui.validator.ZeroNumberValidator; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.Event.Phase; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIFormInputSet; import org.exoplatform.webui.form.UIFormRadioBoxInput; import org.exoplatform.webui.form.UIFormSelectBox; import org.exoplatform.webui.form.UIFormStringInput; import org.exoplatform.webui.form.UIFormTabPane; import org.exoplatform.webui.form.UIFormTextAreaInput; import org.exoplatform.webui.form.ext.UIFormInputSetWithAction; import org.exoplatform.webui.form.input.UICheckBoxInput; import org.exoplatform.webui.form.validator.MandatoryValidator; import org.exoplatform.webui.form.validator.PositiveNumberFormatValidator; /* * Created by The eXo Platform SAS Author : Anh Do Ngoc anh.do@exoplatform.com * Oct 15, 2008 */ /** * The Class UICLVConfig. */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "system:/groovy/ContentListViewer/UICLVConfig.gtmpl", events = { @EventConfig(listeners = UICLVConfig.SaveActionListener.class), @EventConfig(listeners = UICLVConfig.CancelActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UICLVConfig.AddPathActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UICLVConfig.IncreaseActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UICLVConfig.DecreaseActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UICLVConfig.SelectTargetPageActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UICLVConfig.SelectTabActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UICLVConfig.ShowAdvancedBlockActionListener.class, phase = Phase.DECODE) } ) public class UICLVConfig extends UIFormTabPane implements UISelectable { final static public String CONTENT_TAB = "clvContentTab" ; final static public String DISPLAY_TAB = "clvDisplayTab" ; final static public String ADVANCED_TAB = "clvAdvancedTab" ; private static final Log LOG = ExoLogger.getLogger(UICLVConfig.class.getName()); /** The Constant DISPLAY_TRANSLATION_FORM_RADIO_BOX_INPUT. */ public static final String DISPLAY_TRANSLATION_FORM_RADIO_BOX_INPUT = "UICLVConfigCheckTranslationFormCheckboxInput"; /** The Constant DISPLAY_MODE_FORM_RADIO_BOX_INPUT. */ public static final String DISPLAY_MODE_FORM_RADIO_BOX_INPUT = "UICLVConfigDisplayModeFormRadioBoxInput"; /** The Constant ITEM_PATH_FORM_INPUT_SET. */ public final static String ITEM_PATH_FORM_INPUT_SET = "UICLVConfigItemPathFormInputSet"; /** The Constant ITEM_PATH_FORM_STRING_INPUT. */ public final static String ITEM_PATH_FORM_STRING_INPUT = "UICLVConfigItemPathFormStringInput"; /** The Constant ORDER_BY_FORM_SELECT_BOX. */ public static final String ORDER_BY_FORM_SELECT_BOX = "UICLVConfigOrderByFormSelectBox"; /** The Constant ORDER_BY_FORM_SELECT_BOX. */ public static final String ORDER_TYPE_FORM_SELECT_BOX = "UICLVConfigOrderTypeFormSelectBox"; /** The Constant ORDER_TYPE_FORM_RADIO_BOX_INPUT. */ public static final String ORDER_TYPE_FORM_RADIO_BOX_INPUT = "UICLVConfigOrderTypeFormRadioBoxInput"; /** The Constant HEADER_FORM_STRING_INPUT. */ public final static String HEADER_FORM_STRING_INPUT = "UICLVConfigHeaderFormStringInput"; /** The Constant SHOW_AUTOMATIC_DETECTION_CHECKBOX_INPUT. */ public static final String SHOW_AUTOMATIC_DETECTION_CHECKBOX_INPUT = "UICLVConfigShowAutomaticDetectionCheckboxInput"; /** The Constant DISPLAY_TEMPLATE_FORM_SELECT_BOX. */ public final static String DISPLAY_TEMPLATE_FORM_SELECT_BOX = "UICLVConfigDisplayTemplateFormSelectBox"; /** The Constant PAGINATOR_TEMPLATE_FORM_SELECT_BOX. */ public final static String PAGINATOR_TEMPLATE_FORM_SELECT_BOX = "UICLVConfigPaginatorTemplateFormSelectBox"; /** The Constant ITEMS_PER_PAGE_FORM_STRING_INPUT. */ public final static String ITEMS_PER_PAGE_FORM_STRING_INPUT = "UICLVConfigItemsPerPageFormStringInput"; /** The Constant SHOW_TITLE_FORM_CHECKBOX_INPUT. */ public static final String SHOW_TITLE_FORM_CHECKBOX_INPUT = "UICLVConfigShowTitleFormCheckboxInput"; /** The Constant SHOW_HEADER_FORM_CHECKBOX_INPUT. */ public static final String SHOW_HEADER_FORM_CHECKBOX_INPUT = "UICLVConfigShowHeaderFormCheckboxInput"; /** The Constant SHOW_REFRESH_FORM_CHECKBOX_INPUT. */ public final static String SHOW_REFRESH_FORM_CHECKBOX_INPUT = "UICLVConfigShowRefreshFormCheckboxInput"; /** The Constant SHOW_ILLUSTRATION_FORM_CHECKBOX_INPUT. */ /** The Constant SHOW_IMAGE_FORM_CHECKBOX_INPUT. */ public static final String SHOW_ILLUSTRATION_FORM_CHECKBOX_INPUT = "UICLVConfigShowIllustrationFormCheckboxInput"; // public static final String SHOW_IMAGE_FORM_CHECKBOX_INPUT = // "UICLVConfigShowImageFormCheckboxInput"; /** The Constant SHOW_DATE_CREATED_FORM_CHECKBOX_INPUT. */ public static final String SHOW_DATE_CREATED_FORM_CHECKBOX_INPUT = "UICLVConfigShowDateCreatedFormCheckboxInput"; /** The Constant SHOW_MORE_LINK_FORM_CHECKBOX_INPUT. */ public final static String SHOW_READMORE_FORM_CHECKBOX_INPUT = "UICLVConfigShowReadmoreFormCheckboxInput"; // public static final String SHOW_MORE_LINK_FORM_CHECKBOX_INPUT = // "UICLVConfigShowMoreLinkCheckedboxInput"; /** The Constant SHOW_SUMMARY_FORM_CHECKBOX_INPUT. */ public static final String SHOW_SUMMARY_FORM_CHECKBOX_INPUT = "UICLVConfigShowSummaryFormCheckboxInput"; /** The Constant SHOW_LINK_FORM_CHECKBOX_INPUT. */ public static final String SHOW_LINK_FORM_CHECKBOX_INPUT = "UICLVConfigShowLinkFormCheckboxInput"; /** The Constant SHOW_RSSLINK_FORM_CHECKBOX_INPUT. */ public static final String SHOW_RSSLINK_FORM_CHECKBOX_INPUT = "UICLVConfigShowRssLinkFormCheckboxInput"; /** The Constant TARGET_PAGE_FORM_INPUT_SET. */ public final static String TARGET_PAGE_FORM_INPUT_SET = "UICLVConfigTargetPageFormInputSet"; /** The Constant TARGET_PAGE_FORM_STRING_INPUT. */ public final static String TARGET_PAGE_FORM_STRING_INPUT = "UICLVConfigTargetPageFormStringInput"; /** The Constant TARGET_PAGE_SELECTOR_POPUP_WINDOW. */ public final static String TARGET_PAGE_SELECTOR_POPUP_WINDOW = "UICLVConfigTargetPageSelectorPopupWindow"; /** The Constant DYNAMIC_NAVIGATION_LABEL. */ public static final String DYNAMIC_NAVIGATION_LABEL = "UICLVConfigDynamicNavigationLabel"; /** The Constant CONTEXTUAL_FOLDER_RADIOBOX_INPUT. */ public static final String CONTEXTUAL_FOLDER_RADIOBOX_INPUT = "UICLVConfigContextualFolderRadioBoxInput"; /** The Constant SHOW_CLV_BY_STRING_INPUT. */ public static final String SHOW_CLV_BY_STRING_INPUT = "UICLVConfigShowCLVByStringInput"; /** The Constant SHOW_SCV_WITH_STRING_INPUT. */ public static final String SHOW_SCV_WITH_STRING_INPUT = "UICLVConfigshowSCVWithStringInput"; /** The Constant PAGINATOR_TEMPLATE_CATEGORY. */ public final static String PAGINATOR_TEMPLATE_CATEGORY = "paginators"; /** The Constant CACHE_ENABLE_RADIOBOX_INPUT */ public static final String CACHE_ENABLE_RADIOBOX_INPUT = "UICLVConfigCacheEnableRadioBoxInput"; /** The Constant CONTENT_BY_QUERY_TEXT_AREA */ public static final String CONTENT_BY_QUERY_TEXT_AREA = "UICLVConfigContentByQueryTextArea"; /** The Constant WORKSPACE_FORM_SELECT_BOX. */ public final static String WORKSPACE_FORM_SELECT_BOX = "UICLVConfigWorkspaceFormSelectBox"; /** The Constant CACHE_MANAGEMENT_LABEL */ public static final String CACHE_MANAGEMENT_LABEL = "UICLVConfigCacheManagementLabel"; /** The Constant CONTENT_BY_QUERY_LABEL */ public static final String CONTENT_BY_QUERY_LABEL = "UICLVContentByQueryLabel"; /** The Constant DISPLAY_TEMPLATE_CATEGORY. */ public final static String DISPLAY_TEMPLATE_CATEGORY = "navigation"; public final static String DISPLAY_TEMPLATE_LIST = "list"; public final static String TEMPLATE_STORAGE_FOLDER = "content-list-viewer"; public final static String CONTENT_LIST_TYPE = "ContentList"; public final static String CATEGORIES_CONTENT_TYPE = "CategoryContents"; public final static String CATOGORIES_NAVIGATION_TYPE = "CategoryNavigation"; /** The constant values for cache */ public static final String ENABLE_CACHE = "ENABLE"; public static final String DISABLE_CACHE = "DISABLE"; /** The popup id. */ private String popupId; /** The items. */ private List<String> items; private String savedPath; private boolean isShowAdvancedBlock_; private String appType; private String driveName_; public void setSavedPath(String value) { savedPath = value; } public String getSavedPath () { return savedPath; } /** * check if the content in the path is alive and return only alive content * * @return */ public String getAliveSavedPath () { //check if the path is alive if(savedPath != null && !savedPath.isEmpty()){ List<String> tmpItems = new ArrayList<String>(); StringBuffer itemsBuffer = new StringBuffer(); if(savedPath.contains(";")){ tmpItems = Arrays.asList(savedPath.split(";")); } else { tmpItems.add(savedPath); } //only add exist Node for(String item:tmpItems) { try{ if(getRealNode(item) != null){ itemsBuffer.append(item).append(";"); } }catch(RepositoryException e){ if(LOG.isDebugEnabled()){ LOG.debug(e.getMessage()); } } } return itemsBuffer.toString(); } return savedPath; } /** * Gets the popup id. * * @return the popup id */ public String getPopupId() { return popupId; } /** * Sets the popup id. * * @param popupId the new popup id */ public void setPopupId(String popupId) { this.popupId = popupId; } public void setDriveName(String value) { this.driveName_ = value; } public String getDriveName() { return this.driveName_; } /** * Gets the items. * * @return the items */ public List<String> getItems() { String displayMode = ((UIFormRadioBoxInput) findComponentById(UICLVConfig.DISPLAY_MODE_FORM_RADIO_BOX_INPUT)).getValue(); String itemPath = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_ITEM_PATH); if (items == null && UICLVPortlet.DISPLAY_MODE_MANUAL.equals(displayMode) && itemPath != null) { if(itemPath.contains(";")) { List<String> tmpItems = Arrays.asList(itemPath.split(";")); items = new ArrayList<String>(); //only add exist Node for(String item:tmpItems) { try{ Node realNode=getRealNode(item); if(realNode != null){ items.add(item); } }catch(RepositoryException e){ if(LOG.isDebugEnabled()){ LOG.debug(e.getMessage()); } } } } } return items; } /** * Sets the items. * * @param items the new items */ public void setItems(List<String> items) { this.items = items; } public boolean isShowAdvancedBlock() { return isShowAdvancedBlock_; } public void setIsShowAdvancedBlock(boolean value) { isShowAdvancedBlock_ = value; } /** * Instantiates a new uICLV config. * * @throws Exception the exception */ public UICLVConfig() throws Exception { super("UICLVConfig"); PortletPreferences portletPreferences = ((PortletRequestContext) WebuiRequestContext.getCurrentInstance()).getRequest() .getPreferences(); appType = portletPreferences.getValue(UICLVPortlet.PREFERENCE_APPLICATION_TYPE, null); String displayMode = portletPreferences.getValue(UICLVPortlet.PREFERENCE_DISPLAY_MODE, null); boolean addTranslation = Boolean.parseBoolean(portletPreferences.getValue(UICLVPortlet.PREFERENCE_ADD_TRANSLATION, null)); String itemPath = portletPreferences.getValue(UICLVPortlet.PREFERENCE_ITEM_PATH, null); savedPath = itemPath; itemPath = getTitles(savedPath); this.setDriveName(portletPreferences.getValue(UICLVPortlet.PREFERENCE_ITEM_DRIVE, null)); String orderBy = portletPreferences.getValue(UICLVPortlet.PREFERENCE_ORDER_BY, null); String orderType = portletPreferences.getValue(UICLVPortlet.PREFERENCE_ORDER_TYPE, null); String header = portletPreferences.getValue(UICLVPortlet.PREFERENCE_HEADER, null); String displayTemplate = portletPreferences.getValue(UICLVPortlet.PREFERENCE_DISPLAY_TEMPLATE, null); String paginatorTemplate = portletPreferences.getValue(UICLVPortlet.PREFERENCE_PAGINATOR_TEMPLATE, null); String itemsPerPage = portletPreferences.getValue(UICLVPortlet.PREFERENCE_ITEMS_PER_PAGE, null); String contextualFolderMode = portletPreferences.getValue(UICLVPortlet.PREFERENCE_CONTEXTUAL_FOLDER, null); String showClvBy = portletPreferences.getValue(UICLVPortlet.PREFERENCE_SHOW_CLV_BY, null); String targetPage = portletPreferences.getValue(UICLVPortlet.PREFERENCE_TARGET_PAGE, null); String showScvWith = portletPreferences.getValue(UICLVPortlet.PREFERENCE_SHOW_SCV_WITH, null); String isCacheEnabled = portletPreferences.getValue(UICLVPortlet.PREFERENCE_CACHE_ENABLED, null); String workspace = portletPreferences.getValue(UICLVPortlet.PREFERENCE_WORKSPACE, null); String contentByQuery = portletPreferences.getValue(UICLVPortlet.PREFERENCE_CONTENTS_BY_QUERY, null); boolean showAutomaticDetection = Boolean.parseBoolean(portletPreferences.getValue( UICLVPortlet.PREFERENCE_AUTOMATIC_DETECTION,null)); boolean showTitle = Boolean.parseBoolean(portletPreferences.getValue(UICLVPortlet.PREFERENCE_SHOW_TITLE, null)); boolean showHeader = Boolean.parseBoolean(portletPreferences.getValue(UICLVPortlet.PREFERENCE_SHOW_HEADER, null)); boolean showRefresh = Boolean.parseBoolean(portletPreferences.getValue(UICLVPortlet.PREFERENCE_SHOW_REFRESH_BUTTON, null)); boolean showImage = Boolean.parseBoolean(portletPreferences.getValue(UICLVPortlet.PREFERENCE_SHOW_ILLUSTRATION, null)); boolean showDateCreated = Boolean.parseBoolean(portletPreferences.getValue(UICLVPortlet.PREFERENCE_SHOW_DATE_CREATED, null)); boolean showReadmore = Boolean.parseBoolean(portletPreferences.getValue(UICLVPortlet.PREFERENCE_SHOW_READMORE, null)); boolean showSummary = Boolean.parseBoolean(portletPreferences.getValue(UICLVPortlet.PREFERENCE_SHOW_SUMMARY, null)); boolean showLink = Boolean.parseBoolean(portletPreferences.getValue(UICLVPortlet.PREFERENCE_SHOW_LINK, null)); boolean showRssLink = Boolean.parseBoolean(portletPreferences.getValue(UICLVPortlet.PREFERENCE_SHOW_RSSLINK, null)); /** DISPLAY MODE */ List<SelectItemOption<String>> displayModeOptions = new ArrayList<SelectItemOption<String>>(); displayModeOptions.add(new SelectItemOption<String>(UICLVPortlet.DISPLAY_MODE_AUTOMATIC, UICLVPortlet.DISPLAY_MODE_AUTOMATIC)); displayModeOptions.add(new SelectItemOption<String>(UICLVPortlet.DISPLAY_MODE_MANUAL, UICLVPortlet.DISPLAY_MODE_MANUAL)); UIFormRadioBoxInput displayModeRadioBoxInput = new UIFormRadioBoxInput(DISPLAY_MODE_FORM_RADIO_BOX_INPUT, DISPLAY_MODE_FORM_RADIO_BOX_INPUT, displayModeOptions); displayModeRadioBoxInput.setValue(displayMode); /** ACTIVATE TRANSLATION */ UICheckBoxInput addTranslationCheckbox = new UICheckBoxInput(DISPLAY_TRANSLATION_FORM_RADIO_BOX_INPUT , DISPLAY_TRANSLATION_FORM_RADIO_BOX_INPUT, null); addTranslationCheckbox.setChecked(addTranslation); /** ITEM PATH */ UIFormStringInput itemPathInput = new UIFormStringInput(ITEM_PATH_FORM_STRING_INPUT, ITEM_PATH_FORM_STRING_INPUT, itemPath); itemPathInput.setReadOnly(true); itemPathInput.addValidator(MandatoryValidator.class); UIFormInputSetWithAction itemPathInputSet = new UIFormInputSetWithAction(ITEM_PATH_FORM_INPUT_SET); itemPathInputSet.setActionInfo(ITEM_PATH_FORM_STRING_INPUT, new String[] { "AddPath" }) ; itemPathInputSet.addUIFormInput(itemPathInput); /** ORDER BY */ List<SelectItemOption<String>> orderByOptions = new ArrayList<SelectItemOption<String>>(); orderByOptions.add(new SelectItemOption<String>(UICLVPortlet.ORDER_BY_TITLE, NodetypeConstant.EXO_TITLE)); orderByOptions.add(new SelectItemOption<String>(UICLVPortlet.ORDER_BY_DATE_CREATED, NodetypeConstant.EXO_DATE_CREATED)); orderByOptions.add(new SelectItemOption<String>(UICLVPortlet.ORDER_BY_DATE_MODIFIED, NodetypeConstant.EXO_LAST_MODIFIED_DATE)); orderByOptions.add(new SelectItemOption<String>(UICLVPortlet.ORDER_BY_DATE_PUBLISHED, NodetypeConstant.PUBLICATION_LIVE_DATE)); orderByOptions.add(new SelectItemOption<String>(UICLVPortlet.ORDER_BY_DATE_START_EVENT, NodetypeConstant.EXO_START_EVENT)); orderByOptions.add(new SelectItemOption<String>(UICLVPortlet.ORDER_BY_INDEX, NodetypeConstant.EXO_INDEX)); UIFormSelectBox orderBySelectBox = new UIFormSelectBox(ORDER_BY_FORM_SELECT_BOX, ORDER_BY_FORM_SELECT_BOX, orderByOptions); orderBySelectBox.setValue(orderBy); /** ORDER TYPE */ List<SelectItemOption<String>> orderTypeOptions = new ArrayList<SelectItemOption<String>>(); orderTypeOptions.add(new SelectItemOption<String>(UICLVPortlet.ORDER_TYPE_DESCENDENT, "DESC")); orderTypeOptions.add(new SelectItemOption<String>(UICLVPortlet.ORDER_TYPE_ASCENDENT, "ASC")); UIFormRadioBoxInput orderTypeRadioBoxInput = new UIFormRadioBoxInput(ORDER_TYPE_FORM_RADIO_BOX_INPUT, ORDER_TYPE_FORM_RADIO_BOX_INPUT, orderTypeOptions); UIFormSelectBox orderTypeSelectBox = new UIFormSelectBox(ORDER_TYPE_FORM_SELECT_BOX, ORDER_TYPE_FORM_SELECT_BOX, orderTypeOptions); orderTypeSelectBox.setValue(orderType); //orderTypeRadioBoxInput.setValue(orderType); /** HEADER */ UIFormStringInput headerInput = new UIFormStringInput(HEADER_FORM_STRING_INPUT, HEADER_FORM_STRING_INPUT, header); /** AUTOMATIC DETECTION */ UICheckBoxInput showAutomaticDetectionCheckBox = new UICheckBoxInput(SHOW_AUTOMATIC_DETECTION_CHECKBOX_INPUT, SHOW_AUTOMATIC_DETECTION_CHECKBOX_INPUT, null); showAutomaticDetectionCheckBox.setChecked(showAutomaticDetection); List<SelectItemOption<String>> formViewerTemplateList = new ArrayList<SelectItemOption<String>>(); /** DISPLAY TEMPLATE */ List<SelectItemOption<String>> viewerTemplateList = new ArrayList<SelectItemOption<String>>(); if (appType.equals(CONTENT_LIST_TYPE) || appType.equals(CATEGORIES_CONTENT_TYPE) || appType.equals(UICLVPortlet.APPLICATION_CLV_BY_QUERY)) { viewerTemplateList.addAll(getTemplateList(TEMPLATE_STORAGE_FOLDER, DISPLAY_TEMPLATE_LIST)); } if (appType.equals(CONTENT_LIST_TYPE) || appType.equals(CATOGORIES_NAVIGATION_TYPE)) { viewerTemplateList.addAll(getTemplateList(TEMPLATE_STORAGE_FOLDER, DISPLAY_TEMPLATE_CATEGORY)); } Collections.sort(viewerTemplateList, new TemplateNameComparator()); formViewerTemplateList.addAll(viewerTemplateList); UIFormSelectBox formViewTemplateSelector = new UIFormSelectBox(DISPLAY_TEMPLATE_FORM_SELECT_BOX, DISPLAY_TEMPLATE_FORM_SELECT_BOX, formViewerTemplateList); formViewTemplateSelector.setValue(displayTemplate); /** PAGINATOR TEMPLATE */ List<SelectItemOption<String>> paginatorTemplateList = getTemplateList(TEMPLATE_STORAGE_FOLDER, PAGINATOR_TEMPLATE_CATEGORY); Collections.sort(paginatorTemplateList, new TemplateNameComparator()); UIFormSelectBox paginatorTemplateSelector = new UIFormSelectBox(PAGINATOR_TEMPLATE_FORM_SELECT_BOX, PAGINATOR_TEMPLATE_FORM_SELECT_BOX, paginatorTemplateList); paginatorTemplateSelector.setValue(paginatorTemplate); /** ITEMS PER PAGE */ UIFormStringInput itemsPerPageStringInput = new UIFormStringInput(ITEMS_PER_PAGE_FORM_STRING_INPUT, ITEMS_PER_PAGE_FORM_STRING_INPUT, itemsPerPage); itemsPerPageStringInput.addValidator(MandatoryValidator.class); itemsPerPageStringInput.addValidator(ZeroNumberValidator.class); itemsPerPageStringInput.addValidator(PositiveNumberFormatValidator.class); itemsPerPageStringInput.setMaxLength(3); /** SHOW TITLE */ UICheckBoxInput showTitleCheckbox = new UICheckBoxInput(SHOW_TITLE_FORM_CHECKBOX_INPUT, SHOW_TITLE_FORM_CHECKBOX_INPUT, null); showTitleCheckbox.setChecked(showTitle); /** SHOW HEADER */ UICheckBoxInput showHeaderCheckBox = new UICheckBoxInput(SHOW_HEADER_FORM_CHECKBOX_INPUT, SHOW_HEADER_FORM_CHECKBOX_INPUT, null); showHeaderCheckBox.setChecked(showHeader); /** SHOW REFRESH */ UICheckBoxInput showRefreshCheckbox = new UICheckBoxInput(SHOW_REFRESH_FORM_CHECKBOX_INPUT, SHOW_REFRESH_FORM_CHECKBOX_INPUT, null); showRefreshCheckbox.setChecked(showRefresh); /** SHOW_IMAGE */ UICheckBoxInput showImageCheckbox = new UICheckBoxInput(SHOW_ILLUSTRATION_FORM_CHECKBOX_INPUT, SHOW_ILLUSTRATION_FORM_CHECKBOX_INPUT, null); showImageCheckbox.setChecked(showImage); /** SHOW DATE CREATED */ UICheckBoxInput showDateCreatedCheckbox = new UICheckBoxInput(SHOW_DATE_CREATED_FORM_CHECKBOX_INPUT, SHOW_DATE_CREATED_FORM_CHECKBOX_INPUT, null); showDateCreatedCheckbox.setChecked(showDateCreated); /** SHOW MORE LINK */ UICheckBoxInput showMoreLinkCheckbox = new UICheckBoxInput(SHOW_READMORE_FORM_CHECKBOX_INPUT, SHOW_READMORE_FORM_CHECKBOX_INPUT, null); showMoreLinkCheckbox.setChecked(showReadmore); /** SHOW SUMMARY */ UICheckBoxInput showSummaryCheckbox = new UICheckBoxInput(SHOW_SUMMARY_FORM_CHECKBOX_INPUT, SHOW_SUMMARY_FORM_CHECKBOX_INPUT, null); showSummaryCheckbox.setChecked(showSummary); /** SHOW LINK */ UICheckBoxInput showLinkCheckbox = new UICheckBoxInput(SHOW_LINK_FORM_CHECKBOX_INPUT, SHOW_LINK_FORM_CHECKBOX_INPUT, null); showLinkCheckbox.setChecked(showLink); /** SHOW RSS LINK */ UICheckBoxInput showRssLinkCheckbox = new UICheckBoxInput(SHOW_RSSLINK_FORM_CHECKBOX_INPUT, SHOW_RSSLINK_FORM_CHECKBOX_INPUT, null); showRssLinkCheckbox.setChecked(showRssLink); /** CONTEXTUAL FOLDER */ List<SelectItemOption<String>> contextualFolderOptions = new ArrayList<SelectItemOption<String>>(); contextualFolderOptions.add(new SelectItemOption<String>(UICLVPortlet.PREFERENCE_CONTEXTUAL_FOLDER_ENABLE, UICLVPortlet.PREFERENCE_CONTEXTUAL_FOLDER_ENABLE)); contextualFolderOptions.add(new SelectItemOption<String>(UICLVPortlet.PREFERENCE_CONTEXTUAL_FOLDER_DISABLE, UICLVPortlet.PREFERENCE_CONTEXTUAL_FOLDER_DISABLE)); UIFormRadioBoxInput contextualFolderRadioBoxInput = new UIFormRadioBoxInput(CONTEXTUAL_FOLDER_RADIOBOX_INPUT, CONTEXTUAL_FOLDER_RADIOBOX_INPUT, contextualFolderOptions); contextualFolderRadioBoxInput.setValue(contextualFolderMode); /** SHOW CLV BY */ UIFormStringInput showClvByInput = new UIFormStringInput(SHOW_CLV_BY_STRING_INPUT, SHOW_CLV_BY_STRING_INPUT, showClvBy); /** TARGET PAGE */ UIFormInputSetWithAction targetPageInputSet = new UIFormInputSetWithAction(TARGET_PAGE_FORM_INPUT_SET); UIFormStringInput basePathInput = new UIFormStringInput(TARGET_PAGE_FORM_STRING_INPUT, TARGET_PAGE_FORM_STRING_INPUT, targetPage); basePathInput.setValue(targetPage); basePathInput.setReadOnly(true); targetPageInputSet.setActionInfo(TARGET_PAGE_FORM_STRING_INPUT, new String[] {"SelectTargetPage"}) ; targetPageInputSet.addUIFormInput(basePathInput); /** CACHE MODE */ List<SelectItemOption<String>> cacheOptions = new ArrayList<SelectItemOption<String>>(); cacheOptions.add(new SelectItemOption<String>(ENABLE_CACHE, ENABLE_CACHE)); cacheOptions.add(new SelectItemOption<String>(DISABLE_CACHE, DISABLE_CACHE)); UIFormRadioBoxInput cacheEnableRadioBoxInput = new UIFormRadioBoxInput(CACHE_ENABLE_RADIOBOX_INPUT, CACHE_ENABLE_RADIOBOX_INPUT, cacheOptions); cacheEnableRadioBoxInput.setValue("true".equals(isCacheEnabled)? ENABLE_CACHE : DISABLE_CACHE); /** WORKSPACE */ List<SelectItemOption<String>> workspaceOptions = new ArrayList<SelectItemOption<String>>(); String[] workspaceList = WCMCoreUtils.getRepository().getWorkspaceNames(); for (String wkspace : workspaceList) { workspaceOptions.add(new SelectItemOption<String>(wkspace, wkspace)); } UIFormSelectBox workspaceSelector = new UIFormSelectBox(WORKSPACE_FORM_SELECT_BOX, WORKSPACE_FORM_SELECT_BOX, workspaceOptions); workspaceSelector.setValue(workspace); /** CONTENT BY QUERY */ UIFormTextAreaInput queryTextAreaInput = new UIFormTextAreaInput(CONTENT_BY_QUERY_TEXT_AREA, CONTENT_BY_QUERY_TEXT_AREA, contentByQuery); /** ALLOW DYNAMIC URL */ UIFormStringInput showScvWithInput = new UIFormStringInput(SHOW_SCV_WITH_STRING_INPUT, SHOW_SCV_WITH_STRING_INPUT, showScvWith); if (appType.equals(CATOGORIES_NAVIGATION_TYPE)) { //Disable option displayModeRadioBoxInput.setDisabled(true); showAutomaticDetectionCheckBox.setDisabled(true); showImageCheckbox.setDisabled(true); showSummaryCheckbox.setDisabled(true); showDateCreatedCheckbox.setDisabled(true); showLinkCheckbox.setDisabled(true); showRefreshCheckbox.setDisabled(true); showMoreLinkCheckbox.setDisabled(true); showRssLinkCheckbox.setDisabled(true); showScvWithInput.setDisabled(true); } UIFormInputSet uiCLVContentTab = new UIFormInputSet(CONTENT_TAB) ; uiCLVContentTab.addUIFormInput(displayModeRadioBoxInput); uiCLVContentTab.addUIFormInput((UIFormInputSet)itemPathInputSet); uiCLVContentTab.addUIFormInput(orderBySelectBox); uiCLVContentTab.addUIFormInput(orderTypeSelectBox); uiCLVContentTab.addUIFormInput(orderTypeRadioBoxInput); uiCLVContentTab.addUIFormInput(addTranslationCheckbox); setSelectedTab(CONTENT_TAB); addUIComponentInput(uiCLVContentTab) ; UIFormInputSet uiCLVDisplayTab = new UIFormInputSet(DISPLAY_TAB) ; uiCLVDisplayTab.addUIFormInput(headerInput); uiCLVDisplayTab.addUIFormInput(showAutomaticDetectionCheckBox); uiCLVDisplayTab.addUIFormInput(formViewTemplateSelector); uiCLVDisplayTab.addUIFormInput(paginatorTemplateSelector); uiCLVDisplayTab.addUIFormInput(itemsPerPageStringInput); uiCLVDisplayTab.addUIFormInput(showTitleCheckbox); uiCLVDisplayTab.addUIFormInput(showHeaderCheckBox); uiCLVDisplayTab.addUIFormInput(showRefreshCheckbox); uiCLVDisplayTab.addUIFormInput(showImageCheckbox); uiCLVDisplayTab.addUIFormInput(showDateCreatedCheckbox); uiCLVDisplayTab.addUIFormInput(showMoreLinkCheckbox); uiCLVDisplayTab.addUIFormInput(showSummaryCheckbox); uiCLVDisplayTab.addUIFormInput(showLinkCheckbox); uiCLVDisplayTab.addUIFormInput(showRssLinkCheckbox); addUIComponentInput(uiCLVDisplayTab) ; UIFormInputSet uiCLVAdvancedTab = new UIFormInputSet(ADVANCED_TAB) ; uiCLVAdvancedTab.addUIFormInput(contextualFolderRadioBoxInput); uiCLVAdvancedTab.addUIFormInput(showClvByInput); uiCLVAdvancedTab.addUIFormInput((UIFormInputSet)targetPageInputSet); uiCLVAdvancedTab.addUIFormInput(showScvWithInput); uiCLVAdvancedTab.addUIFormInput(cacheEnableRadioBoxInput); if (this.isContentListByQuery()) { uiCLVAdvancedTab.addUIFormInput(workspaceSelector); uiCLVAdvancedTab.addUIFormInput(queryTextAreaInput); } addUIComponentInput(uiCLVAdvancedTab) ; if ((contextualFolderMode != null && contextualFolderMode.equals(UICLVPortlet.PREFERENCE_CONTEXTUAL_FOLDER_ENABLE)) || this.isContentListByQuery()) { isShowAdvancedBlock_ = true; } else { isShowAdvancedBlock_ = false; } setActions(new String[] { "Save", "Cancel" }); } /** * Gets the template list. * * @param portletName the portlet name * @param category the category * @return the template list * @throws Exception the exception */ private List<SelectItemOption<String>> getTemplateList(String portletName, String category) throws Exception { List<SelectItemOption<String>> templateOptionList = new ArrayList<SelectItemOption<String>>(); ApplicationTemplateManagerService templateManagerService = getApplicationComponent(ApplicationTemplateManagerService.class); List<Node> templateNodeList = templateManagerService.getTemplatesByCategory(portletName, category, WCMCoreUtils.getSystemSessionProvider()); for (Node templateNode : templateNodeList) { SelectItemOption<String> template = new SelectItemOption<String>(); template.setLabel(templateNode.getName()); template.setValue(templateNode.getPath()); templateOptionList.add(template); } return templateOptionList; } public boolean isCategoriesNavigation() { return appType.equals(CATOGORIES_NAVIGATION_TYPE); } /** * * @return True if is a CLV by Query */ public boolean isContentListByQuery() { return appType.equals(UICLVPortlet.APPLICATION_CLV_BY_QUERY); } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.selector.UISelectable#doSelect(java.lang.String, java.lang.Object) */ public void doSelect(String selectField, Object value) throws Exception { if (selectField != null && value != null) { String sValue = (String) value; String titles=""; String displayMode = ((UIFormRadioBoxInput) findComponentById(UICLVConfig.DISPLAY_MODE_FORM_RADIO_BOX_INPUT)).getValue(); if (ITEM_PATH_FORM_STRING_INPUT.equals(selectField) && UICLVPortlet.DISPLAY_MODE_MANUAL.equals(displayMode)) { items = Arrays.asList(sValue.split(";")); titles = getTitles(sValue); savedPath = sValue; getUIStringInput(selectField).setValue(titles); } else if (TARGET_PAGE_FORM_STRING_INPUT.equals(selectField)){ getUIStringInput(selectField).setValue(sValue); }else { items = new ArrayList<String>(); String[] values = sValue.split(":"); if (values.length == 4) { this.setDriveName(values[0]); //check if drive is selected instead of folder ManageDriveService managerDriveService = this.getApplicationComponent(ManageDriveService.class); for (DriveData data : managerDriveService.getAllDrives()) { if (data.getHomePath().equals(values[3])) { this.setDriveName(data.getName()); } } sValue = sValue.substring(values[0].length() + 1); } titles = getTitle(sValue); getUIStringInput(selectField).setValue(titles); savedPath = sValue; } } Utils.closePopupWindow(this, popupId); } private String getTitles(String itemPath) throws RepositoryException { if (itemPath == null || itemPath.length() == 0) return ""; StringBuffer titles = new StringBuffer(); List<String> tmpItems; tmpItems = Arrays.asList(itemPath.split(";")); for (String item : tmpItems) { String title = getTitle(item); if (title != null) { if (titles.length() > 0) { titles.append(";").append(title); } else { titles.append(title); } } } return titles.toString(); } /** * * get the realnode with a path * @param itemPath * @return the realnode. null if the path is not ok */ private Node getRealNode(String itemPath) throws RepositoryException{ String strRepository, strWorkspace, strIdentifier; int repoIndex, wsIndex; if (itemPath==null || itemPath.length() == 0) return null; repoIndex = itemPath.indexOf(':'); wsIndex = itemPath.lastIndexOf(':'); strRepository = itemPath.substring(0, repoIndex); strWorkspace = itemPath.substring(repoIndex+1, wsIndex); strIdentifier = itemPath.substring(wsIndex +1); Node selectedNode = Utils.getRealNode(Text.escapeIllegalJcrChars(strRepository), Text.escapeIllegalJcrChars(strWorkspace), Text.escapeIllegalJcrChars(strIdentifier), false); return selectedNode; } /** * * @param itemPath The path * @return The title * @throws RepositoryException */ private String getTitle(String itemPath) throws RepositoryException { Node selectedNode = getRealNode(itemPath); if (selectedNode==null) return null; String title = null; if (selectedNode.hasProperty("exo:title")) { title = selectedNode.getProperty("exo:title").getValue().getString(); } if (selectedNode.hasNode("jcr:content")) { Node content = selectedNode.getNode("jcr:content"); if (content.hasProperty("dc:title")) { try { title = content.getProperty("dc:title").getValues()[0].getString(); } catch (PathNotFoundException e) { title = null; } catch (RepositoryException e) { title = null; } catch (IndexOutOfBoundsException e) { title = null; } } } if (title==null) title = selectedNode.getName(); return ContentReader.getUnescapeIllegalJcrContent(title); } /** * The listener interface for receiving saveAction events. * The class that is interested in processing a saveAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSaveActionListener</code> method. When * the saveAction event occurs, that object's appropriate * method is invoked. */ public static class SaveActionListener extends EventListener<UICLVConfig> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICLVConfig> event) throws Exception { UICLVConfig clvConfig = event.getSource(); /** GET VALUES FROM UIFORM */ String displayMode = ((UIFormRadioBoxInput) clvConfig.findComponentById( UICLVConfig.DISPLAY_MODE_FORM_RADIO_BOX_INPUT)).getValue(); String itemPath = clvConfig.getSavedPath(); if (itemPath == null || itemPath.length() == 0 || (itemPath.contains(";") && displayMode.equals(UICLVPortlet.DISPLAY_MODE_AUTOMATIC)) || (!itemPath.contains(";") && displayMode.equals(UICLVPortlet.DISPLAY_MODE_MANUAL))) { Utils.createPopupMessage(clvConfig, "UICLVConfig.msg.not-valid-path", null, ApplicationMessage.WARNING); WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); requestContext.addUIComponentToUpdateByAjax(clvConfig); return; } String orderBy = clvConfig.getUIFormSelectBox(ORDER_BY_FORM_SELECT_BOX).getValue(); String orderType = clvConfig.getUIFormSelectBox(ORDER_TYPE_FORM_SELECT_BOX).getValue(); String addTranslation = clvConfig.getUICheckBoxInput(UICLVConfig.DISPLAY_TRANSLATION_FORM_RADIO_BOX_INPUT) .isChecked() ? "true" : "false"; String header = clvConfig.getUIStringInput(UICLVConfig.HEADER_FORM_STRING_INPUT).getValue(); if (header == null) header = ""; String showAutomaticDetection = clvConfig.getUICheckBoxInput(UICLVConfig.SHOW_AUTOMATIC_DETECTION_CHECKBOX_INPUT) .isChecked() ? "true" : "false"; String displayTemplate = clvConfig.getUIFormSelectBox(UICLVConfig.DISPLAY_TEMPLATE_FORM_SELECT_BOX).getValue(); String paginatorTemplate = clvConfig.getUIFormSelectBox(UICLVConfig.PAGINATOR_TEMPLATE_FORM_SELECT_BOX).getValue(); String itemsPerPage = clvConfig.getUIStringInput(UICLVConfig.ITEMS_PER_PAGE_FORM_STRING_INPUT).getValue(); String showTitle = clvConfig.getUICheckBoxInput(UICLVConfig.SHOW_TITLE_FORM_CHECKBOX_INPUT) .isChecked() ? "true" : "false"; String showHeader = clvConfig.getUICheckBoxInput(UICLVConfig.SHOW_HEADER_FORM_CHECKBOX_INPUT) .isChecked() ? "true" : "false"; String showRefresh = clvConfig.getUICheckBoxInput(UICLVConfig.SHOW_REFRESH_FORM_CHECKBOX_INPUT) .isChecked() ? "true" : "false"; String showImage = clvConfig.getUICheckBoxInput(UICLVConfig.SHOW_ILLUSTRATION_FORM_CHECKBOX_INPUT) .isChecked() ? "true" : "false"; String showDateCreated = clvConfig.getUICheckBoxInput(UICLVConfig.SHOW_DATE_CREATED_FORM_CHECKBOX_INPUT) .isChecked() ? "true" : "false"; String showMoreLink = clvConfig.getUICheckBoxInput(UICLVConfig.SHOW_READMORE_FORM_CHECKBOX_INPUT) .isChecked() ? "true" : "false"; String showSummary = clvConfig.getUICheckBoxInput(UICLVConfig.SHOW_SUMMARY_FORM_CHECKBOX_INPUT) .isChecked() ? "true" : "false"; String showLink = clvConfig.getUICheckBoxInput(UICLVConfig.SHOW_LINK_FORM_CHECKBOX_INPUT) .isChecked() ? "true" : "false"; String showRssLink = clvConfig.getUICheckBoxInput(UICLVConfig.SHOW_RSSLINK_FORM_CHECKBOX_INPUT) .isChecked() ? "true" : "false"; String contextualFolderMode = ((UIFormRadioBoxInput) clvConfig.findComponentById( UICLVConfig.CONTEXTUAL_FOLDER_RADIOBOX_INPUT)).getValue(); String showClvBy = clvConfig.getUIStringInput(UICLVConfig.SHOW_CLV_BY_STRING_INPUT).getValue(); if (showClvBy == null || showClvBy.length() == 0) showClvBy = UICLVPortlet.DEFAULT_SHOW_CLV_BY; String targetPage = clvConfig.getUIStringInput(UICLVConfig.TARGET_PAGE_FORM_STRING_INPUT).getValue(); String showScvWith = clvConfig.getUIStringInput(UICLVConfig.SHOW_SCV_WITH_STRING_INPUT).getValue(); if (showScvWith == null || showScvWith.length() == 0) showScvWith = UICLVPortlet.DEFAULT_SHOW_SCV_WITH; String cacheEnabled = ((UIFormRadioBoxInput) clvConfig. findComponentById(UICLVConfig.CACHE_ENABLE_RADIOBOX_INPUT)).getValue(); /** SET VALUES TO PREFERENCES */ PortletRequestContext portletRequestContext = (PortletRequestContext) event.getRequestContext(); PortletPreferences portletPreferences = portletRequestContext.getRequest().getPreferences(); portletPreferences.setValue(UICLVPortlet.PREFERENCE_DISPLAY_MODE, displayMode); portletPreferences.setValue(UICLVPortlet.PREFERENCE_ITEM_PATH, itemPath); portletPreferences.setValue(UICLVPortlet.PREFERENCE_ITEM_DRIVE, clvConfig.getDriveName()); portletPreferences.setValue(UICLVPortlet.PREFERENCE_ORDER_BY, orderBy); portletPreferences.setValue(UICLVPortlet.PREFERENCE_ORDER_TYPE, orderType); portletPreferences.setValue(UICLVPortlet.PREFERENCE_ADD_TRANSLATION, addTranslation); portletPreferences.setValue(UICLVPortlet.PREFERENCE_HEADER, header); portletPreferences.setValue(UICLVPortlet.PREFERENCE_AUTOMATIC_DETECTION, showAutomaticDetection); portletPreferences.setValue(UICLVPortlet.PREFERENCE_DISPLAY_TEMPLATE, displayTemplate); portletPreferences.setValue(UICLVPortlet.PREFERENCE_PAGINATOR_TEMPLATE, paginatorTemplate); portletPreferences.setValue(UICLVPortlet.PREFERENCE_ITEMS_PER_PAGE, itemsPerPage); portletPreferences.setValue(UICLVPortlet.PREFERENCE_SHOW_TITLE, showTitle); portletPreferences.setValue(UICLVPortlet.PREFERENCE_SHOW_HEADER, showHeader); portletPreferences.setValue(UICLVPortlet.PREFERENCE_SHOW_REFRESH_BUTTON, showRefresh); portletPreferences.setValue(UICLVPortlet.PREFERENCE_SHOW_ILLUSTRATION, showImage); portletPreferences.setValue(UICLVPortlet.PREFERENCE_SHOW_DATE_CREATED, showDateCreated); portletPreferences.setValue(UICLVPortlet.PREFERENCE_SHOW_READMORE, showMoreLink); portletPreferences.setValue(UICLVPortlet.PREFERENCE_SHOW_SUMMARY, showSummary); portletPreferences.setValue(UICLVPortlet.PREFERENCE_SHOW_LINK, showLink); portletPreferences.setValue(UICLVPortlet.PREFERENCE_SHOW_RSSLINK, showRssLink); portletPreferences.setValue(UICLVPortlet.PREFERENCE_CONTEXTUAL_FOLDER, contextualFolderMode); portletPreferences.setValue(UICLVPortlet.PREFERENCE_SHOW_CLV_BY, showClvBy); portletPreferences.setValue(UICLVPortlet.PREFERENCE_TARGET_PAGE, targetPage); portletPreferences.setValue(UICLVPortlet.PREFERENCE_SHOW_SCV_WITH, showScvWith); portletPreferences.setValue(UICLVPortlet.PREFERENCE_CACHE_ENABLED, ENABLE_CACHE.equals(cacheEnabled)?"true":"false"); String appType = portletPreferences.getValue(UICLVPortlet.PREFERENCE_APPLICATION_TYPE, null); if (UICLVPortlet.APPLICATION_CLV_BY_QUERY.equals(appType)) { String workspace = ((UIFormSelectBox)clvConfig.findComponentById(UICLVConfig.WORKSPACE_FORM_SELECT_BOX)).getValue(); String query = ((UIFormTextAreaInput) clvConfig.findComponentById(UICLVConfig.CONTENT_BY_QUERY_TEXT_AREA)).getValue(); if (query == null) { query = ""; } portletPreferences.setValue(UICLVPortlet.PREFERENCE_WORKSPACE, workspace); portletPreferences.setValue(UICLVPortlet.PREFERENCE_CONTENTS_BY_QUERY, query); } portletPreferences.store(); UICLVPortlet portlet = clvConfig.getAncestorOfType(UICLVPortlet.class); if (Utils.isPortalEditMode()) { portlet.updatePortlet(); } else { if (clvConfig.getModeInternal()) { portlet.changeToViewMode(); }else { Utils.closePopupWindow(clvConfig, "UIViewerManagementPopupWindow"); portlet.updatePortlet(); } } } } /** * The listener interface for receiving cancelAction events. * The class that is interested in processing a cancelAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addCancelActionListener</code> method. When * the cancelAction event occurs, that object's appropriate * method is invoked. */ public static class CancelActionListener extends EventListener<UICLVConfig> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICLVConfig> event) throws Exception { UICLVConfig clvConfig = event.getSource(); if (!Utils.isPortalEditMode()) { if (clvConfig.getModeInternal()) { UICLVPortlet portlet = clvConfig.getAncestorOfType(UICLVPortlet.class); portlet.changeToViewMode(); }else { Utils.closePopupWindow(clvConfig, "UIViewerManagementPopupWindow"); } } } } /** * The listener interface for receiving selectTabAction events. * The class that is interested in processing a selectTabAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSelectTabActionListener</code> method. When * the selectTabAction event occurs, that object's appropriate * method is invoked. */ static public class SelectTabActionListener extends EventListener<UICLVConfig> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICLVConfig> event) throws Exception { WebuiRequestContext context = event.getRequestContext(); String renderTab = context.getRequestParameter(UIComponent.OBJECTID); if (renderTab == null) { return; } event.getSource().setSelectedTab(renderTab); event.getRequestContext().addUIComponentToUpdateByAjax(event.getSource()); } } /** * The listener interface for receiving selectFolderPathAction events. * The class that is interested in processing a selectFolderPathAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSelectFolderPathActionListener</code> method. When * the selectFolderPathAction event occurs, that object's appropriate * method is invoked. */ public static class AddPathActionListener extends EventListener<UICLVConfig> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICLVConfig> event) throws Exception { UICLVConfig clvConfig = event.getSource(); UIFormRadioBoxInput modeBoxInput = (UIFormRadioBoxInput) clvConfig.findComponentById( UICLVConfig.DISPLAY_MODE_FORM_RADIO_BOX_INPUT); String mode = modeBoxInput.getValue(); if (mode.equals(UICLVPortlet.DISPLAY_MODE_AUTOMATIC)) { UIContentSelectorFolder contentSelector = clvConfig.createUIComponent(UIContentSelectorFolder.class, null, null); UIContentBrowsePanelFolder folderContentSelector= contentSelector.getChild(UIContentBrowsePanelFolder.class); String location = clvConfig.getSavedPath(); String[] locations = (location == null) ? null : location.split(":"); Node node = (locations != null && locations.length >= 3) ? Utils.getViewableNodeByComposer(locations[0], locations[1], locations[2]) : null; contentSelector.init(clvConfig.getDriveName(), fixPath(node == null ? "" : node.getPath(), clvConfig, (locations != null && locations.length > 0) ? locations[0] : null)); folderContentSelector.setSourceComponent(clvConfig, new String[] { UICLVConfig.ITEM_PATH_FORM_STRING_INPUT }); Utils.createPopupWindow(clvConfig, contentSelector, UIContentSelector.FOLDER_PATH_SELECTOR_POPUP_WINDOW, 800); clvConfig.setPopupId(UIContentSelector.FOLDER_PATH_SELECTOR_POPUP_WINDOW); } else { UIContentSelectorMulti contentSelector = clvConfig.createUIComponent(UIContentSelectorMulti.class, null, null); UIContentBrowsePanelMulti multiContentSelector= contentSelector.getChild(UIContentBrowsePanelMulti.class); multiContentSelector.setSourceComponent(clvConfig, new String[] { UICLVConfig.ITEM_PATH_FORM_STRING_INPUT }); String itemPath = clvConfig.getSavedPath(); if (itemPath != null && itemPath.contains(";")) multiContentSelector.setItemPaths(itemPath); contentSelector.init(); Utils.createPopupWindow(clvConfig, contentSelector, UIContentSelector.CORRECT_CONTENT_SELECTOR_POPUP_WINDOW, 800); clvConfig.setPopupId(UIContentSelector.CORRECT_CONTENT_SELECTOR_POPUP_WINDOW); } } private String fixPath(String path, UICLVConfig clvConfig, String repository) throws Exception { if (path == null || path.length() == 0 || repository == null || repository.length() == 0 || clvConfig.getDriveName() == null || clvConfig.getDriveName().length() == 0) return ""; ManageDriveService managerDriveService = clvConfig.getApplicationComponent(ManageDriveService.class); DriveData driveData = managerDriveService.getDriveByName(clvConfig.getDriveName()); if (!path.startsWith(driveData.getHomePath())) return ""; if ("/".equals(driveData.getHomePath())) return path; return path.substring(driveData.getHomePath().length()); } } /** * The listener interface for receiving increaseAction events. * The class that is interested in processing a increaseAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addIncreaseActionListener</code> method. When * the increaseAction event occurs, that object's appropriate * method is invoked. */ public static class IncreaseActionListener extends EventListener<UICLVConfig> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICLVConfig> event) throws Exception { UICLVConfig clvConfig = event.getSource(); List<String> items = clvConfig.items; int offset = Integer.parseInt(event.getRequestContext().getRequestParameter(OBJECTID)); if (offset > 0) { String temp = items.get(offset - 1); items.set(offset - 1, items.get(offset)); items.set(offset, temp); } StringBuffer sb = new StringBuffer(""); for (String item : items) { sb.append(item).append(";"); } String itemPath = sb.toString(); clvConfig.getUIStringInput(UICLVConfig.ITEM_PATH_FORM_STRING_INPUT).setValue(clvConfig.getTitles(itemPath)); clvConfig.setSavedPath(itemPath); } } /** * The listener interface for receiving decreaseAction events. * The class that is interested in processing a decreaseAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addDecreaseActionListener</code> method. When * the decreaseAction event occurs, that object's appropriate * method is invoked. */ public static class DecreaseActionListener extends EventListener<UICLVConfig> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICLVConfig> event) throws Exception { UICLVConfig clvConfig = event.getSource(); List<String> items = clvConfig.items; int offset = Integer.parseInt(event.getRequestContext().getRequestParameter(OBJECTID)); if (offset < items.size() - 1) { String temp = items.get(offset + 1); items.set(offset + 1, items.get(offset)); items.set(offset, temp); } StringBuffer sb = new StringBuffer(""); for (String item : items) { sb.append(item).append(";"); } String itemPath = sb.toString(); clvConfig.getUIStringInput(UICLVConfig.ITEM_PATH_FORM_STRING_INPUT).setValue(clvConfig.getTitles(itemPath)); clvConfig.setSavedPath(itemPath); } } /** * The listener interface for receiving selectTargetPageAction events. * The class that is interested in processing a selectTargetPageAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSelectTargetPageActionListener</code> method. When * the selectTargetPageAction event occurs, that object's appropriate * method is invoked. */ public static class SelectTargetPageActionListener extends EventListener<UICLVConfig> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICLVConfig> event) throws Exception { UICLVConfig viewerManagementForm = event.getSource(); UIPageSelector pageSelector = viewerManagementForm.createUIComponent(UIPageSelector.class, null, null); pageSelector.setSourceComponent(viewerManagementForm, new String[] {TARGET_PAGE_FORM_STRING_INPUT}); Utils.createPopupWindow(viewerManagementForm, pageSelector, TARGET_PAGE_SELECTOR_POPUP_WINDOW, 800); viewerManagementForm.setPopupId(TARGET_PAGE_SELECTOR_POPUP_WINDOW); } } public static class ShowAdvancedBlockActionListener extends EventListener<UICLVConfig> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICLVConfig> event) throws Exception { UICLVConfig clvConfig = event.getSource(); String showValue = event.getRequestContext().getRequestParameter(OBJECTID); clvConfig.isShowAdvancedBlock_ = "true".equalsIgnoreCase(showValue); event.getRequestContext().addUIComponentToUpdateByAjax(clvConfig); } } private boolean modeInternal = false; public void setModeInternal(boolean value) { this.modeInternal = value; } public boolean getModeInternal() { return this.modeInternal; } private class TemplateNameComparator implements Comparator<SelectItemOption<String>> { public int compare(SelectItemOption<String> item1,SelectItemOption<String> item2) { String s1 = item1.getLabel().toLowerCase(); String s2 = item2.getLabel().toLowerCase(); return s1.compareTo(s2); } } }
59,812
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CategoryBean.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/clv/CategoryBean.java
package org.exoplatform.wcm.webui.clv; import java.util.List; public class CategoryBean { String name; String path; String title; String url; boolean isSelected = false; int depth=0; long total=0; List<CategoryBean> childs; public CategoryBean(String name, String path, String title, String url, boolean isSelected, int depth, long total) { this.name = name; this.path = path; this.title = title; this.url = url; this.isSelected = isSelected; this.depth = depth; this.total = total; this.childs = null; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public boolean isSelected() { return isSelected; } public void setSelected(boolean isSelected) { this.isSelected = isSelected; } public int getDepth() { return depth; } public void setDepth(int depth) { this.depth = depth; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } public List<CategoryBean> getChilds() { return childs; } public void setChilds(List<CategoryBean> childs) { this.childs = childs; } public boolean hasChilds() { return (childs!=null && childs.size()>0); } }
1,622
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICLVFolderMode.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/clv/UICLVFolderMode.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.clv; import java.util.ArrayList; import java.util.HashMap; import javax.jcr.AccessDeniedException; import javax.jcr.ItemNotFoundException; import javax.jcr.Node; import javax.jcr.query.Query; import javax.portlet.PortletPreferences; import org.exoplatform.portal.webui.application.UIPortlet; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.publication.NodeLocationPaginatedResultIterator; import org.exoplatform.services.wcm.publication.PaginatedResultIterator; import org.exoplatform.services.wcm.publication.Result; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.Lifecycle; /* * Created by The eXo Platform SAS Author : Anh Do Ngoc anh.do@exoplatform.com * Oct 15, 2008 */ /** * The Class UICLVFolderMode. */ @ComponentConfig( lifecycle = Lifecycle.class, template = "system:/groovy/ContentListViewer/UICLVContainer.gtmpl", events = { @EventConfig(listeners = UICLVFolderMode.PreferencesActionListener.class) } ) public class UICLVFolderMode extends UICLVContainer { private UICLVPresentation clvPresentation; /* (non-Javadoc) * @see org.exoplatform.wcm.webui.clv.UICLVContainer#init() */ public void init() throws Exception { PortletPreferences portletPreferences = Utils.getAllPortletPreferences(); Result result = null; messageKey = null; try { result = getRenderedContentNodes(); } catch (ItemNotFoundException e) { messageKey = "UICLVContainer.msg.item-not-found"; return; } catch (AccessDeniedException e) { messageKey = "UICLVContainer.msg.no-permission"; result = new Result(new ArrayList<Node>(), 0, 0, null, null); } if (result.getNumTotal() == 0) { messageKey = "UICLVContainer.msg.non-contents"; } int itemsPerPage = Integer.parseInt(portletPreferences.getValue(UICLVPortlet.PREFERENCE_ITEMS_PER_PAGE, null)); PaginatedResultIterator paginatedResultIterator = new NodeLocationPaginatedResultIterator(result, itemsPerPage); getChildren().clear(); PortletRequestContext pContext = (PortletRequestContext) WebuiRequestContext.getCurrentInstance(); clvPresentation = addChild(UICLVPresentation.class, null, UICLVPresentation.class.getSimpleName() + "_" + pContext.getWindowId() ); ResourceResolver resourceResolver = getTemplateResourceResolver(); clvPresentation.init(resourceResolver, paginatedResultIterator); } /** * Gets the rendered content nodes. * * @return the rendered content nodes * * @throws Exception the exception */ public Result getRenderedContentNodes() throws Exception { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); PortletPreferences preferences = portletRequestContext.getRequest().getPreferences(); WCMComposer wcmComposer = getApplicationComponent(WCMComposer.class); HashMap<String, String> filters = new HashMap<String, String>(); filters.put(WCMComposer.FILTER_MODE, Utils.getCurrentMode()); String orderBy = preferences.getValue(UICLVPortlet.PREFERENCE_ORDER_BY, null); String translation = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_ADD_TRANSLATION); String orderType = preferences.getValue(UICLVPortlet.PREFERENCE_ORDER_TYPE, null); String itemsPerPage = preferences.getValue(UICLVPortlet.PREFERENCE_ITEMS_PER_PAGE, null); String sharedCache = preferences.getValue(UICLVPortlet.PREFERENCE_SHARED_CACHE, "true"); String contextualMode = preferences.getValue(UICLVPortlet.PREFERENCE_CONTEXTUAL_FOLDER, "true"); String workspace = preferences.getValue(UICLVPortlet.PREFERENCE_WORKSPACE, null); String query = preferences.getValue(UICLVPortlet.PREFERENCE_CONTENTS_BY_QUERY, null); if (orderType == null) orderType = "DESC"; if (orderBy == null) orderBy = "exo:title"; filters.put(WCMComposer.FILTER_TRANSLATION, translation); filters.put(WCMComposer.FILTER_ORDER_BY, orderBy); filters.put(WCMComposer.FILTER_ORDER_TYPE, orderType); StringBuffer filterLang = new StringBuffer(Util.getPortalRequestContext().getLocale().getLanguage()); String country = Util.getPortalRequestContext().getLocale().getCountry(); if (country != null && country.length() > 0) { filterLang.append("_").append(country); } filters.put(WCMComposer.FILTER_LANGUAGE, filterLang.toString()); filters.put(WCMComposer.FILTER_LIMIT, itemsPerPage); filters.put(WCMComposer.FILTER_VISIBILITY, ("true".equals(sharedCache))? WCMComposer.VISIBILITY_PUBLIC:WCMComposer.VISIBILITY_USER); if (this.getAncestorOfType(UICLVPortlet.class).isQueryApplication()) { String folderPath = preferences.getValue(UICLVPortlet.PREFERENCE_ITEM_PATH, null); if (folderPath == null) { return new Result(new ArrayList<Node>(), 0, 0, null, null); } folderPath = folderPath.replace("{siteName}", Util.getPortalRequestContext().getSiteName()); String strQuery = this.getAncestorOfType(UICLVPortlet.class).getQueryStatement(query); if (strQuery != null) strQuery = strQuery.replaceAll("\"", "'"); if (UICLVPortlet.PREFERENCE_CONTEXTUAL_FOLDER_ENABLE.equals(contextualMode) && org.exoplatform.wcm.webui.Utils.checkQuery(workspace, strQuery, Query.SQL)) { String[] contentList = null; if (preferences.getValue(UICLVPortlet.PREFERENCE_ITEM_PATH, null) != null) { contentList = preferences.getValue(UICLVPortlet.PREFERENCE_ITEM_PATH, null).split(";"); } if (contentList != null && contentList.length != 0) { for (String itemPath : contentList) { itemPath = itemPath.replace("{siteName}", Util.getPortalRequestContext().getSiteName()); Node currentNode = NodeLocation.getNodeByExpression(itemPath); NodeLocation nodeLocation = new NodeLocation(); if (currentNode != null) { String path = currentNode.getPath(); nodeLocation.setPath(path); nodeLocation.setWorkspace(workspace); nodeLocation.setSystemSession(false); } filters.put(WCMComposer.FILTER_QUERY_FULL, strQuery); return wcmComposer.getPaginatedContents(nodeLocation, filters, WCMCoreUtils.getUserSessionProvider()); } } } } String folderPath = this.getAncestorOfType(UICLVPortlet.class).getFolderPath(); if (folderPath == null) { folderPath = preferences.getValue(UICLVPortlet.PREFERENCE_ITEM_PATH, null); } if (folderPath != null) { folderPath = folderPath.replace("{siteName}", Util.getPortalRequestContext().getSiteName()); } if (folderPath == null) { return new Result(new ArrayList<Node>(), 0, 0, null, null); } NodeLocation nodeLocation = NodeLocation.getNodeLocationByExpression(folderPath); Node targetNode = NodeLocation.getNodeByLocation(nodeLocation); //check if folder is empty, return empty result if (targetNode == null || !targetNode.hasNodes()) { return new Result(new ArrayList<Node>(), 0, 0, nodeLocation, filters); } else { return wcmComposer.getPaginatedContents(nodeLocation, filters, WCMCoreUtils.getUserSessionProvider()); } } /** * Gets the bar info show. * * @return the value for info bar setting * * @throws Exception the exception */ public boolean isShowInfoBar() throws Exception { if (UIPortlet.getCurrentUIPortlet().getShowInfoBar()) return true; return false; } /** * Get portlet name. * * @throws Exception the exception */ public String getPortletName() throws Exception { return UICLVFolderMode.class.getSimpleName(); } }
9,483
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICLVContainer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/clv/UICLVContainer.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.clv; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.Session; import javax.jcr.query.Row; import javax.portlet.PortletPreferences; import org.exoplatform.ecm.resolver.JCRResourceResolver; import org.exoplatform.ecms.legacy.search.data.SearchResult; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.search.base.SearchDataCreator; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS * Author : anh.do * anh.do@exoplatform.com, anhdn86@gmail.com * Feb 23, 2009 */ public abstract class UICLVContainer extends UIContainer { /** The message key. */ protected String messageKey; /** * Inits the. * * @throws Exception the exception */ public abstract void init() throws Exception; /** * Get portlet name. * * @throws Exception the exception */ public abstract String getPortletName() throws Exception; /** * Gets the message. * * @return the message * * @throws Exception the exception */ public String getMessageKey() throws Exception { return messageKey; } /** * Gets the portlet id. * * @return the portlet id */ public String getPortletId() { PortletRequestContext pContext = (PortletRequestContext) WebuiRequestContext.getCurrentInstance(); return pContext.getWindowId(); } /* (non-Javadoc) * @see org.exoplatform.webui.core.UIComponent#processRender(org.exoplatform.webui.application.WebuiRequestContext) */ public void processRender(WebuiRequestContext context) throws Exception { if(!Boolean.parseBoolean(Utils.getCurrentMode()) || context.getFullRender()) { init(); } super.processRender(context); } public String getEditLink(boolean isEditable, boolean isNew) throws Exception { String folderPath = this.getAncestorOfType(UICLVPortlet.class).getFolderPath(); if (folderPath==null) folderPath=""; Node folderNode = null; try{ folderNode = getFolderNode(folderPath); }catch(PathNotFoundException e){ folderNode = getFolderNode(""); } return Utils.getEditLink(folderNode, isEditable, isNew); } public Node getFolderNode() { return NodeLocation.getNodeByExpression( Utils.getPortletPreference(UICLVPortlet.PREFERENCE_ITEM_PATH)); } private Node getFolderNode(String oldPath) throws Exception { if ((oldPath==null) || ((oldPath!=null) && (oldPath.length()==0))) return null; int slashIndex = oldPath.indexOf("/"); String path = oldPath.substring(slashIndex); String[] repoWorkspace = oldPath.substring(0, slashIndex).split(":"); String strWorkspace = repoWorkspace[1]; Session session = WCMCoreUtils.getUserSessionProvider().getSession(strWorkspace, WCMCoreUtils.getRepository()); return (Node)session.getItem(path); } /** * Gets the template resource resolver. * * @return the template resource resolver * * @throws Exception the exception */ public ResourceResolver getTemplateResourceResolver() throws Exception { DMSConfiguration dmsConfiguration = getApplicationComponent(DMSConfiguration.class); String workspace = dmsConfiguration.getConfig().getSystemWorkspace(); return new JCRResourceResolver(workspace); } /** * The listener interface for receiving quickEditAction events. * The class that is interested in processing a quickEditAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addQuickEditActionListener</code> method. When * the quickEditAction event occurs, that object's appropriate * method is invoked. * */ public static class PreferencesActionListener extends EventListener<UICLVFolderMode> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICLVFolderMode> event) throws Exception { UICLVContainer clvContainer = event.getSource(); UICLVConfig viewerManagementForm = clvContainer.createUIComponent(UICLVConfig.class, null, null); Utils.createPopupWindow(clvContainer, viewerManagementForm, "UIViewerManagementPopupWindow", 800); } } public void onRefresh(Event<UICLVPresentation> event) throws Exception { UICLVPresentation clvPresentation = event.getSource(); UICLVContainer uiListViewerBase = clvPresentation.getParent(); uiListViewerBase.getChildren().clear(); uiListViewerBase.init(); } public boolean isModeByFolder() { PortletPreferences portletPreferences = Utils.getAllPortletPreferences(); String currentApplicationMode = portletPreferences.getValue(UICLVPortlet.PREFERENCE_APPLICATION_TYPE, null); if (currentApplicationMode.equals(UICLVPortlet.APPLICATION_CLV_BY_QUERY)) return false; return UICLVPortlet.DISPLAY_MODE_AUTOMATIC.equals( Utils.getPortletPreference(UICLVPortlet.PREFERENCE_DISPLAY_MODE)); } public boolean hasFolderPath() { PortletPreferences portletPreferences = Utils.getAllPortletPreferences(); String itemPath = portletPreferences.getValue(UICLVPortlet.PREFERENCE_ITEM_PATH, null); return (itemPath != null && itemPath.length() > 0) ? true : false; } public boolean isShowManageContent() { return (Utils.isShowQuickEdit() && isModeByFolder() && hasFolderPath()); } public boolean isShowAddContent() { if (isShowManageContent()) { PortletPreferences portletPreferences = ((PortletRequestContext) WebuiRequestContext. getCurrentInstance()).getRequest().getPreferences(); String itemPath = portletPreferences.getValue(UICLVPortlet.PREFERENCE_ITEM_PATH, null); try { Node content = NodeLocation.getNodeByExpression(itemPath); ((ExtendedNode) content).checkPermission(PermissionType.ADD_NODE); } catch (Exception e) { return false; } return true; } else return false; } public boolean isShowPreferences() { try { return Utils.isShowQuickEdit() && Utils.hasEditPermissionOnPage(); } catch (Exception e) { return false; } } public static class CLVNodeCreator implements SearchDataCreator<NodeLocation> { @Override public NodeLocation createData(Node node, Row row, SearchResult searchResult) { return NodeLocation.getNodeLocationByNode(node); } } }
7,994
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICLVPortlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/clv/UICLVPortlet.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.clv; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import javax.jcr.ItemNotFoundException; import javax.jcr.NoSuchWorkspaceException; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.portlet.MimeResponse; import javax.portlet.PortletMode; import javax.portlet.PortletPreferences; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.core.WCMService; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.webui.application.WebuiApplication; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.UIPortletApplication; import org.exoplatform.webui.core.lifecycle.UIApplicationLifecycle; import org.gatein.portal.controller.resource.ResourceScope; /* * Created by The eXo Platform SAS Author : Anh Do Ngoc anh.do@exoplatform.com * Oct 15, 2008 */ /** * The Class UICLVPortlet. */ @ComponentConfig(lifecycle = UIApplicationLifecycle.class, template = "system:/groovy/ContentListViewer/UICLVPortlet.gtmpl") public class UICLVPortlet extends UIPortletApplication { /** The Constant PREFERENCE_DISPLAY_MODE. */ public static final String PREFERENCE_DISPLAY_MODE = "mode"; /** The Constant PREFERENCE_ADD_TRANSLATION. */ public final static String PREFERENCE_ADD_TRANSLATION = "addTranslation"; /** The Constant PREFERENCE_ITEM_PATH. */ public final static String PREFERENCE_ITEM_PATH = "folderPath"; /** The Constant PREFERENCE_ITEM_PATH. */ public final static String PREFERENCE_ITEM_DRIVE = "nodeDrive"; /** The Constant PREFERENCE_ORDER_BY. */ public static final String PREFERENCE_ORDER_BY = "orderBy"; /** The Constant ORDER_BY_TITLE. */ public static final String ORDER_BY_TITLE = "OrderByTitle"; /** The Constant ORDER_BY_DATE_CREATED. */ public static final String ORDER_BY_DATE_CREATED = "OrderByDateCreated"; /** The Constant ORDER_BY_DATE_MODIFIED. */ public static final String ORDER_BY_DATE_MODIFIED = "OrderByDateModified"; /** The Constant ORDER_BY_DATE_PUBLISHED. */ public static final String ORDER_BY_DATE_PUBLISHED = "OrderByDatePublished"; /** The Constant ORDER_BY_DATE_START_EVENT. */ public static final String ORDER_BY_DATE_START_EVENT = "OrderByDateStartEvent"; /** The Constant ORDER_BY_INDEX. */ public static final String ORDER_BY_INDEX = "OrderByIndex"; /** The Constant PREFERENCE_ORDER_TYPE. */ public static final String PREFERENCE_ORDER_TYPE = "orderType"; /** The Constant ORDER_TYPE_DESCENDENT. */ public static final String ORDER_TYPE_DESCENDENT = "OrderDesc"; /** The Constant ORDER_TYPE_ASCENDENT. */ public static final String ORDER_TYPE_ASCENDENT = "OrderAsc"; /** The Constant PREFERENCE_HEADER. */ public final static String PREFERENCE_HEADER = "header"; /** The Constant PREFERENCE_AUTOMATIC_DETECTION. */ public final static String PREFERENCE_AUTOMATIC_DETECTION = "automaticDetection"; /** The Constant PREFERENCE_DISPLAY_TEMPLATE. */ public final static String PREFERENCE_DISPLAY_TEMPLATE = "formViewTemplatePath"; /** The Constant PREFERENCE_PAGINATOR_TEMPLATE. */ public final static String PREFERENCE_PAGINATOR_TEMPLATE = "paginatorTemplatePath"; /** The Constant PREFERENCE_ITEMS_PER_PAGE. */ public final static String PREFERENCE_ITEMS_PER_PAGE = "itemsPerPage"; /** The Constant PREFERENCE_SHOW_TITLE. */ public final static String PREFERENCE_SHOW_TITLE = "showTitle"; /** The Constant PREFERENCE_SHOW_HEADER. */ public final static String PREFERENCE_SHOW_HEADER = "showHeader"; /** The Constant PREFERENCE_SHOW_REFRESH_BUTTON. */ public final static String PREFERENCE_SHOW_REFRESH_BUTTON = "showRefreshButton"; /** The Constant PREFERENCE_SHOW_ILLUSTRATION. */ /** The Constant PREFERENCE_SHOW_IMAGE. */ public final static String PREFERENCE_SHOW_ILLUSTRATION = "showThumbnailsView"; /** The Constant PREFERENCE_SHOW_DATE_CREATED. */ public final static String PREFERENCE_SHOW_DATE_CREATED = "showDateCreated"; /** The Constant PREFERENCE_SHOW_MORE_LINK. */ public final static String PREFERENCE_SHOW_READMORE = "showReadmore"; /** The Constant PREFERNECE_SHOW_SUMMARY. */ public final static String PREFERENCE_SHOW_SUMMARY = "showSummary"; /** The Constant PREFERENCE_SHOW_LINK. */ public final static String PREFERENCE_SHOW_LINK = "showLink"; /** The Constant PREFERENCE_SHOW_RSSLINK. */ public final static String PREFERENCE_SHOW_RSSLINK = "showRssLink"; /** The Constant PREFERENCE_CONTEXTUAL_FOLDER. */ public final static String PREFERENCE_CONTEXTUAL_FOLDER = "contextualFolder"; /** The Constant PREFERENCE_CONTEXTUAL_FOLDER_ENABLE. */ public final static String PREFERENCE_CONTEXTUAL_FOLDER_ENABLE = "contextualEnable"; /** The Constant PREFERENCE_CONTEXTUAL_FOLDER_DISABLE. */ public final static String PREFERENCE_CONTEXTUAL_FOLDER_DISABLE = "contextualDisable"; /** The Constant PREFERENCE_TARGET_PAGE. */ public final static String PREFERENCE_TARGET_PAGE = "basePath"; /** The Constant PREFERENCE_SHOW_SCL_WITH. */ public final static String PREFERENCE_SHOW_SCV_WITH = "showScvWith"; /** The Constant PREFERENCE_SHOW_CLV_BY. */ public final static String PREFERENCE_SHOW_CLV_BY = "showClvBy"; /** The Constant PREFERENCE_CACHE_ENABLED. */ public final static String PREFERENCE_CACHE_ENABLED = "sharedCache"; /** The Constant CONTENT_BY_QUERY. */ public final static String PREFERENCE_CONTENTS_BY_QUERY = "query"; /** The Constant PREFERENCE_WORKSPACE. */ public final static String PREFERENCE_WORKSPACE = "workspace"; /** The Constant DISPLAY_MODE_MANUAL. */ public static final String DISPLAY_MODE_MANUAL = "ManualViewerMode"; /** The Constant DISPLAY_MODE_AUTOMATIC. */ public static final String DISPLAY_MODE_AUTOMATIC = "AutoViewerMode"; public static final String DEFAULT_SHOW_CLV_BY = "folder-id"; public static final String DEFAULT_SHOW_SCV_WITH = "content-id"; public static final String PREFERENCE_APPLICATION_TYPE = "application"; public static final String APPLICATION_CLV_BY_QUERY = "ContentsByQuery"; public static final String PREFERENCE_SHARED_CACHE = "sharedCache"; /* Dynamic parameter for CLV by query */ public static final String QUERY_USER_PARAMETER = "user"; public static final String QUERY_LANGUAGE_PARAMETER = "lang"; private PortletMode cpMode; private UICLVFolderMode folderMode; private UICLVManualMode manualMode; private UICLVConfig clvConfig; private String currentFolderPath; private String header; private String currentDisplayMode; private String currentApplicationMode; /** * Instantiates a new uICLV portlet. * * @throws Exception the exception */ public UICLVPortlet() throws Exception { addChild(UIPopupContainer.class, null, "UIPopupContainer-" + new Date().getTime()); currentFolderPath = getFolderPath(); } public String getHeader() { return header; } public void setCurrentFolderPath(String value) { currentFolderPath = value; } public String getFolderPath() { PortalRequestContext preq = Util.getPortalRequestContext(); currentFolderPath = ""; if (!preq.useAjax()) { currentFolderPath = getFolderPathParamValue(); } try { if (currentFolderPath != null && currentFolderPath.length() > 0) { Node folderNode = null; NodeLocation folderLocation = NodeLocation.getNodeLocationByExpression(currentFolderPath); folderNode = NodeLocation.getNodeByLocation(folderLocation); if (folderNode == null) { header = null; } else { if (folderNode.hasProperty(org.exoplatform.ecm.webui.utils.Utils.EXO_TITLE)) header = folderNode.getProperty(org.exoplatform.ecm.webui.utils.Utils.EXO_TITLE).getString(); else header = folderNode.getName(); } } else header = null; } catch(IllegalArgumentException ex) { header = null; } catch(ItemNotFoundException ex) { header = null; } catch(PathNotFoundException ex) { header = null; } catch(NoSuchWorkspaceException ex) { header = null; } catch(RepositoryException ex) { header = null; } PortletPreferences preferences = Utils.getAllPortletPreferences(); currentDisplayMode = preferences.getValue(PREFERENCE_DISPLAY_MODE, null); currentApplicationMode = preferences.getValue(PREFERENCE_APPLICATION_TYPE, null); if (DISPLAY_MODE_AUTOMATIC.equals(currentDisplayMode)) { if (currentFolderPath == null || currentFolderPath.length() == 0) { currentFolderPath = Utils.getPortletPreference(UICLVPortlet.PREFERENCE_ITEM_PATH); } } return currentFolderPath; } public String getFolderPathParamValue() { PortletPreferences preferences = Utils.getAllPortletPreferences(); String contextualMode = preferences.getValue(PREFERENCE_CONTEXTUAL_FOLDER, null); Node folderNode = null; String folderPath = null; if (PREFERENCE_CONTEXTUAL_FOLDER_ENABLE.equals(contextualMode)) { String folderParamName = preferences.getValue(PREFERENCE_SHOW_CLV_BY, null); if (folderParamName == null || folderParamName.length() == 0) folderParamName = DEFAULT_SHOW_CLV_BY; folderPath = Util.getPortalRequestContext().getRequestParameter(folderParamName); try { NodeLocation folderLocation = NodeLocation.getNodeLocationByExpression(folderPath); folderNode = NodeLocation.getNodeByLocation(folderLocation); if (folderNode == null) return null; } catch (Exception e) { folderNode = null; folderPath = null; } } return folderPath; } /** * * @param params * @return */ public HashMap<String, String> getQueryParammeter(HashSet<String> params) { HashMap<String, String> paramMap = new HashMap<String, String>(); PortalRequestContext context = Util.getPortalRequestContext(); for (String param : params) { String value = context.getRequestParameter(param); if (value != null) { paramMap.put(param, value); } else { paramMap.put(param, ""); } } paramMap.put(UICLVPortlet.QUERY_USER_PARAMETER, context.getRemoteUser()); paramMap.put(UICLVPortlet.QUERY_LANGUAGE_PARAMETER, context.getLocale().getLanguage()); return paramMap; } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIPortletApplication#processRender(org.exoplatform * .webui.application.WebuiApplication, * org.exoplatform.webui.application.WebuiRequestContext) */ public void processRender(WebuiApplication app, WebuiRequestContext context) throws Exception { PortletRequestContext pContext = (PortletRequestContext) context; PortletPreferences preferences = pContext.getRequest().getPreferences(); Boolean sharedCache = "true".equals(preferences.getValue(PREFERENCE_SHARED_CACHE, "true")); if (context.getRemoteUser() == null || (Utils.isLiveMode() && sharedCache && !Utils.isPortalEditMode() && Utils.isPortletViewMode(pContext))) { WCMService wcmService = getApplicationComponent(WCMService.class); pContext.getResponse().setProperty(MimeResponse.EXPIRATION_CACHE, "" + wcmService.getPortletExpirationCache()); if (log.isTraceEnabled()) log.trace("CLV rendering : cache set to " + wcmService.getPortletExpirationCache()); } String nDisplayMode = preferences.getValue(PREFERENCE_DISPLAY_MODE, null); PortletMode npMode = pContext.getApplicationMode(); if (!nDisplayMode.equals(currentDisplayMode)) { activateMode(npMode, nDisplayMode); } else { if (!npMode.equals(cpMode)) { activateMode(npMode, nDisplayMode); } } setId(UICLVPortlet.class.getSimpleName() + "_" + pContext.getWindowId()); if (context.getRemoteUser() != null && WCMComposer.MODE_EDIT.equals(Utils.getCurrentMode())) { pContext.getJavascriptManager().loadScriptResource(ResourceScope.SHARED, "content-selector"); pContext.getJavascriptManager().loadScriptResource(ResourceScope.SHARED, "quick-edit"); } super.processRender(app, context); } /** * Decide which element will be displayed for correspond PortletMode/DisplayMode * @param npMode: View/Edit * @param nDisplayMode : FolderMode/ManualMode * @throws Exception : Exception will be throws if child addition action fails */ private void activateMode(PortletMode npMode, String nDisplayMode) throws Exception { PortletRequestContext pContext = (PortletRequestContext) WebuiRequestContext.getCurrentInstance(); if (npMode.equals(cpMode)) { // Switch manual/auto // Not reach in the case of queryMode. removeChildren(); if (Utils.isPortalEditMode()){ clvConfig = addChild(UICLVConfig.class, null, null); clvConfig.setModeInternal(false); }else { if (nDisplayMode.equals(DISPLAY_MODE_AUTOMATIC)) { folderMode = addChild(UICLVFolderMode.class, null, UICLVFolderMode.class.getSimpleName() + "_" + pContext.getWindowId()); folderMode.init(); folderMode.setRendered(true); } else { manualMode = addChild(UICLVManualMode.class, null, UICLVManualMode.class.getSimpleName() + "_" + pContext.getWindowId()); manualMode.init(); manualMode.setRendered(true); } } } else { if (npMode.equals(PortletMode.VIEW)) { //Change from edit to iew removeChildren(); if (nDisplayMode.equals(DISPLAY_MODE_AUTOMATIC)) { folderMode = addChild(UICLVFolderMode.class, null, UICLVFolderMode.class.getSimpleName() + "_" + pContext.getWindowId()); folderMode.init(); folderMode.setRendered(true); } else { manualMode = addChild(UICLVManualMode.class, null, UICLVManualMode.class.getSimpleName() + "_" + pContext.getWindowId()); manualMode.init(); manualMode.setRendered(true); } } else { // Change from view to edit removeChildren(); clvConfig = addChild(UICLVConfig.class, null, null); clvConfig.setModeInternal(true); } } cpMode = npMode; currentDisplayMode = nDisplayMode; } private void removeChildren() { clvConfig = getChild(UICLVConfig.class); if (clvConfig != null) removeChild(UICLVConfig.class); folderMode = getChild(UICLVFolderMode.class); if (folderMode != null) removeChild(UICLVFolderMode.class); manualMode = getChild(UICLVManualMode.class); if (manualMode != null) removeChild(UICLVManualMode.class); } /** * Force porlet to change to ViewMode * * @throws Exception */ public void changeToViewMode() throws Exception { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); portletRequestContext.setApplicationMode(PortletMode.VIEW); updatePortlet(); } /** * Update the current portlet if config/data changed. * @throws Exception */ public void updatePortlet() throws Exception { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); PortletMode npMode = portletRequestContext.getApplicationMode(); PortletPreferences preferences = Utils.getAllPortletPreferences(); String nDisplayMode = preferences.getValue(PREFERENCE_DISPLAY_MODE, null); activateMode(npMode, nDisplayMode); } /** * * @param sqlQuery * @return */ public String getQueryStatement(String sqlQuery) { HashSet<String> params = Utils.getQueryParams(sqlQuery); HashMap<String, String> queryParam = getQueryParammeter(params); return Utils.buildQuery(sqlQuery, queryParam); } /** * * @return */ public boolean isQueryApplication() { return APPLICATION_CLV_BY_QUERY.equals(currentApplicationMode); } }
18,249
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIEditingPortlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/administration/UIEditingPortlet.java
package org.exoplatform.wcm.webui.administration; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.webui.application.WebuiApplication; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIPortletApplication; import org.exoplatform.webui.core.lifecycle.UIApplicationLifecycle; import org.exoplatform.webui.form.UIFormSelectBox; /** * Created by The eXo Platform SAS Author : eXoPlatform * ngoc.tran@exoplatform.com Jan 28, 2010 */ @ComponentConfig( lifecycle = UIApplicationLifecycle.class, template = "app:/groovy/Editing/UIEditingPortlet.gtmpl" ) public class UIEditingPortlet extends UIPortletApplication { public UIEditingPortlet() throws Exception { addChild(UIEditingForm.class, null, null); } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIPortletApplication#processRender(org.exoplatform * .webui.application.WebuiApplication, * org.exoplatform.webui.application.WebuiRequestContext) */ public void processRender(WebuiApplication app, WebuiRequestContext context) throws Exception { // RenderResponse response = context.getResponse(); // Element elementS = response.createElement("script"); // elementS.setAttribute("type", "text/javascript"); // elementS.setAttribute("src", "/eXoWCMResources/javascript/eXo/wcm/frontoffice/private/QuickEdit.js"); // response.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT,elementS); // elementS = response.createElement("script"); // elementS.setAttribute("type", "text/javascript"); // elementS.setAttribute("src", "/eXoWCMResources/javascript/eXo/wcm/frontoffice/private/InlineEditing.js"); // response.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT,elementS); UIEditingForm editingForm = getChild(UIEditingForm.class); UIFormSelectBox orderBySelectBox = editingForm.getChild(UIFormSelectBox.class); orderBySelectBox.setValue((Utils.isShowQuickEdit())?UIEditingForm.DRAFT:UIEditingForm.PUBLISHED); super.processRender(app, context) ; } }
2,202
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIEditingForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-presentation/src/main/java/org/exoplatform/wcm/webui/administration/UIEditingForm.java
/* * Copyright (C) 2003-2010 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.administration; import java.util.ArrayList; import java.util.List; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormSelectBox; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Feb 2, 2010 */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "app:/groovy/Editing/UIEditingToolBar.gtmpl", events = { @EventConfig(listeners = UIEditingForm.ChangeEditingActionListener.class) }) public class UIEditingForm extends UIForm { /** The Constant PUBLISHED. */ public static final String PUBLISHED = "Published"; /** The Constant DRAFT. */ public static final String DRAFT = "Draft"; /** The Constant EDITING_OPTIONS. */ public static final String EDITING_OPTIONS = "EditingOptions"; public UIEditingForm() { List<SelectItemOption<String>> editingOptions = new ArrayList<SelectItemOption<String>>(); editingOptions.add(new SelectItemOption<String>(PUBLISHED, PUBLISHED)); editingOptions.add(new SelectItemOption<String>(DRAFT, DRAFT)); UIFormSelectBox orderBySelectBox = new UIFormSelectBox(EDITING_OPTIONS, EDITING_OPTIONS, editingOptions); orderBySelectBox.setOnChange("ChangeEditing"); addChild(orderBySelectBox); } /** * The listener interface for receiving changeRepositoryAction events. * The class that is interested in processing a changeRepositoryAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addChangeRepositoryActionListener</code> method. When * the changeRepositoryAction event occurs, that object's appropriate * method is invoked. */ public static class ChangeEditingActionListener extends EventListener<UIEditingForm> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIEditingForm> event) throws Exception { UIEditingForm editingForm = event.getSource(); PortalRequestContext context = Util.getPortalRequestContext(); UIFormSelectBox options = editingForm.getChildById(UIEditingForm.EDITING_OPTIONS); String option = options.getValue() ; if(option.equals(UIEditingForm.PUBLISHED)) { context.getRequest().getSession().setAttribute(Utils.TURN_ON_QUICK_EDIT, false); Utils.updatePortal((PortletRequestContext) event.getRequestContext()); } else { context.getRequest().getSession().setAttribute(Utils.TURN_ON_QUICK_EDIT, true); Utils.updatePortal((PortletRequestContext) event.getRequestContext()); } } } }
4,134
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestDialogFormUtil.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/test/java/org/exoplatform/ecm/webui/TestDialogFormUtil.java
package org.exoplatform.ecm.webui; import org.exoplatform.ecm.webui.form.UIDialogForm; import org.exoplatform.ecm.webui.utils.DialogFormUtil; import org.exoplatform.services.cms.JcrInputProperty; import org.exoplatform.webui.form.UIFormStringInput; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Created by exo on 9/22/16. */ public class TestDialogFormUtil { @Test public void testPrepareMap() throws Exception { // Given List inputs = new ArrayList<UIFormStringInput>(); Map properties = new HashMap<String, String>(); UIFormStringInput property1 = new UIFormStringInput("name", "name"); UIFormStringInput property2 = new UIFormStringInput("title", "title"); UIDialogForm parent = new UIDialogForm(); JcrInputProperty jcrExoName = new JcrInputProperty(); JcrInputProperty jcrExoTitle = new JcrInputProperty(); inputs.add(property1); inputs.add(property2); property1.setParent(parent); property2.setParent(parent); jcrExoName.setJcrPath("/node/exo:name"); jcrExoTitle.setJcrPath("/node/exo:title"); properties.put("name", jcrExoName); properties.put("title", jcrExoTitle); // When Map<String, JcrInputProperty> map = DialogFormUtil.prepareMap(inputs, properties, null); // Then assertNotNull(map); assertEquals(map.get("/node/exo:name").getValue(), "name"); assertEquals(map.get("/node/exo:title").getValue(), "title"); } @Test public void testPrepareMapNameOnly() throws Exception { // Given List inputs = new ArrayList<UIFormStringInput>(); Map properties = new HashMap<String, String>(); UIFormStringInput property1 = new UIFormStringInput("name", "name"); UIDialogForm parent = new UIDialogForm(); JcrInputProperty jcrExoName = new JcrInputProperty(); inputs.add(property1); property1.setParent(parent); jcrExoName.setJcrPath("/node/exo:name"); properties.put("name", jcrExoName); // When Map<String, JcrInputProperty> map = DialogFormUtil.prepareMap(inputs, properties, null); // Then String jcrTitle = (String) map.get("/node/exo:title").getValue(); assertNotNull(map); assertTrue(map.size() == 2); assertEquals(jcrExoName.getValue(), "name"); assertEquals(jcrTitle, "name"); } }
2,487
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestUtils.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/test/java/org/exoplatform/ecm/webui/TestUtils.java
package org.exoplatform.ecm.webui; import org.exoplatform.ecm.webui.utils.Utils; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Created by exo on 29/11/17. */ public class TestUtils { @Test public void testGenerateMountURL() throws Exception { String userMount = "/Users/r___/ro___/roo___/root/Public/file.jpg"; String userMount1 = "/Users/r___/ro___/file.jpg"; String userMount2 = "/Users/file.jpg"; String spaceMount = "/Groups/spaces/spacea/Documents/Activity%20Stream%20Documents/file.jpg"; String spaceMount1 = "/Groups/spaces/spacea/file.jpg"; String spaceMount2 = "/Groups/spaces/file.jpg"; String groupMount = "/Groups/platform/administrators/Documents/file.jpg"; String groupMount1 = "/Groups/platform/file.jpg"; String groupMount2 = "/Groups/file.jpg"; String sitesMount = "/sites/intranet/documents/file.jpg"; String sitesMount1 = "/sites/intranet/file.jpg"; String sitesMount2 = "/sites/file.jpg"; String other = "/folder1/folder2/folder3/folder4/folder5/file.jpg"; String other1 = "/folder1/folder2/file.jpg"; String other2 = "/file.jpg"; String result = Utils.generateMountURL(userMount, "collaboration" , "/Users", "/Groups"); assertEquals("/Users/r___/ro___/roo___/root/Public", result); result = Utils.generateMountURL(userMount, "myWS", "/Users", "/Groups"); assertEquals("/" , result); result = Utils.generateMountURL(userMount1, "collaboration" , "/Users", "/Groups"); assertEquals("/Users/r___/ro___", result); result = Utils.generateMountURL(userMount2, "collaboration" , "/Users", "/Groups"); assertEquals("/Users", result); result = Utils.generateMountURL(spaceMount, "collaboration" , "/Users", "/Groups"); assertEquals("/Groups/spaces/spacea/Documents", result); result = Utils.generateMountURL(spaceMount1, "collaboration" , "/Users", "/Groups"); assertEquals("/Groups/spaces/spacea", result); result = Utils.generateMountURL(spaceMount2, "collaboration" , "/Users", "/Groups"); assertEquals("/Groups/spaces", result); result = Utils.generateMountURL(groupMount, "collaboration" , "/Users", "/Groups"); assertEquals("/Groups/platform", result); result = Utils.generateMountURL(groupMount1, "collaboration" , "/Users", "/Groups"); assertEquals("/Groups/platform", result); result = Utils.generateMountURL(groupMount2, "collaboration" , "/Users", "/Groups"); assertEquals("/Groups", result); result = Utils.generateMountURL(sitesMount, "collaboration" , "/Users", "/Groups"); assertEquals("/sites/intranet", result); result = Utils.generateMountURL(sitesMount1, "collaboration" , "/Users", "/Groups"); assertEquals("/sites/intranet", result); result = Utils.generateMountURL(sitesMount2, "collaboration" , "/Users", "/Groups"); assertEquals("/sites", result); result = Utils.generateMountURL(other, "collaboration" , "/Users", "/Groups"); assertEquals("/folder1/folder2/folder3" , result); result = Utils.generateMountURL(other1, "collaboration" , "/Users", "/Groups"); assertEquals("/folder1/folder2" , result); result = Utils.generateMountURL(other2, "collaboration" , "/Users", "/Groups"); assertEquals("/" , result); } @Test public void testEncodePath() { assertEquals("/path1/path2/path3", Utils.encodePath("/path1/path2/path3", "UTF-8")); assertEquals("/path1/path2%2B/path%2B3", Utils.encodePath("/path1/path2+/path+3", "UTF-8")); } }
3,738
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PermissionsGroupVisibilityPluginTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/test/java/org/exoplatform/ecm/webui/selector/PermissionsGroupVisibilityPluginTest.java
package org.exoplatform.ecm.webui.selector; import org.exoplatform.portal.config.GroupVisibilityPlugin; import org.exoplatform.portal.config.UserACL; import org.exoplatform.services.organization.Group; import org.exoplatform.services.organization.impl.GroupImpl; import org.exoplatform.services.security.Identity; import org.exoplatform.services.security.MembershipEntry; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PermissionsGroupVisibilityPluginTest { @Test public void shouldHasPermissionWhenUserIsSuperUser() { // Given UserACL userACL = mock(UserACL.class); when(userACL.getSuperUser()).thenReturn("john"); GroupVisibilityPlugin plugin = new PermissionsGroupVisibilityPlugin(userACL); Identity userIdentity = new Identity("john", Arrays.asList(new MembershipEntry("/platform/users", "manager"))); Group groupPlatform = new GroupImpl(); groupPlatform.setId("/platform"); Group groupPlatformUsers = new GroupImpl(); groupPlatformUsers.setId("/platform/users"); // When boolean hasPermissionOnPlatform = plugin.hasPermission(userIdentity, groupPlatform); boolean hasPermissionOnPlatformUsers = plugin.hasPermission(userIdentity, groupPlatformUsers); // Then assertTrue(hasPermissionOnPlatform); assertTrue(hasPermissionOnPlatformUsers); } @Test public void shouldHasPermissionWhenUserIsPlatformAdministrator() { // Given UserACL userACL = mock(UserACL.class); when(userACL.getSuperUser()).thenReturn("root"); when(userACL.getAdminGroups()).thenReturn("/platform/administrators"); GroupVisibilityPlugin plugin = new PermissionsGroupVisibilityPlugin(userACL); Identity userIdentity = new Identity("john", Arrays.asList(new MembershipEntry("/platform/administrators", "manager"))); Group groupPlatform = new GroupImpl(); groupPlatform.setId("/platform"); Group groupPlatformUsers = new GroupImpl(); groupPlatformUsers.setId("/platform/users"); // When boolean hasPermissionOnPlatform = plugin.hasPermission(userIdentity, groupPlatform); boolean hasPermissionOnPlatformUsers = plugin.hasPermission(userIdentity, groupPlatformUsers); // Then assertTrue(hasPermissionOnPlatform); assertTrue(hasPermissionOnPlatformUsers); } @Test public void shouldHasPermissionWhenUserIsInGivenGroup() { // Given UserACL userACL = mock(UserACL.class); when(userACL.getSuperUser()).thenReturn("root"); when(userACL.getAdminGroups()).thenReturn("/platform/administrators"); GroupVisibilityPlugin plugin = new PermissionsGroupVisibilityPlugin(userACL); Identity userIdentity = new Identity("john", Arrays.asList(new MembershipEntry("/platform/developers", "manager"), new MembershipEntry("/platform/testers", "member"), new MembershipEntry("/spaces/marketing", "member"), new MembershipEntry("/spaces/sales", "manager"), new MembershipEntry("/organization/rh", "*"))); Group groupPlatform = new GroupImpl(); groupPlatform.setId("/platform"); Group groupPlatformDevelopers = new GroupImpl(); groupPlatformDevelopers.setId("/platform/developers"); Group groupPlatformTesters = new GroupImpl(); groupPlatformTesters.setId("/platform/testers"); Group groupSpaces = new GroupImpl(); groupSpaces.setId("/spaces"); Group groupSpacesMarketing = new GroupImpl(); groupSpacesMarketing.setId("/spaces/marketing"); Group groupSpacesSales = new GroupImpl(); groupSpacesSales.setId("/spaces/sales"); Group groupSpacesEngineering = new GroupImpl(); groupSpacesEngineering.setId("/spaces/engineering"); Group groupOrganization = new GroupImpl(); groupOrganization.setId("/organization"); Group groupOrganizationRh = new GroupImpl(); groupOrganizationRh.setId("/organization/rh"); // When boolean hasPermissionOnPlatform = plugin.hasPermission(userIdentity, groupPlatform); boolean hasPermissionOnPlatformDevelopers = plugin.hasPermission(userIdentity, groupPlatformDevelopers); boolean hasPermissionOnPlatformTesters = plugin.hasPermission(userIdentity, groupPlatformTesters); boolean hasPermissionOnSpaces = plugin.hasPermission(userIdentity, groupSpaces); boolean hasPermissionOnSpacesMarketing = plugin.hasPermission(userIdentity, groupSpacesMarketing); boolean hasPermissionOnSpacesSales = plugin.hasPermission(userIdentity, groupSpacesSales); boolean hasPermissionOnSpacesEngineering = plugin.hasPermission(userIdentity, groupSpacesEngineering); boolean hasPermissionOnOrganization = plugin.hasPermission(userIdentity, groupOrganization); boolean hasPermissionOnOrganizationRh = plugin.hasPermission(userIdentity, groupOrganizationRh); // Then assertTrue(hasPermissionOnPlatform); assertTrue(hasPermissionOnPlatformDevelopers); assertFalse(hasPermissionOnPlatformTesters); assertTrue(hasPermissionOnSpaces); assertTrue(hasPermissionOnSpacesMarketing); assertTrue(hasPermissionOnSpacesSales); assertFalse(hasPermissionOnSpacesEngineering); assertTrue(hasPermissionOnOrganization); assertTrue(hasPermissionOnOrganizationRh); } @Test public void shouldHasPermissionWhenUserIsOnlyMemberOfSpaces() { // Given UserACL userACL = mock(UserACL.class); when(userACL.getSuperUser()).thenReturn("root"); when(userACL.getAdminGroups()).thenReturn("/platform/administrators"); GroupVisibilityPlugin plugin = new PermissionsGroupVisibilityPlugin(userACL); Identity userIdentity = new Identity("john", Arrays.asList(new MembershipEntry("/spaces/marketing", "member"), new MembershipEntry("/spaces/sales", "redactor"))); Group groupSpaces = new GroupImpl(); groupSpaces.setId("/spaces"); Group groupSpacesMarketing = new GroupImpl(); groupSpacesMarketing.setId("/spaces/marketing"); Group groupSpacesSales = new GroupImpl(); groupSpacesSales.setId("/spaces/sales"); Group groupSpacesEngineering = new GroupImpl(); groupSpacesEngineering.setId("/spaces/engineering"); // When boolean hasPermissionOnSpaces = plugin.hasPermission(userIdentity, groupSpaces); boolean hasPermissionOnSpacesMarketing = plugin.hasPermission(userIdentity, groupSpacesMarketing); boolean hasPermissionOnSpacesSales = plugin.hasPermission(userIdentity, groupSpacesSales); boolean hasPermissionOnSpacesEngineering = plugin.hasPermission(userIdentity, groupSpacesEngineering); // Then assertTrue(hasPermissionOnSpaces); assertTrue(hasPermissionOnSpacesMarketing); assertTrue(hasPermissionOnSpacesSales); assertFalse(hasPermissionOnSpacesEngineering); } }
7,040
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
SEOPageMetadataApplicationLifecycle.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/SEOPageMetadataApplicationLifecycle.java
package org.exoplatform.wcm.webui; import java.util.ArrayList; import java.util.Enumeration; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.container.component.BaseComponentPlugin; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.application.RequestNavigationData; import org.exoplatform.portal.mop.SiteKey; import org.exoplatform.portal.mop.SiteType; import org.exoplatform.portal.mop.user.*; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.seo.PageMetadataModel; import org.exoplatform.services.seo.SEOService; import org.exoplatform.web.application.*; import org.exoplatform.webui.application.WebuiRequestContext; public class SEOPageMetadataApplicationLifecycle extends BaseComponentPlugin implements ApplicationLifecycle<WebuiRequestContext> { private static final Log LOG = ExoLogger.getLogger(SEOPageMetadataApplicationLifecycle.class.toString()); public void onInit(Application app) { } public void onStartRequest(final Application app, final WebuiRequestContext context) throws Exception { PortalRequestContext pcontext = (PortalRequestContext) context; String requestPath = pcontext.getControllerContext().getParameter(RequestNavigationData.REQUEST_PATH); String siteName = pcontext.getSiteName(); try { if (pcontext.getSiteType().equals(SiteType.PORTAL)) { // Get page SEOService seoService = CommonsUtils.getService(SEOService.class); ArrayList<String> paramArray = null; if (!pcontext.useAjax()) { Enumeration<String> params = pcontext.getRequest().getParameterNames(); if (params.hasMoreElements()) { paramArray = new ArrayList<>(); while (params.hasMoreElements()) { String contentParam = params.nextElement(); paramArray.add(pcontext.getRequestParameter(contentParam)); } } } UserPortal userPortal = pcontext.getUserPortal(); UserNavigation navigation = userPortal.getNavigation(SiteKey.portal(siteName)); UserNodeFilterConfig.Builder builder = UserNodeFilterConfig.builder(); String nodePath = pcontext.getNodePath(); UserNode currentNode = null; if (StringUtils.isBlank(nodePath)) { currentNode = userPortal.getDefaultPath(builder.build()); } else { currentNode = userPortal.resolvePath(navigation, builder.build(), nodePath); } if (currentNode != null && currentNode.getPageRef() != null && SiteType.PORTAL.equals(currentNode.getPageRef().getSite().getType())) { String pageReference = currentNode.getPageRef().format(); PageMetadataModel metaModel = seoService.getMetadata(paramArray, pageReference, pcontext.getLocale().getLanguage()); if (metaModel != null) { pcontext.setAttribute("PAGE_METADATA", metaModel); if (StringUtils.isNotBlank(metaModel.getTitle())) { pcontext.getRequest().setAttribute(PortalRequestContext.REQUEST_TITLE, metaModel.getTitle()); } } } } } catch (Exception e) { LOG.warn("Error getting page SEO of site {} with path {}", siteName, requestPath, e); } } public void onFailRequest(Application app, WebuiRequestContext context, RequestFailure failureType) { } public void onEndRequest(Application app, WebuiRequestContext context) throws Exception { } public void onDestroy(Application app) { } }
3,646
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
WebUIPropertiesConfigService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/WebUIPropertiesConfigService.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang3.StringUtils; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.PropertiesParam; /** * Created by The eXo Platform SAS * Author : Hoa Pham * hoa.phamvu@exoplatform.com * Dec 13, 2008 */ public class WebUIPropertiesConfigService { /** The Constant SCV_POPUP_SIZE_EDIT_PORTLET_MODE. */ public final static String SCV_POPUP_SIZE_EDIT_PORTLET_MODE = "SCV.popup.size.in.edit.portlet.mode"; /** The Constant SCV_POPUP_SIZE_QUICK_EDIT. */ public final static String SCV_POPUP_SIZE_QUICK_EDIT = "SCV.popup.size.in.quickdedit"; /** The Constant CLV_POPUP_SIZE_EDIT_PORTLET_MODE. */ public final static String CLV_POPUP_SIZE_EDIT_PORTLET_MODE = "CLV.popup.size.in.edit.portlet.mode"; /** The Constant CLV_POPUP_SIZE_QUICK_EDIT. */ public final static String CLV_POPUP_SIZE_QUICK_EDIT = "CLV.popup.size.in.quickedit"; /** The properties map. */ private ConcurrentHashMap<String,Object> propertiesMap = new ConcurrentHashMap<String,Object>(); /** * Instantiates a new web ui properties config service. * * @param params the params */ @SuppressWarnings("unchecked") public WebUIPropertiesConfigService(InitParams params) { for(Iterator iterator = params.getPropertiesParamIterator();iterator.hasNext();) { PropertiesParam propertiesParam = (PropertiesParam)iterator.next(); if(SCV_POPUP_SIZE_EDIT_PORTLET_MODE.equalsIgnoreCase(propertiesParam.getName())) { PopupWindowProperties properties = readPropertiesFromXML(propertiesParam); propertiesMap.put(SCV_POPUP_SIZE_EDIT_PORTLET_MODE,properties); }else if(SCV_POPUP_SIZE_QUICK_EDIT.equals(propertiesParam.getName())) { PopupWindowProperties properties = readPropertiesFromXML(propertiesParam); propertiesMap.put(SCV_POPUP_SIZE_QUICK_EDIT,properties); }else if(CLV_POPUP_SIZE_QUICK_EDIT.equals(propertiesParam.getName())) { PopupWindowProperties properties = readPropertiesFromXML(propertiesParam); propertiesMap.put(CLV_POPUP_SIZE_QUICK_EDIT,properties); }else if(CLV_POPUP_SIZE_EDIT_PORTLET_MODE.equals(propertiesParam.getName())) { PopupWindowProperties properties = readPropertiesFromXML(propertiesParam); propertiesMap.put(CLV_POPUP_SIZE_EDIT_PORTLET_MODE,properties); } } } /** * Gets the properties. * * @param name the name * * @return the properties */ public Object getProperties(String name) { return propertiesMap.get(name); } /** * Read properties from xml. * * @param param the param * * @return the popup window properties */ private PopupWindowProperties readPropertiesFromXML(PropertiesParam param) { PopupWindowProperties properties = new PopupWindowProperties(); String width = param.getProperty(PopupWindowProperties.WIDTH); String height = param.getProperty(PopupWindowProperties.HEIGHT); if(width != null && StringUtils.isNumeric(width)) { properties.setWidth(Integer.parseInt(width)); } if(height != null && StringUtils.isNumeric(height)) { properties.setHeight(Integer.parseInt(height)); } return properties; } /** * The Class PopupWindowProperties. */ public static class PopupWindowProperties { /** The Constant WIDTH. */ public final static String WIDTH = "width"; /** The Constant HEIGHT. */ public final static String HEIGHT = "height"; /** The width. */ private int width = 500; /** The height. */ private int height = 300; /** * Gets the width. * * @return the width */ public int getWidth() { return width; } /** * Sets the width. * * @param width the new width */ public void setWidth(int width) { this.width = width;} /** * Gets the height. * * @return the height */ public int getHeight() { return height; } /** * Sets the height. * * @param height the new height */ public void setHeight(int height) { this.height = height; } } }
5,058
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
Utils.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/Utils.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui; import java.io.InputStream; import java.security.AccessControlException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import javax.jcr.Workspace; import javax.jcr.nodetype.NodeType; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.portlet.PortletMode; import javax.portlet.PortletPreferences; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.download.DownloadService; import org.exoplatform.download.InputStreamDownloadResource; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.ecm.utils.lock.LockUtil; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.config.UserACL; import org.exoplatform.portal.config.UserPortalConfigService; import org.exoplatform.portal.config.model.PortalConfig; import org.exoplatform.portal.mop.SiteType; import org.exoplatform.portal.mop.page.PageContext; import org.exoplatform.portal.mop.page.PageKey; import org.exoplatform.portal.mop.SiteKey; import org.exoplatform.portal.mop.user.UserNavigation; import org.exoplatform.portal.mop.user.UserNode; import org.exoplatform.portal.mop.user.UserPortal; import org.exoplatform.portal.webui.page.UIPage; import org.exoplatform.portal.webui.page.UIPageBody; import org.exoplatform.portal.webui.portal.UIPortal; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.portal.webui.workspace.UIMaskWorkspace; import org.exoplatform.portal.webui.workspace.UIPortalApplication; import org.exoplatform.portal.webui.workspace.UIWorkingWorkspace; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.mimetype.DMSMimeTypeResolver; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.security.Identity; import org.exoplatform.services.security.IdentityRegistry; import org.exoplatform.services.security.MembershipEntry; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.core.WCMConfigurationService; import org.exoplatform.portal.webui.util.NavigationUtils; import org.exoplatform.services.wcm.publication.PublicationDefaultStates; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.services.wcm.publication.WCMPublicationService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.core.UIPopupWindow; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.web.application.RequestContext; import org.exoplatform.web.url.navigation.NavigationResource; import org.exoplatform.web.url.navigation.NodeURL; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.UIPortletApplication; import com.ibm.icu.text.Transliterator; /** * Created by The eXo Platform SAS Author : Hoa Pham hoa.phamvu@exoplatform.com * Oct 23, 2008 */ public class Utils { /** The Quick edit attribute for HTTPSession */ public static final String TURN_ON_QUICK_EDIT = "turnOnQuickEdit"; private static final Log LOG = ExoLogger.getExoLogger(Utils.class); private static final String SQL_PARAM_PATTERN = "\\$\\{([^\\$\\{\\}])+\\}"; private static final String JCR_CONTENT = "jcr:content"; private static final String JCR_DATA = "jcr:data"; private static final String JCR_MIMETYPE = "jcr:mimeType"; private static final String NT_FILE = "nt:file"; private static final String NT_UNSTRUCTURED = "nt:unstructured"; private static final String DOCUMENTS_ACTIVITY = "documents"; /** * Checks if is edits the portlet in create page wizard. * @return true, if is edits the portlet in create page wizard */ public static boolean isEditPortletInCreatePageWizard() { UIPortalApplication portalApplication = Util.getUIPortalApplication(); UIMaskWorkspace uiMaskWS = portalApplication.getChildById(UIPortalApplication.UI_MASK_WS_ID); // show maskworkpace is being in Portal page edit mode if (uiMaskWS.getWindowWidth() > 0 && uiMaskWS.getWindowHeight() < 0) return true; return false; } /** * Checks if is quick editmode. * * @param container the current container * @param popupWindowId the popup window id * * @return true, if is quick editmode */ public static boolean isQuickEditMode(UIContainer container, String popupWindowId) { UIPopupContainer popupContainer = getPopupContainer(container); if (popupContainer == null) return false; UIPopupWindow popupWindow = popupContainer.getChildById(popupWindowId); if (popupWindow == null) return false; return true; } /** * Check if the portlet current mode is view mode or not * @param pContext The request context of a portlet * * @return return true if current portlet mode is view mode; otherwise return false */ public static boolean isPortletViewMode(PortletRequestContext pContext) { return PortletMode.VIEW.equals(pContext.getApplicationMode()); } public static boolean isPortalEditMode() { return Util.getUIPortalApplication().getModeState() != UIPortalApplication.NORMAL_MODE; } public static String getRealPortletId(PortletRequestContext portletRequestContext) { String portletId = portletRequestContext.getWindowId(); int modeState = Util.getUIPortalApplication().getModeState(); switch (modeState) { case UIPortalApplication.NORMAL_MODE: return portletId; case UIPortalApplication.APP_BLOCK_EDIT_MODE: return "UIPortlet-" + portletId; case UIPortalApplication.APP_VIEW_EDIT_MODE: return "EditMode-" + portletId; default: return null; } } /** * Can edit current portal. * * @param remoteUser the remote user * @return true, if successful * @throws Exception the exception */ public static boolean canEditCurrentPortal(String remoteUser) throws Exception { if (remoteUser == null) return false; IdentityRegistry identityRegistry = Util.getUIPortalApplication() .getApplicationComponent(IdentityRegistry.class); Identity identity = identityRegistry.getIdentity(remoteUser); if (identity == null) return false; UIPortal uiPortal = Util.getUIPortal(); // this code only work for single edit permission String editPermission = uiPortal.getEditPermission(); MembershipEntry membershipEntry = MembershipEntry.parse(editPermission); return identity.isMemberOf(membershipEntry); } /** * Clean string. * * @param str the str * @return the string */ public static String cleanString(String str) { Transliterator accentsconverter = Transliterator.getInstance("Latin; NFD; [:Nonspacing Mark:] Remove; NFC;"); str = accentsconverter.transliterate(str); // the character ? seems to not be changed to d by the transliterate // function StringBuffer cleanedStr = new StringBuffer(str.trim()); // delete special character for (int i = 0; i < cleanedStr.length(); i++) { char c = cleanedStr.charAt(i); if (c == ' ') { if (i > 0 && cleanedStr.charAt(i - 1) == '-') { cleanedStr.deleteCharAt(i--); } else { c = '-'; cleanedStr.setCharAt(i, c); } continue; } if (i > 0 && !(Character.isLetterOrDigit(c) || c == '-')) { cleanedStr.deleteCharAt(i--); continue; } if (i > 0 && c == '-' && cleanedStr.charAt(i - 1) == '-') cleanedStr.deleteCharAt(i--); } return cleanedStr.toString().toLowerCase(); } /** * Refresh whole portal by AJAX. * * @param context the portlet request context */ public static void updatePortal(PortletRequestContext context) { UIPortalApplication portalApplication = Util.getUIPortalApplication(); PortalRequestContext portalRequestContext = (PortalRequestContext) context.getParentAppRequestContext(); UIWorkingWorkspace uiWorkingWS = portalApplication.getChildById(UIPortalApplication.UI_WORKING_WS_ID); portalRequestContext.addUIComponentToUpdateByAjax(uiWorkingWS); portalRequestContext.ignoreAJAXUpdateOnPortlets(true); } /** * Gets the viewable node by WCMComposer (depends on site mode) * * @param repository the repository's name * @param workspace the workspace's name * @param nodeIdentifier the node's path or node's UUID * @return the viewable node. Return <code>null</code> if * <code>nodeIdentifier</code> is invalid * @see #getViewableNodeByComposer(String repository, String workspace, String * nodeIdentifier, String version) getViewableNodeByComposer() */ public static Node getViewableNodeByComposer(String repository, String workspace, String nodeIdentifier) { return getViewableNodeByComposer(repository, workspace, nodeIdentifier, null); } /** * Gets the viewable node by WCMComposer (depends on site mode) * * @param repository the repository's name * @param workspace the workspace's name * @param nodeIdentifier the node's path or node's UUID * @param version the base version (e.g. <code>WCMComposer.BASE_VERSION</code> * ) * @return the viewable node. Return <code>null</code> if * <code>nodeIdentifier</code> is invalid * @see #getViewableNodeByComposer(String repository, String workspace, String * nodeIdentifier) getViewableNodeByComposer() * @see WCMComposer */ public static Node getViewableNodeByComposer(String repository, String workspace, String nodeIdentifier, String version) { return getViewableNodeByComposer(repository, workspace, nodeIdentifier, version, WCMComposer.VISIBILITY_USER); } /** * Gets the viewable node by WCMComposer (depends on site mode) * * @param repository the repository's name * @param workspace the workspace's name * @param nodeIdentifier the node's path or node's UUID * @param version the base version (e.g. <code>WCMComposer.BASE_VERSION</code> * ) * @param cacheVisibility the visibility of cache * * @return the viewable node. Return <code>null</code> if * <code>nodeIdentifier</code> is invalid * @see #getViewableNodeByComposer(String repository, String workspace, String * nodeIdentifier) getViewableNodeByComposer() * @see WCMComposer */ public static Node getViewableNodeByComposer(String repository, String workspace, String nodeIdentifier, String version, String cacheVisibility) { try { HashMap<String, String> filters = new HashMap<String, String>(); StringBuffer filterLang = new StringBuffer(Util.getPortalRequestContext() .getLocale() .getLanguage()); String country = Util.getPortalRequestContext().getLocale().getCountry(); if (country != null && country.length() > 0) { filterLang.append("_").append(country); } filters.put(WCMComposer.FILTER_LANGUAGE, filterLang.toString()); filters.put(WCMComposer.FILTER_MODE, Utils.getCurrentMode()); PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); PortletMode portletMode = portletRequestContext.getApplicationMode(); filters.put(WCMComposer.PORTLET_MODE, portletMode.toString()); if (version != null) filters.put(WCMComposer.FILTER_VERSION, version); filters.put(WCMComposer.FILTER_VISIBILITY, cacheVisibility); return WCMCoreUtils.getService(WCMComposer.class) .getContent(workspace, Text.escapeIllegalJcrChars(nodeIdentifier), filters, WCMCoreUtils.getUserSessionProvider()); } catch (Exception e) { return null; } } /** * Gets the current mode of the site * * @return the current mode (e.g. <code>WCMComposer.MODE_EDIT</code>) * @see WCMComposer */ public static String getCurrentMode() { Object isQuickEditable = Util.getPortalRequestContext() .getRequest() .getSession() .getAttribute(TURN_ON_QUICK_EDIT); if (isQuickEditable == null) return WCMComposer.MODE_LIVE; boolean turnOnQuickEdit = Boolean.parseBoolean(isQuickEditable.toString()); return turnOnQuickEdit ? WCMComposer.MODE_EDIT : WCMComposer.MODE_LIVE; } /** * Check if the current mode is live mode or not * * @return return true if current mode is WCMComposer.MODE_LIVE; otherwise * false. */ public static boolean isLiveMode() { return WCMComposer.MODE_LIVE.equals(getCurrentMode()); } /** * Check if the content is draft and current mode of the site is edit mode * * @param content the content node. * @return true, the content is draft and current mode is edit mode, otherwise * return false. */ public static boolean isShowDraft(Node content) { if (content == null) return false; try { if (content.isNodeType("nt:frozenNode")) return false; WCMPublicationService wcmPublicationService = WCMCoreUtils.getService(WCMPublicationService.class); String contentState = wcmPublicationService.getContentState(content); boolean isDraftContent = false; if (PublicationDefaultStates.DRAFT.equals(contentState)) isDraftContent = true; boolean isShowDraft = false; if (WCMComposer.MODE_EDIT.equals(getCurrentMode())) isShowDraft = true; return isDraftContent && isShowDraft; } catch (Exception e) { return false; } } /** * Check if the current mode of the site is edit mode * * @return true, if current mode is edit mode */ public static boolean isShowQuickEdit() { try { boolean isEditMode = false; if (WCMComposer.MODE_EDIT.equals(getCurrentMode())) isEditMode = true; return isEditMode; } catch (Exception e) { return false; } } /** * Check if the user can delete the current node * * @return true, if current mode is edit mode * @throws RepositoryException * @throws AccessControlException */ public static boolean isShowDelete(Node content) throws RepositoryException { boolean isEditMode = false; if (WCMComposer.MODE_EDIT.equals(getCurrentMode())) isEditMode = true; try { ((ExtendedNode) content).checkPermission(PermissionType.SET_PROPERTY); ((ExtendedNode) content).checkPermission(PermissionType.ADD_NODE); ((ExtendedNode) content).checkPermission(PermissionType.REMOVE); } catch (AccessControlException e) { isEditMode = false; } catch (Exception e) { String nodePath = null; try { nodePath = content.getPath(); } catch (Exception e1) { // Nothing to log } LOG.error("Error while checking permissions on node " + nodePath, e); isEditMode = false; } return isEditMode; } /** * Check if the content is editable and current mode of the site is edit mode * * @param content the content node * @return true if there is no content if the content is editable and current * mode is edit mode */ public static boolean isShowQuickEdit(Node content) { if (content == null) return true; try { boolean isEditMode = false; if (WCMComposer.MODE_EDIT.equals(getCurrentMode()) || Util.getUIPortalApplication().getModeState() != UIPortalApplication.NORMAL_MODE) isEditMode = true; ((ExtendedNode) content).checkPermission(PermissionType.SET_PROPERTY); ((ExtendedNode) content).checkPermission(PermissionType.ADD_NODE); ((ExtendedNode) content).checkPermission(PermissionType.REMOVE); return isEditMode; } catch (Exception e) { return false; } } public static String getEditLink(Node node, boolean isEditable, boolean isNew) { try { ManageDriveService manageDriveService = WCMCoreUtils.getService(ManageDriveService.class); String nodeWorkspace = node.getSession().getWorkspace().getName(); String driveWorkspace = nodeWorkspace; List<DriveData> listDrive = manageDriveService.getAllDrives(); for(DriveData drive : listDrive) { if(drive.getWorkspace().equals(nodeWorkspace) && node.getPath().startsWith(drive.getHomePath())) { driveWorkspace = drive.getName(); break; } } String itemPath = driveWorkspace + node.getPath(); return getEditLink(itemPath, isEditable, isNew); } catch (RepositoryException re) { return null; } catch(Exception e) { return null; } } public static String getActivityEditLink(Node node) { try { String itemPath = node.getSession().getWorkspace().getName() + node.getPath(); return getActivityEditLink(itemPath); } catch (RepositoryException e) { return null; } } /** * Creates a restfull compliant link to the editor for editing a content, * adding a content or managing contents. Example : Add Content : isEditable = * false, isNew = true, itemPath = the parent folder path Edit Content : * isEditable = true, isNew = false, itemPath = the content path Manage * Contents = isEditable = false, isNew = false, itemPath = the folder path * * @param itemPath * @param isEditable * @param isNew * @return */ public static String getEditLink(String itemPath, boolean isEditable, boolean isNew) { PortalRequestContext pContext = Util.getPortalRequestContext(); String backto = pContext.getRequestURI(); WCMConfigurationService configurationService = Util.getUIPortalApplication() .getApplicationComponent(WCMConfigurationService.class); String editorPageURI = configurationService.getRuntimeContextParam( isEditable || isNew ? WCMConfigurationService.EDITOR_PAGE_URI : WCMConfigurationService.SITE_EXPLORER_URI); UserNode editorNode = getEditorNode(editorPageURI); if (editorNode == null) { return ""; } NodeURL nodeURL = pContext.createURL(NodeURL.TYPE); nodeURL.setNode(editorNode).setQueryParameterValue("path", itemPath); if (isEditable) { nodeURL.setQueryParameterValue("edit", "true"); } if (isNew) { nodeURL.setQueryParameterValue("addNew", "true"); } nodeURL.setQueryParameterValue(org.exoplatform.ecm.webui.utils.Utils.URL_BACKTO, backto); return nodeURL.toString(); } public static String getActivityEditLink(String itemPath) { PortalRequestContext pContext = Util.getPortalRequestContext(); String siteType = pContext.getSiteKey().getType().getName(); String backto = pContext.getRequestURI(); WCMConfigurationService configurationService = Util.getUIPortalApplication() .getApplicationComponent(WCMConfigurationService.class); String editorPageURI = null; if(siteType.equals(PortalConfig.PORTAL_TYPE)) editorPageURI = configurationService.getRuntimeContextParam(WCMConfigurationService.EDIT_PAGE_URI); else if(siteType.equals(PortalConfig.GROUP_TYPE)) { StringBuffer sb = new StringBuffer(); editorPageURI = pContext.getSiteName(); editorPageURI = editorPageURI.substring(editorPageURI.lastIndexOf("/")+1, editorPageURI.length()); sb.append(editorPageURI).append("/").append(DOCUMENTS_ACTIVITY); editorPageURI = sb.toString(); } UserNode editorNode = getEditorNode(editorPageURI, siteType); if (editorNode == null) { return ""; } NodeURL nodeURL = pContext.createURL(NodeURL.TYPE); nodeURL.setNode(editorNode); nodeURL.setQueryParameterValue("path", itemPath); nodeURL.setQueryParameterValue("edit", "true"); nodeURL.setQueryParameterValue(org.exoplatform.ecm.webui.utils.Utils.URL_BACKTO, backto); return nodeURL.toString(); } private static UserNode getEditorNode(String editorPageURI, String siteType) { UserPortal userPortal = Util.getPortalRequestContext().getUserPortalConfig().getUserPortal(); List<UserNavigation> allNavs = userPortal.getNavigations(); for (UserNavigation nav : allNavs) { if (nav.getKey().getType().getName().equalsIgnoreCase(siteType)) { UserNode userNode = userPortal.resolvePath(nav, null, editorPageURI); if (userNode != null) { return userNode; } } } return null; } private static UserNode getEditorNode(String editorPageURI) { UserPortal userPortal = Util.getPortalRequestContext().getUserPortalConfig().getUserPortal(); List<UserNavigation> allNavs = userPortal.getNavigations(); for (UserNavigation nav : allNavs) { if (nav.getKey().getType().equals(SiteType.GROUP)) { UserNode userNode = userPortal.resolvePath(nav, null, editorPageURI); if (userNode != null) { return userNode; } } } return null; } /** * Creates the popup window. Each portlet have a <code>UIPopupContainer</code> * . <br> * Every <code>UIPopupWindow</code> created by this method is belong to this * container. * * @param container the current container * @param component the component which will be display as a popup * @param popupWindowId the popup's ID * @param width the width of the popup * @throws Exception the exception */ public static void createPopupWindow(UIContainer container, UIComponent component, String popupWindowId, int width) throws Exception { UIPopupContainer popupContainer = initPopup(container, component, popupWindowId, width); WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); requestContext.addUIComponentToUpdateByAjax(popupContainer); } /** * Creates the popup window. Each portlet have a <code>UIPopupContainer</code> * . <br> * Every <code>UIPopupWindow</code> created by this method is belong to this * container. * * @param container the current container * @param component the component which will be display as a popup * @param popupWindowId the popup's ID * @param width the width of the popup * @param isShowMask Set as true to create mask layer * @throws Exception the exception */ public static void createPopupWindow(UIContainer container, UIComponent component, String popupWindowId, int width, boolean isShowMask) throws Exception { UIPopupContainer popupContainer = initPopup(container, component, popupWindowId, width); UIPopupWindow popupWindow = popupContainer.getChildById(popupWindowId); popupWindow.setShowMask(isShowMask); WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); requestContext.addUIComponentToUpdateByAjax(popupContainer); } /** * Creates the popup window. Each portlet have a <code>UIPopupContainer</code> * . <br> * Every <code>UIPopupWindow</code> created by this method is belong to this * container. * * @param container the current container * @param component the component which will be display as a popup * @param popupWindowId the popup's ID * @param width the width of the popup * @param top the top of the popup * @param left the left of the popup * @throws Exception the exception */ public static void createPopupWindow(UIContainer container, UIComponent component, String popupWindowId, int width, int top, int left) throws Exception { UIPopupContainer popupContainer = initPopup(container, component, popupWindowId, width); UIPopupWindow popupWindow = popupContainer.getChildById(popupWindowId); popupWindow.setCoordindate(top, left); WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); requestContext.addUIComponentToUpdateByAjax(popupContainer); } public static void createPopupWindow(UIContainer container, UIComponent component, String popupWindowId, boolean isMiddle, int width) throws Exception { UIPopupContainer popupContainer = initPopup(container, component, popupWindowId, width); UIPopupWindow popupWindow = popupContainer.getChildById(popupWindowId); popupWindow.setMiddle(isMiddle); WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); requestContext.addUIComponentToUpdateByAjax(popupContainer); } private static UIPopupContainer initPopup(UIContainer container, UIComponent component, String popupWindowId, int width) throws Exception { UIPopupContainer popupContainer = getPopupContainer(container); popupContainer.removeChildById(popupWindowId); popupContainer.removeChildById("UIPopupWindow"); UIPopupWindow popupWindow = popupContainer.addChild(UIPopupWindow.class, null, popupWindowId); popupWindow.setUIComponent(component); popupWindow.setWindowSize(width, 0); popupWindow.setShow(true); popupWindow.setRendered(true); popupWindow.setResizable(true); popupWindow.setShowMask(true); return popupContainer; } /** * Close popup window. * * @param container the current container * @param popupWindowId the popup's ID */ public static void closePopupWindow(UIContainer container, String popupWindowId) { UIPopupContainer popupContainer = getPopupContainer(container); popupContainer.removeChildById(popupWindowId); } /** * Update popup window. * * @param container the container * @param component the component which will be replace for the old one in the * same popup * @param popupWindowId the popup's ID */ public static void updatePopupWindow(UIContainer container, UIComponent component, String popupWindowId) { UIPopupContainer popupContainer = getPopupContainer(container); UIPopupWindow popupWindow = popupContainer.getChildById(popupWindowId); popupWindow.setUIComponent(component); } /** * Gets the popup container. * * @param container the current container * @return the popup container */ public static UIPopupContainer getPopupContainer(UIContainer container) { if (container instanceof UIPortletApplication) return container.getChild(UIPopupContainer.class); UIPortletApplication portletApplication = container.getAncestorOfType(UIPortletApplication.class); return portletApplication.getChild(UIPopupContainer.class); } /** * Creates the popup message. * * @param container the current container * @param message the message key * @param args the arguments to show in the message * @param type the message's type (e.g. <code>ApplicationMessage.INFO</code>) * @see ApplicationMessage */ public static void createPopupMessage(UIContainer container, String message, Object[] args, int type) { UIApplication application = container.getAncestorOfType(UIApplication.class); application.addMessage(new ApplicationMessage(message, args, type)); } /** * Get one portlet preference by name * * @param preferenceName the name of preference * @return the portlet preference's value */ public static String getPortletPreference(String preferenceName) { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); PortletPreferences preferences = portletRequestContext.getRequest().getPreferences(); return preferences.getValue(preferenceName, null); } /** * Get all portlet preferences * * @return all portlet preferences */ public static PortletPreferences getAllPortletPreferences() { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); return portletRequestContext.getRequest().getPreferences(); } /** * Check if the node is viewable for the current user or not viewable. <br> * return True if the node is viewable, otherwise will return False * * @param node: The node to check */ public static boolean isViewable(Node node) { try { node.refresh(true); ((ExtendedNode) node).checkPermission(PermissionType.READ); } catch (Exception e) { return false; } return true; } /** * Get the real node from frozen node, symlink node return True if the node is * viewable, otherwise will return False * * @param node: The node to check */ public static Node getRealNode(Node node) throws Exception { // TODO: Need to add to check symlink node if (node.isNodeType("nt:frozenNode")) { String uuid = node.getProperty("jcr:frozenUuid").getString(); return node.getSession().getNodeByUUID(uuid); } return node; } public static String getRealNodePath(Node node) throws Exception { if (node.isNodeType("nt:frozenNode")) { Node realNode = getRealNode(node); return Text.escape(realNode.getPath(),'%',true) + "?version=" + node.getParent().getName(); } return Text.escape(node.getPath(),'%',true); } public static String getWebdavURL(Node node) throws Exception { return getWebdavURL(node, true); } public static String getWebdavURL(Node node, boolean withTimeParam) throws Exception { return getWebdavURL(node, withTimeParam, true); } public static String getWebdavURL(Node node, boolean withTimeParam, boolean isGetRealNodePath) throws Exception { NodeLocation location = NodeLocation.getNodeLocationByNode(getRealNode(node)); String repository = location.getRepository(); String workspace = location.getWorkspace(); String currentProtal = PortalContainer.getCurrentRestContextName(); String portalName = PortalContainer.getCurrentPortalContainerName(); String originalNodePath = isGetRealNodePath ? getRealNodePath(node) : Text.escape(node.getPath(),'%',true); StringBuffer imagePath = new StringBuffer(); imagePath.append("/") .append(portalName) .append("/") .append(currentProtal) .append("/jcr/") .append(repository) .append("/") .append(workspace) .append(originalNodePath); if (withTimeParam) { if (imagePath.indexOf("?") > 0) { imagePath.append("&time="); } else { imagePath.append("?time="); } imagePath.append(System.currentTimeMillis()); } return imagePath.toString(); } /** * GetRealNode * * @param strRepository * @param strWorkspace * @param strIdentifier * @return the required node/ the target of a symlink node / null if node was * in trash. * @throws RepositoryException */ public static Node getRealNode(String strRepository, String strWorkspace, String strIdentifier, boolean isWCMBase) throws RepositoryException { return getRealNode(strRepository, strWorkspace, strIdentifier, isWCMBase, WCMComposer.VISIBILITY_USER); } /** * GetRealNode * * @param strRepository * @param strWorkspace * @param strIdentifier * @param cacheVisibility the visibility of cache * * @return the required node/ the target of a symlink node / null if node was * in trash. * @throws RepositoryException */ public static Node getRealNode(String strRepository, String strWorkspace, String strIdentifier, boolean isWCMBase, String cacheVisibility) throws RepositoryException { LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class); Node selectedNode; if (isWCMBase) { selectedNode = getViewableNodeByComposer(strRepository, strWorkspace, strIdentifier, WCMComposer.BASE_VERSION, cacheVisibility); } else { selectedNode = getViewableNodeByComposer(strRepository, strWorkspace, strIdentifier, null, cacheVisibility); } if (selectedNode != null) { if (!org.exoplatform.ecm.webui.utils.Utils.isInTrash(selectedNode)) { if (linkManager.isLink(selectedNode)) { if (linkManager.isTargetReachable(selectedNode)) { selectedNode = linkManager.getTarget(selectedNode); if (!org.exoplatform.ecm.webui.utils.Utils.isInTrash(selectedNode)) { return selectedNode; } } } else { return selectedNode; } } } return null; } public static boolean hasEditPermissionOnPage() throws Exception { UIPortalApplication portalApp = Util.getUIPortalApplication(); UIWorkingWorkspace uiWorkingWS = portalApp.getChildById(UIPortalApplication.UI_WORKING_WS_ID); UIPageBody pageBody = uiWorkingWS.findFirstComponentOfType(UIPageBody.class); UIPage uiPage = (UIPage) pageBody.getUIComponent(); UserACL userACL = portalApp.getApplicationComponent(UserACL.class); if (uiPage != null) { return userACL.hasEditPermissionOnPage(uiPage.getOwnerType(), uiPage.getOwnerId(), uiPage.getEditPermission()); } UIPortal currentUIPortal = portalApp.<UIWorkingWorkspace> findComponentById(UIPortalApplication.UI_WORKING_WS_ID) .findFirstComponentOfType(UIPortal.class); UserNode currentNode = currentUIPortal.getSelectedUserNode(); PageKey pageReference = currentNode.getPageRef(); if (pageReference == null) { return false; } UserPortalConfigService portalConfigService = portalApp.getApplicationComponent(UserPortalConfigService.class); PageContext page = portalConfigService.getPage(pageReference); if (page == null) { return false; } return userACL.hasEditPermission(page); } public static boolean hasEditPermissionOnNavigation() throws Exception { UserNavigation selectedNavigation = getSelectedNavigation(); if(selectedNavigation == null) return false; return selectedNavigation.isModifiable(); } public static boolean hasEditPermissionOnPortal() throws Exception { UIPortalApplication portalApp = Util.getUIPortalApplication(); UIPortal currentUIPortal = portalApp.<UIWorkingWorkspace> findComponentById(UIPortalApplication.UI_WORKING_WS_ID) .findFirstComponentOfType(UIPortal.class); UserACL userACL = portalApp.getApplicationComponent(UserACL.class); return userACL.hasEditPermissionOnPortal(currentUIPortal.getSiteKey().getTypeName(), currentUIPortal.getSiteKey().getName(), currentUIPortal.getEditPermission()); } public static UserNavigation getSelectedNavigation() throws Exception { SiteKey siteKey = Util.getUIPortal().getSiteKey(); return NavigationUtils.getUserNavigation( Util.getPortalRequestContext().getUserPortalConfig().getUserPortal(), siteKey); } public static boolean isEmptyContent(String inputValue) { boolean isEmpty = true; inputValue = inputValue.trim().replaceAll("<p>", "").replaceAll("</p>", ""); inputValue = inputValue.replaceAll("\n", "").replaceAll("\t",""); inputValue = inputValue.replaceAll("&nbsp;", ""); if(inputValue != null && inputValue.length() > 0) return false; return isEmpty; } /** * @param workspace * @param strQuery * @param SQLLanguage * @return true as valid query, false as Invalid */ public static boolean checkQuery(String workspace, String strQuery, String SQLLanguage) { try { Session session = WCMCoreUtils.getUserSessionProvider().getSession(workspace, WCMCoreUtils.getService(RepositoryService.class).getCurrentRepository()); QueryManager qm = session.getWorkspace().getQueryManager(); Query query = qm.createQuery(strQuery, SQLLanguage); query.execute(); }catch(Exception e) { return false; } return true; } /** * get the parameter list from SQL query, the parameter have the ${PARAM} format. <br> * For example: * <ul> * <li>${folder-id}</li> * <li>${user}</li> * <li>${lang}</li> * </ul> * @param sqlQuery the given input SQL query * @return a list of parameter in input SQL query */ public static HashSet<String> getQueryParams(String sqlQuery) { HashSet<String> params = new HashSet<String>(); if (sqlQuery == null) { return params; } Matcher matcher = Pattern.compile(SQL_PARAM_PATTERN).matcher(sqlQuery); while (matcher.find()) { String param = matcher.group(); param = param.replaceAll("\\$\\{", "").replaceAll("\\}", ""); params.add(param); } return params; } /** * Replace the parameter with the relevant value from <code>params</code>to * build the SQL query * * @param sqlQuery the input query that contain parameter * @param params list of all parameter(key, value) pass to the query * @return SQL query after replacing the parameter with value */ public static String buildQuery(String sqlQuery, HashMap<String, String> params) { if (!hasParam(sqlQuery) || params == null || params.isEmpty()) { return sqlQuery; } String query = sqlQuery; for (String param : params.keySet()) { query = query.replaceAll("\\$\\{" + param + "\\}", params.get(param)); } return query; } /** * Check if the input SQL query contains any parameter or not. * * @param sqlQuery * @return <code>false</code> if input SQL query does not contain any * parameter <br> * <code>true</code> if input SQL query one or more parameter */ public static boolean hasParam(String sqlQuery) { if (sqlQuery == null || sqlQuery.trim().length() == 0) { return false; } if (Pattern.compile(SQL_PARAM_PATTERN).matcher(sqlQuery).find()) { return true; } return false; } /** * Get download link of a node which stored binary data * @param node Node * @return download link * @throws Exception */ public static String getDownloadLink(Node node) throws Exception { if (!Utils.getRealNode(node).isNodeType(NT_FILE)) return null; // Get binary data from node DownloadService dservice = WCMCoreUtils.getService(DownloadService.class); Node jcrContentNode = node.getNode(JCR_CONTENT); InputStream input = jcrContentNode.getProperty(JCR_DATA).getStream(); // Get mimeType of binary data String mimeType = jcrContentNode.getProperty(JCR_MIMETYPE).getString() ; // Make download stream InputStreamDownloadResource dresource = new InputStreamDownloadResource(input, mimeType); // Make extension part for file if it have not yet DMSMimeTypeResolver mimeTypeSolver = DMSMimeTypeResolver.getInstance(); String ext = "." + mimeTypeSolver.getExtension(mimeType) ; String fileName = Utils.getRealNode(node).getName(); if (fileName.lastIndexOf(ext) < 0 && !mimeTypeSolver.getMimeType(fileName).equals(mimeType)) { dresource.setDownloadName(fileName + ext); } else { dresource.setDownloadName(fileName); } return dservice.getDownloadLink(dservice.addDownloadResource(dresource)) ; } /** * Get node nt:file if node support multi-language * * @param currentNode Current Node * @return Node which has type nt:file * @throws Exception */ public static Node getFileLangNode(Node currentNode) throws Exception { if(currentNode.isNodeType(NT_UNSTRUCTURED)) { if(currentNode.getNodes().getSize() > 0) { NodeIterator nodeIter = currentNode.getNodes() ; while(nodeIter.hasNext()) { Node ntFile = nodeIter.nextNode() ; if(ntFile.isNodeType(NT_FILE)) { return ntFile ; } } return currentNode ; } } return currentNode ; } /** * Allows you to add a lock token to the given node */ public static void addLockToken(Node node) throws Exception { if (node.isLocked()) { String lockToken = LockUtil.getLockToken(node); if(lockToken != null) { node.getSession().addLockToken(lockToken); } } } /** * sets to lower case n first elements of string * @param st * @param n */ public static String toLowerCase(String st, int n) { StringBuilder sb = new StringBuilder(st); for (int i = 0; i < n; i++) { if (i < sb.length()) { sb.setCharAt(i, Character.toLowerCase(st.charAt(i))); } } return sb.toString(); } /** * * @return true if current user is administrative user; false if current user is normal user */ public static boolean isAdministratorUser() { UserACL userACL = WCMCoreUtils.getService(UserACL.class); return userACL.isUserInGroup(userACL.getAdminGroups()); } public static String getProfileLink(String userId) { RequestContext ctx = RequestContext.getCurrentInstance(); NodeURL nodeURL = ctx.createURL(NodeURL.TYPE); NavigationResource resource = new NavigationResource(SiteType.PORTAL, Util.getPortalRequestContext().getPortalOwner(), "profile"); return nodeURL.setResource(resource).toString() + "/" + userId; } /** * Remove refences of node * @param destNode * @throws Exception */ public static void removeReferences(Node destNode) throws Exception { NodeType[] mixinTypes = destNode.getMixinNodeTypes(); Session session = destNode.getSession(); for (int i = 0; i < mixinTypes.length; i++) { if (mixinTypes[i].getName().equals(org.exoplatform.ecm.webui.utils.Utils.EXO_CATEGORIZED) && destNode.hasProperty(org.exoplatform.ecm.webui.utils.Utils.EXO_CATEGORIZED)) { Node valueNode = null; Value valueAdd = session.getValueFactory().createValue(valueNode); destNode.setProperty(org.exoplatform.ecm.webui.utils.Utils.EXO_CATEGORIZED, new Value[] { valueAdd }); } } destNode.save(); } }
45,057
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ImageSizeValidator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/ImageSizeValidator.java
package org.exoplatform.wcm.webui; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.exception.MessageException; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormInput; import org.exoplatform.webui.form.validator.Validator; /** * Author : TAN DUNG DANG * dzungdev@gmail.com * Mar 30, 2009 */ public class ImageSizeValidator implements Validator { /* (non-Javadoc) * @see org.exoplatform.webui.form.validator.Validator#validate(org.exoplatform.webui.form.UIFormInput) */ @SuppressWarnings("unchecked") public void validate(UIFormInput uiInput) throws Exception { if (uiInput.getValue()==null || ((String)uiInput.getValue()).length()==0) return; UIComponent uiComponent = (UIComponent) uiInput ; UIForm uiForm = uiComponent.getAncestorOfType(UIForm.class) ; String label; try{ label = uiForm.getLabel(uiInput.getName()); } catch(Exception e) { label = uiInput.getName(); } label = label.trim(); if(label.charAt(label.length() - 1) == ':') label = label.substring(0, label.length() - 1); String s = (String)uiInput.getValue(); int size = s.length(); for(int i = 0; i < size; i ++){ char c = s.charAt(i); if (Character.isDigit(c) || (s.charAt(0) == '-' && i == 0 && s.length() > 1) || (s.charAt(size-1) == '%')){ continue; } Object[] args = { label, uiInput.getBindingField() }; throw new MessageException(new ApplicationMessage("NumberFormatValidator.msg.Invalid-number", args)) ; } } }
1,701
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ContentReader.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/reader/ContentReader.java
package org.exoplatform.wcm.webui.reader; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.exoplatform.services.jcr.util.Text; public class ContentReader { /** * <p> * Gets the content compatibility with XSS problems. This method will do * </p> * - Unescapes previously escaped jcr chars - Escapes the characters in a the content using HTML entities * * @param content the node * * @return the content compatibility with XSS * */ public static String getXSSCompatibilityContent(String content) { if (content != null) content = StringEscapeUtils.escapeHtml4(Text.unescapeIllegalJcrChars(content)); return content; } /** * <p> * Escapes the characters in a content using HTML entities. * </p> * * <p> * For example: * </p> * <p> * <code>"bread" and "butter"</code> * </p> * becomes: * <p> * <code>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</code> * </p> * * @param content to escape, may be null * * @return a new escaped content, null if null string input * */ public static String getEscapeHtmlContent(String content) { if (content != null) { content = StringEscapeUtils.unescapeHtml4(content); content = StringEscapeUtils.escapeHtml4(content); } return content; } /** * <p> * Unescapes previously escaped jcr chars. * </p> * * @param content the content to unescape * * @return the unescaped content * */ public static String getUnescapeIllegalJcrContent(String content) { if (content != null) content = Text.unescapeIllegalJcrChars(content); return content; } /** * Escape html avoid XSS * @param value * @return */ public static String simpleEscapeHtml(String value) { if (StringUtils.isEmpty(value)) return StringUtils.EMPTY; int length = value.length(); StringBuilder result = new StringBuilder((int) (length * 1.5)); for (int i = 0; i < length; i++) { char ch = value.charAt(i); switch (ch) { case '<': result.append("&lt;"); break; case '>': result.append("&gt;"); break; default: result.append(ch); break; } } return result.toString(); } }
2,370
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICustomizeablePaginator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/paginator/UICustomizeablePaginator.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.paginator; import org.exoplatform.commons.exception.ExoMessageException; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIPageIterator; import org.exoplatform.webui.core.lifecycle.Lifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS * Author : Hoa Pham * hoa.phamvu@exoplatform.com * Oct 23, 2008 */ @ComponentConfig( lifecycle = Lifecycle.class, events = @EventConfig(listeners = UICustomizeablePaginator.ShowPageActionListener.class ) ) public class UICustomizeablePaginator extends UIPageIterator { private static final Log LOG = ExoLogger.getLogger(UICustomizeablePaginator.class.getName()); /** The template path. */ private String templatePath; /** The resource resolver. */ private ResourceResolver resourceResolver; /** Page Mode */ private String pageMode; /** * Instantiates a new uI customizeable paginator. */ public UICustomizeablePaginator() { } /** * Gets the total pages. * * @return the total pages */ public int getTotalPages() { return getPageList().getAvailablePage(); } /** * Gets the total items. * * @return the total items */ public int getTotalItems() { return getPageList().getAvailable(); } /** * Gets the item per page. * * @return the item per page */ public int getItemPerPage() { return getPageList().getPageSize(); } /** * Inits the. * * @param resourceResolver the resource resolver * @param templatePath the template path */ public void init(ResourceResolver resourceResolver, String templatePath) { this.resourceResolver = resourceResolver; this.templatePath = templatePath; } /** * Sets the template path. * * @param path the new template path */ public void setTemplatePath(String path) { this.templatePath = path; } /** * Sets the resource resolver. * * @param resolver the new resource resolver */ public void setResourceResolver(ResourceResolver resolver) { this.resourceResolver = resolver; } /* (non-Javadoc) * @see org.exoplatform.webui.core.UIComponent#getTemplate() */ public String getTemplate() { if(templatePath != null) return templatePath; return super.getTemplate(); } /** * gets the page mode (none, more or pagination) * @return PageMode */ public String getPageMode() { return pageMode; } /** * sets the page mode (none, more or pagination) * * @param pageMode */ public void setPageMode(String pageMode) { this.pageMode = pageMode; } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIComponent#getTemplateResourceResolver(org. * exoplatform.webui.application.WebuiRequestContext, java.lang.String) */ public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context,String template) { if(resourceResolver != null) return resourceResolver; return super.getTemplateResourceResolver(context,template); } /** * The listener interface for receiving showPageAction events. * The class that is interested in processing a showPageAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addShowPageActionListener</code> method. When * the showPageAction event occurs, that object's appropriate * method is invoked. * */ static public class ShowPageActionListener extends EventListener<UICustomizeablePaginator> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UICustomizeablePaginator> event) throws Exception { UICustomizeablePaginator uiPaginator = event.getSource() ; int page = Integer.parseInt(event.getRequestContext().getRequestParameter(OBJECTID)) ; try { uiPaginator.setCurrentPage(page) ; } catch (ExoMessageException e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } UIComponent parent = uiPaginator.getParent(); if(parent == null) return ; event.getRequestContext().addUIComponentToUpdateByAjax(parent); parent.broadcast(event,event.getExecutionPhase()); } } }
5,611
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UILazyPageIterator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/paginator/UILazyPageIterator.java
/* * Copyright (C) 2003-2015 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.paginator; import org.exoplatform.commons.serialization.api.annotations.Serialized; import org.exoplatform.services.wcm.search.base.AbstractPageList; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIPageIterator; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Apr 7, 2015 */ @ComponentConfig( template = "classpath:groovy/wcm/webui/paginator/UILazyPageIterator.gtmpl", events = @EventConfig(listeners = UIPageIterator.ShowPageActionListener.class)) @Serialized public class UILazyPageIterator extends UIPageIterator { public boolean loadedAllData() { if (getPageList() instanceof AbstractPageList) { return ((AbstractPageList)getPageList()).loadedAllData(); } else { return true; } } }
1,675
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FriendlyServlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/friendly/FriendlyServlet.java
package org.exoplatform.wcm.webui.friendly; import java.io.IOException; import org.exoplatform.services.wcm.friendly.FriendlyService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; public class FriendlyServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 440086446956963128L; public void destroy() { } public ServletConfig getServletConfig() { return null; } public String getServletInfo() { return null; } public void init(ServletConfig arg0) throws ServletException { } protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FriendlyService fs = WCMCoreUtils.getService(FriendlyService.class); String path = request.getRequestURI(); path = fs.getUnfriendlyUri(path); request.getRequestDispatcher(path).forward(request, response); } }
1,132
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentDialogPreference.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/dialog/UIContentDialogPreference.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.dialog; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.dialog.permission.UIPermissionManager; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.UITabPane; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS * Author : Phan Le Thanh Chuong * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Oct 29, 2009 */ @ComponentConfig ( template = "system:/groovy/webui/form/ext/UITabPaneWithAction.gtmpl", events = { @EventConfig(listeners = UIContentDialogPreference.BackActionListener.class) } ) public class UIContentDialogPreference extends UITabPane { public String[] getActions() { return new String[] {"Back"}; } public void init() throws Exception { UIPermissionManager permissionManager = addChild(UIPermissionManager.class, null, null); permissionManager.updateGrid(); setSelectedTab(permissionManager.getId()); } public static class BackActionListener extends EventListener<UIContentDialogPreference> { public void execute(Event<UIContentDialogPreference> event) throws Exception { UIContentDialogPreference contentDialogPreference = event.getSource(); UIPopupContainer popupContainer = contentDialogPreference.getAncestorOfType(UIPopupContainer.class); UIContentDialogForm contentDialogForm = popupContainer.getChild(UIContentDialogForm.class); popupContainer.removeChildById(contentDialogForm.getId()); Utils.updatePopupWindow(contentDialogPreference, contentDialogForm, UIContentDialogForm.CONTENT_DIALOG_FORM_POPUP_WINDOW); } } }
2,547
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentDialogForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/dialog/UIContentDialogForm.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.dialog; import java.security.AccessControlException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jcr.AccessDeniedException; import javax.jcr.ItemExistsException; import javax.jcr.ItemNotFoundException; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import javax.jcr.lock.LockException; import javax.jcr.version.VersionException; import javax.portlet.PortletMode; import org.exoplatform.ecm.resolver.JCRResourceResolver; import org.exoplatform.ecm.webui.form.UIDialogForm; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.ecm.webui.tree.selectone.UIOneTaxonomySelector; import org.exoplatform.ecm.webui.utils.DialogFormUtil; import org.exoplatform.webui.form.UIFormMultiValueInputSet; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.portal.webui.workspace.UIPortalApplication; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.CmsService; import org.exoplatform.services.cms.JcrInputProperty; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.services.cms.impl.DMSRepositoryConfiguration; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.taxonomy.TaxonomyService; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.ecm.publication.PublicationPlugin; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.publication.PublicationDefaultStates; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIPopupComponent; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.event.Event.Phase; import org.exoplatform.webui.form.UIFormInput; import org.exoplatform.webui.form.UIFormInputBase; import org.exoplatform.webui.form.UIFormStringInput; import org.exoplatform.ecm.webui.form.DialogFormActionListeners; /** * Created by The eXo Platform SAS * Author : Phan Le Thanh Chuong * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Oct 29, 2009 */ @ComponentConfig ( lifecycle = UIFormLifecycle.class, events = { @EventConfig(listeners = UIContentDialogForm.AddActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIContentDialogForm.RemoveReferenceActionListener.class, confirm = "DialogFormField.msg.confirm-delete", phase = Phase.DECODE), @EventConfig(listeners = UIContentDialogForm.SaveDraftActionListener.class), @EventConfig(listeners = UIContentDialogForm.FastPublishActionListener.class), @EventConfig(listeners = UIContentDialogForm.PreferencesActionListener.class), @EventConfig(listeners = UIContentDialogForm.CloseActionListener.class), @EventConfig(listeners = DialogFormActionListeners.RemoveDataActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = DialogFormActionListeners.ChangeTabActionListener.class, phase = Phase.DECODE) } ) public class UIContentDialogForm extends UIDialogForm implements UIPopupComponent, UISelectable { /** The Constant CONTENT_DIALOG_FORM_POPUP_WINDOW. */ public static final String CONTENT_DIALOG_FORM_POPUP_WINDOW = "UIContentDialogFormPopupWindow"; /** The Constant FIELD_TAXONOMY. */ public static final String FIELD_TAXONOMY = "categories"; /** The Constant TAXONOMY_CONTENT_POPUP_WINDOW. */ public static final String TAXONOMY_CONTENT_POPUP_WINDOW = "UIContentPopupWindow"; /** The Log **/ private static final Log LOG = ExoLogger.getLogger(UIContentDialogForm.class.getName()); /** The webcontent node location. */ private NodeLocation webcontentNodeLocation; /** The list taxonomy. */ private List<String> listTaxonomy = new ArrayList<String>(); /** The list taxonomy name. */ private List<String> listTaxonomyName = new ArrayList<String>(); /** The template. */ private String template; /** * Gets the list taxonomy. * * @return the list taxonomy */ public List<String> getListTaxonomy() { return listTaxonomy; } /** * Gets the list taxonomy name. * * @return the list taxonomy name */ public List<String> getlistTaxonomyName() { return listTaxonomyName; } /** * Sets the list taxonomy. * * @param listTaxonomyNew the new list taxonomy */ public void setListTaxonomy(List<String> listTaxonomyNew) { listTaxonomy = listTaxonomyNew; } /** * Sets the list taxonomy name. * * @param listTaxonomyNameNew the new list taxonomy name */ public void setListTaxonomyName(List<String> listTaxonomyNameNew) { listTaxonomyName = listTaxonomyNameNew; } /** The preference component. */ private Class<? extends UIContentDialogPreference> preferenceComponent; /** * Gets the webcontent node location. * * @return the webcontent node location */ public NodeLocation getWebcontentNodeLocation() { return webcontentNodeLocation; } /** * Sets the webcontent node location. * * @param webcontentNodeLocation the new webcontent node location */ public void setWebcontentNodeLocation(NodeLocation webcontentNodeLocation) { this.webcontentNodeLocation = webcontentNodeLocation; } /** * Gets the preference component. * * @return the preference component */ public Class<? extends UIContentDialogPreference> getPreferenceComponent() { return preferenceComponent; } /** * Sets the preference component. * * @param preferenceComponent the new preference component */ public void setPreferenceComponent(Class<? extends UIContentDialogPreference> preferenceComponent) { this.preferenceComponent = preferenceComponent; } /** * Instantiates a new uI content dialog form. * * @throws Exception the exception */ public UIContentDialogForm() throws Exception { setActions(new String [] {"SaveDraft", "FastPublish", "Preferences", "Close"}); } /** * Inits the. * * @param webcontent the webcontent * @param isAddNew the is add new * * @throws Exception the exception */ public void init(Node webcontent, boolean isAddNew) throws Exception { NodeLocation webcontentNodeLocation = null; if(webcontent.isNodeType("exo:symlink")) { LinkManager linkManager = getApplicationComponent(LinkManager.class); Node realNode = linkManager.getTarget(webcontent); webcontentNodeLocation = NodeLocation.getNodeLocationByNode(realNode); this.contentType = realNode.getPrimaryNodeType().getName(); this.nodePath = realNode.getPath(); setStoredPath(getParentPath(realNode)); } else { webcontentNodeLocation = NodeLocation.getNodeLocationByNode(webcontent); this.contentType = webcontent.getPrimaryNodeType().getName(); this.nodePath = webcontent.getPath(); setStoredPath(getParentPath(webcontent)); } this.webcontentNodeLocation = webcontentNodeLocation; this.repositoryName = webcontentNodeLocation.getRepository(); this.workspaceName = webcontentNodeLocation.getWorkspace(); this.isAddNew = isAddNew; resetProperties(); TemplateService templateService = getApplicationComponent(TemplateService.class) ; String userName = Util.getPortalRequestContext().getRemoteUser(); this.template = templateService.getTemplatePathByUser(true, contentType, userName); initFieldInput(); } private String getParentPath(Node node) throws RepositoryException { return node.getPath().substring(0, node.getPath().lastIndexOf('/')); } /** * Inits the field input. * * @throws Exception the exception */ private void initFieldInput() throws Exception { TemplateService tservice = this.getApplicationComponent(TemplateService.class); List<String> documentNodeType = tservice.getDocumentTemplates(); if(!documentNodeType.contains(this.contentType)){ return; } if (!isAddNew) { TaxonomyService taxonomyService = getApplicationComponent(TaxonomyService.class); Node currentNode = getCurrentNode(); List<Node> listCategories = taxonomyService.getAllCategories(currentNode); for (Node itemNode : listCategories) { String categoryPath = itemNode.getPath().replaceAll(getPathTaxonomy() + "/", ""); if (!listTaxonomy.contains(categoryPath)) { listTaxonomy.add(categoryPath); listTaxonomyName.add(categoryPath); } } } if(listTaxonomyName == null || listTaxonomyName.size() == 0) return; UIFormMultiValueInputSet uiFormMultiValue = createUIComponent(UIFormMultiValueInputSet.class, null, null); uiFormMultiValue.setId(FIELD_TAXONOMY); uiFormMultiValue.setName(FIELD_TAXONOMY); uiFormMultiValue.setType(UIFormStringInput.class); uiFormMultiValue.setValue(listTaxonomyName); addUIFormInput(uiFormMultiValue); } /** * Gets the current node. * * @return the current node */ public Node getCurrentNode() { return NodeLocation.getNodeByLocation(webcontentNodeLocation); } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.form.UIDialogForm#getTemplate() */ public String getTemplate() { return template; } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIComponent#getTemplateResourceResolver(org. * exoplatform.webui.application.WebuiRequestContext, java.lang.String) */ public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context, String template) { DMSConfiguration dmsConfiguration = getApplicationComponent(DMSConfiguration.class); String workspace = dmsConfiguration.getConfig().getSystemWorkspace(); return new JCRResourceResolver(workspace); } /** * The listener interface for receiving closeAction events. * The class that is interested in processing a cancelAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addCloseActionListener</code> method. When * the cancelAction event occurs, that object's appropriate * method is invoked. */ static public class CloseActionListener extends EventListener<UIContentDialogForm> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIContentDialogForm> event) throws Exception { UIContentDialogForm contentDialogForm = event.getSource(); if (Util.getUIPortalApplication().getModeState() == UIPortalApplication.NORMAL_MODE) ((PortletRequestContext)event.getRequestContext()).setApplicationMode(PortletMode.VIEW); Utils.closePopupWindow(contentDialogForm, CONTENT_DIALOG_FORM_POPUP_WINDOW); } } /** * The listener interface for receiving preferencesAction events. * The class that is interested in processing a preferencesAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addPreferencesActionListener</code> method. When * the PreferencesAction event occurs, that object's appropriate * method is invoked. */ static public class PreferencesActionListener extends EventListener<UIContentDialogForm> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIContentDialogForm> event) throws Exception { UIContentDialogForm contentDialogForm = event.getSource(); UIPopupContainer popupContainer = Utils.getPopupContainer(contentDialogForm); popupContainer.addChild(contentDialogForm); contentDialogForm.setParent(popupContainer); UIContentDialogPreference contentDialogPreference = null; if (contentDialogForm.getPreferenceComponent() != null) contentDialogPreference = contentDialogForm.createUIComponent(contentDialogForm.getPreferenceComponent(), null, null); else contentDialogPreference = contentDialogForm.createUIComponent(UIContentDialogPreference.class, null, null); Utils.updatePopupWindow(contentDialogForm, contentDialogPreference, CONTENT_DIALOG_FORM_POPUP_WINDOW); contentDialogPreference.init(); } } /** * The listener interface for receiving saveAction events. * The class that is interested in processing a saveAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSaveDraftActionListener</code> method. When * the saveAction event occurs, that object's appropriate * method is invoked. */ public static class SaveDraftActionListener extends EventListener<UIContentDialogForm> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIContentDialogForm> event) throws Exception { UIContentDialogForm contentDialogForm = event.getSource(); try { Node webContentNode = contentDialogForm.getNode(); if (!webContentNode.isCheckedOut()) { webContentNode.checkout(); } List<UIComponent> inputs = contentDialogForm.getChildren(); if (contentDialogForm.checkCategories(contentDialogForm)) { Utils.createPopupMessage(contentDialogForm, "UIContentDialogForm.msg.non-categories", null, ApplicationMessage.WARNING); return; } Map<String, JcrInputProperty> inputProperties = DialogFormUtil.prepareMap(inputs, contentDialogForm.getInputProperties(), contentDialogForm.getInputOptions()); CmsService cmsService = contentDialogForm.getApplicationComponent(CmsService.class); if (WCMCoreUtils.canAccessParentNode(webContentNode)) { cmsService.storeNode(contentDialogForm.contentType, webContentNode.getParent(), inputProperties, contentDialogForm.isAddNew); } else { cmsService.storeEditedNode(contentDialogForm.contentType, webContentNode, inputProperties, contentDialogForm.isAddNew); } if (Util.getUIPortalApplication().getModeState() == UIPortalApplication.NORMAL_MODE) { ((PortletRequestContext) event.getRequestContext()).setApplicationMode(PortletMode.VIEW); } Utils.closePopupWindow(contentDialogForm, CONTENT_DIALOG_FORM_POPUP_WINDOW); } catch(LockException le) { Object[] args = {contentDialogForm.getNode().getPath()}; Utils.createPopupMessage(contentDialogForm, "UIContentDialogForm.msg.node-locked", args, ApplicationMessage.WARNING); } catch(AccessControlException ace) { if (LOG.isWarnEnabled()) { LOG.warn(ace.getMessage()); } } catch (AccessDeniedException ade) { Utils.createPopupMessage(contentDialogForm, "UIDocumentInfo.msg.access-denied-exception", null, ApplicationMessage.WARNING); } catch(VersionException ve) { Utils.createPopupMessage(contentDialogForm, "UIDocumentForm.msg.in-versioning", null, ApplicationMessage.WARNING); } catch(ItemNotFoundException item) { Utils.createPopupMessage(contentDialogForm, "UIDocumentForm.msg.item-not-found", null, ApplicationMessage.WARNING); } catch(RepositoryException repo) { String key = "UIDocumentForm.msg.repository-exception"; if (ItemExistsException.class.isInstance(repo)) key = "UIDocumentForm.msg.not-allowed-same-name-sibling"; Utils.createPopupMessage(contentDialogForm, key, null, ApplicationMessage.WARNING); } catch (NumberFormatException nfe) { Utils.createPopupMessage(contentDialogForm, "UIDocumentForm.msg.numberformat-exception", null, ApplicationMessage.WARNING); } catch (Exception e) { Utils.createPopupMessage(contentDialogForm, "UIDocumentForm.msg.cannot-save", null, ApplicationMessage.WARNING); } } } /** * Check categories. * * @param contentDialogForm the content dialog form * * @return true, if successful */ private boolean checkCategories(UIContentDialogForm contentDialogForm) { String[] categoriesPathList = null; int index = 0; if (contentDialogForm.isReference) { UIFormMultiValueInputSet uiSet = contentDialogForm.getChild(UIFormMultiValueInputSet.class); if ((uiSet != null) && (uiSet.getName() != null) && uiSet.getName().equals(FIELD_TAXONOMY)) { List<UIComponent> listChildren = uiSet.getChildren(); StringBuffer sb = new StringBuffer(); for (UIComponent component : listChildren) { UIFormStringInput uiStringInput = (UIFormStringInput) component; if (uiStringInput.getValue() != null) { String value = uiStringInput.getValue().trim(); sb.append(value).append(","); } } String categoriesPath = sb.toString(); if (categoriesPath != null && categoriesPath.length() > 0) { try { if (categoriesPath.endsWith(",")) { categoriesPath = categoriesPath.substring(0, categoriesPath.length() - 1).trim(); if (categoriesPath.trim().length() == 0) { return true; } } categoriesPathList = categoriesPath.split(","); if ((categoriesPathList == null) || (categoriesPathList.length == 0)) { return true; } for (String categoryPath : categoriesPathList) { index = categoryPath.indexOf("/"); if (index < 0) { return true; } } } catch (Exception e) { return true; } } } } return false; } /** * The listener interface for receiving fastPublishAction events. * The class that is interested in processing a cancelAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addFastPublishActionListener</code> method. When * the cancelAction event occurs, that object's appropriate * method is invoked. */ public static class FastPublishActionListener extends EventListener<UIContentDialogForm> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIContentDialogForm> event) throws Exception { UIContentDialogForm contentDialogForm = event.getSource(); try{ Node webContentNode = contentDialogForm.getNode(); if (!webContentNode.isCheckedOut()) { webContentNode.checkout(); } List<UIComponent> inputs = contentDialogForm.getChildren(); if (contentDialogForm.checkCategories(contentDialogForm)) { Utils.createPopupMessage(contentDialogForm, "UIContentDialogForm.msg.non-categories", null, ApplicationMessage.WARNING); return; } Map<String, JcrInputProperty> inputProperties = DialogFormUtil.prepareMap(inputs, contentDialogForm.getInputProperties(), contentDialogForm.getInputOptions()); CmsService cmsService = contentDialogForm.getApplicationComponent(CmsService.class); cmsService.storeNode(contentDialogForm.contentType, contentDialogForm.getNode().getParent(), inputProperties, contentDialogForm.isAddNew); PublicationService publicationService = contentDialogForm.getApplicationComponent(PublicationService.class); PublicationPlugin publicationPlugin = publicationService.getPublicationPlugins() .get(publicationService.getNodeLifecycleName(webContentNode)); HashMap<String, String> context = new HashMap<String, String>(); if(webContentNode != null) { context.put("Publication.context.currentVersion", webContentNode.getName()); } publicationPlugin.changeState(webContentNode, PublicationDefaultStates.PUBLISHED, context); if (Util.getUIPortalApplication().getModeState() == UIPortalApplication.NORMAL_MODE) { ((PortletRequestContext)event.getRequestContext()).setApplicationMode(PortletMode.VIEW); } Utils.closePopupWindow(contentDialogForm, CONTENT_DIALOG_FORM_POPUP_WINDOW); } catch(LockException le) { Object[] args = {contentDialogForm.getNode().getPath()}; Utils.createPopupMessage(contentDialogForm, "UIContentDialogForm.msg.node-locked", args, ApplicationMessage.WARNING); } catch (AccessControlException ace) { if (LOG.isWarnEnabled()) { LOG.warn(ace.getMessage()); } } catch (AccessDeniedException ade) { Utils.createPopupMessage(contentDialogForm, "UIDocumentInfo.msg.access-denied-exception", null, ApplicationMessage.WARNING); } catch (VersionException ve) { Utils.createPopupMessage(contentDialogForm, "UIDocumentForm.msg.in-versioning", null, ApplicationMessage.WARNING); } catch (ItemNotFoundException item) { Utils.createPopupMessage(contentDialogForm, "UIDocumentForm.msg.item-not-found", null, ApplicationMessage.WARNING); } catch (RepositoryException repo) { String key = "UIDocumentForm.msg.repository-exception"; if (ItemExistsException.class.isInstance(repo)) key = "UIDocumentForm.msg.not-allowed-same-name-sibling"; Utils.createPopupMessage(contentDialogForm, key, null, ApplicationMessage.WARNING); } catch (NumberFormatException nfe) { Utils.createPopupMessage(contentDialogForm, "UIDocumentForm.msg.numberformat-exception", null, ApplicationMessage.WARNING); } catch (Exception e) { Utils.createPopupMessage(contentDialogForm, "UIDocumentForm.msg.cannot-save", null, ApplicationMessage.WARNING); } } } /** * The listener interface for receiving addAction events. The class that is * interested in processing a addAction event implements this interface, and * the object created with that class is registered with a component using the * component's <code>addAddActionListener</code> method. When * the addAction event occurs, that object's appropriate * method is invoked. */ static public class AddActionListener extends EventListener<UIContentDialogForm> { /* * (non-Javadoc) * @see * org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui * .event.Event) */ public void execute(Event<UIContentDialogForm> event) throws Exception { UIContentDialogForm contentDialogForm = event.getSource(); String clickedField = event.getRequestContext().getRequestParameter(OBJECTID); if (contentDialogForm.isReference) { UIApplication uiApp = contentDialogForm.getAncestorOfType(UIApplication.class); try { UIFormMultiValueInputSet uiSet = contentDialogForm.getChildById(FIELD_TAXONOMY); if ((uiSet != null) && (uiSet.getName() != null) && uiSet.getName().equals(FIELD_TAXONOMY)) { if ((clickedField != null) && (clickedField.equals(FIELD_TAXONOMY))) { NodeHierarchyCreator nodeHierarchyCreator = contentDialogForm.getApplicationComponent(NodeHierarchyCreator.class); String repository = contentDialogForm.repositoryName; DMSConfiguration dmsConfiguration = contentDialogForm.getApplicationComponent(DMSConfiguration.class); DMSRepositoryConfiguration repositoryConfiguration = dmsConfiguration.getConfig(); String workspaceName = repositoryConfiguration.getSystemWorkspace(); UIOneTaxonomySelector uiOneTaxonomySelector = contentDialogForm.createUIComponent(UIOneTaxonomySelector.class, null, null); if (uiSet.getValue().size() == 0) uiSet.setValue(new ArrayList<Value>()); String rootTreePath = nodeHierarchyCreator.getJcrPath(BasePath.TAXONOMIES_TREE_STORAGE_PATH); RepositoryService repositoryService = (RepositoryService) contentDialogForm. getApplicationComponent(RepositoryService.class); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); Session session = WCMCoreUtils.getUserSessionProvider() .getSession(workspaceName, manageableRepository); Node rootTree = (Node) session.getItem(rootTreePath); NodeIterator childrenIterator = rootTree.getNodes(); while (childrenIterator.hasNext()) { Node childNode = childrenIterator.nextNode(); rootTreePath = childNode.getPath(); break; } uiOneTaxonomySelector.setRootNodeLocation(repository, workspaceName, rootTreePath); uiOneTaxonomySelector.setExceptedNodeTypesInPathPanel(new String[] { "exo:symlink" }); uiOneTaxonomySelector.init(WCMCoreUtils.getUserSessionProvider()); String param = "returnField=" + FIELD_TAXONOMY; uiOneTaxonomySelector.setSourceComponent(contentDialogForm, new String[] { param }); Utils.createPopupWindow(contentDialogForm, uiOneTaxonomySelector, TAXONOMY_CONTENT_POPUP_WINDOW, 700); } } } catch (AccessDeniedException accessDeniedException) { uiApp.addMessage(new ApplicationMessage("UIContentDialogForm.msg.access-denied", null, ApplicationMessage.WARNING)); return; } catch (Exception e) { uiApp.addMessage(new ApplicationMessage("UIContentDialogForm.msg.exception", null, ApplicationMessage.WARNING)); return; } } else { event.getRequestContext().addUIComponentToUpdateByAjax(contentDialogForm); } } } /* (non-Javadoc) * @see org.exoplatform.webui.core.UIPopupComponent#activate() */ public void activate() { } /* (non-Javadoc) * @see org.exoplatform.webui.core.UIPopupComponent#deActivate() */ public void deActivate() { } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.selector.UISelectable#doSelect(java.lang.String, java.lang.Object) */ @SuppressWarnings("unchecked") public void doSelect(String selectField, Object value) throws Exception { isUpdateSelect = true; UIFormInput formInput = getUIInput(selectField); if(formInput instanceof UIFormInputBase) { ((UIFormInputBase)formInput).setValue(value.toString()); }else if(formInput instanceof UIFormMultiValueInputSet) { UIFormMultiValueInputSet inputSet = (UIFormMultiValueInputSet) formInput; String valueTaxonomy = String.valueOf(value).trim(); List taxonomylist = inputSet.getValue(); if (!taxonomylist.contains(valueTaxonomy)) { listTaxonomy.add(valueTaxonomy); listTaxonomyName.add(valueTaxonomy); taxonomylist.add(valueTaxonomy); } inputSet.setValue(taxonomylist); } } /** * The listener interface for receiving removeReferenceAction events. * The class that is interested in processing a removeReferenceAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addRemoveReferenceActionListener</code> method. When * the removeReferenceAction event occurs, that object's appropriate * method is invoked. */ static public class RemoveReferenceActionListener extends EventListener<UIContentDialogForm> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIContentDialogForm> event) throws Exception { UIContentDialogForm contentDialogForm = event.getSource(); contentDialogForm.isRemovePreference = true; String fieldName = event.getRequestContext().getRequestParameter(OBJECTID); contentDialogForm.getUIStringInput(fieldName).setValue(null); event.getRequestContext().addUIComponentToUpdateByAjax(contentDialogForm); } } }
33,256
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIPermissionManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/dialog/permission/UIPermissionManager.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.dialog.permission; import java.security.AccessControlException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.jcr.AccessDeniedException; import javax.jcr.Node; import javax.jcr.Session; import org.exoplatform.commons.utils.LazyPageList; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.commons.utils.ListAccessImpl; import org.exoplatform.ecm.webui.form.UIFormInputSetWithAction; import org.exoplatform.ecm.webui.selector.UIGroupMemberSelector; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.services.jcr.access.AccessControlEntry; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.security.IdentityConstants; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.dialog.UIContentDialogForm; import org.exoplatform.wcm.webui.selector.account.UIUserContainer; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIGrid; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormStringInput; import org.exoplatform.webui.form.input.UICheckBoxInput; /** * Created by The eXo Platform SAS * Author : Phan Le Thanh Chuong * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Oct 29, 2009 */ @ComponentConfig ( lifecycle = UIFormLifecycle.class, template = "classpath:groovy/wcm/webui/dialog/permission/UIPermissionManager.gtmpl", events = { @EventConfig(listeners = UIPermissionManager.DeleteActionListener.class, confirm = "UIPermissionManagerGrid.msg.confirm-delete-permission"), @EventConfig(listeners = UIPermissionManager.EditActionListener.class), @EventConfig(listeners = UIPermissionManager.SaveActionListener.class), @EventConfig(listeners = UIPermissionManager.ClearActionListener.class), @EventConfig(listeners = UIPermissionManager.SelectUserActionListener.class), @EventConfig(listeners = UIPermissionManager.SelectMemberActionListener.class), @EventConfig(listeners = UIPermissionManager.AddAnyActionListener.class) } ) public class UIPermissionManager extends UIForm implements UISelectable { /** The Constant PERMISSION_MANAGER_GRID. */ public static final String PERMISSION_MANAGER_GRID = "UIPermissionManagerGrid"; /** The Constant PERMISSION_INPUT_SET. */ public static final String PERMISSION_INPUT_SET = "UIPermissionInputSetWithAction"; /** The Constant PERMISSION_STRING_INPUT. */ public static final String PERMISSION_STRING_INPUT = "UIPermissionStringInput"; /** The Constant ACCESSIBLE_CHECKBOX_INPUT. */ public static final String ACCESSIBLE_CHECKBOX_INPUT = "UIAccessibleCheckboxInput"; /** The Constant EDITABLE_CHECKBOX_INPUT. */ public static final String EDITABLE_CHECKBOX_INPUT = "UIEditableCheckboxInput"; public static final String USER_SELECTOR_POPUP_WINDOW = "UIUserSelectorPopupWindow"; public static final String GROUP_SELECTOR_POPUP_WINDOW = "UIGroupSelectorPopupWindow"; private String popupId; public String getPopupId() { return popupId; } public void setPopupId(String popupId) { this.popupId = popupId; } /** * Instantiates a new uI permission info. * * @throws Exception the exception */ public UIPermissionManager() throws Exception { UIGrid uiGrid = createUIComponent(UIGrid.class, null, PERMISSION_MANAGER_GRID); uiGrid.setLabel(PERMISSION_MANAGER_GRID); uiGrid.configure("owner", new String[] {"owner", "accessible", "editable"}, new String[] {"Edit", "Delete"}); addChild(uiGrid); UIFormInputSetWithAction permissionInputSet = new UIFormInputSetWithAction(PERMISSION_INPUT_SET); UIFormStringInput formStringInput = new UIFormStringInput(PERMISSION_STRING_INPUT, PERMISSION_STRING_INPUT, null); formStringInput.setReadOnly(true); permissionInputSet.addChild(formStringInput); permissionInputSet.setActionInfo(PERMISSION_STRING_INPUT, new String[] {"SelectUser", "SelectMember", "AddAny"}); permissionInputSet.showActionInfo(true); addChild(permissionInputSet); addChild(new UICheckBoxInput(ACCESSIBLE_CHECKBOX_INPUT, ACCESSIBLE_CHECKBOX_INPUT, null)); addChild(new UICheckBoxInput(EDITABLE_CHECKBOX_INPUT, EDITABLE_CHECKBOX_INPUT, null)); setActions(new String[] {"Save", "Clear"}); } /** * Update grid. * * @throws Exception the exception */ public void updateGrid() throws Exception { // Get node UIContentDialogForm contentDialogForm = getAncestorOfType(UIPopupContainer.class).getChild(UIContentDialogForm.class); NodeLocation webcontentNodeLocation = contentDialogForm.getWebcontentNodeLocation(); Node node = NodeLocation.getNodeByLocation(webcontentNodeLocation); ExtendedNode webcontent = (ExtendedNode) node; // Convert permission entries to map List<UIPermissionConfig> permissionConfigs = new ArrayList<UIPermissionConfig>(); Map<String, List<String>> permissionMap = new HashMap<String, List<String>>(); List<AccessControlEntry> accessControlEntries = webcontent.getACL().getPermissionEntries(); for (AccessControlEntry accessControlEntry : accessControlEntries) { String identity = accessControlEntry.getIdentity(); String permission = accessControlEntry.getPermission(); List<String> currentPermissions = permissionMap.get(identity); if (!permissionMap.containsKey(identity)) { permissionMap.put(identity, null); } if (currentPermissions == null) currentPermissions = new ArrayList<String>(); if (!currentPermissions.contains(permission)) { currentPermissions.add(permission); } permissionMap.put(identity, currentPermissions); } // Add owner's permission String owner = IdentityConstants.SYSTEM; if (webcontent.hasProperty("exo:owner")) owner = webcontent.getProperty("exo:owner").getString(); UIPermissionConfig permissionConfig = new UIPermissionConfig(); if (!permissionMap.containsKey(owner)) { permissionConfig.setOwner(owner); permissionConfig.setAccessible(true); permissionConfig.setEditable(true); permissionConfigs.add(permissionConfig); } // Add node's permission Iterator<String> permissionIterator = permissionMap.keySet().iterator(); while (permissionIterator.hasNext()) { String identity = (String) permissionIterator.next(); List<String> userPermissions = permissionMap.get(identity); UIPermissionConfig permBean = new UIPermissionConfig(); permBean.setOwner(identity); int numberPermission = 0; for (String p : PermissionType.ALL) { if (!userPermissions.contains(p)) break; numberPermission++; } if (numberPermission == PermissionType.ALL.length) { permBean.setEditable(true); permBean.setAccessible(true); } else { permBean.setAccessible(true); } permissionConfigs.add(permBean); } ListAccess<UIPermissionConfig> permConfigList = new ListAccessImpl<UIPermissionConfig>(UIPermissionConfig.class, permissionConfigs); LazyPageList<UIPermissionConfig> dataPageList = new LazyPageList<UIPermissionConfig>(permConfigList, 10); UIGrid uiGrid = getChildById(PERMISSION_MANAGER_GRID); uiGrid.getUIPageIterator().setPageList(dataPageList); } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.selector.UISelectable#doSelect(java.lang.String, java.lang.Object) */ public void doSelect(String selectField, Object value) throws Exception { UIFormInputSetWithAction permissionInputSet = getChildById(PERMISSION_INPUT_SET); permissionInputSet.getUIStringInput(PERMISSION_STRING_INPUT).setValue(value.toString()); Utils.closePopupWindow(this, popupId); } /** * Checks for change permission right. * * @param node the node * * @return true, if successful * * @throws Exception the exception */ private boolean hasChangePermissionRight(ExtendedNode node) throws Exception { try { node.checkPermission(PermissionType.ADD_NODE); node.checkPermission(PermissionType.REMOVE); node.checkPermission(PermissionType.SET_PROPERTY); return true; } catch (AccessControlException e) { return false; } } /** * The listener interface for receiving deleteAction events. * The class that is interested in processing a deleteAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addDeleteActionListener</code> method. When * the deleteAction event occurs, that object's appropriate * method is invoked. */ public static class DeleteActionListener extends EventListener<UIPermissionManager> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIPermissionManager> event) throws Exception { UIPermissionManager permissionManager = event.getSource(); UIContentDialogForm contentDialogForm = permissionManager.getAncestorOfType(UIPopupContainer.class) .getChild(UIContentDialogForm.class); NodeLocation webcontentNodeLocation = contentDialogForm.getWebcontentNodeLocation(); Node node = NodeLocation.getNodeByLocation(webcontentNodeLocation); ExtendedNode webcontent = (ExtendedNode) node; Session session = webcontent.getSession(); String name = event.getRequestContext().getRequestParameter(OBJECTID); String nodeOwner = webcontent.getProperty("exo:owner").getString(); if (name.equals(nodeOwner)) { Utils.createPopupMessage(permissionManager, "UIPermissionManagerGrid.msg.no-permission-remove", null, ApplicationMessage.WARNING); return; } if (permissionManager.hasChangePermissionRight(webcontent)) { if (webcontent.canAddMixin("exo:privilegeable")) { webcontent.addMixin("exo:privilegeable"); webcontent.setPermission(nodeOwner, PermissionType.ALL); } try { webcontent.removePermission(name); session.save(); permissionManager.updateGrid(); } catch (AccessControlException e) { Object[] args = {webcontent.getPath()}; Utils.createPopupMessage(permissionManager, "UIPermissionManagerGrid.msg.node-locked", args, ApplicationMessage.WARNING); return; } catch (AccessDeniedException ace) { Utils.createPopupMessage(permissionManager, "UIPermissionManagerGrid.msg.access-denied", null, ApplicationMessage.WARNING); return; } } } } /** * The listener interface for receiving editAction events. * The class that is interested in processing a editAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addEditActionListener</code> method. When * the editAction event occurs, that object's appropriate * method is invoked. */ public static class EditActionListener extends EventListener<UIPermissionManager> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIPermissionManager> event) throws Exception { UIPermissionManager permissionManager = event.getSource(); UIContentDialogForm contentDialogForm = permissionManager.getAncestorOfType(UIPopupContainer.class) .getChild(UIContentDialogForm.class); NodeLocation webcontentNodeLocation = contentDialogForm.getWebcontentNodeLocation(); Node node = NodeLocation.getNodeByLocation(webcontentNodeLocation); ExtendedNode webcontent = (ExtendedNode) node; String name = event.getRequestContext().getRequestParameter(OBJECTID); UIFormInputSetWithAction permissionInputSet = permissionManager.getChildById(PERMISSION_INPUT_SET); permissionInputSet.getUIStringInput(PERMISSION_STRING_INPUT).setValue(name); String owner = node.getProperty("exo:owner").getString(); if (name.equals(owner)) { permissionManager.getUICheckBoxInput(ACCESSIBLE_CHECKBOX_INPUT).setChecked(true); permissionManager.getUICheckBoxInput(EDITABLE_CHECKBOX_INPUT).setChecked(true); permissionManager.setActions(new String[] {"Clear"}); permissionInputSet.setActionInfo(PERMISSION_STRING_INPUT, null); } else { List<AccessControlEntry> permsList = webcontent.getACL().getPermissionEntries(); StringBuilder userPermission = new StringBuilder(); for (AccessControlEntry accessControlEntry : permsList) { if (name.equals(accessControlEntry.getIdentity())) { userPermission.append(accessControlEntry.getPermission()).append(" "); } } int numPermission = 0; for (String perm : PermissionType.ALL) { if (userPermission.toString().contains(perm)) numPermission++; } if (numPermission == PermissionType.ALL.length) { permissionManager.getUICheckBoxInput(ACCESSIBLE_CHECKBOX_INPUT).setChecked(true); permissionManager.getUICheckBoxInput(EDITABLE_CHECKBOX_INPUT).setChecked(true); } else { permissionManager.getUICheckBoxInput(ACCESSIBLE_CHECKBOX_INPUT).setChecked(true); permissionManager.getUICheckBoxInput(EDITABLE_CHECKBOX_INPUT).setChecked(false); } permissionManager.setActions(new String[] {"Save", "Clear"}); permissionInputSet.setActionInfo(PERMISSION_STRING_INPUT, new String[] { "SelectUser", "SelectMember", "AddAny" }); } } } /** * The listener interface for receiving saveAction events. * The class that is interested in processing a saveAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSaveActionListener</code> method. When * the saveAction event occurs, that object's appropriate * method is invoked. */ public static class SaveActionListener extends EventListener<UIPermissionManager> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIPermissionManager> event) throws Exception { UIPermissionManager permissionManager = event.getSource(); UIContentDialogForm contentDialogForm = permissionManager.getAncestorOfType(UIPopupContainer.class) .getChild(UIContentDialogForm.class); NodeLocation webcontentNodeLocation = contentDialogForm.getWebcontentNodeLocation(); Node node = NodeLocation.getNodeByLocation(webcontentNodeLocation); ExtendedNode webcontent = (ExtendedNode) node; Session session = webcontent.getSession(); UIFormInputSetWithAction formInputSet = permissionManager.getChildById(PERMISSION_INPUT_SET); String identity = ((UIFormStringInput) formInputSet.getChildById(PERMISSION_STRING_INPUT)).getValue(); List<String> permsList = new ArrayList<String>(); if (!webcontent.isCheckedOut()) { Utils.createPopupMessage(permissionManager, "UIPermissionManagerGrid.msg.node-checkedin", null, ApplicationMessage.WARNING); return; } if (permissionManager.getUICheckBoxInput(ACCESSIBLE_CHECKBOX_INPUT).isChecked()) { permsList.clear(); permsList.add(PermissionType.READ); } if (permissionManager.getUICheckBoxInput(EDITABLE_CHECKBOX_INPUT).isChecked()) { permsList.clear(); for (String perm : PermissionType.ALL) permsList.add(perm); } if (identity == null || identity.trim().length() == 0) { Utils.createPopupMessage(permissionManager, "UIPermissionManagerGrid.msg.userOrGroup-required", null, ApplicationMessage.WARNING); return; } if (permsList.size() == 0) { Utils.createPopupMessage(permissionManager, "UIPermissionManagerGrid.msg.checkbox-require", null, ApplicationMessage.WARNING); return; } String[] permsArray = permsList.toArray(new String[permsList.size()]); if (webcontent.canAddMixin("exo:privilegeable")) { webcontent.addMixin("exo:privilegeable"); webcontent.setPermission(webcontent.getProperty("exo:owner").getString(), PermissionType.ALL); } try { webcontent.setPermission(identity, permsArray); } catch (AccessControlException e) { Object[] args = {webcontent.getPath()}; Utils.createPopupMessage(permissionManager, "UIPermissionManagerGrid.msg.node-locked", args, ApplicationMessage.WARNING); return; } session.save(); permissionManager.updateGrid(); UIFormInputSetWithAction permissionInputSet = permissionManager.getChildById(PERMISSION_INPUT_SET); ((UIFormStringInput) permissionInputSet.getChildById(PERMISSION_STRING_INPUT)).setValue(""); permissionManager.getUICheckBoxInput(ACCESSIBLE_CHECKBOX_INPUT).setChecked(false); permissionManager.getUICheckBoxInput(EDITABLE_CHECKBOX_INPUT).setChecked(false); } } /** * The listener interface for receiving resetAction events. * The class that is interested in processing a resetAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addResetActionListener</code> method. When * the resetAction event occurs, that object's appropriate * method is invoked. */ public static class ClearActionListener extends EventListener<UIPermissionManager> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIPermissionManager> event) throws Exception { UIPermissionManager permissionManager = event.getSource(); UIFormInputSetWithAction permissionInputSet = permissionManager.getChildById(PERMISSION_INPUT_SET); ((UIFormStringInput) permissionInputSet.getChildById(PERMISSION_STRING_INPUT)).setValue(""); permissionManager.getUICheckBoxInput(ACCESSIBLE_CHECKBOX_INPUT).setChecked(false); permissionManager.getUICheckBoxInput(EDITABLE_CHECKBOX_INPUT).setChecked(false); permissionManager.setActions(new String[] {"Save", "Clear"}); permissionInputSet.setActionInfo(PERMISSION_STRING_INPUT, new String[] { "SelectUser", "SelectMember", "AddAny" }); } } /** * The listener interface for receiving selectUserAction events. * The class that is interested in processing a selectUserAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSelectUserActionListener</code> method. When * the selectUserAction event occurs, that object's appropriate * method is invoked. */ public static class SelectUserActionListener extends EventListener<UIPermissionManager> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIPermissionManager> event) throws Exception { UIPermissionManager permissionManager = event.getSource(); UIUserContainer userContainer = permissionManager.createUIComponent(UIUserContainer.class, null, null); userContainer.setSelectable(permissionManager); userContainer.setSourceComponent(PERMISSION_STRING_INPUT); Utils.createPopupWindow(permissionManager, userContainer, USER_SELECTOR_POPUP_WINDOW, 740); permissionManager.setPopupId(USER_SELECTOR_POPUP_WINDOW); } } /** * The listener interface for receiving selectMemberAction events. * The class that is interested in processing a selectMemberAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSelectMemberActionListener</code> method. When * the selectMemberAction event occurs, that object's appropriate * method is invoked. */ public static class SelectMemberActionListener extends EventListener<UIPermissionManager> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIPermissionManager> event) throws Exception { UIPermissionManager permissionManager = event.getSource(); UIGroupMemberSelector groupContainer = permissionManager.createUIComponent(UIGroupMemberSelector.class, null, null); groupContainer.setShowAnyPermission(false); groupContainer.setSourceComponent(permissionManager, new String[] {PERMISSION_STRING_INPUT}); Utils.createPopupWindow(permissionManager, groupContainer, GROUP_SELECTOR_POPUP_WINDOW, 600); permissionManager.setPopupId(GROUP_SELECTOR_POPUP_WINDOW); } } /** * The listener interface for receiving addAnyAction events. * The class that is interested in processing a addAnyAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addAddAnyActionListener</code> method. When * the addAnyAction event occurs, that object's appropriate * method is invoked. */ public static class AddAnyActionListener extends EventListener<UIPermissionManager> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIPermissionManager> event) throws Exception { UIPermissionManager permissionManager = event.getSource(); UIFormInputSetWithAction permisionInputSet = permissionManager.getChildById(PERMISSION_INPUT_SET); ((UIFormStringInput) permisionInputSet.getChildById(PERMISSION_STRING_INPUT)).setValue(IdentityConstants.ANY); permissionManager.getUICheckBoxInput(ACCESSIBLE_CHECKBOX_INPUT).setChecked(true); permissionManager.getUICheckBoxInput(EDITABLE_CHECKBOX_INPUT).setChecked(false); } } }
24,972
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIPermissionConfig.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/dialog/permission/UIPermissionConfig.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.dialog.permission; /** * Created by The eXo Platform SAS * Author : Phan Le Thanh Chuong * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Oct 30, 2009 */ public class UIPermissionConfig { private String owner; private boolean accessible; private boolean editable; public String getOwner() { return owner; } public void setOwner(String usersOrGroups) { this.owner = usersOrGroups; } public boolean isAccessible() { return accessible; } public void setAccessible(boolean accessible) { this.accessible = accessible; } public boolean isEditable() { return editable; } public void setEditable(boolean editable) { this.editable = editable; } }
1,471
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIFormFieldSet.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/container/UIFormFieldSet.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.container; import java.io.Writer; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.form.UIForm; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Jun 26, 2009 */ public class UIFormFieldSet extends UIContainer { /** * Instantiates a new uI form field set. * * @param name the name */ public UIFormFieldSet(String name) { setId(name) ; } /* (non-Javadoc) * @see org.exoplatform.webui.core.UIComponent#processDecode(org.exoplatform.webui.application.WebuiRequestContext) */ public void processDecode(WebuiRequestContext context) throws Exception { for(UIComponent child : getChildren()) { child.processDecode(context) ; } } /* (non-Javadoc) * @see org.exoplatform.webui.core.UIComponent#processRender(org.exoplatform.webui.application.WebuiRequestContext) */ public void processRender(WebuiRequestContext context) throws Exception { if (getComponentConfig() != null) { super.processRender(context); return; } UIForm uiForm = getAncestorOfType(UIForm.class); Writer writer = context.getWriter() ; writer.write("<div class=\"" + getId() + "\">") ; writer.write("<fieldset>") ; writer.write("<legend>" + uiForm.getLabel(getId()) + "</legend>") ; writer.write("<table class=\"UIFormGrid\">") ; for(UIComponent component : getChildren()) { if(component.isRendered()) { writer.write("<tr>") ; String componentName = uiForm.getLabel(component.getId()); if(componentName != null && componentName.length() > 0 && !componentName.equals(getId())) { writer.write("<td class=\"FieldLabel\"><label for=\"" + component.getId() + "\">" + componentName + "</td>"); writer.write("<td class=\"FieldComponent\">") ; renderUIComponent(component) ; writer.write("</td>") ; } else { writer.write("<td class=\"FieldComponent\" colspans=\"2\">") ; renderUIComponent(component) ; writer.write("</td>") ; } writer.write("</tr>") ; } } writer.write("</table>") ; writer.write("</fieldset>") ; writer.write("</div>") ; } }
3,196
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentViewer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/viewer/UIContentViewer.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.viewer; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import org.exoplatform.ecm.resolver.JCRResourceResolver; import org.exoplatform.ecm.webui.presentation.UIBaseNodePresentation; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.lifecycle.Lifecycle; /** * Created by The eXo Platform SAS * Author : Phan Le Thanh Chuong * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Nov 9, 2009 */ @ComponentConfig( lifecycle = Lifecycle.class ) public class UIContentViewer extends UIBaseNodePresentation { public static final String TEMPLATE_NOT_SUPPORT = "UIContentViewer.msg.template-not-support"; private NodeLocation originalNodeLocation; private NodeLocation viewNodeLocation; public Node getOriginalNode() { return NodeLocation.getNodeByLocation(originalNodeLocation); } public void setOriginalNode(Node originalNode) throws Exception{ originalNodeLocation = NodeLocation.getNodeLocationByNode(originalNode); } public Node getNode() { return NodeLocation.getNodeByLocation(viewNodeLocation); } public void setNode(Node viewNode) { viewNodeLocation = NodeLocation.getNodeLocationByNode(viewNode); } public String getTemplate() { TemplateService templateService = getApplicationComponent(TemplateService.class); String userName = Util.getPortalRequestContext().getRemoteUser() ; try { String nodeType = getOriginalNode().getPrimaryNodeType().getName(); if(templateService.isManagedNodeType(nodeType)) return templateService.getTemplatePathByUser(false, nodeType, userName) ; } catch (PathNotFoundException e) { Utils.createPopupMessage(this, TEMPLATE_NOT_SUPPORT, null, ApplicationMessage.ERROR); } catch (Exception e) { Utils.createPopupMessage(this, TEMPLATE_NOT_SUPPORT, null, ApplicationMessage.ERROR); } return null ; } public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context, String template) { try { DMSConfiguration dmsConfiguration = getApplicationComponent(DMSConfiguration.class); String workspace = dmsConfiguration.getConfig().getSystemWorkspace(); return new JCRResourceResolver(workspace); } catch (Exception e) { return null; } } public String getRepositoryName() { try { return getRepository(); }catch (Exception ex) { return null; } } public String getTemplatePath() { return null; } public String getNodeType() { return null; } public boolean isNodeTypeSupported() { return false; } public UIComponent getCommentComponent() { return null; } public UIComponent getRemoveAttach() { return null; } public UIComponent getRemoveComment() { return null; } public UIComponent getUIComponent(String mimeType) throws Exception { return org.exoplatform.ecm.webui.utils.Utils.getUIComponent(mimeType, this); } }
4,203
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIUserMemberSelector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/UIUserMemberSelector.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.selector; import org.exoplatform.ecm.webui.selector.ComponentSelector; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.organization.account.UIUserSelector; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * June 10, 2009 */ @ComponentConfig( lifecycle = UIContainerLifecycle.class, events = {@EventConfig(listeners = UIUserMemberSelector.AddUserActionListener.class)} ) public class UIUserMemberSelector extends UIContainer implements ComponentSelector { /** The ui component. */ private UIComponent uiComponent; /** The return field. */ private String returnField; /** The is use popup. */ private boolean isUsePopup = true; /** The is multi. */ private boolean isMulti = true; /** The is show search user. */ private boolean isShowSearchUser = true; /** The is show search. */ private boolean isShowSearch; /** * Instantiates a new uIWCM user container. */ public UIUserMemberSelector() {} /** * Inits the. * * @throws Exception the exception */ public void init() throws Exception { UIUserSelector uiUserSelector = getChild(UIUserSelector.class); if (uiUserSelector == null) { uiUserSelector = addChild(UIUserSelector.class, null, null); } uiUserSelector.setMulti(isMulti); uiUserSelector.setShowSearchUser(isShowSearchUser); uiUserSelector.setShowSearch(isShowSearch); } /** * Checks if is use popup. * * @return true, if is use popup */ public boolean isUsePopup() { return isUsePopup; } /** * Sets the use popup. * * @param isUsePopup the new use popup */ public void setUsePopup(boolean isUsePopup) { this.isUsePopup = isUsePopup; } /** * Checks if is multi. * * @return true, if is multi */ public boolean isMulti() { return isMulti; } /** * Sets the multi. * * @param isMulti the new multi */ public void setMulti(boolean isMulti) { this.isMulti = isMulti; } /** * Checks if is show search user. * * @return true, if is show search user */ public boolean isShowSearchUser() { return isShowSearchUser; } /** * Sets the show search user. * * @param isShowSearchUser the new show search user */ public void setShowSearchUser(boolean isShowSearchUser) { this.isShowSearchUser = isShowSearchUser; } /** * Checks if is show search. * * @return true, if is show search */ public boolean isShowSearch() { return isShowSearch; } /** * Sets the show search. * * @param isShowSearch the new show search */ public void setShowSearch(boolean isShowSearch) { this.isShowSearch = isShowSearch; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.selector.ComponentSelector#getSourceComponent() */ public UIComponent getSourceComponent() { return uiComponent; } /** * Gets the return field. * * @return the return field */ public String getReturnField() { return returnField; } /* * (non-Javadoc) * @see * org.exoplatform.ecm.webui.selector.ComponentSelector#setSourceComponent * (org.exoplatform.webui.core.UIComponent, java.lang.String[]) */ public void setSourceComponent(UIComponent uicomponent, String[] initParams) { uiComponent = uicomponent; if (initParams == null || initParams.length == 0) return; for (int i = 0; i < initParams.length; i++) { if (initParams[i].indexOf("returnField") > -1) { String[] array = initParams[i].split("="); returnField = array[1]; break; } returnField = initParams[0]; } } /** * The listener interface for receiving addUserAction events. * The class that is interested in processing a addUserAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addAddUserActionListener</code> method. When * the addUserAction event occurs, that object's appropriate * method is invoked. */ static public class AddUserActionListener extends EventListener<UIUserMemberSelector> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIUserMemberSelector> event) throws Exception { UIUserMemberSelector userMemberSelector = event.getSource(); UIUserSelector userSelector = userMemberSelector.getChild(UIUserSelector.class); String returnField = userMemberSelector.getReturnField(); ((UISelectable)userMemberSelector.getSourceComponent()).doSelect(returnField, userSelector.getSelectedUsers()); if (userMemberSelector.isUsePopup) { UIPopupWindow uiPopup = userMemberSelector.getParent(); uiPopup.setShow(false); UIComponent uicomp = userMemberSelector.getSourceComponent().getParent(); event.getRequestContext().addUIComponentToUpdateByAjax(uicomp); if (!uiPopup.getId().equals("PopupComponent")) event.getRequestContext().addUIComponentToUpdateByAjax(uiPopup); } else { event.getRequestContext().addUIComponentToUpdateByAjax( userMemberSelector.getSourceComponent()); } } } }
6,745
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIPageSelectorPanel.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/page/UIPageSelectorPanel.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.selector.page; import java.util.ArrayList; import java.util.List; import org.exoplatform.commons.utils.LazyPageList; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.commons.utils.ListAccessImpl; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.portal.mop.user.UserNode; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPageIterator; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Jun 30, 2009 */ @ComponentConfig( template = "classpath:groovy/wcm/webui/selector/page/UIPageSelectorPanel.gtmpl", events = { @EventConfig(listeners = UIPageSelectorPanel.SelectActionListener.class) } ) public class UIPageSelectorPanel extends UIContainer { /** The Constant PAGE_SELECTOR_ITERATOR. */ private static final String PAGE_SELECTOR_ITERATOR = "UIPageSelectorIterator"; /** The page iterator. */ private UIPageIterator pageIterator; /** The selected page. */ private UserNode selectedNode; /** * Instantiates a new uI page selector panel. * * @throws Exception the exception */ public UIPageSelectorPanel() throws Exception { pageIterator = addChild(UIPageIterator.class, null, PAGE_SELECTOR_ITERATOR); } /** * Update grid. */ public void updateGrid() { List<UserNode> children = null; if (selectedNode == null) { UIPageSelector pageSelector = getAncestorOfType(UIPageSelector.class); UIPageNodeSelector pageNodeSelector = pageSelector.getChild(UIPageNodeSelector.class); UserNode rootNode = pageNodeSelector.getRootNodeOfSelectedNav(); children = new ArrayList<UserNode>(rootNode.getChildren()); } else { children = new ArrayList<UserNode>(selectedNode.getChildren()); } ListAccess<UserNode> pageNodeList = new ListAccessImpl<UserNode>(UserNode.class, children); LazyPageList<UserNode> pageList = new LazyPageList<UserNode>(pageNodeList, 10); pageIterator.setPageList(pageList); } /** * Gets the selectable pages. * * @return the selectable pages * * @throws Exception the exception */ @SuppressWarnings("unchecked") public List getSelectablePages() throws Exception { return pageIterator.getCurrentPageData(); } /** * Gets the selected node. * * @return the selected node */ public UserNode getSelectedNode() { return selectedNode; } /** * Sets the selected node. * * @param selectedNode the new selected node */ public void setSelectedNode(UserNode selectedNode) { this.selectedNode = selectedNode; } /** * Gets the page iterator. * * @return the page iterator */ public UIPageIterator getPageIterator() { return pageIterator; } /** * Sets the page iterator. * * @param pageIterator the new page iterator */ public void setPageIterator(UIPageIterator pageIterator) { this.pageIterator = pageIterator; } /** * The listener interface for receiving selectAction events. * The class that is interested in processing a selectAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSelectActionListener</code> method. When * the selectAction event occurs, that object's appropriate * method is invoked. */ public static class SelectActionListener extends EventListener<UIPageSelectorPanel> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIPageSelectorPanel> event) throws Exception { UIPageSelectorPanel pageSelectorPanel = event.getSource(); String uri = event.getRequestContext().getRequestParameter(OBJECTID) ; UIPageSelector pageSelector = pageSelectorPanel.getAncestorOfType(UIPageSelector.class); ((UISelectable)pageSelector.getSourceComponent()).doSelect(pageSelector.getReturnFieldName(), uri); } } }
5,194
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIPageNodeSelector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/page/UIPageNodeSelector.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.selector.page; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.exoplatform.portal.mop.user.UserNavigation; import org.exoplatform.portal.mop.user.UserNode; import org.exoplatform.portal.mop.user.UserPortal; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.portal.webui.util.NavigationUtils; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.ComponentConfigs; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIDropDownControl; import org.exoplatform.webui.core.UIRightClickPopupMenu; import org.exoplatform.webui.core.UITree; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.Event.Phase; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SARL * Author : chungnv * nguyenchung136@yahoo.com * Jun 23, 2006 * 10:07:15 AM */ @ComponentConfigs({ @ComponentConfig( template = "classpath:groovy/wcm/webui/selector/page/UIPageNodeSelector.gtmpl" , events = { @EventConfig(listeners = UIPageNodeSelector.SelectNavigationActionListener.class, phase=Phase.DECODE) } ), @ComponentConfig ( type = UIDropDownControl.class , id = "UIDropDown", template = "classpath:groovy/wcm/webui/selector/page/UINavigationSelector.gtmpl", events = { @EventConfig(listeners = UIPageNodeSelector.SelectNavigationActionListener.class) } ) }) public class UIPageNodeSelector extends UIContainer { /** The navigations. */ private List<UserNavigation> navigations; /** The selected node. */ private SelectedNode selectedNode; /** The copy node. */ private SelectedNode copyNode; /** The delete navigations. */ private List<UserNavigation> deleteNavigations = new ArrayList<UserNavigation>(); /** the user portal */ private UserPortal userPortal; /** * Instantiates a new uI page node selector. * * @throws Exception the exception */ public UIPageNodeSelector() throws Exception { userPortal = Util.getPortalRequestContext().getUserPortalConfig().getUserPortal(); UIDropDownControl uiDopDownControl = addChild(UIDropDownControl.class, "UIDropDown", "UIDropDown"); uiDopDownControl.setParent(this); UITree uiTree = addChild(UITree.class, null, "TreeNodeSelector"); uiTree.setIcon("DefaultPageIcon"); uiTree.setSelectedIcon("DefaultPageIcon"); uiTree.setBeanIdField("URI"); uiTree.setBeanChildCountField("ChildrenCount"); uiTree.setBeanLabelField("encodedResolvedLabel"); uiTree.setBeanIconField("icon"); loadNavigations(); } /** * Load navigations. * * @throws Exception the exception */ public void loadNavigations() throws Exception { // get all navigations navigations = new ArrayList<UserNavigation>(); navigations.addAll(userPortal.getNavigations()); // check navigation list if (navigations == null || navigations.size() <= 0) { getChild(UIDropDownControl.class).setOptions(null); getChild(UITree.class).setSibbling(null); return; } // set option values for navigation selector dropdown updateNavigationSelector(); // choose one navigation and show it on UI chooseAndShowNavigation(); } /** * Choose one navigation and show it on UI * * @throws Exception */ private void chooseAndShowNavigation() throws Exception { // select the navigation of current portal String currentPortalName = Util.getPortalRequestContext().getUserPortalConfig().getPortalName(); UserNavigation portalSelectedNav = NavigationUtils.getUserNavigationOfPortal( userPortal, currentPortalName); int portalSelectedNavId = getId(portalSelectedNav); if (getUserNavigation(portalSelectedNavId) != null) { selectNavigation(portalSelectedNavId); UserNode portalSelectedNode = Util.getUIPortal().getSelectedUserNode(); if (portalSelectedNode != null) selectUserNodeByUri(portalSelectedNode.getURI()); return; } // select the first navigation UserNavigation firstNav = navigations.get(0); selectNavigation(getId(firstNav)); UserNode rootNode = userPortal.getNode(firstNav, NavigationUtils.ECMS_NAVIGATION_SCOPE, null, null); Iterator<UserNode> childrenIter = rootNode.getChildren().iterator(); if (childrenIter.hasNext()) { selectUserNodeByUri(childrenIter.next().getURI()); } } /** */ public int getId(UserNavigation nav) { return (nav.getKey().getTypeName() + "::" + nav.getKey().getName()).hashCode(); } /** * get index of a navigation in navigation list * * @param navId the identify of navigation * @return the index of the navigation in navigation list */ private int getIndex(int navId) { int index = -1; if (navigations == null || navigations.size() <= 0) { return index; } for (int i = 0; i < navigations.size(); i++) { UserNavigation nav = navigations.get(i); if (getId(nav) == navId) { index = i; break; } } return index; } /** * Set option values for navigation selector dropdown */ private void updateNavigationSelector() { List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>(); for (UserNavigation navigation : navigations) { options.add(new SelectItemOption<String>(navigation.getKey().getTypeName() + ":" + navigation.getKey().getName(), String.valueOf(getId(navigation)))); } UIDropDownControl uiNavigationSelector = getChild(UIDropDownControl.class); uiNavigationSelector.setOptions(options); if (options.size() > 0) uiNavigationSelector.setValue(0); } /** * Select navigation. * * @param id the id */ public void selectNavigation(int id) throws Exception { UserNavigation selectedNav = getUserNavigation(id); if (selectedNav == null) { return; } UserNode rootNode = userPortal.getNode(selectedNav, NavigationUtils.ECMS_NAVIGATION_SCOPE, null, null); selectedNode = new SelectedNode(selectedNav, rootNode, null, null); selectUserNodeByUri(null); // update tree UITree uiTree = getChild(UITree.class); uiTree.setSibbling(rootNode.getChildren()); // update dropdown UIDropDownControl uiDropDownSelector = getChild(UIDropDownControl.class); uiDropDownSelector.setValue(getIndex(id)); } /** * Select page node by uri. * * @param uri the uri */ public void selectUserNodeByUri(String uri) throws Exception { if (selectedNode == null || uri == null) return; UITree tree = getChild(UITree.class); Collection<?> sibbling = tree.getSibbling(); tree.setSibbling(null); tree.setParentSelected(null); UserNavigation selectedNav = selectedNode.getUserNavigation(); UserNode userNode = userPortal.resolvePath(selectedNav, null, uri); if (userNode != null) { userPortal.updateNode(userNode, NavigationUtils.ECMS_NAVIGATION_SCOPE, null); if (userNode != null) { // selectedNode.setNode(searchUserNodeByUri(selectedNode.getRootNode(), uri)); selectedNode.setNode(userNode); selectedNode.setParentNode(userNode.getParent()); tree.setParentSelected(selectedNode.getParentNode()); tree.setSibbling(selectedNode.getParentNode().getChildren()); tree.setSelected(selectedNode.getNode()); tree.setChildren(selectedNode.getNode().getChildren()); return; } } tree.setSelected(null); tree.setChildren(null); tree.setSibbling(sibbling); } /** * Gets the user navigations. * * @return the page navigations */ public List<UserNavigation> getUserNavigations() { if(navigations == null) navigations = new ArrayList<UserNavigation>(); return navigations; } /** * Gets the user navigation. * * @param id the id * @return the page navigation */ public UserNavigation getUserNavigation(int id) { for (UserNavigation nav : getUserNavigations()) { if (getId(nav) == id) return nav; } return null; } /* (non-Javadoc) * @see org.exoplatform.webui.core.UIComponent#processRender(org.exoplatform.webui.application.WebuiRequestContext) */ public void processRender(WebuiRequestContext context) throws Exception { UIRightClickPopupMenu uiPopupMenu = getChild(UIRightClickPopupMenu.class); if(uiPopupMenu != null) { if(navigations == null || navigations.size() < 1) uiPopupMenu.setRendered(false) ; else uiPopupMenu.setRendered(true) ; } super.processRender(context) ; } /** * Gets the copy node. * * @return the copy node */ public SelectedNode getCopyNode() { return copyNode; } /** * Sets the copy node. * * @param copyNode the new copy node */ public void setCopyNode(SelectedNode copyNode) { this.copyNode = copyNode; } /** * The listener interface for receiving selectNavigationAction events. * The class that is interested in processing a selectNavigationAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSelectNavigationActionListener</code> method. When * the selectNavigationAction event occurs, that object's appropriate * method is invoked. */ static public class SelectNavigationActionListener extends EventListener<UIDropDownControl> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIDropDownControl> event) throws Exception { String id = event.getRequestContext().getRequestParameter(OBJECTID); UIDropDownControl uiDropDownControl = event.getSource(); UIPageNodeSelector uiPageNodeSelector = uiDropDownControl.getAncestorOfType(UIPageNodeSelector.class); event.getRequestContext().addUIComponentToUpdateByAjax(uiPageNodeSelector.getParent()) ; if(id != null) uiPageNodeSelector.selectNavigation(Integer.parseInt(id)); try { UIPageSelector pageSelector = uiPageNodeSelector.getAncestorOfType(UIPageSelector.class); UIPageSelectorPanel pageSelectorPanel = pageSelector.getChild(UIPageSelectorPanel.class); pageSelectorPanel.setSelectedNode(uiPageNodeSelector.getSelectedNode().getNode()); pageSelectorPanel.updateGrid(); event.getRequestContext().addUIComponentToUpdateByAjax(pageSelector); } catch (Exception ex) { org.exoplatform.wcm.webui.Utils.createPopupMessage(uiPageNodeSelector, "UIMessageBoard.msg.select-navigation", null, ApplicationMessage.ERROR); } uiPageNodeSelector.<UIComponent> getParent().broadcast(event, event.getExecutionPhase()); } } /** * The Class SelectedNode. */ public static class SelectedNode { /** The nav. */ private UserNavigation nav; /** The parent node. */ private UserNode parentNode; /** The node. */ private UserNode node; private UserNode rootNode; /** The delete node. */ private boolean deleteNode = false; /** The clone node. */ private boolean cloneNode = false; /** * Instantiates a new selected node. * * @param nav the nav * @param parentNode the parent node * @param node the node */ public SelectedNode(UserNavigation nav, UserNode rootNode, UserNode parentNode, UserNode node) { this.nav = nav; this.rootNode = rootNode; this.parentNode = parentNode; this.node = node; } /** * Gets the user navigation. * * @return the user navigation */ public UserNavigation getUserNavigation() { return nav; } /** * Sets the page navigation. * * @param nav the new page navigation */ public void setUserNavigation(UserNavigation nav) { this.nav = nav; } /** * Gets the root node * * @return the root node */ public UserNode getRootNode() { return rootNode; } /** * Sets the root node * * @param rootNode the root node */ public void setRootNode(UserNode rootNode) { this.rootNode = rootNode; } /** * Gets the parent node. * * @return the parent node */ public UserNode getParentNode() { return parentNode; } /** * Sets the parent node. * * @param parentNode the new parent node */ public void setParentNode(UserNode parentNode) { this.parentNode = parentNode; } /** * Gets the node. * * @return the node */ public UserNode getNode() { return node; } /** * Sets the node. * * @param node the new node */ public void setNode(UserNode node) { this.node = node; } /** * Checks if is delete node. * * @return true, if is delete node */ public boolean isDeleteNode() { return deleteNode; } /** * Sets the delete node. * * @param deleteNode the new delete node */ public void setDeleteNode(boolean deleteNode) { this.deleteNode = deleteNode; } /** * Checks if is clone node. * * @return true, if is clone node */ public boolean isCloneNode() { return cloneNode; } /** * Sets the clone node. * * @param b the new clone node */ public void setCloneNode(boolean b) { cloneNode = b; } } /** * Gets the selected node. * * @return the selected node */ public SelectedNode getSelectedNode() { return selectedNode; } /** * Gets the selected navigation. * * @return the selected navigation */ public UserNavigation getSelectedNavigation() { return selectedNode == null ? null : selectedNode.getUserNavigation(); } /** * Gets the root node of the selected navigation. * * @return the root node of the selected navigation. */ public UserNode getRootNodeOfSelectedNav() { return selectedNode == null ? null : selectedNode.getRootNode(); } /** * Gets the selected page node. * * @return the selected page node */ public UserNode getSelectedUserNode() { return selectedNode == null ? null : selectedNode.getNode(); } /** * Gets the up level uri. * * @return the up level uri */ public String getUpLevelUri() { return selectedNode.getParentNode().getURI(); } /** * Gets the delete navigations. * * @return the delete navigations */ public List<UserNavigation> getDeleteNavigations() { return deleteNavigations; } }
16,294
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIPageSelector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/page/UIPageSelector.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.selector.page; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.ComponentConfigs; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UITree; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.event.Event.Phase; import org.exoplatform.webui.form.UIForm; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Jun 30, 2009 */ @ComponentConfigs({ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "classpath:groovy/wcm/webui/selector/page/UIPageSelector.gtmpl", events = {@EventConfig(listeners = UIPageSelector.ChangeNodeActionListener.class, phase = Phase.DECODE)} ) } ) public class UIPageSelector extends UIForm { /** The source ui component. */ private UIComponent sourceUIComponent ; /** The return field name. */ private String returnFieldName ; /** * Instantiates a new uI page selector. * * @throws Exception the exception */ public UIPageSelector() throws Exception { UIPageNodeSelector pageNodeSelector = addChild(UIPageNodeSelector.class, null, null); UITree uiTree = pageNodeSelector.getChild(UITree.class); uiTree.setUIRightClickPopupMenu(null); UIPageSelectorPanel pageSelectorPanel = addChild(UIPageSelectorPanel.class, null, null); pageSelectorPanel.setSelectedNode(pageNodeSelector.getSelectedNode().getNode()); pageSelectorPanel.updateGrid(); } /** * Gets the return field name. * * @return the return field name */ public String getReturnFieldName() { return returnFieldName; } /** * Sets the return field name. * * @param name the new return field name */ public void setReturnFieldName(String name) { this.returnFieldName = name; } /** * Gets the source component. * * @return the source component */ public UIComponent getSourceComponent() { return sourceUIComponent; } /** * Sets the source component. * * @param uicomponent the uicomponent * @param initParams the init params */ public void setSourceComponent(UIComponent uicomponent, String[] initParams) { sourceUIComponent = uicomponent ; if(initParams == null || initParams.length < 0) return ; for(int i = 0; i < initParams.length; i ++) { if(initParams[i].indexOf("returnField") > -1) { String[] array = initParams[i].split("=") ; returnFieldName = array[1] ; break ; } returnFieldName = initParams[0] ; } } /* (non-Javadoc) * @see org.exoplatform.webui.core.UIComponent#processDecode(org.exoplatform.webui.application.WebuiRequestContext) */ public void processDecode(WebuiRequestContext context) throws Exception { super.processDecode(context); String action = context.getRequestParameter(UIForm.ACTION); Event<UIComponent> event = createEvent(action, Event.Phase.DECODE, context) ; if(event != null) event.broadcast() ; } /** * The listener interface for receiving changeNodeAction events. * The class that is interested in processing a changeNodeAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addChangeNodeActionListener</code> method. When * the changeNodeAction event occurs, that object's appropriate * method is invoked. */ public static class ChangeNodeActionListener extends EventListener<UIPageSelector> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIPageSelector> event) throws Exception { UIPageSelector pageSelector = event.getSource() ; UIPageNodeSelector pageNodeSelector = pageSelector.getChild(UIPageNodeSelector.class) ; String uri = event.getRequestContext().getRequestParameter(OBJECTID) ; UITree tree = pageNodeSelector.getChild(UITree.class) ; if(tree.getParentSelected() == null && (uri == null || uri.length() < 1)){ pageNodeSelector.selectNavigation(pageNodeSelector.getId(pageNodeSelector.getSelectedNavigation())); } else { pageNodeSelector.selectUserNodeByUri(uri); } UIPageSelectorPanel pageSelectorPanel = pageSelector.getChild(UIPageSelectorPanel.class); pageSelectorPanel.setSelectedNode(pageNodeSelector.getSelectedNode().getNode()); pageSelectorPanel.updateGrid(); event.getRequestContext().addUIComponentToUpdateByAjax(pageSelector) ; } } }
5,782
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIUserContainer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/account/UIUserContainer.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.selector.account; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.organization.account.UIUserSelector; /** * Created by The eXo Platform SAS * Author : Phan Le Thanh Chuong * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Nov 1, 2009 */ @ComponentConfig ( lifecycle = UIContainerLifecycle.class, events = { @EventConfig(listeners = UIUserContainer.AddUserActionListener.class) } ) public class UIUserContainer extends UIContainer { private UISelectable selectable; private String sourceComponent; public UISelectable getSelectable() { return selectable; } public void setSelectable(UISelectable selectable) { this.selectable = selectable; } public String getSourceComponent() { return sourceComponent; } public void setSourceComponent(String sourceComponent) { this.sourceComponent = sourceComponent; } public UIUserContainer() throws Exception { UIUserSelector userSelector = addChild(UIUserSelector.class, null, null); userSelector.setMulti(false); userSelector.setShowSearchUser(true); userSelector.setShowSearch(true); } public static class AddUserActionListener extends EventListener<UIUserContainer> { public void execute(Event<UIUserContainer> event) throws Exception { UIUserContainer userContainer = event.getSource(); UIUserSelector userSelector = userContainer.getChild(UIUserSelector.class); userContainer.getSelectable().doSelect(userContainer.getSourceComponent(), userSelector.getSelectedUsers()); } } }
2,653
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentResultViewer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/content/UIContentResultViewer.java
package org.exoplatform.wcm.webui.selector.content; import javax.jcr.Node; import javax.portlet.PortletPreferences; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.wcm.core.NodeIdentifier; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.publication.NotInWCMPublicationException; import org.exoplatform.services.wcm.publication.WCMPublicationService; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Author : TAN DUNG DANG * dzungdev@gmail.com * Feb 12, 2009 */ @ComponentConfig ( template="classpath:groovy/wcm/webui/selector/content/UIContentResultViewer.gtmpl", events = { @EventConfig(listeners = UIContentResultViewer.SelectActionListener.class) } ) public class UIContentResultViewer extends UIContainer { private NodeLocation presentNodeLocation; public String[] getActions() { return new String[] {"Select"}; } public static class SelectActionListener extends EventListener<UIContentResultViewer> { public void execute(Event<UIContentResultViewer> event) throws Exception { UIContentResultViewer contentResultView = event.getSource(); Node presentNode = NodeLocation.getNodeByLocation(contentResultView.presentNodeLocation); Node webContent = presentNode; NodeIdentifier nodeIdentifier = NodeIdentifier.make(webContent); PortletRequestContext pContext = (PortletRequestContext) event.getRequestContext(); PortletPreferences prefs = pContext.getRequest().getPreferences(); prefs.setValue("repository", nodeIdentifier.getRepository()); prefs.setValue("workspace", nodeIdentifier.getWorkspace()); prefs.setValue("nodeIdentifier", nodeIdentifier.getUUID()); prefs.store(); String remoteUser = Util.getPortalRequestContext().getRemoteUser(); String currentSite = Util.getPortalRequestContext().getPortalOwner(); WCMPublicationService wcmPublicationService = contentResultView.getApplicationComponent(WCMPublicationService.class); try { wcmPublicationService.isEnrolledInWCMLifecycle(webContent); } catch (NotInWCMPublicationException e){ wcmPublicationService.unsubcribeLifecycle(webContent); wcmPublicationService.enrollNodeInLifecycle(webContent, currentSite, remoteUser); } } } }
2,702
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentBrowsePanel.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/content/UIContentBrowsePanel.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.selector.content; import javax.jcr.Node; import org.exoplatform.ecm.webui.tree.UIBaseNodeTreeSelector; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.Lifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS. * * @author : Hoa.Pham hoa.pham@exoplatform.com Jun 23, 2008 */ @ComponentConfig( lifecycle = Lifecycle.class, events = { @EventConfig(listeners = UIContentBrowsePanel.ChangeContentTypeActionListener.class) } ) public abstract class UIContentBrowsePanel extends UIBaseNodeTreeSelector { public static final String WEBCONTENT = "Web Contents"; public static final String DMSDOCUMENT = "DMS Documents"; public static final String MEDIA = "Medias"; private String contentType = WEBCONTENT; public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public void onChange(Node node, Object context) throws Exception {} public static class ChangeContentTypeActionListener extends EventListener<UIContentBrowsePanel> { public void execute(Event<UIContentBrowsePanel> event) throws Exception { UIContentBrowsePanel contentBrowsePanel = event.getSource(); contentBrowsePanel.contentType = event.getRequestContext().getRequestParameter(OBJECTID); event.getRequestContext() .addUIComponentToUpdateByAjax(contentBrowsePanel.getAncestorOfType(UIContentSelector.class) .getChild(UIContentSearchForm.class)); } } }
2,541
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentSelector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/content/UIContentSelector.java
package org.exoplatform.wcm.webui.selector.content; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.UITabPane; /** * Author : TAN DUNG DANG * dzungdev@gmail.com * Jan 20, 2009 */ @ComponentConfig( template = "system:/groovy/webui/core/UITabPane_New.gtmpl" ) public class UIContentSelector extends UITabPane { /** The Constant FOLDER_PATH_SELECTOR_POPUP_WINDOW. */ public static final String FOLDER_PATH_SELECTOR_POPUP_WINDOW = "FolderPathSelectorPopupWindow"; /** The Constant CORRECT_CONTENT_SELECTOR_POPUP_WINDOW. */ public static final String CORRECT_CONTENT_SELECTOR_POPUP_WINDOW = "CorrectContentSelectorPopupWindow"; public void initMetadataPopup(UIContainer uicontainer) throws Exception { UIPopupWindow uiPopupWindow = this.initPopup(uicontainer, UIContentPropertySelector.WEB_CONTENT_METADATA_POPUP); UIContentPropertySelector contentPropertySelector = createUIComponent(UIContentPropertySelector.class, null, null); uiPopupWindow.setUIComponent(contentPropertySelector); contentPropertySelector.setFieldName(UIContentSearchForm.PROPERTY); // Utils.createPopupWindow(this, contentPropertySelector, UIContentPropertySelector.WEB_CONTENT_METADATA_POPUP, 500); contentPropertySelector.init(); this.setSelectedTab(2); uiPopupWindow.setRendered(true); uiPopupWindow.setShow(true); } public void initNodeTypePopup(UIContainer uicontainer) throws Exception { UIPopupWindow uiPopupWindow = this.initPopup(uicontainer, UIContentNodeTypeSelector.WEB_CONTENT_NODETYPE_POPUP); UIContentNodeTypeSelector contentNodetypeSelector = createUIComponent(UIContentNodeTypeSelector.class, null, null); uiPopupWindow.setUIComponent(contentNodetypeSelector); contentNodetypeSelector.init(); this.setSelectedTab(2); uiPopupWindow.setRendered(true); uiPopupWindow.setShow(true); } private UIPopupWindow initPopup(UIContainer uiContainer, String id) throws Exception { UIPopupWindow uiPopup = uiContainer.getChildById(id); if (uiPopup == null) { uiPopup = uiContainer.addChild(UIPopupWindow.class, null, id); } uiPopup.setWindowSize(500, 0); uiPopup.setShow(false); uiPopup.setResizable(true); return uiPopup; } }
2,459
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentSearchResult.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/content/UIContentSearchResult.java
package org.exoplatform.wcm.webui.selector.content; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import javax.jcr.Node; import javax.jcr.Session; import javax.portlet.PortletPreferences; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.core.WCMConfigurationService; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.services.wcm.search.ResultNode; import org.exoplatform.services.wcm.search.base.AbstractPageList; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.viewer.UIContentViewer; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.UIGrid; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Author : TAN DUNG DANG * dzungdev@gmail.com * Feb 10, 2009 */ @ComponentConfig( events = { @EventConfig(listeners = UIContentSearchResult.SelectActionListener.class), @EventConfig(listeners = UIContentSearchResult.ViewActionListener.class) } ) public class UIContentSearchResult extends UIGrid { /** The Constant TITLE. */ public static final String TITLE = "title"; /** The Constant NODE_EXPECT. */ public static final String NODE_EXPECT = "excerpt"; /** The Constant SCORE. */ public static final String SCORE = "score"; /** The Constant CREATE_DATE. */ public static final String CREATE_DATE = "CreateDate"; /** The Constant PUBLICATION_STATE. */ public static final String PUBLICATION_STATE = "publicationstate"; /** The Constant NODE_PATH. */ public static final String NODE_PATH = "path"; /** The Actions. */ public String[] Actions = {"Select", "View"}; /** The BEA n_ fields. */ public String[] BEAN_FIELDS = {TITLE, SCORE, PUBLICATION_STATE}; /** * Instantiates a new uIWCM search result. * * @throws Exception the exception */ public UIContentSearchResult() throws Exception { configure(NODE_PATH, BEAN_FIELDS, Actions); getUIPageIterator().setId("UIWCMSearchResultPaginator"); } /** * Gets the date format. * * @return the date format */ public DateFormat getDateFormat() { Locale locale = Util.getPortalRequestContext().getLocale(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); return dateFormat; } /** * Update grid. * * @param pageList the paginated result * * @throws Exception the exception */ public void updateGrid(AbstractPageList<ResultNode> pageList) throws Exception { getUIPageIterator().setPageList(pageList); } /** * Gets the title node. * * @param node the node * * @return the title node * * @throws Exception the exception */ public String getTitleNode(Node node) throws Exception { return node.hasProperty("exo:title") ? node.getProperty("exo:title").getValue().getString() : node.getName(); } /** * Gets the creates the date. * * @param node the node * * @return the creates the date * * @throws Exception the exception */ public Date getCreateDate(Node node) throws Exception { if(node.hasProperty("exo:dateCreated")) { Calendar cal = node.getProperty("exo:dateCreated").getValue().getDate(); return cal.getTime(); } return null; } /** * Gets the expect. * * @param expect the expect * * @return the expect */ public String getExpect(String expect) { expect = expect.replaceAll("<[^>]*/?>", ""); return expect; } /** * Gets the current state. * * @param node the node * * @return the current state * * @throws Exception the exception */ public String getCurrentState(Node node) throws Exception { PublicationService pubService = getApplicationComponent(PublicationService.class); return pubService.getCurrentState(node); } /** * Gets the session. * * @return the session * * @throws Exception the exception */ public Session getSession() throws Exception { RepositoryService repoService = getApplicationComponent(RepositoryService.class); ManageableRepository maRepository = repoService.getCurrentRepository(); PortletRequestContext pContext = (PortletRequestContext) WebuiRequestContext.getCurrentInstance(); PortletPreferences prefs = pContext.getRequest().getPreferences(); String workspace = prefs.getValue("workspace", null); if(workspace == null) { WCMConfigurationService wcmConfService = getApplicationComponent(WCMConfigurationService.class); NodeLocation nodeLocation = wcmConfService.getLivePortalsLocation(); workspace = nodeLocation.getWorkspace(); } Session session = WCMCoreUtils.getUserSessionProvider().getSession(workspace, maRepository); return session; } /** * Gets the workspace name. * @param node the node * @return name of workspace * @throws Exception the exception */ public String getWorkspaceName(Node node) throws Exception { return node.getSession().getWorkspace().getName(); } public String getRepository() throws Exception { RepositoryService repoService = getApplicationComponent(RepositoryService.class); ManageableRepository maRepository = repoService.getCurrentRepository(); return maRepository.getConfiguration().getName(); } /** * The listener interface for receiving selectAction events. * The class that is interested in processing a selectAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSelectActionListener</code> method. When * the selectAction event occurs, that object's appropriate * method is invoked. */ public static class SelectActionListener extends EventListener<UIContentSearchResult> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIContentSearchResult> event) throws Exception { UIContentSearchResult contentSearchResult = event.getSource(); UIContentSelector contentSelector = contentSearchResult.getAncestorOfType(UIContentSelector.class); UIContentBrowsePanel contentBrowsePanel = contentSelector.getChild(UIContentBrowsePanel.class); ((UISelectable) (contentBrowsePanel.getSourceComponent())).doSelect(contentBrowsePanel.getReturnFieldName(), event.getRequestContext() .getRequestParameter(OBJECTID)); } } /** * The listener interface for receiving viewAction events. * The class that is interested in processing a viewAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addViewActionListener</code> method. When * the viewAction event occurs, that object's appropriate * method is invoked. */ public static class ViewActionListener extends EventListener<UIContentSearchResult> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIContentSearchResult> event) throws Exception { UIContentSearchResult contentSearchResult = event.getSource(); UIApplication uiApp = contentSearchResult.getAncestorOfType(UIApplication.class); String expression = event.getRequestContext().getRequestParameter(OBJECTID); NodeLocation nodeLocation = NodeLocation.getNodeLocationByExpression(expression); String repository = nodeLocation.getRepository(); String workspace = nodeLocation.getWorkspace(); String webcontentPath = nodeLocation.getPath(); Node originalNode = Utils.getViewableNodeByComposer(repository, workspace, webcontentPath, WCMComposer.BASE_VERSION); Node viewNode = Utils.getViewableNodeByComposer(repository, workspace, webcontentPath); TemplateService templateService = WCMCoreUtils.getService(TemplateService.class); String nodeType = originalNode.getPrimaryNodeType().getName(); if (templateService.isManagedNodeType(nodeType)) { UIContentSelector contentSelector = contentSearchResult.getAncestorOfType(UIContentSelector.class); UIContentViewer contentResultViewer = contentSelector.getChild(UIContentViewer.class); if (contentResultViewer == null) contentResultViewer = contentSelector.addChild(UIContentViewer.class, null, null); contentResultViewer.setNode(viewNode); contentResultViewer.setOriginalNode(originalNode); event.getRequestContext().addUIComponentToUpdateByAjax(contentSelector); contentSelector.setSelectedTab(contentResultViewer.getId()); } else { uiApp.addMessage(new ApplicationMessage("UIContentSearchResult.msg.template-not-support", null, ApplicationMessage.WARNING)); } } } }
10,460
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentSearchForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/content/UIContentSearchForm.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.selector.content; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.ResourceBundle; import javax.jcr.RepositoryException; import javax.jcr.query.InvalidQueryException; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.wcm.core.WCMConfigurationService; import org.exoplatform.services.wcm.search.QueryCriteria; import org.exoplatform.services.wcm.search.QueryCriteria.DATE_RANGE_SELECTED; import org.exoplatform.services.wcm.search.QueryCriteria.DatetimeRange; import org.exoplatform.services.wcm.search.ResultNode; import org.exoplatform.services.wcm.search.SiteSearchService; import org.exoplatform.services.wcm.search.base.AbstractPageList; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.selector.content.UIContentSelector; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormDateTimeInput; import org.exoplatform.webui.form.UIFormSelectBox; import org.exoplatform.webui.form.UIFormStringInput; /** * Created by The eXo Platform SAS * Author : DANG TAN DUNG * dzungdev@gmail.com * Jan 5, 2009 */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "classpath:groovy/wcm/webui/selector/content/UIContentSearchForm.gtmpl", events = { @EventConfig(listeners = UIContentSearchForm.SearchWebContentActionListener.class), @EventConfig(listeners = UIContentSearchForm.AddMetadataTypeActionListener.class), @EventConfig(listeners = UIContentSearchForm.AddNodeTypeActionListener.class) } ) public class UIContentSearchForm extends UIForm { public static final String LOCATION = "location"; public static final String SEARCH_BY_NAME = "name"; public static final String SEARCH_BY_CONTENT = "content"; public static final String RADIO_NAME = "WcmRadio"; final static public String TIME_OPTION = "timeOpt"; final static public String PROPERTY = "property"; final static public String CONTAIN = "contain"; final static public String START_TIME = "startTime"; final static public String END_TIME = "endTime"; final static public String DOC_TYPE = "docType"; final static public String CATEGORY = "category"; final static public String CREATED_DATE = "CREATED"; final static public String MODIFIED_DATE = "MODIFIED"; final static public String EXACTLY_PROPERTY = "exactlyPro"; final static public String CONTAIN_PROPERTY = "containPro"; final static public String NOT_CONTAIN_PROPERTY = "notContainPro"; final static public String DATE_PROPERTY = "datePro"; final static public String NODETYPE_PROPERTY = "nodetypePro"; final static public String CHECKED_RADIO_ID = "checkedRadioId"; private String checkedRadioId; public UIContentSearchForm() throws Exception { } public void init() throws Exception { List<SelectItemOption<String>> portalNameOptions = new ArrayList<SelectItemOption<String>>(); List<String> portalNames = getPortalNames(); for(String portalName: portalNames) { portalNameOptions.add(new SelectItemOption<String>(portalName, portalName)); } UIFormSelectBox portalNameSelectBox = new UIFormSelectBox(LOCATION, LOCATION, portalNameOptions); portalNameSelectBox.setDefaultValue(portalNames.get(0)); addChild(portalNameSelectBox); addUIFormInput(new UIFormStringInput(SEARCH_BY_NAME,SEARCH_BY_NAME,null)); addUIFormInput(new UIFormStringInput(SEARCH_BY_CONTENT, SEARCH_BY_CONTENT, null)); addUIFormInput(new UIFormStringInput(PROPERTY, PROPERTY, null).setDisabled(true)); addUIFormInput(new UIFormStringInput(CONTAIN, CONTAIN, null)); List<SelectItemOption<String>> dateOptions = new ArrayList<SelectItemOption<String>>(); dateOptions.add(new SelectItemOption<String>(CREATED_DATE,CREATED_DATE)); dateOptions.add(new SelectItemOption<String>(MODIFIED_DATE,MODIFIED_DATE)); addUIFormInput(new UIFormSelectBox(TIME_OPTION,TIME_OPTION, dateOptions)); UIFormDateTimeInput startTime = new UIFormDateTimeInput(START_TIME, START_TIME, null, true); addUIFormInput(startTime); UIFormDateTimeInput endTime = new UIFormDateTimeInput(END_TIME, END_TIME, null, true); addUIFormInput(endTime); addUIFormInput(new UIFormStringInput(DOC_TYPE, DOC_TYPE, null).setDisabled(true)); setActions(new String[] {"SearchWebContent"} ); } private List<String> getPortalNames() throws Exception { List<String> portalNames = new ArrayList<String>(); String currentPortalName = Util.getPortalRequestContext().getPortalOwner(); WCMConfigurationService configService = getApplicationComponent(WCMConfigurationService.class); String sharedPortalName = configService.getSharedPortalName(); portalNames.add(currentPortalName); portalNames.add(sharedPortalName); return portalNames; } public static class AddMetadataTypeActionListener extends EventListener<UIContentSearchForm> { public void execute(Event<UIContentSearchForm> event) throws Exception { UIContentSearchForm contentSearchForm = event.getSource(); UIContentSelector contentSelector = contentSearchForm.getParent(); contentSearchForm.setCheckedRadioId(event.getRequestContext().getRequestParameter(CHECKED_RADIO_ID)); UIContainer uiContainer = contentSearchForm.getAncestorOfType(UIContentSelector.class).getAncestorOfType(UIContainer.class); contentSelector.initMetadataPopup(uiContainer); event.getRequestContext().addUIComponentToUpdateByAjax(uiContainer); } } public static class AddNodeTypeActionListener extends EventListener<UIContentSearchForm> { public void execute(Event<UIContentSearchForm> event) throws Exception { UIContentSearchForm contentSearchForm = event.getSource(); UIContentSelector contentSelector = contentSearchForm.getParent(); contentSearchForm.setCheckedRadioId(event.getRequestContext().getRequestParameter(CHECKED_RADIO_ID)); UIContainer uiContainer = contentSearchForm.getAncestorOfType(UIContentSelector.class).getAncestorOfType(UIContainer.class); contentSelector.initNodeTypePopup(uiContainer); event.getRequestContext().addUIComponentToUpdateByAjax(uiContainer); } } private QueryCriteria getInitialQueryCriteria(String siteName) throws Exception { QueryCriteria qCriteria = new QueryCriteria(); TemplateService templateService = WCMCoreUtils.getService(TemplateService.class); String[] allContentType = templateService.getDocumentTemplates().toArray(new String[0]); qCriteria.setContentTypes(allContentType); //only get the content nodes which have the document template. qCriteria.setSearchWebpage(false); qCriteria.setSiteName(siteName); qCriteria.setLiveMode(false); return qCriteria; } private boolean haveEmptyField(UIApplication uiApp, Event<UIContentSearchForm> event, String field, String messageKey) throws Exception { if(field == null || "".equals(field) || (field.toString().trim().length() <= 0)) { uiApp.addMessage(new ApplicationMessage( messageKey, null, ApplicationMessage.WARNING)); WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); requestContext.addUIComponentToUpdateByAjax(this); return true; } return false; } private AbstractPageList<ResultNode> searchContentByName(String keyword, QueryCriteria qCriteria, int pageSize) throws Exception { qCriteria.setFulltextSearch(false); qCriteria.setKeyword(keyword); WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); SiteSearchService siteSearch = getApplicationComponent(SiteSearchService.class); return siteSearch.searchSiteContents(WCMCoreUtils.getUserSessionProvider(), qCriteria, requestContext.getLocale(), pageSize, true); } private AbstractPageList<ResultNode> searchContentByFulltext(String keyword, QueryCriteria qCriteria, int pageSize) throws Exception { qCriteria.setFulltextSearch(true); qCriteria.setFulltextSearchProperty(new String[] {QueryCriteria.ALL_PROPERTY_SCOPE}); qCriteria.setKeyword(keyword); WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); SiteSearchService siteSearch = getApplicationComponent(SiteSearchService.class); return siteSearch.searchSiteContents(WCMCoreUtils.getUserSessionProvider(), qCriteria, requestContext.getLocale(), pageSize, true); } private AbstractPageList<ResultNode> searchContentByProperty(String property, String keyword, QueryCriteria qCriteria, int pageSize) throws Exception { qCriteria.setFulltextSearch(true); qCriteria.setFulltextSearchProperty(new String[] {property}); qCriteria.setKeyword(keyword); WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); SiteSearchService siteSearchService = getApplicationComponent(SiteSearchService.class); return siteSearchService.searchSiteContents(WCMCoreUtils.getUserSessionProvider(), qCriteria, requestContext.getLocale(), pageSize, true); } private AbstractPageList<ResultNode> searchContentByDate(DATE_RANGE_SELECTED dateRangeSelected, Calendar fromDate, Calendar endDate, QueryCriteria qCriteria, int pageSize) throws Exception { qCriteria.setDateRangeSelected(dateRangeSelected); DatetimeRange dateTimeRange = new QueryCriteria.DatetimeRange(fromDate, endDate); if(DATE_RANGE_SELECTED.CREATED.equals(dateRangeSelected)) { qCriteria.setCreatedDateRange(dateTimeRange); } else if(DATE_RANGE_SELECTED.MODIFIDED.equals(dateRangeSelected)) { qCriteria.setLastModifiedDateRange(dateTimeRange); } qCriteria.setFulltextSearch(true); qCriteria.setFulltextSearchProperty(null); WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); SiteSearchService siteSearch = getApplicationComponent(SiteSearchService.class); return siteSearch.searchSiteContents(WCMCoreUtils.getUserSessionProvider(), qCriteria, requestContext.getLocale(), pageSize, true); } private AbstractPageList<ResultNode> searchContentByType(String documentType, QueryCriteria qCriteria, int pageSize) throws Exception { qCriteria.setFulltextSearch(true); qCriteria.setFulltextSearchProperty(null); qCriteria.setContentTypes(documentType.split(",")); WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); SiteSearchService siteSearch = getApplicationComponent(SiteSearchService.class); return siteSearch.searchSiteContents(WCMCoreUtils.getUserSessionProvider(), qCriteria, requestContext.getLocale(), pageSize, true); } static public class SearchWebContentActionListener extends EventListener<UIContentSearchForm> { public void execute(Event<UIContentSearchForm> event) throws Exception { WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); UIContentSearchForm uiWCSearch = event.getSource(); int pageSize = 5; String radioValue = event.getRequestContext().getRequestParameter(RADIO_NAME); uiWCSearch.setCheckedRadioId(event.getRequestContext().getRequestParameter(CHECKED_RADIO_ID)); String siteName = uiWCSearch.getUIStringInput(UIContentSearchForm.LOCATION).getValue(); UIContentSelector uiWCTabSelector = uiWCSearch.getParent(); UIApplication uiApp = uiWCSearch.getAncestorOfType(UIApplication.class); QueryCriteria qCriteria = uiWCSearch.getInitialQueryCriteria(siteName); AbstractPageList<ResultNode> pagResult = null; ResourceBundle resourceBundle = WebuiRequestContext.getCurrentInstance().getApplicationResourceBundle(); try { if (UIContentSearchForm.SEARCH_BY_NAME.equals(radioValue)) { String keyword = uiWCSearch.getUIStringInput(radioValue).getValue(); if (uiWCSearch.haveEmptyField(uiApp, event, keyword,"UIContentSearchForm.msg.empty-name")) return; pagResult = uiWCSearch.searchContentByName(keyword.trim(), qCriteria, pageSize); } else if (UIContentSearchForm.SEARCH_BY_CONTENT.equals(radioValue)) { String keyword = uiWCSearch.getUIStringInput(radioValue).getValue(); if (uiWCSearch.haveEmptyField(uiApp, event, keyword,"UIContentSearchForm.msg.empty-content")) return; pagResult = uiWCSearch.searchContentByFulltext(keyword, qCriteria, pageSize); } else if (UIContentSearchForm.PROPERTY.equals(radioValue)) { String property = uiWCSearch.getUIStringInput(UIContentSearchForm.PROPERTY).getValue(); if (uiWCSearch.haveEmptyField(uiApp, event, property,"UIContentSearchForm.msg.empty-property")) return; String keyword = uiWCSearch.getUIStringInput(UIContentSearchForm.CONTAIN).getValue(); if (uiWCSearch.haveEmptyField(uiApp, event, keyword,"UIContentSearchForm.msg.empty-property-keyword")) return; pagResult = uiWCSearch.searchContentByProperty(property, keyword, qCriteria, pageSize); } else if (UIContentSearchForm.TIME_OPTION.equals(radioValue)) { UIFormDateTimeInput startDateInput = uiWCSearch.getUIFormDateTimeInput(UIContentSearchForm.START_TIME); UIFormDateTimeInput endDateInput = uiWCSearch.getUIFormDateTimeInput(UIContentSearchForm.END_TIME); //startDateInput cannot be empty String strStartDate = startDateInput.getValue(); if (uiWCSearch.haveEmptyField(uiApp, event, strStartDate,"UIContentSearchForm.msg.empty-startDate")) return; //startDateInput must have a valid format try { DateFormat dateFormat = new SimpleDateFormat(startDateInput.getDatePattern_().trim()); dateFormat.setLenient(false); dateFormat.parse(startDateInput.getValue()); } catch (ParseException e) { uiApp.addMessage(new ApplicationMessage("UIContentSearchForm.msg.invalid-format", new Object[] { resourceBundle.getString("UIContentSearchForm.title.FromDate") }, ApplicationMessage.WARNING)); requestContext.addUIComponentToUpdateByAjax(uiWCSearch); return; } Calendar startDate = startDateInput.getCalendar(); Calendar endDate = null; if (endDateInput.getValue() == null || endDateInput.getValue().length() == 0) { //set endDate value when endDateInput is empty if (startDate.getTimeInMillis() > Calendar.getInstance().getTimeInMillis()) { endDate = startDate; } else { endDate = Calendar.getInstance(); } } else { //endDateInput should have a valid format try { DateFormat dateFormat = new SimpleDateFormat(endDateInput.getDatePattern_().trim()); dateFormat.setLenient(false); dateFormat.parse(endDateInput.getValue()); } catch (ParseException e) { uiApp.addMessage(new ApplicationMessage("UIContentSearchForm.msg.invalid-format", new Object[] { resourceBundle.getString("UIContentSearchForm.title.ToDate") }, ApplicationMessage.WARNING)); requestContext.addUIComponentToUpdateByAjax(uiWCSearch); return; } endDate = endDateInput.getCalendar(); } //startDate cannot be after endDate if (startDate.getTimeInMillis() > endDate.getTimeInMillis()) { uiApp.addMessage(new ApplicationMessage("UIContentSearchForm.msg.invalid-date", null, ApplicationMessage.WARNING)); requestContext.addUIComponentToUpdateByAjax(uiWCSearch); return; } // startDate cannot be later than today if (startDate.getTimeInMillis() > Calendar.getInstance().getTimeInMillis()) { uiApp.addMessage(new ApplicationMessage("UIContentSearchForm.msg.invalid-startDate", null, ApplicationMessage.WARNING)); requestContext.addUIComponentToUpdateByAjax(uiWCSearch); return; } try { String dateRangeSelected = uiWCSearch.getUIStringInput(UIContentSearchForm.TIME_OPTION).getValue(); if (UIContentSearchForm.CREATED_DATE.equals(dateRangeSelected)) { pagResult = uiWCSearch.searchContentByDate(DATE_RANGE_SELECTED.CREATED, startDate, endDate, qCriteria, pageSize); } else { pagResult = uiWCSearch.searchContentByDate(DATE_RANGE_SELECTED.MODIFIDED, startDate, endDate, qCriteria, pageSize); } } catch (IllegalArgumentException iaEx) { uiApp.addMessage(new ApplicationMessage("UIContentSearchForm.msg.time-to-late", null, ApplicationMessage.WARNING)); requestContext.addUIComponentToUpdateByAjax(uiWCSearch); return; } } else if (UIContentSearchForm.DOC_TYPE.equals(radioValue)) { String documentType = uiWCSearch.getUIStringInput(UIContentSearchForm.DOC_TYPE) .getValue(); if (uiWCSearch.haveEmptyField(uiApp, event, documentType,"UIContentSearchForm.msg.empty-doctype")) return; try { pagResult = uiWCSearch.searchContentByType(documentType, qCriteria, pageSize); } catch (Exception ex) { uiApp.addMessage(new ApplicationMessage("UIContentSearchForm.msg.invalid-nodeType", new Object[] { documentType }, ApplicationMessage.ERROR)); requestContext.addUIComponentToUpdateByAjax(uiWCSearch); return; } } } catch (InvalidQueryException iqe) { uiApp.addMessage(new ApplicationMessage("UIContentSearchForm.msg.invalid-keyword", null, ApplicationMessage.WARNING)); requestContext.addUIComponentToUpdateByAjax(uiWCSearch); return; } catch (RepositoryException re) { uiApp.addMessage(new ApplicationMessage("UIContentSearchForm.msg.invalid-keyword", null, ApplicationMessage.WARNING)); requestContext.addUIComponentToUpdateByAjax(uiWCSearch); return; } UIContentSearchResult uiWCSearchResult = uiWCTabSelector.getChild(UIContentSearchResult.class); uiWCSearchResult.updateGrid(pagResult); event.getRequestContext().addUIComponentToUpdateByAjax(uiWCTabSelector); uiWCTabSelector.setSelectedTab(uiWCSearchResult.getId()); } } public String getCheckedRadioId() { return checkedRadioId; } public void setCheckedRadioId(String checkedRadioId) { this.checkedRadioId = checkedRadioId; } }
22,279
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentNodeTypeSelector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/content/UIContentNodeTypeSelector.java
package org.exoplatform.wcm.webui.selector.content; import java.util.ArrayList; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.Event.Phase; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.input.UICheckBoxInput; /** * Author : TAN DUNG DANG * dzungdev@gmail.com * Feb 2, 2009 */ @ComponentConfig ( lifecycle = UIFormLifecycle.class, template = "system:/groovy/webui/form/UIForm.gtmpl", events = { @EventConfig(listeners = UIContentNodeTypeSelector.SaveActionListener.class), @EventConfig(listeners = UIContentNodeTypeSelector.CancelActionListener.class, phase=Phase.DECODE) } ) public class UIContentNodeTypeSelector extends UIForm { public final static String WEB_CONTENT_NODETYPE_POPUP = "WebContentNodeTypePopup"; /** * Instantiates a new uIWCM node type select form. * * @throws Exception the exception */ public UIContentNodeTypeSelector() throws Exception { } /** * Inits the. * * @throws Exception the exception */ public void init() throws Exception { getChildren().clear(); TemplateService tempService = getApplicationComponent(TemplateService.class); List<String> nodeTypes = tempService.getAllDocumentNodeTypes(); UICheckBoxInput uiCheckBox = null; for(String nodeType : nodeTypes) { uiCheckBox = new UICheckBoxInput(nodeType, nodeType, null); if(propertiesSelected(nodeType)) uiCheckBox.setChecked(true); else uiCheckBox.setChecked(false); addUIFormInput(uiCheckBox); } } public String getLabel(ResourceBundle res, String id) { try { return res.getString("UIContentNodeTypeSelector.label." + id) ; } catch (MissingResourceException ex) { return id + " "; } } /** * Properties selected. * * @param name the name * * @return true, if successful */ private boolean propertiesSelected(String name) { UIPopupWindow uiPopupWindow = this.getParent(); UIContainer uiContainer = uiPopupWindow.getAncestorOfType(UIContainer.class); UIContentSelector contentSelector = (UIContentSelector) uiContainer.findFirstComponentOfType(UIContentSelector.class); UIContentSearchForm contentSearchForm = contentSelector.getChild(UIContentSearchForm.class); String typeValues = contentSearchForm.getUIStringInput(UIContentSearchForm.DOC_TYPE).getValue() ; if(typeValues == null) return false ; if(typeValues.indexOf(",") > -1) { String[] values = typeValues.split(",") ; for(String value : values) { if(value.equals(name)) return true ; } } else if(typeValues.equals(name)) { return true ; } return false ; } /** * Sets the node types. * * @param selectedNodeTypes the selected node types * @param uiWCSearchForm the ui wc search form */ private void setNodeTypes(List<String> selectedNodeTypes, UIContentSearchForm uiWCSearchForm) { StringBuffer strNodeTypes = new StringBuffer(); for (int i = 0; i < selectedNodeTypes.size(); i++) { if (strNodeTypes.length() == 0) strNodeTypes = new StringBuffer(selectedNodeTypes.get(i)); else strNodeTypes.append(",").append(selectedNodeTypes.get(i)); } uiWCSearchForm.getUIStringInput(UIContentSearchForm.DOC_TYPE).setValue(strNodeTypes.toString()); } /** * The listener interface for receiving saveAction events. * The class that is interested in processing a saveAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSaveActionListener</code> method. When * the saveAction event occurs, that object's appropriate * method is invoked. */ public static class SaveActionListener extends EventListener<UIContentNodeTypeSelector> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIContentNodeTypeSelector> event) throws Exception { UIContentNodeTypeSelector contentNodetypeSelector = event.getSource(); UIPopupWindow uiPopupWindow = contentNodetypeSelector.getParent(); UIContainer uiContainer = uiPopupWindow.getAncestorOfType(UIContainer.class); UIContentSelector contentSelector = (UIContentSelector) uiContainer.findFirstComponentOfType(UIContentSelector.class); List<String> selectedNodeTypes = new ArrayList<String>(); List<UICheckBoxInput> listCheckbox = new ArrayList<UICheckBoxInput>(); contentNodetypeSelector.findComponentOfType(listCheckbox, UICheckBoxInput.class); UIContentSearchForm contentSearchForm = contentSelector.getChild(UIContentSearchForm.class); String nodeTypesValue = contentSearchForm.getUIStringInput(UIContentSearchForm.DOC_TYPE).getValue(); contentNodetypeSelector.makeSelectedNode(nodeTypesValue, selectedNodeTypes, listCheckbox); contentNodetypeSelector.setNodeTypes(selectedNodeTypes, contentSearchForm); contentSelector.setSelectedTab(contentSearchForm.getId()); uiPopupWindow.setRendered(false); uiPopupWindow.setShow(false); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupWindow); event.getRequestContext().addUIComponentToUpdateByAjax(contentSearchForm); } } /** * Make selected node. * * @param nodeTypesValue the node types value * @param selectedNodeTypes the selected node types * @param listCheckbox the list checkbox * * @throws Exception the exception */ private void makeSelectedNode(String nodeTypesValue, List<String> selectedNodeTypes, List<UICheckBoxInput> listCheckbox) throws Exception { if(nodeTypesValue != null && nodeTypesValue.length() > 0) { String[] array = nodeTypesValue.split(","); for(int i = 0; i < array.length; i ++) { selectedNodeTypes.add(array[i].trim()); } } for(int i = 0; i < listCheckbox.size(); i ++) { if(listCheckbox.get(i).isChecked()) { if(!selectedNodeTypes.contains(listCheckbox.get(i).getName())) { selectedNodeTypes.add(listCheckbox.get(i).getName()); } } else if(selectedNodeTypes.contains(listCheckbox.get(i))) { selectedNodeTypes.remove(listCheckbox.get(i).getName()); } else { selectedNodeTypes.remove(listCheckbox.get(i).getName()); } } } /** * The listener interface for receiving cancelAction events. * The class that is interested in processing a cancelAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addCancelActionListener</code> method. When * the cancelAction event occurs, that object's appropriate * method is invoked. */ public static class CancelActionListener extends EventListener<UIContentNodeTypeSelector> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIContentNodeTypeSelector> event) throws Exception { UIContentNodeTypeSelector contentNodetypeSelector = event.getSource(); UIPopupWindow uiPopupWindow = contentNodetypeSelector.getParent(); uiPopupWindow.setRendered(false); uiPopupWindow.setShow(false); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupWindow); } } }
8,151
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentPropertySelector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/content/UIContentPropertySelector.java
package org.exoplatform.wcm.webui.selector.content; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Session; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeManager; import javax.jcr.nodetype.PropertyDefinition; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.Event.Phase; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormRadioBoxInput; import org.exoplatform.webui.form.UIFormSelectBox; /** * Author : TAN DUNG DANG * dzungdev@gmail.com * Jan 21, 2009 */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "system:/groovy/webui/form/UIForm.gtmpl", events = { @EventConfig(phase=Phase.DECODE, listeners = UIContentPropertySelector.CancelActionListener.class), @EventConfig(listeners = UIContentPropertySelector.AddActionListener.class), @EventConfig(listeners = UIContentPropertySelector.ChangeMetadataTypeActionListener.class) } ) public class UIContentPropertySelector extends UIForm{ public final static String WEB_CONTENT_METADATA_POPUP = "WebContentMetadataPopup"; final static public String METADATA_TYPE = "metadataType" ; final static public String PROPERTY_SELECT = "property_select" ; private String fieldName = null ; private List<SelectItemOption<String>> properties = new ArrayList<SelectItemOption<String>>() ; public UIContentPropertySelector() throws Exception { setActions(new String[] {"Add", "Cancel"}) ; } public void init() throws Exception { List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>(); NodeHierarchyCreator nodeHierarchyCreator = getApplicationComponent(NodeHierarchyCreator.class); UIFormSelectBox uiSelect = new UIFormSelectBox(METADATA_TYPE, METADATA_TYPE, options); uiSelect.setOnChange("ChangeMetadataType"); addUIFormInput(uiSelect); SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); RepositoryService repoService = getApplicationComponent(RepositoryService.class); ManageableRepository manRepository = repoService.getCurrentRepository(); //String workspaceName = manRepository.getConfiguration().getSystemWorkspaceName(); DMSConfiguration dmsConfiguration = getApplicationComponent(DMSConfiguration.class); String workspaceName = dmsConfiguration.getConfig().getSystemWorkspace(); Session session = sessionProvider.getSession(workspaceName, manRepository); String metadataPath = nodeHierarchyCreator.getJcrPath(BasePath.METADATA_PATH); Node homeNode = (Node) session.getItem(metadataPath); NodeIterator nodeIter = homeNode.getNodes(); Node meta = nodeIter.nextNode(); renderProperties(meta.getName()); options.add(new SelectItemOption<String>(meta.getName(), meta.getName())); while(nodeIter.hasNext()) { meta = nodeIter.nextNode(); options.add(new SelectItemOption<String>(meta.getName(), meta.getName())); } addUIFormInput(new UIFormRadioBoxInput(PROPERTY_SELECT, null, properties). setAlign(UIFormRadioBoxInput.VERTICAL_ALIGN)); } public void setFieldName(String fieldName) { this.fieldName = fieldName ; } public void renderProperties(String metadata) throws Exception { properties.clear() ; SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); RepositoryService repoService = getApplicationComponent(RepositoryService.class); ManageableRepository manRepository = repoService.getCurrentRepository(); String workspaceName = manRepository.getConfiguration().getSystemWorkspaceName(); Session session = sessionProvider.getSession(workspaceName, manRepository); NodeTypeManager ntManager = session.getWorkspace().getNodeTypeManager(); NodeType nt = ntManager.getNodeType(metadata); PropertyDefinition[] propertieDefs = nt.getPropertyDefinitions(); for(PropertyDefinition property : propertieDefs) { String name = property.getName(); if(!name.equals("exo:internalUse")) { this.properties.add(new SelectItemOption<String>(name,name)); } } } static public class CancelActionListener extends EventListener<UIContentPropertySelector> { public void execute(Event<UIContentPropertySelector> event) throws Exception { UIContentPropertySelector contentPropertySelector = event.getSource(); UIPopupWindow uiPopupWindow = contentPropertySelector.getParent(); uiPopupWindow.setRendered(false); uiPopupWindow.setShow(false); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupWindow); } } static public class AddActionListener extends EventListener<UIContentPropertySelector> { public void execute(Event<UIContentPropertySelector> event) throws Exception { UIContentPropertySelector contentPropertySelector = event.getSource(); String property = contentPropertySelector.<UIFormRadioBoxInput>getUIInput(PROPERTY_SELECT).getValue(); UIPopupWindow uiPopupWindow = contentPropertySelector.getParent(); UIContainer uiContainer = uiPopupWindow.getAncestorOfType(UIContainer.class); UIContentSelector contentSelector = (UIContentSelector) uiContainer.findFirstComponentOfType(UIContentSelector.class); UIContentSearchForm contentSearchForm = contentSelector.findFirstComponentOfType(UIContentSearchForm.class); contentSearchForm.getUIStringInput(contentPropertySelector.getFieldName()).setValue(property); uiPopupWindow.setRendered(false); uiPopupWindow.setShow(false); contentSelector.setSelectedTab(contentSearchForm.getId()); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupWindow); event.getRequestContext().addUIComponentToUpdateByAjax(contentSearchForm); } } static public class ChangeMetadataTypeActionListener extends EventListener<UIContentPropertySelector> { public void execute(Event<UIContentPropertySelector> event) throws Exception { UIContentPropertySelector contentPropertySelector = event.getSource(); contentPropertySelector.renderProperties(contentPropertySelector.getUIFormSelectBox(METADATA_TYPE).getValue()); event.getRequestContext().addUIComponentToUpdateByAjax(contentPropertySelector); } } public String getFieldName() { return fieldName; } }
7,349
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentBrowsePanelFolder.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/content/folder/UIContentBrowsePanelFolder.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.selector.content.folder; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.wcm.webui.selector.content.UIContentBrowsePanel; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.Lifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS. * * @author : Hoa.Pham hoa.pham@exoplatform.com Jun 23, 2008 */ @ComponentConfig( lifecycle = Lifecycle.class, template = "classpath:groovy/wcm/webui/selector/content/folder/UIContentBrowsePanel.gtmpl", events = { @EventConfig(listeners = UIContentBrowsePanel.ChangeContentTypeActionListener.class), @EventConfig(listeners = UIContentBrowsePanelFolder.SelectActionListener.class) } ) public class UIContentBrowsePanelFolder extends UIContentBrowsePanel{ private String _initPath = ""; private String _initDrive = ""; public void setInitPath(String initDrive, String initPath) { this._initPath = initPath; this._initDrive = initDrive; } public String getInitDrive() { return this._initDrive; } public String getInitPath() { return this._initPath; } public static class SelectActionListener extends EventListener<UIContentBrowsePanel> { public void execute(Event<UIContentBrowsePanel> event) throws Exception { UIContentBrowsePanel contentBrowsePanel = event.getSource(); String returnFieldName = contentBrowsePanel.getReturnFieldName(); ((UISelectable) (contentBrowsePanel.getSourceComponent())).doSelect(returnFieldName, event.getRequestContext() .getRequestParameter(OBJECTID)); } } }
2,684
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentSelectorFolder.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/content/folder/UIContentSelectorFolder.java
package org.exoplatform.wcm.webui.selector.content.folder; import org.exoplatform.wcm.webui.selector.content.UIContentSelector; import org.exoplatform.webui.config.annotation.ComponentConfig; /** * Author : TAN DUNG DANG * dzungdev@gmail.com * Jan 20, 2009 */ @ComponentConfig( template = "system:/groovy/webui/core/UITabPane_New.gtmpl" ) public class UIContentSelectorFolder extends UIContentSelector { public UIContentSelectorFolder() throws Exception { addChild(UIContentBrowsePanelFolder.class, null, null); setSelectedTab(1); } /** * Set the init path, when the popup window appears, it will go to the node * specified by this init path. * @param initPath * @throws Exception */ public void init(String initDrive, String initPath) throws Exception { this.getChild(UIContentBrowsePanelFolder.class).setInitPath(initDrive, initPath); } }
926
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentBrowsePanelMulti.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/content/multi/UIContentBrowsePanelMulti.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.selector.content.multi; import javax.jcr.ItemNotFoundException; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.selector.content.UIContentBrowsePanel; import org.exoplatform.wcm.webui.selector.content.UIContentSelector; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.Lifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * The Class UIContentBrowsePanelMulti. */ @ComponentConfig( lifecycle = Lifecycle.class, template = "classpath:groovy/wcm/webui/selector/content/multi/UIContentBrowsePanel.gtmpl", events = { @EventConfig(listeners = UIContentBrowsePanel.ChangeContentTypeActionListener.class), @EventConfig(listeners = UIContentBrowsePanelMulti.SelectActionListener.class), @EventConfig(listeners = UIContentBrowsePanelMulti.CloseActionListener.class), @EventConfig(listeners = UIContentBrowsePanelMulti.SaveTemporaryActionListener.class) } ) public class UIContentBrowsePanelMulti extends UIContentBrowsePanel { private static final Log LOG = ExoLogger.getLogger(UIContentBrowsePanelMulti.class.getName()); /** The item paths. */ private String itemPaths; private String itemTarget; /** i18n Delete Confirmation message */ private String deleteConfirmationMsg = "UIBrowserPanel.Confirm.Delete"; /** * Gets the item paths. * * @return the item paths */ public String getItemPaths() { return itemPaths; } private String _initPath = ""; private String _initDrive = ""; public void setInitPath(String initDrive, String initPath) { this._initPath = initPath; this._initDrive = initDrive; } public String getInitDrive() { return this._initDrive; } public String getInitPath() { return this._initPath; } /** * Sets the item paths. * * @param itemPaths the new item paths */ public void setItemPaths(String itemPaths) { this.itemPaths = itemPaths; setItemTargetPath(getTargetPath(itemPaths)); } public void setItemTargetPath(String _itemTarget) { this.itemTarget = _itemTarget; } public String getItemTargetPath(){ return this.itemTarget; } /** * * @param savedItems * @return */ protected String getTargetPath(String savedItems) { int i, n; LinkManager linkManager; String[] savedItemList =savedItems.split(";"); String savedItem; n = savedItemList.length; StringBuilder result = new StringBuilder(""); linkManager = WCMCoreUtils.getService(LinkManager.class); for (i = 0; i<n; i++) { savedItem = savedItemList[i]; String[] locations = (savedItem == null) ? null : savedItem.split(":"); Node node = (locations != null && locations.length >= 3) ? Utils.getViewableNodeByComposer( locations[0], locations[1], locations[2]) : null; savedItem = StringUtils.EMPTY; if (node != null){ try { savedItem = node.getPath(); if (linkManager.isLink(node)) { node = linkManager.getTarget(node); savedItem = node.getPath(); } } catch (ItemNotFoundException e){ savedItem = StringUtils.EMPTY; } catch (RepositoryException e){ savedItem = StringUtils.EMPTY; } } result.append(savedItem).append(";"); } return result.toString(); } /** * The listener interface for receiving selectAction events. * The class that is interested in processing a selectAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSelectActionListener</code> method. When * the selectAction event occurs, that object's appropriate * method is invoked. */ public static class SelectActionListener extends EventListener<UIContentBrowsePanelMulti> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIContentBrowsePanelMulti> event) throws Exception { UIContentBrowsePanelMulti contentBrowsePanelMulti = event.getSource(); String returnFieldName = contentBrowsePanelMulti.getReturnFieldName(); ((UISelectable)(contentBrowsePanelMulti.getSourceComponent())).doSelect(returnFieldName, contentBrowsePanelMulti.getItemPaths()); } } /** * The listener interface for receiving SaveTemporaryAction events. * The class that is interested in processing a SaveTemporaryAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>SaveTemporaryActionListener</code> method. When * the selectAction event occurs, that object's appropriate * method is invoked. * * @see SaveTemporaryActionListener */ public static class SaveTemporaryActionListener extends EventListener<UIContentBrowsePanelMulti> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIContentBrowsePanelMulti> event) throws Exception { UIContentBrowsePanelMulti contentBrowsePanelMulti = event.getSource(); Node node = null; String itemPathtemp = ""; String operationType = event.getRequestContext().getRequestParameter("oper"); String dPath = event.getRequestContext().getRequestParameter("path"); String iDriver = event.getRequestContext().getRequestParameter("driverName"); String iPath = event.getRequestContext().getRequestParameter("currentPath"); String tempIPath = iPath; String[] locations = (iPath == null) ? null : iPath.split(":"); if (operationType.equals("clean") && contentBrowsePanelMulti.getItemPaths() != null) { contentBrowsePanelMulti.setItemPaths(""); return; } if (iDriver != null && iDriver.length() > 0) { if (locations != null && locations.length > 2) node = Utils.getViewableNodeByComposer(Text.escapeIllegalJcrChars(locations[0]), Text.escapeIllegalJcrChars(locations[1]), Text.escapeIllegalJcrChars(locations[2]), WCMComposer.BASE_VERSION); if (node != null) { iPath = fixPath(iDriver, node.getPath(), contentBrowsePanelMulti); contentBrowsePanelMulti.setInitPath(iDriver, iPath); } else { contentBrowsePanelMulti.setInitPath(iDriver, iPath); } } else contentBrowsePanelMulti.setInitPath("", ""); if (operationType.equals("add") && contentBrowsePanelMulti.getItemPaths() != null) { itemPathtemp = contentBrowsePanelMulti.getItemPaths().concat(tempIPath).concat(";"); contentBrowsePanelMulti.setItemPaths(itemPathtemp); } else if (operationType.equals("delete") && contentBrowsePanelMulti.getItemPaths() != null) { itemPathtemp = contentBrowsePanelMulti.getItemPaths(); itemPathtemp = StringUtils.remove(itemPathtemp, dPath.concat(";")); contentBrowsePanelMulti.setItemPaths(itemPathtemp); } else contentBrowsePanelMulti.setItemPaths(tempIPath.concat(";")); UIContentSelector contentSelector = contentBrowsePanelMulti.getAncestorOfType(UIContentSelector.class); contentSelector.setSelectedTab(contentBrowsePanelMulti.getId()); } private String fixPath(String driveName, String path, UIContentBrowsePanelMulti uiBrowser) throws Exception { if (path == null || path.length() == 0) return ""; path = Text.escapeIllegalJcrChars(path); ManageDriveService managerDriveService = uiBrowser.getApplicationComponent(ManageDriveService.class); DriveData driveData = managerDriveService.getDriveByName(driveName); if (!path.startsWith(driveData.getHomePath())) return ""; if ("/".equals(driveData.getHomePath())) return path; return path.substring(driveData.getHomePath().length()); } } public String getDeleteConfirmationMsg() { return org.exoplatform.ecm.webui.utils.Utils.getResourceBundle(org.exoplatform.ecm.webui.utils.Utils.LOCALE_WEBUI_DMS, deleteConfirmationMsg, UIContentBrowsePanelMulti.class.getClassLoader()); } public String getLocaleMsg(String key) { return org.exoplatform.ecm.webui.utils.Utils.getResourceBundle(org.exoplatform.ecm.webui.utils.Utils.LOCALE_WEBUI_DMS, key, UIContentBrowsePanelMulti.class.getClassLoader()); } /** * The listener interface for receiving closeAction events. * The class that is interested in processing a closeAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addCloseActionListener</code> method. When * the closeAction event occurs, that object's appropriate * method is invoked. */ public static class CloseActionListener extends EventListener<UIContentBrowsePanelMulti> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIContentBrowsePanelMulti> event) throws Exception { UIContentBrowsePanelMulti contentBrowsePanelMulti = event.getSource(); ((UISelectable)(contentBrowsePanelMulti.getSourceComponent())).doSelect(null, null); } } }
11,604
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentSelectorMulti.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/content/multi/UIContentSelectorMulti.java
package org.exoplatform.wcm.webui.selector.content.multi; import org.exoplatform.wcm.webui.selector.content.UIContentSearchForm; import org.exoplatform.wcm.webui.selector.content.UIContentSearchResult; import org.exoplatform.wcm.webui.selector.content.UIContentSelector; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.ComponentConfigs; import org.exoplatform.webui.config.annotation.EventConfig; /** * Author : TAN DUNG DANG * dzungdev@gmail.com * Jan 20, 2009 */ @ComponentConfigs ({ @ComponentConfig( template = "system:/groovy/webui/core/UITabPane_New.gtmpl" ), @ComponentConfig( type = UIContentSearchResult.class, template = "classpath:groovy/wcm/webui/selector/content/multi/UIContentSearchResult.gtmpl", events = { @EventConfig(listeners = UIContentSearchResult.ViewActionListener.class) } ) }) public class UIContentSelectorMulti extends UIContentSelector { /** * Instantiates a new uI content selector multi. * * @throws Exception the exception */ public UIContentSelectorMulti() throws Exception { addChild(UIContentBrowsePanelMulti.class, null, null); addChild(UIContentSearchForm.class,null,null); addChild(UIContentSearchResult.class,null,null); setSelectedTab(1); } /** * Inits the. * * @throws Exception the exception */ public void init() throws Exception { getChild(UIContentSearchForm.class).init(); } }
1,537
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentSelectorOne.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/content/one/UIContentSelectorOne.java
package org.exoplatform.wcm.webui.selector.content.one; import org.exoplatform.wcm.webui.selector.content.UIContentSearchForm; import org.exoplatform.wcm.webui.selector.content.UIContentSearchResult; import org.exoplatform.wcm.webui.selector.content.UIContentSelector; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.ComponentConfigs; import org.exoplatform.webui.config.annotation.EventConfig; /** * Author : TAN DUNG DANG * dzungdev@gmail.com * Jan 20, 2009 */ @ComponentConfigs ({ @ComponentConfig( template = "system:/groovy/webui/core/UITabPane_New.gtmpl" ), @ComponentConfig( type = UIContentSearchResult.class, template = "classpath:groovy/wcm/webui/selector/content/one/UIContentSearchResult.gtmpl", events = { @EventConfig(listeners = UIContentSearchResult.SelectActionListener.class), @EventConfig(listeners = UIContentSearchResult.ViewActionListener.class) } ) }) public class UIContentSelectorOne extends UIContentSelector { /** * Instantiates a new uI content selector one. * * @throws Exception the exception */ public UIContentSelectorOne() throws Exception { addChild(UIContentBrowsePanelOne.class, null, null); addChild(UIContentSearchForm.class,null,null); addChild(UIContentSearchResult.class,null,null); setSelectedTab(1); } /** * Inits the. * * @throws Exception the exception */ public void init() throws Exception { getChild(UIContentSearchForm.class).init(); } /** * Set the init path, when the popup window appears, it will go to the node * specified by this init path. * @param initPath * @throws Exception */ public void init(String initDrive, String initPath) throws Exception { getChild(UIContentBrowsePanelOne.class).setInitPath(initDrive, initPath); this.init(); } }
1,960
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIContentBrowsePanelOne.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/selector/content/one/UIContentBrowsePanelOne.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.selector.content.one; import javax.jcr.Node; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.selector.content.UIContentBrowsePanel; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.Lifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS. * * @author : Hoa.Pham hoa.pham@exoplatform.com Jun 23, 2008 */ @ComponentConfig( lifecycle = Lifecycle.class, template = "classpath:groovy/wcm/webui/selector/content/one/UIContentBrowsePanel.gtmpl", events = { @EventConfig(listeners = UIContentBrowsePanel.ChangeContentTypeActionListener.class), @EventConfig(listeners = UIContentBrowsePanelOne.SelectActionListener.class) } ) public class UIContentBrowsePanelOne extends UIContentBrowsePanel{ private String _initPath = ""; private String _initDrive = ""; public void setInitPath(String initDrive, String initPath) { this._initPath = initPath; this._initDrive = initDrive; } public String getInitDrive() { return this._initDrive; } public String getInitPath() { return this._initPath; } public static class SelectActionListener extends EventListener<UIContentBrowsePanel> { public void execute(Event<UIContentBrowsePanel> event) throws Exception { UIContentBrowsePanel contentBrowsePanel = event.getSource(); String returnFieldName = contentBrowsePanel.getReturnFieldName(); String itemPath = event.getRequestContext().getRequestParameter(OBJECTID); Node node = NodeLocation.getNodeByExpression(Text.escapeIllegalJcrChars(itemPath.substring(itemPath.indexOf(':') + 1))); Node realNode = node; if (node.isNodeType("exo:symlink")) { String uuid = node.getProperty("exo:uuid").getString(); realNode = node.getSession().getNodeByUUID(uuid); } if(!realNode.isCheckedOut()){ Utils.createPopupMessage(contentBrowsePanel, "UIContentBrowsePanelOne.msg.node-checkout", null, ApplicationMessage.WARNING); return; } ((UISelectable) (contentBrowsePanel.getSourceComponent())).doSelect(returnFieldName, event.getRequestContext() .getRequestParameter(OBJECTID)); } } }
3,608
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIFormInputSetWithNoLabel.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/form/UIFormInputSetWithNoLabel.java
/* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.form; import java.io.Writer; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.form.UIFormInputSet; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Mar 23, 2013 */ public class UIFormInputSetWithNoLabel extends UIFormInputSet { public UIFormInputSetWithNoLabel(String name) throws Exception { super(name); } @Override public void processRender(WebuiRequestContext context) throws Exception { if (getComponentConfig() != null) { super.processRender(context); return; } Writer w = context.getWriter(); w.write("<div class=\"UIFormInputSet\">"); w.write("<div class=\"form-horizontal\">"); for (UIComponent inputEntry : getChildren()) { if (inputEntry.isRendered()) { w.write("<div class=\"control-group\">"); w.write("<div class=\"controls-full\">"); renderUIComponent(inputEntry); w.write("</div>"); w.write("</div>"); } } w.write("</div>"); w.write("</div>"); } }
1,911
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIPopupWindow.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/core/UIPopupWindow.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.core; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS * Author : Phan Le Thanh Chuong * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Oct 29, 2009 */ @ComponentConfig( template = "classpath:groovy/wcm/webui/core/UIPopupWindow.gtmpl", events = @EventConfig(listeners = UIPopupWindow.CloseActionListener.class, name = "ClosePopup") ) public class UIPopupWindow extends org.exoplatform.webui.core.UIPopupWindow { private int top_ = -1; private int left_ = -1; private boolean isMiddle = false; /** * @return the isMiddle */ public boolean isMiddle() { return isMiddle; } /** * @param isMiddle the isMiddle to set */ public void setMiddle(boolean isMiddle) { this.isMiddle = isMiddle; } public int getWindowTop() { return top_; } public int getWindowLeft() { return left_; } public void setCoordindate(int top, int left) { top_ = top; left_ = left; } public static class CloseActionListener extends EventListener<UIPopupWindow> { public void execute(Event<UIPopupWindow> event) throws Exception { UIPopupWindow popupWindow = event.getSource(); UIPopupContainer popupContainer = popupWindow.getAncestorOfType(UIPopupContainer.class); popupContainer.removeChildById(popupWindow.getId()); event.getRequestContext().addUIComponentToUpdateByAjax(popupContainer); } } }
2,411
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FloatNumberValidator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/validator/FloatNumberValidator.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.validator; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormInput; import org.exoplatform.webui.form.validator.Validator; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.exception.MessageException; import org.exoplatform.webui.application.WebuiRequestContext; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Jul 27, 2011 */ public class FloatNumberValidator implements Validator{ @SuppressWarnings("unchecked") public void validate(UIFormInput uiInput) throws Exception { if (uiInput.getValue()==null || ((String)uiInput.getValue()).length()==0) return; WebuiRequestContext rc = WebuiRequestContext.getCurrentInstance(); UIComponent uiComponent = (UIComponent) uiInput ; UIForm uiForm = uiComponent.getAncestorOfType(UIForm.class) ; String label; try{ label = uiForm.getLabel(uiInput.getName()); } catch(Exception e) { label = uiInput.getName(); } label = label.trim(); String s = (String)uiInput.getValue(); try { Float.parseFloat(s); } catch (NumberFormatException ex) { Object[] args = {label}; throw new MessageException(new ApplicationMessage("FloatNumberValidator.msg.Invalid-number", args, ApplicationMessage.WARNING)); } } }
2,194
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
MandatoryValidator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/validator/MandatoryValidator.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.validator; import java.util.MissingResourceException; import java.util.ResourceBundle; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.exception.MessageException; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormInput; /** * Created by The eXo Platform SAS * Author : Phan Le Thanh Chuong * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Modified: - Extends from org.exoplatform.webui.form.validator.MandatoryValidator * Use template name to generate a label for input instead of use form name * - Only use for Form Generator feature * Nov 11, 2009 */ public class MandatoryValidator extends org.exoplatform.webui.form.validator.MandatoryValidator { @SuppressWarnings("unchecked") public void validate(UIFormInput uiInput) throws Exception { if((uiInput.getValue() != null) && ((String)uiInput.getValue()).trim().length() > 0) { return ; } UIComponent uiComponent = (UIComponent) uiInput ; UIForm uiForm = uiComponent.getAncestorOfType(UIForm.class) ; String templatePath = uiForm.getTemplate(); String nodetypeName = ""; String[] temps = templatePath.split("/"); for (String temp : temps){ if (temp.contains("_fg_n")) { nodetypeName = temp; break; } } TemplateService templateService = uiForm.getApplicationComponent(TemplateService.class); String nodetypeLabel = templateService.getTemplateLabel(nodetypeName).trim(); ResourceBundle res = Util.getPortalRequestContext().getApplicationResourceBundle(); String label = ""; try { label = res.getString(nodetypeLabel + ".label." + uiInput.getName()); } catch (MissingResourceException e) { label = uiInput.getName(); } Object[] args = {label, uiInput.getBindingField() } ; throw new MessageException(new ApplicationMessage("EmptyFieldValidator.msg.empty-input", args, ApplicationMessage.WARNING)) ; } }
2,905
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ZeroNumberValidator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/validator/ZeroNumberValidator.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.validator; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.exception.MessageException; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormInput; import org.exoplatform.webui.form.validator.Validator; /** * Created by The eXo Platform SAS * Author : Phan Le Thanh Chuong * chuong_phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Oct 15, 2009 */ public class ZeroNumberValidator implements Validator { @SuppressWarnings("unchecked") public void validate(UIFormInput uiInput) throws Exception { if (uiInput.getValue()==null || ((String)uiInput.getValue()).length()==0) return; UIComponent uiComponent = (UIComponent) uiInput ; UIForm uiForm = uiComponent.getAncestorOfType(UIForm.class) ; String label; try{ label = uiForm.getLabel(uiInput.getName()); } catch(Exception e) { label = uiInput.getName(); } label = label.trim(); if(label.charAt(label.length() - 1) == ':') label = label.substring(0, label.length() - 1); if (((String)uiInput.getValue()).charAt(0) == '0') { Object[] args = { label, uiInput.getBindingField() }; throw new MessageException(new ApplicationMessage("ZeroValidator.msg.Invalid-number", args)) ; } } }
2,079
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FckMandatoryValidator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/wcm/webui/validator/FckMandatoryValidator.java
/* * Copyright (C) 2003-2010 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.validator; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.exception.MessageException; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormInput; /** * Created by The eXo Platform SAS * Author : Dung Khuong * dung.khuong@exoplatform.com * Jul 6, 2010 */ @SuppressWarnings("serial") public class FckMandatoryValidator extends org.exoplatform.webui.form.validator.MandatoryValidator { @SuppressWarnings("unchecked") public void validate(UIFormInput uiInput) throws Exception { if ((uiInput.getValue() != null) && (((String) uiInput.getValue()).trim().length() > 0) && (!uiInput.getValue().toString().trim().equals("<br />"))) { return; } else { UIComponent uiComponent = (UIComponent)uiInput; UIForm uiForm = uiComponent.getAncestorOfType(UIForm.class); String label; try { label = uiForm.getId() + ".label." + uiInput.getName(); } catch (Exception e) { label = uiInput.getName(); } label = label.trim(); Object[] args = {label}; throw new MessageException(new ApplicationMessage("EmptyFieldValidator.msg.empty-input", args, ApplicationMessage.WARNING)); } } }
2,231
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
JCRResourceResolver.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/resolver/JCRResourceResolver.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.resolver; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.Session; import org.exoplatform.resolver.ResourceKey; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Created by The eXo Platform SARL Author : Dang Van Minh * minh.dang@exoplatform.com May 8, 2008 3:07:02 PM */ public class JCRResourceResolver extends ResourceResolver { protected String repository ; protected String workspace ; protected String propertyName ; /** The log. */ private static final Log LOG = ExoLogger.getLogger(JCRResourceResolver.class.getName()); private TemplateService templateService; /** * Instantiates a new jCR resource resolver to load template that stored as a * property of node in jcr * * @param workspace the workspace */ public JCRResourceResolver(String workspace) { this.workspace = workspace; templateService = WCMCoreUtils.getService(TemplateService.class); } /* (non-Javadoc) * @see org.exoplatform.resolver.ResourceResolver#getResource(java.lang.String) */ public URL getResource(String url) throws Exception { throw new Exception("This method is not supported") ; } /** * @param url URL must be like jcr:path with path is node path * @see org.exoplatform.resolver.ResourceResolver#getInputStream(java.lang.String) */ public InputStream getInputStream(String url) throws Exception { SessionProvider provider = WCMCoreUtils.getSystemSessionProvider(); Session session = provider.getSession(workspace, WCMCoreUtils.getRepository()); ByteArrayInputStream inputStream = null; try { Node template = (Node)session.getItem(removeScheme(url)); inputStream = new ByteArrayInputStream(templateService.getTemplate(template).getBytes()); } catch(Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected problem happen when try to process with url"); } } finally { session.logout(); } return inputStream; } /* (non-Javadoc) * @see org.exoplatform.resolver.ResourceResolver#getResources(java.lang.String) */ public List<URL> getResources(String url) throws Exception { throw new Exception("This method is not supported") ; } /* (non-Javadoc) * @see org.exoplatform.resolver.ResourceResolver#getInputStreams(java.lang.String) */ public List<InputStream> getInputStreams(String url) throws Exception { ArrayList<InputStream> inputStreams = new ArrayList<InputStream>(1) ; inputStreams.add(getInputStream(url)) ; return inputStreams ; } /* (non-Javadoc) * @see org.exoplatform.resolver.ResourceResolver#isModified(java.lang.String, long) */ public boolean isModified(String url, long lastAccess) { return false ; } /* (non-Javadoc) * @see org.exoplatform.resolver.ResourceResolver#createResourceId(java.lang.String) */ public String createResourceId(String url) { return url ; } @Override public ResourceKey createResourceKey(String url) { return new ResourceKey(url.hashCode(), url); } /* (non-Javadoc) * @see org.exoplatform.resolver.ResourceResolver#getResourceScheme() */ public String getResourceScheme() { return "jcr:" ; } }
4,433
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
NTFileResourceResolver.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/resolver/NTFileResourceResolver.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.resolver; import java.io.InputStream; import javax.jcr.Node; import javax.jcr.Session; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Created by The eXo Platform SAS. * * @author : Hoa.Pham hoa.pham@exoplatform.com Jun 23, 2008 */ public class NTFileResourceResolver extends JCRResourceResolver { /** * Instantiates a new nT file resource resolver. * * @param workspace the workspace */ public NTFileResourceResolver(String workspace) { super(workspace); } /** * @param url URL must be like: jcr:uuid with uuid is node uiid of the file * @see org.exoplatform.resolver.ResourceResolver#getInputStream(java.lang.String) */ public InputStream getInputStream(String url) throws Exception { SessionProvider provider = WCMCoreUtils.getSystemSessionProvider(); Session session = provider.getSession(workspace, WCMCoreUtils.getRepository()); String fileUUID = removeScheme(url); Node node = session.getNodeByUUID(fileUUID); return node.getNode("jcr:content").getProperty("jcr:data").getStream(); } }
1,927
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
StringResourceResolver.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/resolver/StringResourceResolver.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.resolver; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.exoplatform.resolver.ResourceResolver; /** * Created by The eXo Platform SAS * @author : Hoa.Pham * hoa.pham@exoplatform.com * May 6, 2008 */ public class StringResourceResolver extends ResourceResolver { private String templateData ; public StringResourceResolver(String templateData) { this.templateData = templateData ; } public InputStream getInputStream(String template) throws Exception { return new ByteArrayInputStream(templateData.getBytes()); } public List<InputStream> getInputStreams(String template) throws Exception { List<InputStream> list = new ArrayList<InputStream>(); list.add(getInputStream(template)) ; return list; } @SuppressWarnings("unused") public URL getResource(String arg0) throws Exception { return null; } @SuppressWarnings("unused") public String getResourceScheme() { return null; } @SuppressWarnings("unused") public List<URL> getResources(String arg0) throws Exception { return null; } @SuppressWarnings("unused") public boolean isModified(String arg0, long arg1) { return false; } }
2,050
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UINodeTree.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/tree/UINodeTree.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.tree; import java.util.MissingResourceException; import javax.jcr.Node; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.jcr.util.Text; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIRightClickPopupMenu; import org.exoplatform.webui.core.UITree; /** * Created by The eXo Platform SAS * @author : Hoa.Pham * hoa.pham@exoplatform.com * Jun 23, 2008 */ @ComponentConfig( template = "system:/groovy/webui/core/UITree.gtmpl" , events = @EventConfig(listeners = UITree.ChangeNodeActionListener.class) ) /** * This class extend <code>org.exoplatform.webui.core.UITree</code> * to render node tree for <code>javax.jcr.Node</code> * * */ public class UINodeTree extends UITree { /** The log. */ private static final Log LOG = ExoLogger.getLogger(UINodeTree.class.getName()); private String rootPath = ""; private boolean isTaxonomyLocalize; public boolean isTaxonomyLocalize() { return isTaxonomyLocalize; } public void setTaxonomyLocalize(boolean isTaxonomyLocalize) { this.isTaxonomyLocalize = isTaxonomyLocalize; } public String getRootPath() { return rootPath; } public void setRootPath(String rootPath) { this.rootPath = rootPath; } /* * render nodetype icon for node in tree * @see org.exoplatform.webui.core.UITree#renderNode(java.lang.Object) */ public String renderNode(Object obj) throws Exception { Node node = (Node) obj; String nodeTypeIcon = Utils.getNodeTypeIcon(node,"uiIconEcms"); String nodeIcon = this.getColapseIcon(); String iconGroup = this.getIcon(); String note = "" ; if(isSelected(obj)) { nodeIcon = getExpandIcon(); iconGroup = getSelectedIcon(); note = " nodeSelected" ; } String beanIconField = getBeanIconField(); if(beanIconField != null && beanIconField.length() > 0) { if(getFieldValue(obj, beanIconField) != null) iconGroup = (String)getFieldValue(obj, beanIconField); } String objId = Utils.formatNodeName(String.valueOf(getId(obj))); String actionLink = event("ChangeNode", objId); StringBuilder builder = new StringBuilder(); if(nodeIcon.equals(getColapseIcon())) { builder.append(" <a class=\"") .append(nodeIcon) .append(" ") .append(nodeTypeIcon) .append("\" href=\"javascript:void(0);\" onclick=\"") .append(actionLink) .append("\">"); } else { builder.append(" <a class=\"") .append(nodeIcon) .append(" ") .append(nodeTypeIcon) .append("\" onclick=\"eXo.portal.UIPortalControl.collapseTree(this)") .append("\">"); } UIRightClickPopupMenu popupMenu = getUiPopupMenu(); String beanFieldValue = getDisplayFieldValue(obj); beanFieldValue = Text.unescapeIllegalJcrChars(Utils.getTitle(node)); String className="uiIconFileMini uiIconLightGray"; boolean flgSymlink = false; if (Utils.isSymLink(node)) { flgSymlink = true; className = "uiIconNodeLink"; } if(popupMenu == null) { builder.append(" <i class=\"").append(className).append(" ").append(iconGroup).append(" ").append(nodeTypeIcon) .append(note).append("\"").append(" title=\"").append(beanFieldValue) .append("\"").append(">"); if (flgSymlink) { builder.append(" <i class=\"linkSmall\">") .append("</i>").append(beanFieldValue); } builder.append("</i>"); builder.append(beanFieldValue); } else { builder.append(" <i class=\"").append(className).append(" ").append(iconGroup).append(" ").append(nodeTypeIcon) .append(note).append("\" ").append(popupMenu.getJSOnclickShowPopup(objId, null)).append( " title=\"").append(beanFieldValue).append("\"").append(">"); if (flgSymlink) { builder.append(" <i class=\"linkSmall\">") .append(beanFieldValue) .append("</i>"); } builder.append("</i>"); builder.append(beanFieldValue); } builder.append(" </a>"); return builder.toString(); } private String getDisplayFieldValue(Object bean) throws Exception{ if (isTaxonomyLocalize && Node.class.isInstance(bean)) { String path = ((Node)bean).getPath(); String taxonomyTreeName = rootPath.substring(rootPath.lastIndexOf("/") + 1); try { String display = taxonomyTreeName.concat(path.replace(rootPath, "")).replaceAll("/", "."); return Utils.getResourceBundle(("eXoTaxonomies.").concat(display).concat(".label")); } catch (MissingResourceException me) { if (LOG.isWarnEnabled()) { LOG.warn(me.getMessage()); } } } return String.valueOf(getFieldValue(bean, getBeanLabelField())); } public boolean isSelected(Object obj) throws Exception { Node selectedNode = this.getSelected(); Node node = (Node) obj; if(selectedNode == null) return false; return selectedNode.getPath().equals(node.getPath()); } }
6,200
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UITreeTaxonomyBuilder.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/tree/UITreeTaxonomyBuilder.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.tree; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.nodetype.NodeType; import org.exoplatform.ecm.webui.comparator.NodeTitleComparator; import org.exoplatform.ecm.webui.tree.selectone.UIOneTaxonomySelector; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.container.UIContainer; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIBreadcumbs; import org.exoplatform.webui.core.UITree; import org.exoplatform.webui.core.UIBreadcumbs.LocalPath; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS. * * @author : Hoa.Pham hoa.pham@exoplatform.com Jun 23, 2008 */ @ComponentConfig( events = @EventConfig(listeners = UITreeTaxonomyBuilder.ChangeNodeActionListener.class) ) public class UITreeTaxonomyBuilder extends UIContainer { private boolean allowPublish = false; private PublicationService publicationService_ = null; private List<String> templates_ = null; private String[] acceptedNodeTypes = {}; private String[] defaultExceptedNodeTypes = {}; /** The root tree node. */ protected NodeLocation rootTreeNode; /** The current node. */ protected NodeLocation currentNode; public boolean isAllowPublish() { return allowPublish; } public void setAllowPublish(boolean allowPublish, PublicationService publicationService, List<String> templates) { this.allowPublish = allowPublish; publicationService_ = publicationService; templates_ = templates; } /** * Instantiates a new uI node tree builder. * * @throws Exception the exception */ public UITreeTaxonomyBuilder() throws Exception { UITree tree = addChild(UINodeTree.class, null, "TaxonomyTreeBuilder") ; tree.setBeanLabelField("name") ; tree.setBeanIdField("path") ; } /** * Gets the root tree node. * * @return the root tree node */ public Node getRootTreeNode() { return NodeLocation.getNodeByLocation(rootTreeNode); } /** * Sets the root tree node. * * @param node the new root tree node * @throws Exception the exception */ public final void setRootTreeNode(Node node) throws Exception { this.rootTreeNode = NodeLocation.getNodeLocationByNode(node); this.currentNode = NodeLocation.getNodeLocationByNode(node); UINodeTree uiNodeTree = getChild(UINodeTree.class); uiNodeTree.setRootPath(node.getPath()); uiNodeTree.setTaxonomyLocalize(true); broadcastOnChange(node,null); } /** * Gets the current node. * * @return the current node */ public Node getCurrentNode() { return NodeLocation.getNodeByLocation(currentNode); } /** * Sets the current node. * * @param currentNode the new current node */ public void setCurrentNode(Node currentNode) { this.currentNode = NodeLocation.getNodeLocationByNode(currentNode); } /** * Gets the accepted node types. * * @return the accepted node types */ public String[] getAcceptedNodeTypes() { return acceptedNodeTypes; } /** * Sets the accepted node types. * * @param acceptedNodeTypes the new accepted node types */ public void setAcceptedNodeTypes(String[] acceptedNodeTypes) { this.acceptedNodeTypes = acceptedNodeTypes; } /** * Gets the default excepted node types. * * @return the default excepted node types */ public String[] getDefaultExceptedNodeTypes() { return defaultExceptedNodeTypes; } /** * Sets the default excepted node types. * * @param defaultExceptedNodeTypes the new excepted node types */ public void setDefaultExceptedNodeTypes(String[] defaultExceptedNodeTypes) { this.defaultExceptedNodeTypes = defaultExceptedNodeTypes; } public boolean isExceptedNodeType(Node node) throws RepositoryException { if(defaultExceptedNodeTypes.length > 0) { for(String nodeType: defaultExceptedNodeTypes) { if(node.isNodeType(nodeType)) return true; } } return false; } public void buildTree() throws Exception { NodeIterator sibbling = null ; NodeIterator children = null ; UINodeTree tree = getChild(UINodeTree.class); Node selectedNode = getNodeByPathBreadcumbs(); if ((tree != null) && (selectedNode != null)) { tree.setSelected(selectedNode); if (Utils.getNodeSymLink(selectedNode).getDepth() > 0) { if (!selectedNode.getPath().equals(rootTreeNode.getPath())) tree.setParentSelected(selectedNode.getParent()) ; sibbling = Utils.getNodeSymLink(selectedNode).getNodes() ; children = Utils.getNodeSymLink(selectedNode).getNodes() ; } else { tree.setParentSelected(selectedNode) ; sibbling = Utils.getNodeSymLink(selectedNode).getNodes() ; children = null; } if (sibbling != null) { tree.setSibbling(filfer(sibbling)); } if (children != null) { tree.setChildren(filfer(children)); } } } private Node getNodeByPathBreadcumbs() throws PathNotFoundException, RepositoryException { UIOneTaxonomySelector uiOneTaxonomySelector = (UIOneTaxonomySelector) getParent(); UIBreadcumbs uiBreadcumbs = uiOneTaxonomySelector.getChildById("BreadcumbOneTaxonomy"); List<LocalPath> listLocalPath = uiBreadcumbs.getPath(); StringBuilder buffer = new StringBuilder(1024); String rootPath = ""; if (rootTreeNode != null) rootPath = rootTreeNode.getPath(); for (LocalPath iterLocalPath : listLocalPath) { buffer.append("/").append(iterLocalPath.getId()); } String path = buffer.toString(); if (rootPath.endsWith(path)) rootPath = rootPath.substring(0, rootPath.length() - path.length()); path = path.replaceAll("/+", "/"); if (!path.startsWith(rootPath)) { StringBuffer sb = new StringBuffer(); sb.append(rootPath).append(path); path = sb.toString(); } if (path.endsWith("/")) path = path.substring(0, path.length() - 1); if (path.length() == 0) path = "/"; if (buffer.length() == 0) return NodeLocation.getNodeByLocation(currentNode); NodeFinder nodeFinder_ = getApplicationComponent(NodeFinder.class); return (Node)nodeFinder_.getItem(uiOneTaxonomySelector.getWorkspaceName(), path); } private void addNodePublish(List<Node> listNode, Node node, PublicationService publicationService) throws Exception { if (isAllowPublish()) { NodeType nt = node.getPrimaryNodeType(); if (templates_.contains(nt.getName())) { Node nodecheck = publicationService.getNodePublish(node, null); if (nodecheck != null) { listNode.add(nodecheck); } } else { listNode.add(node); } } else { listNode.add(node); } } private List<Node> filfer(final NodeIterator iterator) throws Exception{ List<Node> list = new ArrayList<Node>(); if (acceptedNodeTypes.length > 0) { for(;iterator.hasNext();) { Node sibbling = iterator.nextNode(); if(sibbling.isNodeType("exo:hiddenable")) continue; for(String nodetype: acceptedNodeTypes) { if(sibbling.isNodeType(nodetype)) { list.add(sibbling); break; } } } Collections.sort(list, new NodeTitleComparator(NodeTitleComparator.ASCENDING_ORDER)); List<Node> listNodeCheck = new ArrayList<Node>(); for (Node node : list) { addNodePublish(listNodeCheck, node, publicationService_); } return listNodeCheck; } for(;iterator.hasNext();) { Node sibbling = iterator.nextNode(); if(sibbling.isNodeType("exo:hiddenable") || isExceptedNodeType(sibbling)) continue; list.add(sibbling); } Collections.sort(list, new NodeTitleComparator(NodeTitleComparator.ASCENDING_ORDER)); List<Node> listNodeCheck = new ArrayList<Node>(); for (Node node : list) addNodePublish(listNodeCheck, node, publicationService_); return listNodeCheck; } /* (non-Javadoc) * @see org.exoplatform.webui.core.UIComponent#processRender(org.exoplatform.webui.application.WebuiRequestContext) */ public void processRender(WebuiRequestContext context) throws Exception { Writer writer = context.getWriter() ; writer.write("<div class=\"explorerTree\">") ; buildTree() ; super.renderChildren() ; writer.write("</div>") ; } /** * When a node is change in tree. This method will be rerender the children and sibbling nodes of * current node and broadcast change node event to other uicomponent * * @param path the path * @param context the request context * @throws Exception the exception */ public void changeNode(String path, Object context) throws Exception { if (path == null) return; NodeFinder nodeFinder_ = getApplicationComponent(NodeFinder.class); String rootPath = rootTreeNode.getPath(); if(rootPath.equals(path) || !path.startsWith(rootPath)) { currentNode = rootTreeNode; }else { if (path.startsWith(rootPath)) path = path.substring(rootPath.length()); if (path.startsWith("/")) path = path.substring(1); currentNode = NodeLocation.getNodeLocationByNode(nodeFinder_.getNode( NodeLocation.getNodeByLocation(rootTreeNode), path)); } broadcastOnChange(NodeLocation.getNodeByLocation(currentNode),context); } /** * Broadcast on change. * * @param node the node * @param context the request context * @throws Exception the exception */ public void broadcastOnChange(Node node, Object context) throws Exception { UIBaseNodeTreeSelector nodeTreeSelector = getAncestorOfType(UIBaseNodeTreeSelector.class); nodeTreeSelector.onChange(node, context); } /** * The listener interface for receiving changeNodeAction events. The class * that is interested in processing a changeNodeAction event implements this * interface, and the object created with that class is registered with a * component using the component's * <code>addChangeNodeActionListener</code> method. When * the changeNodeAction event occurs, that object's appropriate * method is invoked. */ static public class ChangeNodeActionListener extends EventListener<UITree> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UITree> event) throws Exception { UITreeTaxonomyBuilder builder = event.getSource().getParent(); String uri = event.getRequestContext().getRequestParameter(OBJECTID); builder.changeNode(uri,event.getRequestContext()); UIBaseNodeTreeSelector nodeTreeSelector = builder.getAncestorOfType(UIBaseNodeTreeSelector.class); event.getRequestContext().addUIComponentToUpdateByAjax(nodeTreeSelector); } } }
12,480
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIBaseNodeTreeSelector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/tree/UIBaseNodeTreeSelector.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.tree; import javax.jcr.Node; import org.exoplatform.ecm.webui.selector.ComponentSelector; import org.exoplatform.portal.webui.container.UIContainer; import org.exoplatform.webui.core.UIComponent; /** * Created by The eXo Platform SAS. * * @author : Hoa.Pham hoa.pham@exoplatform.com Jun 23, 2008 */ public abstract class UIBaseNodeTreeSelector extends UIContainer implements ComponentSelector { protected UIComponent sourceUIComponent ; protected String returnFieldName = null ; /** * On change. * * @param currentNode the current node * @param context the request context * @throws Exception the exception */ public abstract void onChange(final Node currentNode, Object context) throws Exception; public String getReturnFieldName() { return returnFieldName; } public void setReturnFieldName(String name) { this.returnFieldName = name; } public UIComponent getSourceComponent() { return sourceUIComponent; } public void setSourceComponent(UIComponent uicomponent, String[] initParams) { sourceUIComponent = uicomponent ; if(initParams == null || initParams.length < 0) return ; for(int i = 0; i < initParams.length; i ++) { if(initParams[i].indexOf("returnField") > -1) { String[] array = initParams[i].split("=") ; returnFieldName = array[1] ; break ; } returnFieldName = initParams[0] ; } } }
2,200
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UINodeTreeBuilder.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/tree/UINodeTreeBuilder.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.tree; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.nodetype.NodeType; import org.exoplatform.ecm.webui.comparator.NodeTitleComparator; import org.exoplatform.ecm.webui.tree.selectone.UIOneNodePathSelector; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.container.UIContainer; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIBreadcumbs; import org.exoplatform.webui.core.UITree; import org.exoplatform.webui.core.UIBreadcumbs.LocalPath; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS. * * @author : Hoa.Pham hoa.pham@exoplatform.com Jun 23, 2008 */ @ComponentConfig( events = @EventConfig(listeners = UINodeTreeBuilder.ChangeNodeActionListener.class) ) public class UINodeTreeBuilder extends UIContainer { private boolean allowPublish = false; private PublicationService publicationService_ = null; private List<String> templates_ = null; private String[] acceptedNodeTypes = {}; private String[] defaultExceptedNodeTypes = {}; /** The root tree node. */ protected NodeLocation rootTreeNode; /** The current node. */ protected NodeLocation currentNode; public boolean isAllowPublish() { return allowPublish; } public void setAllowPublish(boolean allowPublish, PublicationService publicationService, List<String> templates) { this.allowPublish = allowPublish; publicationService_ = publicationService; templates_ = templates; } /** * Instantiates a new uI node tree builder. * * @throws Exception the exception */ public UINodeTreeBuilder() throws Exception { UITree tree = addChild(UINodeTree.class, null, UINodeTree.class.getSimpleName()+hashCode()) ; tree.setBeanLabelField("name") ; tree.setBeanIdField("path") ; } /** * Gets the root tree node. * * @return the root tree node */ public Node getRootTreeNode() { return NodeLocation.getNodeByLocation(rootTreeNode); } /** * Sets the root tree node. * * @param node the new root tree node * @throws Exception the exception */ public final void setRootTreeNode(Node node) throws Exception { this.rootTreeNode = NodeLocation.getNodeLocationByNode(node); this.currentNode = NodeLocation.getNodeLocationByNode(node); broadcastOnChange(node,null); } /** * Gets the current node. * * @return the current node */ public Node getCurrentNode() { return NodeLocation.getNodeByLocation(currentNode); } /** * Sets the current node. * * @param currentNode the new current node */ public void setCurrentNode(Node currentNode) { this.currentNode = NodeLocation.getNodeLocationByNode(currentNode); } /** * Gets the accepted node types. * * @return the accepted node types */ public String[] getAcceptedNodeTypes() { return acceptedNodeTypes; } /** * Sets the accepted node types. * * @param acceptedNodeTypes the new accepted node types */ public void setAcceptedNodeTypes(String[] acceptedNodeTypes) { this.acceptedNodeTypes = acceptedNodeTypes; } /** * Gets the default excepted node types. * * @return the default excepted node types */ public String[] getDefaultExceptedNodeTypes() { return defaultExceptedNodeTypes; } /** * Sets the default excepted node types. * * @param defaultExceptedNodeTypes the new excepted node types */ public void setDefaultExceptedNodeTypes(String[] defaultExceptedNodeTypes) { this.defaultExceptedNodeTypes = defaultExceptedNodeTypes; } public boolean isExceptedNodeType(Node node) throws RepositoryException { if(defaultExceptedNodeTypes.length > 0) { for(String nodeType: defaultExceptedNodeTypes) { if(node.isNodeType(nodeType)) return true; } } return false; } /** * Builds the tree. * * @throws Exception the exception */ public void buildTree() throws Exception { NodeIterator sibbling = null ; NodeIterator children = null ; UINodeTree tree = getChild(UINodeTree.class) ; Node selectedNode = getNodeByPathBreadcumbs(); tree.setSelected(selectedNode); if (Utils.getNodeSymLink(selectedNode).getDepth() > 0) { tree.setParentSelected(selectedNode.getParent()) ; sibbling = Utils.getNodeSymLink(selectedNode).getNodes() ; children = Utils.getNodeSymLink(selectedNode).getNodes() ; } else { tree.setParentSelected(selectedNode) ; sibbling = Utils.getNodeSymLink(selectedNode).getNodes() ; children = null; } if (sibbling != null) { tree.setSibbling(filfer(sibbling)); } if (children != null) { tree.setChildren(filfer(children)); } } private Node getNodeByPathBreadcumbs() throws PathNotFoundException, RepositoryException { UIOneNodePathSelector uiOneNodePathSelector = (UIOneNodePathSelector) getParent(); UIBreadcumbs uiBreadcumbs = uiOneNodePathSelector.getChildById("BreadcumbCategoriesOne"); List<LocalPath> listLocalPath = uiBreadcumbs.getPath(); StringBuilder buffer = new StringBuilder(1024); String rootPath = rootTreeNode.getPath(); for (LocalPath iterLocalPath : listLocalPath) { buffer.append("/").append(iterLocalPath.getId()); } String path = buffer.toString(); if (path.startsWith("//")) path = path.substring(1); if (!path.startsWith(rootPath)) { StringBuffer sb = new StringBuffer(); sb.append(rootPath).append(path); path = sb.toString(); } if (path.endsWith("/")) path = path.substring(0, path.length() - 1); if (path.length() == 0) path = "/"; if (buffer.length() == 0) return NodeLocation.getNodeByLocation(currentNode); NodeFinder nodeFinder_ = getApplicationComponent(NodeFinder.class); return (Node)nodeFinder_.getItem(uiOneNodePathSelector.getWorkspaceName(), path); } private void addNodePublish(List<Node> listNode, Node node, PublicationService publicationService) throws Exception { if (isAllowPublish()) { NodeType nt = node.getPrimaryNodeType(); if (templates_.contains(nt.getName())) { Node nodecheck = publicationService.getNodePublish(node, null); if (nodecheck != null) { listNode.add(nodecheck); } } else { listNode.add(node); } } else { listNode.add(node); } } private List<Node> filfer(final NodeIterator iterator) throws Exception{ List<Node> list = new ArrayList<Node>(); if (acceptedNodeTypes.length > 0) { for(;iterator.hasNext();) { Node sibbling = iterator.nextNode(); if(sibbling.isNodeType("exo:hiddenable")) continue; for(String nodetype: acceptedNodeTypes) { if(sibbling.isNodeType(nodetype)) { list.add(sibbling); break; } } } Collections.sort(list, new NodeTitleComparator(NodeTitleComparator.ASCENDING_ORDER)); List<Node> listNodeCheck = new ArrayList<Node>(); for (Node node : list) { addNodePublish(listNodeCheck, node, publicationService_); } return listNodeCheck; } for(;iterator.hasNext();) { Node sibbling = iterator.nextNode(); if(sibbling.isNodeType("exo:hiddenable") || isExceptedNodeType(sibbling)) continue; list.add(sibbling); } Collections.sort(list, new NodeTitleComparator(NodeTitleComparator.ASCENDING_ORDER)); List<Node> listNodeCheck = new ArrayList<Node>(); for (Node node : list) addNodePublish(listNodeCheck, node, publicationService_); return listNodeCheck; } /* (non-Javadoc) * @see org.exoplatform.webui.core.UIComponent#processRender(org.exoplatform.webui.application.WebuiRequestContext) */ public void processRender(WebuiRequestContext context) throws Exception { Writer writer = context.getWriter() ; writer.write("<div class=\"explorerTree\">") ; buildTree() ; super.renderChildren() ; writer.write("</div>") ; } /** * When a node is change in tree. This method will be rerender the children and sibbling nodes of * current node and broadcast change node event to other uicomponent * * @param path the path * @param context the request context * @throws Exception the exception */ public void changeNode(String path, Object context) throws Exception { NodeFinder nodeFinder_ = getApplicationComponent(NodeFinder.class); String rootPath = rootTreeNode.getPath(); if(rootPath.equals(path) || !path.startsWith(rootPath)) { currentNode = rootTreeNode; }else { if (path.startsWith(rootPath)) path = path.substring(rootPath.length()); if (path.startsWith("/")) path = path.substring(1); currentNode = NodeLocation.getNodeLocationByNode(nodeFinder_.getNode( NodeLocation.getNodeByLocation(rootTreeNode), path)); } broadcastOnChange(NodeLocation.getNodeByLocation(currentNode),context); } /** * Broadcast on change. * * @param node the node * @param context the request context * @throws Exception the exception */ public void broadcastOnChange(Node node, Object context) throws Exception { UIBaseNodeTreeSelector nodeTreeSelector = getAncestorOfType(UIBaseNodeTreeSelector.class); nodeTreeSelector.onChange(node, context); } /** * The listener interface for receiving changeNodeAction events. The class * that is interested in processing a changeNodeAction event implements this * interface, and the object created with that class is registered with a * component using the component's * <code>addChangeNodeActionListener</code> method. When * the changeNodeAction event occurs, that object's appropriate * method is invoked. */ static public class ChangeNodeActionListener extends EventListener<UITree> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UITree> event) throws Exception { UINodeTreeBuilder builder = event.getSource().getParent(); String uri = event.getRequestContext().getRequestParameter(OBJECTID); builder.changeNode(uri,event.getRequestContext()); UIBaseNodeTreeSelector nodeTreeSelector = builder.getAncestorOfType(UIBaseNodeTreeSelector.class); event.getRequestContext().addUIComponentToUpdateByAjax(nodeTreeSelector); } } }
12,106
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIOneTaxonomySelector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/tree/selectone/UIOneTaxonomySelector.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.tree.selectone; import java.util.ArrayList; import java.util.List; import java.util.MissingResourceException; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.webui.tree.UIBaseNodeTreeSelector; import org.exoplatform.ecm.webui.tree.UITreeTaxonomyBuilder; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.cms.taxonomy.TaxonomyService; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.ComponentConfigs; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIBreadcumbs; import org.exoplatform.webui.core.UIBreadcumbs.LocalPath; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIFormSelectBox; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Oct 18, 2006 * 2:12:26 PM */ @ComponentConfigs( { @ComponentConfig( template = "classpath:groovy/ecm/webui/UIOneTaxonomySelector.gtmpl" ), @ComponentConfig( type = UIBreadcumbs.class, id = "BreadcumbOneTaxonomy", template = "system:/groovy/webui/core/UIBreadcumbs.gtmpl", events = @EventConfig(listeners = UIOneTaxonomySelector.SelectPathActionListener.class) ) } ) public class UIOneTaxonomySelector extends UIBaseNodeTreeSelector { private String[] acceptedNodeTypesInTree = {}; private String[] acceptedNodeTypesInPathPanel = {}; private String[] acceptedMimeTypes = {}; private String[] exceptedNodeTypesInPathPanel = {}; private String repositoryName = null; private String workspaceName = null; private String rootTreePath = null; private boolean isDisable = false; private boolean allowPublish = false; private boolean alreadyChangePath = false; private String rootTaxonomyName = null; private String[] defaultExceptedNodeTypes = {"exo:symlink"}; public UIOneTaxonomySelector() throws Exception { addChild(UIBreadcumbs.class, "BreadcumbOneTaxonomy", "BreadcumbOneTaxonomy"); addChild(UITreeTaxonomyList.class, null, null); addChild(UITreeTaxonomyBuilder.class, null, UITreeTaxonomyBuilder.class.getSimpleName()+hashCode()); addChild(UISelectTaxonomyPanel.class, null, null); } public String getRootTaxonomyName() { return rootTaxonomyName; } public void setRootTaxonomyName(String rootTaxonomyName) { this.rootTaxonomyName = rootTaxonomyName; } Node getTaxoTreeNode(String taxoTreeName) throws RepositoryException { TaxonomyService taxonomyService = getApplicationComponent(TaxonomyService.class); return taxonomyService.getTaxonomyTree(taxoTreeName); } public String[] getDefaultExceptedNodeTypes() { return defaultExceptedNodeTypes; } public void init(SessionProvider sessionProvider) throws Exception { RepositoryService repositoryService = getApplicationComponent(RepositoryService.class); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); PublicationService publicationService = getApplicationComponent(PublicationService.class); TemplateService templateService = getApplicationComponent(TemplateService.class); List<String> templates = templateService.getDocumentTemplates(); Node rootNode; if (rootTreePath.trim().equals("/")) { rootNode = sessionProvider.getSession(workspaceName, manageableRepository) .getRootNode(); } else { NodeFinder nodeFinder = getApplicationComponent(NodeFinder.class); try { rootNode = (Node) nodeFinder.getItem(workspaceName, rootTreePath); } catch (PathNotFoundException pathNotFoundException) { rootNode = null; } } UITreeTaxonomyList uiTreeTaxonomyList = getChild(UITreeTaxonomyList.class); uiTreeTaxonomyList.setTaxonomyTreeList(); UITreeTaxonomyBuilder builder = getChild(UITreeTaxonomyBuilder.class); builder.setAllowPublish(allowPublish, publicationService, templates); builder.setAcceptedNodeTypes(acceptedNodeTypesInTree); builder.setDefaultExceptedNodeTypes(defaultExceptedNodeTypes); if (rootNode != null) builder.setRootTreeNode(rootNode); UISelectTaxonomyPanel selectPathPanel = getChild(UISelectTaxonomyPanel.class); selectPathPanel.setAllowPublish(allowPublish, publicationService, templates); selectPathPanel.setAcceptedNodeTypes(acceptedNodeTypesInPathPanel); selectPathPanel.setAcceptedMimeTypes(acceptedMimeTypes); selectPathPanel.setExceptedNodeTypes(exceptedNodeTypesInPathPanel); selectPathPanel.setDefaultExceptedNodeTypes(defaultExceptedNodeTypes); selectPathPanel.updateGrid(); String taxoTreeName = ((UIFormSelectBox)this.findComponentById(UITreeTaxonomyList.TAXONOMY_TREE)).getValue(); Node taxoTreeNode = this.getTaxoTreeNode(taxoTreeName); this.setWorkspaceName(taxoTreeNode.getSession().getWorkspace().getName()); this.setRootTaxonomyName(taxoTreeNode.getName()); this.setRootTreePath(taxoTreeNode.getPath()); UITreeTaxonomyBuilder uiTreeJCRExplorer = this.findFirstComponentOfType(UITreeTaxonomyBuilder.class); uiTreeJCRExplorer.setRootTreeNode(taxoTreeNode); uiTreeJCRExplorer.buildTree(); } public boolean isAllowPublish() { return allowPublish; } public void setAllowPublish(boolean allowPublish) { this.allowPublish = allowPublish; } public void setRootNodeLocation(String repository, String workspace, String rootPath) throws Exception { this.repositoryName = repository; this.workspaceName = workspace; this.rootTreePath = rootPath; } public void setIsDisable(String wsName, boolean isDisable) { setWorkspaceName(wsName); this.isDisable = isDisable; } public boolean isDisable() { return isDisable; } public void setIsShowSystem(boolean isShowSystem) { getChild(UITreeTaxonomyList.class).setIsShowSystem(isShowSystem); } public void setShowRootPathSelect(boolean isRendered) { UITreeTaxonomyList uiTreeTaxonomyList = getChild(UITreeTaxonomyList.class); uiTreeTaxonomyList.setShowRootPathSelect(isRendered); } public String[] getAcceptedNodeTypesInTree() { return acceptedNodeTypesInTree; } public void setAcceptedNodeTypesInTree(String[] acceptedNodeTypesInTree) { this.acceptedNodeTypesInTree = acceptedNodeTypesInTree; } public String[] getAcceptedNodeTypesInPathPanel() { return acceptedNodeTypesInPathPanel; } public void setAcceptedNodeTypesInPathPanel(String[] acceptedNodeTypesInPathPanel) { this.acceptedNodeTypesInPathPanel = acceptedNodeTypesInPathPanel; } public String[] getExceptedNodeTypesInPathPanel() { return exceptedNodeTypesInPathPanel; } public void setExceptedNodeTypesInPathPanel(String[] exceptedNodeTypesInPathPanel) { this.exceptedNodeTypesInPathPanel = exceptedNodeTypesInPathPanel; } public String[] getAcceptedMimeTypes() { return acceptedMimeTypes; } public void setAcceptedMimeTypes(String[] acceptedMimeTypes) { this.acceptedMimeTypes = acceptedMimeTypes; } public String getRepositoryName() { return repositoryName; } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } public String getWorkspaceName() { return workspaceName; } public void setWorkspaceName(String workspaceName) { this.workspaceName = workspaceName; } public String getRootTreePath() { return rootTreePath; } public void setRootTreePath(String rootTreePath) { this.rootTreePath = rootTreePath; getChild(UISelectTaxonomyPanel.class).setTaxonomyTreePath(rootTreePath); } public String getTaxonomyLabel(Node node) throws RepositoryException { try { String display = node.getName(); if (rootTaxonomyName == null) rootTaxonomyName = rootTreePath.substring(rootTreePath.lastIndexOf("/") + 1); display = rootTaxonomyName.concat(node.getPath().replace(rootTreePath, "")).replaceAll("/", "."); return Utils.getResourceBundle(("eXoTaxonomies.").concat(display).concat(".label")); } catch (MissingResourceException me) { return node.getName(); } } public void onChange(final Node currentNode, Object context) throws Exception { UISelectTaxonomyPanel selectPathPanel = getChild(UISelectTaxonomyPanel.class); UITreeTaxonomyList uiTreeTaxonomyList = getChild(UITreeTaxonomyList.class); String taxoTreeName = uiTreeTaxonomyList.getUIFormSelectBox(UITreeTaxonomyList.TAXONOMY_TREE).getValue(); if (StringUtils.isEmpty(taxoTreeName)) return; Node parentRoot = getTaxoTreeNode(taxoTreeName); selectPathPanel.setParentNode(currentNode); selectPathPanel.updateGrid(); UIBreadcumbs uiBreadcumbs = getChild(UIBreadcumbs.class); String pathName = currentNode.getName(); if (currentNode.equals(parentRoot)) { pathName = ""; } String label = pathName.length() > 0 ? getTaxonomyLabel(currentNode) : pathName; UIBreadcumbs.LocalPath localPath = new UIBreadcumbs.LocalPath(pathName, label); List<LocalPath> listLocalPath = uiBreadcumbs.getPath(); StringBuilder buffer = new StringBuilder(1024); for(LocalPath iterLocalPath: listLocalPath) { buffer.append("/").append(iterLocalPath.getId()); } if (!alreadyChangePath) { String path = buffer.toString(); path = path.replaceAll("/+", "/"); if (!path.startsWith(rootTreePath)) { StringBuffer buf = new StringBuffer(); if (currentNode.getPath().contains(parentRoot.getPath())) { buf.append(currentNode.getPath()); } else { buf.append(rootTreePath).append(path); } path = buf.toString(); } if (path.endsWith("/")) path = path.substring(0, path.length() - 1); if (path.length() == 0) path = "/"; String breadcumbPath = rootTreePath + buffer.toString(); if (!breadcumbPath.equals(path)) { if (breadcumbPath.startsWith(path)) { if (listLocalPath != null && listLocalPath.size() > 0) { listLocalPath.remove(listLocalPath.size() - 1); } } else { if (!currentNode.equals(parentRoot)) { listLocalPath.add(localPath); } } } } alreadyChangePath = false; uiBreadcumbs.setPath(listLocalPath); } private void changeNode(String stringPath, Object context) throws Exception { UITreeTaxonomyBuilder builder = getChild(UITreeTaxonomyBuilder.class); builder.changeNode(stringPath, context); } public void changeGroup(String groupId, Object context) throws Exception { StringBuffer stringPath = new StringBuffer(rootTreePath); if (!rootTreePath.equals("/")) { stringPath.append("/"); } UIBreadcumbs uiBreadcumb = getChild(UIBreadcumbs.class); if (groupId == null) groupId = ""; List<LocalPath> listLocalPath = uiBreadcumb.getPath(); if (listLocalPath == null || listLocalPath.size() == 0) return; List<String> listLocalPathString = new ArrayList<String>(); for (LocalPath localPath : listLocalPath) { listLocalPathString.add(localPath.getId().trim()); } if (listLocalPathString.contains(groupId)) { int index = listLocalPathString.indexOf(groupId); alreadyChangePath = false; if (index == listLocalPathString.size() - 1) return; for (int i = listLocalPathString.size() - 1; i > index; i--) { listLocalPathString.remove(i); listLocalPath.remove(i); } alreadyChangePath = true; uiBreadcumb.setPath(listLocalPath); for (int i = 0; i < listLocalPathString.size(); i++) { String pathName = listLocalPathString.get(i); if (pathName != null && pathName.trim().length() != 0) { stringPath.append(pathName.trim()); if (i < listLocalPathString.size() - 1) stringPath.append("/"); } } changeNode(stringPath.toString(), context); } } static public class SelectPathActionListener extends EventListener<UIBreadcumbs> { public void execute(Event<UIBreadcumbs> event) throws Exception { UIBreadcumbs uiBreadcumbs = event.getSource(); UIOneTaxonomySelector uiOneNodePathSelector = uiBreadcumbs.getParent(); String objectId = event.getRequestContext().getRequestParameter(OBJECTID); uiBreadcumbs.setSelectPath(objectId); String selectGroupId = uiBreadcumbs.getSelectLocalPath().getId(); uiOneNodePathSelector.changeGroup(selectGroupId, event.getRequestContext()); event.getRequestContext().addUIComponentToUpdateByAjax(uiOneNodePathSelector); } } }
13,862
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDriveListForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/tree/selectone/UIDriveListForm.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.tree.selectone; /** * Created by The eXo Platform SAS * @author : Hoa.Pham * hoa.pham@exoplatform.com * Jun 23, 2008 */ public class UIDriveListForm { }
936
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIWorkspaceList.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/tree/selectone/UIWorkspaceList.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.tree.selectone; import java.util.ArrayList; import java.util.List; import javax.jcr.AccessDeniedException; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.exoplatform.ecm.webui.form.UIFormInputSetWithAction; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.ecm.webui.tree.UINodeTreeBuilder; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.UIBreadcumbs; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormInputInfo; import org.exoplatform.webui.form.UIFormSelectBox; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Jun 21, 2007 2:32:49 PM */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "classpath:groovy/ecm/webui/form/UIFormWithoutAction.gtmpl", events = { @EventConfig(listeners = UIWorkspaceList.ChangeWorkspaceActionListener.class), @EventConfig(listeners = UIWorkspaceList.AddRootNodeActionListener.class) } ) public class UIWorkspaceList extends UIForm { static private String WORKSPACE_NAME = "workspaceName"; static private String ROOT_NODE_INFO = "rootNodeInfo"; static private String ROOT_NODE_PATH = "rootNodePath"; private List<String> wsList_; private boolean isShowSystem_ = true; private static final Log LOG = ExoLogger.getLogger(UIWorkspaceList.class.getName()); public UIWorkspaceList() throws Exception { List<SelectItemOption<String>> wsList = new ArrayList<SelectItemOption<String>>(); UIFormSelectBox uiWorkspaceList = new UIFormSelectBox(WORKSPACE_NAME, WORKSPACE_NAME, wsList); uiWorkspaceList.setOnChange("ChangeWorkspace"); addUIFormInput(uiWorkspaceList); UIFormInputSetWithAction rootNodeInfo = new UIFormInputSetWithAction(ROOT_NODE_INFO); rootNodeInfo.addUIFormInput(new UIFormInputInfo(ROOT_NODE_PATH, ROOT_NODE_PATH, null)); String[] actionInfor = {"AddRootNode"}; rootNodeInfo.setActionInfo(ROOT_NODE_PATH, actionInfor); rootNodeInfo.showActionInfo(true); rootNodeInfo.setRendered(false); addUIComponentInput(rootNodeInfo); } public void setIsShowSystem(boolean isShowSystem) { isShowSystem_ = isShowSystem; } public boolean isShowSystemWorkspace() { return isShowSystem_; } public void setShowRootPathSelect(boolean isRender) { UIFormInputSetWithAction uiInputAction = getChildById(ROOT_NODE_INFO); uiInputAction.setRendered(isRender); } public void setWorkspaceList() throws Exception { wsList_ = new ArrayList<String>(); RepositoryService repositoryService = getApplicationComponent(RepositoryService.class); String[] wsNames = repositoryService.getCurrentRepository().getWorkspaceNames(); String systemWsName = repositoryService.getCurrentRepository() .getConfiguration() .getSystemWorkspaceName(); List<SelectItemOption<String>> workspace = new ArrayList<SelectItemOption<String>>(); for (String wsName : wsNames) { Node rootNode = null; try { rootNode = getRootNode(wsName); } catch(AccessDeniedException ex) { continue; } catch(RepositoryException ex) { continue; } if (!isShowSystem_) { if (!wsName.equals(systemWsName)) { workspace.add(new SelectItemOption<String>(wsName, wsName)); wsList_.add(wsName); } } else { workspace.add(new SelectItemOption<String>(wsName, wsName)); wsList_.add(wsName); } } UIFormSelectBox uiWorkspaceList = getUIFormSelectBox(WORKSPACE_NAME); uiWorkspaceList.setOptions(workspace); UIOneNodePathSelector uiBrowser = getParent(); if (uiBrowser.getWorkspaceName() != null) { if (wsList_.contains(uiBrowser.getWorkspaceName())) { uiWorkspaceList.setValue(uiBrowser.getWorkspaceName()); } } } public void setIsDisable(String wsName, boolean isDisable) { if(wsList_.contains(wsName)) getUIFormSelectBox(WORKSPACE_NAME).setValue(wsName); getUIFormSelectBox(WORKSPACE_NAME).setDisabled(isDisable); } private Node getRootNode(String workspaceName) throws RepositoryException { RepositoryService repositoryService = getApplicationComponent(RepositoryService.class); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); return WCMCoreUtils.getUserSessionProvider().getSession(workspaceName, manageableRepository).getRootNode(); } static public class ChangeWorkspaceActionListener extends EventListener<UIWorkspaceList> { public void execute(Event<UIWorkspaceList> event) throws Exception { UIWorkspaceList uiWorkspaceList = event.getSource(); UIOneNodePathSelector uiJBrowser = uiWorkspaceList.getParent(); String wsName = uiWorkspaceList.getUIFormSelectBox(WORKSPACE_NAME).getValue(); uiJBrowser.setWorkspaceName(wsName); UINodeTreeBuilder uiTreeBuilder = uiJBrowser.getChild(UINodeTreeBuilder.class); UIBreadcumbs uiBreadcumbs = uiJBrowser.getChild(UIBreadcumbs.class); if (uiBreadcumbs != null) uiBreadcumbs.getPath().clear(); UIApplication uiApp = uiWorkspaceList.getAncestorOfType(UIApplication.class); try { uiTreeBuilder.setRootTreeNode(uiWorkspaceList.getRootNode(wsName)); } catch(Exception e) { if (LOG.isErrorEnabled()) { LOG.error("An unexpected error occurs", e); } return; } uiTreeBuilder.buildTree(); event.getRequestContext().addUIComponentToUpdateByAjax(uiJBrowser); } } static public class AddRootNodeActionListener extends EventListener<UIWorkspaceList> { public void execute(Event<UIWorkspaceList> event) throws Exception { UIWorkspaceList uiWorkspaceList = event.getSource(); UIOneNodePathSelector uiJBrowser = uiWorkspaceList.getParent(); String returnField = uiJBrowser.getReturnFieldName(); String workspaceName = uiJBrowser.getWorkspaceName(); RepositoryService repositoryService = uiWorkspaceList.getApplicationComponent(RepositoryService.class); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); Session session = WCMCoreUtils.getSystemSessionProvider().getSession(workspaceName, manageableRepository); String value = session.getRootNode().getPath(); if (!uiJBrowser.isDisable()) { StringBuffer sb = new StringBuffer(); sb.append(uiJBrowser.getWorkspaceName()).append(":").append(value); value = sb.toString(); } ((UISelectable)uiJBrowser.getSourceComponent()).doSelect(returnField, value); } } }
8,192
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIOneNodePathSelector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/tree/selectone/UIOneNodePathSelector.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.tree.selectone; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.jcr.Item; import javax.jcr.Node; import javax.jcr.Session; import org.exoplatform.ecm.webui.tree.UIBaseNodeTreeSelector; import org.exoplatform.ecm.webui.tree.UINodeTreeBuilder; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.security.IdentityConstants; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.ComponentConfigs; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIBreadcumbs; import org.exoplatform.webui.core.UIBreadcumbs.LocalPath; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Oct 18, 2006 * 2:12:26 PM */ @ComponentConfigs( { @ComponentConfig( template = "classpath:groovy/ecm/webui/UIOneNodePathSelector.gtmpl" ), @ComponentConfig( type = UIBreadcumbs.class, id = "BreadcumbCategoriesOne", template = "system:/groovy/webui/core/UIBreadcumbs.gtmpl", events = @EventConfig(listeners = UIOneNodePathSelector.SelectPathActionListener.class) ) } ) public class UIOneNodePathSelector extends UIBaseNodeTreeSelector { private String[] acceptedNodeTypesInTree = {}; private String[] acceptedNodeTypesInPathPanel = {}; private String[] acceptedMimeTypes = {}; private String[] exceptedNodeTypesInPathPanel = {}; private String[] exceptedNodeTypesInTree = {}; private String[] defaultExceptedNodeTypes = {"exo:symlink"}; private String repositoryName = null; private String workspaceName = null; private String rootTreePath = null; private boolean isDisable = false; private boolean allowPublish = false; private boolean alreadyChangePath = false; private boolean showOnlyFolderNodeInTree = true; private String rootTaxonomyName = null; public UIOneNodePathSelector() throws Exception { addChild(UIBreadcumbs.class, "BreadcumbCategoriesOne", "BreadcumbCategoriesOne"); addChild(UIWorkspaceList.class, null, null); addChild(UINodeTreeBuilder.class, null, UINodeTreeBuilder.class.getSimpleName()+hashCode()); addChild(UISelectPathPanel.class, null, null).setShowTrashHomeNode(false); } public String getRootTaxonomyName() { return rootTaxonomyName; } public void setRootTaxonomyName(String rootTaxonomyName) { this.rootTaxonomyName = rootTaxonomyName; } public void init(SessionProvider sessionProvider) throws Exception { RepositoryService repositoryService = getApplicationComponent(RepositoryService.class); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); PublicationService publicationService = getApplicationComponent(PublicationService.class); TemplateService templateService = getApplicationComponent(TemplateService.class); List<String> templates = templateService.getDocumentTemplates(); Node rootNode; if (rootTreePath.trim().equals("/")) { rootNode = sessionProvider.getSession(workspaceName, manageableRepository).getRootNode(); } else { NodeFinder nodeFinder = getApplicationComponent(NodeFinder.class); if (rootTreePath.indexOf("${userId}") > -1) { String userId = Util.getPortalRequestContext().getRemoteUser(); String rootTreeOfSpecialDriver = org.exoplatform.services.cms.impl.Utils.getPersonalDrivePath(rootTreePath , userId); rootTreePath = rootTreeOfSpecialDriver; } rootNode = (Node) nodeFinder.getItem(workspaceName, rootTreePath); } UIWorkspaceList uiWorkspaceList = getChild(UIWorkspaceList.class); uiWorkspaceList.setWorkspaceList(); uiWorkspaceList.setIsDisable(workspaceName, isDisable); UINodeTreeBuilder builder = getChild(UINodeTreeBuilder.class); builder.setAllowPublish(allowPublish, publicationService, templates); if (this.showOnlyFolderNodeInTree) { List<String> nodeTypesInTree = new ArrayList<String>(Arrays.asList(acceptedNodeTypesInTree)); if (!nodeTypesInTree.contains(Utils.NT_UNSTRUCTURED)) nodeTypesInTree.add(Utils.NT_UNSTRUCTURED); if (!nodeTypesInTree.contains(Utils.NT_FOLDER)) nodeTypesInTree.add(Utils.NT_FOLDER); if (!nodeTypesInTree.contains(Utils.EXO_TAXONOMY)) nodeTypesInTree.add(Utils.EXO_TAXONOMY); this.acceptedNodeTypesInTree = nodeTypesInTree.toArray(new String[]{}); } builder.setAcceptedNodeTypes(acceptedNodeTypesInTree); builder.setDefaultExceptedNodeTypes(defaultExceptedNodeTypes); builder.setRootTreeNode(rootNode); UISelectPathPanel selectPathPanel = getChild(UISelectPathPanel.class); selectPathPanel.setAllowPublish(allowPublish, publicationService, templates); selectPathPanel.setAcceptedNodeTypes(acceptedNodeTypesInPathPanel); selectPathPanel.setAcceptedMimeTypes(acceptedMimeTypes); selectPathPanel.setExceptedNodeTypes(exceptedNodeTypesInPathPanel); selectPathPanel.setDefaultExceptedNodeTypes(defaultExceptedNodeTypes); selectPathPanel.updateGrid(); } public boolean isAllowPublish() { return allowPublish; } public void setAllowPublish(boolean allowPublish) { this.allowPublish = allowPublish; } public void setRootNodeLocation(String repository, String workspace, String rootPath) throws Exception { this.repositoryName = repository; this.workspaceName = workspace; this.rootTreePath = rootPath; } public void setIsDisable(String wsName, boolean isDisable) { setWorkspaceName(wsName); this.isDisable = isDisable; } public boolean isDisable() { return isDisable; } public void setIsShowSystem(boolean isShowSystem) { getChild(UIWorkspaceList.class).setIsShowSystem(isShowSystem); } public void setShowRootPathSelect(boolean isRendered) { UIWorkspaceList uiWorkspaceList = getChild(UIWorkspaceList.class); uiWorkspaceList.setShowRootPathSelect(isRendered); } public String[] getAcceptedNodeTypesInTree() { return acceptedNodeTypesInTree; } public void setAcceptedNodeTypesInTree(String[] acceptedNodeTypesInTree) { this.acceptedNodeTypesInTree = acceptedNodeTypesInTree; } public String[] getAcceptedNodeTypesInPathPanel() { return acceptedNodeTypesInPathPanel; } public void setAcceptedNodeTypesInPathPanel(String[] acceptedNodeTypesInPathPanel) { this.acceptedNodeTypesInPathPanel = acceptedNodeTypesInPathPanel; } public String[] getExceptedNodeTypesInTree() { return exceptedNodeTypesInTree; } public void setExceptedNodeTypesInTree(String[] exceptedNodeTypesInTree) { this.exceptedNodeTypesInTree = exceptedNodeTypesInTree; } public String[] getExceptedNodeTypesInPathPanel() { return exceptedNodeTypesInPathPanel; } public void setExceptedNodeTypesInPathPanel(String[] exceptedNodeTypesInPathPanel) { this.exceptedNodeTypesInPathPanel = exceptedNodeTypesInPathPanel; } public String[] getDefaultExceptedNodeTypes() { return defaultExceptedNodeTypes; } public String[] getAcceptedMimeTypes() { return acceptedMimeTypes; } public void setAcceptedMimeTypes(String[] acceptedMimeTypes) { this.acceptedMimeTypes = acceptedMimeTypes; } public boolean isShowOnlyFolderNodeInTree() { return showOnlyFolderNodeInTree; } public void setShowOnlyFolderNodeInTree(boolean value) { showOnlyFolderNodeInTree = value; } public String getRepositoryName() { return repositoryName; } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } public String getWorkspaceName() { return workspaceName; } public void setWorkspaceName(String workspaceName) { this.workspaceName = workspaceName; } public String getRootTreePath() { return rootTreePath; } public void setRootTreePath(String rootTreePath) { this.rootTreePath = rootTreePath; } public void onChange(final Node currentNode, Object context) throws Exception { UISelectPathPanel selectPathPanel = getChild(UISelectPathPanel.class); selectPathPanel.setParentNode(currentNode); selectPathPanel.updateGrid(); UIBreadcumbs uiBreadcumbs = getChild(UIBreadcumbs.class); String pathName = currentNode.getName(); String pathTitle = pathName; if (currentNode.hasProperty("exo:title")){ pathTitle = currentNode.getProperty("exo:title").getString(); } NodeFinder nodeFinder = getApplicationComponent(NodeFinder.class); Session session; if(currentNode.getSession().getUserID().equals(IdentityConstants.SYSTEM)) { // use system session to fetch node if current session is a system session session = WCMCoreUtils.getSystemSessionProvider().getSession(workspaceName, WCMCoreUtils.getRepository()); } else { session = WCMCoreUtils.getUserSessionProvider().getSession(workspaceName, WCMCoreUtils.getRepository()); } Node rootNode = (Node) nodeFinder.getItem(session, rootTreePath); if (currentNode.equals(rootNode)) { pathName = ""; } UIBreadcumbs.LocalPath localPath = new UIBreadcumbs.LocalPath(pathName, pathTitle); List<LocalPath> listLocalPath = uiBreadcumbs.getPath(); StringBuilder buffer = new StringBuilder(1024); for(LocalPath iterLocalPath: listLocalPath) { buffer.append("/").append(iterLocalPath.getId()); } if (!alreadyChangePath) { String path = buffer.toString(); if (path.startsWith("//")) path = path.substring(1); if (!path.startsWith(rootTreePath)) { StringBuffer buf = new StringBuffer(); buf.append(rootTreePath).append(path); path = buf.toString(); } if (path.endsWith("/")) path = path.substring(0, path.length() - 1); if (path.length() == 0) path = "/"; Node currentBreadcumbsNode = getNodeByVirtualPath(path, session); if (currentNode.equals(rootNode) || ((!currentBreadcumbsNode.equals(rootNode) && currentBreadcumbsNode.getParent() .equals(currentNode)))) { if (listLocalPath != null && listLocalPath.size() > 0) { listLocalPath.remove(listLocalPath.size() - 1); } } else { listLocalPath.add(localPath); } } alreadyChangePath = false; uiBreadcumbs.setPath(listLocalPath); } private Node getNodeByVirtualPath(String pathLinkNode, Session session) throws Exception{ NodeFinder nodeFinder_ = getApplicationComponent(NodeFinder.class); Item item = nodeFinder_.getItem(session, pathLinkNode); return (Node)item; } private void changeNode(String stringPath, Object context) throws Exception { UINodeTreeBuilder builder = getChild(UINodeTreeBuilder.class); builder.changeNode(stringPath, context); } public void changeGroup(String groupId, Object context) throws Exception { StringBuffer stringPath = new StringBuffer(rootTreePath); if (!rootTreePath.equals("/")) { stringPath.append("/"); } UIBreadcumbs uiBreadcumb = getChild(UIBreadcumbs.class); if (groupId == null) groupId = ""; List<LocalPath> listLocalPath = uiBreadcumb.getPath(); if (listLocalPath == null || listLocalPath.size() == 0) return; List<String> listLocalPathString = new ArrayList<String>(); for (LocalPath localPath : listLocalPath) { listLocalPathString.add(localPath.getId().trim()); } if (listLocalPathString.contains(groupId)) { int index = listLocalPathString.indexOf(groupId); alreadyChangePath = false; if (index == listLocalPathString.size() - 1) return; for (int i = listLocalPathString.size() - 1; i > index; i--) { listLocalPathString.remove(i); listLocalPath.remove(i); } alreadyChangePath = true; uiBreadcumb.setPath(listLocalPath); for (int i = 0; i < listLocalPathString.size(); i++) { String pathName = listLocalPathString.get(i); if (pathName != null && pathName.trim().length() != 0) { stringPath.append(pathName.trim()); if (i < listLocalPathString.size() - 1) stringPath.append("/"); } } changeNode(stringPath.toString(), context); } } static public class SelectPathActionListener extends EventListener<UIBreadcumbs> { public void execute(Event<UIBreadcumbs> event) throws Exception { UIBreadcumbs uiBreadcumbs = event.getSource(); UIOneNodePathSelector uiOneNodePathSelector = uiBreadcumbs.getParent(); String objectId = event.getRequestContext().getRequestParameter(OBJECTID); uiBreadcumbs.setSelectPath(objectId); String selectGroupId = uiBreadcumbs.getSelectLocalPath().getId(); uiOneNodePathSelector.changeGroup(selectGroupId, event.getRequestContext()); event.getRequestContext().addUIComponentToUpdateByAjax(uiOneNodePathSelector); } } }
14,258
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISelectPathPanel.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/tree/selectone/UISelectPathPanel.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.tree.selectone; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.nodetype.NodeType; import org.exoplatform.commons.utils.LazyPageList; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.commons.utils.ListAccessImpl; import org.exoplatform.ecm.webui.comparator.NodeTitleComparator; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.ecm.webui.tree.UIBaseNodeTreeSelector; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.container.UIContainer; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIBreadcumbs; import org.exoplatform.webui.core.UIBreadcumbs.LocalPath; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIPageIterator; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS * @author : Hoa.Pham * hoa.pham@exoplatform.com * Jun 23, 2008 */ @ComponentConfig( template = "classpath:groovy/ecm/webui/tree/selectone/UISelectPathPanel.gtmpl", events = { @EventConfig(listeners = UISelectPathPanel.SelectActionListener.class) } ) public class UISelectPathPanel extends UIContainer { private UIPageIterator uiPageIterator_; public String[] acceptedMimeTypes = {}; protected NodeLocation parentNode; private String[] acceptedNodeTypes = {}; private String[] exceptedNodeTypes = {}; private String[] defaultExceptedNodeTypes = {}; private boolean allowPublish = false; private PublicationService publicationService_ = null; private List<String> templates_ = null; private boolean _showTrashHomeNode = true; public UISelectPathPanel() throws Exception { uiPageIterator_ = addChild(UIPageIterator.class, null, "UISelectPathIterate"); } public UIPageIterator getUIPageIterator() { return uiPageIterator_; } public boolean isAllowPublish() { return allowPublish; } public void setShowTrashHomeNode(boolean value) { _showTrashHomeNode = value; } public void setAllowPublish(boolean allowPublish, PublicationService publicationService, List<String> templates) { this.allowPublish = allowPublish; publicationService_ = publicationService; templates_ = templates; } private void addNodePublish(List<Node> listNode, Node node, PublicationService publicationService) throws Exception { if (isAllowPublish()) { NodeType nt = node.getPrimaryNodeType(); if (templates_.contains(nt.getName())) { Node nodecheck = publicationService.getNodePublish(node, null); if (nodecheck != null) { listNode.add(nodecheck); } } else { listNode.add(node); } } else { listNode.add(node); } } public void setParentNode(Node node) { this.parentNode = NodeLocation.getNodeLocationByNode(node); } public Node getParentNode() { return NodeLocation.getNodeByLocation(parentNode); } public String[] getAcceptedNodeTypes() { return acceptedNodeTypes; } public void setAcceptedNodeTypes(String[] acceptedNodeTypes) { this.acceptedNodeTypes = acceptedNodeTypes; } public String[] getExceptedNodeTypes() { return exceptedNodeTypes; } public void setExceptedNodeTypes(String[] exceptedNodeTypes) { this.exceptedNodeTypes = exceptedNodeTypes; } public String[] getDefaultExceptedNodeTypes() { return defaultExceptedNodeTypes; } public void setDefaultExceptedNodeTypes(String[] defaultExceptedNodeTypes) { this.defaultExceptedNodeTypes = defaultExceptedNodeTypes; } public String[] getAcceptedMimeTypes() { return acceptedMimeTypes; } public void setAcceptedMimeTypes(String[] acceptedMimeTypes) { this.acceptedMimeTypes = acceptedMimeTypes; } public List getSelectableNodes() throws Exception { return NodeLocation.getNodeListByLocationList(uiPageIterator_.getCurrentPageData()); } public void updateGrid() throws Exception { ListAccess<Object> selectableNodeList = new ListAccessImpl<Object>(Object.class, NodeLocation.getLocationsByNodeList(getListSelectableNodes())); LazyPageList<Object> objPageList = new LazyPageList<Object>(selectableNodeList, 10); uiPageIterator_.setPageList(objPageList); } public List<Node> getListSelectableNodes() throws Exception { List<Node> list = new ArrayList<Node>(); if (parentNode == null) return list; Node realNode = Utils.getNodeSymLink(NodeLocation.getNodeByLocation(parentNode)); for (NodeIterator iterator = realNode.getNodes();iterator.hasNext();) { Node child = iterator.nextNode(); if(child.isNodeType("exo:hiddenable") || !child.isCheckedOut()) continue; if(Utils.isTrashHomeNode(child) && !_showTrashHomeNode) continue; if(matchMimeType(Utils.getNodeSymLink(child)) && matchNodeType(Utils.getNodeSymLink(child)) && !isExceptedNodeType(child)) { list.add(child); } } Collections.sort(list, new NodeTitleComparator(NodeTitleComparator.ASCENDING_ORDER)); List<Node> listNodeCheck = new ArrayList<Node>(); for (Node node : list) { addNodePublish(listNodeCheck, node, publicationService_); } return listNodeCheck; } protected boolean matchNodeType(Node node) throws Exception { if(acceptedNodeTypes == null || acceptedNodeTypes.length == 0) return true; for(String nodeType: acceptedNodeTypes) { if((node != null) && node.isNodeType(nodeType)) return true; } return false; } protected boolean isExceptedNodeType(Node node) throws RepositoryException { if(defaultExceptedNodeTypes.length > 0) { for(String nodeType: defaultExceptedNodeTypes) { if((node != null) && node.isNodeType(nodeType)) return true; } } if(exceptedNodeTypes == null || exceptedNodeTypes.length == 0) return false; for(String nodeType: exceptedNodeTypes) { if((node != null) && node.isNodeType(nodeType)) return true; } return false; } protected boolean matchMimeType(Node node) throws Exception { if(acceptedMimeTypes == null || acceptedMimeTypes.length == 0) return true; if(!node.isNodeType("nt:file")) return true; String mimeType = node.getNode("jcr:content").getProperty("jcr:mimeType").getString(); for(String type: acceptedMimeTypes) { if(type.equalsIgnoreCase(mimeType)) return true; } return false; } public String getPathTaxonomy() throws Exception { NodeHierarchyCreator nodeHierarchyCreator = getApplicationComponent(NodeHierarchyCreator.class); return nodeHierarchyCreator.getJcrPath(BasePath.TAXONOMIES_TREE_STORAGE_PATH); } public String getDisplayName(Node node) throws RepositoryException { return node.getName(); } static public class SelectActionListener extends EventListener<UISelectPathPanel> { public void execute(Event<UISelectPathPanel> event) throws Exception { UISelectPathPanel uiSelectPathPanel = event.getSource(); UIContainer uiTreeSelector = uiSelectPathPanel.getParent(); UIBreadcumbs uiBreadcumbs = uiTreeSelector.getChild(UIBreadcumbs.class); StringBuffer breadcumbsPaths = new StringBuffer(); for(LocalPath iterLocalPath: uiBreadcumbs.getPath()) { breadcumbsPaths.append("/").append(iterLocalPath.getId()); } StringBuffer sbPath = new StringBuffer(); String objectid = event.getRequestContext().getRequestParameter(OBJECTID); sbPath.append(breadcumbsPaths).append(objectid.substring(objectid.lastIndexOf("/"))); if(uiTreeSelector instanceof UIOneNodePathSelector) { if(!((UIOneNodePathSelector)uiTreeSelector).isDisable()) { sbPath.insert(0, ":").insert(0, ((UIOneNodePathSelector)uiTreeSelector).getWorkspaceName()); } } String returnField = ((UIBaseNodeTreeSelector)uiTreeSelector).getReturnFieldName(); ((UISelectable)((UIBaseNodeTreeSelector)uiTreeSelector).getSourceComponent()).doSelect(returnField, sbPath.toString()) ; UIComponent uiOneNodePathSelector = uiSelectPathPanel.getParent(); if (uiOneNodePathSelector instanceof UIOneNodePathSelector) { UIComponent uiComponent = uiOneNodePathSelector.getParent(); if (uiComponent instanceof UIPopupWindow) { UIComponent uiParentOfPopup = uiComponent.getParent(); ((UIPopupWindow)uiComponent).setShow(false); ((UIPopupWindow)uiComponent).setRendered(false); if(uiParentOfPopup != null) { event.getRequestContext().addUIComponentToUpdateByAjax(uiParentOfPopup); } } UIComponent component = ((UIOneNodePathSelector)uiOneNodePathSelector).getSourceComponent().getParent(); if (component != null) { event.getRequestContext().addUIComponentToUpdateByAjax(component); } } } } }
10,351
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UITreeTaxonomyList.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/tree/selectone/UITreeTaxonomyList.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.tree.selectone; import java.util.ArrayList; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.jcr.AccessDeniedException; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.exoplatform.ecm.webui.form.UIFormInputSetWithAction; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.ecm.webui.tree.UIBaseNodeTreeSelector; import org.exoplatform.ecm.webui.tree.UITreeTaxonomyBuilder; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.taxonomy.TaxonomyService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.web.application.RequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.UIBreadcumbs; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormInputInfo; import org.exoplatform.webui.form.UIFormSelectBox; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Jun 21, 2007 2:32:49 PM */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "classpath:groovy/ecm/webui/form/UIFormWithoutAction.gtmpl", events = { @EventConfig(listeners = UITreeTaxonomyList.ChangeTaxonomyTreeActionListener.class), @EventConfig(listeners = UITreeTaxonomyList.AddRootNodeActionListener.class) } ) public class UITreeTaxonomyList extends UIForm { static private String ROOT_NODE_INFO = "rootNodeInfo"; static private String ROOT_NODE_PATH = "rootNodePath"; public static String TAXONOMY_TREE = "taxonomyTree"; private static final Log LOG = ExoLogger.getLogger(UITreeTaxonomyList.class.getName()); private boolean isShowSystem_ = true; public UITreeTaxonomyList() throws Exception { List<SelectItemOption<String>> taxonomyTreeList = new ArrayList<SelectItemOption<String>>(); UIFormSelectBox uiTaxonomyTreeList = new UIFormSelectBox(TAXONOMY_TREE, TAXONOMY_TREE, taxonomyTreeList); uiTaxonomyTreeList.setOnChange("ChangeTaxonomyTree"); addUIFormInput(uiTaxonomyTreeList); UIFormInputSetWithAction rootNodeInfo = new UIFormInputSetWithAction(ROOT_NODE_INFO); rootNodeInfo.addUIFormInput(new UIFormInputInfo(ROOT_NODE_PATH, ROOT_NODE_PATH, null)); String[] actionInfor = {"AddRootNode"}; rootNodeInfo.setActionInfo(ROOT_NODE_PATH, actionInfor); rootNodeInfo.showActionInfo(true); rootNodeInfo.setRendered(true); addUIComponentInput(rootNodeInfo); } public void setIsShowSystem(boolean isShowSystem) { isShowSystem_ = isShowSystem; } public boolean isShowSystemWorkspace() { return isShowSystem_; } public void setShowRootPathSelect(boolean isRender) { UIFormInputSetWithAction uiInputAction = getChildById(ROOT_NODE_INFO); uiInputAction.setRendered(isRender); } private String getTaxonomyLabel(String taxonomyTree) { String display = taxonomyTree; RequestContext context = Util.getPortalRequestContext(); ResourceBundle res = context.getApplicationResourceBundle(); try { return res.getString(("eXoTaxonomies.").concat(taxonomyTree).concat(".label")); } catch (MissingResourceException me) { return display; } } public void setTaxonomyTreeList() throws Exception { TaxonomyService taxonomyService = getApplicationComponent(TaxonomyService.class); List<Node> listNode = taxonomyService.getAllTaxonomyTrees(); List<SelectItemOption<String>> taxonomyTree = new ArrayList<SelectItemOption<String>>(); for(Node itemNode : listNode) { taxonomyTree.add(new SelectItemOption<String>(getTaxonomyLabel(itemNode.getName()), itemNode.getName())); } UIFormSelectBox uiTreeTaxonomyList = getUIFormSelectBox(TAXONOMY_TREE); uiTreeTaxonomyList.setOptions(taxonomyTree); } private Node getRootNode(String workspaceName, String pathNode) throws RepositoryException { RepositoryService repositoryService = getApplicationComponent(RepositoryService.class); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); SessionProvider sessionProvider = WCMCoreUtils.getUserSessionProvider(); return (Node) sessionProvider.getSession(workspaceName, manageableRepository).getItem(pathNode); } static public class ChangeTaxonomyTreeActionListener extends EventListener<UITreeTaxonomyList> { public void execute(Event<UITreeTaxonomyList> event) throws Exception { UITreeTaxonomyList uiTreeTaxonomyList = event.getSource(); UIOneTaxonomySelector uiOneTaxonomySelector = uiTreeTaxonomyList.getParent(); String taxoTreeName = uiTreeTaxonomyList.getUIFormSelectBox(TAXONOMY_TREE).getValue(); Node taxoTreeNode = uiOneTaxonomySelector.getTaxoTreeNode(taxoTreeName); String workspaceName = taxoTreeNode.getSession().getWorkspace().getName(); String pathTaxonomy = taxoTreeNode.getPath(); UIApplication uiApp = uiTreeTaxonomyList.getAncestorOfType(UIApplication.class); if (taxoTreeNode.hasNodes()) { uiOneTaxonomySelector.setWorkspaceName(workspaceName); uiOneTaxonomySelector.setRootTaxonomyName(taxoTreeNode.getName()); uiOneTaxonomySelector.setRootTreePath(taxoTreeNode.getPath()); UIBreadcumbs uiBreadcumbs = uiOneTaxonomySelector.getChildById("BreadcumbOneTaxonomy"); uiBreadcumbs.getPath().clear(); UITreeTaxonomyBuilder uiTreeJCRExplorer = uiOneTaxonomySelector.getChild(UITreeTaxonomyBuilder.class); try { uiTreeJCRExplorer.setRootTreeNode(uiTreeTaxonomyList.getRootNode(workspaceName, pathTaxonomy)); uiTreeJCRExplorer.buildTree(); } catch (AccessDeniedException ade) { UIFormSelectBox uiTaxonomyTree = uiTreeTaxonomyList.getUIFormSelectBox(TAXONOMY_TREE); List<SelectItemOption<String>> taxonomyTree = uiTaxonomyTree.getOptions(); if (taxonomyTree != null && taxonomyTree.size() > 0) uiTaxonomyTree.setValue(taxonomyTree.get(0).getValue()); uiApp.addMessage(new ApplicationMessage("UIWorkspaceList.msg.AccessDeniedException", null, ApplicationMessage.WARNING)); event.getRequestContext().addUIComponentToUpdateByAjax(uiTaxonomyTree.getParent()); return; } catch(Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } return; } } else { UIFormSelectBox uiTaxonomyTree = uiTreeTaxonomyList.getUIFormSelectBox(TAXONOMY_TREE); List<SelectItemOption<String>> taxonomyTree = uiTaxonomyTree.getOptions(); if (taxonomyTree != null && taxonomyTree.size() > 0) uiTaxonomyTree.setValue(taxonomyTree.get(0).getValue()); uiApp.addMessage(new ApplicationMessage("UITreeTaxonomyList.msg.NoChild", null, ApplicationMessage.WARNING)); return; } event.getRequestContext().addUIComponentToUpdateByAjax(uiOneTaxonomySelector); } } static public class AddRootNodeActionListener extends EventListener<UITreeTaxonomyList> { public void execute(Event<UITreeTaxonomyList> event) throws Exception { UITreeTaxonomyList uiTreeTaxonomyList = event.getSource(); String taxoTreeName = uiTreeTaxonomyList.getUIFormSelectBox(TAXONOMY_TREE).getValue(); UIOneTaxonomySelector uiTaxonomySelector = uiTreeTaxonomyList.getParent(); String returnField = ((UIBaseNodeTreeSelector) uiTaxonomySelector).getReturnFieldName(); ((UISelectable)((UIBaseNodeTreeSelector) uiTaxonomySelector).getSourceComponent()).doSelect(returnField, taxoTreeName) ; UIComponent uiComponent = uiTaxonomySelector.getParent(); if (uiComponent instanceof UIPopupWindow) { ((UIPopupWindow)uiComponent).setShow(false); ((UIPopupWindow)uiComponent).setRendered(false); event.getRequestContext().addUIComponentToUpdateByAjax(uiComponent); } UIComponent component = uiTaxonomySelector.getSourceComponent().getParent(); if (component != null) { event.getRequestContext().addUIComponentToUpdateByAjax(component); } } } }
9,693
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISelectTaxonomyPanel.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/tree/selectone/UISelectTaxonomyPanel.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.tree.selectone; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.ecm.webui.tree.UIBaseNodeTreeSelector; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPageIterator; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS * @author : Hoa.Pham * hoa.pham@exoplatform.com * Jun 23, 2008 */ @ComponentConfig( template = "classpath:groovy/ecm/webui/tree/selectone/UISelectPathPanel.gtmpl", events = { @EventConfig(listeners = UISelectTaxonomyPanel.SelectActionListener.class) } ) public class UISelectTaxonomyPanel extends UISelectPathPanel { private UIPageIterator uiPageIterator_ = null; private static String TAXONOMY_TREE = "taxonomyTree"; private String taxonomyTreePath = ""; public String getTaxonomyTreePath() { return taxonomyTreePath; } public void setTaxonomyTreePath(String taxonomyTreePath) { this.taxonomyTreePath = taxonomyTreePath; } public UISelectTaxonomyPanel() throws Exception { this.uiPageIterator_ = addChild(UIPageIterator.class, null, "UISelectPathIterate"); } public String getPathTaxonomy() throws Exception { NodeHierarchyCreator nodeHierarchyCreator = getApplicationComponent(NodeHierarchyCreator.class); return nodeHierarchyCreator.getJcrPath(BasePath.TAXONOMIES_TREE_STORAGE_PATH); } public String getDisplayName(Node node) throws RepositoryException { return getAncestorOfType(UIOneTaxonomySelector.class).getTaxonomyLabel(node); } static public class SelectActionListener extends EventListener<UISelectTaxonomyPanel> { public void execute(Event<UISelectTaxonomyPanel> event) throws Exception { UISelectTaxonomyPanel uiSelectPathPanel = event.getSource(); UIOneTaxonomySelector uiTaxonomySelector = uiSelectPathPanel.getParent(); UITreeTaxonomyList uiTreeList = uiTaxonomySelector.getChild(UITreeTaxonomyList.class); UIContainer uiTreeSelector = uiSelectPathPanel.getParent(); String value = event.getRequestContext().getRequestParameter(OBJECTID); String taxoTreeName = uiTreeList.getUIFormSelectBox(TAXONOMY_TREE).getValue(); Node taxoTreeNode = uiTaxonomySelector.getTaxoTreeNode(taxoTreeName); String taxoTreePath = taxoTreeNode.getPath(); value = value.replace(taxoTreePath, taxoTreeName); if (uiTreeSelector instanceof UIOneNodePathSelector) { if (!((UIOneNodePathSelector) uiTreeSelector).isDisable()) { StringBuffer sb = new StringBuffer(); sb.append(((UIOneNodePathSelector) uiTreeSelector).getWorkspaceName()) .append(":") .append(value); value = sb.toString(); } } String returnField = ((UIBaseNodeTreeSelector)uiTreeSelector).getReturnFieldName(); ((UISelectable)((UIBaseNodeTreeSelector)uiTreeSelector).getSourceComponent()).doSelect(returnField, value) ; if (uiTreeSelector instanceof UIOneNodePathSelector) { UIPopupWindow uiPopupWindow = uiTreeSelector.getAncestorOfType(UIPopupWindow.class); if (uiPopupWindow != null) { uiPopupWindow.setShow(false); uiPopupWindow.setRendered(false); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupWindow); } UIComponent component = ((UIOneNodePathSelector) uiTreeSelector).getSourceComponent().getParent(); if (component != null) { event.getRequestContext().addUIComponentToUpdateByAjax(component); return; } } if (uiTreeSelector instanceof UIOneTaxonomySelector) { UIPopupWindow uiPopupWindow = uiTreeSelector.getAncestorOfType(UIPopupWindow.class); UIComponent parentOfUITreeSelector = uiTreeSelector.getParent(); if ((parentOfUITreeSelector instanceof UIPopupWindow) || (uiPopupWindow != null && ((UIContainer)parentOfUITreeSelector).getChildren().size() == 1)) { uiPopupWindow.setShow(false); uiPopupWindow.setRendered(false); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupWindow); } UIComponent component = ((UIOneTaxonomySelector) uiTreeSelector).getSourceComponent().getParent(); if (component != null) { event.getRequestContext().addUIComponentToUpdateByAjax(component); } } } } }
5,692
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDriveContext.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/clouddrives/CloudDriveContext.java
/* * Copyright (C) 2003-2018 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.ecm.webui.clouddrives; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import org.json.JSONObject; import org.exoplatform.ecm.webui.presentation.UIBaseNodePresentation; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveException; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.clouddrives.CloudProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.web.application.JavascriptManager; import org.exoplatform.web.application.RequestContext; import org.exoplatform.web.application.RequireJS; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.core.UIComponent; /** * Initialize Cloud Drive support in portal request.<br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudDriveContext.java 00000 Oct 22, 2012 pnedonosko $ */ public class CloudDriveContext { /** The Constant JAVASCRIPT. */ protected static final String JAVASCRIPT = "CloudDriveContext_Javascript".intern(); /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(CloudDriveContext.class); /** The constant UIJCREXPLORER_CONTEXT_NODE. */ public static final String UIJCREXPLORER_CONTEXT_NODE = "UIJCRExplorer.contextNode"; /** * Initialize request with Cloud Drive support from given WebUI component. * * @param uiComponent {@link UIComponent} * @throws Exception the exception */ public static void init(UIComponent uiComponent) throws Exception { Node contextNode; // when in document explorer WebuiRequestContext reqContext = WebuiRequestContext.getCurrentInstance(); contextNode = (Node) reqContext.getAttribute(UIJCREXPLORER_CONTEXT_NODE); if (contextNode == null && uiComponent.getParent() instanceof UIBaseNodePresentation) { // when in social activity stream (file view) UIBaseNodePresentation docViewer = uiComponent.getParent(); contextNode = docViewer.getNode(); } if (contextNode != null) { // we store current node in the context init(WebuiRequestContext.getCurrentInstance(), contextNode.getSession().getWorkspace().getName(), contextNode.getPath()); } else { LOG.warn("Cannot find ancestor context node in component " + uiComponent + ", parent: " + uiComponent.getParent()); } } /** * Initialize request with Cloud Drive support (global settings only). * * @param requestContext the request context * @throws CloudDriveException the cloud drive exception */ public static void init(RequestContext requestContext) throws CloudDriveException { init(requestContext, null, null); } /** * Initialize request with Cloud Drive support for given JCR location and * {@link CloudProvider}. * * @param requestContext {@link RequestContext} * @param workspace {@link String} can be <code>null</code> * @param nodePath {@link String} can be <code>null</code> * @throws CloudDriveException if cannot auth url from the provider */ public static void init(RequestContext requestContext, String workspace, String nodePath) throws CloudDriveException { Object obj = requestContext.getAttribute(JAVASCRIPT); if (obj == null) { CloudDriveContext context = new CloudDriveContext(requestContext); CloudDriveService service = WCMCoreUtils.getService(CloudDriveService.class); // add all providers to let related UI works for already connected and // linked files for (CloudProvider provider : service.getProviders()) { context.addProvider(provider); } if (workspace != null && nodePath != null) { context.init(workspace, nodePath); } else { context.init(); } Map<String, String> contextMessages = messages.get(); if (contextMessages != null) { for (Map.Entry<String, String> msg : contextMessages.entrySet()) { context.showInfo(msg.getKey(), msg.getValue()); } contextMessages.clear(); } requestContext.setAttribute(JAVASCRIPT, context); } else if (CloudDriveContext.class.isAssignableFrom(obj.getClass())) { CloudDriveContext context = CloudDriveContext.class.cast(obj); if (!context.hasContextNode() && workspace != null && nodePath != null) { context.init(workspace, nodePath); } } } /** * Initialize already connected drives for a request and given JCR location. * This method assumes that request already initialized by * {@link #init(RequestContext, String, String)} method. * * @param requestContext {@link RequestContext} * @param parent {@link Node} * @return boolean <code>true</code> if nodes successfully initialized, * <code>false</code> if nodes already initialized * @throws RepositoryException the repository exception * @throws CloudDriveException the cloud drive exception * @see #init(RequestContext, String, String) */ public static boolean initConnected(RequestContext requestContext, Node parent) throws RepositoryException, CloudDriveException { Object obj = requestContext.getAttribute(JAVASCRIPT); if (obj != null) { CloudDriveContext context = (CloudDriveContext) obj; context.addConnected(parent.getNodes()); return true; } else { if (LOG.isDebugEnabled()) { LOG.debug("Context not initialized for adding of drive nodes."); } return false; } } /** * Show info notification to the user. * * @param requestContext the request context * @param title {@link String} * @param message {@link String} * @throws RepositoryException the repository exception * @throws CloudDriveException the cloud drive exception */ public static void showInfo(RequestContext requestContext, String title, String message) throws RepositoryException, CloudDriveException { Object obj = requestContext.getAttribute(JAVASCRIPT); if (obj != null) { CloudDriveContext context = (CloudDriveContext) obj; context.showInfo(title, message); } else { // store the message in thread local if (LOG.isDebugEnabled()) { LOG.debug("Context not initialized. Adding info message to local cache."); } Map<String, String> contextMessages = messages.get(); if (contextMessages == null) { contextMessages = new LinkedHashMap<String, String>(); messages.set(contextMessages); } contextMessages.put(title, message); } } // static variables /** The Constant messages. */ private final static ThreadLocal<Map<String, String>> messages = new ThreadLocal<Map<String, String>>(); // instance methods /** The require. */ private final RequireJS require; /** The nodes. */ private final Set<String> nodes = new HashSet<String>(); /** The providers. */ private final Set<String> providers = new HashSet<String>(); private boolean hasContextNode; /** * Internal constructor. * * @param requestContext {@link RequestContext} */ private CloudDriveContext(RequestContext requestContext) { JavascriptManager js = ((WebuiRequestContext) requestContext).getJavascriptManager(); this.require = js.require("SHARED/cloudDriveDocuments", "cloudDriveDocuments"); this.hasContextNode = false; } /** * Inits the only global context. * * @return the cloud drive context */ private CloudDriveContext init() { require.addScripts("\ncloudDriveDocuments.init();\n"); return this; } /** * Inits the context with a node. * * @param workspace the workspace * @param nodePath the node path * @return the cloud drive context */ private CloudDriveContext init(String workspace, String nodePath) { require.addScripts("\ncloudDriveDocuments.init('" + workspace + "','" + nodePath + "');\n"); hasContextNode = true; return this; } /** * Checks for context node. * * @return true, if successful */ private boolean hasContextNode() { return hasContextNode; } /** * Adds the connected. * * @param nodes the nodes * @return the cloud drive context * @throws CloudDriveException the cloud drive exception * @throws RepositoryException the repository exception */ private CloudDriveContext addConnected(NodeIterator nodes) throws CloudDriveException, RepositoryException { if (nodes.hasNext()) { CloudDriveService driveService = WCMCoreUtils.getService(CloudDriveService.class); StringBuilder map = new StringBuilder(); // we construct JSON object on the fly map.append('{'); int count = 0; while (nodes.hasNext()) { Node child = nodes.nextNode(); CloudDrive drive = driveService.findDrive(child); if (drive != null) { String title = child.getProperty("exo:title").getString(); if (!this.nodes.contains(title)) { map.append('"'); map.append(title); // exo:title required for js side map.append("\":\""); map.append(drive.getUser().getProvider().getId()); map.append("\","); count++; this.nodes.add(title); } } } if (count >= 1) { map.deleteCharAt(map.length() - 1); // remove last semicolon map.append('}'); // we already "required" cloudDrive as AMD dependency in init() require.addScripts("\ncloudDriveDocuments.initConnected(" + map.toString() + ");\n"); } } return this; } /** * Adds the provider. * * @param provider the provider * @return the cloud drive context * @throws CloudDriveException the cloud drive exception */ private CloudDriveContext addProvider(CloudProvider provider) throws CloudDriveException { String id = provider.getId(); if (!providers.contains(id)) { // if provider cannot be converted to JSON then null will be String providerJson = new JSONObject(provider).toString(); if (providerJson != null) { require.addScripts("\ncloudDriveDocuments.initProvider('" + id + "', " + providerJson.toString() + ");\n"); providers.add(id); } else { LOG.error("Error converting cloud provider (" + provider.getName() + ") to JSON object (null)."); } } return this; } /** * Show info. * * @param title the title * @param text the text * @return the cloud drive context */ private CloudDriveContext showInfo(String title, String text) { require.addScripts("\ncloudDriveDocuments.showInfo('" + title + "','" + text + "');\n"); return this; } }
12,232
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DateComparator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/comparator/DateComparator.java
/* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.comparator; import java.util.Calendar; import java.util.Comparator; import javax.jcr.Node; import org.exoplatform.services.wcm.core.NodetypeConstant; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Jan 9, 2013 */ public class DateComparator implements Comparator<Node>{ public static final String ASCENDING_ORDER = "Ascending" ; public static final String DESCENDING_ORDER = "Descending" ; private String order_ ; public DateComparator(String pOrder) { order_ = pOrder ; } public int compare(Node node1, Node node2) { try{ Calendar date1 = node1.hasProperty(NodetypeConstant.EXO_DATE_MODIFIED) ? node1.getProperty(NodetypeConstant.EXO_DATE_MODIFIED).getDate() : node1.getProperty(NodetypeConstant.EXO_DATE_CREATED).getDate(); Calendar date2 = node2.hasProperty(NodetypeConstant.EXO_DATE_MODIFIED) ? node2.getProperty(NodetypeConstant.EXO_DATE_MODIFIED).getDate() : node2.getProperty(NodetypeConstant.EXO_DATE_CREATED).getDate(); if(order_.equals(ASCENDING_ORDER)) { return date1.compareTo(date2) ; } return date2.compareTo(date1) ; }catch (Exception e) { return 0; } } }
2,080
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
NodeSizeComparator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/comparator/NodeSizeComparator.java
/* * Copyright (C) 2003-2012 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.comparator; import java.util.Comparator; import javax.jcr.Node; /** * Created by The eXo Platform SAS * Author : eXoPlatform * vinh_nguyen@exoplatform.com * 8 May 2012 */ public class NodeSizeComparator implements Comparator<Node> { public static final String ASCENDING_ORDER = "Ascending" ; private String order_ ; public NodeSizeComparator(String pOrder) { order_ = pOrder ; } public int compare(Node node1, Node node2) { try{ long sizeNode1 = getSize(node1); long sizeNode2 = getSize(node2); if (sizeNode1 == sizeNode2) return 0; if(order_.equals(ASCENDING_ORDER)) { return sizeNode1 < sizeNode2 ? -1 : 1; } return sizeNode1 < sizeNode2 ? 1 : -1; }catch (Exception e) { return 0; } } private long getSize(Node node) { try { return node.getProperty("jcr:content/jcr:data").getLength(); } catch (Exception e) { return 0; } } }
1,714
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ItemOptionNameComparator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/comparator/ItemOptionNameComparator.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.comparator; import java.util.Comparator; import org.exoplatform.webui.core.model.SelectItemOption; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Sep 15, 2008 10:05:19 AM */ public class ItemOptionNameComparator implements Comparator<SelectItemOption> { public int compare(SelectItemOption o1, SelectItemOption o2) throws ClassCastException { try { String name1 = o1.getLabel().toString() ; String name2 = o2.getLabel().toString() ; return name1.compareToIgnoreCase(name2) ; } catch(Exception e) { return 0; } } }
1,401
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
NodeOwnerComparator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/comparator/NodeOwnerComparator.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.comparator; import java.util.Comparator; import javax.jcr.Node; import javax.jcr.RepositoryException; public class NodeOwnerComparator implements Comparator<Node> { public static final String ASCENDING_ORDER = "Ascending" ; public static final String DESCENDING_ORDER = "Descending" ; private String order_ ; public NodeOwnerComparator(String pOrder) { order_ = pOrder ; } public int compare(Node node1, Node node2) { try{ String nodeOwner1 = node1.getName(); String nodeOwner2 = node2.getName(); if(order_.equals(ASCENDING_ORDER)) { return nodeOwner1.compareToIgnoreCase(nodeOwner2) ; } return nodeOwner2.compareToIgnoreCase(nodeOwner1) ; }catch (RepositoryException e) { return 0; } } }
1,510
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
NodeNameComparator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/comparator/NodeNameComparator.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.comparator; import java.util.Comparator; import javax.jcr.Node; public class NodeNameComparator implements Comparator<Node> { public static final String ASCENDING_ORDER = "Ascending" ; public static final String DESCENDING_ORDER = "Descending" ; private String order_ ; public NodeNameComparator(String pOrder) { order_ = pOrder ; } public int compare(Node node1, Node node2) { try{ String nodeName1 = node1.getName(); String nodeName2 = node2.getName(); if(order_.equals(ASCENDING_ORDER)) { return nodeName1.compareToIgnoreCase(nodeName2) ; } return nodeName2.compareToIgnoreCase(nodeName1) ; }catch (Exception e) { return 0; } } }
1,477
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
StringComparator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/comparator/StringComparator.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.comparator; import java.util.Comparator; import javax.jcr.Node; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.jcr.ext.audit.AuditHistory; import org.exoplatform.services.jcr.ext.audit.AuditService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Created by The eXo Platform SARL * Author : Ly Dinh Quang * quang.ly@exoplatform.com * xxx5669@gmail.com * Jan 20, 2009 */ public class StringComparator implements Comparator<Node> { public static final String ASCENDING_ORDER = "Ascending" ; public static final String DESCENDING_ORDER = "Descending" ; private String order_; private String type_ ; private static final Log LOG = ExoLogger.getLogger(StringComparator.class.getName()); public StringComparator(String order, String type) { this.order_ = order ; this.type_ = type; } private String getVersionName(Node node) throws Exception { return node.getBaseVersion().getName() ; } private String versionName(Node node) throws Exception { String returnString = ""; returnString = String.valueOf(Utils.isVersionable(node)); if (Utils.isVersionable(node) && !getVersionName(node).equals("jcr:rootVersion")) { returnString = "(" + getVersionName(node) + ")" ; } return returnString; } private boolean hasAuditHistory(Node node) throws Exception{ AuditService auServ = WCMCoreUtils.getService(AuditService.class); return auServ.hasHistory(node); } private int getNumAuditHistory(Node node) throws Exception{ AuditService auServ = WCMCoreUtils.getService(AuditService.class); if (auServ.hasHistory(node)) { AuditHistory auHistory = auServ.getHistory(node); return (auHistory.getAuditRecords()).size(); } return 0; } private String getAuditing(Node node) throws Exception { String returnString = ""; returnString = String.valueOf(Utils.isAuditable(node)); if (Utils.isAuditable(node)&& hasAuditHistory(node)) { returnString = "(" + getNumAuditHistory(node) + ")"; } return returnString; } private int compare(String s1, String s2) { if (ASCENDING_ORDER.equals(order_)) { return s1.compareTo(s2) ; } return s2.compareTo(s1) ; } public int compare(Node node1, Node node2) { int returnCompare = 0; try { if (type_.equals("Owner")) { if (node1.hasProperty("exo:owner") && node2.hasProperty("exo:owner")) { String owner1 = node1.getProperty("exo:owner").getString(); String owner2 = node2.getProperty("exo:owner").getString(); returnCompare = compare(owner1, owner2); } } else if (type_.equals("Versionable")) { String versionNode1 = versionName(node1); String versionNode2 = versionName(node2); returnCompare = compare(versionNode1, versionNode2); } else if (type_.equals("Auditing")) { String auditing1 = getAuditing(node1); String auditing2 = getAuditing(node2); returnCompare = compare(auditing1, auditing2); } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } return returnCompare; } }
4,165
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
NodeTitleComparator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/comparator/NodeTitleComparator.java
/* * Copyright (C) 2003-2012 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.comparator; import java.util.Comparator; import javax.jcr.Node; import org.exoplatform.ecm.webui.utils.Utils; /** * Created by The eXo Platform SAS * Author : eXoPlatform * vinh_nguyen@exoplatform.com * 8 May 2012 */ public class NodeTitleComparator implements Comparator<Node> { public static final String ASCENDING_ORDER = "Ascending" ; private String order_ ; public NodeTitleComparator(String pOrder) { order_ = pOrder ; } public int compare(Node node1, Node node2) { try{ String titleNode1 = Utils.getTitle(node1); String titleNode2 = Utils.getTitle(node2); if(order_.equals(ASCENDING_ORDER)) { return titleNode1.compareToIgnoreCase(titleNode2) ; } return titleNode2.compareToIgnoreCase(titleNode1) ; }catch (Exception e) { return 0; } } }
1,595
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PropertyValueComparator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/comparator/PropertyValueComparator.java
/*************************************************************************** * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. * **************************************************************************/ package org.exoplatform.ecm.webui.comparator; /** * Created by The eXo Platform SARL Author : Hoang Van Hung hunghvit@gmail.com * Mar 8, 2009 * This class is the same as org.exoplatform.ecm.utils.comparator.PropertyValueComparator<br> * but it is kept for the compatible purpose. */ public class PropertyValueComparator extends org.exoplatform.ecm.utils.comparator.PropertyValueComparator { public PropertyValueComparator(String propertyName, String orderType) { super(propertyName, orderType); } }
1,405
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PermissionUtil.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/utils/PermissionUtil.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.utils; /** * The Class PermissionUtil use to check permission for a node */ public class PermissionUtil extends org.exoplatform.ecm.utils.permission.PermissionUtil { }
938
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
JCRExceptionManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/utils/JCRExceptionManager.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.utils; import java.security.AccessControlException; import javax.jcr.AccessDeniedException; import javax.jcr.InvalidItemStateException; import javax.jcr.InvalidSerializedDataException; import javax.jcr.ItemExistsException; import javax.jcr.ItemNotFoundException; import javax.jcr.LoginException; import javax.jcr.NoSuchWorkspaceException; import javax.jcr.PathNotFoundException; import javax.jcr.ReferentialIntegrityException; import javax.jcr.RepositoryException; import javax.jcr.UnsupportedRepositoryOperationException; import javax.jcr.ValueFormatException; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.version.VersionException; import org.exoplatform.services.log.Log; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.exception.MessageException; /** * Created by The eXo Platform SARL Author : Dang Van Minh * minh.dang@exoplatform.com May 8, 2008 3:18:06 PM */ public class JCRExceptionManager { /** * Logger. */ private static final Log LOG = ExoLogger.getLogger(JCRExceptionManager.class.getName()); /** * Process. * * @param uiApp the ui app * @param e the e * @param messageKey the message key * @throws Exception the exception */ public static void process(UIApplication uiApp,Exception e,String messageKey) throws Exception{ if (LOG.isErrorEnabled()) { LOG.error("The following error occurs : " + e); } if(e instanceof LoginException) { if(messageKey == null) messageKey = "LoginException.msg"; } else if(e instanceof AccessDeniedException) { if(messageKey == null) messageKey = "AccessDeniedException.msg"; } else if(e instanceof NoSuchWorkspaceException) { if(messageKey == null) messageKey = "NoSuchWorkspaceException.msg"; } else if(e instanceof ItemNotFoundException) { if(messageKey == null) messageKey = "ItemNotFoundException.msg"; } else if(e instanceof ItemExistsException) { if(messageKey == null) messageKey = "ItemExistsException.msg"; } else if(e instanceof ConstraintViolationException) { if(messageKey == null) messageKey = "ConstraintViolationException.msg"; } else if(e instanceof InvalidItemStateException) { if(messageKey == null) messageKey = "InvalidItemStateException.msg"; } else if(e instanceof ReferentialIntegrityException) { if(messageKey == null) messageKey = "ReferentialIntegrityException.msg"; } else if(e instanceof LockException) { if(messageKey == null) messageKey = "LockException.msg"; } else if(e instanceof NoSuchNodeTypeException) { if(messageKey == null) messageKey = "NoSuchNodeTypeException.msg"; } else if(e instanceof VersionException) { if(messageKey == null) messageKey = "VersionException.msg"; } else if(e instanceof PathNotFoundException) { if(messageKey == null) messageKey = "PathNotFoundException.msg"; } else if(e instanceof ValueFormatException) { if(messageKey == null) messageKey = "ValueFormatException.msg"; } else if(e instanceof InvalidSerializedDataException) { if(messageKey == null) messageKey = "InvalidSerializedDataException.msg"; } else if(e instanceof RepositoryException) { if(messageKey == null) messageKey = "RepositoryException.msg"; } else if(e instanceof AccessControlException) { if(messageKey == null) messageKey = "AccessControlException.msg"; } else if(e instanceof UnsupportedRepositoryOperationException) { if(messageKey == null) messageKey = "UnsupportedRepositoryOperationException.msg"; } else if(e instanceof MessageException) { if(messageKey == null) messageKey = ((MessageException)e).getDetailMessage().getMessageKey(); } else { throw e; } uiApp.addMessage(new ApplicationMessage(messageKey, null, ApplicationMessage.WARNING)); } /** * Process. * * @param uiApp the ui app * @param e the e * @throws Exception the exception */ public static void process(UIApplication uiApp, Exception e) throws Exception { process(uiApp,e,null) ; } }
5,223
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DialogFormUtil.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/utils/DialogFormUtil.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.utils; import java.io.InputStream; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.Property; import javax.jcr.PropertyType; import org.apache.commons.lang3.StringEscapeUtils; import org.exoplatform.commons.utils.HTMLSanitizer; import org.exoplatform.commons.utils.IOUtil; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.ecm.webui.form.UIDialogForm; import org.exoplatform.ecm.webui.form.UIFormUploadInputNoUploadButton; import org.exoplatform.ecm.webui.form.validator.CategoryValidator; import org.exoplatform.ecm.webui.form.validator.CronExpressionValidator; import org.exoplatform.ecm.webui.form.validator.DateValidator; import org.exoplatform.ecm.webui.form.validator.ECMNameValidator; import org.exoplatform.ecm.webui.form.validator.PhoneFormatValidator; import org.exoplatform.ecm.webui.form.validator.RepeatCountValidator; import org.exoplatform.ecm.webui.form.validator.RepeatIntervalValidator; import org.exoplatform.ecm.webui.form.validator.XSSValidator; import org.exoplatform.services.cms.JcrInputProperty; import org.exoplatform.upload.UploadResource; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.form.UIFormDateTimeInput; import org.exoplatform.webui.form.UIFormInputBase; import org.exoplatform.webui.form.UIFormMultiValueInputSet; import org.exoplatform.webui.form.UIFormSelectBox; import org.exoplatform.webui.form.input.UICheckBoxInput; import org.exoplatform.webui.form.input.UIUploadInput; import org.exoplatform.webui.form.validator.DateTimeValidator; import org.exoplatform.webui.form.validator.DoubleFormatValidator; import org.exoplatform.webui.form.validator.EmailAddressValidator; import org.exoplatform.webui.form.validator.MandatoryValidator; import org.exoplatform.webui.form.validator.NullFieldValidator; import org.exoplatform.webui.form.validator.NumberFormatValidator; import org.exoplatform.webui.form.validator.StringLengthValidator; /* * Created by The eXo Platform SAS * @author : Hoa.Pham * hoa.pham@exoplatform.com * Jun 23, 2008 */ /** * The Class DialogFormUtil. */ public class DialogFormUtil { public static String VALIDATOR_PARAM_BEGIN = "("; public static String VALIDATOR_PARAM_END = ")"; public static String VALIDATOR_PARAM_SEPERATOR = ";"; public static String SANITIZATION_FLAG = "noSanitization"; /** * Type of parameters which were passed for the validator TODO: Please add all * the possible type here and parser it in side the function * parserValidatorParam. If any question, ask for VinhNT from Content's team. */ public static String TYPE_FLOAT = "Float"; public static String TYPE_DOUBLE = "Double"; public static String TYPE_INTEGER = "Int"; public static String TYPE_STRING = "String"; /** * Prepare map. * * @param inputs the inputs * @param properties the properties * @return the map of string and jcr input property * @throws Exception the exception */ public static Map<String, JcrInputProperty> prepareMap(List inputs, Map properties) throws Exception { return prepareMap(inputs, properties, null); } @SuppressWarnings("unchecked") public static Map<String, JcrInputProperty> prepareMap(List inputs, Map properties, Map options) throws Exception { Map<String, String> changeInJcrPathParamMap = new HashMap<String, String>(); Map<String, JcrInputProperty> rawinputs = new HashMap<String, JcrInputProperty>(); HashMap<String, JcrInputProperty> hasMap = new HashMap<String, JcrInputProperty>(); String inputName = null; String mimeTypeJcrPath = null; InputStream inputStream = null; Map<String, JcrInputProperty> mimeTypes = new HashMap<String, JcrInputProperty>(); for (int i = 0; i < inputs.size(); i++) { JcrInputProperty property = null; String option = null; if (inputs.get(i) instanceof UIFormMultiValueInputSet) { UIFormMultiValueInputSet inputI = (UIFormMultiValueInputSet) inputs.get(i); inputName = (inputI).getName(); if (!hasMap.containsKey(inputName)) { List<UIComponent> inputChild = inputI.getChildren(); property = (JcrInputProperty) properties.get(inputName); if (inputChild != null && inputChild.size() > 0 && inputChild.get(0) instanceof UIUploadInput) { Map<String, List> uploadDataMap = new TreeMap<String, List>(); for (UIComponent child : inputChild) { UIUploadInput uploadInput = (UIUploadInput) child; String uploadId = uploadInput.getUploadIds()[0]; String uploadDataName = null; String uploadMimeType = null; byte[] uploadData = null; if (uploadInput instanceof UIFormUploadInputNoUploadButton) { uploadDataName = ((UIFormUploadInputNoUploadButton) uploadInput).getFileName(); uploadMimeType = ((UIFormUploadInputNoUploadButton) uploadInput).getMimeType(); uploadData = ((UIFormUploadInputNoUploadButton) uploadInput).getByteValue(); } else { UploadResource uploadResource = (uploadInput).getUploadResource(uploadId); if (uploadResource != null) { String location = uploadResource.getStoreLocation(); uploadDataName = uploadResource.getFileName(); uploadData = IOUtil.getFileContentAsBytes(location); uploadMimeType = uploadResource.getMimeType(); } } if (uploadDataName != null && uploadData != null) { List<Object> data = new ArrayList<Object>(); data.add(uploadMimeType); data.add(uploadData); if (!uploadDataMap.containsKey(uploadDataName)) { uploadDataMap.put(uploadDataName, data); } else { int count = 1; while (uploadDataMap.containsKey(uploadDataName + count)) { count++; } uploadDataMap.put(uploadDataName + count, data); } } } property.setValue(uploadDataMap); } else { List<String> values = (List<String>) (inputI).getValue(); if (property != null) { property.setValue(values.toArray(new String[values.size()])); } } } hasMap.put(inputName, property); } else { UIFormInputBase input = (UIFormInputBase) inputs.get(i); property = (JcrInputProperty) properties.get(input.getName()); if (options != null && options.get(input.getName()) != null) option = (String) options.get(input.getName()); if (property != null) { if (input instanceof UIUploadInput) { String uploadId = ((UIUploadInput) input).getUploadIds()[0]; UploadResource uploadResource = ((UIUploadInput) input).getUploadResource(uploadId); if (uploadResource == null) { if (property.getChangeInJcrPathParam() != null) changeInJcrPathParamMap.put(property.getChangeInJcrPathParam(), ""); continue; } String location = uploadResource.getStoreLocation(); byte[] uploadData = IOUtil.getFileContentAsBytes(location); property.setValue(uploadData); // change param in jcr path if (property.getChangeInJcrPathParam() != null) changeInJcrPathParamMap.put(property.getChangeInJcrPathParam(), Text.escapeIllegalJcrChars(uploadResource.getFileName())); mimeTypeJcrPath = property.getJcrPath().replace("jcr:data", "jcr:mimeType"); JcrInputProperty mimeTypeInputPropertyTmp = new JcrInputProperty(); mimeTypeInputPropertyTmp.setJcrPath(mimeTypeJcrPath); mimeTypeInputPropertyTmp.setValue(((UIUploadInput) input).getUploadResource(uploadId).getMimeType()); mimeTypes.put(mimeTypeJcrPath, mimeTypeInputPropertyTmp); } else if (input instanceof UIFormDateTimeInput) { property.setValue(((UIFormDateTimeInput) input).getCalendar()); } else if (input instanceof UIFormSelectBox) { UIFormSelectBox uiSelectBox = (UIFormSelectBox) input; if (!uiSelectBox.isMultiple()) { property.setValue(uiSelectBox.getValue()); } else { property.setValue(uiSelectBox.getSelectedValues()); } } else if (input instanceof UICheckBoxInput) { property.setValue(((UICheckBoxInput) input).isChecked()); } else { if (input.getValue() != null) { String inputValue = input.getValue().toString().trim(); boolean isEmpty = Utils.isEmptyContent(inputValue); if (isEmpty) inputValue = ""; else if (option == null || option.indexOf(SANITIZATION_FLAG) < 0) { inputValue = HTMLSanitizer.sanitize(inputValue); inputValue = StringEscapeUtils.unescapeHtml4(inputValue); } if (input.getName().equals("name") && input.getAncestorOfType(UIDialogForm.class).isAddNew()) { JcrInputProperty titleInputProperty = (JcrInputProperty) properties.get("title"); if(titleInputProperty == null) { JcrInputProperty jcrExoTitle = new JcrInputProperty(); jcrExoTitle.setJcrPath("/node/exo:title"); jcrExoTitle.setValue(inputValue); properties.put("/node/exo:title", jcrExoTitle); } else if(titleInputProperty.getValue() == null){ JcrInputProperty jcrExoTitle = new JcrInputProperty(); jcrExoTitle.setJcrPath(titleInputProperty.getJcrPath()); jcrExoTitle.setValue(inputValue); properties.put("title", jcrExoTitle); } property.setValue(Text.escapeIllegalJcrChars(inputValue)); } else { property.setValue(inputValue); } } else { // The is already setted in the previous block, thus it needs to be skipped here. if (input.getName() == "title") continue; property.setValue(input.getValue()); } } } } } Iterator iter = properties.values().iterator(); JcrInputProperty property; while (iter.hasNext()) { property = (JcrInputProperty) iter.next(); rawinputs.put(property.getJcrPath(), property); } for (String jcrPath : mimeTypes.keySet()) { if (!rawinputs.containsKey(jcrPath)) { rawinputs.put(jcrPath, mimeTypes.get(jcrPath)); } } List<UIUploadInput> formUploadList = new ArrayList<UIUploadInput>(); for (Object input : inputs) { if (input instanceof UIFormMultiValueInputSet) { UIFormMultiValueInputSet uiSet = (UIFormMultiValueInputSet) input; if (uiSet.getId() != null && uiSet.getUIFormInputBase().equals(UIUploadInput.class) && uiSet.getId().equals("attachment__")) { List<UIComponent> list = uiSet.getChildren(); for (UIComponent component : list) { if (!formUploadList.contains(component)) formUploadList.add((UIUploadInput) component); } } } else if (input instanceof UIUploadInput) { if (!formUploadList.contains(input)) formUploadList.add((UIUploadInput) input); } } if (formUploadList.size() > 0) { List<String> keyListToRemove = new ArrayList<String>(); Map<String, JcrInputProperty> jcrPropertiesToAdd = new HashMap<String, JcrInputProperty>(); for (Object inputJCRKeyTmp : rawinputs.keySet()) { String inputJCRKey = (String) inputJCRKeyTmp; if (inputJCRKey.contains("attachment__")) { JcrInputProperty jcrInputProperty = rawinputs.get(inputJCRKey); for (UIUploadInput uploadInput : formUploadList) { String uploadId = uploadInput.getUploadIds()[0]; JcrInputProperty newJcrInputProperty = clone(jcrInputProperty); if (uploadInput == null || uploadInput.getUploadResource(uploadId) == null || uploadInput.getUploadResource(uploadId).getFileName() == null) continue; String fileName = uploadInput.getUploadResource(uploadId).getFileName(); String newJCRPath = inputJCRKey.replace("attachment__", fileName); newJcrInputProperty.setJcrPath(newJCRPath); if (inputJCRKey.endsWith("attachment__")) { newJcrInputProperty.setValue(fileName); JcrInputProperty mimeTypeInputPropertyTmp = new JcrInputProperty(); mimeTypeInputPropertyTmp.setJcrPath(newJCRPath + "/jcr:content/jcr:mimeType"); mimeTypeInputPropertyTmp.setValue(uploadInput.getUploadResource(uploadId).getMimeType()); jcrPropertiesToAdd.put(mimeTypeInputPropertyTmp.getJcrPath(), mimeTypeInputPropertyTmp); } if (inputJCRKey.endsWith("jcr:data")) { inputStream = uploadInput.getUploadDataAsStream(uploadId); newJcrInputProperty.setValue(inputStream); } jcrPropertiesToAdd.put(newJCRPath, newJcrInputProperty); } keyListToRemove.add(inputJCRKey); keyListToRemove.add(inputJCRKey.replace("jcr:data", "jcr:mimeType")); } } for (String keyToRemove : keyListToRemove) { rawinputs.remove(keyToRemove); } rawinputs.putAll(jcrPropertiesToAdd); } if (changeInJcrPathParamMap.isEmpty()) { return rawinputs; } Map<String, JcrInputProperty> ret = new HashMap<String, JcrInputProperty>(); Set<String> removedKeys = new HashSet<String>(); for (Map.Entry<String, String> changeEntry : changeInJcrPathParamMap.entrySet()) { for (Map.Entry<String, JcrInputProperty> entry : rawinputs.entrySet()) { if (entry.getKey().contains(changeEntry.getKey())) { removedKeys.add(entry.getKey()); JcrInputProperty value = entry.getValue(); if (value.getJcrPath() != null) { value.setJcrPath(value.getJcrPath().replace(changeEntry.getKey(), changeEntry.getValue())); } if (value.getValue() != null && value.getValue() instanceof String) { value.setValue(((String) value.getValue()).replace(changeEntry.getKey(), changeEntry.getValue())); } if (value != null && !"".equals(value) && changeEntry.getValue() != null && !"".equals(changeEntry.getValue())) { ret.put(entry.getKey().replace(changeEntry.getKey(), changeEntry.getValue()), value); } } } } for (Map.Entry<String, JcrInputProperty> entry : rawinputs.entrySet()) { if (!removedKeys.contains(entry.getKey())) { ret.put(entry.getKey(), entry.getValue()); } } return ret; } private static JcrInputProperty clone(JcrInputProperty fileNodeInputProperty) { JcrInputProperty jcrInputProperty = new JcrInputProperty(); jcrInputProperty.setJcrPath(fileNodeInputProperty.getJcrPath()); jcrInputProperty.setMixintype(fileNodeInputProperty.getMixintype()); jcrInputProperty.setNodetype(fileNodeInputProperty.getNodetype()); jcrInputProperty.setType(fileNodeInputProperty.getType()); jcrInputProperty.setValue(fileNodeInputProperty.getValue()); jcrInputProperty.setValueType(fileNodeInputProperty.getValueType()); return jcrInputProperty; } /** * Creates the form input. * * @param type the type * @param name the name * @param label the label * @param validateType the validate type * @param valueType the value type * @return the t * @throws Exception the exception */ public static <T extends UIFormInputBase> T createFormInput(Class<T> type, String name, String label, String validateType, Class valueType) throws Exception { Object[] args = { name, null, valueType }; UIFormInputBase formInput = type.getConstructor().newInstance(args); addValidators(formInput, validateType); if (label != null && label.length() != 0) { formInput.setLabel(label); } return type.cast(formInput); } /** * Gets the property value as string. * * @param node the node * @param propertyName the property name * @return the property value as string * @throws Exception the exception */ public static String getPropertyValueAsString(Node node, String propertyName) throws Exception { Property property = null; try { property = node.getProperty(propertyName); } catch (PathNotFoundException e) { return ""; } int valueType = property.getType(); switch (valueType) { case PropertyType.STRING: // String return property.getString(); case PropertyType.LONG: // Long return Long.toString(property.getLong()); case PropertyType.DOUBLE: // Double return Double.toString(property.getDouble()); case PropertyType.DATE: // Date return property.getDate().getTime().toString(); case PropertyType.BOOLEAN: // Boolean return Boolean.toString(property.getBoolean()); case PropertyType.NAME: // Name return property.getName(); case 8: // Path case 9: // References case 0: // Undifine } return ""; } public static Class getValidator(String validatorType) throws ClassNotFoundException { if (validatorType.equals("name")) { return ECMNameValidator.class; } else if (validatorType.equals("email")) { return EmailAddressValidator.class; } else if (validatorType.equals("number")) { return NumberFormatValidator.class; } else if (validatorType.equals("double")) { return DoubleFormatValidator.class; } else if (validatorType.equals("empty")) { return MandatoryValidator.class; } else if (validatorType.equals("null")) { return NullFieldValidator.class; } else if (validatorType.equals("datetime")) { return DateTimeValidator.class; } else if (validatorType.equals("date")) { return DateValidator.class; } else if (validatorType.equals("cronExpressionValidator")) { return CronExpressionValidator.class; } else if (validatorType.equals("repeatCountValidator")) { return RepeatCountValidator.class; } else if (validatorType.equals("repeatIntervalValidator")) { return RepeatIntervalValidator.class; } else if (validatorType.equals("length")) { return StringLengthValidator.class; } else if (validatorType.equals("category")) { return CategoryValidator.class; } else if (validatorType.equals("XSSValidator")) { return XSSValidator.class; } else if (validatorType.equals("phone")) { return PhoneFormatValidator.class; } else { ClassLoader cl = Thread.currentThread().getContextClassLoader(); return cl.loadClass(validatorType); } } @SuppressWarnings("unchecked") public static void addValidators(UIFormInputBase uiInput, String validators) throws Exception { String[] validatorList = null; if (validators.indexOf(',') > -1) validatorList = validators.split(","); else validatorList = new String[] { validators }; for (String validator : validatorList) { Object[] params; String s_param = null; int p_begin, p_end; p_begin = validator.indexOf(VALIDATOR_PARAM_BEGIN); p_end = validator.indexOf(VALIDATOR_PARAM_END); if (p_begin > 0 && p_end > p_begin) { String v_name; s_param = validator.substring(p_begin + 1, p_end); params = s_param.split(VALIDATOR_PARAM_SEPERATOR); params = parserValidatorParam(params, params.length - 1, params[params.length - 1].toString()); v_name = validator.substring(0, p_begin); uiInput.addValidator(getValidator(v_name.trim()), params); } else { uiInput.addValidator(getValidator(validator.trim())); } } } /** * @param params * @param length * @param type * @return the conversion of the input parameters with the new type. * @throws Exception */ public static Object[] parserValidatorParam(Object[] params, int length, String type) throws Exception { int i; Object[] newParams; if (length < 1) return params; newParams = new Object[length]; if (type.equalsIgnoreCase(TYPE_INTEGER)) { for (i = 0; i < length; i++) newParams[i] = Integer.parseInt(params[i].toString()); } else if (type.equalsIgnoreCase(TYPE_FLOAT)) { for (i = 0; i < length; i++) newParams[i] = Float.parseFloat(params[i].toString()); } else if (type.equalsIgnoreCase(TYPE_DOUBLE)) { for (i = 0; i < length; i++) newParams[i] = Double.parseDouble(params[i].toString()); } else return params;// Do not convert, let those parameters are the Objec type return newParams; } }
23,030
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
Utils.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/utils/Utils.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.utils; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.security.AccessControlException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.Optional; import java.util.ResourceBundle; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipInputStream; import javax.imageio.ImageIO; import javax.jcr.ItemNotFoundException; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import javax.jcr.nodetype.NodeDefinition; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeManager; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.api.settings.SettingService; import org.exoplatform.commons.api.settings.SettingValue; import org.exoplatform.commons.api.settings.data.Context; import org.exoplatform.commons.api.settings.data.Scope; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.commons.utils.HTMLSanitizer; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.definition.PortalContainerConfig; import org.exoplatform.container.xml.PortalContainerInfo; import org.exoplatform.download.DownloadService; import org.exoplatform.download.InputStreamDownloadResource; import org.exoplatform.ecm.webui.form.UIOpenDocumentForm; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.documents.TrashService; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.cms.thumbnail.ThumbnailService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.jcr.impl.Constants; import org.exoplatform.services.jcr.impl.core.NodeImpl; import org.exoplatform.services.jcr.impl.core.nodetype.NodeTypeImpl; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.resources.ResourceBundleService; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.Identity; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.reader.ContentReader; import org.exoplatform.web.application.RequestContext; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.ext.UIExtension; import org.exoplatform.webui.ext.UIExtensionManager; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; /** * Created by The eXo Platform SARL Author : Dang Van Minh * minh.dang@exoplatform.com May 8, 2008 3:13:32 PM */ public class Utils { final public static String WORKSPACE_NAME = "workspace"; final public static String JCR_PATH = "path"; final public static String DRIVE_FOLDER = "allowCreateFolder"; final public static String MIN_WIDTH = "minwidth"; final public static String CB_DOCUMENT_NAME = "documentName"; final public static String CB_SCRIPT_NAME = "scriptName"; final public static String CB_REF_DOCUMENT = "reference"; final public static String CB_CHILD_DOCUMENT = "child"; final public static String CB_NB_PER_PAGE = "nbPerPage"; final public static String CB_QUERY_STATEMENT = "queryStatement"; final public static String CB_QUERY_ISNEW = "isAddNew"; final public static String CB_QUERY_TYPE = "queryType"; final public static String CB_QUERY_STORE = "queryStore"; final public static String CB_QUERY_LANGUAGE = "queryLanguage"; final public static String CB_VIEW_TOOLBAR = "viewToolbar"; final public static String CB_VIEW_TAGMAP = "viewTagMap"; final public static String CB_VIEW_COMMENT = "viewComment"; final public static String CB_VIEW_VOTE = "viewVote"; final public static String CB_SEARCH_LOCATION = "searchLocation"; final public static String CB_ENABLE_SEARCH_LOCATION = "enableSearch"; final public static String CB_FILTER_CATEGORY = "filterCategory"; final static public String EXO_AUDITABLE = "exo:auditable"; final public static String CB_BOX_TEMPLATE = "boxTemplate"; final public static String CB_TEMPLATE = "template"; final public static String CB_USECASE = "usecase"; final public static String CB_ALLOW_PUBLISH = "isAllowPublish"; final public static String FROM_PATH = "From Path"; final public static String USE_DOCUMENT = "Document"; final public static String USE_JCR_QUERY = "Using a JCR query"; final public static String USE_SCRIPT = "Using a script"; final public static String CB_USE_FROM_PATH = "path"; final public static String CB_USE_DOCUMENT = "detail-document"; final public static String CB_USE_JCR_QUERY = "query"; final public static String CB_USE_SCRIPT = "script"; final public static String SEMI_COLON = ";"; final public static String COLON = ":"; final public static String SLASH = "/"; final public static String BACKSLASH = "\\"; final public static String EXO_CREATED_DATE = "exo:dateCreated"; final public static String EXO_DATETIME = "exo:datetime"; final public static String EXO_MODIFIED_DATE = "exo:dateModified"; final public static String EXO_OWNER = "exo:owner"; final public static String SPECIALCHARACTER[] = { SEMI_COLON, SLASH, BACKSLASH, "|", ">", "<", "\"", "?", "!", "#", "$", "&", "*", "(", ")", "{", "}", "[", "]", ":", ".", "'" }; final public static String REPOSITORY = "repository"; final public static String VIEWS = "views"; final public static String DRIVE = "drive"; final static public String TRASH_HOME_NODE_PATH = "trashHomeNodePath"; final static public String TRASH_REPOSITORY = "trashRepository"; final static public String TRASH_WORKSPACE = "trashWorkspace"; final public static String JCR_INFO = "jcrInfo"; final static public String NT_UNSTRUCTURED = "nt:unstructured"; final static public String NT_FILE = "nt:file"; final static public String NT_FOLDER = "nt:folder"; final static public String NT_FROZEN = "nt:frozenNode"; final static public String EXO_TITLE = "exo:title"; final static public String EXO_SUMMARY = "exo:summary"; final static public String EXO_RELATION = "exo:relation"; final static public String EXO_TAXONOMY = "exo:taxonomy"; final static public String EXO_IMAGE = "exo:image"; final static public String EXO_LANGUAGE = "exo:language"; final static public String LANGUAGES = "languages"; final static public String EXO_METADATA = "exo:metadata"; final static public String MIX_REFERENCEABLE = "mix:referenceable"; final static public String MIX_VERSIONABLE = "mix:versionable"; final static public String NT_RESOURCE = "nt:resource"; final static public String NT_BASE = "nt:base"; final static public String DEFAULT = "default"; final static public String JCR_CONTENT = "jcr:content"; final static public String JCR_CONTENT_DESCRIPTION = "jcr:content/dc:description"; final static public String JCR_MIMETYPE = "jcr:mimeType"; final static public String JCR_FROZEN = "jcr:frozenNode"; final public static String JCR_LASTMODIFIED = "jcr:lastModified"; final public static String JCR_PRIMARYTYPE = "jcr:primaryType"; final static public String JCR_DATA = "jcr:data"; final static public String JCR_SCORE = "jcr:score"; final static public String EXO_ROLES = "exo:roles"; final static public String EXO_TEMPLATEFILE = "exo:templateFile"; final static public String EXO_TEMPLATE = "exo:template"; final static public String EXO_ACTION = "exo:action"; final static public String EXO_ACTIONS = "exo:actions"; final static public String MIX_LOCKABLE = "mix:lockable"; final static public String EXO_CATEGORIZED = "exo:categorized"; final static public String EXO_CATEGORY = "exo:category"; final static public String EXO_HIDDENABLE = "exo:hiddenable"; final static public String EXO_ACCESSPERMISSION = "exo:accessPermissions"; final static public String EXO_PERMISSIONS = "exo:permissions"; final static public String EXO_FAVOURITE = "exo:favourite"; final static public String EXO_FAVOURITE_FOLDER = "exo:favoriteFolder"; final static public String EXO_FAVOURITER = "exo:favouriter"; final static public String EXO_RESTOREPATH = "exo:restorePath"; final static public String EXO_RESTORELOCATION = "exo:restoreLocation"; final static public String EXO_RESTORE_WORKSPACE = "exo:restoreWorkspace"; final static public String EXO_LASTMODIFIER = "exo:lastModifier"; final static public String EXO_TRASH_FOLDER = "exo:trashFolder"; final static public String EXO_TOTAL = "exo:total"; final static public String EXO_WEBCONTENT = "exo:webContent"; final static public String EXO_RSS_ENABLE = "exo:rss-enable"; final static public String EXO_COMMENTS = "exo:comments"; final static public String EXO_MUSICFOLDER = "exo:musicFolder"; final static public String EXO_VIDEOFOLDER = "exo:videoFolder"; final static public String EXO_PICTUREFOLDER = "exo:pictureFolder"; final static public String EXO_DOCUMENTFOLDER = "exo:documentFolder"; final static public String EXO_SEARCHFOLDER = "exo:searchFolder"; final static public String MIX_COMMENTABLE = "mix:commentable"; final static public String MIX_VOTABLE = "mix:votable"; final static public String EXO_SYMLINK = "exo:symlink"; final static public String EXO_PRIMARYTYPE = "exo:primaryType"; final static public String INLINE_DRAFT = "Draft"; final static public String INLINE_PUBLISHED = "Published"; final static public String EXO_SORTABLE = "exo:sortable"; final static public String EXO_RISIZEABLE = "exo:documentSize"; final static public String FLASH_MIMETYPE = "flash"; final static public String[] SPECIFIC_FOLDERS = { EXO_MUSICFOLDER, EXO_VIDEOFOLDER, EXO_PICTUREFOLDER, EXO_DOCUMENTFOLDER, EXO_SEARCHFOLDER }; final static public String[] FOLDERS = { NT_UNSTRUCTURED, NT_FOLDER }; final static public String[] NON_EDITABLE_NODETYPES = { NT_UNSTRUCTURED, NT_FOLDER, NT_RESOURCE }; final public static String[] CATEGORY_NODE_TYPES = { NT_FOLDER, NT_UNSTRUCTURED, EXO_TAXONOMY }; final static public String CATEGORY_MANDATORY = "categoryMandatoryWhenFileUpload"; final static public String UPLOAD_SIZE_LIMIT_MB = "uploadFileSizeLimitMB"; final static public String FILE_VIEWER_EXTENSION_TYPE = "org.exoplatform.ecm.dms.FileViewer"; final static public String MIME_TYPE = "mimeType"; final static public String LOCALE_WEBUI_DMS = "locale.portlet.i18n.WebUIDms"; final static public String REQUESTCONTEXT = "requestcontext"; final static public String WORKSPACE_PARAM = "workspaceName"; final static public String SPACE_GROUP = "/spaces"; final static public String SITES_PATH = "/sites"; final static public String COLLABORATION_WS = "collaboration"; final static public int USER_DEPTH = 5; final static public String EMPTY = ""; final static public String PUBLIC = "Public"; final static public String GROUP = "Group"; final static public String SITE = "Site"; final static public String PRIVATE = "Private"; final static public String URL_BACKTO = "backto"; public static final String INPUT_TEXT_AREA = "TEXTAREA"; public static final String INPUT_WYSIWYG = "WYSIWYG"; public static final String INPUT_TEXT = "TEXT"; public static final String DEFAULT_CSS_NAME = "InlineText"; public static final String LEFT2RIGHT = "left-to-right"; public static final String RIGHT2LEFT = "right-to-left"; protected static final String SEPARATOR = "="; protected static final String TOOLBAR = "toolbar"; protected static final String CSS = "CSSData"; protected static final String HEIGHT = "height"; protected static final String BUTTON_DIR = "button_direction"; protected static final String PREV_HTML = "prev_html"; protected static final String POST_HTML = "post_html"; protected static final String FAST_PUBLISH_LINK = "fast_publish"; private static final Log LOG = ExoLogger.getLogger(Utils.class.getName()); public static String encodeHTML(String text) { return text.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); } public static String formatNodeName(String text) { return text.replaceAll("('|\")", "\\\\'"); } public static boolean isVersionable(Node node) throws RepositoryException { return node.isNodeType(MIX_VERSIONABLE); } public static boolean isTrashHomeNode(Node node) throws RepositoryException { return node.isNodeType(EXO_TRASH_FOLDER); } public static boolean isInTrash(Node node) throws RepositoryException { TrashService trashService = WCMCoreUtils.getService(TrashService.class); return trashService.isInTrash(node); } /** check a symlink node and its target are in Trash or not */ public static boolean targetNodeAndLinkInTrash(Node currentNode) throws Exception { if (Utils.isInTrash(currentNode) && Utils.isSymLink(currentNode)) { Node targetNode = Utils.getNodeSymLink(currentNode); if (Utils.isInTrash(targetNode)) { return true; } } return false; } /** check if we can restore a node */ public static boolean isAbleToRestore(Node currentNode) throws Exception { String restorePath; String restoreWorkspace; Node restoreLocationNode; if (!Utils.isInTrash(currentNode)) { return false; } // return false if the node is exo:actions if (Utils.EXO_ACTIONS.equals(currentNode.getName()) && Utils.isInTrash(currentNode)) { return false; } // return false if the target has been already in Trash. if (Utils.targetNodeAndLinkInTrash(currentNode)) { return false; } if (ConversationState.getCurrent().getIdentity().getUserId().equalsIgnoreCase(WCMCoreUtils.getSuperUser())) { return true; } if (currentNode.isNodeType(TrashService.EXO_RESTORE_LOCATION)) { restorePath = currentNode.getProperty(TrashService.RESTORE_PATH).getString(); restoreWorkspace = currentNode.getProperty(TrashService.RESTORE_WORKSPACE).getString(); restorePath = restorePath.substring(0, restorePath.lastIndexOf("/")); } else { // Is not a deleted node, may be groovy action, hidden node,... return false; } Session session = WCMCoreUtils.getUserSessionProvider().getSession(restoreWorkspace, WCMCoreUtils.getRepository()); try { if (restorePath == null || restorePath.length() == 0) { restoreLocationNode = session.getRootNode(); } else { restoreLocationNode = (Node) session.getItem(restorePath); } } catch (Exception e) { return false; } return PermissionUtil.canAddNode(restoreLocationNode); } public static boolean isReferenceable(Node node) throws RepositoryException { return node.isNodeType(MIX_REFERENCEABLE); } public static boolean isNameValid(String name, String[] regexpression) { for (String c : regexpression) { if (name == null || name.contains(c)) return false; } return true; } public static boolean isNameEmpty(String name) { return (name == null || name.trim().length() == 0); } public static boolean isAuditable(Node node) throws RepositoryException { return node.isNodeType(EXO_AUDITABLE); } public static String getIndexName(Node node) throws RepositoryException { StringBuilder buffer = new StringBuilder(128); buffer.append(node.getName()); int index = node.getIndex(); if (index > 1) { buffer.append('['); buffer.append(index); buffer.append(']'); } return buffer.toString(); } public static List<String> getListAllowedFileType(Node currentNode, TemplateService templateService) throws Exception { List<String> nodeTypes = new ArrayList<String>(); NodeTypeManager ntManager = currentNode.getSession().getWorkspace().getNodeTypeManager(); NodeType currentNodeType = currentNode.getPrimaryNodeType(); NodeDefinition[] childDefs = currentNodeType.getChildNodeDefinitions(); List<String> templates = templateService.getDocumentTemplates(); try { for (int i = 0; i < templates.size(); i++) { String nodeTypeName = templates.get(i).toString(); NodeType nodeType = ntManager.getNodeType(nodeTypeName); NodeType[] superTypes = nodeType.getSupertypes(); boolean isCanCreateDocument = false; for (NodeDefinition childDef : childDefs) { NodeType[] requiredChilds = childDef.getRequiredPrimaryTypes(); for (NodeType requiredChild : requiredChilds) { if (nodeTypeName.equals(requiredChild.getName())) { isCanCreateDocument = true; break; } } if (nodeTypeName.equals(childDef.getName()) || isCanCreateDocument) { if (!nodeTypes.contains(nodeTypeName)) nodeTypes.add(nodeTypeName); isCanCreateDocument = true; } } if (!isCanCreateDocument) { for (NodeType superType : superTypes) { for (NodeDefinition childDef : childDefs) { for (NodeType requiredType : childDef.getRequiredPrimaryTypes()) { if (superType.getName().equals(requiredType.getName())) { if (!nodeTypes.contains(nodeTypeName)) nodeTypes.add(nodeTypeName); isCanCreateDocument = true; break; } } if (isCanCreateDocument) break; } if (isCanCreateDocument) break; } } } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } return nodeTypes; } public static String getNodeTypeIcon(Node node, String appended, String mode) throws RepositoryException { return org.exoplatform.services.cms.impl.Utils.getNodeTypeIcon(node, appended, mode); } public static String getNodeTypeIcon(Node node, String appended) throws RepositoryException { return org.exoplatform.services.cms.impl.Utils.getNodeTypeIcon(node, appended); } public static NodeIterator getAuthorizedChildNodes(Node node) throws Exception { NodeIterator iter = node.getNodes(); while (iter.hasNext()) { if (!PermissionUtil.canRead(iter.nextNode())) iter.remove(); } return iter; } public static List<Node> getAuthorizedChildList(Node node) throws Exception { List<Node> children = new ArrayList<Node>(); NodeIterator iter = node.getNodes(); while (iter.hasNext()) { Node child = iter.nextNode(); if (PermissionUtil.canRead(child)) children.add(child); } return children; } public static boolean isLockTokenHolder(Node node) throws Exception { if (node.getLock().getLockToken() != null) { return true; } return false; } public static List<String> getMemberships() throws Exception { return org.exoplatform.services.cms.impl.Utils.getMemberships(); } public static List<String> getGroups() throws Exception { ConversationState conversationState = ConversationState.getCurrent(); Identity identity = conversationState.getIdentity(); Set<String> groups = identity.getGroups(); return new ArrayList<String>(groups); } public static String getNodeOwner(Node node) throws Exception { try { if (node.hasProperty(EXO_OWNER)) { return node.getProperty(EXO_OWNER).getString(); } } catch (Exception e) { return null; } return null; } public static Node findNodeByUUID(String uuid) throws Exception { RepositoryService repositoryService = Util.getUIPortal().getApplicationComponent(RepositoryService.class); SessionProviderService sessionProviderService = Util.getUIPortal().getApplicationComponent(SessionProviderService.class); SessionProvider sessionProvider = sessionProviderService.getSessionProvider(null); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); Node node = null; for (String wsName : manageableRepository.getWorkspaceNames()) { try { node = sessionProvider.getSession(wsName, manageableRepository).getNodeByUUID(uuid); } catch (ItemNotFoundException e) { continue; } } return node; } public static boolean isSymLink(Node node) throws RepositoryException { LinkManager linkManager = Util.getUIPortal().getApplicationComponent(LinkManager.class); return linkManager.isLink(node); } public static Node getNodeSymLink(Node node) throws Exception { LinkManager linkManager = Util.getUIPortal().getApplicationComponent(LinkManager.class); Node realNode = null; if (linkManager.isLink(node)) { if (linkManager.isTargetReachable(node)) { realNode = linkManager.getTarget(node); } } else { realNode = node; } return realNode; } public static InputStream extractFirstEntryFromZipFile(ZipInputStream zipStream) throws Exception { return zipStream.getNextEntry() == null ? null : zipStream; } public static String getThumbnailImage(InputStream input, String downloadName) throws Exception { DownloadService dservice = WCMCoreUtils.getService(DownloadService.class); InputStreamDownloadResource dresource = new InputStreamDownloadResource(input, "image"); dresource.setDownloadName(downloadName); return dservice.getDownloadLink(dservice.addDownloadResource(dresource)); } public static String getThumbnailImage(Node node, String propertyName) throws Exception { ThumbnailService thumbnailService = Util.getUIPortal().getApplicationComponent(ThumbnailService.class); if (node.isNodeType(NT_FILE)) { String mimeType = node.getNode(JCR_CONTENT).getProperty(JCR_MIMETYPE).getString(); if (mimeType.startsWith("image")) { Node thumbnailNode = thumbnailService.addThumbnailNode(node); InputStream inputStream = node.getNode(JCR_CONTENT).getProperty(JCR_DATA).getStream(); thumbnailService.createSpecifiedThumbnail(thumbnailNode, ImageIO.read(inputStream), propertyName); } } Node thumbnailNode = thumbnailService.getThumbnailNode(node); if (thumbnailNode != null && thumbnailNode.hasProperty(propertyName)) { DownloadService dservice = Util.getUIPortal().getApplicationComponent(DownloadService.class); InputStream input = thumbnailNode.getProperty(propertyName).getStream(); InputStreamDownloadResource dresource = new InputStreamDownloadResource(input, "image"); dresource.setDownloadName(node.getName()); return dservice.getDownloadLink(dservice.addDownloadResource(dresource)); } return null; } public static String calculateFileSize(double fileLengthLong) { int fileLengthDigitCount = Double.toString(fileLengthLong).length(); double fileSizeKB = 0.0; String howBig = ""; if (fileLengthDigitCount < 5) { fileSizeKB = Math.abs(fileLengthLong); howBig = "Byte(s)"; } else if (fileLengthDigitCount >= 5 && fileLengthDigitCount <= 6) { fileSizeKB = Math.abs((fileLengthLong / 1024)); howBig = "KB"; } else if (fileLengthDigitCount >= 7 && fileLengthDigitCount <= 9) { fileSizeKB = Math.abs(fileLengthLong / (1024 * 1024)); howBig = "MB"; } else if (fileLengthDigitCount > 9) { fileSizeKB = Math.abs((fileLengthLong / (1024 * 1024 * 1024))); howBig = "GB"; } String finalResult = roundTwoDecimals(fileSizeKB); return finalResult + " " + howBig; } private static String roundTwoDecimals(double d) { DecimalFormat twoDForm = new DecimalFormat("#.##"); return twoDForm.format(d); } /** * Get resource bundle from PortalApplication resource bundle * * @param key * @return * @throws MissingResourceException */ public static String getResourceBundle(String key) throws MissingResourceException { RequestContext context = Util.getPortalRequestContext(); ResourceBundle res = context.getApplicationResourceBundle(); return res.getString(key); } /** * Get resource bundle from given resource file * * @param name : resource file name * @param key : key * @param cl : ClassLoader to load resource file * @return */ public static String getResourceBundle(String name, String key, ClassLoader cl) { Locale locale = WebuiRequestContext.getCurrentInstance().getLocale(); ResourceBundleService resourceBundleService = WCMCoreUtils.getService(ResourceBundleService.class); ResourceBundle resourceBundle = resourceBundleService.getResourceBundle(name, locale, cl); try { return resourceBundle.getString(key); } catch (MissingResourceException ex) { return key; } } public static String getRestContextName(String portalContainerName) { ExoContainer container = ExoContainerContext.getCurrentContainer(); PortalContainerConfig portalContainerConfig = (PortalContainerConfig) container.getComponentInstance(PortalContainerConfig.class); return portalContainerConfig.getRestContextName(portalContainerName); } public static String getInlineEditingField(Node orgNode, String propertyName) throws Exception { String defaultValue = ""; String idGenerator = ""; Pattern p = Pattern.compile("[^a-zA-Z0-9]"); Matcher m = p.matcher(propertyName); if (orgNode.hasProperty(propertyName)) { defaultValue = orgNode.getProperty(propertyName).getString(); } idGenerator = m.replaceAll("_"); return getInlineEditingField(orgNode, propertyName, defaultValue, INPUT_TEXT, idGenerator, DEFAULT_CSS_NAME, true); } /** * @param orgNode Processed node * @param propertyName which property used for editing * @param inputType input type for editing: TEXT, TEXTAREA, WYSIWYG * @param cssClass class name for CSS, should implement: cssClass, * [cssClass]Title Edit[cssClass] as relative css Should create the * function: InlineEditor.presentationRequestChange[cssClass] to * request the rest-service * @param isGenericProperty set as true to use generic javascript function, * other wise, must create the correctspond function * InlineEditor.presentationRequestChange[cssClass] * @param arguments Extra parameter for Input component (toolbar, width, * height,.. for CKEditor/TextArea) * @return String that can be put on groovy template * @throws Exception * @author vinh_nguyen */ public static String getInlineEditingField(Node orgNode, String propertyName, String defaultValue, String inputType, String idGenerator, String cssClass, boolean isGenericProperty, String... arguments) throws Exception { HashMap<String, String> parsedArguments = parseArguments(arguments); String height = parsedArguments.get(HEIGHT); String bDirection = parsedArguments.get(BUTTON_DIR); String publishLink = parsedArguments.get(FAST_PUBLISH_LINK); Locale locale = WebuiRequestContext.getCurrentInstance().getLocale(); String language = locale.toString(); ResourceBundleService resourceBundleService = WCMCoreUtils.getService(ResourceBundleService.class); ResourceBundle resourceBundle; resourceBundle = resourceBundleService.getResourceBundle(LOCALE_WEBUI_DMS, locale); String draft = INLINE_DRAFT; String published = INLINE_PUBLISHED; try { draft = StringEscapeUtils.escapeHtml4(resourceBundle.getString("PublicationStates.draft")); published = StringEscapeUtils.escapeHtml4(resourceBundle.getString("PublicationStates.published")); } catch (MissingResourceException ex) { if (LOG.isWarnEnabled()) { LOG.warn("Missing resource exception of draft/published status.", ex); } } String portletRealID; if(WebuiRequestContext.getCurrentInstance() instanceof PortletRequestContext) { portletRealID = org.exoplatform.wcm.webui.Utils.getRealPortletId((PortletRequestContext) WebuiRequestContext.getCurrentInstance()); } else { portletRealID = ""; } StringBuffer sb = new StringBuffer(); StringBuffer actionsb = new StringBuffer(); String repo = ((ManageableRepository) orgNode.getSession().getRepository()).getConfiguration().getName(); String workspace = orgNode.getSession().getWorkspace().getName(); String uuid = orgNode.getUUID(); String strSuggestion = ""; String acceptButton = ""; String cancelButton = ""; portletRealID = portletRealID.replace('-', '_'); String showBlockId = "Current" + idGenerator + "_" + portletRealID; String editBlockEditorID = "Edit" + idGenerator + "_" + portletRealID; String editFormID = "Edit" + idGenerator + "Form_" + portletRealID; String newValueInputId = "new" + idGenerator + "_" + portletRealID; String currentValueID = "old" + idGenerator + "_" + portletRealID; String siteName = org.exoplatform.portal.webui.util.Util.getPortalRequestContext().getPortalOwner(); String currentValue = StringUtils.replace(defaultValue, "{portalName}", siteName); try { strSuggestion = StringEscapeUtils.escapeHtml4(resourceBundle.getString("UIPresentation.label.EditingSuggestion")); acceptButton = StringEscapeUtils.escapeHtml4(resourceBundle.getString("UIPresentation.title.AcceptButton")); cancelButton = StringEscapeUtils.escapeHtml4(resourceBundle.getString("UIPresentation.title.CancelButton")); } catch (MissingResourceException e) { if (LOG.isWarnEnabled()) { LOG.warn("MissingResourceException of EditingSuggestion/Accept/Cancel buttons.", e); } } actionsb.append(" return InlineEditor.presentationRequestChange"); if (isGenericProperty) { actionsb.append("Property").append("('").append("/property?', '").append(propertyName).append("', '"); } else { actionsb.append(cssClass).append("('"); } actionsb.append(currentValueID) .append("', '") .append(newValueInputId) .append("', '") .append(repo) .append("', '") .append(workspace) .append("', '") .append(uuid) .append("', '") .append(editBlockEditorID) .append("', '") .append(showBlockId) .append("', '") .append(siteName) .append("', '") .append(language); if (inputType.equals(INPUT_WYSIWYG)) { actionsb.append("', 1);"); } else { actionsb.append("');"); } String strAction = actionsb.toString(); if (orgNode.hasProperty(propertyName)) { try { if (propertyName.equals(EXO_TITLE)) return ContentReader.getXSSCompatibilityContent(orgNode.getProperty(propertyName).getString()); String propertyValue; if (propertyName.equals(JCR_CONTENT_DESCRIPTION)) { propertyValue = orgNode.getProperty(propertyName).getValues()[0].getString(); return HTMLSanitizer.sanitize(propertyValue); } if (orgNode.getProperty(propertyName).getDefinition().isMultiple()) { // The requested property is multiple-valued, inline editing enable // users to edit the first value of property propertyValue = orgNode.getProperty(propertyName).getValues()[0].getString(); propertyValue = ContentReader.simpleEscapeHtml(propertyValue); } else { propertyValue = orgNode.getProperty(propertyName).getString(); } if (org.exoplatform.wcm.webui.Utils.getCurrentMode().equals(WCMComposer.MODE_LIVE)) return StringUtils.replace(propertyValue, "{portalName}", siteName); else return "<div class=\"WCMInlineEditable\" contenteditable=\"true\" propertyName=\"" + propertyName + "\" repo=\"" + repo + "\" workspace=\"" + workspace + "\"" + " uuid=\"" + uuid + "\" siteName=\"" + siteName + "\" publishedMsg=\"" + published + "\" draftMsg=\"" + draft + "\" fastpublishlink=\"" + publishLink + "\" language=\"" + language + "\" >" + propertyValue + "</div>"; } catch (Exception e) { if (org.exoplatform.wcm.webui.Utils.getCurrentMode().equals(WCMComposer.MODE_LIVE)) return currentValue; else return "<div class=\"WCMInlineEditable\" contenteditable=\"true\" propertyName=\"" + propertyName + "\" repo=\"" + repo + "\" workspace=\"" + workspace + "\" " + "uuid=\"" + uuid + "\" siteName=\"" + siteName + "\" publishedMsg=\"" + published + "\" draftMsg=\"" + draft + "\" fastpublishlink=\"" + publishLink + "\" language=\"" + language + "\" >" + defaultValue + "</div>"; } } sb.append("<div class=\"InlineEditing\" >\n"); sb.append("\n<div rel=\"tooltip\" data-placement=\"bottom\" id=\"") .append(showBlockId) .append("\" Class=\"") .append(cssClass) .append("\""); sb.append("title=\"").append(strSuggestion).append("\""); sb.append(" onClick=\"InlineEditor.presentationSwitchBlock('") .append(showBlockId) .append("', '") .append(editBlockEditorID) .append("');\""); sb.append("onmouseout=\"this.className='") .append(cssClass) .append("';\" onblur=\"this.className='") .append(cssClass) .append("';\" onfocus=\"this.className='") .append(cssClass) .append("Hover") .append("';\" onmouseover=\"this.className='") .append(cssClass) .append("Hover';\">") .append(currentValue) .append("</div>\n"); sb.append("\t<div id=\"").append(editBlockEditorID).append("\" class=\"Edit").append(cssClass).append("\">\n"); sb.append("\t\t<form name=\"") .append(editFormID) .append("\" id=\"") .append(editFormID) .append("\" onSubmit=\"") .append(strAction) .append("\">\n"); sb.append("<DIV style=\"display:none; visible:hidden\" id=\"") .append(currentValueID) .append("\" name=\"") .append(currentValueID) .append("\">") .append(currentValue) .append("</DIV>"); if (bDirection != null && bDirection.equals(LEFT2RIGHT)) { sb.append("\t\t<a href=\"#\" rel=\"tooltip\" data-placement=\"bottom\"") .append(" class =\"AcceptButton\" style=\"float:left\" onclick=\"") .append(strAction) .append("\" title=\"" + acceptButton + "\">&nbsp;</a>\n"); sb.append("\t\t<a href=\"#\" rel=\"tooltip\" data-placement=\"bottom\" class =\"CancelButton\" style=\"float:left\" ") .append("onClick=\"InlineEditor.presentationSwitchBlock('"); sb.append(editBlockEditorID).append("', '").append(showBlockId).append("');\" title=\"" + cancelButton + "\">&nbsp;</a>\n"); } else { sb.append("\t\t<a href=\"#\" rel=\"tooltip\" data-placement=\"bottom\" class =\"CancelButton\" ") .append("onClick=\"InlineEditor.presentationSwitchBlock('"); sb.append(editBlockEditorID).append("', '").append(showBlockId).append("');\" title=\"" + cancelButton + "\">&nbsp;</a>\n"); sb.append("\t\t<a href=\"#\" rel=\"tooltip\" data-placement=\"bottom\" class =\"AcceptButton\" onclick=\"") .append(strAction) .append("\" title=\"" + acceptButton + "\">&nbsp;</a>\n"); } sb.append("\t\t<div class=\"Edit").append(cssClass).append("Input\">\n "); sb.append("\n\t\t</div>\n\t</form>\n</div>\n\n</div>"); return sb.toString(); } private static HashMap<String, String> parseArguments(String... arguments) { HashMap<String, String> map = new HashMap<String, String>(); int sIndex = -1; for (String argument : arguments) { String value = null; sIndex = argument.indexOf(SEPARATOR); if (sIndex > 0) { value = argument.substring(sIndex + 1); } else { continue; } if (argument.startsWith(JCR_PATH)) { map.put(JCR_PATH, value); continue; } else if (argument.startsWith(TOOLBAR)) { map.put(TOOLBAR, value); continue; } else if (argument.startsWith(CSS)) { map.put(CSS, value); continue; } else if (argument.startsWith(HEIGHT)) { map.put(HEIGHT, value); continue; } else if (argument.startsWith(BUTTON_DIR)) { map.put(BUTTON_DIR, value); continue; } else if (argument.startsWith(PREV_HTML)) { map.put(PREV_HTML, value); continue; } else if (argument.startsWith(POST_HTML)) { map.put(POST_HTML, value); continue; } else if (argument.startsWith(FAST_PUBLISH_LINK)) { map.put(FAST_PUBLISH_LINK, value); continue; } } return map; } /** * Gets the title. * * @param node the node * @return the title * @throws Exception the exception */ public static String getTitle(Node node) throws Exception { String title = null; try { title = node.getProperty("exo:title").getValue().getString(); } catch (PathNotFoundException pnf1) { try { Value[] values = node.getNode("jcr:content").getProperty("dc:title").getValues(); if (values.length != 0) { title = values[0].getString(); } } catch (PathNotFoundException pnf2) { title = null; } } catch (IllegalStateException | RepositoryException e) { title = null; } if (StringUtils.isBlank(title)) { title = node.getName(); } int index = node.getIndex(); StringBuilder buffer = new StringBuilder(128); if (index > 1) { buffer.append(title); buffer.append('['); buffer.append(index); buffer.append(']'); title = buffer.toString(); } try { title = URLDecoder.decode(title, "UTF-8"); return URLDecoder.decode(title, "UTF-8"); }catch (Exception e){ return title; } } /** * Gets the name. * * @param node the node * @return the name * @throws Exception the exception */ public static String getName(Node node) throws Exception { String name = null; try { name = node.getProperty("exo:name").getValue().getString(); } catch (PathNotFoundException pnf1) { try { Value[] values = node.getNode("jcr:content").getProperty("dc:name").getValues(); if (values.length != 0) { name = values[0].getString(); } } catch (PathNotFoundException pnf2) { name = null; } } catch (IllegalStateException | RepositoryException e) { name = null; } return URLDecoder.decode(name, "UTF-8"); } /** * @param node * @return * @throws Exception */ public static String getTitleWithSymlink(Node node) throws Exception { String title = null; Node nProcessNode = node; if (isSymLink(node)) { nProcessNode = Optional.ofNullable(getNodeSymLink(node)).orElse(node); } if (nProcessNode.hasProperty("exo:title")) { title = nProcessNode.getProperty("exo:title").getValue().getString(); } if (title == null && nProcessNode.hasNode("jcr:content")) { Node content = nProcessNode.getNode("jcr:content"); if (content.hasProperty("dc:title")) { try { title = content.getProperty("dc:title").getValues()[0].getString(); } catch (Exception e) { title = null; } } } if (title == null) { title = nProcessNode.getName(); } if (title != null && title.length() > 0) { title = title.trim(); } return ContentReader.getXSSCompatibilityContent(title); } /** * Get UIComponent to process render a node which has specified mimeType * * @param mimeType * @param container * @return * @throws Exception */ public static UIComponent getUIComponent(String mimeType, UIContainer container) throws Exception { UIExtensionManager manager = WCMCoreUtils.getService(UIExtensionManager.class); List<UIExtension> extensions = manager.getUIExtensions(FILE_VIEWER_EXTENSION_TYPE); Map<String, Object> context = new HashMap<String, Object>(); context.put(MIME_TYPE, mimeType.toLowerCase()); for (UIExtension extension : extensions) { UIComponent uiComponent = manager.addUIExtension(extension, context, container); if (uiComponent != null) return uiComponent; } return null; } /* * Check the current node is eligible to add mix:versionable or not * @param node the current node * @param nodetypes The list of node types have child nodes which are not add * mix:versionaboe while enrolling. * @throws Exception the exception */ public static boolean isMakeVersionable(Node node, String[] nodeTypes) throws Exception { String ws = node.getSession().getWorkspace().getName(); SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); ManageableRepository manageableRepository = WCMCoreUtils.getRepository(); Session session = sessionProvider.getSession(ws, manageableRepository); node = (Node) session.getItem(node.getPath()); int deep = node.getDepth(); for (int i = 0; i < deep; i++) { Node parent = node.getParent(); for (String nodeType : nodeTypes) { if (nodeType != null && nodeType.length() > 0 && parent.isNodeType(nodeType)) return false; } node = parent; } return true; } /** * Get a cookie value with given name * * @param cookieName cookies * @return a cookies value */ public static String getCookieByCookieName(String cookieName) { HttpServletRequest request = Util.getPortalRequestContext().getRequest(); Cookie[] cookies = request.getCookies(); if (cookies == null) { return null; } for (int loopIndex = 0; loopIndex < cookies.length; loopIndex++) { Cookie cookie1 = cookies[loopIndex]; if (cookie1.getName().equals(cookieName)) return cookie1.getValue(); } return null; } /** * @param node nt:file node with have the data stream * @return Link to download the jcr:data of the given node * @throws Exception */ public static String getDownloadRestServiceLink(Node node) throws Exception { ExoContainer container = ExoContainerContext.getCurrentContainer(); PortalContainerInfo containerInfo = (PortalContainerInfo) container.getComponentInstanceOfType(PortalContainerInfo.class); String portalName = containerInfo.getContainerName(); PortalContainerConfig portalContainerConfig = (PortalContainerConfig) container.getComponentInstance(PortalContainerConfig.class); String restContextName = portalContainerConfig.getRestContextName(portalName); StringBuilder sb = new StringBuilder(); Node currentNode = org.exoplatform.wcm.webui.Utils.getRealNode(node); String ndPath = currentNode.getPath(); if (ndPath.startsWith("/")) { ndPath = ndPath.substring(1); } String encodedPath = encodePath(ndPath,"UTF-8"); sb.append("/").append(restContextName).append("/contents/download/"); sb.append(currentNode.getSession().getWorkspace().getName()).append("/").append(encodedPath); if (node.isNodeType("nt:frozenNode")) { sb.append("?version=" + node.getParent().getName()); } return sb.toString(); } public static String getPDFViewerLink(Node node) throws Exception { ExoContainer container = ExoContainerContext.getCurrentContainer(); PortalContainerInfo containerInfo = (PortalContainerInfo) container.getComponentInstanceOfType(PortalContainerInfo.class); String portalName = containerInfo.getContainerName(); PortalContainerConfig portalContainerConfig = (PortalContainerConfig) container.getComponentInstance(PortalContainerConfig.class); String restContextName = portalContainerConfig.getRestContextName(portalName); StringBuilder sb = new StringBuilder(); String repository = ((ManageableRepository) node.getSession().getRepository()).getConfiguration().getName(); sb.append("/").append(restContextName).append("/pdfviewer/"); sb.append(repository).append("/"); sb.append(node.getSession().getWorkspace().getName()).append("/").append(node.getUUID()); return sb.toString(); } /** * Get allowed folder types in current path. * * @param currentNode * @param currentDrive * @return list of node types * @throws Exception */ public static List<String> getAllowedFolderTypesInCurrentPath(Node currentNode, DriveData currentDrive) throws Exception { List<String> allowedTypes = new ArrayList<String>(); NodeTypeImpl currentNodeType = (NodeTypeImpl) currentNode.getPrimaryNodeType(); String[] arrFoldertypes = currentDrive.getAllowCreateFolders().split(","); NodeTypeManager ntManager = currentNode.getSession().getWorkspace().getNodeTypeManager(); for (String strFolderType : arrFoldertypes) { if (strFolderType.isEmpty()) continue; NodeType folderType = ntManager.getNodeType(strFolderType); if ((currentNodeType).isChildNodePrimaryTypeAllowed(Constants.JCR_ANY_NAME, ((NodeTypeImpl) folderType).getQName())) { allowedTypes.add(strFolderType); } } return allowedTypes; } /** * removes child nodes in path list if ancestor of the node exists in list * * @param srcPath the list of nodes * @return the node list with out child nodes */ public static String[] removeChildNodes(String srcPath) { if (StringUtils.isEmpty(srcPath)) { return new String[] {}; } if (!srcPath.contains(";")) { return new String[] { srcPath }; } String[] paths = srcPath.split(";"); List<String> ret = new ArrayList<String>(); for (int i = 0; i < paths.length; i++) { boolean ok = true; for (int j = 0; j < paths.length; j++) { // check if [i] is child of [j] if ((i != j) && paths[i].startsWith(paths[j]) && (paths[i].length() > paths[j].length()) && (paths[i].charAt(paths[j].length()) == '/')) { ok = false; break; } } if (ok) { ret.add(paths[i]); } } return ret.toArray(new String[] {}); } public static void openDocumentInDesktop(Node currentNode, UIPopupContainer popupContainer, Event<? extends UIComponent> event) throws Exception { HttpServletRequest httpServletRequest = Util.getPortalRequestContext().getRequest(); String nodePath = currentNode.getPath(); String ws = currentNode.getSession().getWorkspace().getName(); String repo = WCMCoreUtils.getRepository().getConfiguration().getName(); String filePath = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + "/" + WCMCoreUtils.getRestContextName() + "/private/jcr/" + repo + "/" + ws + nodePath; String workspaceMountPath = httpServletRequest.getScheme()+ "://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + "/" + WCMCoreUtils.getRestContextName()+ "/private/jcr/" + repo + "/" + ws; NodeHierarchyCreator nodeHierarchyCreator = WCMCoreUtils.getService(NodeHierarchyCreator.class); String mountPath; if(((NodeImpl)currentNode.getParent()).isRoot()) { mountPath = workspaceMountPath; } else{ mountPath = workspaceMountPath + checkMountPath(currentNode, generateMountURL(nodePath, ws, nodeHierarchyCreator.getJcrPath(BasePath.CMS_USERS_PATH), nodeHierarchyCreator.getJcrPath(BasePath.CMS_GROUPS_PATH))); } if (currentNode.isLocked()) { String[] userLock = { currentNode.getLock().getLockOwner() }; UIOpenDocumentForm uiOpenDocumentForm = popupContainer.activate(UIOpenDocumentForm.class, 600); uiOpenDocumentForm.setId("UIReadOnlyFileConfirmMessage"); uiOpenDocumentForm.setMessageKey("UIPopupMenu.msg.lock-node-read-only"); uiOpenDocumentForm.setArguments(userLock); uiOpenDocumentForm.setFilePath(nodePath); uiOpenDocumentForm.setMountPath(mountPath); uiOpenDocumentForm.setAbsolutePath(filePath); event.getRequestContext() .getJavascriptManager() .require("SHARED/openDocumentInOffice") .addScripts("eXo.ecm.OpenDocumentInOffice.showConfirmBox();"); } else { event.getRequestContext() .getJavascriptManager() .require("SHARED/openDocumentInOffice") .addScripts("eXo.ecm.OpenDocumentInOffice.openDocument('" + filePath + "', '" + mountPath + "');"); } event.getRequestContext().addUIComponentToUpdateByAjax(popupContainer.getParent()); } public static void logUnavaiblePreview(String path) { LOG.warn("Can not preview the document having path : " + path); } public static String encodePath(String path, String encoding) { try { String encodedPath = URLEncoder.encode(path,encoding); encodedPath = encodedPath.replaceAll("%2F","/"); return encodedPath; } catch (UnsupportedEncodingException e){ LOG.error("Failed to encode path '" + path + "' with encoding '" + encoding + "'",e); } return null; } static public class NodeTypeNameComparator implements Comparator<NodeType> { public int compare(NodeType n1, NodeType n2) throws ClassCastException { String name1 = n1.getName(); String name2 = n2.getName(); return name1.compareToIgnoreCase(name2); } } /** * Generate the webdav mount URL * @param nodePath : jcr path * @param ws : workspace name * @return */ public static String generateMountURL(String nodePath, String ws, String userPath, String groupPath) { if (StringUtils.isNotBlank(nodePath) && COLLABORATION_WS.equals(ws)) { StringBuilder mountPath = new StringBuilder(); String[] ancestors = nodePath.substring(1).split("/"); if (ancestors.length <= 1) return "/"; //User folder mount if (nodePath.startsWith(userPath)) { if (ancestors.length >= USER_DEPTH + 1) mountPath.append(nodePath.substring(0, nodePath.indexOf(ancestors[USER_DEPTH + 1])-1)); else mountPath.append(nodePath.substring(0, nodePath.indexOf(ancestors[ancestors.length-1])-1)); } //Space folder mount else if (nodePath.startsWith(groupPath + SPACE_GROUP)) { if (ancestors.length > 4) mountPath.append(nodePath.substring(0, nodePath.indexOf(ancestors[4])-1)); else if (ancestors.length == 4) { mountPath.append(nodePath.substring(0, nodePath.indexOf(ancestors[3])-1)); } else mountPath.append(groupPath + SPACE_GROUP); } //Group folder mount else if (nodePath.startsWith(groupPath)) { if (ancestors.length > 2) mountPath.append(nodePath.substring(0, nodePath.indexOf(ancestors[2])-1)); else mountPath.append(groupPath); } //Site folder mount else if (nodePath.startsWith(SITES_PATH)) { if (ancestors.length > 2) mountPath.append(nodePath.substring(0, nodePath.indexOf(ancestors[2])-1)); else mountPath.append(SITES_PATH); } //other case mount level -1 else{ if (ancestors.length > 4){ mountPath.append(nodePath.substring(0, nodePath.indexOf(ancestors[3])-1)); }else if (ancestors.length > 1){ mountPath.append(nodePath.substring(0, nodePath.indexOf(ancestors[ancestors.length-1])-1)); } } return mountPath.toString(); } return "/"; } private static String checkMountPath(Node node, String mountPath) throws AccessControlException, RepositoryException { NodeImpl parent = (NodeImpl) node.getParent(); boolean hasPermission = false; while (PermissionUtil.canRead(parent)) { hasPermission = true; if(mountPath.equals(parent.getPath()) || parent.isRoot()) break; parent = parent.getParent(); } if (hasPermission) { return parent.getPath(); } else { LOG.warn("Cannot mount webdav path {} You don't have read permission access", parent.getPath()); throw new AccessControlException("You don't have read permission access to " + parent.getPath()); } } /** * Check the status of download action * @return */ public static boolean isDownloadDocumentActivated() { SettingService settingService = CommonsUtils.getService(SettingService.class); SettingValue<?> settingValue = settingService.get(Context.GLOBAL.id("downloadDocumentStatus"), Scope.APPLICATION.id("downloadDocumentStatus"), "exo:downloadDocumentStatus"); return !(settingValue != null && !settingValue.getValue().toString().isEmpty() ? Boolean.valueOf(settingValue.getValue().toString()) : false); } }
58,856
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIBaseNodePresentation.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/presentation/UIBaseNodePresentation.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.presentation; import com.google.common.collect.Lists; import org.exoplatform.commons.utils.DateUtils; import org.exoplatform.container.xml.PortalContainerInfo; import org.exoplatform.download.DownloadService; import org.exoplatform.download.InputStreamDownloadResource; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.container.UIContainer; import org.exoplatform.services.cms.comments.CommentsService; import org.exoplatform.services.cms.folksonomy.NewFolksonomyService; import org.exoplatform.services.cms.i18n.MultiLanguageService; import org.exoplatform.services.cms.taxonomy.TaxonomyService; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.cms.voting.VotingService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.web.application.Parameter; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.lifecycle.WebuiBindingContext; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import javax.jcr.*; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; /* * Created by The eXo Platform SAS * @author : Hoa.Pham * hoa.pham@exoplatform.com * Jun 23, 2008 */ /** * The Class UIBaseNodePresentation should implement some common method in * NodePresentation like getIcons,getWebDavLink.... */ public abstract class UIBaseNodePresentation extends UIContainer implements NodePresentation { /** The language_. */ private String language_ ; private boolean enableVote; private boolean enableComment; private String mediaState = MEDIA_STATE_NONE; private static final Log LOG = ExoLogger.getLogger(UIBaseNodePresentation.class.getName()); /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getNode() */ public abstract Node getNode() throws Exception ; /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getTemplatePath() */ public abstract String getTemplatePath() throws Exception ; /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getOriginalNode() */ public abstract Node getOriginalNode() throws Exception ; /** * Gets the repository name. * * @return the repository name * * @throws Exception the exception */ public String getRepositoryName() throws Exception { return WCMCoreUtils.getRepository().getConfiguration().getName(); } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#encodeHTML(java.lang.String) */ public String encodeHTML(String text) throws Exception { return Utils.encodeHTML(text) ; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getAttachments() */ public List<Node> getAttachments() throws Exception { List<Node> attachments = new ArrayList<Node>() ; NodeIterator childrenIterator = getNode().getNodes();; TemplateService templateService = getApplicationComponent(TemplateService.class) ; while (childrenIterator.hasNext()) { Node childNode = childrenIterator.nextNode(); String nodeType = childNode.getPrimaryNodeType().getName(); List<String> listCanCreateNodeType = Utils.getListAllowedFileType(getNode(), templateService) ; if (listCanCreateNodeType.contains(nodeType)) attachments.add(childNode); } return attachments; } public String getViewableLink(Node attNode, Parameter[] params) throws Exception { return ""; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getComments() */ public List<Node> getComments() throws Exception { return getApplicationComponent(CommentsService.class).getComments(getOriginalNode(), getLanguage()) ; } public List<Node> getSortedComments() throws Exception { return Lists.reverse(this.getComments()); } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getComponentInstanceOfType(java.lang.String) */ public Object getComponentInstanceOfType(String className) { Object service = null; try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class object = loader.loadClass(className); service = getApplicationComponent(object); } catch (ClassNotFoundException ex) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", ex); } } return service; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getDownloadLink(javax.jcr.Node) */ public String getDownloadLink(Node node) throws Exception { return org.exoplatform.wcm.webui.Utils.getDownloadLink(node); } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getIcons(javax.jcr.Node, java.lang.String) */ public String getIcons(Node node, String size) throws Exception { return Utils.getNodeTypeIcon(node, size) ; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getImage(javax.jcr.Node) */ public String getImage(Node node) throws Exception { DownloadService dservice = getApplicationComponent(DownloadService.class) ; InputStreamDownloadResource dresource ; Node imageNode = node.getNode(Utils.EXO_IMAGE) ; InputStream input = imageNode.getProperty(Utils.JCR_DATA).getStream() ; dresource = new InputStreamDownloadResource(input, "image") ; dresource.setDownloadName(node.getName()) ; return dservice.getDownloadLink(dservice.addDownloadResource(dresource)) ; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getLanguage() */ public String getLanguage() { return language_ ; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#setLanguage(java.lang.String) */ public void setLanguage(String language) { language_ = language ; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getPortalName() */ public String getPortalName() { PortalContainerInfo containerInfo = WCMCoreUtils.getService(PortalContainerInfo.class); return containerInfo.getContainerName(); } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getRelations() */ public List<Node> getRelations() throws Exception { List<Node> relations = new ArrayList<Node>() ; if (getNode().hasProperty(Utils.EXO_RELATION)) { Value[] vals = getNode().getProperty(Utils.EXO_RELATION).getValues(); for (int i = 0; i < vals.length; i++) { String uuid = vals[i].getString(); Node node = getNodeByUUID(uuid); relations.add(node); } } return relations; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getRepository() */ public String getRepository() throws Exception { return ((ManageableRepository)getNode().getSession().getRepository()).getConfiguration().getName() ; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getRssLink() */ public String getRssLink() { return null ; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#isRssLink() */ public boolean isRssLink() { return false ; } /** * Checks if allow render fast publish link for the inline editting * * @return true, if need to render fast publish link */ public boolean isFastPublishLink() { return false ; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getSupportedLocalise() */ public List getSupportedLocalise() throws Exception { MultiLanguageService multiLanguageService = getApplicationComponent(MultiLanguageService.class) ; return multiLanguageService.getSupportedLanguages(getNode()) ; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getViewTemplate(java.lang.String, java.lang.String) */ public String getViewTemplate(String nodeTypeName, String templateName) throws Exception { TemplateService tempServ = getApplicationComponent(TemplateService.class) ; return tempServ.getTemplatePath(false, nodeTypeName, templateName) ; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getWebDAVServerPrefix() */ public String getWebDAVServerPrefix() throws Exception { PortletRequestContext portletRequestContext = PortletRequestContext.getCurrentInstance() ; String prefixWebDAV = portletRequestContext.getRequest().getScheme() + "://" + portletRequestContext.getRequest().getServerName() + ":" + String.format("%s",portletRequestContext.getRequest().getServerPort()) ; return prefixWebDAV ; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.NodePresentation#getWorkspaceName() */ public String getWorkspaceName() throws Exception { return getNode().getSession().getWorkspace().getName(); } /** * Gets the node by uuid. * * @param uuid the uuid * * @return the node by uuid */ public Node getNodeByUUID(String uuid) { ManageableRepository manageRepo = WCMCoreUtils.getRepository(); String[] workspaces = manageRepo.getWorkspaceNames() ; //TODO: SystemProvider or SessionProvider SessionProvider provider = WCMCoreUtils.getSystemSessionProvider(); for(String ws : workspaces) { try { return provider.getSession(ws, manageRepo).getNodeByUUID(uuid) ; } catch (ItemNotFoundException e) { continue; } catch (RepositoryException e) { continue; } } return null; } /** * Retrieve all categories of a node. * * @param node the node * * @return the categories * * @throws Exception the exception */ public List<Node> getCategories(Node node) throws Exception { TaxonomyService taxonomyService = getApplicationComponent(TaxonomyService.class); return taxonomyService.getCategories(node,getRepositoryName()); } /** * Retrieve all tags of a node. * * @param node the node * * @return the tags * * @throws Exception the exception */ public List<Node> getTags(Node node) throws Exception { NewFolksonomyService folksonomyService = getApplicationComponent(NewFolksonomyService.class); return folksonomyService.getLinkedTagsOfDocumentByScope(NewFolksonomyService.PRIVATE, getStrValue(Utils.PRIVATE, node), node, getWorkspaceName()); } /** * Retrieve the voting rate. * * @param node the node * * @return the votes * * @throws Exception the exception */ public long getVotingRate(Node node) throws Exception { VotingService votingService = getApplicationComponent(VotingService.class); return votingService.getVoteTotal(node); } /** * Retrieve the image in property value. * * @param node the node * @param propertyName the property name * * @return the image in property * * @throws Exception the exception */ public String getImageURIInProperty(Node node, String propertyName) throws Exception { try { InputStream input = node.getProperty(propertyName).getStream() ; InputStreamDownloadResource dresource = new InputStreamDownloadResource(input, "image") ; dresource.setDownloadName(node.getName()) ; DownloadService dservice = getApplicationComponent(DownloadService.class) ; return dservice.getDownloadLink(dservice.addDownloadResource(dresource)) ; } catch (Exception e) { return null; } } /** * Retrieve the portlet preference value. * * @param preferenceName the preference name * * @return the portlet preference value */ public String getPortletPreferenceValue(String preferenceName) { WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); if(requestContext instanceof PortletRequestContext) { PortletRequestContext context = PortletRequestContext.class.cast(requestContext); return context.getRequest().getPreferences().getValue(preferenceName,null); } return null; } /** * Retrieve the portlet preference values. * * @param preferenceName the preference name * * @return the portlet preference values */ public String[] getPortletPreferenceValues(String preferenceName) { WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); if(requestContext instanceof PortletRequestContext) { PortletRequestContext context = PortletRequestContext.class.cast(requestContext); return context.getRequest().getPreferences().getValues(preferenceName,null); } return null; } public String getTemplateSkin(String nodeTypeName, String skinName) throws Exception { TemplateService tempServ = getApplicationComponent(TemplateService.class) ; return tempServ.getSkinPath(nodeTypeName, skinName, getLanguage()) ; } private String getStrValue(String scope, Node node) throws Exception { StringBuilder ret = new StringBuilder(); if (Utils.PRIVATE.equals(scope)) ret.append(node.getSession().getUserID()); else if (Utils.GROUP.equals(scope)) { for (String group : Utils.getGroups()) ret.append(group).append(';'); ret.deleteCharAt(ret.length() - 1); } return ret.toString(); } public boolean isEnableComment() { return enableComment; } public boolean isEnableVote() { return enableVote; } public void setEnableComment(boolean value) { enableComment = value; } public void setEnableVote(boolean value) { enableVote = value; } /** * @param orgNode Processed node * @param propertyName which property used for editing * @param inputType input type for editing: TEXT, TEXTAREA, WYSIWYG * @param cssClass class name for CSS, should implement: cssClass, [cssClass]Title * Edit[cssClass] as relative css * Should create the function: InlineEditor.presentationRequestChange[cssClass] * to request the rest-service * @param isGenericProperty set as true to use generic javascript function, other wise, must create * the correctspond function InlineEditor.presentationRequestChange[cssClass] * @param arguments Extra parameter for Input component (toolbar, width, height,.. for CKEditor/TextArea) * @return String that can be put on groovy template * @throws Exception */ public String getInlineEditingField(Node orgNode, String propertyName, String defaultValue, String inputType, String idGenerator, String cssClass, boolean isGenericProperty, String... arguments) throws Exception { return org.exoplatform.ecm.webui.utils.Utils.getInlineEditingField(orgNode, propertyName, defaultValue, inputType, idGenerator, cssClass, isGenericProperty, arguments); } public String getInlineEditingField(Node orgNode, String propertyName) throws Exception { return org.exoplatform.ecm.webui.utils.Utils.getInlineEditingField(orgNode, propertyName); } public String getMediaState() { return mediaState; } public void switchMediaState() { mediaState = MEDIA_STATE_DISPLAY.equals(mediaState) ? MEDIA_STATE_NONE : MEDIA_STATE_DISPLAY; } public boolean isDisplayAlternativeText() { return false; } @Override public boolean playAudioDescription() { return false; } @Override public boolean switchBackAudioDescription() { return false; } @Override public String getActionOpenDocInDesktop() throws Exception { return this.event("OpenDocInDesktop"); } @Override public UIPopupContainer getPopupContainer() throws Exception { return null; } static public class OpenDocInDesktopActionListener extends EventListener<UIBaseNodePresentation> { public void execute(Event<UIBaseNodePresentation> event) throws Exception { UIBaseNodePresentation uicomp = event.getSource() ; Node node = uicomp.getNode(); Utils.openDocumentInDesktop(node, uicomp.getPopupContainer(), event); } } public String getRelativeTimeLabel(WebuiBindingContext webuiBindingContext, Date postedTime) { Locale locale = webuiBindingContext.getRequestContext().getLocale(); long postedTimeLong = postedTime.getTime(); return DateUtils.getRelativeTimeLabel(locale, postedTimeLong); } }
18,435
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
AbstractActionComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/presentation/AbstractActionComponent.java
/*************************************************************************** * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. * **************************************************************************/ package org.exoplatform.ecm.webui.presentation; import java.util.ArrayList; import java.util.List; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.core.UIComponent; /** * Created by The eXo Platform SARL * Author : Hoang Van Hung * hunghvit@gmail.com * Sep 18, 2009 */ public abstract class AbstractActionComponent extends UIComponent { private List<Class> lstComponentupdate = new ArrayList<Class>(); public void setLstComponentupdate(List<Class> lstComponentupdate) { this.lstComponentupdate = lstComponentupdate; } public List<Class> getLstComponentupdate() { return lstComponentupdate; } public void updateAjax(WebuiRequestContext requestcontext) { for (Class clazz : lstComponentupdate) { requestcontext.addUIComponentToUpdateByAjax(this.getAncestorOfType((Class<UIComponent>)clazz)); } } }
1,801
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
NodePresentation.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui/src/main/java/org/exoplatform/ecm/webui/presentation/NodePresentation.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.presentation; import java.util.List; import javax.jcr.Node; import org.exoplatform.web.application.Parameter; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIPopupContainer; /** * Created by The eXo Platform SARL Author : Dang Van Minh * minh.dang@exoplatform.com May 8, 2008 3:22:08 PM */ public interface NodePresentation { public static final String MEDIA_STATE_DISPLAY = "DISPLAY"; public static final String MEDIA_STATE_NONE = "NONE"; /** * Sets enable vote * * @param value value to set */ public void setEnableVote(boolean value); /** * checks if enable vote * */ public boolean isEnableVote(); /** * Sets enable comment * * @param value value to set */ public void setEnableComment(boolean value); /** * checks if enable comment * */ public boolean isEnableComment(); /** * Sets the node. * * @param node the new node */ public void setNode(Node node); /** * Gets the node. * * @return the node * @throws Exception the exception */ public Node getNode() throws Exception; /** * Gets the original node. * * @return the original node * @throws Exception the exception */ public Node getOriginalNode() throws Exception; /** * Gets the node type. * * @return the node type * @throws Exception the exception */ public String getNodeType() throws Exception; /** * Checks if is node type supported. * * @return true, if is node type supported */ public boolean isNodeTypeSupported(); /** * Gets the template path. * * @return the template path * @throws Exception the exception */ public String getTemplatePath() throws Exception; /** * Gets the relations. * * @return the relations * @throws Exception the exception */ public List<Node> getRelations() throws Exception; /** * Gets the attachments. * * @return the attachments * @throws Exception the exception */ public List<Node> getAttachments() throws Exception; /** * Gets the viewable link. * * @return the viewable URL * @throws Exception the exception */ public String getViewableLink(Node attNode, Parameter[] params) throws Exception; /** * Checks if is rss link. * * @return true, if is rss link */ public boolean isRssLink(); /** * Gets the rss link. * * @return the rss link */ public String getRssLink(); /** * Gets the supported localise. * * @return the supported localise * @throws Exception the exception */ public List getSupportedLocalise() throws Exception; /** * Sets the language. * * @param language the new language */ public void setLanguage(String language); /** * Gets the language. * * @return the language */ public String getLanguage(); /** * Gets the component instance of type. * * @param className the class name * @return the component instance of type */ public Object getComponentInstanceOfType(String className); /** * Gets the web dav server prefix. * * @return the web dav server prefix * @throws Exception the exception */ public String getWebDAVServerPrefix() throws Exception; /** * Gets the image. * * @param node the node * @return the image * @throws Exception the exception */ public String getImage(Node node) throws Exception; /** * Gets the portal name. * * @return the portal name */ public String getPortalName(); /** * Gets the repository. * * @return the repository * @throws Exception the exception */ public String getRepository() throws Exception; /** * Gets the workspace name. * * @return the workspace name * @throws Exception the exception */ public String getWorkspaceName() throws Exception; /** * Gets the view template. * * @param nodeTypeName the node type name * @param templateName the template name * @return the view template * @throws Exception the exception */ public String getViewTemplate(String nodeTypeName, String templateName) throws Exception; /** * Get the skin of template if it's existing * @param nodeTypeName The node type name * @param skinName Skin name * @return The skin template * @throws Exception */ public String getTemplateSkin(String nodeTypeName, String skinName) throws Exception; /** * Get UIComponent for comment * @return * @throws Exception */ public UIComponent getCommentComponent() throws Exception; /** * Get UIComponent to remove attachment in document * @return * @throws Exception */ public UIComponent getRemoveAttach() throws Exception; /** * Get UIComponent to remove comment in document * @return * @throws Exception */ public UIComponent getRemoveComment() throws Exception; /** * Gets the comments. * * @return the comments * @throws Exception the exception */ public List<Node> getComments() throws Exception; /** * Gets the download link. * * @param node the node * @return the download link * @throws Exception the exception */ public String getDownloadLink(Node node) throws Exception; /** * Encode html. * * @param text the text * @return the string * @throws Exception the exception */ public String encodeHTML(String text) throws Exception; /** * Gets the icons. * * @param node the node * @param size the size * @return the icons * @throws Exception the exception */ public String getIcons(Node node, String size) throws Exception; /** * Get the UIComponent which to display file * @param mimeType * @return * @throws Exception */ public UIComponent getUIComponent(String mimeType) throws Exception; /** * @param orgNode Processed node * @param propertyName which property used for editing * @param inputType input type for editing: TEXT, TEXTAREA, WYSIWYG * @param cssClass class name for CSS, should implement: cssClass, [cssClass]Title * Edit[cssClass] as relative css * Should create the function: InlineEditor.presentationRequestChange[cssClass] * to request the rest-service * @param isGenericProperty set as true to use generic javascript function, other wise, must create * the correctspond function InlineEditor.presentationRequestChange[cssClass] * @param arguments Extra parameter for Input component (toolbar, width, height,.. for CKEditor/TextArea) * @return String that can be put on groovy template * @throws Exception */ public String getInlineEditingField(Node orgNode, String propertyName, String defaultValue, String inputType, String idGenerator, String cssClass, boolean isGenericProperty, String... arguments) throws Exception; public String getInlineEditingField(Node orgNode, String propertyName) throws Exception; /** * gets the status of display audio description for accessible media * @return status of display audio description for accessible media */ public String getMediaState(); /** * switches the status of display audio description for accessible media */ public void switchMediaState(); /** * * @return true if node can display audio description */ public boolean isDisplayAlternativeText(); /** * * @return true if can switch to play audio description of the media */ public boolean playAudioDescription(); /** * * @return true if can switch back from original node from audio description */ public boolean switchBackAudioDescription(); public String getActionOpenDocInDesktop() throws Exception; public UIPopupContainer getPopupContainer() throws Exception; }
9,067
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z