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
SyncingFileManagerComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/SyncingFileManagerComponent.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui; import java.util.Arrays; import java.util.List; import org.exoplatform.ecm.webui.clouddrives.CloudDriveContext; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.UIWorkingArea; import org.exoplatform.ecm.webui.component.explorer.control.UIActionBar; import org.exoplatform.ecm.webui.component.explorer.control.UIAddressBar; import org.exoplatform.ecm.webui.component.explorer.control.UIControl; import org.exoplatform.services.cms.clouddrives.webui.filters.SyncingCloudFileFilter; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.web.application.Parameter; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilters; import org.exoplatform.webui.ext.manager.UIAbstractManager; import org.exoplatform.webui.ext.manager.UIAbstractManagerComponent; /** * SyncingFile hidden action in working area used by Cloud Drive Javascript to * mark synchronzing files in UI. Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: RefreshCloudDriveManagerComponent.java 00000 Dec 15, 2014 * pnedonosko $ */ @ComponentConfig(lifecycle = UIContainerLifecycle.class, events = { @EventConfig(listeners = SyncingFileManagerComponent.SyncingFileActionListener.class) }) public class SyncingFileManagerComponent extends UIAbstractManagerComponent { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(SyncingFileManagerComponent.class); /** The Constant EVENT_NAME. */ public static final String EVENT_NAME = "SyncingFile"; /** The Constant FILTERS. */ protected static final List<UIExtensionFilter> FILTERS = Arrays.asList(new UIExtensionFilter[] { new SyncingCloudFileFilter() }); /** * The listener interface for receiving syncingFileAction events. The class * that is interested in processing a syncingFileAction event implements this * interface, and the object created with that class is registered with a * component using the component's <code>addSyncingFileActionListener</code> * method. When the syncingFileAction event occurs, that object's appropriate * method is invoked. */ public static class SyncingFileActionListener extends EventListener<SyncingFileManagerComponent> { /** * {@inheritDoc} */ public void execute(Event<SyncingFileManagerComponent> event) throws Exception { // code adopted from UIAddressBar.RefreshSessionActionListener.execute() // -- effect of refresh here, // it should be never invoked (menu action invisible) UIJCRExplorer explorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); explorer.getSession().refresh(false); explorer.refreshExplorer(); UIWorkingArea workingArea = explorer.getChild(UIWorkingArea.class); UIActionBar actionBar = workingArea.getChild(UIActionBar.class); UIControl control = explorer.getChild(UIControl.class); if (control != null) { UIAddressBar addressBar = control.getChild(UIAddressBar.class); if (addressBar != null) { actionBar.setTabOptions(addressBar.getSelectedViewName()); } } } } /** * Gets the filters. * * @return the filters */ @UIExtensionFilters public List<UIExtensionFilter> getFilters() { return FILTERS; } /** * {@inheritDoc} */ @Override public String renderEventURL(boolean ajax, String name, String beanId, Parameter[] params) throws Exception { if (EVENT_NAME.equals(name)) { CloudDriveContext.init(this); } return super.renderEventURL(ajax, name, beanId, params); } @Override public Class<? extends UIAbstractManager> getUIAbstractManagerClass() { return null; } }
5,162
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDriveContextFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/CloudDriveContextFilter.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui; import java.io.IOException; import org.exoplatform.container.PortalContainer; import org.exoplatform.portal.application.PortalApplication; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.web.WebAppController; import org.exoplatform.web.filter.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; /** * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudDriveContextFilter.java 00000 Nov 17, 2016 pnedonosko $ */ @Deprecated // TODO should not be used in PLF V6 public class CloudDriveContextFilter implements Filter { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(CloudDriveContextFilter.class); /** * {@inheritDoc} */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { PortalContainer container = PortalContainer.getInstance(); WebAppController controller = (WebAppController) container.getComponentInstanceOfType(WebAppController.class); PortalApplication app = controller.getApplication(PortalApplication.PORTAL_APPLICATION_ID); final CloudDriveLifecycle lifecycle = new CloudDriveLifecycle(); try { app.getApplicationLifecycle().add(lifecycle); chain.doFilter(request, response); } finally { app.getApplicationLifecycle().remove(lifecycle); } } }
2,487
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDriveUIService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/CloudDriveUIService.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.exoplatform.ecm.webui.CloudDriveUIMenuAction; import org.picocontainer.Startable; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.component.ComponentPlugin; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.views.ManageViewService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.impl.RepositoryContainer; import org.exoplatform.services.jcr.impl.WorkspaceContainer; import org.exoplatform.services.jcr.impl.backup.ResumeException; import org.exoplatform.services.jcr.impl.backup.SuspendException; import org.exoplatform.services.jcr.impl.backup.Suspendable; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.ext.UIExtension; import org.exoplatform.webui.ext.UIExtensionManager; /** * Add ImportCloudDocument button in ListView. We're doing this by hack of * already stored DMS navigation. */ public class CloudDriveUIService implements Startable { /** * Instance of this class will be registered in ECMS's system workspace of JCR * repository. It has maximum priority and will be suspended on a repository * stop first. It invokes ECMS menu restoration to remove CD actions for a * case of the extension uninstallation. */ class ViewRestorer implements Suspendable { /** The suspended. */ boolean suspended = false; /** * {@inheritDoc} */ @Override public void suspend() throws SuspendException { try { restoreViews(); LOG.info("Cloud Drive actions successfully disabled"); } catch (Exception e) { LOG.error("Error disabling Cloud Drive actions: " + e.getMessage(), e); } suspended = true; } /** * {@inheritDoc} */ @Override public void resume() throws ResumeException { suspended = true; } /** * {@inheritDoc} */ @Override public boolean isSuspended() { return suspended; } /** * {@inheritDoc} */ @Override public int getPriority() { return Integer.MAX_VALUE; // it should be very first (sure it's not 100% // this way) } } /** The Constant LOG. */ private static final Log LOG = ExoLogger.getLogger(CloudDriveUIService.class); /** The Constant DMS_SYSTEM_WORKSPACE. */ protected static final String DMS_SYSTEM_WORKSPACE = "dms-system"; /** The Constant EXO_BUTTONS. */ protected static final String EXO_BUTTONS = "exo:buttons"; /** The Constant ECD_USER_BUTTONS. */ protected static final String ECD_USER_BUTTONS = "ecd:userButtons"; /** The Constant ECD_BUTTONS. */ protected static final String ECD_BUTTONS = "ecd:buttons"; /** The Constant ECD_DEFAULT_BUTTONS. */ protected static final String ECD_DEFAULT_BUTTONS = "ecd:defaultButtons"; /** The Constant CONNECT_CLOUD_DRIVE_ACTION. */ public static final String CONNECT_CLOUD_DRIVE_ACTION = "add.connect.clouddrive.action"; /** The jcr service. */ protected final RepositoryService jcrService; /** The manage view. */ protected final ManageViewService manageView; /** The drive service. */ protected final CloudDriveService driveService; /** The ui extensions. */ protected final UIExtensionManager uiExtensions; /** The default menu actions. */ protected final Set<String> defaultMenuActions = new HashSet<String>(); /** The views. */ protected final List<String> VIEWS = Arrays.asList("List/List", "Admin/Admin", "Web/Authoring", "Icons/Icons", "Categories/Collaboration"); /** * Instantiates a new cloud drive UI service. * * @param repoService the repo service * @param driveService the drive service * @param uiExtensions the ui extensions * @param manageView the manage view */ public CloudDriveUIService(RepositoryService repoService, CloudDriveService driveService, UIExtensionManager uiExtensions, ManageViewService manageView) { this.jcrService = repoService; this.manageView = manageView; this.driveService = driveService; this.uiExtensions = uiExtensions; } /** * Adds the plugin. * * @param plugin the plugin */ public void addPlugin(ComponentPlugin plugin) { if (plugin instanceof CloudDriveUIExtension) { // default menu action to initialize CloudDriveUIExtension ext = (CloudDriveUIExtension) plugin; defaultMenuActions.addAll(ext.getDefaultActions()); } else { LOG.warn("Cannot recognize component plugin for " + plugin.getName() + ": type " + plugin.getClass() + " not supported"); } } /** * List of Cloud Drive actions configured to apper in menu by default. * * @return List of Strings with action names * @throws Exception the exception */ protected Set<String> getDefaultActions() throws Exception { // find all Cloud Drive actions configured by default for action bar Set<String> cdActions = new LinkedHashSet<String>(); for (UIExtension ext : uiExtensions.getUIExtensions(ManageViewService.EXTENSION_TYPE)) { String menuAction = ext.getName(); if (defaultMenuActions.contains(menuAction)) { cdActions.add(menuAction); } } return cdActions; } /** * All Cloud Drive actions registered in the system. * * @return List of Strings with action names * @throws Exception the exception */ protected List<String> getAllActions() throws Exception { // find all Cloud Drive actions configured by default for action bar List<String> cdActions = new ArrayList<String>(); for (UIExtension ext : uiExtensions.getUIExtensions(ManageViewService.EXTENSION_TYPE)) { Class<? extends UIComponent> extComp = ext.getComponent(); if (CloudDriveUIMenuAction.class.isAssignableFrom(extComp)) { cdActions.add(ext.getName()); } } return cdActions; } /** * Read all buttons actions from given node, in buttons property, to given * string builder. * * @param node {@link Node} * @return String The list of buttons * @throws RepositoryException the repository exception */ protected String readViewActions(Node node, String propertyName) throws RepositoryException { List<String> actionList = new ArrayList<>(); if (node.hasProperty(propertyName)) { String[] actions = node.getProperty(propertyName).getString().split(";"); for (int i = 0; i < actions.length; i++) { String a = actions[i].trim(); if (!actionList.contains(a)) { // add only if not already exists actionList.add(a); } } } return String.join(";",actionList); } /** * Add Cloud Drive actions to ECMS actions menu if they are not already there. * This method adds Cloud Drive actions saved in previous container execution * (saved on container stop, see {@link #restoreViews()} ). If no saved * actions, then defaults will be added from configuration. * * @throws Exception the exception */ protected void prepareViews() throws Exception { SessionProvider jcrSessions = SessionProvider.createSystemProvider(); try { Set<String> defaultConfiguredActions = getDefaultActions(); Session session = jcrSessions.getSession(DMS_SYSTEM_WORKSPACE, jcrService.getCurrentRepository()); for (String view : VIEWS) { Node viewNode = manageView.getViewByName(view, jcrSessions); // read all already existing ECMS actions StringBuilder newActions = new StringBuilder(); newActions.append(readViewActions(viewNode, EXO_BUTTONS)); int menuLength = newActions.length(); // read all actions saved for CD StringBuilder cdActions = new StringBuilder(); cdActions.append(readViewActions(viewNode, ECD_BUTTONS)); // merge others with CD for real action bar set if (cdActions.length() > 0) { newActions.append(';'); newActions.append(' '); newActions.append(cdActions); } if (newActions.length() == menuLength) { // no CD actions saved previously - add defaults cdActions.append(' '); for (String cda : defaultConfiguredActions) { // doing some trick to fix the string: make first char lowercase String acs = uncapitalize(cda); if (newActions.indexOf(acs) < 0) { newActions.append(';'); newActions.append(' '); newActions.append(acs); } if (cdActions.indexOf(acs) < 0) { cdActions.append(acs); cdActions.append(';'); } } // save CD actions as initial user actions String cdButtons = cdActions.toString().trim(); if (viewNode.canAddMixin(ECD_USER_BUTTONS)) { viewNode.addMixin(ECD_USER_BUTTONS); } viewNode.setProperty(ECD_BUTTONS, cdButtons); if (viewNode.canAddMixin(ECD_DEFAULT_BUTTONS)) { viewNode.addMixin(ECD_DEFAULT_BUTTONS); } viewNode.setProperty(ECD_DEFAULT_BUTTONS, cdButtons); } else { // check if we don't have new defaults in configuration (actual for // upgrades since 1.3.0) StringBuilder defaultSavedActions = new StringBuilder(); defaultSavedActions.append(readViewActions(viewNode, ECD_DEFAULT_BUTTONS)); Set<String> addDefaultActions = new LinkedHashSet<String>(); for (String cda : defaultConfiguredActions) { String acs = uncapitalize(cda); // make first char lowercase here if (defaultSavedActions.indexOf(acs) < 0) { addDefaultActions.add(acs); defaultSavedActions.append(acs); defaultSavedActions.append(';'); } } if (addDefaultActions.size() > 0) { for (String acs : addDefaultActions) { if (newActions.indexOf(acs) < 0) { newActions.append(';'); newActions.append(' '); newActions.append(acs); } if (cdActions.indexOf(acs) < 0) { cdActions.append(acs); cdActions.append(';'); } } viewNode.setProperty(ECD_BUTTONS, cdActions.toString().trim()); if (viewNode.canAddMixin(ECD_DEFAULT_BUTTONS)) { viewNode.addMixin(ECD_DEFAULT_BUTTONS); } viewNode.setProperty(ECD_DEFAULT_BUTTONS, defaultSavedActions.toString().trim()); } } if (LOG.isDebugEnabled()) { LOG.debug("New buttons: " + newActions.toString()); } viewNode.setProperty(EXO_BUTTONS, newActions.toString()); } session.save(); } finally { jcrSessions.close(); } } /** * Remove Cloud Drive actions from ECMS actions menu and store them in * dedicated property. We remove actions to make the add-on uninstallation * safe (don't leave our menu actions in the content). * * @throws Exception the exception */ protected void restoreViews() throws Exception { SessionProvider jcrSessions = SessionProvider.createSystemProvider(); try { Session session = jcrSessions.getSession(DMS_SYSTEM_WORKSPACE, jcrService.getCurrentRepository()); for (String view : VIEWS) { Node viewNode = manageView.getViewByName(view, jcrSessions); String newActions = ""; String cdActions = ""; // split current actions, including customized by user, to Cloud Drive's // and others if (viewNode.hasProperty(EXO_BUTTONS)) { String[] actions = viewNode.getProperty(EXO_BUTTONS).getString().split(";"); List<String> cloudDriveActions = new ArrayList<>(); List<String> defaultActions = new ArrayList<>(); for (String action : actions) { String a = action.trim(); String aname = capitalize(a); UIExtension ae = uiExtensions.getUIExtension(ManageViewService.EXTENSION_TYPE, aname); if (ae != null) { if (CloudDriveUIMenuAction.class.isAssignableFrom(ae.getComponent())) { if (!cloudDriveActions.contains(a)) { // add only if not already exists cloudDriveActions.add(a); } } else if (!defaultActions.contains(a)) { // add only if not already defaultActions.add(a); } } else { LOG.warn("Cannot find UIExtension for action " + aname); } } newActions = String.join(";", defaultActions); cdActions = String.join(";", cloudDriveActions); } if (LOG.isDebugEnabled()) { LOG.debug("Stored user buttons: " + cdActions); } viewNode.setProperty(EXO_BUTTONS, newActions); viewNode.setProperty(ECD_BUTTONS, cdActions); } session.save(); } finally { jcrSessions.close(); } } /** * Capitalize. * * @param text the text * @return the string */ protected String capitalize(String text) { char[] tc = text.toCharArray(); if (tc.length > 0) { tc[0] = Character.toUpperCase(tc[0]); } return new String(tc); } /** * Uncapitalize. * * @param text the text * @return the string */ protected String uncapitalize(String text) { char[] tc = text.toCharArray(); if (tc.length > 0) { tc[0] = Character.toLowerCase(tc[0]); } return new String(tc); } /** * {@inheritDoc} */ @Override public void start() { try { prepareViews(); // also register menu restorer... // XXX yeah, we do nasty things for this as Startable.stop() works later, // when JCR already stopped. List<?> repoContainers = ExoContainerContext.getCurrentContainer().getComponentInstancesOfType(RepositoryContainer.class); for (Object rco : repoContainers) { RepositoryContainer rc = (RepositoryContainer) rco; WorkspaceContainer wc = rc.getWorkspaceContainer(DMS_SYSTEM_WORKSPACE); if (wc != null) { wc.registerComponentInstance(new ViewRestorer()); } } LOG.info("Cloud Drive actions successfully enabled"); } catch (Exception e) { LOG.error("Error enabling Cloud Drive actions: " + e.getMessage(), e); } } /** * {@inheritDoc} */ @Override public void stop() { // nothing, see ViewRestorer class above } }
16,437
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
RefreshViewManagerComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/RefreshViewManagerComponent.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui; import java.util.Arrays; import java.util.List; import org.exoplatform.ecm.webui.clouddrives.CloudDriveContext; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.UIWorkingArea; import org.exoplatform.ecm.webui.component.explorer.control.UIActionBar; import org.exoplatform.ecm.webui.component.explorer.control.UIAddressBar; import org.exoplatform.ecm.webui.component.explorer.control.UIControl; import org.exoplatform.services.cms.clouddrives.webui.filters.CloudDriveFilter; import org.exoplatform.ecm.webui.filters.CloudFileFilter; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.web.application.Parameter; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilters; import org.exoplatform.webui.ext.manager.UIAbstractManager; import org.exoplatform.webui.ext.manager.UIAbstractManagerComponent; /** * RefreshView hidden action in working area used by Cloud Drive Javascript to * refresh the user view automatically. Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: RefreshCloudDriveManagerComponent.java 00000 Nov 05, 2012 * pnedonosko $ */ @ComponentConfig(lifecycle = UIContainerLifecycle.class, events = { @EventConfig(listeners = RefreshViewManagerComponent.RefreshViewActionListener.class, csrfCheck = false) }) public class RefreshViewManagerComponent extends UIAbstractManagerComponent { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(RefreshViewManagerComponent.class); /** The Constant EVENT_NAME. */ public static final String EVENT_NAME = "RefreshView"; /** The Constant FILTERS. */ protected static final List<UIExtensionFilter> FILTERS = Arrays.asList(new UIExtensionFilter[] { new CloudDriveFilter(), new CloudFileFilter() }); /** * The listener interface for receiving refreshViewAction events. The class * that is interested in processing a refreshViewAction event implements this * interface, and the object created with that class is registered with a * component using the component's <code>addRefreshViewActionListener</code> * method. When the refreshViewAction event occurs, that object's appropriate * method is invoked. */ public static class RefreshViewActionListener extends EventListener<RefreshViewManagerComponent> { /** * {@inheritDoc} */ public void execute(Event<RefreshViewManagerComponent> event) throws Exception { // code adopted from UIAddressBar.RefreshSessionActionListener.execute() UIJCRExplorer explorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); explorer.getSession().refresh(false); explorer.refreshExplorer(); UIWorkingArea workingArea = explorer.getChild(UIWorkingArea.class); UIActionBar actionBar = workingArea.getChild(UIActionBar.class); UIControl control = explorer.getChild(UIControl.class); if (control != null) { UIAddressBar addressBar = control.getChild(UIAddressBar.class); if (addressBar != null) { actionBar.setTabOptions(addressBar.getSelectedViewName()); } } } } /** * Gets the filters. * * @return the filters */ @UIExtensionFilters public List<UIExtensionFilter> getFilters() { return FILTERS; } /** * {@inheritDoc} */ @Override public String renderEventURL(boolean ajax, String name, String beanId, Parameter[] params) throws Exception { if (EVENT_NAME.equals(name)) { CloudDriveContext.init(this); } return super.renderEventURL(ajax, name, beanId, params); } @Override public Class<? extends UIAbstractManager> getUIAbstractManagerClass() { return null; } }
5,109
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PortalEnvironment.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/PortalEnvironment.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; import org.exoplatform.services.cms.clouddrives.CloudDriveEnvironment; import org.exoplatform.services.cms.clouddrives.CloudDriveException; import org.exoplatform.services.cms.clouddrives.CloudDrive.Command; import org.exoplatform.web.application.RequestContext; import org.exoplatform.webui.application.WebuiRequestContext; /** * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: PortalEnvironment.java 00000 Jan 16, 2014 pnedonosko $ */ public class PortalEnvironment extends CloudDriveEnvironment { /** * The Class Settings. */ protected class Settings { /** The context. */ final RequestContext context; /** The prev context. */ RequestContext prevContext; /** * Instantiates a new settings. * * @param context the context */ Settings(RequestContext context) { this.context = context; } } /** The config. */ protected final Map<Command, Settings> config = Collections.synchronizedMap(new WeakHashMap<Command, Settings>()); /** * Instantiates a new portal environment. */ public PortalEnvironment() { } /** * {@inheritDoc} */ @Override public void configure(Command command) throws CloudDriveException { super.configure(command); config.put(command, new Settings(WebuiRequestContext.getCurrentInstance())); } /** * {@inheritDoc} */ @Override public void prepare(Command command) throws CloudDriveException { super.prepare(command); Settings settings = config.get(command); if (settings != null) { settings.prevContext = WebuiRequestContext.getCurrentInstance(); WebuiRequestContext.setCurrentInstance(settings.context); } else { throw new CloudDriveException(this.getClass().getName() + " setting not configured for " + command + " to be prepared."); } } /** * {@inheritDoc} */ @Override public void cleanup(Command command) throws CloudDriveException { Settings settings = config.remove(command); if (settings != null) { WebuiRequestContext.setCurrentInstance(settings.prevContext); } else { throw new CloudDriveException(this.getClass().getName() + " setting not configured for " + command + " to be cleaned."); } super.cleanup(command); } }
3,314
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ShowConnectCloudDriveActionComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/ShowConnectCloudDriveActionComponent.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui; import org.exoplatform.ecm.webui.CloudDriveUIMenuAction; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.control.listener.UIActionBarActionListener; 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.event.Event; import org.exoplatform.webui.ext.manager.UIAbstractManager; import org.exoplatform.webui.ext.manager.UIAbstractManagerComponent; /** * The Class ShowConnectCloudDriveActionComponent. */ @ComponentConfig(events = { @EventConfig(listeners = ShowConnectCloudDriveActionComponent.ShowConnectCloudDriveActionListener.class) }) public class ShowConnectCloudDriveActionComponent extends UIAbstractManagerComponent implements CloudDriveUIMenuAction { /** * The listener interface for receiving showConnectCloudDriveAction events. * The class that is interested in processing a showConnectCloudDriveAction * event implements this interface, and the object created with that class is * registered with a component using the component's * <code>addShowConnectCloudDriveActionListener</code> method. When the * showConnectCloudDriveAction event occurs, that object's appropriate method * is invoked. */ public static class ShowConnectCloudDriveActionListener extends UIActionBarActionListener<ShowConnectCloudDriveActionComponent> { /** * {@inheritDoc} */ public void processEvent(Event<ShowConnectCloudDriveActionComponent> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); connectToDrive(event, uiExplorer); } /** * Connect to drive. * * @param event the event * @param uiExplorer the ui explorer * @throws Exception the exception */ private void connectToDrive(Event<? extends UIComponent> event, UIJCRExplorer uiExplorer) throws Exception { UIPopupContainer uiPopupContainer = uiExplorer.getChild(UIPopupContainer.class); // this form will initialize request context from its template uiPopupContainer.activate(ConnectCloudDriveForm.class, 400); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupContainer); } } /** * {@inheritDoc} */ @Override public Class<? extends UIAbstractManager> getUIAbstractManagerClass() { return null; } }
3,487
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDriveUIExtension.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/CloudDriveUIExtension.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.exoplatform.container.component.BaseComponentPlugin; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ValuesParam; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; /** * Configuration of Cloud Drive menu in ECMS. Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudDriveUIExtension.java 00000 Jan 31, 2014 pnedonosko $ */ public class CloudDriveUIExtension extends BaseComponentPlugin { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(CloudDriveUIExtension.class); /** The default actions. */ protected final Set<String> defaultActions = new HashSet<String>(); /** * Instantiates a new cloud drive UI extension. * * @param config the config */ public CloudDriveUIExtension(InitParams config) { ValuesParam params = config.getValuesParam("default-actions"); if (params != null) { for (Object ov : params.getValues()) { if (ov instanceof String) { defaultActions.add((String) ov); } } } else { LOG.warn("Value parameters' default-actions not specified. Nothing will be configured in ECMS menu for Cloud Drive."); } } /** * Gets the default actions. * * @return the default actions */ public Collection<String> getDefaultActions() { return Collections.unmodifiableSet(defaultActions); } }
2,505
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDriveLifecycle.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/CloudDriveLifecycle.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui; import org.exoplatform.container.ExoContainer; import org.exoplatform.portal.webui.container.UIContainer; import org.exoplatform.portal.webui.workspace.UIPortalApplication; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.web.application.Application; import org.exoplatform.web.application.ApplicationLifecycle; import org.exoplatform.web.application.RequestFailure; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIComponentDecorator; /** * This listener should hide navigation toolbar in the Platform page. The code * is similar to the one in Outlook add-in.<br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudDriveLifecycle.java 00000 Nov 17, 2016 pnedonosko $ */ @Deprecated // TODO should not be used in PLF V6 public class CloudDriveLifecycle implements ApplicationLifecycle<WebuiRequestContext> { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(CloudDriveLifecycle.class); /** The toolbar rendered. */ protected final ThreadLocal<Boolean> toolbarRendered = new ThreadLocal<Boolean>(); /** * Instantiates a new cloud drive lifecycle. */ public CloudDriveLifecycle() { // } /** * {@inheritDoc} */ @Override public void onInit(Application app) throws Exception { // nothing } /** * {@inheritDoc} */ @Override public void onStartRequest(Application app, WebuiRequestContext context) throws Exception { UIComponent toolbar = findToolbarComponent(app, context); if (toolbar != null && toolbar.isRendered()) { toolbarRendered.set(true); toolbar.setRendered(false); } } /** * {@inheritDoc} */ @Override public void onEndRequest(Application app, WebuiRequestContext context) throws Exception { UIComponent toolbar = findToolbarComponent(app, context); if (toolbar != null) { Boolean render = toolbarRendered.get(); if (render != null && render.booleanValue()) { // restore rendered if was rendered and set hidden explicitly toolbar.setRendered(true); } } } /** * {@inheritDoc} */ @Override public void onFailRequest(Application app, WebuiRequestContext context, RequestFailure failureType) { // nothing } /** * {@inheritDoc} */ @Override public void onDestroy(Application app) throws Exception { // nothing } // ******* internals ****** /** * Find toolbar component. * * @param app the app * @param context the context * @return the UI component * @throws Exception the exception */ protected UIComponent findToolbarComponent(Application app, WebuiRequestContext context) throws Exception { ExoContainer container = app.getApplicationServiceContainer(); if (container != null) { UIApplication uiApp = context.getUIApplication(); UIComponentDecorator uiViewWS = uiApp.findComponentById(UIPortalApplication.UI_VIEWING_WS_ID); if (uiViewWS != null) { UIContainer viewContainer = (UIContainer) uiViewWS.getUIComponent(); if (viewContainer != null) { UIContainer navContainer = viewContainer.getChildById("NavigationPortlet"); if (navContainer == null) { navContainer = viewContainer; } for (UIComponent child : navContainer.getChildren()) { if (UIContainer.class.isAssignableFrom(child.getClass())) { UIContainer childContainer = UIContainer.class.cast(child); UIComponent toolbar = childContainer.getChildById("UIToolbarContainer"); if (toolbar != null) { // attempt #1 return toolbar; } } } // attempt #2 return navContainer.findComponentById("UIToolbarContainer"); } } } return null; } }
4,998
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
RefreshCloudDriveManagerComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/RefreshCloudDriveManagerComponent.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui; import java.util.Arrays; import java.util.List; import org.exoplatform.ecm.webui.clouddrives.CloudDriveContext; import org.exoplatform.services.cms.clouddrives.webui.filters.CloudDriveFilter; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.web.application.Parameter; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilters; import org.exoplatform.webui.ext.manager.UIAbstractManager; import org.exoplatform.webui.ext.manager.UIAbstractManagerComponent; /** * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: RefreshCloudDriveManagerComponent.java 00000 Nov 05, 2012 * pnedonosko $ */ @ComponentConfig(lifecycle = UIContainerLifecycle.class) public class RefreshCloudDriveManagerComponent extends UIAbstractManagerComponent { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(RefreshCloudDriveManagerComponent.class); /** The Constant EVENT_NAME. */ public static final String EVENT_NAME = "RefreshCloudDrive"; /** The Constant FILTERS. */ protected static final List<UIExtensionFilter> FILTERS = Arrays.asList(new UIExtensionFilter[] { new CloudDriveFilter() }); /** * Gets the filters. * * @return the filters */ @UIExtensionFilters public List<UIExtensionFilter> getFilters() { return FILTERS; } /** * {@inheritDoc} */ @Override public String renderEventURL(boolean ajax, String name, String beanId, Parameter[] params) throws Exception { if (EVENT_NAME.equals(name)) { CloudDriveContext.init(this); return "javascript:void(0);//objectId"; } return super.renderEventURL(ajax, name, beanId, params); } @Override public Class<? extends UIAbstractManager> getUIAbstractManagerClass() { return null; } }
3,004
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
BaseCloudDriveForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/BaseCloudDriveForm.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui; import org.exoplatform.ecm.webui.clouddrives.CloudDriveContext; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.webui.core.UIPopupComponent; import org.exoplatform.webui.form.UIForm; /** * The Class BaseCloudDriveForm. */ public abstract class BaseCloudDriveForm extends UIForm implements UIPopupComponent { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(BaseCloudDriveForm.class); /** * Inits the context. * * @throws Exception the exception */ protected void initContext() throws Exception { CloudDriveContext.init(this); } /** * {@inheritDoc} */ @Override public void activate() { // nothing } /** * {@inheritDoc} */ @Override public void deActivate() { // nothing } }
1,721
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PushCloudFileManagerComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/PushCloudFileManagerComponent.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui; import java.util.Arrays; import java.util.List; import javax.jcr.Item; import javax.jcr.Node; import org.exoplatform.ecm.webui.clouddrives.CloudDriveContext; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.UIWorkingArea; import org.exoplatform.ecm.webui.component.explorer.control.UIActionBar; import org.exoplatform.ecm.webui.component.explorer.control.UIAddressBar; import org.exoplatform.ecm.webui.component.explorer.control.UIControl; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.clouddrives.CloudDriveStorage; import org.exoplatform.services.cms.clouddrives.DriveRemovedException; import org.exoplatform.services.cms.clouddrives.NotCloudDriveException; import org.exoplatform.services.cms.clouddrives.webui.filters.LocalNodeFilter; 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.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilters; import org.exoplatform.webui.ext.manager.UIAbstractManager; import org.exoplatform.webui.ext.manager.UIAbstractManagerComponent; /** * PushCloudFile action in working area used to force ignored nodes inside Cloud * Drive to push to cloud side.<br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: PushCloudFileManagerComponent.java 00000 Dec 15, 2014 * pnedonosko $ */ @ComponentConfig(lifecycle = UIContainerLifecycle.class, events = { @EventConfig(listeners = PushCloudFileManagerComponent.PushCloudFileActionListener.class) }) public class PushCloudFileManagerComponent extends UIAbstractManagerComponent { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(PushCloudFileManagerComponent.class); /** The Constant EVENT_NAME. */ public static final String EVENT_NAME = "PushCloudFile"; /** The Constant FILTERS. */ protected static final List<UIExtensionFilter> FILTERS = Arrays.asList(new UIExtensionFilter[] { new LocalNodeFilter() }); /** * The listener interface for receiving pushCloudFileAction events. The class * that is interested in processing a pushCloudFileAction event implements * this interface, and the object created with that class is registered with a * component using the component's <code>addPushCloudFileActionListener</code> * method. When the pushCloudFileAction event occurs, that object's * appropriate method is invoked. */ public static class PushCloudFileActionListener extends EventListener<PushCloudFileManagerComponent> { /** * {@inheritDoc} */ public void execute(Event<PushCloudFileManagerComponent> event) throws Exception { UIJCRExplorer explorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); String nodePath; String objectId = event.getRequestContext().getRequestParameter(OBJECTID); String wsName = explorer.getCurrentWorkspace(); if (objectId.startsWith(wsName)) { try { nodePath = objectId.substring(wsName.length() + 1); } catch (IndexOutOfBoundsException e) { nodePath = null; } } else if (objectId.startsWith("/")) { nodePath = objectId; } else { nodePath = null; } if (nodePath != null) { Item item = explorer.getSession().getItem(nodePath); if (item.isNode()) { Node node = (Node) item; CloudDriveService driveService = WCMCoreUtils.getService(CloudDriveService.class); CloudDrive drive = driveService.findDrive(node); if (drive != null) { CloudDriveStorage storage = (CloudDriveStorage) drive; try { storage.create(node); } catch (DriveRemovedException e) { LOG.warn(e.getMessage()); } catch (NotCloudDriveException e) { LOG.warn(e.getMessage()); } } // code adopted from // UIAddressBar.RefreshSessionActionListener.execute() -- effect of // refresh here explorer.refreshExplorer(); UIWorkingArea workingArea = explorer.getChild(UIWorkingArea.class); UIActionBar actionBar = workingArea.getChild(UIActionBar.class); UIControl control = explorer.getChild(UIControl.class); if (control != null) { UIAddressBar addressBar = control.getChild(UIAddressBar.class); if (addressBar != null) { actionBar.setTabOptions(addressBar.getSelectedViewName()); } } } else { throw new IllegalArgumentException("Not node " + nodePath); } } else { throw new IllegalArgumentException("Cannot extract node path from objectId " + objectId); } } } /** * Gets the filters. * * @return the filters */ @UIExtensionFilters public List<UIExtensionFilter> getFilters() { return FILTERS; } /** * {@inheritDoc} */ @Override public String renderEventURL(boolean ajax, String name, String beanId, Parameter[] params) throws Exception { if (EVENT_NAME.equals(name)) { CloudDriveContext.init(this); } return super.renderEventURL(ajax, name, beanId, params); } @Override public Class<? extends UIAbstractManager> getUIAbstractManagerClass() { return null; } }
6,878
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDriveThumbnailServiceImpl.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/thumbnail/CloudDriveThumbnailServiceImpl.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.thumbnail; import java.awt.image.BufferedImage; import java.io.InputStream; import javax.jcr.Node; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.thumbnail.impl.ThumbnailServiceImpl; import org.exoplatform.services.thumbnail.ImageResizeService; /** * TODO not finished! not used. Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudDriveThumbnailServiceImpl.java 00000 May 21, 2014 * pnedonosko $ */ public class CloudDriveThumbnailServiceImpl extends ThumbnailServiceImpl { /** The cloud drives. */ protected final CloudDriveService cloudDrives; /** * Instantiates a new cloud drive thumbnail service impl. * * @param initParams the init params * @param cloudDrives the cloud drives * @throws Exception the exception */ public CloudDriveThumbnailServiceImpl(InitParams initParams, CloudDriveService cloudDrives, ImageResizeService imageResizeService) throws Exception { super(initParams, imageResizeService); this.cloudDrives = cloudDrives; } /** * {@inheritDoc} */ @Override public InputStream getThumbnailImage(Node node, String thumbnailType) throws Exception { // TODO Auto-generated method stub return super.getThumbnailImage(node, thumbnailType); } /** * {@inheritDoc} */ @Override public void addThumbnailImage(Node thumbnailNode, BufferedImage image, String propertyName) throws Exception { // TODO Auto-generated method stub super.addThumbnailImage(thumbnailNode, image, propertyName); } /** * {@inheritDoc} */ @Override public void createSpecifiedThumbnail(Node node, BufferedImage image, String propertyName) throws Exception { // TODO Auto-generated method stub super.createSpecifiedThumbnail(node, image, propertyName); } /** * {@inheritDoc} */ @Override public void createThumbnailImage(Node node, BufferedImage image, String mimeType) throws Exception { // TODO Auto-generated method stub super.createThumbnailImage(node, image, mimeType); } /** * {@inheritDoc} */ @Override public Node addThumbnailNode(Node node) throws Exception { // TODO Auto-generated method stub return super.addThumbnailNode(node); } /** * {@inheritDoc} */ @Override public Node getThumbnailNode(Node node) throws Exception { // return null for Cloud Drive files if (cloudDrives.findDrive(node) != null) { return null; } else { return super.getThumbnailNode(node); } } }
3,629
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDriveThumbnailRESTService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/thumbnail/CloudDriveThumbnailRESTService.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.thumbnail; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.jcr.RepositoryException; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.cms.thumbnail.ThumbnailService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.wcm.connector.collaboration.ThumbnailRESTService; /** * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudDriveThumbnailRESTService.java 00000 May 21, 2014 * pnedonosko $ */ @Path("/thumbnailImage/") public class CloudDriveThumbnailRESTService extends ThumbnailRESTService { /** The Constant LAST_MODIFIED_PROPERTY. */ private static final String LAST_MODIFIED_PROPERTY = "Last-Modified"; /** The Constant IF_MODIFIED_SINCE_DATE_FORMAT. */ private static final DateFormat DATE_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); /** The cloud drives. */ protected final CloudDriveService cloudDrives; /** * Instantiates a new cloud drive thumbnail REST service. * * @param repositoryService the repository service * @param thumbnailService the thumbnail service * @param nodeFinder the node finder * @param linkManager the link manager * @param cloudDrives the cloud drives */ public CloudDriveThumbnailRESTService(RepositoryService repositoryService, ThumbnailService thumbnailService, NodeFinder nodeFinder, LinkManager linkManager, CloudDriveService cloudDrives) { super(repositoryService, thumbnailService, nodeFinder, linkManager); this.cloudDrives = cloudDrives; } /** * {@inheritDoc} */ @Path("/medium/{repoName}/{workspaceName}/{nodePath:.*}/") @GET @Override public Response getThumbnailImage(@PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("nodePath") String nodePath, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { if (accept(workspaceName, nodePath)) { return super.getThumbnailImage(repoName, workspaceName, nodePath, ifModifiedSince); } else { return ok(); } } /** * {@inheritDoc} */ @Path("/big/{repoName}/{workspaceName}/{nodePath:.*}/") @GET @Override public Response getCoverImage(@PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("nodePath") String nodePath, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { if (accept(workspaceName, nodePath)) { return super.getCoverImage(repoName, workspaceName, nodePath, ifModifiedSince); } else { return ok(); } } /** * {@inheritDoc} */ @Path("/large/{repoName}/{workspaceName}/{nodePath:.*}/") @GET @Override public Response getLargeImage(@PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("nodePath") String nodePath, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { if (accept(workspaceName, nodePath)) { return super.getLargeImage(repoName, workspaceName, nodePath, ifModifiedSince); } else { return ok(); } } /** * {@inheritDoc} */ @Override @Path("/small/{repoName}/{workspaceName}/{nodePath:.*}/") @GET public Response getSmallImage(@PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("nodePath") String nodePath, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { if (accept(workspaceName, nodePath)) { return super.getSmallImage(repoName, workspaceName, nodePath, ifModifiedSince); } else { return ok(); } } /** * {@inheritDoc} */ @Path("/custom/{size}/{repoName}/{workspaceName}/{nodePath:.*}/") @GET @Override public Response getCustomImage(@PathParam("size") String size, @PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("nodePath") String nodePath, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { if (accept(workspaceName, nodePath)) { return super.getCustomImage(size, repoName, workspaceName, nodePath, ifModifiedSince); } else { return ok(); } } @Path("/custom/{size}/{workspaceName}/{identifier}") @GET @Override public Response getCustomImage(@PathParam("size") String size, @PathParam("workspaceName") String workspaceName, @PathParam("identifier") String identifier, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { if (accept(workspaceName, identifier)) { return super.getCustomImage(size, workspaceName, identifier, ifModifiedSince); } else { return ok(); } } /** * {@inheritDoc} */ @Path("/origin/{repoName}/{workspaceName}/{nodePath:.*}/") @GET @Override public Response getOriginImage(@PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("nodePath") String nodePath, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { if (accept(workspaceName, nodePath)) { return super.getOriginImage(repoName, workspaceName, nodePath, ifModifiedSince); } else { return ok(); } } // internals /** * Accept. * * @param workspaceName the workspace name * @param nodePath the node path * @return true, if successful * @throws RepositoryException the repository exception */ protected boolean accept(String workspaceName, String nodePath) throws RepositoryException { return cloudDrives.findDrive(workspaceName, getNodePath(nodePath)) == null; } /** * Ok. * * @return the response */ protected Response ok() { return Response.ok().header(LAST_MODIFIED_PROPERTY, DATE_FORMAT.format(new Date())).build(); } /** * Method copied from {@link ThumbnailRESTService}. * * @param nodePath the node path * @return the node path */ private String getNodePath(String nodePath) { ArrayList<String> encodeNameArr = new ArrayList<String>(); if (!nodePath.equals("/")) { for (String name : nodePath.split("/")) { if (name.length() > 0) { encodeNameArr.add(Text.escapeIllegalJcrChars(name)); } } StringBuilder encodedPath = new StringBuilder(); for (String encodedName : encodeNameArr) { encodedPath.append("/").append(encodedName); } nodePath = encodedPath.toString(); } return nodePath; } }
8,717
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ManagePublicationsActionComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/ManagePublicationsActionComponent.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.action; import java.util.List; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilters; /** * Overrides original ECMS component to replace * {@link IsNotIgnoreVersionNodeFilter} with safe version that can work with * symlinks to private user Cloud Drive files.<br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: ManagePublicationsActionComponent.java 00000 Jul 6, 2015 * pnedonosko $ */ @ComponentConfig(events = { @EventConfig(listeners = ManagePublicationsActionComponent.ManagePublicationsActionListener.class) }) public class ManagePublicationsActionComponent extends org.exoplatform.ecm.webui.component.explorer.control.action.ManagePublicationsActionComponent { /** The cd filter. */ protected static IsNotIgnoreVersionNodeFilter cdFilter = new IsNotIgnoreVersionNodeFilter(); /** * {@inheritDoc} */ @UIExtensionFilters public List<UIExtensionFilter> getFilters() { List<UIExtensionFilter> filters = super.getFilters(); // replace ECMS's IsNotIgnoreVersionNodeFilter with ones from Cloud Drive for (int i = 0; i < filters.size(); i++) { UIExtensionFilter of = filters.get(i); if (of instanceof org.exoplatform.ecm.webui.component.explorer.control.filter.IsNotIgnoreVersionNodeFilter) { filters.set(i, cdFilter); } } return filters; } }
2,527
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
RemoveCloudFileLinkAction.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/RemoveCloudFileLinkAction.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.action; import javax.jcr.Node; import org.apache.commons.chain.Context; import org.exoplatform.services.cms.clouddrives.jcr.AbstractJCRAction; import org.exoplatform.services.cms.documents.TrashService; import org.exoplatform.services.ext.action.InvocationContext; import org.exoplatform.services.jcr.observation.ExtendedEvent; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; /** * Care about symlinks to ecd:cloudFile nodes removal - this action should * initiate group permissions removal from the cloud file added in time of * sharing to group drives. <br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: RemoveCloudFileLinkAction.java 00000 Jul 7, 2015 pnedonosko $ */ public class RemoveCloudFileLinkAction extends AbstractJCRAction { /** The log. */ private static Log LOG = ExoLogger.getLogger(RemoveCloudFileLinkAction.class); /** * {@inheritDoc} */ @Override public boolean execute(Context context) throws Exception { Node linkNode = (Node) context.get(InvocationContext.CURRENT_ITEM); // we work only with node removal (no matter what set in the action config) if (ExtendedEvent.NODE_REMOVED == (Integer) context.get(InvocationContext.EVENT)) { TrashService trash = getComponent(context, TrashService.class); // Don't care about removal from Trash: it can be Cloud Drive itself when // removing cloud file by sync op. if (!trash.getTrashHomeNode().isSame(linkNode.getParent())) { CloudFileActionService actions = getComponent(context, CloudFileActionService.class); Node targetNode = actions.markRemoveLink(linkNode); if (targetNode != null) { if (LOG.isDebugEnabled()) { LOG.debug("Cloud File link marked for removal: " + linkNode.getPath() + " -> " + targetNode.getPath()); } } } } else { LOG.warn(RemoveCloudFileLinkAction.class.getName() + " supports only node removal. Check configuration. Item skipped: " + linkNode.getPath()); } return false; } }
3,032
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDriveDeleteManageComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/CloudDriveDeleteManageComponent.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.services.cms.clouddrives.webui.action; import java.util.Map; import java.util.regex.Matcher; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.Session; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.UIWorkingArea; import org.exoplatform.ecm.webui.component.explorer.rightclick.manager.DeleteManageComponent; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.clouddrives.webui.action.CloudDriveDeleteManageComponent.DeleteActionListener; 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.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.exception.MessageException; /** * Overridden component to keep listener context with correct node (in case of * Cloud File links it should be a link node, not a target. XXX it's a * workaround).<br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudDriveDeleteManageComponent.java 00000 Jun 29, 2018 * pnedonosko $ */ @ComponentConfig(events = { @EventConfig(listeners = DeleteActionListener.class) }) public class CloudDriveDeleteManageComponent extends DeleteManageComponent { /** The LOG. */ private static final Log LOG = ExoLogger.getLogger(CloudDriveDeleteManageComponent.class.getName()); /** * The listener interface for receiving deleteAction events. */ public static class DeleteActionListener extends org.exoplatform.ecm.webui.component.explorer.rightclick.manager.DeleteManageComponent.DeleteActionListener { /** * {@inheritDoc} */ @Override protected Map<String, Object> createContext(Event<DeleteManageComponent> event) throws Exception { // Take original context Map<String, Object> context = super.createContext(event); if (context != null) { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); String nodePath = event.getRequestContext().getRequestParameter(UIComponent.OBJECTID); // For cloud files we set context node without finding its target in // case of symlink try { Node currentNode = getNodeByPath(nodePath, uiExplorer, false); CloudDriveService driveService = WCMCoreUtils.getService(CloudDriveService.class); CloudDrive drive = driveService.findDrive(currentNode); if (drive != null) { context.put(Node.class.getName(), currentNode); } } catch (PathNotFoundException pte) { throw new MessageException(new ApplicationMessage("UIPopupMenu.msg.path-not-found", null, ApplicationMessage.WARNING)); } catch (Exception e) { LOG.error("Unexpected error while updating listener context", e); } } return context; } /** * Gets the node by path (code copied from super's private method). * * @param nodePath the node path * @param uiExplorer the ui explorer * @param giveTarget the give target * @return the node by path * @throws Exception the exception */ private Node getNodeByPath(String nodePath, UIJCRExplorer uiExplorer, boolean giveTarget) throws Exception { nodePath = uiExplorer.getCurrentWorkspace() + ":" + nodePath; Matcher matcher = UIWorkingArea.FILE_EXPLORER_URL_SYNTAX.matcher(nodePath); String wsName = null; if (matcher.find()) { wsName = matcher.group(1); nodePath = matcher.group(2); } else { wsName = uiExplorer.getCurrentWorkspace(); } Session session = uiExplorer.getSessionByWorkspace(wsName); return uiExplorer.getNodeByPath(nodePath, session, giveTarget); } } }
5,082
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDrivePasteManageComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/CloudDrivePasteManageComponent.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.action; import java.util.Deque; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Set; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.rightclick.manager.PasteManageComponent; import org.exoplatform.services.cms.clipboard.ClipboardService; import org.exoplatform.services.cms.clipboard.jcr.model.ClipboardCommand; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.security.ConversationState; 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.event.Event; /** * Support of Cloud Drive files pasting from ECMS Clipboard. If not a cloud file * then original behaviour of {@link PasteManageComponent} will be applied. <br> * Code parts of this class based on original {@link PasteManageComponent} * (state of ECMS 4.0.4).<br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudDrivePasteManageComponent.java 00000 May 12, 2014 * pnedonosko $ */ @ComponentConfig(events = { @EventConfig(listeners = CloudDrivePasteManageComponent.PasteActionListener.class) }) public class CloudDrivePasteManageComponent extends PasteManageComponent { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(CloudDrivePasteManageComponent.class); /** * The listener interface for receiving pasteAction events. The class that is * interested in processing a pasteAction event implements this interface, and * the object created with that class is registered with a component using the * component's <code>addPasteActionListener</code> method. When the * pasteAction event occurs, that object's appropriate method is invoked. */ public static class PasteActionListener extends PasteManageComponent.PasteActionListener { /** * {@inheritDoc} */ public void processEvent(Event<PasteManageComponent> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); CloudFileAction action = new CloudFileAction(uiExplorer); try { String destParam = event.getRequestContext().getRequestParameter(OBJECTID); if (destParam == null) { action.setDestination(uiExplorer.getCurrentNode()); } else { action.setDestination(destParam); } String userId = ConversationState.getCurrent().getIdentity().getUserId(); ClipboardService clipboardService = WCMCoreUtils.getService(ClipboardService.class); Deque<ClipboardCommand> allClipboards = new LinkedList<ClipboardCommand>(clipboardService.getClipboardList(userId, false)); if (allClipboards.size() > 0) { Set<ClipboardCommand> virtClipboards = clipboardService.getClipboardList(userId, true); // will refer to last attempted to link ClipboardCommand current = null; if (virtClipboards.isEmpty()) { // single file current = allClipboards.getLast(); boolean isCut = ClipboardCommand.CUT.equals(current.getType()); action.addSource(current.getWorkspace(), current.getSrcPath()); if (isCut) { action.move(); } if (action.apply()) { // file was linked if (isCut) { // TODO should not happen until we will support cut-paste // between drives virtClipboards.clear(); allClipboards.remove(current); } // complete the event here uiExplorer.updateAjax(event); return; } } else { // multiple files final int virtSize = virtClipboards.size(); Set<ClipboardCommand> linked = new LinkedHashSet<ClipboardCommand>(); Boolean isCut = null; for (Iterator<ClipboardCommand> iter = virtClipboards.iterator(); iter.hasNext();) { current = iter.next(); boolean isThisCut = ClipboardCommand.CUT.equals(current.getType()); if (isCut == null) { isCut = isThisCut; } if (isCut.equals(isThisCut)) { action.addSource(current.getWorkspace(), current.getSrcPath()); linked.add(current); } else { // we have unexpected state when items in group clipboard have // different types of operation LOG.warn("Cannot handle different types of clipboard operations for group action. Files " + (isCut ? " cut-paste" : " copy-paste") + " already started but " + (isThisCut ? " cut-paste" : " copy-paste") + " found for " + current.getSrcPath()); // let default logic deal with this break; } } if (virtSize == linked.size()) { if (isCut != null && isCut) { action.move(); } if (action.apply()) { // files was successfully linked if (isCut) { // TODO should not happen until we will support cut-paste // between drives virtClipboards.clear(); for (ClipboardCommand c : linked) { allClipboards.remove(c); } } // complete the event here uiExplorer.updateAjax(event); return; } } else { // something goes wrong and we will let default code to work action.rollback(); LOG.warn("Links cannot be created for all cloud files. Destination " + action.getDestonationPath() + "." + (current != null ? " Last file " + current.getSrcPath() + "." : "") + " Default behaviour will be applied (files Paste)."); } } } } catch (CloudFileActionException e) { // this exception is a part of logic and it interrupts the operation LOG.warn(e.getMessage(), e); UIApplication uiApp = uiExplorer.getAncestorOfType(UIApplication.class); uiApp.addMessage(e.getUIMessage()); action.rollback(); // complete the event here uiExplorer.updateAjax(event); return; } catch (Exception e) { // ignore and return false LOG.warn("Error creating link of cloud file. Default behaviour will be applied (file Paste).", e); } // else... call PasteManageComponent in all other cases super.processEvent(event); } } /** * Instantiates a new cloud drive paste manage component. */ public CloudDrivePasteManageComponent() { super(); } }
8,078
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDriveMoveNodeManageComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/CloudDriveMoveNodeManageComponent.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.action; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.rightclick.manager.MoveNodeManageComponent; 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.UIApplication; import org.exoplatform.webui.event.Event; /** * Move node support for Cloud Drive files. Instead of moving the cloud file * node we create a symlink to the file in drive folder.<br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: MoveNodeManageComponent.java 00000 May 19, 2014 pnedonosko $ */ @ComponentConfig(events = { @EventConfig(listeners = CloudDriveMoveNodeManageComponent.MoveNodeActionListener.class, confirm = "UIWorkingArea.msg.confirm-move") }) public class CloudDriveMoveNodeManageComponent extends MoveNodeManageComponent { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(CloudDriveMoveNodeManageComponent.class); /** * The listener interface for receiving moveNodeAction events. The class that * is interested in processing a moveNodeAction event implements this * interface, and the object created with that class is registered with a * component using the component's <code>addMoveNodeActionListener</code> * method. When the moveNodeAction event occurs, that object's appropriate * method is invoked. */ public static class MoveNodeActionListener extends MoveNodeManageComponent.MoveNodeActionListener { /** * {@inheritDoc} */ public void processEvent(Event<MoveNodeManageComponent> event) throws Exception { String srcPath = event.getRequestContext().getRequestParameter(OBJECTID); String destInfo = event.getRequestContext().getRequestParameter("destInfo"); UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); CloudFileAction action = new CloudFileAction(uiExplorer); try { action.setDestination(destInfo); if (srcPath.indexOf(";") > -1) { // multiple nodes move String[] srcPaths = srcPath.split(";"); for (String srcp : srcPaths) { action.addSource(srcp); } } else { // single node move action.addSource(srcPath); } if (action.move().apply()) { uiExplorer.updateAjax(event); return; } // else default logic } catch (CloudFileActionException e) { // this exception is a part of logic and it interrupts the move // operation LOG.warn(e.getMessage(), e); UIApplication uiApp = uiExplorer.getAncestorOfType(UIApplication.class); uiApp.addMessage(e.getUIMessage()); action.rollback(); uiExplorer.updateAjax(event); return; } catch (Exception e) { // let default logic handle this in super LOG.warn("Error creating link of cloud file. Default behaviour will be applied (file move).", e); } // invoke original code in all other cases super.processEvent(event); } } /** * Instantiates a new cloud drive move node manage component. */ public CloudDriveMoveNodeManageComponent() { super(); } }
4,333
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
IsVersionableOrAncestorFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/IsVersionableOrAncestorFilter.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.action; import java.util.Map; import org.exoplatform.services.cms.clouddrives.webui.filters.NotCloudDriveOrFileFilter; /** * Overrides original ECMS's filter to do not accept Cloud Drive and its * files.<br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: IsVersionableOrAncestorFilter.java 00000 Jul 8, 2015 pnedonosko * $ */ public class IsVersionableOrAncestorFilter extends org.exoplatform.ecm.webui.component.explorer.control.filter.IsVersionableOrAncestorFilter { /** The not cloud drive filter. */ private NotCloudDriveOrFileFilter notCloudDriveFilter = new NotCloudDriveOrFileFilter(); /** * {@inheritDoc} */ @Override public boolean accept(Map<String, Object> context) throws Exception { if (notCloudDriveFilter.accept(context)) { return super.accept(context); } else { return false; } } }
1,869
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudFileActionService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/CloudFileActionService.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.services.cms.clouddrives.webui.action; import java.security.AccessControlException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import javax.jcr.Item; 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.observation.Event; import javax.jcr.observation.EventIterator; import javax.jcr.observation.EventListener; import javax.jcr.observation.ObservationManager; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import org.picocontainer.Startable; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.component.RequestLifeCycle; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.CmsService; 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.CloudDriveStorage; import org.exoplatform.services.cms.clouddrives.DriveRemovedException; import org.exoplatform.services.cms.clouddrives.NotCloudDriveException; import org.exoplatform.services.cms.clouddrives.ThreadExecutor; import org.exoplatform.services.cms.clouddrives.CloudDriveStorage.Change; import org.exoplatform.services.cms.clouddrives.jcr.JCRLocalCloudDrive; import org.exoplatform.services.cms.clouddrives.jcr.NodeFinder; import org.exoplatform.services.cms.documents.TrashService; 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.jcr.RepositoryService; 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.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.listener.ListenerService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.organization.OrganizationService; import org.exoplatform.wcm.ext.component.activity.listener.Utils; /** * Integration of Cloud Drive with eXo Platform apps.<br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudFileActionService.java 00000 Jul 6, 2015 pnedonosko $ */ public class CloudFileActionService implements Startable { /** The Constant EXO_SYMLINK. */ public static final String EXO_SYMLINK = "exo:symlink"; /** The Constant ECD_CLOUDFILELINK. */ public static final String ECD_CLOUDFILELINK = "ecd:cloudFileLink"; /** The Constant ECD_SHAREIDENTITY. */ public static final String ECD_SHAREIDENTITY = "ecd:shareIdentity"; /** The Constant SHARE_CLOUD_FILES_SPACES. */ public static final String SHARE_CLOUD_FILES_SPACES = "sharecloudfiles:spaces"; /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(CloudFileActionService.class); /** The Constant SPACES_GROUP. */ protected static final String SPACES_GROUP = "spaces"; /** The Constant EXO_OWNEABLE. */ protected static final String EXO_OWNEABLE = "exo:owneable"; /** The Constant EXO_PRIVILEGEABLE. */ protected static final String EXO_PRIVILEGEABLE = "exo:privilegeable"; /** The Constant EXO_TRASHFOLDER. */ protected static final String EXO_TRASHFOLDER = "exo:trashFolder"; /** The Constant READER_PERMISSION. */ protected static final String[] READER_PERMISSION = new String[] { PermissionType.READ }; /** The Constant MANAGER_PERMISSION. */ protected static final String[] MANAGER_PERMISSION = new String[] { PermissionType.READ, PermissionType.REMOVE, PermissionType.SET_PROPERTY }; /** * Act on ecd:cloudFileLinkGroup property removal on a cloud file symlink and * then unshare the file from the group where it was shared by the link. */ protected class LinkRemoveListener implements EventListener { /** * {@inheritDoc} */ @Override public void onEvent(EventIterator events) { while (events.hasNext()) { Event event = events.nextEvent(); try { final String eventPath = event.getPath(); if (eventPath.endsWith(ECD_SHAREIDENTITY)) { if (LOG.isDebugEnabled()) { LOG.debug("Cloud File link removed. User: " + event.getUserID() + ". Path: " + eventPath); } String linkPath = eventPath.substring(0, eventPath.indexOf(ECD_SHAREIDENTITY) - 1); String cloudFileUUID = removedLinks.remove(linkPath); if (cloudFileUUID != null) { String identity = removedShared.get(cloudFileUUID); if (identity != null) { // was marked by RemoveCloudFileLinkAction try { Node fileNode = systemSession().getNodeByUUID(cloudFileUUID); CloudDrive localDrive = cloudDrives.findDrive(fileNode); if (localDrive != null) { if (getCloudFileLinks(fileNode, identity, true).getSize() == 0) { // unshare only if no more links found for given identity // (user or group) DriveData documentDrive = null; if (identity.startsWith("/")) { // it's group drive documentDrive = getGroupDrive(identity); if (documentDrive != null) { removeCloudFilePermission(fileNode, localDrive, new StringBuilder("*:").append(identity).toString()); } } else { // try as user drive documentDrive = getUserDrive(identity); if (documentDrive != null) { removeCloudFilePermission(fileNode, localDrive, identity); } } if (documentDrive == null) { if (LOG.isDebugEnabled()) { LOG.debug("Cannot find documents drive for " + fileNode.getPath() + ". Unsharing not complete for this node."); } } } } // drive not found, may be this file in Trash folder and // user is cleaning it, do nothing } catch (DriveRemovedException e) { LOG.warn("Cloud File unsharing canceled due to removed drive: " + e.getMessage() + ". Path: " + eventPath); } catch (NotCloudDriveException e) { LOG.warn("Cloud File unsharing not possible for not cloud drives: " + e.getMessage() + ". Path: " + eventPath); } catch (Throwable e) { LOG.error("Cloud File unsharing error: " + e.getMessage() + ". Path: " + eventPath, e); } } } } } catch (RepositoryException e) { LOG.error("Symlink removal listener error: " + e.getMessage(), e); } } } protected void removeCloudFilePermission(final Node fileNode, final CloudDrive cloudDrive, final String sharedIndentity) throws NotCloudDriveException, DriveRemovedException, RepositoryException, CloudDriveException { if (LOG.isDebugEnabled()) { LOG.debug("Unsharing Cloud File " + fileNode.getPath() + " of " + cloudDrive + " from " + " " + sharedIndentity); } // avoid firing Cloud Drive synchronization CloudDriveStorage cdStorage = (CloudDriveStorage) cloudDrive; cdStorage.localChange(new Change<Void>() { @Override public Void apply() throws RepositoryException { removePermission(fileNode, sharedIndentity); return null; } }); } } /** * Act on Cloud File symlink trashing. */ protected class LinkTrashListener implements EventListener { /** The processing links. */ private final Queue<String> processingLinks = new ConcurrentLinkedQueue<String>(); /** * {@inheritDoc} */ @Override public void onEvent(EventIterator events) { while (events.hasNext()) { Event event = events.nextEvent(); try { final String eventPath = event.getPath(); Item linkItem = systemSession().getItem(eventPath); if (linkItem.isNode() && linkManager.isLink(linkItem)) { try { Node fileNode = linkManager.getTarget((Node) linkItem, true); CloudDrive localDrive = cloudDrives.findDrive(fileNode); if (localDrive != null) { if (localDrive.isConnected()) { if (LOG.isDebugEnabled()) { LOG.debug("Cloud File link trashed. User: " + event.getUserID() + ". Path: " + eventPath); } // update removals with trashed path final String cloudFileUUID = fileNode.getUUID(); if (!processingLinks.contains(cloudFileUUID)) { processingLinks.add(cloudFileUUID); removedLinks.values().remove(cloudFileUUID); removedLinks.put(eventPath, cloudFileUUID); // remove symlink with a delay in another thread final ExoContainer container = ExoContainerContext.getCurrentContainer(); workerExecutor.submit(new Runnable() { @Override public void run() { try { Thread.sleep(1000 * 2); // wait a bit for ECMS actions ExoContainerContext.setCurrentContainer(container); RequestLifeCycle.begin(container); try { Item linkItem = systemSession().getItem(eventPath); if (linkItem.isNode()) { Node linkNode = (Node) linkItem; Node parent = linkNode.getParent(); // FYI target node permissions will be updated by // LinkRemoveListener linkNode.remove(); parent.save(); if (LOG.isDebugEnabled()) { LOG.debug("Cloud File link '" + linkItem.getName() + "' successfully removed from the Trash."); } } } finally { RequestLifeCycle.end(); } } catch (PathNotFoundException e) { // node already deleted LOG.warn("Cloud File " + eventPath + " node already removed directly from JCR: " + e.getMessage()); } catch (InterruptedException e) { LOG.warn("Cloud File symlink remover interrupted " + e.getMessage()); Thread.currentThread().interrupt(); } catch (Throwable e) { LOG.error("Error removing node of Cloud File " + eventPath + ". " + e.getMessage(), e); } finally { processingLinks.remove(cloudFileUUID); } } }); } // else, link already processing } else { LOG.warn("Cloud Drive not connected for " + fileNode.getPath() + ". Drive: " + localDrive); } } else { LOG.warn("Cloud Drive not found for " + fileNode.getPath()); } } catch (Exception e) { LOG.error("Symlink " + eventPath + " removal error: " + e.getMessage(), e); } } } catch (PathNotFoundException e) { if (LOG.isDebugEnabled()) { try { LOG.debug("Trashed item not found " + event.getPath() + ". " + e.getMessage(), e); } catch (RepositoryException ee) { // ignore } } } catch (RepositoryException e) { LOG.error("Symlink listener error: " + e.getMessage(), e); } } } } /** The cloud drive. */ protected final CloudDriveService cloudDrives; /** The jcr service. */ protected final RepositoryService jcrService; /** The hierarchy creator. */ protected final NodeHierarchyCreator hierarchyCreator; /** The session providers. */ protected final SessionProviderService sessionProviders; /** The org service. */ protected final OrganizationService orgService; /** The link manager. */ protected final LinkManager linkManager; /** The document drives. */ protected final ManageDriveService documentDrives; /** The trash. */ protected final TrashService trash; /** The listener service. */ protected final ListenerService listenerService; /** The cms service. */ protected final CmsService cmsService; /** * Symlink to cloud file UUID mappings. */ protected final Map<String, String> removedLinks = new ConcurrentHashMap<String, String>(); /** * Cloud file UUID to shared group/user name mappings. */ protected final Map<String, String> removedShared = new ConcurrentHashMap<String, String>(); /** * Node finder facade on actual storage implementation. */ protected final NodeFinder finder; /** * Trashed symlinks removal workers. */ protected final ThreadExecutor workerExecutor = ThreadExecutor.getInstance(); /** The groups path. */ protected final String groupsPath; /** The users path. */ protected final String usersPath; /** * Instantiates a new cloud file action service. * * @param cloudDrives the cloud drive * @param jcrService the jcr service * @param sessionProviders the session providers * @param orgService the org service * @param finder the finder * @param hierarchyCreator the hierarchy creator * @param linkManager the link manager * @param documentDrives the document drives * @param trash the trash * @param listeners the listeners * @param cmsService the cms service */ public CloudFileActionService(CloudDriveService cloudDrives, RepositoryService jcrService, SessionProviderService sessionProviders, OrganizationService orgService, NodeFinder finder, NodeHierarchyCreator hierarchyCreator, LinkManager linkManager, ManageDriveService documentDrives, TrashService trash, ListenerService listeners, CmsService cmsService) { this.cloudDrives = cloudDrives; this.jcrService = jcrService; this.orgService = orgService; this.sessionProviders = sessionProviders; this.finder = finder; this.hierarchyCreator = hierarchyCreator; this.linkManager = linkManager; this.documentDrives = documentDrives; this.trash = trash; this.listenerService = listeners; this.cmsService = cmsService; this.groupsPath = hierarchyCreator.getJcrPath(BasePath.CMS_GROUPS_PATH); this.usersPath = hierarchyCreator.getJcrPath(BasePath.CMS_USERS_PATH); } /** * Checks if is group drive. * * @param drive the drive * @return true, if is group drive */ @Deprecated public boolean isGroupDrive(DriveData drive) { return drive.getHomePath().startsWith(groupsPath); } /** * Checks if is user drive. * * @param drive the drive * @return true, if is user drive */ @Deprecated public boolean isUserDrive(DriveData drive) { return drive.getHomePath().startsWith(usersPath); } /** * Checks if is group path. * * @param path the path * @return true, if is group path */ @Deprecated public boolean isGroupPath(String path) { return path.startsWith(groupsPath); } /** * Checks if is user path. * * @param path the path * @return true, if is user path */ @Deprecated public boolean isUserPath(String path) { return path.startsWith(usersPath); } /** * Gets the group drive. * * @param groupId the group id * @return the space drive * @throws Exception the exception */ @Deprecated public DriveData getGroupDrive(String groupId) throws Exception { return documentDrives.getDriveByName(groupId.replace('/', '.')); } /** * Gets the user drive. * * @param userName the user name * @return the user drive * @throws Exception the exception */ @Deprecated public DriveData getUserDrive(String userName) throws Exception { DriveData userDrive = null; String homePath = null; for (Iterator<DriveData> diter = documentDrives.getPersonalDrives(userName).iterator(); diter.hasNext();) { DriveData drive = diter.next(); String path = drive.getHomePath(); if (path.startsWith(usersPath) && path.endsWith("/Private")) { homePath = path; userDrive = drive; // we prefer drives with already defined real user path as home if (homePath.indexOf("${userId}") < 0) { break; } else if (!diter.hasNext()) { // if no real home path found and no more drives, do this job here homePath = org.exoplatform.services.cms.impl.Utils.getPersonalDrivePath(homePath, userName); userDrive.setHomePath(homePath); break; } } } return userDrive; } /** * Gets the user public node. * * @param userName the user name * @return the user public node * @throws Exception the exception */ @Deprecated public Node getUserPublicNode(String userName) throws Exception { Node profileNode = getUserProfileNode(userName); String userPublic = hierarchyCreator.getJcrPath("userPublic"); return profileNode.getNode(userPublic != null ? userPublic : "Public"); } /** * Gets the user profile node (a node where /Private and /Public nodes live). * * @param userName the user name * @return the user profile node * @throws Exception the exception */ @Deprecated public Node getUserProfileNode(String userName) throws Exception { SessionProvider ssp = sessionProviders.getSystemSessionProvider(null); if (ssp != null) { return hierarchyCreator.getUserNode(ssp, userName); } throw new RepositoryException("Cannot get session provider."); } /** * Share cloud file to an user by its ID. * * @param fileNode the file node * @param userId the user id * @param canEdit the can edit flag, if <code>true</code> then user should be * able to modify the shared link node, read-only link otherwise * @throws RepositoryException the repository exception */ public void shareToUser(Node fileNode, String userId, boolean canEdit) throws RepositoryException { setUserFilePermission(fileNode, userId, true); fileNode.save(); // initialize files links in the user docs try { DriveData userDrive = getUserDrive(userId); if (userDrive != null) { initCloudFileLink(fileNode, userId, userDrive.getHomePath(), canEdit); } } catch (Exception e) { LOG.error("Error reading Cloud File links of " + fileNode.getPath(), e); } } /** * Unshare to user. * * @param fileNode the file node * @param userId the user id * @throws RepositoryException the repository exception */ public void unshareToUser(Node fileNode, String userId) throws RepositoryException { // remove all copied/linked symlinks from the original shared to given // identity (or all if it is null) removeLinks(fileNode, userId); // remove sharing permissions removePermission(fileNode, userId); } /** * Share cloud file to a group by its ID and create a symlink in the target * space. * * @param fileNode the file node * @param groupId the group id * @param canEdit the can edit flag, if <code>true</code> then group members * should be able to modify the shared link node, read-only link * otherwise * @throws RepositoryException the repository exception */ public void shareToGroup(Node fileNode, String groupId, boolean canEdit) throws RepositoryException { // set permission on the cloud file setGroupFilePermission(fileNode, groupId, true); fileNode.save(); // initialize files links in space docs try { DriveData documentDrive = getGroupDrive(groupId); if (documentDrive != null) { initCloudFileLink(fileNode, groupId, documentDrive.getHomePath(), canEdit); } } catch (Exception e) { LOG.error("Error reading Cloud File links of " + fileNode.getPath(), e); } } /** * Unshare to space. * * @param fileNode the file node * @param groupId the group id * @throws RepositoryException the repository exception */ public void unshareToSpace(Node fileNode, String groupId) throws RepositoryException { // remove all copied/linked symlinks from the original shared to given // identity (or all if it is null) removeLinks(fileNode, groupId); // remove sharing permissions removePermission(fileNode, new StringBuilder("*:").append(groupId).toString()); } /** * Mark remove link. * * @param linkNode the link node * @return the node * @throws NotCloudDriveException the not cloud drive exception * @throws DriveRemovedException the drive removed exception * @throws RepositoryException the repository exception * @throws CloudDriveException the cloud drive exception */ public Node markRemoveLink(final Node linkNode) throws NotCloudDriveException, DriveRemovedException, RepositoryException, CloudDriveException { if (linkNode.isNodeType(ECD_CLOUDFILELINK)) { try { Node target = linkManager.getTarget(linkNode, true); String cloudFileUUID = target.getUUID(); removedLinks.put(linkNode.getPath(), cloudFileUUID); try { removedShared.put(cloudFileUUID, linkNode.getProperty(ECD_SHAREIDENTITY).getString()); } catch (PathNotFoundException e) { // wasn't shared in documents drive } return target; } catch (ItemNotFoundException e) { if (LOG.isDebugEnabled()) { LOG.debug("Cloud File link has no target node: " + linkNode.getPath() + ". " + e.getMessage()); } } } else { LOG.warn("Not cloud file link: node " + linkNode.getPath() + " not of type " + ECD_CLOUDFILELINK); } return null; } /** * {@inheritDoc} */ @Override public void start() { try { listenFileLinks(); } catch (RepositoryException e) { LOG.error("Error starting symlinks remove listener", e); } } /** * {@inheritDoc} */ @Override public void stop() { // nothing } // ******************* internals ******************* /** * Listen file links. * * @throws RepositoryException the repository exception */ protected void listenFileLinks() throws RepositoryException { Session session = null; try { session = systemSession(); ObservationManager observation = session.getWorkspace().getObservationManager(); observation.addEventListener(new LinkTrashListener(), Event.NODE_ADDED, null, false, null, new String[]{EXO_TRASHFOLDER}, false); observation.addEventListener(new LinkRemoveListener(), Event.PROPERTY_REMOVED, null, false, null, new String[]{ECD_CLOUDFILELINK}, false); } finally { if(session != null) { session.logout(); } } } /** * Find pretty name of the document. * * @param document the document * @return the string * @throws RepositoryException the repository exception */ protected String documentName(Node document) throws RepositoryException { try { return document.getProperty("exo:title").getString(); } catch (PathNotFoundException te) { try { return document.getProperty("exo:name").getString(); } catch (PathNotFoundException ne) { return document.getName(); } } } /** * System session in default workspace of current JCR repository. * * @return the session * @throws RepositoryException the repository exception */ protected Session systemSession() throws RepositoryException { SessionProvider ssp = sessionProviders.getSystemSessionProvider(null); if (ssp != null) { ManageableRepository jcrRepository = jcrService.getCurrentRepository(); String workspaceName = jcrRepository.getConfiguration().getDefaultWorkspaceName(); return ssp.getSession(workspaceName, jcrRepository); } throw new RepositoryException("Cannot get session provider."); } /** * Removes the links. * * @param fileNode the file node * @param identity the shared identity * @throws RepositoryException the repository exception */ protected void removeLinks(Node fileNode, String identity) throws RepositoryException { // remove all copied/linked symlinks from the original shared to given // identity (or all if it is null) for (NodeIterator niter = getCloudFileLinks(fileNode, identity, true); niter.hasNext();) { Node linkNode = niter.nextNode(); // Care about Social activity removal (avoid showing null activity posts), // do it safe for the logic try { Utils.deleteFileActivity(linkNode); } catch (Throwable e) { LOG.warn("Failed to remove unpublished file activity: " + linkNode.getPath(), e); } Node parent = linkNode.getParent(); // Remove the link itself linkNode.remove(); parent.save(); } } /** * Gets the cloud file links. * * @param targetNode the target node * @param shareIdentity the share identity * @param scopePath the scope path (only nodes from this sub-tree will be * searched) * @param useSystemSession the use system session * @return the cloud file links * @throws RepositoryException the repository exception */ public NodeIterator getCloudFileLinks(Node targetNode, String shareIdentity, String scopePath, boolean useSystemSession) throws RepositoryException { StringBuilder queryCode = new StringBuilder().append("SELECT * FROM ") .append(ECD_CLOUDFILELINK) .append(" WHERE exo:uuid='") .append(targetNode.getUUID()) .append("'"); if (shareIdentity != null && shareIdentity.length() > 0) { queryCode.append(" AND " + ECD_SHAREIDENTITY + "='").append(shareIdentity).append("'"); } if (scopePath != null && scopePath.length() > 0) { queryCode.append(" AND jcr:path LIKE '").append(scopePath).append("/%'"); } QueryManager queryManager; if (useSystemSession) { queryManager = systemSession().getWorkspace().getQueryManager(); } else { queryManager = targetNode.getSession().getWorkspace().getQueryManager(); } Query query = queryManager.createQuery(queryCode.toString(), Query.SQL); QueryResult queryResult = query.execute(); return queryResult.getNodes(); } /** * Gets organizational membership name by its type name. * * @param membershipType the membership type * @return the membership name */ protected String getMembershipName(String membershipType) { try { return orgService.getMembershipTypeHandler().findMembershipType(membershipType).getName(); } catch (Exception e) { LOG.error("Error finding manager membership in organization service. " + "Will use any (*) to remove permissions of shared cloud file link", e); return "*"; } } /** * Removes the permission of an identity on given node. * * @param node the node, expected {@link ExtendedNode} here * @param permIdentity the identity, it should include membership if actual * (e.g. for space it's <code>*:/space/my_team</code>, but simply * <code>john</code> for an user) */ protected void removePermission(Node node, String permIdentity) { try { ExtendedNode target = (ExtendedNode) node; target.removePermission(permIdentity); target.save(); } catch (Exception e) { LOG.warn("Failed to remove permissions on " + node + " for " + permIdentity, e); } } /** * Adds the user permission. * * @param fileNode the file node * @param userId the user id * @param forcePrivilegeable if need force adding of exo:privilegeable mixin * to the node * @throws RepositoryException the repository exception */ protected void setUserFilePermission(Node fileNode, String userId, boolean forcePrivilegeable) throws RepositoryException { ExtendedNode file = (ExtendedNode) fileNode; boolean setPermission = false; if (file.canAddMixin(EXO_PRIVILEGEABLE)) { if (forcePrivilegeable) { file.addMixin(EXO_PRIVILEGEABLE); setPermission = true; } // else will not set permissions on this node, but will check the child // nodes } else if (file.isNodeType(EXO_PRIVILEGEABLE)) { // already exo:privilegeable setPermission = true; } if (setPermission) { // XXX we DON'T clean what ShareDocumentService could add to let // UIShareDocuments show permissions correctly, // we only ensure that required rights are OK if (!file.getACL().getPermissions(userId).contains(PermissionType.READ)) { file.getACL().addPermissions(userId, READER_PERMISSION); } } // For folders we do recursive (in 1.6.0 this is not actual as UI will not // let to share a folder to other user) if (fileNode.isNodeType(JCRLocalCloudDrive.NT_FOLDER)) { // check the all children but don't force adding exo:privilegeable for (NodeIterator niter = file.getNodes(); niter.hasNext();) { Node child = niter.nextNode(); setUserFilePermission(child, userId, false); } } // Don't save the all here, do this once in the caller // target.save(); } /** * Adds the group permission for cloud file. * * @param fileNode the node * @param groupId the group id * @param forcePrivilegeable if need force adding of exo:privilegeable mixin * to the node * @throws RepositoryException the repository exception */ protected void setGroupFilePermission(Node fileNode, String groupId, boolean forcePrivilegeable) throws RepositoryException { ExtendedNode file = (ExtendedNode) fileNode; boolean setPermission = false; if (file.canAddMixin(EXO_PRIVILEGEABLE)) { if (forcePrivilegeable) { file.addMixin(EXO_PRIVILEGEABLE); setPermission = true; } // else will not set permissions on this node, but will check the child // nodes } else if (file.isNodeType(EXO_PRIVILEGEABLE)) { // already exo:privilegeable setPermission = true; } if (setPermission) { // XXX we DON'T clean what ShareDocumentService could add to let // UIShareDocuments show permissions correctly, // we only ensure that required rights are OK String identity = new StringBuilder("*:").append(groupId).toString(); if (!file.getACL().getPermissions(identity).contains(PermissionType.READ)) { file.getACL().addPermissions(identity, READER_PERMISSION); } } // For folders we do recursive if (fileNode.isNodeType(JCRLocalCloudDrive.NT_FOLDER)) { // check the all children but don't force adding exo:privilegeable for (NodeIterator niter = file.getNodes(); niter.hasNext();) { Node child = niter.nextNode(); setGroupFilePermission(child, groupId, false); } } // Don't save the all here, do this once in the caller // target.save(); } /** * Adds the permission for a cloud file link: user who shared and to whom or * group manager have full permissions, others can read only. * * @param linkNode the node * @param ownerId the owner id * @param sharedIdentity the group id * @param canEdit the can edit flag * @throws AccessControlException the access control exception * @throws RepositoryException the repository exception */ protected void setLinkPermission(Node linkNode, String ownerId, String sharedIdentity, boolean canEdit) throws AccessControlException, RepositoryException { ExtendedNode link = (ExtendedNode) linkNode; boolean setPermission = false; if (link.canAddMixin(EXO_PRIVILEGEABLE)) { link.addMixin(EXO_PRIVILEGEABLE); setPermission = true; } else if (link.isNodeType(EXO_PRIVILEGEABLE)) { // already exo:privilegeable setPermission = true; } if (setPermission) { if (sharedIdentity.startsWith("/")) { // It's space link // File owner can do everything in any case link.setPermission(ownerId, PermissionType.ALL); if (canEdit) { // Allow any member to modify the link node link.setPermission(new StringBuilder("*:").append(sharedIdentity).toString(), MANAGER_PERMISSION); } else { // First remove write rights to anybody of the group removeWritePermissions(link, sharedIdentity); // Allow any member read only (this includes copy) link.setPermission(new StringBuilder("*:").append(sharedIdentity).toString(), READER_PERMISSION); // But space manager should be able to move/rename/delete and change // properties also String managerMembership = getMembershipName("manager"); link.setPermission(new StringBuilder(managerMembership).append(':').append(sharedIdentity).toString(), MANAGER_PERMISSION); } } else { // It's user link // File owner can do everything link.setPermission(ownerId, PermissionType.ALL); // Target user should be able to move/rename/delete and change // properties link.setPermission(sharedIdentity, MANAGER_PERMISSION); } } // Don't save the all here, do this once in the caller // target.save(); } /** * Initialize the cloud file link node (mixin node type and permissions). * * @param fileNode the file node * @param identity the identity this link was shared to * @param targetPath the target path * @param canEdit the can edit flag */ protected void initCloudFileLink(Node fileNode, String identity, String targetPath, boolean canEdit) { try { // FYI link(s) should be created by CloudDriveShareDocumentService, it // creates them under system session, thus we will do the same. SessionProvider systemSession = sessionProviders.getSystemSessionProvider(null); List<Node> links = linkManager.getAllLinks(fileNode, EXO_SYMLINK, systemSession); for (Node linkNode : links) { // do only for a target (space or user) if (linkNode.getPath().startsWith(targetPath)) { if (linkNode.canAddMixin(CloudFileActionService.ECD_CLOUDFILELINK)) { linkNode.addMixin(CloudFileActionService.ECD_CLOUDFILELINK); if (identity != null) { linkNode.setProperty(CloudFileActionService.ECD_SHAREIDENTITY, identity); } setLinkPermission(linkNode, ((ExtendedNode) fileNode).getACL().getOwner(), identity, canEdit); linkNode.save(); } else { // TODO it seems a normal case, should we update ECD_SHAREIDENTITY // on existing link? LOG.warn("Cannot add mixin " + CloudFileActionService.ECD_CLOUDFILELINK + " to symlink " + linkNode.getPath()); } } } } catch (Exception e) { LOG.error("Error initializing cloud file link: " + fileNode, e); } } /** * Remove write permissions for all kinds of membership for this group or * user. * * @param target the target * @param groupOrUserId the group or user id * @throws RepositoryException the repository exception */ protected void removeWritePermissions(ExtendedNode target, String groupOrUserId) throws RepositoryException { for (AccessControlEntry acle : target.getACL().getPermissionEntries()) { if (acle.getIdentity().equals(groupOrUserId) || (acle.getMembershipEntry() != null && acle.getMembershipEntry().getGroup().equals(groupOrUserId))) { if (PermissionType.ADD_NODE.equals(acle.getPermission()) || PermissionType.REMOVE.equals(acle.getPermission()) || PermissionType.SET_PROPERTY.equals(acle.getPermission())) { target.removePermission(acle.getIdentity(), acle.getPermission()); } } } } /** * Gets the cloud file links. * * @param targetNode the target node * @param shareIdentity the share identity * @param useSystemSession the use system session * @return the cloud file links * @throws RepositoryException the repository exception */ public NodeIterator getCloudFileLinks(Node targetNode, String shareIdentity, boolean useSystemSession) throws RepositoryException { return getCloudFileLinks(targetNode, shareIdentity, null, useSystemSession); } }
40,628
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CheckInManageComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/CheckInManageComponent.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.action; import java.util.List; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilters; /** * Overrides original ECMS component to replace * {@link IsVersionableOrAncestorFilter} with safe version that can work with * symlinks to private user Cloud Drive files.<br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CheckInManageComponent.java 00000 Jul 8, 2015 pnedonosko $ */ @ComponentConfig(events = { @EventConfig(listeners = CheckInManageComponent.CheckInActionListener.class) }) public class CheckInManageComponent extends org.exoplatform.ecm.webui.component.explorer.rightclick.manager.CheckInManageComponent { /** The cd filter. */ protected static IsVersionableOrAncestorFilter cdFilter = new IsVersionableOrAncestorFilter(); /** * {@inheritDoc} */ @UIExtensionFilters public List<UIExtensionFilter> getFilters() { List<UIExtensionFilter> filters = super.getFilters(); // replace ECMS's IsVersionableOrAncestorFilter with ones from Cloud Drive for (int i = 0; i < filters.size(); i++) { UIExtensionFilter of = filters.get(i); if (of instanceof org.exoplatform.ecm.webui.component.explorer.control.filter.IsVersionableOrAncestorFilter) { filters.set(i, cdFilter); } } return filters; } }
2,460
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UICloudDriveClipboard.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/UICloudDriveClipboard.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.action; import javax.jcr.Node; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.sidebar.UIClipboard; import org.exoplatform.services.cms.clipboard.jcr.model.ClipboardCommand; 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.UIApplication; import org.exoplatform.webui.event.Event; /** * Extended ECMS clipboard with support of Cloud Drive files pasting as * symlinks. This class used as component config for actual {@link UIClipboard} * in {@link CloudDriveClipboardActionComponent}.<br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: UICloudDriveClipboard.java 00000 May 13, 2014 pnedonosko $ */ @ComponentConfig(template = "app:/groovy/webui/component/explorer/sidebar/UIClipboard.gtmpl", events = { @EventConfig(listeners = UICloudDriveClipboard.PasteActionListener.class), @EventConfig(listeners = UIClipboard.DeleteActionListener.class), @EventConfig(listeners = UIClipboard.ClearAllActionListener.class) }) public class UICloudDriveClipboard extends UIClipboard { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(UICloudDriveClipboard.class); /** * The listener interface for receiving pasteAction events. The class that is * interested in processing a pasteAction event implements this interface, and * the object created with that class is registered with a component using the * component's <code>addPasteActionListener</code> method. When the * pasteAction event occurs, that object's appropriate method is invoked. */ public static class PasteActionListener extends UIClipboard.PasteActionListener { /** * {@inheritDoc} */ public void execute(Event<UIClipboard> event) throws Exception { UIClipboard uiClipboard = event.getSource(); UIJCRExplorer uiExplorer = uiClipboard.getAncestorOfType(UIJCRExplorer.class); String indexParam = event.getRequestContext().getRequestParameter(OBJECTID); int index = Integer.parseInt(indexParam); ClipboardCommand selectedClipboard = uiClipboard.getClipboardData().get(index - 1); Node destNode = uiExplorer.getCurrentNode(); CloudFileAction symlinks = new CloudFileAction(uiExplorer); try { symlinks.setDestination(destNode); symlinks.addSource(selectedClipboard.getWorkspace(), selectedClipboard.getSrcPath()); boolean isCut = ClipboardCommand.CUT.equals(selectedClipboard.getType()); if (isCut) { symlinks.move(); } if (symlinks.apply()) { if (isCut) { uiClipboard.getClipboardData().remove(selectedClipboard); } uiExplorer.updateAjax(event); return; } } catch (CloudFileActionException e) { // this exception is a part of logic and it interrupts the move // operation LOG.warn(e.getMessage(), e); UIApplication uiApp = uiExplorer.getAncestorOfType(UIApplication.class); uiApp.addMessage(e.getUIMessage()); symlinks.rollback(); uiExplorer.updateAjax(event); return; } catch (Exception e) { // let original code to work LOG.warn("Error creating link of cloud file. Default behaviour will be applied (file Paste).", e); } // else... original behaviour super.execute(event); } } /** * Instantiates a new UI cloud drive clipboard. * * @throws Exception the exception */ public UICloudDriveClipboard() throws Exception { super(); } }
4,714
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ManageVersionsActionComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/ManageVersionsActionComponent.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.action; import java.util.List; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilters; /** * Overrides original ECMS component to replace * {@link IsNotIgnoreVersionNodeFilter} with safe version that can work with * symlinks to private user Cloud Drive files.<br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: ManageVersionsActionComponent.java 00000 Jul 6, 2015 pnedonosko * $ */ @ComponentConfig(events = { @EventConfig(listeners = ManageVersionsActionComponent.ManageVersionsActionListener.class) }) public class ManageVersionsActionComponent extends org.exoplatform.ecm.webui.component.explorer.control.action.ManageVersionsActionComponent { /** The cd filter. */ protected static IsNotIgnoreVersionNodeFilter cdFilter = new IsNotIgnoreVersionNodeFilter(); /** * {@inheritDoc} */ @UIExtensionFilters public List<UIExtensionFilter> getFilters() { List<UIExtensionFilter> filters = super.getFilters(); // replace ECMS's IsNotIgnoreVersionNodeFilter with ones from Cloud Drive for (int i = 0; i < filters.size(); i++) { UIExtensionFilter of = filters.get(i); if (of instanceof org.exoplatform.ecm.webui.component.explorer.control.filter.IsNotIgnoreVersionNodeFilter) { filters.set(i, cdFilter); } } return filters; } }
2,503
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudFileActionException.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/CloudFileActionException.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.action; import org.exoplatform.web.application.ApplicationMessage; /** * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudFileActionException.java 00000 May 19, 2014 pnedonosko $ */ public class CloudFileActionException extends Exception { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 24966321739068360L; /** The ui message. */ protected final ApplicationMessage uiMessage; /** * Instantiates a new cloud file action exception. * * @param message the message * @param uiMessage the ui message */ public CloudFileActionException(String message, ApplicationMessage uiMessage) { super(message); this.uiMessage = uiMessage; } /** * Instantiates a new cloud file action exception. * * @param message the message * @param uiMessage the ui message * @param cause the cause */ public CloudFileActionException(String message, ApplicationMessage uiMessage, Throwable cause) { super(message, cause); this.uiMessage = uiMessage; } /** * Gets the UI message. * * @return the uiMessage */ public ApplicationMessage getUIMessage() { return uiMessage; } }
2,155
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudFileAction.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/CloudFileAction.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.action; import java.util.LinkedHashSet; import java.util.ResourceBundle; import java.util.Set; import java.util.regex.Matcher; import javax.jcr.ItemExistsException; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.UIWorkingArea; import org.exoplatform.ecm.webui.component.explorer.rightclick.manager.MoveNodeManageComponent; import org.exoplatform.ecm.webui.component.explorer.rightclick.manager.PasteManageComponent; import org.exoplatform.ecm.webui.utils.PermissionUtil; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveManager; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.ecm.webui.clouddrives.CloudDriveContext; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.organization.Group; import org.exoplatform.services.organization.OrganizationService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.social.core.space.model.Space; import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.wcm.ext.component.document.service.IShareDocumentService; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.web.application.RequestContext; import org.exoplatform.webui.application.WebuiRequestContext; /** * Support of Cloud Drive file operations (move, copy and linking) in ECMS. If * not a cloud file then this helper return <code>false</code> and the caller * code should apply default logic for the file. <br> * Code parts of this class based on original {@link PasteManageComponent} and * {@link MoveNodeManageComponent} (state of ECMS 4.0.4).<br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudFileAction.java 00000 May 12, 2014 pnedonosko $ */ public class CloudFileAction { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(CloudFileAction.class); /** The empty params. */ protected final String[] emptyParams = new String[0]; /** The ui explorer. */ protected final UIJCRExplorer uiExplorer; /** * Set of source nodes for the operation. We rely on proper implementation of * Node's hash code and equality to avoid duplicates. */ protected final Set<Node> srcNodes = new LinkedHashSet<Node>(); /** The dest path. */ protected String destWorkspace, destPath; /** The dest node. */ protected Node destNode; /** The link. */ protected Node link; /** The move. */ protected boolean move; /** * Instantiates a new cloud file action. * * @param uiExplorer the ui explorer */ public CloudFileAction(UIJCRExplorer uiExplorer) { this.uiExplorer = uiExplorer; } /** * Add source file (target file). * * @param srcNode {@link Node} * @return the cloud file action */ public CloudFileAction addSource(Node srcNode) { this.srcNodes.add(srcNode); return this; } /** * Add source file path (path to target file). * * @param srcInfo {@link String} in format of portal request ObjectId, see * {@link UIWorkingArea#FILE_EXPLORER_URL_SYNTAX} * @return the cloud file action * @throws Exception if cannot find node by given path */ public CloudFileAction addSource(String srcInfo) throws Exception { // FYI don't take a target, use current context node return addSource(getNodeByInfo(srcInfo, false)); } /** * Add source file by its wokrspace name and path. * * @param srcWorkspace {@link String} * @param srcPath {@link String} * @return the cloud file action * @throws Exception the exception */ public CloudFileAction addSource(String srcWorkspace, String srcPath) throws Exception { // FYI don't take a target, use current context node return addSource(getNodeByPath(srcWorkspace, srcPath, false)); } /** * Set link destination node. * * @param destNode {@link Node} * @return the cloud file action * @throws Exception the exception */ public CloudFileAction setDestination(Node destNode) throws Exception { this.destWorkspace = destNode.getSession().getWorkspace().getName(); // FYI take real target node, not the link this.destNode = getNodeByPath(this.destWorkspace, destNode.getPath(), true); this.destPath = this.destNode.getPath(); return this; } /** * Set path of link destination. * * @param destInfo {@link String} in format of portal request ObjectId, see * {@link UIWorkingArea#FILE_EXPLORER_URL_SYNTAX} * @return the cloud file action * @throws Exception if cannot find node by given path or cannot read its * metadata */ public CloudFileAction setDestination(String destInfo) throws Exception { // FYI take real target node, not the link return setDestination(getNodeByInfo(destInfo, true)); } /** * Link behaviour as instead of "move" operation. Behaviour of "copy" by * default. * * @return the cloud file action */ public CloudFileAction move() { this.move = true; return this; } /** * Return symlink-node created by {@link #apply()} method if it returned * <code>true</code>. This method has sense only after calling the mentioned * method, otherwise this method returns <code>null</code>. * * @return the link {@link Node} or <code>null</code> if link not yet created * or creation wasn't successful. */ public Node getLink() { return link; } /** * Workspace of already set destination or <code>null</code> if not yet set. * * @return the destWorkspace {@link String} */ public String getDestinationWorkspace() { return destWorkspace; } /** * Path of already set destination or <code>null</code> if not yet set. * * @return the destPath {@link String} */ public String getDestonationPath() { return destPath; } /** * Node of already set destination or <code>null</code> if not yet set. * * @return the destNode {@link Node} */ public Node getDestinationNode() { return destNode; } /** * Rollback the symlink at its destination in JCR. * * @throws RepositoryException the repository exception */ public void rollback() throws RepositoryException { destNode.getSession().refresh(false); } /** * Apply an action for all added source files: move, copy or link from source * to destination. This method will save the session of destination node in * case of symlink creation. * * @return <code>true</code> if all sources were linked in destination * successfully, <code>false</code> otherwise. If nothing applied * return <code>false</code> also. * @throws CloudFileActionException if destination cannot be created locally, * this exception will contain detailed message and a * internationalized text for WebUI application. * @throws Exception the exception */ public boolean apply() throws CloudFileActionException, Exception { if (destWorkspace != null) { if (PermissionUtil.canAddNode(destNode) && !uiExplorer.nodeIsLocked(destNode) && destNode.isCheckedOut()) { if (srcNodes.size() > 0) { Space destSpace = null; String groupId = null; CloudFileActionService actions = WCMCoreUtils.getService(CloudFileActionService.class); DriveData documentsDrive = uiExplorer.getDriveData(); if (documentsDrive != null) { if (actions.isGroupDrive(documentsDrive)) { groupId = documentsDrive.getName().replace('.', '/'); // destination in group documents SpaceService spaces = WCMCoreUtils.getService(SpaceService.class); destSpace = spaces.getSpaceByGroupId(groupId); } } CloudDriveService driveService = WCMCoreUtils.getService(CloudDriveService.class); LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class); CloudDrive destLocal = driveService.findDrive(destNode); int linksCreated = 0; for (Node srcNode : srcNodes) { CloudDrive srcLocal = driveService.findDrive(srcNode); String srcPath = srcNode.getPath(); if (!destPath.startsWith(srcPath)) { if (srcLocal != null && srcLocal.isDrive(srcNode)) { // it is a drive node as source - reject it throw new CloudFileActionException("Copy or move of cloud drive not supported: " + srcPath + " to " + destPath, new ApplicationMessage("CloudFile.msg.CloudDriveCopyMoveNotSupported", null, ApplicationMessage.WARNING)); } } if (destLocal == null) { // paste outside a cloud drive if (srcLocal != null && !linkManager.isLink(srcNode)) { // if cloud file, not a link to it... // it is also not a cloud drive root node as was checked // above... // then move not supported for the moment! if (move) { if (srcLocal.hasFile(srcPath)) { throw new CloudFileActionException("Move of cloud file to outside the cloud drive not supported: " + srcPath + " -> " + destPath, new ApplicationMessage("CloudFile.msg.MoveToOutsideDriveNotSupported", null, ApplicationMessage.WARNING)); } // else, it's local (ignored) node in the drive folder - use // default behaviour for it } else { // it's copy... check if it is the same workspace String srcWorkspace = srcNode.getSession().getWorkspace().getName(); if (srcWorkspace.equals(destWorkspace)) { // need create symlink into destNode if (groupId != null && destSpace != null) { // it's link in group documents (e.g. space documents): // need share with the group IShareDocumentService shareService = WCMCoreUtils.getService(IShareDocumentService.class); shareService.publishDocumentToSpace(groupId, srcNode, "", PermissionType.READ); // ShareDocumentService will create a link into Shared // folder of the space docs, so we need move it to a right // place at pointed destination by Paste action. // XXX we use names hardcoded in // ShareDocumentService.publishDocumentToSpace() try { String sharedFolderPath = documentsDrive.getHomePath() + "/Shared"; for (NodeIterator niter = actions.getCloudFileLinks(srcNode, groupId, true); niter.hasNext();) { Node link = niter.nextNode(); if (link.getParent().getPath().equals(sharedFolderPath)) { Session sysSession = link.getSession(); sysSession.refresh(true); try { sysSession.move(link.getPath(), destNode.getPath() + "/" + link.getName()); sysSession.save(); } catch (ItemExistsException e) { throw new CloudFileActionException("Cannot move pasted Cloud File to a destination. " + srcWorkspace + ":" + srcPath + " -> " + destWorkspace + ":" + destPath, new ApplicationMessage("CloudFile.msg.DestinationItemNameExists", null, ApplicationMessage.ERROR), e); } // don't touch others, assume the first is ours break; } } } catch (Exception e) { throw new CloudFileActionException("Error moving pasted Cloud File to a destination. " + srcWorkspace + ":" + srcPath + " -> " + destWorkspace + ":" + destPath, new ApplicationMessage("CloudFile.msg.ErrorMoveToDestination", null, ApplicationMessage.ERROR), e); } linksCreated++; } else { // else, since 1.6.0 we don't support sharing cloud files // to non space groups (due to PLF5 UI limitation in // ECMS's UIShareDocuments) throw new CloudFileActionException("Linking to not space groups not supported for Cloud Drive files. " + srcWorkspace + ":" + srcPath + " -> " + destWorkspace + ":" + destPath, new ApplicationMessage("CloudFile.msg.FileLinksNotSupportedToThisDestination", null, ApplicationMessage.ERROR)); } } else { // else, we don't support cross-workspaces paste for cloud // drive throw new CloudFileActionException("Linking between workspaces not supported for Cloud Drive files. " + srcWorkspace + ":" + srcPath + " -> " + destWorkspace + ":" + destPath, new ApplicationMessage("CloudFile.msg.MoveBetweenWorkspacesNotSupported", null, ApplicationMessage.WARNING)); } } } // else, dest and src nulls means this happens not with cloud // drive files at all } else { // it's paste to a cloud drive sub-tree... if (srcLocal != null) { if (srcLocal.equals(destLocal)) { if (!move) { // track "paste" fact for copy-behaviour and then let // original code work new CloudDriveManager(destLocal).initCopy(srcNode, destNode); } } else { // TODO implement support copy/move to another drive // For support of move also need refresh paths of all // items in clipboard to reflect the // moved parents, see PasteManageComponent.updateClipboard() throw new CloudFileActionException("Copy or move of cloud file to another cloud drive not supported: " + srcPath + " -> " + destPath, new ApplicationMessage("CloudFile.msg.MoveToAnotherDriveNotSupported", null, ApplicationMessage.WARNING)); } } // otherwise, let original code to copy the file to cloud drive // sub-tree // TODO do links need special handling for copy-to-drive? } } if (linksCreated > 0) { RequestContext rcontext = WebuiRequestContext.getCurrentInstance(); if (rcontext != null) { String multiple = linksCreated > 1 ? "s" : ""; String destName = actions.documentName(destNode); ApplicationMessage title = new ApplicationMessage("CloudFile.msg.LinkCreated", new String[] { multiple }); ApplicationMessage text; if (destSpace != null) { text = new ApplicationMessage("CloudFile.msg.FileLinksSharedInSpace", new String[] { multiple, destName, destSpace.getDisplayName() }); } else if (groupId != null) { OrganizationService orgService = WCMCoreUtils.getService(OrganizationService.class); Group group = orgService.getGroupHandler().findGroupById(groupId); text = new ApplicationMessage("CloudFile.msg.FileLinksSharedInGroup", new String[] { multiple, destName, group.getGroupName() }); } else { text = new ApplicationMessage("CloudFile.msg.FileLinksCreated", new String[] { multiple, destName }); } ResourceBundle res = rcontext.getApplicationResourceBundle(); title.setResourceBundle(res); text.setResourceBundle(res); CloudDriveContext.showInfo(rcontext, title.getMessage(), text.getMessage()); } // finally save the link and related changes destNode.getSession().save(); return true; } else { return false; } } else { throw new CloudFileActionException("Source should be defined.", new ApplicationMessage("CloudFile.msg.SourceNotDefined", emptyParams)); } } else { throw new CloudFileActionException("Destination not writtable.", new ApplicationMessage("CloudFile.msg.DestinationNotWrittable", emptyParams)); } } else { throw new CloudFileActionException("Destination should be defined.", new ApplicationMessage("CloudFile.msg.DestinationNotDefined", emptyParams)); } } /** * Gets the node by info. * * @param pathInfo the path info * @param giveTarget the give target * @return the node by info * @throws Exception the exception */ protected Node getNodeByInfo(String pathInfo, boolean giveTarget) throws Exception { Matcher matcher = UIWorkingArea.FILE_EXPLORER_URL_SYNTAX.matcher(pathInfo); String workspace, path; if (matcher.find()) { workspace = matcher.group(1); path = matcher.group(2); } else { throw new IllegalArgumentException("The ObjectId is invalid '" + pathInfo + "'"); } return getNodeByPath(workspace, path, giveTarget); } /** * Gets the node by path. * * @param workspace the workspace * @param path the path * @param giveTarget the give target * @return the node by path * @throws Exception the exception */ protected Node getNodeByPath(String workspace, String path, boolean giveTarget) throws Exception { Session srcSession = uiExplorer.getSessionByWorkspace(workspace); return uiExplorer.getNodeByPath(path, srcSession, giveTarget); } }
21,142
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDriveClipboardActionComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/CloudDriveClipboardActionComponent.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.action; import org.exoplatform.ecm.webui.component.explorer.sidebar.UIClipboard; import org.exoplatform.ecm.webui.component.explorer.sidebar.UISideBar; import org.exoplatform.ecm.webui.component.explorer.sidebar.action.ClipboardActionComponent; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.event.Event; /** * Override ECMS's {@link ClipboardActionComponent} to extend * {@link UIClipboard} Paste-action to support Cloud Drive file linking instead * of copying or moving the file.<br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: ClipboardActionComponent.java 00000 May 12, 2014 pnedonosko $ */ @ComponentConfig(events = { @EventConfig(listeners = CloudDriveClipboardActionComponent.ClipboardActionListener.class) }) public class CloudDriveClipboardActionComponent extends ClipboardActionComponent { /** * The listener interface for receiving clipboardAction events. The class that * is interested in processing a clipboardAction event implements this * interface, and the object created with that class is registered with a * component using the component's <code>addClipboardActionListener</code> * method. When the clipboardAction event occurs, that object's appropriate * method is invoked. */ public static class ClipboardActionListener extends ClipboardActionComponent.ClipboardActionListener { /** * {@inheritDoc} */ @Override protected void processEvent(Event<ClipboardActionComponent> event) throws Exception { // Replace UIClipboard listener in UISideBar UISideBar uiSideBar = event.getSource().getAncestorOfType(UISideBar.class); UIClipboard clipboard = uiSideBar.getChild(UIClipboard.class); // patch clipboard with Cloud Drive config clipboard.setComponentConfig(UICloudDriveClipboard.class, null); // let original code to continue super.processEvent(event); } } /** * Instantiates a new cloud drive clipboard action component. */ public CloudDriveClipboardActionComponent() { super(); } }
3,102
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
IsNotIgnoreVersionNodeFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/action/IsNotIgnoreVersionNodeFilter.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.action; import java.util.Map; import org.exoplatform.services.cms.clouddrives.webui.filters.NotCloudDriveOrFileFilter; /** * Overrides original ECMS's filter to do not accept Cloud Drive and its * files.<br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: IsNotIgnoreVersionNodeFilter.java 00000 Jul 6, 2015 pnedonosko * $ */ public class IsNotIgnoreVersionNodeFilter extends org.exoplatform.ecm.webui.component.explorer.control.filter.IsNotIgnoreVersionNodeFilter { /** The not cloud drive filter. */ private NotCloudDriveOrFileFilter notCloudDriveFilter = new NotCloudDriveOrFileFilter(); /** * {@inheritDoc} */ @Override public boolean accept(Map<String, Object> context) throws Exception { if (notCloudDriveFilter.accept(context)) { return super.accept(context); } else { return false; } } }
1,866
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
AbstractFileForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/viewer/AbstractFileForm.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.viewer; import java.util.Locale; import java.util.ResourceBundle; import javax.ws.rs.core.MediaType; import org.exoplatform.ecm.webui.viewer.CloudFileViewer; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.portal.webui.workspace.UIPortalApplication; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudFile; import org.exoplatform.services.cms.clouddrives.webui.BaseCloudDriveForm; import org.exoplatform.services.resources.ResourceBundleService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.webui.application.WebuiRequestContext; /** * Base support for WebUI forms based on Cloud Drive file. */ public abstract class AbstractFileForm extends BaseCloudDriveForm implements CloudFileViewer { /** The drive. */ protected CloudDrive drive; /** The file. */ protected CloudFile file; /** * {@inheritDoc} */ @Override public void processRender(WebuiRequestContext context) throws Exception { initContext(); Object obj = context.getAttribute(CloudDrive.class); if (obj != null) { CloudDrive drive = (CloudDrive) obj; obj = context.getAttribute(CloudFile.class); if (obj != null) { initFile(drive, (CloudFile) obj); } } super.processRender(context); } /** * {@inheritDoc} */ @Override public void initFile(CloudDrive drive, CloudFile file) { this.drive = drive; this.file = file; } /** * Gets the drive. * * @return the drive */ public CloudDrive getDrive() { return drive; } /** * Gets the file. * * @return the file */ public CloudFile getFile() { return file; } /** * Checks if is viewable. * * @return <code>true</code> if file can be represented as Web document. */ public boolean isViewable() { String mimeType = file.getType(); return !mimeType.startsWith(MediaType.APPLICATION_OCTET_STREAM); } /** * Gets the resource bundle. * * @param key the key * @return the resource bundle */ public String appRes(String key) { Locale locale = Util.getUIPortal().getAncestorOfType(UIPortalApplication.class).getLocale(); ResourceBundleService resourceBundleService = WCMCoreUtils.getService(ResourceBundleService.class); ResourceBundle resourceBundle = resourceBundleService.getResourceBundle( new String[] { "locale.clouddrive.CloudDrive", "locale.ecm.views", localeFile() }, locale, this.getClass().getClassLoader()); return resourceBundle.getString(key); } /** * Locale file. * * @return the string */ protected abstract String localeFile(); }
3,883
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
H264VideoViewer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/viewer/H264VideoViewer.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.viewer; import org.exoplatform.ecm.webui.viewer.AbstractCloudFileViewer; import org.exoplatform.webui.config.annotation.ComponentConfig; /** * H.264 media files viewer for Cloud Drive. */ @ComponentConfig(template = "classpath:groovy/templates/H264VideoViewer.gtmpl") public class H264VideoViewer extends AbstractCloudFileViewer { /** * Instantiates a new h 264 video viewer. * * @throws Exception the exception */ public H264VideoViewer() throws Exception { } }
1,369
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ImageViewer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/viewer/ImageViewer.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.viewer; import org.exoplatform.ecm.webui.viewer.AbstractCloudFileViewer; import org.exoplatform.webui.config.annotation.ComponentConfig; /** * Image files viewer for Cloud Drive. */ @ComponentConfig(template = "classpath:groovy/templates/ImageViewer.gtmpl") public class ImageViewer extends AbstractCloudFileViewer { }
1,207
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
MpegVideoViewer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/viewer/MpegVideoViewer.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.viewer; import org.exoplatform.ecm.webui.viewer.AbstractCloudFileViewer; import org.exoplatform.webui.config.annotation.ComponentConfig; /** * MPEG files viewer for Cloud Drive. */ @ComponentConfig(template = "classpath:groovy/templates/MpegVideoViewer.gtmpl") public class MpegVideoViewer extends AbstractCloudFileViewer { /** * Instantiates a new mpeg video viewer. * * @throws Exception the exception */ public MpegVideoViewer() throws Exception { } }
1,361
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FlashViewer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/viewer/FlashViewer.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.viewer; import org.exoplatform.ecm.webui.viewer.AbstractCloudFileViewer; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.ext.manager.UIAbstractManager; /** * Flash files viewer for Cloud Drive. */ @ComponentConfig(template = "classpath:groovy/templates/FlashViewer.gtmpl") public class FlashViewer extends AbstractCloudFileViewer { /** * Instantiates a new flash viewer. * * @throws Exception the exception */ public FlashViewer() throws Exception { } }
1,405
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PDFViewer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/viewer/PDFViewer.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.viewer; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.jcr.RepositoryException; import org.exoplatform.ecm.connector.clouddrives.ContentService; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveException; import org.exoplatform.services.cms.clouddrives.CloudFile; import org.exoplatform.services.cms.clouddrives.DriveRemovedException; import org.exoplatform.services.cms.clouddrives.viewer.DocumentNotFoundException; import org.exoplatform.services.cms.clouddrives.viewer.ViewerStorage; import org.exoplatform.services.cms.clouddrives.viewer.ViewerStorage.ContentFile; import org.exoplatform.services.cms.clouddrives.viewer.ViewerStorage.PDFFile; import org.exoplatform.services.jcr.RepositoryService; 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.UIFormSelectBox; import org.exoplatform.webui.form.UIFormStringInput; /** * PDF Viewer component which will be used to display PDF and office files from * Cloud Drive. */ @ComponentConfig(lifecycle = UIFormLifecycle.class, template = "classpath:groovy/templates/PDFViewer.gtmpl", events = { @EventConfig(listeners = PDFViewer.NextPageActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = PDFViewer.PreviousPageActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = PDFViewer.GotoPageActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = PDFViewer.RotateRightPageActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = PDFViewer.RotateLeftPageActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = PDFViewer.ScalePageActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = PDFViewer.ZoomInPageActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = PDFViewer.ZoomOutPageActionListener.class, phase = Phase.DECODE) }) public class PDFViewer extends AbstractFileForm { /** The Constant PAGE_NUMBER. */ private static final String PAGE_NUMBER = "pageNumber"; /** The Constant SCALE_PAGE. */ private static final String SCALE_PAGE = "scalePage"; /** The Constant localeFile. */ private static final String localeFile = "locale.portlet.viewer.PDFViewer"; /** The storage. */ private final ViewerStorage storage; /** The jcr service. */ private final RepositoryService jcrService; /** The pdf file. */ private PDFFile pdfFile; /** The pdf link. */ private String pdfLink; /** The pdf page link. */ private String pdfPageLink; /** The current page number. */ private int currentPageNumber = 1; /** The current rotation. */ private float currentRotation = 0.0f; /** The current scale. */ private float currentScale = 1.0f; /** * Instantiates a new PDF viewer. * * @throws Exception the exception */ public PDFViewer() throws Exception { this.storage = (ViewerStorage) getApplicationComponent(ViewerStorage.class); this.jcrService = (RepositoryService) getApplicationComponent(RepositoryService.class); addUIFormInput(new UIFormStringInput(PAGE_NUMBER, PAGE_NUMBER, "1")); UIFormSelectBox uiScaleBox = new UIFormSelectBox(SCALE_PAGE, SCALE_PAGE, initScaleOptions()); uiScaleBox.setOnChange("ScalePage"); addUIFormInput(uiScaleBox); uiScaleBox.setValue("1.0f"); } /** * {@inheritDoc} */ @Override public boolean isViewable() { return pdfFile != null && super.isViewable(); } /** * {@inheritDoc} */ @Override protected String localeFile() { return localeFile; } /** * {@inheritDoc} */ @Override public void initFile(CloudDrive drive, CloudFile file) { this.pdfFile = null; this.pdfLink = pdfPageLink = null; super.initFile(drive, file); try { // init PDF viewer data (aka initDatas()) String repository = jcrService.getCurrentRepository().getConfiguration().getName(); String workspace = drive.getWorkspace(); ContentFile contentFile = storage.createFile(repository, workspace, drive, file); if (contentFile.isPDF()) { this.pdfFile = contentFile.asPDF(); // FYI preview link can be provider specific, thus we use exactly our // Content service // String previewLink = file.getPreviewLink(); String contentLink = ContentService.contentLink(workspace, file.getPath(), file.getId()); this.pdfLink = ContentService.pdfLink(contentLink); this.pdfPageLink = ContentService.pdfPageLink(contentLink); } else { LOG.warn("Current file view is not of PDF format " + file.getPath()); } } catch (DocumentNotFoundException e) { LOG.error("Error preparing PDF viewer", e); } catch (RepositoryException e) { LOG.error("Error initializing PDF viewer", e); } catch (DriveRemovedException e) { LOG.warn("Error initializing PDF viewer: " + e.getMessage()); } catch (CloudDriveException e) { LOG.warn("Error initializing PDF viewer: " + e.getMessage()); } catch (IOException e) { LOG.warn("Error initializing PDF viewer: " + e.getMessage()); } } /** * Gets the file metadata. * * @return the file metadata */ public Map<String, String> getFileMetadata() { if (pdfFile != null) { return pdfFile.getMetadata(); } return Collections.emptyMap(); } /** * Gets the number of pages. * * @return the number of pages */ public int getNumberOfPages() { if (pdfFile != null) { return pdfFile.getNumberOfPages(); } return 0; } /** * Gets the page image link. * * @return the pageImageLink */ public String getPageImageLink() { if (pdfPageLink != null) { StringBuilder link = new StringBuilder(); link.append(pdfPageLink); link.append(pdfPageLink.indexOf('?') > 0 ? '&' : '?'); link.append("page="); link.append(getPageNumber()); link.append("&rotation="); link.append(getCurrentRotation()); link.append("&scale="); link.append(getCurrentScale()); return link.toString(); } else { return null; } } /** * Gets the pdf link. * * @return the PDF link */ public String getPdfLink() { return pdfLink; } /** * Gets the current rotation. * * @return the current rotation */ public float getCurrentRotation() { return currentRotation; } /** * Sets the rotation. * * @param rotation the new rotation */ public void setRotation(float rotation) { currentRotation = rotation; } /** * Gets the current scale. * * @return the current scale */ public float getCurrentScale() { return currentScale; } /** * Sets the scale. * * @param scale the new scale */ public void setScale(float scale) { currentScale = scale; } /** * Gets the page number. * * @return the page number */ public int getPageNumber() { return currentPageNumber; } /** * Sets the page number. * * @param pageNum the new page number */ public void setPageNumber(int pageNum) { currentPageNumber = pageNum; }; /** * Inits the scale options. * * @return the list */ private List<SelectItemOption<String>> initScaleOptions() { List<SelectItemOption<String>> scaleOptions = new ArrayList<SelectItemOption<String>>(); scaleOptions.add(new SelectItemOption<String>("5%", "0.05f")); scaleOptions.add(new SelectItemOption<String>("10%", "0.1f")); scaleOptions.add(new SelectItemOption<String>("25%", "0.25f")); scaleOptions.add(new SelectItemOption<String>("50%", "0.5f")); scaleOptions.add(new SelectItemOption<String>("75%", "0.75f")); scaleOptions.add(new SelectItemOption<String>("100%", "1.0f")); scaleOptions.add(new SelectItemOption<String>("125%", "1.25f")); scaleOptions.add(new SelectItemOption<String>("150%", "1.5f")); scaleOptions.add(new SelectItemOption<String>("200%", "2.0f")); scaleOptions.add(new SelectItemOption<String>("300%", "3.0f")); return scaleOptions; } /** * The listener interface for receiving previousPageAction events. The class * that is interested in processing a previousPageAction event implements this * interface, and the object created with that class is registered with a * component using the component's <code>addPreviousPageActionListener</code> * method. When the previousPageAction event occurs, that object's appropriate * method is invoked. */ public static class PreviousPageActionListener extends EventListener<PDFViewer> { /** * {@inheritDoc} */ public void execute(Event<PDFViewer> event) throws Exception { PDFViewer pdfViewer = event.getSource(); if (pdfViewer.currentPageNumber == 1) { pdfViewer.getUIStringInput(PAGE_NUMBER).setValue(Integer.toString((pdfViewer.currentPageNumber))); } else { pdfViewer.getUIStringInput(PAGE_NUMBER).setValue(Integer.toString((pdfViewer.currentPageNumber - 1))); pdfViewer.setPageNumber(pdfViewer.currentPageNumber - 1); } event.getRequestContext().addUIComponentToUpdateByAjax(pdfViewer); } } /** * The listener interface for receiving nextPageAction events. The class that * is interested in processing a nextPageAction event implements this * interface, and the object created with that class is registered with a * component using the component's <code>addNextPageActionListener</code> * method. When the nextPageAction event occurs, that object's appropriate * method is invoked. */ static public class NextPageActionListener extends EventListener<PDFViewer> { /** * {@inheritDoc} */ public void execute(Event<PDFViewer> event) throws Exception { PDFViewer pdfViewer = event.getSource(); if (pdfViewer.currentPageNumber == pdfViewer.getNumberOfPages()) { pdfViewer.getUIStringInput(PAGE_NUMBER).setValue(Integer.toString((pdfViewer.currentPageNumber))); } else { pdfViewer.getUIStringInput(PAGE_NUMBER).setValue(Integer.toString((pdfViewer.currentPageNumber + 1))); pdfViewer.setPageNumber(pdfViewer.currentPageNumber + 1); } event.getRequestContext().addUIComponentToUpdateByAjax(pdfViewer); } } /** * The listener interface for receiving gotoPageAction events. The class that * is interested in processing a gotoPageAction event implements this * interface, and the object created with that class is registered with a * component using the component's <code>addGotoPageActionListener</code> * method. When the gotoPageAction event occurs, that object's appropriate * method is invoked. */ static public class GotoPageActionListener extends EventListener<PDFViewer> { /** * {@inheritDoc} */ public void execute(Event<PDFViewer> event) throws Exception { PDFViewer pdfViewer = event.getSource(); String pageStr = pdfViewer.getUIStringInput(PAGE_NUMBER).getValue(); int pageNumber = 1; try { pageNumber = Integer.parseInt(pageStr); } catch (NumberFormatException e) { pageNumber = pdfViewer.currentPageNumber; } if (pageNumber >= pdfViewer.getNumberOfPages()) pageNumber = pdfViewer.getNumberOfPages(); else if (pageNumber < 1) pageNumber = 1; pdfViewer.getUIStringInput(PAGE_NUMBER).setValue(Integer.toString((pageNumber))); pdfViewer.setPageNumber(pageNumber); event.getRequestContext().addUIComponentToUpdateByAjax(pdfViewer); } } /** * The listener interface for receiving rotateRightPageAction events. The * class that is interested in processing a rotateRightPageAction event * implements this interface, and the object created with that class is * registered with a component using the component's * <code>addRotateRightPageActionListener</code> method. When the * rotateRightPageAction event occurs, that object's appropriate method is * invoked. */ static public class RotateRightPageActionListener extends EventListener<PDFViewer> { /** * {@inheritDoc} */ public void execute(Event<PDFViewer> event) throws Exception { PDFViewer pdfViewer = event.getSource(); pdfViewer.setRotation(pdfViewer.currentRotation + 270.0f); event.getRequestContext().addUIComponentToUpdateByAjax(pdfViewer); } } /** * The listener interface for receiving rotateLeftPageAction events. The class * that is interested in processing a rotateLeftPageAction event implements * this interface, and the object created with that class is registered with a * component using the component's * <code>addRotateLeftPageActionListener</code> method. When the * rotateLeftPageAction event occurs, that object's appropriate method is * invoked. */ static public class RotateLeftPageActionListener extends EventListener<PDFViewer> { /** * {@inheritDoc} */ public void execute(Event<PDFViewer> event) throws Exception { PDFViewer pdfViewer = event.getSource(); pdfViewer.setRotation(pdfViewer.currentRotation + 90.0f); event.getRequestContext().addUIComponentToUpdateByAjax(pdfViewer); } } /** * The listener interface for receiving scalePageAction events. The class that * is interested in processing a scalePageAction event implements this * interface, and the object created with that class is registered with a * component using the component's <code>addScalePageActionListener</code> * method. When the scalePageAction event occurs, that object's appropriate * method is invoked. */ static public class ScalePageActionListener extends EventListener<PDFViewer> { /** * {@inheritDoc} */ public void execute(Event<PDFViewer> event) throws Exception { PDFViewer pdfViewer = event.getSource(); String scale = pdfViewer.getUIFormSelectBox(SCALE_PAGE).getValue(); pdfViewer.setScale(Float.parseFloat(scale)); event.getRequestContext().addUIComponentToUpdateByAjax(pdfViewer); } } /** * The listener interface for receiving zoomInPageAction events. The class * that is interested in processing a zoomInPageAction event implements this * interface, and the object created with that class is registered with a * component using the component's <code>addZoomInPageActionListener</code> * method. When the zoomInPageAction event occurs, that object's appropriate * method is invoked. */ static public class ZoomInPageActionListener extends EventListener<PDFViewer> { /** * {@inheritDoc} */ public void execute(Event<PDFViewer> event) throws Exception { PDFViewer pdfViewer = event.getSource(); String[] arrValue = { "0.05f", "0.1f", "0.25f", "0.5f", "0.75f", "1.0f", "1.25f", "1.5f", "2.0f", "3.0f" }; String scale = pdfViewer.getUIFormSelectBox(SCALE_PAGE).getValue(); if (scale.equals(arrValue[arrValue.length - 1])) return; for (int i = 0; i < arrValue.length - 1; i++) { if (scale.equals(arrValue[i])) { pdfViewer.setScale(Float.parseFloat(arrValue[i + 1])); pdfViewer.getUIFormSelectBox(SCALE_PAGE).setValue(arrValue[i + 1]); break; } } event.getRequestContext().addUIComponentToUpdateByAjax(pdfViewer); } } /** * The listener interface for receiving zoomOutPageAction events. The class * that is interested in processing a zoomOutPageAction event implements this * interface, and the object created with that class is registered with a * component using the component's <code>addZoomOutPageActionListener</code> * method. When the zoomOutPageAction event occurs, that object's appropriate * method is invoked. */ static public class ZoomOutPageActionListener extends EventListener<PDFViewer> { /** * {@inheritDoc} */ public void execute(Event<PDFViewer> event) throws Exception { PDFViewer pdfViewer = event.getSource(); String scale = pdfViewer.getUIFormSelectBox(SCALE_PAGE).getValue(); String[] arrValue = { "0.05f", "0.1f", "0.25f", "0.5f", "0.75f", "1.0f", "1.25f", "1.5f", "2.0f", "3.0f" }; if (scale.equals(arrValue[0])) return; for (int i = 0; i < arrValue.length - 1; i++) { if (scale.equals(arrValue[i])) { pdfViewer.setScale(Float.parseFloat(arrValue[i - 1])); pdfViewer.getUIFormSelectBox(SCALE_PAGE).setValue(arrValue[i - 1]); break; } } event.getRequestContext().addUIComponentToUpdateByAjax(pdfViewer); } } }
18,149
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
VideoAudioViewer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/viewer/VideoAudioViewer.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.viewer; import org.exoplatform.ecm.webui.viewer.AbstractCloudFileViewer; import org.exoplatform.webui.config.annotation.ComponentConfig; /** * Flash video/audio/mp3 files viewer for Cloud Drive. */ @ComponentConfig(template = "classpath:groovy/templates/VideoAudioViewer.gtmpl") public class VideoAudioViewer extends AbstractCloudFileViewer { /** * Instantiates a new video audio viewer. * * @throws Exception the exception */ public VideoAudioViewer() throws Exception { } }
1,382
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TextViewer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/viewer/TextViewer.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.viewer; import org.exoplatform.ecm.webui.viewer.AbstractCloudFileViewer; import org.exoplatform.services.cms.clouddrives.CloudDriveStorage; import org.exoplatform.services.cms.clouddrives.viewer.ContentReader; import org.exoplatform.services.cms.clouddrives.webui.filters.CloudDriveFilter; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.webui.config.annotation.ComponentConfig; /** * Text files viewer for Cloud Drive. */ @ComponentConfig(template = "classpath:groovy/templates/TextViewer.gtmpl") public class TextViewer extends AbstractCloudFileViewer { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(TextViewer.class); /** The Constant MAX_FILE_SIZE. */ public static final long MAX_FILE_SIZE = 2 * 1024 * 1024; // 2M /** * Checks if is web document. * * @return true, if is web document */ public boolean isWebDocument() { String mimeType = file.getType(); return mimeType.startsWith("text/html") || mimeType.startsWith("application/rss+xml") || mimeType.startsWith("application/xhtml"); } /** * Checks if is xml document. * * @return true, if is xml document */ public boolean isXmlDocument() { String mimeType = file.getType(); return mimeType.startsWith("text/xml") || mimeType.startsWith("application/xml") || (mimeType.startsWith("application/") && mimeType.indexOf("+xml") > 0); } /** * Checks if is formatted text. * * @return true, if is formatted text */ public boolean isFormattedText() { String mimeType = file.getType(); // text/x- can be used for various programming languages return (mimeType.startsWith("text/") && file.getTypeMode() != null) || (mimeType.startsWith("application/") && file.getTypeMode() != null) || mimeType.startsWith("text/x-") || mimeType.startsWith("application/x-sh") || mimeType.startsWith("text/javascript") || mimeType.startsWith("application/javascript") || mimeType.startsWith("text/json") || mimeType.startsWith("application/json"); } /** * {@inheritDoc} */ @Override public boolean isViewable() { boolean res = super.isViewable(); if (res) { // ensure size OK try { ContentReader content = ((CloudDriveStorage) drive).getFileContent(file.getId()); res = content.getLength() <= MAX_FILE_SIZE; } catch (Throwable e) { LOG.warn("Error getting file content reader for " + file.getId() + " " + file.getPath(), e); } } return res; } }
3,481
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDriveShareDocumentService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/document/CloudDriveShareDocumentService.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.services.cms.clouddrives.webui.document; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveException; import org.exoplatform.services.cms.clouddrives.CloudDriveSecurity; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.clouddrives.CloudDriveStorage; import org.exoplatform.services.cms.clouddrives.DriveRemovedException; import org.exoplatform.services.cms.clouddrives.NotCloudDriveException; import org.exoplatform.services.cms.clouddrives.CloudDriveStorage.Change; import org.exoplatform.services.cms.clouddrives.jcr.JCRLocalCloudDrive; import org.exoplatform.services.cms.clouddrives.webui.action.CloudFileActionService; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.identity.provider.SpaceIdentityProvider; import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.social.core.manager.IdentityManager; import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.wcm.ext.component.document.service.ShareDocumentService; /** * We need care about shared Cloud Files in special way: use dedicated activity * type.<br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudDriveShareDocumentService.java 00000 Jun 25, 2018 * pnedonosko $ */ public class CloudDriveShareDocumentService extends ShareDocumentService { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(CloudDriveShareDocumentService.class); /** The Constant SHARE_PERMISSION_MODIFY (copied from UIShareDocuments). */ protected static final String SHARE_PERMISSION_MODIFY = "modify"; /** The activity manager. */ protected final ActivityManager activityManager; /** The link manager. */ protected final LinkManager linkManager; /** The identity manager. */ protected final IdentityManager identityManager; /** The cloud drive service. */ protected final CloudDriveService cloudDrives; /** The hierarchy creator. */ protected final NodeHierarchyCreator hierarchyCreator; /** The cloud file actions. */ protected final CloudFileActionService cloudFileActions; /** The groups path. */ protected final String groupsPath; /** The users path. */ protected final String usersPath; /** * Instantiates a new share cloud drive document service. * * @param repoService the repo service * @param linkManager the link manager * @param sessionProviderService the session provider service * @param activityManager the activity manager * @param hierarchyCreator the hierarchy creator * @param identityManager the identity manager * @param cloudDrives the cloud drive service * @param cloudFileActions the cloud file actions */ public CloudDriveShareDocumentService(RepositoryService repoService, LinkManager linkManager, SessionProviderService sessionProviderService, ActivityManager activityManager, NodeHierarchyCreator hierarchyCreator, IdentityManager identityManager, CloudDriveService cloudDrives, CloudFileActionService cloudFileActions, SpaceService spaceService) { super(repoService, linkManager, identityManager, activityManager, spaceService, sessionProviderService); this.activityManager = activityManager; this.linkManager = linkManager; this.hierarchyCreator = hierarchyCreator; this.identityManager = identityManager; this.cloudDrives = cloudDrives; this.cloudFileActions = cloudFileActions; this.groupsPath = hierarchyCreator.getJcrPath(BasePath.CMS_GROUPS_PATH); this.usersPath = hierarchyCreator.getJcrPath(BasePath.CMS_USERS_PATH); } /** * {@inheritDoc} */ @Override public String publishDocumentToSpace(String groupId, Node node, String comment, String perm) { // TODO There is a problem how UIShareDocuments updates the permission of // already shared file: it calls unpublishDocumentToSpace() then // publishDocumentToSpace(), by doing this it causes removal of all links // (including copied, moved and renamed) and then creation of an one in // Shared folder. This way we don't respect what user did by pasting or // copying, moving, renaming the links - so we have bad UX. // This could be solved by extending UIShareDocuments in the addon and // overriding it's Change and Confirm listeners together with // updatePermission() and removePermission() methods - by these methods we // could know is it an update or just a sole addition/removal, and then in // Change listener we could inform our CloudDriveShareDocumentService (via // setting thread-local internally) that it's need of an update (of // permissions update actually) and don't unpublish then publish but just // make required updates. This should be done before invoking the super's // method unpublishDocumentToSpace() then publishDocumentToSpace(). // The same story for sharing with user. CloudDrive localDrive = findCloudDrive(node); if (localDrive != null) { return applyInDrive(localDrive, new Change<String>() { @Override public String apply() throws RepositoryException { if (LOG.isDebugEnabled()) { LOG.debug("Sharing Cloud File " + node.getPath() + " of " + localDrive + " to " + " " + groupId + " " + perm); } String activityId = CloudDriveShareDocumentService.super.publishDocumentToSpace(groupId, node, comment, perm); // We fix what super did to allow only read the cloud // file (instead of read, add node, set property and remove for 'Can // Write' option). cloudFileActions.shareToGroup(node, groupId, SHARE_PERMISSION_MODIFY.equalsIgnoreCase(perm)); // We change activity type to CloudDrive's one... ExoSocialActivity activity = activityManager.getActivity(activityId); if (activity != null && !CloudFileActionService.SHARE_CLOUD_FILES_SPACES.equals(activity.getType())) { activity.setType(CloudFileActionService.SHARE_CLOUD_FILES_SPACES); // ...and update activity in the space stream // XXX first we do update in the ActivityManager to clear its // storage cache, then we need saveActivityNoReturn() to save the // new type as updateActivity() doesn't do this. activityManager.updateActivity(activity); activityManager.saveActivityNoReturn(identityManager.getOrCreateIdentity(SpaceIdentityProvider.NAME, activity.getActivityStream().getPrettyId(), true), activity); } // Finally share if the drive supports this shareInDrive(node, localDrive, groupId); return activityId; } }); } // If not cloud file - super's behaviour return super.publishDocumentToSpace(groupId, node, comment, perm); } /** * {@inheritDoc} */ @Override public void publishDocumentToUser(String userId, Node node, String comment, String perm) { CloudDrive localDrive = findCloudDrive(node); if (localDrive != null) { applyInDrive(localDrive, new Change<Void>() { @Override public Void apply() throws RepositoryException { if (LOG.isDebugEnabled()) { LOG.debug("Sharing Cloud File " + node.getPath() + " of " + localDrive + " to " + userId + " " + perm); } CloudDriveShareDocumentService.super.publishDocumentToUser(userId, node, comment, perm); // We fix what super did to allow only read the cloud // file (instead of read, add node, set property and remove for 'Can // Write' option). cloudFileActions.shareToUser(node, userId, SHARE_PERMISSION_MODIFY.equalsIgnoreCase(perm)); // Finally share if the drive supports this shareInDrive(node, localDrive, userId); return null; } }); return; } // If not cloud file - super's behaviour super.publishDocumentToUser(userId, node, comment, perm); } /** * {@inheritDoc} */ @Override public void unpublishDocumentToUser(String userId, ExtendedNode node) { CloudDrive localDrive = findCloudDrive(node); if (localDrive != null) { applyInDrive(localDrive, new Change<Void>() { @Override public Void apply() throws RepositoryException, CloudDriveException { if (LOG.isDebugEnabled()) { LOG.debug("Unsharing Cloud File " + node.getPath() + " of " + localDrive); } // XXX original ShareDocumentService's method works not clean, it will // not remove copied or renamed link nodes, even more in case of link // rename it will fail to delete it with PathNotFoundException // internally but the exception will not be thrown out (only logged). // Thus we need make better cleanup after its logic. // In case of JCR error this will rollback the above work CloudDriveShareDocumentService.super.unpublishDocumentToUser(userId, node); node.refresh(false); cloudFileActions.unshareToUser(node, userId); // Finally unshare if the drive supports this unshareInDrive(node, localDrive, userId); return null; } }); return; } // If not cloud file - super's behaviour super.unpublishDocumentToUser(userId, node); } /** * {@inheritDoc} */ @Override public void unpublishDocumentToSpace(String groupId, ExtendedNode node) { CloudDrive localDrive = findCloudDrive(node); if (localDrive != null) { applyInDrive(localDrive, new Change<Void>() { @Override public Void apply() throws RepositoryException { if (LOG.isDebugEnabled()) { LOG.debug("Unsharing Cloud File " + node.getPath() + " of " + localDrive); } // XXX original ShareDocumentService's method works not clean, it will // not remove copied or renamed link nodes, even more in case of link // rename it will fail to delete it with PathNotFoundException // internally but the exception will not be thrown out (only logged). // Thus we need make better cleanup after its logic. CloudDriveShareDocumentService.super.unpublishDocumentToSpace(groupId, node); // in case of JCR error this will rollback the above work node.refresh(false); cloudFileActions.unshareToSpace(node, groupId); // Finally unshare if the drive supports this unshareInDrive(node, localDrive, groupId); return null; } }); return; } // If not cloud file - super's behaviour super.unpublishDocumentToSpace(groupId, node); } // ****************** Internals ****************** protected CloudDrive findCloudDrive(Node node) { try { if (node.isNodeType(JCRLocalCloudDrive.ECD_CLOUDFILE)) { CloudDrive localDrive = cloudDrives.findDrive(node); if (localDrive != null) { return localDrive; } else { LOG.warn("Cloud File node not be found in any of registered drives: " + node.getPath()); } } } catch (RepositoryException e) { LOG.warn("Error reading node of shared document " + node, e); } return null; } protected <R> R applyInDrive(CloudDrive cloudDrive, Change<R> change) { try { // Apply local file node changes in JCR via Change object to // avoid firing Cloud Drive synchronization CloudDriveStorage cdStorage = (CloudDriveStorage) cloudDrive; return cdStorage.localChange(change); } catch (RepositoryException e) { LOG.error("Error applying cloud drive changes in " + cloudDrive, e); } catch (NotCloudDriveException e) { LOG.warn("Cannot apply changes to not connected cloud drive: " + cloudDrive, e); } catch (DriveRemovedException e) { LOG.warn("Cannot apply changes to removed cloud drive: " + cloudDrive, e); } catch (CloudDriveException e) { LOG.error("Error applying cloud drive changes: " + cloudDrive, e); } return null; } /** * Share cloud file (by its node) in Cloud Drive. * * @param node the cloud file node * @param localDrive the local drive * @param identity the identity */ protected void shareInDrive(Node node, CloudDrive localDrive, String identity) { // share file in cloud provider (if applicable) CloudDriveSecurity srcSecurity = (CloudDriveSecurity) localDrive; if (srcSecurity.isSharingSupported()) { try { srcSecurity.shareFile(node, identity); } catch (RepositoryException e) { LOG.error("Error sharing cloud file: " + node, e); } catch (CloudDriveException e) { LOG.error("Error sharing cloud file: " + node, e); } } } /** * Unshare cloud file (by its node) in Cloud Drive. * * @param node the cloud file node * @param localDrive the local drive * @param identity the identity */ protected void unshareInDrive(Node node, CloudDrive localDrive, String identity) { // share file in cloud provider (if applicable) CloudDriveSecurity srcSecurity = (CloudDriveSecurity) localDrive; if (srcSecurity.isSharingSupported()) { try { srcSecurity.unshareFile(node, identity); } catch (RepositoryException e) { LOG.error("Error unsharing cloud file: " + node, e); } catch (CloudDriveException e) { LOG.error("Error unsharing cloud file: " + node, e); } } } }
15,685
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CMSNodeFinder.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/jcr/CMSNodeFinder.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.jcr; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; import javax.jcr.Item; 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.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.services.cms.clouddrives.jcr.NodeFinder; import org.exoplatform.services.cms.impl.Utils; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.link.impl.NodeFinderImpl; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; /** * Node finder based on original implementation from ECMS.<br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CMSNodeFinder.java 00000 Feb 26, 2013 pnedonosko $ */ public class CMSNodeFinder extends NodeFinderImpl implements NodeFinder { /** The session provider service. */ protected final SessionProviderService sessionProviderService; /** The hierarchy creator. */ protected final NodeHierarchyCreator hierarchyCreator; /** * Instantiates a new CMS node finder. * * @param repositoryService the repository service * @param linkManager the link manager * @param sessionProviderService the session provider service * @param hierarchyCreator the hierarchy creator */ public CMSNodeFinder(RepositoryService repositoryService, LinkManager linkManager, SessionProviderService sessionProviderService, NodeHierarchyCreator hierarchyCreator) { super(repositoryService, linkManager); this.sessionProviderService = sessionProviderService; this.hierarchyCreator = hierarchyCreator; } /** * {@inheritDoc} */ public String cleanName(String name) { // Align name to ECMS conventions // we keep using the dot character as separator between name and extension // for backward compatibility int extIndex = name.lastIndexOf('.'); StringBuilder jcrName = new StringBuilder(); if (extIndex >= 0 && extIndex < name.length() - 1) { jcrName.append(Text.escapeIllegalJcrChars(Utils.cleanString(name.substring(0, extIndex)))); String extName = Text.escapeIllegalJcrChars(Utils.cleanString(name.substring(extIndex + 1))); jcrName.append('.').append(extName).toString(); } else { jcrName.append(Text.escapeIllegalJcrChars(Utils.cleanString(name))); } return jcrName.toString(); } /** * {@inheritDoc} */ @Override public Item findItem(Session session, String absPath) throws PathNotFoundException, RepositoryException { return getItem(session, absPath, true); } /** * {@inheritDoc} */ @Override public Collection<Node> findLinked(Session session, String uuid) throws PathNotFoundException, RepositoryException { Set<Node> res = new LinkedHashSet<Node>(); try { QueryManager qm = session.getWorkspace().getQueryManager(); Query q = qm.createQuery("SELECT * FROM exo:symlink WHERE exo:uuid='" + uuid + "'", Query.SQL); QueryResult qr = q.execute(); for (NodeIterator niter = qr.getNodes(); niter.hasNext();) { res.add(niter.nextNode()); } } catch (ItemNotFoundException e) { // nothing } return res; } /** * {@inheritDoc} */ @Override public Node getUserNode(String userName) throws Exception { SessionProvider sessionProvider = sessionProviderService.getSessionProvider(null); Node userNode = hierarchyCreator.getUserNode(sessionProvider, userName); return userNode; } }
4,885
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
WatchCloudDocumentServiceImpl.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/watch/WatchCloudDocumentServiceImpl.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.watch; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Session; import javax.jcr.Value; import javax.jcr.nodetype.NodeType; import javax.jcr.observation.Event; import javax.jcr.observation.EventListener; import javax.jcr.observation.ObservationManager; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.picocontainer.Startable; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.cms.clouddrives.jcr.JCRLocalCloudDrive; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.cms.watch.WatchDocumentService; import org.exoplatform.services.cms.watch.impl.MessageConfig; import org.exoplatform.services.cms.watch.impl.MessageConfigPlugin; import org.exoplatform.services.cms.watch.impl.WatchDocumentServiceImpl; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.config.RepositoryEntry; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; /** * This is a COPY of ECMS's {@link WatchDocumentServiceImpl} with proposed fix * of https://jira.exoplatform.org/browse/ECMS-5973. */ public class WatchCloudDocumentServiceImpl implements WatchDocumentService, Startable { /** The Constant EXO_WATCHABLE_MIXIN. */ final public static String EXO_WATCHABLE_MIXIN = "exo:watchable"; /** The Constant EMAIL_WATCHERS_PROP. */ final public static String EMAIL_WATCHERS_PROP = "exo:emailWatcher"; /** The Constant RSS_WATCHERS_PROP. */ final public static String RSS_WATCHERS_PROP = "exo:rssWatcher"; /** The Constant WATCHABLE_MIXIN_QUERY. */ final private static String WATCHABLE_MIXIN_QUERY = "//element(*,exo:watchable)"; /** The Constant CLOUDDRIVE_WATCH_LINK. */ final public static String CLOUDDRIVE_WATCH_LINK = "ecd:watchLink"; /** The repo service. */ private RepositoryService repoService_; /** The message config. */ private MessageConfig messageConfig_; /** The template service. */ private TemplateService templateService_; /** The Constant LOG. */ private static final Log LOG = ExoLogger.getLogger(WatchCloudDocumentServiceImpl.class.getName()); /** * Constructor Method. * * @param params the params * @param repoService the repo service * @param templateService the template service */ public WatchCloudDocumentServiceImpl(InitParams params, RepositoryService repoService, TemplateService templateService) { repoService_ = repoService; templateService_ = templateService; } /** * {@inheritDoc} */ public void initializeMessageConfig(MessageConfigPlugin msgConfigPlugin) { messageConfig_ = msgConfigPlugin.getMessageConfig(); } /** * {@inheritDoc} */ public int getNotificationType(Node documentNode, String userName) throws Exception { NodeType[] mixinTypes = documentNode.getMixinNodeTypes(); NodeType watchableMixin = null; if (mixinTypes.length > 0) { for (NodeType nodeType : mixinTypes) { if (nodeType.getName().equalsIgnoreCase(EXO_WATCHABLE_MIXIN)) { watchableMixin = nodeType; break; } } } if (watchableMixin == null) return -1; boolean notifyByEmail = checkNotifyTypeOfWatcher(documentNode, userName, EMAIL_WATCHERS_PROP); boolean notifyByRss = checkNotifyTypeOfWatcher(documentNode, userName, RSS_WATCHERS_PROP); if (notifyByEmail && notifyByRss) return FULL_NOTIFICATION; if (notifyByEmail) return NOTIFICATION_BY_EMAIL; if (notifyByRss) return NOTIFICATION_BY_RSS; return -1; } /** * {@inheritDoc} */ public void watchDocument(Node documentNode, String userName, int notifyType) throws Exception { Value newWatcher = documentNode.getSession().getValueFactory().createValue(userName); EmailNotifyCloudDocumentListener listener = null; Node specificNode = documentNode.isNodeType(NodetypeConstant.NT_FILE) ? documentNode.getNode("jcr:content") : documentNode; if (!documentNode.isNodeType(EXO_WATCHABLE_MIXIN)) { documentNode.addMixin(EXO_WATCHABLE_MIXIN); if (notifyType == NOTIFICATION_BY_EMAIL) { documentNode.setProperty(EMAIL_WATCHERS_PROP, new Value[] { newWatcher }); listener = new EmailNotifyCloudDocumentListener(documentNode); observeNode(specificNode, listener); } } else { List<Value> watcherList = new ArrayList<Value>(); if (notifyType == NOTIFICATION_BY_EMAIL) { listener = new EmailNotifyCloudDocumentListener(documentNode); if (documentNode.hasProperty(EMAIL_WATCHERS_PROP)) { for (Value watcher : documentNode.getProperty(EMAIL_WATCHERS_PROP).getValues()) { watcherList.add(watcher); } watcherList.add(newWatcher); } documentNode.setProperty(EMAIL_WATCHERS_PROP, watcherList.toArray(new Value[watcherList.size()])); } } if (listener != null && documentNode.isNodeType(JCRLocalCloudDrive.ECD_CLOUDFILE) && !documentNode.hasProperty(CLOUDDRIVE_WATCH_LINK)) { // init Cloud Drive document with document URI in portal and store this // URI documentNode.setProperty(CLOUDDRIVE_WATCH_LINK, listener.getViewableLink(documentNode)); } documentNode.save(); } /** * {@inheritDoc} */ public void unwatchDocument(Node documentNode, String userName, int notificationType) throws Exception { if (!documentNode.isNodeType(EXO_WATCHABLE_MIXIN)) return; if (notificationType == NOTIFICATION_BY_EMAIL) { Value[] watchers = documentNode.getProperty(EMAIL_WATCHERS_PROP).getValues(); List<Value> watcherList = new ArrayList<Value>(); for (Value watcher : watchers) { if (!watcher.getString().equals(userName)) { watcherList.add(watcher); } } documentNode.setProperty(EMAIL_WATCHERS_PROP, watcherList.toArray(new Value[watcherList.size()])); } if (documentNode.isNodeType(JCRLocalCloudDrive.ECD_CLOUDFILE)) { documentNode.setProperty(CLOUDDRIVE_WATCH_LINK, (String) null); } documentNode.save(); } /** * This method will observes the specification node by giving the following * param : listener, node Its add an event listener to this node to observes * anything that changes to this. * * @param node Specify the node to observe * @param listener The object of EventListener * @throws Exception the exception * @see EventListener * @see Node */ private void observeNode(Node node, EventListener listener) throws Exception { String workspace = node.getSession().getWorkspace().getName(); Session systemSession = repoService_.getCurrentRepository().getSystemSession(workspace); List<String> list = getDocumentNodeTypes(node); String[] observedNodeTypeNames = list.toArray(new String[list.size()]); ObservationManager observationManager = systemSession.getWorkspace().getObservationManager(); observationManager.addEventListener(listener, Event.PROPERTY_CHANGED, node.getPath(), true, null, observedNodeTypeNames, false); systemSession.logout(); } /** * This method will check notify type of watcher, userName is equal value of * property with notification type. * * @param documentNode specify a node to watch * @param userName userName to watch a document * @param notificationType the notification type * @return boolean * @throws Exception the exception */ private boolean checkNotifyTypeOfWatcher(Node documentNode, String userName, String notificationType) throws Exception { if (documentNode.hasProperty(notificationType)) { Value[] watchers = documentNode.getProperty(notificationType).getValues(); for (Value value : watchers) { if (userName.equalsIgnoreCase(value.getString())) return true; } } return false; } /** * This method will get all node types of node. * * @param node the node * @return the document node types * @throws Exception the exception */ private List<String> getDocumentNodeTypes(Node node) throws Exception { List<String> nodeTypeNameList = new ArrayList<String>(); NodeType primaryType = node.getPrimaryNodeType(); if (templateService_.isManagedNodeType(primaryType.getName())) { nodeTypeNameList.add(primaryType.getName()); } for (NodeType nodeType : node.getMixinNodeTypes()) { if (templateService_.isManagedNodeType(nodeType.getName())) { nodeTypeNameList.add(nodeType.getName()); } } return nodeTypeNameList; } /** * This method will re-observer all nodes that have been ever observed with * all repositories. * * @throws Exception the exception */ private void reInitObserver() throws Exception { RepositoryEntry repo = repoService_.getCurrentRepository().getConfiguration(); ManageableRepository repository = repoService_.getCurrentRepository(); String[] workspaceNames = repository.getWorkspaceNames(); for (String workspace : workspaceNames) { Session session = repository.getSystemSession(workspace); QueryManager queryManager = null; try { queryManager = session.getWorkspace().getQueryManager(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } if (queryManager == null) { session.logout(); continue; } try { Query query = queryManager.createQuery(WATCHABLE_MIXIN_QUERY, Query.XPATH); QueryResult queryResult = query.execute(); for (NodeIterator iter = queryResult.getNodes(); iter.hasNext();) { Node observedNode = iter.nextNode(); EmailNotifyCloudDocumentListener emailNotifyListener = new EmailNotifyCloudDocumentListener(observedNode); ObservationManager manager = session.getWorkspace().getObservationManager(); List<String> list = getDocumentNodeTypes(observedNode); String[] observedNodeTypeNames = list.toArray(new String[list.size()]); manager.addEventListener(emailNotifyListener, Event.PROPERTY_CHANGED, observedNode.getPath(), true, null, observedNodeTypeNames, false); } session.logout(); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn("==>>> Cannot init observer for node: " + e.getLocalizedMessage() + " in '" + repo.getName() + "' repository"); } if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } } } /** * This method will get message configuration when a node is observing and * there is some changes with it's properties. * * @return MessageCongig */ protected MessageConfig getMessageConfig() { return messageConfig_; } /** * using for re-observer. */ public void start() { try { reInitObserver(); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn("==>>> Exeption when startd WatchDocumentSerice!!!!"); } } } /** * {@inheritDoc} */ public void stop() { } }
12,760
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
EmailNotifyCloudDocumentListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/watch/EmailNotifyCloudDocumentListener.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.watch; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.observation.EventIterator; import javax.jcr.observation.EventListener; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.commons.utils.MailUtils; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.watch.WatchDocumentService; import org.exoplatform.services.cms.watch.impl.EmailNotifyListener; import org.exoplatform.services.cms.watch.impl.MessageConfig; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.mail.MailService; import org.exoplatform.services.mail.Message; import org.exoplatform.services.organization.OrganizationService; import org.exoplatform.services.organization.Query; import org.exoplatform.services.organization.User; 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.NodetypeConstant; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.ext.component.activity.listener.Utils; import groovy.text.GStringTemplateEngine; import groovy.text.TemplateEngine; /** * This is a COPY of ECMS {@link EmailNotifyListener} with proposed fix of * https://jira.exoplatform.org/browse/ECMS-5973.<br> * Created by The eXo Platform SAS Author : Xuan Hoa Pham * hoapham@exoplatform.com phamvuxuanhoa@gmail.com Dec 6, 2006 */ public class EmailNotifyCloudDocumentListener implements EventListener { /** The observed node. */ private NodeLocation observedNode_; /** The Constant EMAIL_WATCHERS_PROP. */ final public static String EMAIL_WATCHERS_PROP = "exo:emailWatcher"; /** The Constant LOG. */ private static final Log LOG = ExoLogger.getLogger(EmailNotifyCloudDocumentListener.class.getName()); /** * Instantiates a new email notify cloud document listener. * * @param oNode the o node */ public EmailNotifyCloudDocumentListener(Node oNode) { observedNode_ = NodeLocation.getNodeLocationByNode(oNode); } /** * This method is used for listening to all changes of property of a node, * when there is a change, message is sent to list of email. * * @param arg0 the arg 0 */ public void onEvent(EventIterator arg0) { MailService mailService = WCMCoreUtils.getService(MailService.class); WatchCloudDocumentServiceImpl watchService = (WatchCloudDocumentServiceImpl) WCMCoreUtils.getService(WatchDocumentService.class); MessageConfig messageConfig = watchService.getMessageConfig(); String sender = MailUtils.getSenderName() + "<" + MailUtils.getSenderEmail() + ">"; messageConfig.setSender(sender); try { Node node = NodeLocation.getNodeByLocation(observedNode_); NodeLocation nodeLocation = node.isNodeType(NodetypeConstant.NT_RESOURCE) ? NodeLocation.getNodeLocationByNode(node.getParent()) : observedNode_; List<String> emailList = getEmailList(NodeLocation.getNodeByLocation(nodeLocation)); for (String receiver : emailList) { notifyUser(receiver, messageConfig, mailService); } } catch (RepositoryException e) { if (LOG.isErrorEnabled()) { LOG.error("Unable to get node location", e); } } } /** * Create message when there is any changes of property of a node. * * @param receiver the receiver * @param messageConfig the message config * @return the message * @throws Exception the exception */ private Message createMessage(String receiver, MessageConfig messageConfig) throws Exception { Message message = new Message(); message.setFrom(messageConfig.getSender()); message.setTo(receiver); message.setSubject(messageConfig.getSubject()); TemplateEngine engine = new GStringTemplateEngine(); Map<String, String> binding = new HashMap<String, String>(); Query query = new Query(); query.setEmail(receiver); binding.put("user_name", WCMCoreUtils.getService(OrganizationService.class) .getUserHandler() .findUsersByQuery(query) .load(0, 1)[0].getFullName()); Node node = NodeLocation.getNodeByLocation(observedNode_); binding.put("doc_title", org.exoplatform.services.cms.impl.Utils.getTitle(node)); binding.put("doc_name", node.getName()); binding.put("doc_url", getViewableLink(node)); // XXX instead of getViewableLink() message.setBody(engine.createTemplate(messageConfig.getContent()).make(binding).toString()); message.setMimeType(messageConfig.getMimeType()); return message; } /** * Used in * {@link WatchCloudDocumentServiceImpl#watchDocument(Node, String, int)}. * * @return the viewable link * @throws Exception the exception */ String getViewableLink(Node node) throws Exception { // Exemple Link : http://localhost:8080/portal/private/rest/documents/view/collaboration/f3cf201e7f0001016c28b6ac54feb98e return CommonsUtils.getCurrentDomain() + Utils.getContentLink(node); } /** * Gets the memberships. * * @return the memberships */ public List<String> getMemberships() { String userId = Util.getPortalRequestContext().getRemoteUser(); List<String> userMemberships = new ArrayList<String>(); userMemberships.add(userId); // here we must retrieve memberships of the user using the // IdentityRegistry Service instead of Organization Service to // allow JAAS based authorization Collection<MembershipEntry> memberships = getUserMembershipsFromIdentityRegistry(userId); if (memberships != null) { for (MembershipEntry membership : memberships) { String role = membership.getMembershipType() + ":" + membership.getGroup(); userMemberships.add(role); } } return userMemberships; } /** * Gets the user memberships from identity registry. * * @param authenticatedUser the authenticated user * @return the user memberships from identity registry */ private Collection<MembershipEntry> getUserMembershipsFromIdentityRegistry(String authenticatedUser) { IdentityRegistry identityRegistry = WCMCoreUtils.getService(IdentityRegistry.class); Identity currentUserIdentity = identityRegistry.getIdentity(authenticatedUser); return currentUserIdentity.getMemberships(); } /** * This Method will get email of watchers when they watch a document. * * @param observedNode the observed node * @return the email list */ private List<String> getEmailList(Node observedNode) { List<String> emailList = new ArrayList<String>(); OrganizationService orgService = WCMCoreUtils.getService(OrganizationService.class); try { if (observedNode.hasProperty(EMAIL_WATCHERS_PROP)) { Value[] watcherNames = observedNode.getProperty(EMAIL_WATCHERS_PROP).getValues(); for (Value value : watcherNames) { String userName = value.getString(); User user = orgService.getUserHandler().findUserByName(userName); if (user != null) { emailList.add(user.getEmail()); } } } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } return emailList; } private void notifyUser(String receiver, MessageConfig messageConfig, MailService mailService) { try { Message message = createMessage(receiver, messageConfig); mailService.sendMessage(message); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } } }
8,914
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ResourceService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/rest/ResourceService.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.rest; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import javax.annotation.security.RolesAllowed; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.exoplatform.services.cms.clouddrives.CloudProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.resources.ResourceBundleService; import org.exoplatform.services.rest.resource.ResourceContainer; import jakarta.servlet.http.HttpServletRequest; /** * REST service providing access to UI resources. Created by The eXo Platform * SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: ResourceService.java 00000 Apr 20, 2016 pnedonosko $ */ @Path("/clouddrive/resource") @Produces(MediaType.APPLICATION_JSON) public class ResourceService implements ResourceContainer { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(ResourceService.class); /** * The Class LocaleBundle. */ public static class LocaleBundle { /** The data. */ protected final Map<String, String> data; /** The language. */ protected final String language; /** The country. */ protected final String country; /** * Instantiates a new locale bundle. * * @param language the language * @param country the country * @param data the data */ protected LocaleBundle(String language, String country, Map<String, String> data) { super(); this.language = language; this.country = country; this.data = data; } /** * Gets the data. * * @return the data */ public Map<String, String> getData() { return data; } /** * Gets the language. * * @return the language */ public String getLanguage() { return language; } /** * Gets the country. * * @return the country */ public String getCountry() { return country; } } /** The resource service. */ protected final ResourceBundleService resourceService; /** * Constructor. * * @param resourceService the resource service */ public ResourceService(ResourceBundleService resourceService) { this.resourceService = resourceService; } /** * Return provider by its id. * * @param uriInfo the uri info * @param request the request * @return response with asked {@link CloudProvider} json */ @GET @RolesAllowed("users") @Path("/bundle") public Response getBundle(@Context UriInfo uriInfo, @Context HttpServletRequest request) { Locale locale = request.getLocale(); try { // TODO should we use user locale (for current user)? ResourceBundle bundle = resourceService.getResourceBundle("locale.clouddrive.CloudDrive", locale); if (bundle != null) { Map<String, String> bundleMap = new HashMap<String, String>(); for (Enumeration<String> keys = bundle.getKeys(); keys.hasMoreElements();) { String key = keys.nextElement(); String value = bundle.getString(key); bundleMap.put(key, value); } return Response.ok().entity(new LocaleBundle(locale.getLanguage(), locale.getCountry(), bundleMap)).build(); } else { return Response.status(Status.NOT_FOUND).entity("Bundle not found for " + locale.toLanguageTag()).build(); } } catch (Throwable e) { LOG.error("Error returning locale bundle for " + locale + ": " + e.getMessage()); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error getting bundle for " + locale.toLanguageTag()).build(); } } }
4,872
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
SharedCloudFile.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/rest/SharedCloudFile.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.services.cms.clouddrives.webui.rest; import java.util.Calendar; import javax.jcr.Node; import org.exoplatform.ecm.connector.clouddrives.LinkedCloudFile; import org.exoplatform.services.cms.clouddrives.CloudFile; /** * Wraps fields from {@link CloudFile} shared with other users and offers its * path (as a path of that file {@link Node} symlink) and a link for opening * this file in eXo Platform.<br> * NOTE: we cannot wrap instance of another another {@link CloudFile} as it * leads to StackOverflowError in WS JsonGeneratorImpl.<br> * Created by The eXo Platform SAS.<br> * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: LinkedCloudFile.java 00000 Jan 24, 2013 pnedonosko $ */ public class SharedCloudFile extends LinkedCloudFile { /** The is symlink. */ private final boolean isSymlink; /** The open link. */ private final String openLink; // FYI transient fields will not appear in serialized forms like JSON object // on client side /** The created date. */ final transient Calendar createdDate = null; /** The modified date. */ final transient Calendar modifiedDate = null; /** * Instantiates a new linked cloud file. * * @param file the file * @param path the path * @param openLink the open link */ public SharedCloudFile(CloudFile file, String path, String openLink) { super(file, path); this.isSymlink = !file.getPath().equals(path); this.openLink = openLink; } /** * @return the openLink */ public String getOpenLink() { return openLink; } /** * Checks if is symlink. * * @return true, if is symlink */ public boolean isSymlink() { return isSymlink; } }
2,580
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FileService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/rest/FileService.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.services.cms.clouddrives.webui.rest; import javax.annotation.security.RolesAllowed; import javax.jcr.Item; import javax.jcr.LoginException; import javax.jcr.NoSuchWorkspaceException; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.exoplatform.ecm.connector.clouddrives.AcceptedCloudFile; import org.exoplatform.ecm.connector.clouddrives.ErrorEntiry; import org.exoplatform.ecm.connector.clouddrives.LinkedCloudFile; 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.CloudFile; import org.exoplatform.services.cms.clouddrives.NotCloudFileException; import org.exoplatform.services.cms.clouddrives.NotYetCloudFileException; import org.exoplatform.services.cms.clouddrives.jcr.JCRLocalCloudFile; import org.exoplatform.services.cms.clouddrives.webui.action.CloudFileActionService; import org.exoplatform.services.cms.documents.DocumentService; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.access.AccessControlEntry; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.Identity; import org.exoplatform.services.security.MembershipEntry; import jakarta.servlet.http.HttpServletRequest; /** * REST service providing information about cloud files in Documents (ECMS) app.<br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: DriveService.java 00000 Jul 11, 2018 pnedonosko $ */ @Path("/clouddrive/document/") @Produces(MediaType.APPLICATION_JSON) public class FileService implements ResourceContainer { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(FileService.class); /** The cloud drives. */ protected final CloudDriveService cloudDrives; /** The jcr service. */ protected final RepositoryService jcrService; /** The session providers. */ protected final SessionProviderService sessionProviders; /** The document service. */ protected final DocumentService documentService; /** The link manager. */ protected final CloudFileActionService cloudActions; /** * REST cloudDrives uses {@link CloudDriveService} for actual job. * * @param cloudDrives {@link CloudDriveService} * @param jcrService {@link RepositoryService} * @param sessionProviders {@link SessionProviderService} * @param documentService the document service * @param cloudActions the cloud actions */ public FileService(CloudDriveService cloudDrives, RepositoryService jcrService, SessionProviderService sessionProviders, DocumentService documentService, CloudFileActionService cloudActions) { this.cloudDrives = cloudDrives; this.jcrService = jcrService; this.sessionProviders = sessionProviders; this.documentService = documentService; this.cloudActions = cloudActions; } /** * Return file information. Returned file may be not yet created in cloud (accepted for creation), then this service response * will be with status ACCEPTED, otherwise it's OK response. * * @param uriInfo the uri info * @param workspace {@link String} Drive Node workspace * @param path {@link String} File Node path * @return {@link Response} REST response */ @GET @Path("/file/") @RolesAllowed("users") public Response getFile(@Context UriInfo uriInfo, @QueryParam("workspace") String workspace, @QueryParam("path") String path) { if (workspace != null) { if (path != null) { try { CloudDrive local = cloudDrives.findDrive(workspace, path); if (local != null) { try { CloudFile file = local.getFile(path); if (!file.getPath().equals(path)) { file = new LinkedCloudFile(file, path); // it's symlink } else { Identity currentIdentity = ConversationState.getCurrent().getIdentity(); if (!local.getLocalUser().equals(currentIdentity.getUserId())) { // XXX for shared file we need return also a right open link // It's a workaround for PLF-8078 ExtendedNode fileNode = fileNode(file, workspace); if (fileNode != null) { // Find is the node shared via a group or via a personal // documents to current user - generate open link // accordingly // We'll use a first one as in search context it has less // sense. String openLink = null; String filePath = null; nextAce: for (AccessControlEntry ace : fileNode.getACL().getPermissionEntries()) { MembershipEntry me = ace.getMembershipEntry(); if (me != null) { // it's group - url to group docs with the link if (currentIdentity.getGroups().contains(me.getGroup())) { DriveData groupDrive = cloudActions.getGroupDrive(me.getGroup()); if (groupDrive != null) { for (NodeIterator niter = cloudActions.getCloudFileLinks(fileNode, me.getGroup(), groupDrive.getHomePath(), false); niter.hasNext();) { Node linkNode = niter.nextNode(); filePath = linkNode.getPath(); openLink = documentService.getLinkInDocumentsApp(linkNode.getPath(), groupDrive); break nextAce; } } } } else if (ace.getIdentity().equals(currentIdentity.getUserId())) { // user, url to the symlink in current user docs Node profileNode = cloudActions.getUserProfileNode(currentIdentity.getUserId()); String userPath = profileNode.getPath(); for (NodeIterator niter = cloudActions.getCloudFileLinks(fileNode, currentIdentity.getUserId(), userPath, false); niter.hasNext();) { Node linkNode = niter.nextNode(); filePath = linkNode.getPath(); DriveData linkDrive = documentService.getDriveOfNode(filePath); if (linkDrive != null) { openLink = documentService.getLinkInDocumentsApp(linkNode.getPath(), linkDrive); break nextAce; } else { LOG.warn("Cannot find Documents drive for shared Cloud File: " + filePath); } } } } if (openLink != null) { file = new SharedCloudFile(file, filePath, openLink); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(ErrorEntiry.message("File node cannot be found.")) .build(); } } } return Response.ok().entity(file).build(); } catch (NotYetCloudFileException e) { return Response.status(Status.ACCEPTED).entity(new AcceptedCloudFile(path)).build(); } catch (NotCloudFileException e) { return Response.status(Status.NOT_FOUND).entity(ErrorEntiry.notCloudFile(e.getMessage(), workspace, path)).build(); } } if (LOG.isDebugEnabled()) { LOG.debug("Item " + workspace + ":" + path + " not a cloud file or drive not connected."); } return Response.status(Status.NOT_FOUND) .entity(ErrorEntiry.notCloudDrive("Not a cloud file or drive not connected", workspace, path)) .build(); } catch (LoginException e) { LOG.warn("Error login to read drive file " + workspace + ":" + path + ": " + e.getMessage()); return Response.status(Status.UNAUTHORIZED).entity(ErrorEntiry.message("Authentication error")).build(); } catch (CloudDriveException e) { LOG.warn("Error reading file " + workspace + ":" + path, e); return Response.status(Status.BAD_REQUEST).entity(ErrorEntiry.message("Error reading file. " + e.getMessage())).build(); } catch (RepositoryException e) { LOG.error("Error reading file " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(ErrorEntiry.message("Error reading file: storage error.")) .build(); } catch (Throwable e) { LOG.error("Error reading file " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(ErrorEntiry.message("Error reading file: runtime error.")) .build(); } } else { return Response.status(Status.BAD_REQUEST).entity(ErrorEntiry.message("Null path")).build(); } } else { return Response.status(Status.BAD_REQUEST).entity(ErrorEntiry.message("Null workspace")).build(); } } @GET @RolesAllowed("users") @Path("/drive/personal") public Response getUserDrive(@Context HttpServletRequest request, @Context UriInfo uriInfo) { Identity currentIdentity = ConversationState.getCurrent().getIdentity(); try { DriveData drive = cloudActions.getUserDrive(currentIdentity.getUserId()); return Response.ok().entity(drive).build(); } catch (Exception e) { LOG.error("Error reading user drive for " + currentIdentity, e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(ErrorEntiry.message("Error reading user drive: ")).build(); } } /** * Read cloud file node. * * @param file the file * @param workspace the workspace * @return the node * @throws PathNotFoundException the path not found exception * @throws LoginException the login exception * @throws NoSuchWorkspaceException the no such workspace exception * @throws RepositoryException the repository exception */ protected ExtendedNode fileNode(CloudFile file, String workspace) throws PathNotFoundException, LoginException, NoSuchWorkspaceException, RepositoryException { ExtendedNode node; if (JCRLocalCloudFile.class.isAssignableFrom(file.getClass())) { node = ExtendedNode.class.cast(JCRLocalCloudFile.class.cast(file).getNode()); } else { node = null; } if (node == null) { SessionProvider sp = sessionProviders.getSessionProvider(null); if (sp != null) { Item item = sp.getSession(workspace, jcrService.getCurrentRepository()).getItem(file.getPath()); if (ExtendedNode.class.isAssignableFrom(item.getClass())) { node = ExtendedNode.class.cast(item); } else { LOG.warn("Cannot cast cloud file node from item: " + item); } } else { LOG.warn("Cannot get session provider to read cloud file node: " + file.getPath()); } } return node; } }
13,887
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDriveFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/filters/CloudDriveFilter.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.filters; import java.util.List; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.exoplatform.ecm.webui.filters.AbstractCloudDriveNodeFilter; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.clouddrives.DriveRemovedException; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Accept only ecd:cloudDrive nodes.<br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudDriveFiler.java 00000 Nov 5, 2012 pnedonosko $ */ public class CloudDriveFilter extends AbstractCloudDriveNodeFilter { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(CloudDriveFilter.class); /** * Instantiates a new cloud drive filter. */ public CloudDriveFilter() { super(); } /** * Instantiates a new cloud drive filter. * * @param providers the providers */ public CloudDriveFilter(List<String> providers) { super(providers); } /** * {@inheritDoc} */ @Override protected boolean accept(Node node) throws RepositoryException { CloudDriveService driveService = WCMCoreUtils.getService(CloudDriveService.class); CloudDrive drive = driveService.findDrive(node); try { // accept only exactly the drive node return drive != null && acceptProvider(drive.getUser().getProvider()) && drive.getPath().equals(node.getPath()); } catch (DriveRemovedException e) { // doesn't accept removed if (LOG.isDebugEnabled()) { LOG.debug(">> CloudDriveFilter.accept(" + node.getPath() + ") drive removed " + drive + ": " + e.getMessage()); } } return false; } }
2,771
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudFileSmallerFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/filters/CloudFileSmallerFilter.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.filters; import org.exoplatform.ecm.webui.filters.CloudFileFilter; import java.util.List; /** * Filter files with size smaller of configured.<br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: FileSizeSmallerOfFilter.java 00000 Jul 27, 2015 pnedonosko $ */ public class CloudFileSmallerFilter extends CloudFileFilter { /** * Instantiates a new cloud file smaller filter. */ public CloudFileSmallerFilter() { super(); } /** * Instantiates a new cloud file smaller filter. * * @param providers the providers * @param maxSize the max size */ public CloudFileSmallerFilter(List<String> providers, long maxSize) { super(providers, 0, maxSize); } /** * Instantiates a new cloud file smaller filter. * * @param maxSize the max size */ public CloudFileSmallerFilter(long maxSize) { super(0, maxSize); } }
1,836
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FileTypeFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/filters/FileTypeFilter.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.filters; import java.util.Map; import java.util.Set; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilterType; /** * Filter files by MIME type including wildcard types. <br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: FileTypeFilter.java 00000 Nov 24, 2014 pnedonosko $ */ public class FileTypeFilter implements UIExtensionFilter { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(FileTypeFilter.class); /** The mime types. */ protected Set<String> mimeTypes; /** * {@inheritDoc} */ public boolean accept(Map<String, Object> context) throws Exception { if (context == null) { return true; } if (mimeTypes == null || mimeTypes.isEmpty()) { return true; } // try quick check first String type = context.get("mimeType").toString(); if (mimeTypes.contains(type)) { return true; } // try wildcard (type starts with accepted) for (String accepted : mimeTypes) { if (type.startsWith(accepted)) { return true; } } return false; } /** * {@inheritDoc} */ public UIExtensionFilterType getType() { return UIExtensionFilterType.MANDATORY; } /** * {@inheritDoc} */ public void onDeny(Map<String, Object> context) throws Exception { } }
2,427
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PersonalDocumentsFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/filters/PersonalDocumentsFilter.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.filters; import java.util.Map; import javax.jcr.Item; import javax.jcr.Node; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.ecm.webui.clouddrives.CloudDriveContext; import org.exoplatform.services.cms.impl.Utils; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilterType; /** * Filter for personal drives. */ public class PersonalDocumentsFilter implements UIExtensionFilter { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(PersonalDocumentsFilter.class); /** * {@inheritDoc} */ public boolean accept(Map<String, Object> context) throws Exception { if (context == null) { return true; } Node contextNode = (Node) context.get(Node.class.getName()); if (contextNode == null) { return false; } String contextPath = contextNode.getPath(); // only show in Personal Doc's root! String userId = Util.getPortalRequestContext().getRemoteUser(); UIJCRExplorer uiExplorer = (UIJCRExplorer) context.get(UIJCRExplorer.class.getName()); String personalDocsPath = Utils.getPersonalDrivePath(uiExplorer.getDriveData().getHomePath(), userId); if (contextPath.startsWith(personalDocsPath)) { boolean isRoot = contextNode.getPath().equals(personalDocsPath); // additionally we initialize all already connected drives in the context, // they can be used for drive folder icons rendering or other similar // purpose if (isRoot) { CloudDriveContext.initConnected(WebuiRequestContext.getCurrentInstance(), contextNode); } else { Item personalDocs = contextNode.getSession().getItem(personalDocsPath); if (personalDocs.isNode()) { CloudDriveContext.initConnected(WebuiRequestContext.getCurrentInstance(), (Node) personalDocs); } else { // this should not happen LOG.warn("Personal Documents not a Node: " + personalDocs.getPath()); } } return isRoot; } else { return false; } } /** * {@inheritDoc} */ public UIExtensionFilterType getType() { return UIExtensionFilterType.MANDATORY; } /** * {@inheritDoc} */ public void onDeny(Map<String, Object> context) throws Exception { } }
3,415
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
LocalNodeFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/filters/LocalNodeFilter.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.filters; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.exoplatform.ecm.webui.filters.AbstractCloudDriveNodeFilter; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.clouddrives.CloudDriveStorage; import org.exoplatform.services.cms.clouddrives.DriveRemovedException; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.webui.application.WebuiRequestContext; /** * Filter for nodes are not cloud files but existing in cloud drive folder. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: LocalNodeFilter.java 00000 May 25, 2014 pnedonosko $ */ public class LocalNodeFilter extends AbstractCloudDriveNodeFilter { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(LocalNodeFilter.class); /** * {@inheritDoc} */ @Override protected boolean accept(Node node) throws RepositoryException { CloudDriveService driveService = WCMCoreUtils.getService(CloudDriveService.class); CloudDrive drive = driveService.findDrive(node); if (drive != null) { if (acceptProvider(drive.getUser().getProvider())) { try { if (((CloudDriveStorage) drive).isLocal(node)) { WebuiRequestContext.getCurrentInstance().setAttribute(CloudDrive.class, drive); return true; } } catch (DriveRemovedException e) { // doesn't accept removed drive if (LOG.isDebugEnabled()) { LOG.debug(">> LocalNodeFilter.accept(" + node.getPath() + ") drive removed " + drive + ": " + e.getMessage()); } } } } return false; } }
2,750
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
NotCloudDriveOrFileFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/filters/NotCloudDriveOrFileFilter.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.filters; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.exoplatform.ecm.webui.filters.AbstractCloudDriveNodeFilter; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.clouddrives.DriveRemovedException; import org.exoplatform.services.cms.clouddrives.NotCloudDriveException; import org.exoplatform.services.cms.clouddrives.NotCloudFileException; import org.exoplatform.services.cms.clouddrives.NotYetCloudFileException; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Filter for cloud files. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: NotCloudDriveOrFileFilter.java 00000 Jul 6, 2015 pnedonosko $ */ public class NotCloudDriveOrFileFilter extends AbstractCloudDriveNodeFilter { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(NotCloudDriveOrFileFilter.class); /** * {@inheritDoc} */ @Override protected boolean accept(Node node) throws RepositoryException { if (node != null) { CloudDriveService driveService = WCMCoreUtils.getService(CloudDriveService.class); CloudDrive drive = driveService.findDrive(node); if (drive != null) { try { if (acceptProvider(drive.getUser().getProvider())) { if (drive.getPath().equals(node.getPath())) { return false; } else { // call it for exceptions it can throw away drive.getFile(node.getPath()); return false; } } } catch (DriveRemovedException e) { // don't accept it! if (LOG.isDebugEnabled()) { LOG.debug(">> NotCloudDriveOrFileFilter.accept(" + node.getPath() + ") drive removed " + drive + ": " + e.getMessage()); } return false; } catch (NotYetCloudFileException e) { // don't accept it! if (LOG.isDebugEnabled()) { LOG.debug(">> NotCloudDriveOrFileFilter.accept(" + node.getPath() + ") not yet cloud file: " + e.getMessage()); } return false; } catch (NotCloudFileException e) { // accept it if (LOG.isDebugEnabled()) { LOG.debug(">> NotCloudDriveOrFileFilter.accept(" + node.getPath() + ") not cloud file: " + e.getMessage()); } } catch (NotCloudDriveException e) { // accept it if (LOG.isDebugEnabled()) { LOG.debug(">> NotCloudDriveOrFileFilter.accept(" + node.getPath() + ") not in cloud drive: " + e.getMessage()); } } } } return true; } }
3,719
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
HasEditPermissionsFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/filters/HasEditPermissionsFilter.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.filters; import java.util.Map; import javax.jcr.Node; import org.exoplatform.ecm.utils.permission.PermissionUtil; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilterType; /** * Filter nodes where current user can set properties and change permissions. */ public class HasEditPermissionsFilter implements UIExtensionFilter { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(HasEditPermissionsFilter.class); /** * {@inheritDoc} */ public boolean accept(Map<String, Object> context) throws Exception { if (context == null) { return true; } Node contextNode = (Node) context.get(Node.class.getName()); if (contextNode == null) { return false; } // only accept if current have edit permissions return PermissionUtil.canSetProperty(contextNode) && PermissionUtil.canChangePermission(contextNode); } /** * {@inheritDoc} */ public UIExtensionFilterType getType() { return UIExtensionFilterType.MANDATORY; } /** * {@inheritDoc} */ public void onDeny(Map<String, Object> context) throws Exception { } }
2,154
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
SyncingCloudFileFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/filters/SyncingCloudFileFilter.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.filters; import java.util.List; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.exoplatform.ecm.webui.filters.AbstractCloudDriveNodeFilter; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.clouddrives.CloudFile; import org.exoplatform.services.cms.clouddrives.DriveRemovedException; import org.exoplatform.services.cms.clouddrives.NotCloudDriveException; import org.exoplatform.services.cms.clouddrives.NotCloudFileException; import org.exoplatform.services.cms.clouddrives.NotYetCloudFileException; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.webui.application.WebuiRequestContext; /** * Filter for cloud files currently synchronizing. */ public class SyncingCloudFileFilter extends AbstractCloudDriveNodeFilter { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(SyncingCloudFileFilter.class); /** * Instantiates a new syncing cloud file filter. */ public SyncingCloudFileFilter() { super(); } /** * Instantiates a new syncing cloud file filter. * * @param providers the providers */ public SyncingCloudFileFilter(List<String> providers) { super(providers); } /** * {@inheritDoc} */ @Override protected boolean accept(Node node) throws RepositoryException { if (node != null) { CloudDriveService driveService = WCMCoreUtils.getService(CloudDriveService.class); CloudDrive drive = driveService.findDrive(node); if (drive != null) { if (acceptProvider(drive.getUser().getProvider())) { String path = node.getPath(); try { WebuiRequestContext rcontext = WebuiRequestContext.getCurrentInstance(); rcontext.setAttribute(CloudDrive.class, drive); try { CloudFile file = drive.getFile(path); // attribute may be used in UI rcontext.setAttribute(CloudFile.class, file); } catch (NotYetCloudFileException e) { // newly creating file we accept: UI should render it properly // according file existence return true; } // FilesState driveState = drive.getState(); // return driveState != null ? driveState.isUpdating(path) : false; // XXX accept only "not yet cloud files", thus synchronizing first // time only return false; } catch (DriveRemovedException e) { // doesn't accept } catch (NotCloudFileException e) { // doesn't accept } catch (NotCloudDriveException e) { // doesn't accept } } } } return false; } }
3,797
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudFileLargerFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/webui/filters/CloudFileLargerFilter.java
/* * Copyright (C) 2003-2016 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.services.cms.clouddrives.webui.filters; import org.exoplatform.ecm.webui.filters.CloudFileFilter; import java.util.List; /** * Filter files with size larger of configured.<br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: FileSizeSmallerOfFilter.java 00000 Jul 27, 2015 pnedonosko $ */ public class CloudFileLargerFilter extends CloudFileFilter { /** * Instantiates a new cloud file larger filter. */ public CloudFileLargerFilter() { super(); } /** * Instantiates a new cloud file larger filter. * * @param providers the providers * @param minSize the min size * @param maxSize the max size */ public CloudFileLargerFilter(List<String> providers, long minSize, long maxSize) { super(providers, minSize, maxSize); // TODO Auto-generated constructor stub } /** * Instantiates a new cloud file larger filter. * * @param providers the providers */ public CloudFileLargerFilter(List<String> providers) { super(providers); // TODO Auto-generated constructor stub } /** * Instantiates a new cloud file larger filter. * * @param minSize the min size * @param maxSize the max size */ public CloudFileLargerFilter(long minSize, long maxSize) { super(minSize, maxSize); // TODO Auto-generated constructor stub } /** * Instantiates a new cloud file larger filter. * * @param providers the providers * @param minSize the min size */ public CloudFileLargerFilter(List<String> providers, long minSize) { super(providers, minSize, Long.MAX_VALUE); } /** * Instantiates a new cloud file larger filter. * * @param minSize the min size */ public CloudFileLargerFilter(long minSize) { super(minSize, Long.MAX_VALUE); } }
2,700
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIVersionInfoTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/test/java/org/exoplatform/ecm/webui/component/explorer/versions/UIVersionInfoTest.java
package org.exoplatform.ecm.webui.component.explorer.versions; import org.exoplatform.component.test.ConfigurationUnit; import org.exoplatform.component.test.ConfiguredBy; import org.exoplatform.component.test.ContainerScope; import org.exoplatform.ecm.jcr.model.VersionNode; import org.exoplatform.ecms.test.BaseECMSTestCase; import org.exoplatform.services.cms.documents.VersionHistoryUtils; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.wcm.core.NodetypeConstant; import javax.jcr.Node; import javax.jcr.RepositoryException; import java.io.ByteArrayInputStream; import java.util.Calendar; import java.util.Comparator; import java.util.GregorianCalendar; import java.util.List; @ConfiguredBy({ @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/exo.portal.component.portal-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/exo.portal.component.identity-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/standalone/ecms-test-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/portal/mock-rest-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/ecms/configuration.xml") }) public class UIVersionInfoTest extends BaseECMSTestCase { public void testVersioning() throws Exception { // Given Node file = session.getRootNode().addNode("testXLSFile", "nt:file"); Node contentNode = file.addNode("jcr:content", "nt:resource"); contentNode.setProperty("jcr:encoding", "UTF-8"); contentNode.setProperty("jcr:data", new ByteArrayInputStream("".getBytes())); contentNode.setProperty("jcr:mimeType", "application/excel"); contentNode.setProperty("jcr:lastModified", Calendar.getInstance()); session.getRootNode().save(); addNodeVersion(file); // V1 addNodeVersion(file); // V2 // When VersionNode versionNode = new VersionNode(file, session); // Then assertEquals("3", versionNode.getName()); //root Version assertEquals("2", versionNode.getDisplayName()); List<VersionNode> versionNodes = versionNode.getChildren(); assertNotNull(versionNodes); assertEquals(2, versionNodes.size()); versionNodes.sort(Comparator.comparing(VersionNode::getName)); assertEquals("1", versionNodes.get(0).getName()); assertEquals("0", versionNodes.get(0).getDisplayName()); assertEquals("2", versionNodes.get(1).getName()); assertEquals("1", versionNodes.get(1).getDisplayName()); } public void testRemoveVersionNode() throws Exception { // Given Node file = session.getRootNode().addNode("testXLSFile", "nt:file"); Node contentNode = file.addNode("jcr:content", "nt:resource"); contentNode.setProperty("jcr:encoding", "UTF-8"); contentNode.setProperty("jcr:data", new ByteArrayInputStream("".getBytes())); contentNode.setProperty("jcr:mimeType", "application/excel"); contentNode.setProperty("jcr:lastModified", Calendar.getInstance()); session.getRootNode().save(); addNodeVersion(file); // V1 addNodeVersion(file); // V2 // When VersionHistoryUtils.removeVersion(file,"1"); // Then VersionNode versionNode = new VersionNode(file, session); assertEquals("3", versionNode.getName()); assertEquals("2", versionNode.getDisplayName()); List<VersionNode> versionNodes = versionNode.getChildren(); assertEquals(1, versionNodes.size()); versionNodes.sort(Comparator.comparing(VersionNode::getName)); assertEquals("2", versionNodes.get(0).getName()); assertEquals("1", versionNodes.get(0).getDisplayName()); } public void testRemoveAndCreateVersionNode() throws Exception{ // Given Node file = session.getRootNode().addNode("testXLSFile", "nt:file"); Node contentNode = file.addNode("jcr:content", "nt:resource"); contentNode.setProperty("jcr:encoding", "UTF-8"); contentNode.setProperty("jcr:data", new ByteArrayInputStream("".getBytes())); contentNode.setProperty("jcr:mimeType", "application/excel"); contentNode.setProperty("jcr:lastModified", Calendar.getInstance()); session.getRootNode().save(); addNodeVersion(file); // V1 addNodeVersion(file); // V2 // When VersionHistoryUtils.removeVersion(file,"2"); VersionHistoryUtils.createVersion(file); // Then VersionNode versionNode = new VersionNode(file, session); assertEquals("3", versionNode.getName()); assertEquals("3", versionNode.getDisplayName()); List<VersionNode> versionNodes = versionNode.getChildren(); assertEquals(2, versionNodes.size()); versionNodes.sort(Comparator.comparing(VersionNode::getName)); assertEquals("1", versionNodes.get(0).getName()); assertEquals("0", versionNodes.get(0).getDisplayName()); assertEquals("2", versionNodes.get(1).getName()); assertEquals("2", versionNodes.get(1).getDisplayName()); } private void addNodeVersion(Node node) throws RepositoryException { if(node.canAddMixin(NodetypeConstant.MIX_VERSIONABLE)){ node.addMixin(NodetypeConstant.MIX_VERSIONABLE); node.save(); } ConversationState conversationState = ConversationState.getCurrent(); String userName = (conversationState == null) ? node.getSession().getUserID() : conversationState.getIdentity().getUserId(); if(node.canAddMixin("exo:modify")) { node.addMixin("exo:modify"); } node.setProperty("exo:lastModifiedDate", new GregorianCalendar()); node.setProperty("exo:lastModifier",userName); node.save(); // add version node.checkin(); node.checkout(); } }
6,059
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
IsNotSpecificFolderNodeFilterTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/test/java/org/exoplatform/ecm/webui/component/explorer/control/filter/IsNotSpecificFolderNodeFilterTest.java
package org.exoplatform.ecm.webui.component.explorer.control.filter; import org.exoplatform.component.test.ConfigurationUnit; import org.exoplatform.component.test.ConfiguredBy; import org.exoplatform.component.test.ContainerScope; import org.exoplatform.ecms.test.BaseECMSTestCase; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import javax.jcr.Node; import java.util.HashMap; import java.util.Map; @ConfiguredBy({ @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/exo.portal.component.portal-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/exo.portal.component.identity-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/standalone/ecms-test-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/portal/mock-rest-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/ecms/configuration.xml") }) public class IsNotSpecificFolderNodeFilterTest extends BaseECMSTestCase { private Node testFolder; @Override public void setUp() throws Exception { super.setUp(); if(session.getRootNode().hasNode("testNotSpecificFolderNodeFilter")) { testFolder = session.getRootNode().getNode("testNotSpecificFolderNodeFilter"); testFolder.remove(); session.getRootNode().save(); } testFolder = session.getRootNode().addNode("testNotSpecificFolderNodeFilter", "nt:unstructured"); } public void testShouldReturnFalseWhenPersonalPublicFolder() throws Exception { // Given Node folderPublic = testFolder.addNode("Private", "nt:folder").addNode("Public", "nt:folder"); session.getRootNode().save(); Map<String, Object> context = new HashMap<>(); context.put(Node.class.getName(), folderPublic); IsNotSpecificFolderNodeFilter filter = new IsNotSpecificFolderNodeFilter(); // When boolean accept = filter.accept(context); // Then assertFalse(accept); } public void testShouldReturnTrueWhenNotPersonalFolder() throws Exception { Node folderPublic = testFolder.addNode("Private", "nt:folder").addNode("Public", "nt:folder"); Node folderVideo = folderPublic.addNode("Videos", "nt:folder"); folderVideo.addMixin("exo:videoFolder"); session.save(); Map<String, Object> context = new HashMap<>(); context.put(Node.class.getName(), folderVideo); assertTrue(new IsNotSpecificFolderNodeFilter().accept(context)); } public void testShouldReturnFalseWhenPersonalFolder() throws Exception { Node folderPrivate = testFolder.addNode("Private", "nt:folder"); Node folderVideo = folderPrivate.addNode("Videos", "nt:folder"); folderVideo.addMixin("exo:videoFolder"); session.save(); Map<String, Object> context = new HashMap<>(); context.put(Node.class.getName(), folderVideo); assertFalse(new IsNotSpecificFolderNodeFilter().accept(context)); } public void testShouldReturnTrueWhenNotSpecificFolder() throws Exception { // Given Node folderTwo = testFolder.addNode("testFolderTwo", "nt:folder"); session.getRootNode().save(); Map<String, Object> context = new HashMap<>(); context.put(Node.class.getName(), folderTwo); IsNotSpecificFolderNodeFilter filter = new IsNotSpecificFolderNodeFilter(); // When boolean accept = filter.accept(context); // Then assertTrue(accept); } @Override public void tearDown() throws Exception { super.tearDown(); } }
3,517
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
IsNotIgnoreVersionNodeFilterTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/test/java/org/exoplatform/ecm/webui/component/explorer/control/filter/IsNotIgnoreVersionNodeFilterTest.java
package org.exoplatform.ecm.webui.component.explorer.control.filter; import org.exoplatform.component.test.ConfigurationUnit; import org.exoplatform.component.test.ConfiguredBy; import org.exoplatform.component.test.ContainerScope; import org.exoplatform.ecms.test.BaseECMSTestCase; import org.exoplatform.services.jcr.impl.core.NodeImpl; import javax.jcr.Node; import java.io.ByteArrayInputStream; import java.util.Calendar; import java.util.HashMap; import java.util.Map; @ConfiguredBy({ @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/exo.portal.component.portal-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/exo.portal.component.identity-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/standalone/ecms-test-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/portal/mock-rest-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/ecms/configuration.xml") }) public class IsNotIgnoreVersionNodeFilterTest extends BaseECMSTestCase { private Node testFolder; @Override public void setUp() throws Exception { super.setUp(); if(session.getRootNode().hasNode("testFolderNotIgnoreVersionNodeFilter")) { testFolder = session.getRootNode().getNode("testFolderNotIgnoreVersionNodeFilter"); testFolder.remove(); session.getRootNode().save(); } testFolder = session.getRootNode().addNode("testFolderNotIgnoreVersionNodeFilter", "nt:folder"); } public void testShouldReturnTrueWhenNoParamAndNodeFile() throws Exception { // Given System.clearProperty(IsNotIgnoreVersionNodeFilter.NODETYPES_IGNOREVERSION_PARAM); Node file = testFolder.addNode("testFile", "nt:file"); Node contentNode = file.addNode("jcr:content", "nt:resource"); contentNode.setProperty("jcr:encoding", "UTF-8"); contentNode.setProperty("jcr:data", new ByteArrayInputStream("".getBytes())); contentNode.setProperty("jcr:mimeType", "application/excel"); contentNode.setProperty("jcr:lastModified", Calendar.getInstance()); session.getRootNode().save(); Map<String, Object> context = new HashMap<>(); context.put(Node.class.getName(), file); IsNotIgnoreVersionNodeFilter filter = new IsNotIgnoreVersionNodeFilter(); // When boolean accept = filter.accept(context); // Then assertTrue(accept); } public void testShouldReturnTrueWhenNoParamAndNodeWebContent() throws Exception { // Given System.clearProperty(IsNotIgnoreVersionNodeFilter.NODETYPES_IGNOREVERSION_PARAM); Node webContent = testFolder.addNode("testWebContent", "exo:webContent"); webContent.setProperty("exo:title", "Title"); session.getRootNode().save(); Map<String, Object> context = new HashMap<>(); context.put(Node.class.getName(), webContent); IsNotIgnoreVersionNodeFilter filter = new IsNotIgnoreVersionNodeFilter(); // When boolean accept = filter.accept(context); // Then assertTrue(accept); } public void testShouldReturnFalseWhenNodeChildOfWebContent() throws Exception { // Given System.setProperty(IsNotIgnoreVersionNodeFilter.NODETYPES_IGNOREVERSION_PARAM, "exo:webContent,nt:file"); Node webContent = testFolder.addNode("testWebContent", "exo:webContent"); webContent.setProperty("exo:title", "Title"); Node webContentChild = webContent.addNode("testChildWebContent", "nt:folder"); session.getRootNode().save(); Map<String, Object> context = new HashMap<>(); context.put(Node.class.getName(), webContentChild); IsNotIgnoreVersionNodeFilter filter = new IsNotIgnoreVersionNodeFilter(); // When boolean accept = filter.accept(context); // Then assertFalse(accept); } /** * Test when the user can see the file but not its parent (case of a shared * document between spaces). * @throws Exception */ public void testShouldReturnTrueWhenNoParamAndNodeChildOfWebContent() throws Exception { // Given System.clearProperty(IsNotIgnoreVersionNodeFilter.NODETYPES_IGNOREVERSION_PARAM); testFolder.addMixin("exo:privilegeable"); ((NodeImpl)testFolder).setPermission("*:/platform/administrators", new String[] {"read", "add_node", "set_property", "remove"}); Node file = testFolder.addNode("testFile", "nt:file"); file.addMixin("exo:privilegeable"); ((NodeImpl)file).setPermission("any", new String[] {"read"}); Node contentNode = file.addNode("jcr:content", "nt:resource"); contentNode.setProperty("jcr:encoding", "UTF-8"); contentNode.setProperty("jcr:data", new ByteArrayInputStream("".getBytes())); contentNode.setProperty("jcr:mimeType", "application/excel"); contentNode.setProperty("jcr:lastModified", Calendar.getInstance()); session.getRootNode().save(); applyUserSession("marry", "gtn", "collaboration"); Node fileMarry = (Node) session.getItem("/testFolderNotIgnoreVersionNodeFilter/testFile"); Map<String, Object> context = new HashMap<>(); context.put(Node.class.getName(), fileMarry); IsNotIgnoreVersionNodeFilter filter = new IsNotIgnoreVersionNodeFilter(); // When boolean accept = filter.accept(context); // Then assertTrue(accept); } @Override public void tearDown() throws Exception { System.clearProperty(IsNotIgnoreVersionNodeFilter.NODETYPES_IGNOREVERSION_PARAM); super.tearDown(); } }
5,494
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDocumentAutoVersionForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIDocumentAutoVersionForm.java
package org.exoplatform.ecm.webui.component.explorer; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.webui.component.explorer.rightclick.manager.PasteManageComponent; import org.exoplatform.ecm.webui.utils.JCRExceptionManager; import org.exoplatform.services.cms.actions.ActionServiceContainer; import org.exoplatform.services.cms.documents.TrashService; import org.exoplatform.services.jcr.ext.ActivityTypeUtils; import org.exoplatform.wcm.webui.reader.ContentReader; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.services.cms.clipboard.jcr.model.ClipboardCommand; import org.exoplatform.services.cms.documents.AutoVersionService; 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.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.UIPopupComponent; import org.exoplatform.webui.core.UIPopupWindow; 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.input.UICheckBoxInput; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.version.VersionException; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; /** * Created by The eXo Platform SEA * Author : eXoPlatform * toannh@exoplatform.com * On 7/27/15 * Build popup document auto versioning */ @ComponentConfig( template = "app:/groovy/webui/component/explorer/versions/UIDocumentAutoVersionForm.gtmpl", lifecycle = UIFormLifecycle.class, events = { @EventConfig(listeners = UIDocumentAutoVersionForm.KeepBothActionListener.class), @EventConfig(listeners = UIDocumentAutoVersionForm.CreateNewVersionActionListener.class), @EventConfig(listeners = UIDocumentAutoVersionForm.ReplaceActionListener.class), @EventConfig(listeners = UIDocumentAutoVersionForm.OnChangeActionListener.class), @EventConfig(listeners = UIDocumentAutoVersionForm.CancelActionListener.class, phase = Event.Phase.DECODE) } ) public class UIDocumentAutoVersionForm extends UIForm implements UIPopupComponent { private static final Log LOG = ExoLogger.getLogger(UIDocumentAutoVersionForm.class.getName()); public static final String KEEP_BOTH = "KeepBoth"; public static final String CREATE_VERSION = "CreateNewVersion"; public static final String REPLACE = "Replace"; public static final String CREATE_OR_REPLACE = "CreateVersionOrReplace"; public static final String CANCEL = "Cancel"; public static final String REMEMBER_VERSIONED_COMPONENT = "UIDocumentAutoVersionForm.UIChkRememberVersioned"; public static final String REMEMBER_NONVERSIONED_COMPONENT = "UIDocumentAutoVersionForm.UIChkRememberNonVersioned"; private boolean isVersioned, isSingleProcess = false; private String sourcePath; private String destPath; private String sourceWorkspace; private String destWorkspace; private String message_; private String[] args_ = {}; private static String[] actions = new String[] {KEEP_BOTH, CREATE_VERSION, REPLACE, CREATE_OR_REPLACE ,CANCEL}; private static Set<ClipboardCommand> clipboardCommands = null; private ClipboardCommand currentClipboard = null; private static AutoVersionService autoVersionService = WCMCoreUtils.getService(AutoVersionService.class); @Override public void activate() { } @Override public void deActivate() { } public UIDocumentAutoVersionForm(){ UICheckBoxInput chkRememberVersioned = new UICheckBoxInput(REMEMBER_VERSIONED_COMPONENT, "", false); UICheckBoxInput chkRememberNonVersioned = new UICheckBoxInput(REMEMBER_NONVERSIONED_COMPONENT, "", false); chkRememberVersioned.setOnChange("OnChange"); chkRememberVersioned.setChecked(true); chkRememberNonVersioned.setChecked(true); chkRememberVersioned.setRendered(false); chkRememberNonVersioned.setRendered(false); this.addChild(chkRememberVersioned); this.addChild(chkRememberNonVersioned); } public void init(Node currentNode) throws Exception{ UICheckBoxInput chkRemVersion = this.findComponentById(REMEMBER_VERSIONED_COMPONENT); UICheckBoxInput chkRemNonVersioned = this.findComponentById(REMEMBER_NONVERSIONED_COMPONENT); if(currentNode.isNodeType(NodetypeConstant.MIX_VERSIONABLE)){ setActions(new String[]{KEEP_BOTH, CREATE_VERSION, CANCEL}); chkRemVersion.setRendered(true); chkRemNonVersioned.setRendered(false); }else{ setActions(new String[]{KEEP_BOTH, REPLACE, CANCEL}); chkRemVersion.setRendered(false); chkRemNonVersioned.setRendered(true); } if(isSingleProcess) { chkRemVersion.setRendered(false); chkRemNonVersioned.setRendered(false); } } public String[] getActions() { return actions; } public static class KeepBothActionListener extends EventListener<UIDocumentAutoVersionForm> { @Override public void execute(Event<UIDocumentAutoVersionForm> event) throws Exception { UIDocumentAutoVersionForm autoVersionComponent = event.getSource(); UIJCRExplorer uiExplorer = autoVersionComponent.getAncestorOfType(UIJCRExplorer.class); UIApplication uiApp = uiExplorer.getAncestorOfType(UIApplication.class); UICheckBoxInput chkRemVersion = autoVersionComponent.findComponentById(REMEMBER_VERSIONED_COMPONENT); UICheckBoxInput chkRemNonVersioned = autoVersionComponent.findComponentById(REMEMBER_NONVERSIONED_COMPONENT); boolean chkRem = chkRemVersion.isChecked() && chkRemVersion.isRendered(); boolean chkRemNon = chkRemNonVersioned.isChecked() && chkRemNonVersioned.isRendered(); Session destSession = uiExplorer.getSessionByWorkspace(autoVersionComponent.getDestWorkspace()); Session srcSession = uiExplorer.getSessionByWorkspace(autoVersionComponent.getSourceWorkspace()); Node sourceNode = uiExplorer.getNodeByPath(autoVersionComponent.getSourcePath(), srcSession); String destPath = autoVersionComponent.getDestPath(); Node destNode = uiExplorer.getNodeByPath(destPath, srcSession); boolean isFolder = destNode.isNodeType(org.exoplatform.ecm.webui.utils.Utils.NT_FOLDER); if (destPath != null) { Matcher matcher = UIWorkingArea.FILE_EXPLORER_URL_SYNTAX.matcher(destPath); if (matcher.find()) { destPath = matcher.group(2); } } if (!"/".equals(destPath)) destPath = destPath.concat("/"); destPath = destPath.concat(sourceNode.getName()); if(autoVersionComponent.isSingleProcess) { try { if(ClipboardCommand.CUT.equals(autoVersionComponent.getCurrentClipboard().getType())){ //cut process PasteManageComponent.pasteByCut(autoVersionComponent.getCurrentClipboard(), uiExplorer, destSession, autoVersionComponent.getCurrentClipboard().getWorkspace(), sourceNode.getPath(), destPath, WCMCoreUtils.getService(ActionServiceContainer.class), false,false, false); }else { // nt:folder Does not support SNS int fileIndex = 0; String copyTitle = null; if (isFolder) { Node existNode = uiExplorer.getNodeByPath(destPath, srcSession); fileIndex = 1; String newDestPath = ""; int lastDotIndex = destPath.lastIndexOf('.'); while (existNode != null) { newDestPath = destPath.substring(0, lastDotIndex) + "-" + (fileIndex + 1 ) + destPath.substring(lastDotIndex); existNode = uiExplorer.getNodeByPath(newDestPath, srcSession); fileIndex ++; } destPath = newDestPath; copyTitle = destPath.substring(destPath.lastIndexOf("/") + 1, lastDotIndex) + "(" + (fileIndex + 1 ) + ")" + destPath.substring(lastDotIndex); } copyNode(destSession, autoVersionComponent.getSourceWorkspace(), autoVersionComponent.getSourcePath(), destPath, uiApp, uiExplorer, event, ClipboardCommand.COPY, copyTitle); } } catch (ItemExistsException iee) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.paste-node-same-name", null, ApplicationMessage.WARNING)); uiExplorer.updateAjax(event); return; } } destNode = (Node)destSession.getItem(destPath); Map<String, Boolean> remember = new HashMap<>(); if(destNode.isNodeType(NodetypeConstant.MIX_VERSIONABLE) && chkRem){ remember.put("keepboth", true); PasteManageComponent.setVersionedRemember(remember); }else if(!destNode.isNodeType(NodetypeConstant.MIX_VERSIONABLE) && chkRemNon){ remember.put("keepboth", true); PasteManageComponent.setNonVersionedRemember(remember); } Set<ClipboardCommand> _clipboardCommands = autoVersionComponent.getClipboardCommands(); if(!autoVersionComponent.isSingleProcess && _clipboardCommands!=null && _clipboardCommands.size()>0){ if (ClipboardCommand.CUT.equals(autoVersionComponent.getCurrentClipboard().getType())) { //cut process PasteManageComponent.pasteByCut(autoVersionComponent.getCurrentClipboard(), uiExplorer, destSession, autoVersionComponent.getCurrentClipboard().getWorkspace(), sourceNode.getPath(), destPath, WCMCoreUtils.getService(ActionServiceContainer.class), false, false, false); } else { copyNode(destSession, autoVersionComponent.getSourceWorkspace(), autoVersionComponent.getSourcePath(), destPath, uiApp, uiExplorer, event, ClipboardCommand.COPY); } _clipboardCommands.remove(autoVersionComponent.getCurrentClipboard()); if(_clipboardCommands.isEmpty()){ closePopup(autoVersionComponent, uiExplorer, event); return; } PasteManageComponent.processPasteMultiple(destNode.getParent(), event, uiExplorer, _clipboardCommands, KEEP_BOTH); }else { closePopup(autoVersionComponent, uiExplorer, event); } if((chkRem && chkRemNon)) closePopup(autoVersionComponent, uiExplorer, event); } } public static class CreateNewVersionActionListener extends EventListener<UIDocumentAutoVersionForm> { @Override public void execute(Event<UIDocumentAutoVersionForm> event) throws Exception { UIDocumentAutoVersionForm autoVersionComponent = event.getSource(); UIJCRExplorer uijcrExplorer = autoVersionComponent.getAncestorOfType(UIJCRExplorer.class); UICheckBoxInput chkRemVersion = autoVersionComponent.findComponentById(REMEMBER_VERSIONED_COMPONENT); UICheckBoxInput chkRemNonVersioned = autoVersionComponent.findComponentById(REMEMBER_NONVERSIONED_COMPONENT); boolean chkRem = chkRemVersion.isChecked() && chkRemVersion.isRendered(); boolean chkRemNon = chkRemNonVersioned.isChecked() && chkRemNonVersioned.isRendered(); Session destSession = uijcrExplorer.getSessionByWorkspace(autoVersionComponent.getDestWorkspace()); Session srcSession = uijcrExplorer.getSessionByWorkspace(autoVersionComponent.getSourceWorkspace()); Node sourceNode = uijcrExplorer.getNodeByPath(autoVersionComponent.getSourcePath(), srcSession); String destPath = autoVersionComponent.getDestPath(); if (destPath != null) { Matcher matcher = UIWorkingArea.FILE_EXPLORER_URL_SYNTAX.matcher(destPath); if(matcher.find()) destPath = matcher.group(2); } if (!"/".equals(destPath)) destPath = destPath.concat("/"); destPath = destPath.concat(sourceNode.getName()); Node destNode = (Node)destSession.getItem(destPath); if(autoVersionComponent.isSingleProcess || autoVersionComponent.clipboardCommands.size()==1){ if(ClipboardCommand.CUT.equals(autoVersionComponent.getCurrentClipboard().getType())){ PasteManageComponent.pasteByCut(autoVersionComponent.getCurrentClipboard(), uijcrExplorer, destSession, autoVersionComponent.getCurrentClipboard().getWorkspace(), sourceNode.getPath(), destNode.getParent().getPath(), WCMCoreUtils.getService(ActionServiceContainer.class), false,false, true); }else { autoVersionService.autoVersion(destNode, sourceNode); } closePopup(autoVersionComponent, uijcrExplorer, event); String msg = event.getRequestContext().getApplicationResourceBundle().getString("DocumentAuto.message"); msg = msg.replace("{0}", ContentReader.simpleEscapeHtml( new StringBuilder("<span style='font-weight:bold;'>").append(destNode.getName()).append("</span>").toString())); event.getRequestContext().getJavascriptManager().require("SHARED/wcm-utils", "wcm_utils") .addScripts("eXo.ecm.WCMUtils.showNotice(\" "+msg+"\", 'true'); "); return; } Map<String, Boolean> remember = new HashMap<>(); if(destNode.isNodeType(NodetypeConstant.MIX_VERSIONABLE) && chkRem){ remember.put("createVersion", true); PasteManageComponent.setVersionedRemember(remember); }else if(destNode.isNodeType(NodetypeConstant.MIX_VERSIONABLE) && chkRemNon){ remember.put("createVersion", true); PasteManageComponent.setNonVersionedRemember(remember); } Set<ClipboardCommand> _clipboardCommands = autoVersionComponent.getClipboardCommands(); if(!autoVersionComponent.isSingleProcess && _clipboardCommands!=null && _clipboardCommands.size()>0){ if (ClipboardCommand.COPY.equals(autoVersionComponent.getCurrentClipboard().getType())) { _clipboardCommands.remove(autoVersionComponent.getCurrentClipboard()); AutoVersionService autoVersionService = WCMCoreUtils.getService(AutoVersionService.class); autoVersionService.autoVersion(destNode, sourceNode); }else if (ClipboardCommand.CUT.equals(autoVersionComponent.getCurrentClipboard().getType())) { PasteManageComponent.pasteByCut(autoVersionComponent.getCurrentClipboard(), uijcrExplorer, destSession, autoVersionComponent.getCurrentClipboard().getWorkspace(), sourceNode.getPath(), destNode.getParent().getPath(), WCMCoreUtils.getService(ActionServiceContainer.class), false,false, true); _clipboardCommands.remove(autoVersionComponent.getCurrentClipboard()); } if(_clipboardCommands.isEmpty()){ closePopup(autoVersionComponent, uijcrExplorer, event); return; } Map<String, Boolean> versionedRemember = PasteManageComponent.getVersionedRemember(); if(versionedRemember!=null && BooleanUtils.isTrue(versionedRemember.get("createVersion")) && !_clipboardCommands.isEmpty() ){ String msg = event.getRequestContext().getApplicationResourceBundle().getString("DocumentAuto.messageMultiFile"); event.getRequestContext().getJavascriptManager().require("SHARED/wcm-utils", "wcm_utils") .addScripts("eXo.ecm.WCMUtils.showNotice(\" "+msg+"\", 'true'); "); }else { String msg = event.getRequestContext().getApplicationResourceBundle().getString("DocumentAuto.message"); msg = msg.replace("{0}", ContentReader.simpleEscapeHtml( new StringBuilder("<span style='font-weight:bold;'>").append(destNode.getName()).append("</span>").toString())); event.getRequestContext().getJavascriptManager().require("SHARED/wcm-utils", "wcm_utils") .addScripts("eXo.ecm.WCMUtils.showNotice(\" "+msg+"\", 'true'); "); } PasteManageComponent.processPasteMultiple(destNode.getParent(), event, uijcrExplorer, _clipboardCommands, CREATE_VERSION); }else { closePopup(autoVersionComponent, uijcrExplorer, event); } if(chkRem && chkRemNon) closePopup(autoVersionComponent, uijcrExplorer, event); } } public static class ReplaceActionListener extends EventListener<UIDocumentAutoVersionForm> { @Override public void execute(Event<UIDocumentAutoVersionForm> event) throws Exception { UIDocumentAutoVersionForm autoVersionComponent = event.getSource(); UIJCRExplorer uijcrExplorer = autoVersionComponent.getAncestorOfType(UIJCRExplorer.class); UIApplication uiApp = uijcrExplorer.getAncestorOfType(UIApplication.class); UICheckBoxInput chkRemVersion = autoVersionComponent.findComponentById(REMEMBER_VERSIONED_COMPONENT); UICheckBoxInput chkRemNonVersioned = autoVersionComponent.findComponentById(REMEMBER_NONVERSIONED_COMPONENT); boolean chkRem = chkRemVersion.isChecked() && chkRemVersion.isRendered(); boolean chkRemNon = chkRemNonVersioned.isChecked() && chkRemNonVersioned.isRendered(); Session destSession = uijcrExplorer.getSessionByWorkspace(autoVersionComponent.getDestWorkspace()); Session srcSession = uijcrExplorer.getSessionByWorkspace(autoVersionComponent.getSourceWorkspace()); Node sourceNode = uijcrExplorer.getNodeByPath(autoVersionComponent.getSourcePath(), srcSession); String destPath = autoVersionComponent.getDestPath(); Set<ClipboardCommand> _clipboardCommands = autoVersionComponent.getClipboardCommands(); ClipboardCommand currentCliboard = autoVersionComponent.getCurrentClipboard(); if (destPath != null) { Matcher matcher = UIWorkingArea.FILE_EXPLORER_URL_SYNTAX.matcher(destPath); if(matcher.find()) destPath = matcher.group(2); } Node _destNode = (Node)destSession.getItem(destPath); //If replace in same location, do nothing if(destPath.equals(sourceNode.getParent().getPath()) && autoVersionComponent.isSingleProcess) { closePopup(autoVersionComponent, uijcrExplorer, event); return; } Node destNode = _destNode.getNode(sourceNode.getName()); Map<String, Boolean> remember = new HashMap<>(); if(destNode.isNodeType(NodetypeConstant.MIX_VERSIONABLE) && chkRem){ remember.put("replace", true); PasteManageComponent.setVersionedRemember(remember); }else if(!destNode.isNodeType(NodetypeConstant.MIX_VERSIONABLE) && chkRemNon){ remember.put("replace", true); PasteManageComponent.setNonVersionedRemember(remember); } TrashService trashService = WCMCoreUtils.getService(TrashService.class); String trashID=null; destPath = destNode.getPath(); if(ClipboardCommand.CUT.equals(currentCliboard.getType()) && _destNode.hasNode(sourceNode.getName())) { if(_clipboardCommands!=null && _clipboardCommands.size()>0){ if(!StringUtils.equals(destNode.getPath(), sourceNode.getPath())){ trashID = trashService.moveToTrash(destNode, WCMCoreUtils.getUserSessionProvider()); try { PasteManageComponent.pasteByCut(autoVersionComponent.getCurrentClipboard(), uijcrExplorer, destSession, autoVersionComponent.getCurrentClipboard().getWorkspace(), sourceNode.getPath(), destPath, WCMCoreUtils.getService(ActionServiceContainer.class), false, false, false); }catch (Exception ex){ if(LOG.isErrorEnabled()){ LOG.error("Cannot cut files while replace", ex); } trashService.restoreFromTrash(trashID, WCMCoreUtils.getUserSessionProvider()); } Node deletedNode = trashService.getNodeByTrashId(trashID); deletedNode.remove(); deletedNode.getSession().save(); } _clipboardCommands.remove(currentCliboard); PasteManageComponent.processPasteMultiple(_destNode, event, uijcrExplorer, _clipboardCommands, REPLACE); }else{ closePopup(autoVersionComponent, uijcrExplorer, event); } return; } Node destDriectory = destNode.getParent(); if(autoVersionComponent.isSingleProcess){ trashID = trashService.moveToTrash(destNode, WCMCoreUtils.getUserSessionProvider()); try { copyNode(destSession, autoVersionComponent.getSourceWorkspace(), autoVersionComponent.getSourcePath(), destPath, uiApp, uijcrExplorer, event, ClipboardCommand.COPY); }catch (Exception ex){ if(LOG.isErrorEnabled()){ LOG.error("Cannot copy files while replace", ex); } trashService.restoreFromTrash(trashID, WCMCoreUtils.getUserSessionProvider()); } Node deletedNode = trashService.getNodeByTrashId(trashID); deletedNode.remove(); deletedNode.getSession().save(); closePopup(autoVersionComponent, uijcrExplorer, event); return; } if(_clipboardCommands!=null && _clipboardCommands.size()>0){ _clipboardCommands.remove(autoVersionComponent.getCurrentClipboard()); if(!StringUtils.equals(destPath, autoVersionComponent.getSourcePath())){ trashID = trashService.moveToTrash(destNode, WCMCoreUtils.getUserSessionProvider()); try { copyNode(destSession, autoVersionComponent.getSourceWorkspace(), autoVersionComponent.getSourcePath(), destPath, uiApp, uijcrExplorer, event, ClipboardCommand.COPY); }catch (Exception ex){ if(LOG.isErrorEnabled()){ LOG.error("Cannot copy files while replace", ex); } trashService.restoreFromTrash(trashID, WCMCoreUtils.getUserSessionProvider()); } Node deletedNode = trashService.getNodeByTrashId(trashID); deletedNode.remove(); deletedNode.getSession().save(); destSession.save(); } PasteManageComponent.processPasteMultiple(destDriectory, event, uijcrExplorer, _clipboardCommands, REPLACE); }else { closePopup(autoVersionComponent, uijcrExplorer, event); } if(chkRem && chkRemNon) closePopup(autoVersionComponent, uijcrExplorer, event); } } public static class CancelActionListener extends EventListener<UIDocumentAutoVersionForm> { @Override public void execute(Event<UIDocumentAutoVersionForm> event) throws Exception { UIDocumentAutoVersionForm autoVersionComponent = event.getSource(); UIJCRExplorer uiExplorer = autoVersionComponent.getAncestorOfType(UIJCRExplorer.class); UICheckBoxInput chkRemVersion = autoVersionComponent.findComponentById(REMEMBER_VERSIONED_COMPONENT); UICheckBoxInput chkRemNonVersioned = autoVersionComponent.findComponentById(REMEMBER_NONVERSIONED_COMPONENT); boolean chkRem = chkRemVersion.isChecked() && chkRemVersion.isRendered(); boolean chkRemNon = chkRemNonVersioned.isChecked() && chkRemNonVersioned.isRendered(); Session destSession = uiExplorer.getSessionByWorkspace(autoVersionComponent.getDestWorkspace()); Session srcSession = uiExplorer.getSessionByWorkspace(autoVersionComponent.getSourceWorkspace()); Node sourceNode = uiExplorer.getNodeByPath(autoVersionComponent.getSourcePath(), srcSession); String destPath = autoVersionComponent.getDestPath(); if(autoVersionComponent.isSingleProcess) { closePopup(autoVersionComponent, uiExplorer, event); } if (destPath != null) { Matcher matcher = UIWorkingArea.FILE_EXPLORER_URL_SYNTAX.matcher(destPath); if (matcher.find()) { destPath = matcher.group(2); } } if (!"/".equals(destPath)) destPath = destPath.concat("/"); destPath = destPath.concat(sourceNode.getName()); Node destNode = (Node)destSession.getItem(destPath); Map<String, Boolean> remember = new HashMap<>(); if(destNode.isNodeType(NodetypeConstant.MIX_VERSIONABLE) && chkRem){ remember.put(CANCEL, true); PasteManageComponent.setVersionedRemember(remember); }else if(!destNode.isNodeType(NodetypeConstant.MIX_VERSIONABLE) && chkRemNon){ remember.put(CANCEL, true); PasteManageComponent.setNonVersionedRemember(remember); } Set<ClipboardCommand> _clipboardCommands = autoVersionComponent.getClipboardCommands(); if(!autoVersionComponent.isSingleProcess && _clipboardCommands!=null && _clipboardCommands.size()>0){ _clipboardCommands.remove(autoVersionComponent.getCurrentClipboard()); if(_clipboardCommands.isEmpty()){ closePopup(autoVersionComponent, uiExplorer, event); return; } PasteManageComponent.processPasteMultiple(destNode.getParent(), event, uiExplorer, _clipboardCommands, CANCEL); }else { closePopup(autoVersionComponent, uiExplorer, event); } if((chkRem && chkRemNon)) closePopup(autoVersionComponent, uiExplorer, event); } } public String getSourcePath() { return sourcePath; } public void setSourcePath(String sourcePath) { this.sourcePath = sourcePath; } public String getDestPath() { return destPath; } public void setDestPath(String destPath) { this.destPath = destPath; } public String getSourceWorkspace() { return sourceWorkspace; } public void setSourceWorkspace(String sourceWorkspace) { this.sourceWorkspace = sourceWorkspace; } public String getDestWorkspace() { return destWorkspace; } public void setDestWorkspace(String destWorkspace) { this.destWorkspace = destWorkspace; } public void setMessage(String message) { message_ = message; } public String getMessage() { return message_; } public void setArguments(String[] args) { args_ = args; } public String[] getArguments() { return args_; } public boolean isVersioned() { return isVersioned; } public void setVersioned(boolean isVersioned) { this.isVersioned = isVersioned; } public void setActions(String[] actions) { this.actions = actions; } public void setSingleProcess(boolean isSingleProcess) { this.isSingleProcess = isSingleProcess; } /** * Copy node using workspace * @param session session of dest node * @param srcWorkspaceName source * @param srcPath * @param destPath * @param copyTitle title of the copied file with its index * @throws Exception */ public static void copyNode(Session session, String srcWorkspaceName, String srcPath, String destPath, UIApplication uiApp, UIJCRExplorer uiExplorer, Event<?> event, String type, String copyTitle) throws Exception { Workspace workspace = session.getWorkspace(); if (workspace.getName().equals(srcWorkspaceName)) { try { workspace.copy(srcPath, destPath); Node parentDestNode = session.getItem(destPath).getParent(); String destName = session.getItem(destPath).getName(); NodeIterator destNodeIterator = parentDestNode.getNodes(destName); Node destNode = null; while (destNodeIterator.hasNext()) { destNode = destNodeIterator.nextNode(); } if(destNode!=null) { if (destNode.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO)) { destNode.removeMixin(ActivityTypeUtils.EXO_ACTIVITY_INFO); } if (destNode.isNodeType(NodetypeConstant.EOO_ONLYOFFICE_FILE)) { destNode.removeMixin(NodetypeConstant.EOO_ONLYOFFICE_FILE); } destNode.save(); if (copyTitle != null) { destNode.setProperty("exo:title", copyTitle); } Utils.removeReferences(destNode); } }catch (ConstraintViolationException ce) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.current-node-not-allow-paste", null, ApplicationMessage.WARNING)); uiExplorer.updateAjax(event); return; } catch (VersionException ve) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.copied-node-in-versioning", null, ApplicationMessage.WARNING)); uiExplorer.updateAjax(event); return; } catch (ItemExistsException iee) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.paste-node-same-name", null, ApplicationMessage.WARNING)); uiExplorer.updateAjax(event); return; } catch (LoginException e) { if (ClipboardCommand.CUT.equals(type)) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.cannot-login-node", null, ApplicationMessage.WARNING)); uiExplorer.updateAjax(event); return; } uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.cannot-paste-nodetype", null, ApplicationMessage.WARNING)); uiExplorer.updateAjax(event); return; } catch (AccessDeniedException ace) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.access-denied", null, ApplicationMessage.WARNING)); uiExplorer.updateAjax(event); return; } catch (LockException locke) { Object[] arg = { srcPath }; uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.paste-lock-exception", arg, ApplicationMessage.WARNING)); } catch (Exception e) { JCRExceptionManager.process(uiApp, e); uiExplorer.updateAjax(event); return; } } else { try { if (LOG.isDebugEnabled()) LOG.debug("Copy to another workspace"); workspace.copy(srcWorkspaceName, srcPath, destPath); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("an unexpected error occurs while pasting the node", e); } if (LOG.isDebugEnabled()) LOG.debug("Copy to other workspace by clone"); try { workspace.clone(srcWorkspaceName, srcPath, destPath, false); } catch (Exception f) { if (LOG.isErrorEnabled()) { LOG.error("an unexpected error occurs while pasting the node", f); } } } } } public static void copyNode(Session session, String srcWorkspaceName, String srcPath, String destPath, UIApplication uiApp, UIJCRExplorer uiExplorer, Event<?> event, String type) throws Exception { copyNode(session, srcWorkspaceName, srcPath, destPath,uiApp, uiExplorer, event, type, null); } public Set<ClipboardCommand> getClipboardCommands() { return clipboardCommands; } public void setClipboardCommands(Set<ClipboardCommand> clipboardCommands) { this.clipboardCommands = clipboardCommands; } public ClipboardCommand getCurrentClipboard() { return currentClipboard; } public void setCurrentClipboard(ClipboardCommand currentClipboard) { this.currentClipboard = currentClipboard; } public static void closePopup(UIDocumentAutoVersionForm autoVersionComponent, UIJCRExplorer uijcrExplorer, Event<?> event) throws Exception{ UIPopupWindow popupAction = uijcrExplorer.findFirstComponentOfType(UIPopupWindow.class) ; UICheckBoxInput chkRememberVersioned = autoVersionComponent.findComponentById(REMEMBER_VERSIONED_COMPONENT); UICheckBoxInput chkRememberNonVersioned = autoVersionComponent.findComponentById(REMEMBER_NONVERSIONED_COMPONENT); chkRememberVersioned.setChecked(false); chkRememberNonVersioned.setChecked(false); PasteManageComponent.setVersionedRemember(null); PasteManageComponent.setNonVersionedRemember(null); autoVersionComponent.setCurrentClipboard(null); popupAction.setShow(false) ; popupAction.setRendered(false); uijcrExplorer.updateAjax(event); } static public class OnChangeActionListener extends EventListener<UIDocumentAutoVersionForm> { public void execute(Event<UIDocumentAutoVersionForm> event) throws Exception { event.getRequestContext().addUIComponentToUpdateByAjax(event.getSource()); } } @Override public void processRender(WebuiRequestContext context) throws Exception { super.processRender(context); } }
32,538
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIJcrExplorerContainer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIJcrExplorerContainer.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.explorer; import java.util.*; import javax.jcr.*; import javax.portlet.PortletPreferences; import javax.portlet.PortletRequest; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.api.settings.*; import org.exoplatform.ecm.jcr.model.Preference; import org.exoplatform.ecm.webui.component.explorer.control.*; import org.exoplatform.ecm.webui.component.explorer.sidebar.UISideBar; import org.exoplatform.ecm.webui.utils.JCRExceptionManager; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.views.ManageViewService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.social.core.space.SpaceUtils; 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.core.*; import org.exoplatform.webui.core.model.SelectItemOption; /** * Created by The eXo Platform SARL */ @ComponentConfig( template = "app:/groovy/webui/component/explorer/UIJCRExplorerContainer.gtmpl" ) public class UIJcrExplorerContainer extends UIContainer { private static final Log LOG = ExoLogger.getLogger(UIJcrExplorerContainer.class.getName()); private ExoFeatureService featureService; public UIJcrExplorerContainer() throws Exception { addChild(UIJCRExplorer.class, null, null); addChild(UIMultiUpload.class, null, null); } public String getUserAgent() { PortletRequestContext requestContext = PortletRequestContext.getCurrentInstance(); PortletRequest portletRequest = requestContext.getRequest(); return portletRequest.getProperty("User-Agent"); } public void initExplorer() throws Exception { try { UIJCRExplorerPortlet uiFEPortlet = getParent(); PortletPreferences preference = uiFEPortlet.getPortletPreferences(); initExplorerPreference(preference); String driveName = preference.getValue("driveName", ""); String nodePath = preference.getValue("nodePath", ""); RepositoryService rservice = getApplicationComponent(RepositoryService.class); String repoName = rservice.getCurrentRepository().getConfiguration().getName(); ManageDriveService dservice = getApplicationComponent(ManageDriveService.class); DriveData drive = dservice.getDriveByName(driveName); String userId = Util.getPortalRequestContext().getRemoteUser(); List<String> userRoles = Utils.getMemberships(); if(!uiFEPortlet.canUseConfigDrive(driveName)) { drive = getAncestorOfType(UIJCRExplorerPortlet.class).getUserDrive(); } UIApplication uiApp = getApplicationComponent(UIApplication.class); List<String> viewList = new ArrayList<String>(); for (String role : userRoles) { for (String viewName : drive.getViews().split(",")) { if (!viewList.contains(viewName.trim())) { Node viewNode = getApplicationComponent(ManageViewService.class) .getViewByName(viewName.trim(), WCMCoreUtils.getSystemSessionProvider()); String permiss = viewNode.getProperty("exo:accessPermissions").getString(); if (permiss.contains("${userId}")) permiss = permiss.replace("${userId}", userId); String[] viewPermissions = permiss.split(","); if (permiss.equals("*")) viewList.add(viewName.trim()); if (drive.hasPermission(viewPermissions, role)) viewList.add(viewName.trim()); } } } if (viewList.isEmpty()) { return; } StringBuffer viewListStr = new StringBuffer(); List<SelectItemOption<String>> viewOptions = new ArrayList<SelectItemOption<String>>(); WebuiRequestContext context = WebuiRequestContext.getCurrentInstance(); ResourceBundle res = context.getApplicationResourceBundle(); String viewLabel = null; for (String viewName : viewList) { try { viewLabel = res.getString("Views.label." + viewName) ; } catch (MissingResourceException e) { viewLabel = viewName; } viewOptions.add(new SelectItemOption<String>(viewLabel, viewName)); if(viewListStr.length() > 0) viewListStr.append(",").append(viewName); else viewListStr.append(viewName); } drive.setViews(viewListStr.toString()); StringBuffer homePathBuf = new StringBuffer(); homePathBuf.append(drive.getHomePath()); if (homePathBuf.indexOf("${userId}") >= 0) homePathBuf = new StringBuffer(org.exoplatform.services.cms.impl.Utils.getPersonalDrivePath(homePathBuf.toString(), userId)); //Check to make sure new behavior will be also correct with the legacy data //By default all the group drive will be point to Documents folder. //Therefore in the case spaces drives we no need to specify the nodepath or consider it is equals "/" if(drive.getHomePath().startsWith("/Groups/spaces/") && (StringUtils.isBlank(nodePath) || nodePath.equals("Documents") || nodePath.equals("/Documents"))) nodePath = "/"; if (nodePath != null && nodePath.length() > 0 && !nodePath.equals("/")) homePathBuf.append("/").append(nodePath); String homePath = homePathBuf.toString().replaceAll("//", "/"); UIJCRExplorer uiJCRExplorer = getChild(UIJCRExplorer.class); uiJCRExplorer.setDriveData(drive); uiJCRExplorer.setIsReferenceNode(false); Session session = WCMCoreUtils.getUserSessionProvider().getSession(drive.getWorkspace(), rservice.getCurrentRepository()); try { // we assume that the path is a real path session.getItem(homePath); } catch(AccessDeniedException ace) { Object[] args = { driveName }; uiApp.addMessage(new ApplicationMessage("UIDrivesArea.msg.access-denied", args, ApplicationMessage.WARNING)); return; } catch(NoSuchWorkspaceException nosuchWS) { Object[] args = { driveName }; uiApp.addMessage(new ApplicationMessage("UIDrivesArea.msg.workspace-not-exist", args, ApplicationMessage.WARNING)); return; } catch(Exception e) { JCRExceptionManager.process(uiApp, e); return; } uiJCRExplorer.setRepositoryName(repoName); uiJCRExplorer.setWorkspaceName(drive.getWorkspace()); uiJCRExplorer.setRootPath(homePath); uiJCRExplorer.setSelectNode(drive.getWorkspace(), homePath); Preference pref = uiJCRExplorer.getPreference(); pref.setShowSideBar(drive.getViewSideBar()); pref.setShowNonDocumentType(drive.getViewNonDocument()); pref.setShowPreferenceDocuments(drive.getViewPreferences()); pref.setAllowCreateFoder(drive.getAllowCreateFolders()); pref.setShowHiddenNode(drive.getShowHiddenNode()); UIControl uiControl = uiJCRExplorer.getChild(UIControl.class); UIWorkingArea uiWorkingArea = uiJCRExplorer.getChild(UIWorkingArea.class); UIAddressBar uiAddressBar = uiControl.getChild(UIAddressBar.class); uiAddressBar.setViewList(viewList); uiAddressBar.setSelectedViewName(viewList.get(0)); uiAddressBar.setRendered(uiFEPortlet.isShowTopBar()); UIActionBar uiActionbar = uiWorkingArea.getChild(UIActionBar.class); boolean isShowActionBar = uiFEPortlet.isShowActionBar(); uiActionbar.setTabOptions(viewList.get(0)); uiActionbar.setRendered(isShowActionBar); uiWorkingArea.setRenderedChildrenOfTypes(new Class[] { UIActionBar.class, UIDocumentWorkspace.class }); uiJCRExplorer.refreshExplorer(); UIRightClickPopupMenu uiRightClickPopupMenu = uiWorkingArea.findFirstComponentOfType(UIRightClickPopupMenu.class); if(uiRightClickPopupMenu!=null && !uiRightClickPopupMenu.isRendered()) uiRightClickPopupMenu.setRendered(true); UISideBar uiSideBar = uiWorkingArea.findFirstComponentOfType(UISideBar.class); uiSideBar.setRendered(true); uiSideBar.initialize(); if (uiSideBar.isRendered()) { uiSideBar.updateSideBarView(); } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } } private void initExplorerPreference(PortletPreferences portletPref) { UIJCRExplorer uiExplorer = getChild(UIJCRExplorer.class); if (uiExplorer != null) { Preference pref = uiExplorer.getPreference(); if (pref == null) { pref = new Preference(); pref.setNodesPerPage(Integer.parseInt(portletPref.getValue(Preference.NODES_PER_PAGE, "20"))); uiExplorer.setPreferences(pref); } } } public boolean isOldDocumentsFeatureEnabled() { try { if (!SpaceUtils.isSpaceContext() && !getChild(UIJCRExplorer.class).getRootNode().getName().equals("Private")) { return true; } } catch (Exception e) { LOG.warn("Cannot get File explorer root node"); } String userId = Util.getPortalRequestContext().getRemoteUser(); return getFeatureService().isFeatureActiveForUser("OldDocuments", userId); } public boolean isSwitchDocumentsFeatureEnabled() { String userId = Util.getPortalRequestContext().getRemoteUser(); return getFeatureService().isFeatureActiveForUser("SwitchOldDocuments", userId); } public ExoFeatureService getFeatureService() { if (featureService == null) { featureService = getApplicationComponent(ExoFeatureService.class); } return featureService; } }
10,973
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDocumentWorkspace.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIDocumentWorkspace.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.explorer ; import org.exoplatform.ecm.webui.component.explorer.lifecycle.UIDocumentWorkspaceLifeCycle; import org.exoplatform.ecm.webui.component.explorer.search.UISearchResult; import org.exoplatform.ecm.webui.component.explorer.versions.UIDiff; import org.exoplatform.ecm.webui.component.explorer.versions.UIVersionInfo; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIContainer; /** * Created by The eXo Platform SARL * Author : tran the trong * trongtt@gmail.com * July 3, 2006 * 10:07:15 AM */ @ComponentConfig(lifecycle = UIDocumentWorkspaceLifeCycle.class) public class UIDocumentWorkspace extends UIContainer { static public String SIMPLE_SEARCH_RESULT = "SimpleSearchResult" ; public UIDocumentWorkspace() throws Exception { addChild(UIDocumentContainer.class, null, null) ; addChild(UISearchResult.class, null, SIMPLE_SEARCH_RESULT).setRendered(false); addChild(UIVersionInfo.class, null, null).setRendered(false); addChild(UIDiff.class, null, null).setRendered(false); } }
1,827
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIMultiUpload.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIMultiUpload.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.component.explorer; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.connector.fckeditor.DriverConnector; 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.UIContainer; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Oct 18, 2012 */ @ComponentConfig( template = "app:/groovy/webui/component/explorer/upload/UIMultiUpload.gtmpl", events = { @EventConfig(listeners = UIMultiUpload.RefreshExplorerActionListener.class) } ) public class UIMultiUpload extends UIContainer { private static final Log LOG = ExoLogger.getLogger(UIMultiUpload.class.getName()); private DriverConnector driveConnector_; public UIMultiUpload() throws Exception { this.driveConnector_ = WCMCoreUtils.getService(DriverConnector.class); } public int getLimitFileSize() { return driveConnector_.getLimitSize(); } public int getMaxUploadCount() { return driveConnector_.getMaxUploadCount(); } @Override public void processRender(WebuiRequestContext context) throws Exception { // context.getJavascriptManager().require("SHARED/explorer-module", "explorer"). // addScripts("explorer.MultiUpload.initDropBox('" + this.getId() + " ');"); super.processRender(context); } public static class RefreshExplorerActionListener extends EventListener<UIMultiUpload> { public void execute(Event<UIMultiUpload> event) throws Exception { UIMultiUpload uiUpload = event.getSource(); uiUpload.getAncestorOfType(UIJcrExplorerContainer.class).getChild(UIJCRExplorer.class).updateAjax(event); } } }
2,738
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISelectDocumentTemplateTitle.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UISelectDocumentTemplateTitle.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.component.explorer; import org.exoplatform.ecm.webui.component.explorer.popup.actions.UIDocumentFormController; import org.exoplatform.ecm.webui.component.explorer.popup.actions.UISelectDocumentForm; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS Author : * eXoPlatform dongpd@exoplatform.com * Feb 2, 2013 */ @ComponentConfig(template = "app:/groovy/webui/component/explorer/UISelectDocumentTemplateTitle.gtmpl", events = { @EventConfig(listeners = UISelectDocumentTemplateTitle.ChangeViewActionListener.class), @EventConfig(listeners = UISelectDocumentTemplateTitle.CancelActionListener.class) }) public class UISelectDocumentTemplateTitle extends UIComponent { private final static String THUMBNAIL_VIEW_TEMPLATE = "app:/groovy/webui/component/explorer/UISelectDocumentFormThumbnailView.gtmpl"; private final static String LIST_VIEW_TEMPLATE = "app:/groovy/webui/component/explorer/UISelectDocumentFormListView.gtmpl"; static public class ChangeViewActionListener extends EventListener<UISelectDocumentTemplateTitle> { private static final String THUMBNAIL_VIEW_TYPE = "ThumbnailView"; public void execute(Event<UISelectDocumentTemplateTitle> event) throws Exception { String viewType = event.getRequestContext().getRequestParameter(OBJECTID); UISelectDocumentTemplateTitle uiTemplateTitle = event.getSource(); UIWorkingArea uiWorkingArea = uiTemplateTitle.getAncestorOfType(UIWorkingArea.class); UISelectDocumentForm uiSelectForm = uiWorkingArea.getChild(UIDocumentWorkspace.class) .getChild(UIDocumentFormController.class) .getChild(UISelectDocumentForm.class); UIJCRExplorer uiExplorer = uiSelectForm.getAncestorOfType(UIJCRExplorer.class); if (viewType.equals(THUMBNAIL_VIEW_TYPE)) { uiSelectForm.setTemplate(THUMBNAIL_VIEW_TEMPLATE); } else { uiSelectForm.setTemplate(LIST_VIEW_TEMPLATE); } uiExplorer.updateAjax(event); } } static public class CancelActionListener extends EventListener<UISelectDocumentTemplateTitle> { public void execute(Event<UISelectDocumentTemplateTitle> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); if (uiExplorer != null) { UIWorkingArea uiWorkingArea = uiExplorer.getChild(UIWorkingArea.class); UIDocumentWorkspace uiDocumentWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class); if (uiDocumentWorkspace.getChild(UIDocumentFormController.class) != null) { uiDocumentWorkspace.removeChild(UIDocumentFormController.class); } else uiExplorer.cancelAction(); uiExplorer.updateAjax(event); } } } }
3,772
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDocumentNodeList.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIDocumentNodeList.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.component.explorer; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.utils.*; import org.exoplatform.ecm.jcr.model.Preference; import org.exoplatform.ecm.webui.component.explorer.control.action.ManageVersionsActionComponent; import org.exoplatform.ecm.webui.component.explorer.versions.UIActivateVersion; import org.exoplatform.ecm.webui.component.explorer.versions.UIVersionInfo; import org.exoplatform.ecm.webui.utils.JCRExceptionManager; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.portal.webui.workspace.UIPortalApplication; import org.exoplatform.services.cms.documents.VersionHistoryUtils; import org.exoplatform.services.cms.link.*; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.IdentityConstants; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.core.NodetypeConstant; 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.*; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import javax.jcr.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Nov 29, 2012 */ @ComponentConfig ( template = "app:/groovy/webui/component/explorer/UIDocumentNodeList.gtmpl", events = { @EventConfig(listeners = UIDocumentNodeList.ExpandNodeActionListener.class), @EventConfig(listeners = UIDocumentNodeList.CollapseNodeActionListener.class), @EventConfig(listeners = UIDocumentNodeList.ManageVersionsActionListener.class), @EventConfig(listeners = UIDocumentNodeList.MoreActionListener.class) } ) public class UIDocumentNodeList extends UIContainer { private static final Log LOG = ExoLogger.getLogger(UIDocumentNodeList.class.getName()); private UIPageIterator pageIterator_; private LinkManager linkManager_; private List dataList_; private int padding_; private boolean showMoreButton_ = true; public UIDocumentNodeList() throws Exception { linkManager_ = WCMCoreUtils.getService(LinkManager.class); addChild(ManageVersionsActionComponent.class, null, null); pageIterator_ = addChild(UIPageIterator.class, null, "UIDocumentNodeListPageIterator"); padding_ = 0; } @SuppressWarnings("unchecked") public List<Node> getNodeChildrenList() throws Exception { return NodeLocation.getNodeListByLocationList(showMoreButton_ ? dataList_ : pageIterator_.getCurrentPageData()); } public void setPageList(PageList p) throws Exception { pageIterator_.setPageList(p); dataList_ = new ArrayList(); if (p != null && p.getAvailable() > 0) { dataList_.addAll(p.getPage(1)); } updateUIDocumentNodeListChildren(); } public int getPadding() { return padding_; } public void setPadding(int value) { padding_ = value; } public boolean isShowMoreButton() { return showMoreButton_ && (pageIterator_ != null) && (pageIterator_.getPageList() != null) && (dataList_ != null) && (dataList_.size() < pageIterator_.getPageList().getAvailable()); } public void setShowMoreButton(boolean value) { showMoreButton_ = value; } public void setCurrentNode(Node node) throws Exception { setPageList(this.getPageList(node.getPath())); } public void updateUIDocumentNodeListChildren() throws Exception { Set<String> ids = new HashSet<String>(); //get all ids of UIDocumentNodeList children for (UIComponent component : getChildren()) { if (component instanceof UIDocumentNodeList) { ids.add(component.getId()); } } //remove all UIDocumentNodeList children for (String id : ids) { this.removeChildById(id); } //add new UIDocumentNodeList children for (Node node : getNodeChildrenList()) { if (node == null) { continue; } if (node instanceof NodeLinkAware) { node = ((NodeLinkAware)node).getRealNode(); } try { Node targetNode = linkManager_.isLink(node) ? linkManager_.getTarget(node) : node; if (targetNode != null && targetNode.isNodeType(NodetypeConstant.NT_FOLDER) || targetNode.isNodeType(NodetypeConstant.NT_UNSTRUCTURED)) { addUIDocList(getID(node)); } } catch(ItemNotFoundException ine) { continue; } } } public UIPageIterator getContentPageIterator() { return pageIterator_; } public String getID(Node node) throws Exception { return this.getAncestorOfType(UIDocumentInfo.class).getClass().getSimpleName() + this.getClass().getSimpleName() + String.valueOf(Math.abs(node.getPath().hashCode())); } public UIComponent addUIDocList(String id) throws Exception { UIDocumentNodeList child = addChild(UIDocumentNodeList.class, null, id); child.setPadding(padding_ + 1); child.getContentPageIterator().setId(child.getId() + "PageIterator"); return child; } /** * gets the name of file * @param file the file * @param title the title * @return name of file * @throws Exception */ public String getFileName(Node file, String title) throws Exception { if (!file.isNodeType(NodetypeConstant.NT_FILE) || title == null) { return title; } else { int index = title.lastIndexOf('.'); if (index != -1) { return title.substring(0, index); } else { return title; } } } /** * gets the extension of file * @param file the file * @param title the title * @return extension of file * @throws Exception */ public String getFileExtension(Node file, String title) throws Exception { if (!file.isNodeType(NodetypeConstant.NT_FILE) || title == null) { return ""; } else { int index = title.lastIndexOf('.'); if (index != -1) { return title.substring(index); } else { return ""; } } } /** * gets date presentation of file * @param file the file * @return file date presentation * @throws Exception */ public String getFileDate(Node file) throws Exception { String createdDate = this.getDatePropertyValue(file, NodetypeConstant.EXO_DATE_CREATED); String modifiedDate = this.getDatePropertyValue(file, NodetypeConstant.EXO_LAST_MODIFIED_DATE); return StringUtils.isEmpty(modifiedDate) || equalDates(file, NodetypeConstant.EXO_DATE_CREATED, NodetypeConstant.EXO_LAST_MODIFIED_DATE)? getLabel("CreatedOn") + " " + createdDate : getLabel("Updated") + " " + modifiedDate; } private boolean equalDates(Node node, String p1, String p2) { Calendar pr1 = null; Calendar pr2 = null; try { pr1 = node.getProperty(p1).getDate(); } catch (PathNotFoundException e) { pr1 = null; } catch (ValueFormatException e) { pr1 = null; } catch (RepositoryException e) { pr1 = null; } try { pr2 = node.getProperty(p2).getDate(); } catch (PathNotFoundException e) { pr2 = null; } catch (ValueFormatException e) { pr2 = null; } catch (RepositoryException e) { pr2 = null; } if ((pr1 == null) && (pr2 == null)) return true; if ((pr1 == null) || (pr2 == null)) return false; return Math.abs(pr1.getTimeInMillis() - pr2.getTimeInMillis()) < 3000; } public String getDatePropertyValue(Node node, String propertyName) throws Exception { try { Property property = node.getProperty(propertyName); if(property != null) { Locale locale = Util.getUIPortal().getAncestorOfType(UIPortalApplication.class).getLocale(); DateFormat dateFormat = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, locale); return dateFormat.format(property.getDate().getTime()); } } catch(PathNotFoundException PNE) { return ""; } return ""; } /** * gets label * @param id the id * @return label */ public String getLabel(String id) { RequestContext context = RequestContext.getCurrentInstance(); ResourceBundle res = context.getApplicationResourceBundle(); try { return res.getString("UIDocumentNodeList.label." + id); } catch (MissingResourceException ex) { return id; } } /** * gets version number of the node * @param file the node * @return version number */ protected String getVersionNumber(Node file) throws Exception { String currentVersion = null; if (file.isNodeType(NodetypeConstant.MIX_VERSIONABLE)){ try { if (file.isNodeType(VersionHistoryUtils.MIX_DISPLAY_VERSION_NAME) && file.hasProperty(VersionHistoryUtils.MAX_VERSION_PROPERTY)) { //Get max version ID int max = (int) file.getProperty(VersionHistoryUtils.MAX_VERSION_PROPERTY).getLong(); currentVersion = String.valueOf(max-1); }else { currentVersion = file.getBaseVersion().getName(); if (currentVersion.contains("jcr:rootVersion")) currentVersion = "0"; } }catch (Exception e) { currentVersion ="0"; } return "V"+currentVersion; } return ""; } public String getAuthorName(Node file) throws Exception { String userName = getAncestorOfType(UIDocumentInfo.class).getPropertyValue(file, NodetypeConstant.EXO_LAST_MODIFIER); if (StringUtils.isEmpty(userName) || IdentityConstants.SYSTEM.equals(userName)) { return StringUtils.EMPTY; } return String.format("%s %s", getLabel("by"), userName.equals(ConversationState.getCurrent().getIdentity().getUserId()) ? getLabel("you") : userName); } public String getFileSize(Node file) throws Exception { return org.exoplatform.services.cms.impl.Utils.fileSize(file); } @SuppressWarnings("unchecked") private PageList<Object> getPageList(String path) throws Exception { UIJCRExplorer uiExplorer = this.getAncestorOfType(UIJCRExplorer.class); Preference pref = uiExplorer.getPreference(); DocumentProviderUtils docProviderUtil = DocumentProviderUtils.getInstance(); if (docProviderUtil.canSortType(pref.getSortType()) && uiExplorer.getAllItemByTypeFilterMap().isEmpty()) { return docProviderUtil.getPageList( uiExplorer.getWorkspaceName(), path, pref, uiExplorer.getAllItemFilterMap(), uiExplorer.getAllItemByTypeFilterMap(), (NodeLinkAware) ItemLinkAware.newInstance(uiExplorer.getWorkspaceName(), path, uiExplorer.getNodeByPath(path, uiExplorer.getSystemSession()))); } List<Node> nodeList = null; UIDocumentInfo uiDocInfo = this.getAncestorOfType(UIDocumentInfo.class); int nodesPerPage = pref.getNodesPerPage(); Set<String> allItemByTypeFilterMap = uiExplorer.getAllItemByTypeFilterMap(); if (allItemByTypeFilterMap.size() > 0) nodeList = uiDocInfo.filterNodeList(uiExplorer.getChildrenList(path, !pref.isShowPreferenceDocuments())); else nodeList = uiDocInfo.filterNodeList(uiExplorer.getChildrenList(path, pref.isShowPreferenceDocuments())); ListAccess<Object> nodeAccList = new ListAccessImpl<Object>(Object.class, NodeLocation.getLocationsByNodeList(nodeList)); return new LazyPageList<Object>(nodeAccList, nodesPerPage); } static public class ExpandNodeActionListener extends EventListener<UIDocumentNodeList> { public void execute(Event<UIDocumentNodeList> event) throws Exception { UIDocumentNodeList uicomp = event.getSource(); NodeFinder nodeFinder = uicomp.getApplicationComponent(NodeFinder.class); String uri = event.getRequestContext().getRequestParameter(OBJECTID); String workspaceName = event.getRequestContext().getRequestParameter("workspaceName"); UIApplication uiApp = uicomp.getAncestorOfType(UIApplication.class); try { // Manage ../ and ./ uri = LinkUtils.evaluatePath(uri); // Just in order to check if the node exists Item item = nodeFinder.getItem(workspaceName, uri); if ((item instanceof Node) && Utils.isInTrash((Node) item)) { return; } // uiExplorer.setSelectNode(workspaceName, uri); Node clickedNode = (Node)item; // UIDocumentNodeList uiDocNodeListChild = uicomp.addChild(UIDocumentNodeList.class, null, // String.valueOf(clickedNode.getPath().hashCode())); UIDocumentNodeList uiDocNodeListChild = uicomp.getChildById(uicomp.getID(clickedNode)); uiDocNodeListChild.setCurrentNode(clickedNode); uicomp.getAncestorOfType(UIDocumentInfo.class).getExpandedFolders().add(uri); event.getRequestContext().addUIComponentToUpdateByAjax(uiDocNodeListChild); } catch(ItemNotFoundException nu) { uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.null-exception", null, ApplicationMessage.WARNING)) ; return ; } catch(PathNotFoundException pa) { uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.path-not-found", null, ApplicationMessage.WARNING)) ; return ; } catch(AccessDeniedException ace) { uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.access-denied", null, ApplicationMessage.WARNING)) ; return ; } catch(RepositoryException e) { if (LOG.isErrorEnabled()) { LOG.error("Repository cannot be found"); } uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.repository-error", null, ApplicationMessage.WARNING)) ; return ; } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } } } static public class CollapseNodeActionListener extends EventListener<UIDocumentNodeList> { public void execute(Event<UIDocumentNodeList> event) throws Exception { UIDocumentNodeList uicomp = event.getSource(); NodeFinder nodeFinder = uicomp.getApplicationComponent(NodeFinder.class); String uri = event.getRequestContext().getRequestParameter(OBJECTID); String workspaceName = event.getRequestContext().getRequestParameter("workspaceName"); UIApplication uiApp = uicomp.getAncestorOfType(UIApplication.class); try { // Manage ../ and ./ uri = LinkUtils.evaluatePath(uri); // Just in order to check if the node exists Item item = nodeFinder.getItem(workspaceName, uri); if ((item instanceof Node) && Utils.isInTrash((Node) item)) { return; } Node clickedNode = (Node)item; UIDocumentNodeList uiDocNodeListChild = uicomp.getChildById(uicomp.getID(clickedNode)); uiDocNodeListChild.setPageList(EmptySerializablePageList.get()); uicomp.getAncestorOfType(UIDocumentInfo.class).getExpandedFolders().remove(uri); event.getRequestContext().addUIComponentToUpdateByAjax(uiDocNodeListChild); } catch(ItemNotFoundException nu) { uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.null-exception", null, ApplicationMessage.WARNING)) ; return ; } catch(PathNotFoundException pa) { uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.path-not-found", null, ApplicationMessage.WARNING)) ; return ; } catch(AccessDeniedException ace) { uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.access-denied", null, ApplicationMessage.WARNING)) ; return ; } catch(RepositoryException e) { if (LOG.isErrorEnabled()) { LOG.error("Repository cannot be found"); } uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.repository-error", null, ApplicationMessage.WARNING)) ; return ; } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } } } public static class ManageVersionsActionListener extends EventListener<UIDocumentNodeList> { public void execute(Event<UIDocumentNodeList> event) throws Exception { NodeFinder nodeFinder = event.getSource().getApplicationComponent(NodeFinder.class); UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); UIPopupContainer UIPopupContainer = uiExplorer.getChild(UIPopupContainer.class); String uri = event.getRequestContext().getRequestParameter(OBJECTID); String workspaceName = event.getRequestContext().getRequestParameter("workspaceName"); // Manage ../ and ./ uri = LinkUtils.evaluatePath(uri); // Just in order to check if the node exists Node currentNode = (Node)nodeFinder.getItem(workspaceName, uri); uiExplorer.setIsHidePopup(false); if (currentNode.canAddMixin(Utils.MIX_VERSIONABLE)) { UIPopupContainer.activate(UIActivateVersion.class, 400); event.getRequestContext().addUIComponentToUpdateByAjax(UIPopupContainer); } else if (currentNode.isNodeType(Utils.MIX_VERSIONABLE)) { UIWorkingArea uiWorkingArea = uiExplorer.getChild(UIWorkingArea.class); UIDocumentWorkspace uiDocumentWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class); UIVersionInfo uiVersionInfo = uiDocumentWorkspace.getChild(UIVersionInfo.class); uiVersionInfo.setCurrentNode(currentNode); uiVersionInfo.setRootOwner(currentNode.getProperty("exo:lastModifier").getString()); uiVersionInfo.activate(); uiDocumentWorkspace.setRenderedChild(UIVersionInfo.class); event.getRequestContext().addUIComponentToUpdateByAjax(uiDocumentWorkspace); } } } public static class MoreActionListener extends EventListener<UIDocumentNodeList> { public void execute(Event<UIDocumentNodeList> event) throws Exception { UIDocumentNodeList uicomp = event.getSource(); UIApplication uiApp = uicomp.getAncestorOfType(UIApplication.class); try { int currentPage = uicomp.dataList_.size() / uicomp.pageIterator_.getPageList().getPageSize(); uicomp.dataList_.addAll(uicomp.pageIterator_.getPageList().getPage(currentPage + 1)); event.getRequestContext().addUIComponentToUpdateByAjax(uicomp); } catch(AccessDeniedException ace) { uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.access-denied", null, ApplicationMessage.WARNING)) ; return ; } catch(RepositoryException e) { if (LOG.isErrorEnabled()) { LOG.error("Repository cannot be found"); } uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.repository-error", null, ApplicationMessage.WARNING)) ; return ; } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } } } }
20,134
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDocumentWithTree.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIDocumentWithTree.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.explorer; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Oct 15, 2007 10:10:03 AM */ @ComponentConfig( events = { @EventConfig(listeners = UIDocumentInfo.ChangeNodeActionListener.class), @EventConfig(listeners = UIDocumentInfo.ViewNodeActionListener.class), @EventConfig(listeners = UIDocumentInfo.SortActionListener.class), @EventConfig(listeners = UIDocumentInfo.VoteActionListener.class), @EventConfig(listeners = UIDocumentInfo.ChangeLanguageActionListener.class), @EventConfig(listeners = UIDocumentInfo.DownloadActionListener.class), @EventConfig(listeners = UIDocumentInfo.ShowPageActionListener.class) } ) public class UIDocumentWithTree extends UIDocumentInfo { public UIDocumentWithTree() throws Exception { getChildById(CONTENT_PAGE_ITERATOR_ID).setId("PageIteratorWithTreeView"); getChildById(CONTENT_TODAY_PAGE_ITERATOR_ID).setId("TodayPageIteratorWithTreeView"); getChildById(CONTENT_YESTERDAY_PAGE_ITERATOR_ID).setId("YesterdayPageIteratorWithTreeView"); getChildById(CONTENT_WEEK_PAGE_ITERATOR_ID).setId("WeekPageIteratorWithTreeView"); getChildById(CONTENT_MONTH_PAGE_ITERATOR_ID).setId("MonthPageIteratorWithTreeView"); getChildById(CONTENT_YEAR_PAGE_ITERATOR_ID).setId("YearPageIteratorWithTreeView"); getChild(UIDocumentNodeList.class).setId("UIDocumentNodeListWithTreeView"); } public String getTemplate() { UIJCRExplorer uiExplorer = getAncestorOfType(UIJCRExplorer.class) ; return uiExplorer.getDocumentInfoTemplate(); } }
2,525
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DocumentProviderUtils.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/DocumentProviderUtils.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.component.explorer; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeIterator; import javax.jcr.nodetype.NodeTypeManager; import javax.jcr.query.Query; import javax.jcr.query.Row; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecms.legacy.search.data.SearchResult; import org.exoplatform.ecm.jcr.model.Preference; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.documents.DocumentTypeService; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.cms.link.NodeLinkAware; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.search.base.LazyPageList; import org.exoplatform.services.wcm.search.base.PageListFactory; import org.exoplatform.services.wcm.search.base.QueryData; import org.exoplatform.services.wcm.search.base.SearchDataCreator; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Created by The eXo Platform SARL * Author : Nguyen Anh Vu * anhvurz90@gmail.com * Nov 9, 2009 * 1:48:20 PM */ public class DocumentProviderUtils { private static final String Contents_Document_Type = "Content"; private static final String FAVORITE_ALIAS = "userPrivateFavorites"; private static final Log LOG = ExoLogger.getLogger(DocumentProviderUtils.class.getName()); private static final String[] prohibitedSortType = { NodetypeConstant.SORT_BY_NODESIZE, NodetypeConstant.SORT_BY_NODETYPE, NodetypeConstant.SORT_BY_DATE, }; private static DocumentProviderUtils docProviderUtil_ = new DocumentProviderUtils(); private List<String> folderTypes_; private DocumentProviderUtils() { } public static DocumentProviderUtils getInstance() { return docProviderUtil_; } public boolean canSortType(String sortType) { for (String type : prohibitedSortType) { if (type.equals(sortType)) { return false; } } return true; } public <E> LazyPageList<E> getPageList(String ws, String path, Preference pref, Set<String> allItemFilter, Set<String> allItemByTypeFilter, SearchDataCreator<E> dataCreater) throws Exception{ String statement = getStatement(ws, path, pref, allItemFilter, allItemByTypeFilter); QueryData queryData = new QueryData(statement, ws, Query.SQL, WCMCoreUtils.getRemoteUser().equals(WCMCoreUtils.getSuperUser())); return PageListFactory.createLazyPageList(queryData, pref.getNodesPerPage(),dataCreater); } public LazyPageList<NodeLinkAware> getPageList(String ws, String path, Preference pref, Set<String> allItemFilter, Set<String> allItemByTypeFilter, NodeLinkAware parent) throws Exception { LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class); NodeFinder nodeFinder = WCMCoreUtils.getService(NodeFinder.class); String statement; try { Node node = (Node)nodeFinder.getItem(ws, path); if (linkManager.isLink(node)) { path = linkManager.getTarget(node).getPath(); }else{ path = node.getPath(); } statement = getStatement(ws, path, pref, allItemFilter, allItemByTypeFilter); } catch (Exception e) { statement = null; } QueryData queryData = new QueryData(statement, ws, Query.SQL, WCMCoreUtils.getRemoteUser().equals(WCMCoreUtils.getSuperUser())); return PageListFactory.createLazyPageList(queryData, pref.getNodesPerPage(), new NodeLinkAwareCreator(parent)); } private String getStatement(String ws, String path, Preference pref, Set<String> allItemsFilterSet, Set<String> allItemsByTypeFilter) throws Exception { StringBuilder buf = new StringBuilder(); //path buf = addPathParam(buf, path); //jcrEnable buf = addJcrEnableParam(buf, ws, path, pref); //show non document buf = addShowNonDocumentType(buf, pref, allItemsByTypeFilter); //show hidden node buf = addShowHiddenNodeParam(buf, pref); //owned by me buf = addOwnedByMeParam(buf, allItemsFilterSet); //favorite buf = addFavoriteParam(buf, ws, allItemsFilterSet); //all items by type buf = addAllItemByType(buf, allItemsByTypeFilter); //sort buf = addSortParam(buf, pref); return (buf == null) ? null : buf.toString(); } /** * add path condition to query statement */ private StringBuilder addPathParam(StringBuilder buf, String path) { buf.append("SELECT * FROM nt:base "); if (path != null) { if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } buf.append("WHERE jcr:path LIKE '").append(path) .append("/%' AND NOT jcr:path LIKE '").append(path).append("/%/%' "); } return buf; } /** * add is_jcr_enable condition to query statement */ private StringBuilder addJcrEnableParam(StringBuilder buf, String ws, String path, Preference pref) throws Exception { TemplateService templateService = WCMCoreUtils.getService(TemplateService.class); SessionProvider provider = WCMCoreUtils.getUserSessionProvider(); Session session = provider.getSession(ws, WCMCoreUtils.getRepository()); Node node = (Node)session.getItem(path); if(!pref.isJcrEnable() && templateService.isManagedNodeType(node.getPrimaryNodeType().getName()) && !(node.isNodeType(NodetypeConstant.NT_FOLDER) || node.isNodeType(NodetypeConstant.NT_UNSTRUCTURED) )) { return null; } return buf; } /** * add show_non_document_type condition to query statement */ private StringBuilder addShowNonDocumentType(StringBuilder buf, Preference pref, Set<String> allItemsByTypeFilter) throws Exception { if (buf == null) return null; if (!pref.isShowNonDocumentType() || allItemsByTypeFilter.contains(Contents_Document_Type)) { if (folderTypes_ == null) { folderTypes_ = getFolderTypes(); } buf.append(" AND ("); //nt:unstructured && nt:folder buf.append("( jcr:primaryType='").append(Utils.NT_UNSTRUCTURED) .append("') OR (exo:primaryType='").append(Utils.NT_UNSTRUCTURED).append("') "); buf.append(" OR ( jcr:primaryType='").append(Utils.NT_FOLDER) .append("') OR (exo:primaryType='").append(Utils.NT_FOLDER).append("') "); //supertype of nt:unstructured or nt:folder for (String fType : folderTypes_) { buf.append(" OR ( jcr:primaryType='").append(fType) .append("') OR (exo:primaryType='").append(fType).append("') "); } //all document type TemplateService templateService = WCMCoreUtils.getService(TemplateService.class); List<String> docTypes = templateService.getDocumentTemplates(); for (String docType : docTypes) { buf.append(" OR ( jcr:primaryType='").append(docType) .append("') OR (exo:primaryType='").append(docType).append("') "); } buf.append(" ) "); } return buf; } private List<String> getFolderTypes() { List<String> ret = new ArrayList<String>(); NodeTypeManager nodeTypeManager = WCMCoreUtils.getRepository().getNodeTypeManager(); try { for (NodeTypeIterator iter = nodeTypeManager.getAllNodeTypes(); iter.hasNext();) { NodeType type = iter.nextNodeType(); if (type.isNodeType(NodetypeConstant.NT_FOLDER) || type.isNodeType(NodetypeConstant.NT_UNSTRUCTURED)) { ret.add(type.getName()); } } } catch (RepositoryException e) { if (LOG.isWarnEnabled()) { LOG.warn("Can not get all node types", e.getMessage()); } } return ret; } /** * add show_hidden_node condition to query statement */ private StringBuilder addShowHiddenNodeParam(StringBuilder buf, Preference pref) { if (buf == null) return null; if (!pref.isShowHiddenNode()) { buf.append(" AND ( NOT jcr:mixinTypes='").append(NodetypeConstant.EXO_HIDDENABLE).append("')"); } return buf; } /** * add owned_by_me condition to query statement */ private StringBuilder addOwnedByMeParam(StringBuilder buf, Set<String> allItemsFilterSet) { if (buf == null) return null; if (allItemsFilterSet.contains(NodetypeConstant.OWNED_BY_ME)) { buf.append(" AND ( exo:owner='") .append(ConversationState.getCurrent().getIdentity().getUserId()) .append("')"); } return buf; } /** * add favorite condition to query statement * @throws Exception */ private StringBuilder addFavoriteParam(StringBuilder buf, String ws, Set<String> allItemsFilterSet) throws Exception { if (buf == null) return null; if (allItemsFilterSet.contains(NodetypeConstant.FAVORITE)) { NodeHierarchyCreator nodeHierarchyCreator = WCMCoreUtils.getService(NodeHierarchyCreator.class); Node userNode = nodeHierarchyCreator.getUserNode(WCMCoreUtils.getSystemSessionProvider(), ConversationState.getCurrent().getIdentity().getUserId()); String favoritePath = nodeHierarchyCreator.getJcrPath(FAVORITE_ALIAS); int count = 0; buf.append(" AND ("); for (NodeIterator iter = userNode.getNode(favoritePath).getNodes();iter.hasNext();) { Node node = iter.nextNode(); if (node.isNodeType(NodetypeConstant.EXO_SYMLINK) && node.hasProperty(NodetypeConstant.EXO_WORKSPACE) && ws.equals(node.getProperty(NodetypeConstant.EXO_WORKSPACE).getString())) { if (count ++ > 0) { buf.append(" OR "); } buf.append(" jcr:uuid='") .append(node.getProperty("exo:uuid").getString()) .append("'"); } } buf.append(" ) "); if (count == 0) { return null; } } return buf; } /** * add mimetype condition to query statement */ private StringBuilder addAllItemByType(StringBuilder buf, Set<String> allItemsByTypeFilterSet) { if(allItemsByTypeFilterSet.isEmpty()) { return buf; } DocumentTypeService documentTypeService = WCMCoreUtils.getService(DocumentTypeService.class); StringBuilder buf1 = new StringBuilder(" AND ("); int count = 0; for (String documentType : allItemsByTypeFilterSet) { for (String mimeType : documentTypeService.getMimeTypes(documentType)) { if (count++ > 0) { buf1.append(" OR "); } if (mimeType.endsWith("/")) { mimeType = mimeType.substring(0, mimeType.length() - 1); } buf1.append(" 'jcr:content/jcr:mimeType' like '").append(mimeType).append("/%'"); } } buf1.append(" )"); if (count > 0) { buf.append(buf1); } return buf; } /** * adds 'sort by' condition to query statement */ private StringBuilder addSortParam(StringBuilder buf, Preference pref) { if (buf == null) return null; String type = ""; if (NodetypeConstant.SORT_BY_NODENAME.equals(pref.getSortType())) { type="exo:name"; } else if (NodetypeConstant.SORT_BY_CREATED_DATE.equals(pref.getSortType())) { type = NodetypeConstant.EXO_DATE_CREATED; } else if (NodetypeConstant.SORT_BY_MODIFIED_DATE.equals(pref.getSortType())) { type = NodetypeConstant.EXO_LAST_MODIFIED_DATE; } else { type= pref.getSortType(); } buf.append(" ORDER BY ").append(type).append(" "); buf.append("Ascending".equals(pref.getOrder()) ? "ASC" : "DESC"); return buf; } /** * Simple data creator, just creates the node result itself */ public class NodeLinkAwareCreator implements SearchDataCreator<NodeLinkAware> { private NodeLinkAware parent; public NodeLinkAwareCreator(NodeLinkAware parent) { this.parent = parent; } @Override public NodeLinkAware createData(Node node, Row row, SearchResult searchResult) { try { if (parent.hasNode(node.getName())) { return (NodeLinkAware) parent.getNode(StringUtils.substringAfterLast(node.getPath(), "/")); } } catch (RepositoryException e) { LOG.error("Can not create NodeLinkAware", e); } return null; } } }
13,808
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIConfirmMessage.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIConfirmMessage.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.explorer; import org.exoplatform.ecm.webui.component.explorer.rightclick.manager.DeleteManageComponent; 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.UIPopupComponent; import org.exoplatform.webui.core.UIPopupWindow; 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 * Sep 18, 2008 9:52:55 AM */ @ComponentConfig( template = "classpath:groovy/ecm/webui/UIConfirmMessage.gtmpl", events = { @EventConfig(listeners = UIConfirmMessage.OKActionListener.class), @EventConfig(listeners = UIConfirmMessage.CloseActionListener.class) } ) public class UIConfirmMessage extends UIComponent implements UIPopupComponent { private String messageKey_; private String[] args_ = {}; protected boolean isOK_ = false; protected String nodePath_; private boolean isNodeInTrash = false; public UIConfirmMessage() throws Exception { } public void setMessageKey(String messageKey) { messageKey_ = messageKey; } public String getMessageKey() { return messageKey_; } public void setArguments(String[] args) { args_ = args; } public String[] getArguments() { return args_; } public boolean isOK() { return isOK_; } public void setNodePath(String nodePath) { nodePath_ = nodePath; } public String[] getActions() { return new String[] {"OK", "Close"}; } public boolean isNodeInTrash() { return isNodeInTrash; } public void setNodeInTrash(boolean isNodeInTrash) { this.isNodeInTrash = isNodeInTrash; } static public class OKActionListener extends EventListener<UIConfirmMessage> { public void execute(Event<UIConfirmMessage> event) throws Exception { UIConfirmMessage uiConfirm = event.getSource(); UIJCRExplorer uiExplorer = uiConfirm.getAncestorOfType(UIJCRExplorer.class); UIWorkingArea uiWorkingArea = uiExplorer.getChild(UIWorkingArea.class); if (uiConfirm.isNodeInTrash()) { uiWorkingArea.getChild(DeleteManageComponent.class).doDeleteWithoutTrash(uiConfirm.nodePath_, event); } else { uiWorkingArea.getChild(DeleteManageComponent.class).doDelete(uiConfirm.nodePath_, event); } uiConfirm.isOK_ = true; UIPopupWindow popupAction = uiConfirm.getAncestorOfType(UIPopupWindow.class) ; popupAction.setShow(false) ; event.getRequestContext().addUIComponentToUpdateByAjax(popupAction); } } static public class CloseActionListener extends EventListener<UIConfirmMessage> { public void execute(Event<UIConfirmMessage> event) throws Exception { UIConfirmMessage uiConfirm = event.getSource(); uiConfirm.isOK_ = false; UIPopupWindow popupAction = uiConfirm.getAncestorOfType(UIPopupWindow.class) ; popupAction.setShow(false) ; event.getRequestContext().addUIComponentToUpdateByAjax(popupAction); event.getRequestContext().getJavascriptManager().require("SHARED/uiFileView", "uiFileView"). addScripts("uiFileView.UIFileView.clearCheckboxes();"); } } public void activate() { } public void deActivate() { } }
4,211
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDocumentContainer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIDocumentContainer.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.explorer; import java.util.ArrayList; import java.util.List; import org.exoplatform.ecm.webui.component.explorer.optionblocks.UIOptionBlockPanel; import org.exoplatform.services.cms.templates.TemplateService; 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.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.ext.UIExtension; import org.exoplatform.webui.ext.UIExtensionManager; import javax.jcr.Node; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Oct 15, 2007 10:05:43 AM */ @ComponentConfig( template = "app:/groovy/webui/component/explorer/UIDocumentTabPane.gtmpl", events = { @EventConfig(listeners = UIDocumentContainer.ChangeTabActionListener.class) } ) public class UIDocumentContainer extends UIContainer { private String OPTION_BLOCK_EXTENSION_TYPE = "org.exoplatform.ecm.dms.UIOptionBlockPanel"; private List<UIComponent> listExtenstion = new ArrayList<UIComponent>(); private boolean isDisplayOptionPanel = false; public UIDocumentContainer() throws Exception { addChild(UIDocumentWithTree.class, null, null) ; addChild(UIDocumentInfo.class, null, null) ; this.initOptionBlockPanel(); } public boolean isShowViewFile() throws Exception { return getAncestorOfType(UIJCRExplorer.class).isShowViewFile() ; } public boolean isJcrEnable() { return getAncestorOfType(UIJCRExplorer.class).getPreference().isJcrEnable() ; } public boolean isDocumentNode() { try { Node currentNode = this.getAncestorOfType(UIJCRExplorer.class).getCurrentNode(); TemplateService templateService = WCMCoreUtils.getService(TemplateService.class); List<String> documentNodeTypes = templateService.getAllDocumentNodeTypes(); if(documentNodeTypes.contains(currentNode.getPrimaryNodeType().getName())) return true; return false; } catch(Exception ex) { return false; } } public static class ChangeTabActionListener extends EventListener<UIDocumentContainer> { public void execute(Event<UIDocumentContainer> event) throws Exception { UIDocumentContainer uiDocumentContainer = event.getSource(); String selectedTabName = event.getRequestContext().getRequestParameter(OBJECTID); UIDocumentWithTree uiDocTree = uiDocumentContainer.getChild(UIDocumentWithTree.class); uiDocTree.setRendered(uiDocTree.getId().equals(selectedTabName)); UIDocumentInfo uiDocInfo = uiDocumentContainer.getChildById(UIDocumentInfo.class.getSimpleName()); uiDocInfo.setRendered(uiDocInfo.getId().equals(selectedTabName)); UIJCRExplorer uiExplorer = uiDocumentContainer.getAncestorOfType(UIJCRExplorer.class); uiExplorer.setShowDocumentViewForFile(uiDocInfo.getId().equals(selectedTabName)); event.getRequestContext().addUIComponentToUpdateByAjax(uiDocumentContainer); uiExplorer.updateAjax(event); } } /* * * This method get Option Block Panel extenstion and add it into this * * */ public void addOptionBlockPanel() throws Exception { UIExtensionManager manager = getApplicationComponent(UIExtensionManager.class); List<UIExtension> extensions = manager.getUIExtensions(OPTION_BLOCK_EXTENSION_TYPE); for (UIExtension extension : extensions) { UIComponent uicomp = manager.addUIExtension(extension, null, this); uicomp.setRendered(false); listExtenstion.add(uicomp); } } /* * This method checks and returns true if the Option Block Panel is configured to display, else it returns false * */ public boolean isHasOptionBlockPanel() { UIExtensionManager manager = getApplicationComponent(UIExtensionManager.class); List<UIExtension> extensions = manager.getUIExtensions(OPTION_BLOCK_EXTENSION_TYPE); if(extensions != null) { return true; } return false; } public void setDisplayOptionBlockPanel(boolean display) { for(UIComponent uicomp : listExtenstion) { uicomp.setRendered(display); } isDisplayOptionPanel = display; } public boolean isDisplayOptionBlockPanel() { return isDisplayOptionPanel; } public void initOptionBlockPanel() throws Exception { if(isHasOptionBlockPanel()) { addOptionBlockPanel(); UIOptionBlockPanel optionBlockPanel = this.getChild(UIOptionBlockPanel.class); if(optionBlockPanel.isHasOptionBlockExtension()) { optionBlockPanel.addOptionBlockExtension(); setDisplayOptionBlockPanel(true); } } } }
5,651
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIJcrExplorerEditForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIJcrExplorerEditForm.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.explorer; import java.util.ArrayList; import java.util.List; import javax.portlet.PortletPreferences; import org.exoplatform.ecm.webui.form.UIFormInputSetWithAction; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.services.cms.drives.DriveData; 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.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.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.input.UICheckBoxInput; /** * Created by The eXo Platform SARL * Author : Ly Dinh Quang * quang.ly@exoplatform.com * 3 févr. 09 */ @ComponentConfig(lifecycle = UIFormLifecycle.class, template = "system:/groovy/webui/form/UIFormWithTitle.gtmpl", events = { @EventConfig(phase = Phase.DECODE, listeners = UIJcrExplorerEditForm.SaveActionListener.class), @EventConfig(phase = Phase.DECODE, listeners = UIJcrExplorerEditForm.CancelActionListener.class), @EventConfig(phase = Phase.DECODE, listeners = UIJcrExplorerEditForm.SelectTypeActionListener.class), @EventConfig(phase = Phase.DECODE, listeners = UIJcrExplorerEditForm.SelectDriveActionListener.class), @EventConfig(phase = Phase.DECODE, listeners = UIJcrExplorerEditForm.SelectNodePathActionListener.class) } ) public class UIJcrExplorerEditForm extends UIForm implements UISelectable { private boolean flagSelectRender = false; public static final String PARAM_PATH_ACTION = "SelectNodePath"; public static final String PARAM_PATH_INPUT = "nodePath"; private static final String POPUP_SELECT_PATH_INPUT = "PopupSelectPath"; public UIJcrExplorerEditForm() throws Exception { List<SelectItemOption<String>> listType = new ArrayList<SelectItemOption<String>>(); String usecase = getPreference().getValue(UIJCRExplorerPortlet.USECASE, ""); listType.add(new SelectItemOption<String>("Selection", "selection")); listType.add(new SelectItemOption<String>("Jailed", "jailed")); listType.add(new SelectItemOption<String>("Personal", "personal")); listType.add(new SelectItemOption<String>("Parameterize", "parameterize")); UIFormSelectBox typeSelectBox = new UIFormSelectBox(UIJCRExplorerPortlet.USECASE, UIJCRExplorerPortlet.USECASE, listType); typeSelectBox.setValue(usecase); typeSelectBox.setOnChange("SelectType"); addChild(typeSelectBox); UIFormInputSetWithAction driveNameInput = new UIFormInputSetWithAction("DriveNameInput"); UIFormStringInput stringInputDrive = new UIFormStringInput(UIJCRExplorerPortlet.DRIVE_NAME, UIJCRExplorerPortlet.DRIVE_NAME, null); stringInputDrive.setValue(getPreference().getValue(UIJCRExplorerPortlet.DRIVE_NAME, "")); stringInputDrive.setDisabled(true); driveNameInput.addUIFormInput(stringInputDrive); driveNameInput.setActionInfo(UIJCRExplorerPortlet.DRIVE_NAME, new String[] {"SelectDrive"}); addUIComponentInput(driveNameInput); UIFormInputSetWithAction uiParamPathInput = new UIFormInputSetWithAction(PARAM_PATH_ACTION); UIFormStringInput pathInput = new UIFormStringInput(UIJCRExplorerPortlet.PARAMETERIZE_PATH, UIJCRExplorerPortlet.PARAMETERIZE_PATH, null); pathInput.setValue(getPreference().getValue(UIJCRExplorerPortlet.PARAMETERIZE_PATH, "")); pathInput.setDisabled(true); uiParamPathInput.addUIFormInput(pathInput); uiParamPathInput.setActionInfo(UIJCRExplorerPortlet.PARAMETERIZE_PATH, new String[] {PARAM_PATH_ACTION}); addUIComponentInput(uiParamPathInput); driveNameInput.setRendered(true); uiParamPathInput.setRendered(false); UICheckBoxInput uiFormCheckBoxTop = new UICheckBoxInput(UIJCRExplorerPortlet.SHOW_TOP_BAR, UIJCRExplorerPortlet.SHOW_TOP_BAR, true); uiFormCheckBoxTop.setChecked(Boolean.parseBoolean(getPreference().getValue(UIJCRExplorerPortlet.SHOW_TOP_BAR, "true"))); addUIFormInput(uiFormCheckBoxTop); UICheckBoxInput uiFormCheckBoxAction = new UICheckBoxInput(UIJCRExplorerPortlet.SHOW_ACTION_BAR, UIJCRExplorerPortlet.SHOW_ACTION_BAR, true); uiFormCheckBoxAction.setChecked(Boolean.parseBoolean(getPreference().getValue(UIJCRExplorerPortlet.SHOW_ACTION_BAR, "true"))); addUIFormInput(uiFormCheckBoxAction); UICheckBoxInput uiFormCheckBoxSide = new UICheckBoxInput(UIJCRExplorerPortlet.SHOW_SIDE_BAR, UIJCRExplorerPortlet.SHOW_SIDE_BAR, true); uiFormCheckBoxSide.setChecked(Boolean.parseBoolean(getPreference().getValue(UIJCRExplorerPortlet.SHOW_SIDE_BAR, "true"))); addUIFormInput(uiFormCheckBoxSide); UICheckBoxInput uiFormCheckBoxFilter = new UICheckBoxInput(UIJCRExplorerPortlet.SHOW_FILTER_BAR, UIJCRExplorerPortlet.SHOW_FILTER_BAR, true); uiFormCheckBoxFilter.setChecked(Boolean.parseBoolean(getPreference().getValue(UIJCRExplorerPortlet.SHOW_FILTER_BAR, "true"))); addUIFormInput(uiFormCheckBoxFilter); if(usecase.equals(UIJCRExplorerPortlet.PERSONAL)) { driveNameInput.setRendered(false); } else if (usecase.equals(UIJCRExplorerPortlet.PARAMETERIZE)) { uiParamPathInput.setRendered(true); } setActions(new String[] {"Save", "Cancel"}); } public boolean isFlagSelectRender() { return flagSelectRender; } public void setFlagSelectRender(boolean flagSelectRender) { this.flagSelectRender = flagSelectRender; } private PortletPreferences getPreference() { PortletRequestContext pcontext = (PortletRequestContext)WebuiRequestContext.getCurrentInstance(); return pcontext.getRequest().getPreferences(); } public static class CancelActionListener extends EventListener<UIJcrExplorerEditForm>{ public void execute(Event<UIJcrExplorerEditForm> event) throws Exception { UIJcrExplorerEditForm uiForm = event.getSource(); PortletPreferences pref = uiForm.getPreference(); UIFormSelectBox typeSelectBox = uiForm.getChildById(UIJCRExplorerPortlet.USECASE); typeSelectBox.setValue(pref.getValue(UIJCRExplorerPortlet.USECASE, "")); UIFormInputSetWithAction driveNameInput = uiForm.getChildById("DriveNameInput"); UIFormStringInput stringInputDrive = driveNameInput.getUIStringInput(UIJCRExplorerPortlet.DRIVE_NAME); stringInputDrive.setValue(pref.getValue(UIJCRExplorerPortlet.DRIVE_NAME, "")); UICheckBoxInput checkBoxShowTopBar = uiForm.getChildById(UIJCRExplorerPortlet.SHOW_TOP_BAR); checkBoxShowTopBar.setChecked(Boolean.parseBoolean(pref.getValue(UIJCRExplorerPortlet.SHOW_TOP_BAR, "true"))); UICheckBoxInput checkBoxShowActionBar = uiForm.getChildById(UIJCRExplorerPortlet.SHOW_ACTION_BAR); checkBoxShowActionBar.setChecked(Boolean.parseBoolean(pref.getValue(UIJCRExplorerPortlet.SHOW_ACTION_BAR, "true"))); UICheckBoxInput checkBoxShowLeftBar = uiForm.getChildById(UIJCRExplorerPortlet.SHOW_SIDE_BAR); checkBoxShowLeftBar.setChecked(Boolean.parseBoolean(pref.getValue(UIJCRExplorerPortlet.SHOW_SIDE_BAR, "true"))); UICheckBoxInput checkBoxShowFilterBar = uiForm.getChildById(UIJCRExplorerPortlet.SHOW_FILTER_BAR); checkBoxShowFilterBar.setChecked(Boolean.parseBoolean(pref.getValue(UIJCRExplorerPortlet.SHOW_FILTER_BAR, "true"))); // update UIFormInputSetWithAction uiParamPathInput = uiForm.getChildById(PARAM_PATH_ACTION); UIFormStringInput stringInputPath = uiParamPathInput.getUIStringInput(UIJCRExplorerPortlet.PARAMETERIZE_PATH); stringInputPath.setValue(pref.getValue(UIJCRExplorerPortlet.PARAMETERIZE_PATH, "")); if (pref.getValue(UIJCRExplorerPortlet.USECASE, "").equals(UIJCRExplorerPortlet.JAILED)) { driveNameInput.setRendered(true); uiParamPathInput.setRendered(false); } else if (pref.getValue(UIJCRExplorerPortlet.USECASE, "").equals(UIJCRExplorerPortlet.PARAMETERIZE)) { driveNameInput.setRendered(true); uiParamPathInput.setRendered(true); } else { driveNameInput.setRendered(false); uiParamPathInput.setRendered(false); } UIApplication uiApp = uiForm.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIJcrExplorerEditForm.msg.fields-cancelled", null)); event.getRequestContext().addUIComponentToUpdateByAjax(uiForm); } } public static class SelectTypeActionListener extends EventListener<UIJcrExplorerEditForm>{ public void execute(Event<UIJcrExplorerEditForm> event) throws Exception { UIJcrExplorerEditForm uiForm = event.getSource(); UIJCRExplorerPortlet uiJExplorerPortlet = uiForm.getAncestorOfType(UIJCRExplorerPortlet.class); UIFormSelectBox typeSelectBox = uiForm.getChildById(UIJCRExplorerPortlet.USECASE); UIFormInputSetWithAction driveNameInput = uiForm.getChildById("DriveNameInput"); UIFormInputSetWithAction uiParamPathInput = uiForm.getChildById(PARAM_PATH_ACTION); driveNameInput.setRendered(true); uiParamPathInput.setRendered(false); if (typeSelectBox.getValue().equals(UIJCRExplorerPortlet.JAILED)) { UIFormStringInput stringInputDrive = driveNameInput.getUIStringInput(UIJCRExplorerPortlet.DRIVE_NAME); stringInputDrive.setRendered(true); stringInputDrive.setValue(""); driveNameInput.setRendered(true); } else if(typeSelectBox.getValue().equals(UIJCRExplorerPortlet.SELECTION)) { UIFormStringInput stringInputDrive = driveNameInput.getUIStringInput(UIJCRExplorerPortlet.DRIVE_NAME); if(stringInputDrive.isRendered()) stringInputDrive.setRendered(false); } else if(typeSelectBox.getValue().equals(UIJCRExplorerPortlet.PERSONAL)) { DriveData personalPrivateDrive = uiJExplorerPortlet.getUserDrive(); UIFormStringInput stringInputDrive = driveNameInput.getUIStringInput(UIJCRExplorerPortlet.DRIVE_NAME); stringInputDrive.setRendered(true); stringInputDrive.setValue(personalPrivateDrive.getName()); driveNameInput.setRendered(false); UIApplication uiApp = uiForm.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIJcrExplorerEditForm.msg.personal-usecase", null)); } else if(typeSelectBox.getValue().equals(UIJCRExplorerPortlet.PARAMETERIZE)) { UIFormStringInput stringInputDrive = driveNameInput.getUIStringInput(UIJCRExplorerPortlet.DRIVE_NAME); stringInputDrive.setRendered(true); stringInputDrive.setValue(""); driveNameInput.setRendered(true); UIFormStringInput stringInputDrivePath = uiParamPathInput.getUIStringInput(UIJCRExplorerPortlet.PARAMETERIZE_PATH); stringInputDrivePath.setValue(""); uiParamPathInput.setRendered(true); } event.getRequestContext().addUIComponentToUpdateByAjax(uiForm); } } public static class SaveActionListener extends EventListener<UIJcrExplorerEditForm>{ public void execute(Event<UIJcrExplorerEditForm> event) throws Exception { UIJcrExplorerEditForm uiForm = event.getSource(); PortletPreferences pref = uiForm.getPreference(); UIFormSelectBox typeSelectBox = uiForm.getChildById(UIJCRExplorerPortlet.USECASE); UIFormInputSetWithAction driveNameInput = uiForm.getChildById("DriveNameInput"); UIFormStringInput stringInputDrive = driveNameInput.getUIStringInput(UIJCRExplorerPortlet.DRIVE_NAME); UICheckBoxInput uiFormCheckBoxTop = uiForm.getChildById(UIJCRExplorerPortlet.SHOW_TOP_BAR); UICheckBoxInput uiFormCheckBoxAction = uiForm.getChildById(UIJCRExplorerPortlet.SHOW_ACTION_BAR); UICheckBoxInput uiFormCheckBoxSide = uiForm.getChildById(UIJCRExplorerPortlet.SHOW_SIDE_BAR); UICheckBoxInput uiFormCheckBoxFilter= uiForm.getChildById(UIJCRExplorerPortlet.SHOW_FILTER_BAR); String nodePath = ((UIFormStringInput)uiForm.findComponentById(UIJCRExplorerPortlet.PARAMETERIZE_PATH)).getValue(); String driveName = stringInputDrive.getValue(); String useCase = typeSelectBox.getValue(); if (useCase.equals(UIJCRExplorerPortlet.JAILED) ) { if ((driveName == null) || (driveName.length() == 0)) { UIApplication uiApp = uiForm.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIJcrExplorerEditForm.msg.notNullDriveName", null, ApplicationMessage.WARNING)); return; } } else if (useCase.equals(UIJCRExplorerPortlet.PARAMETERIZE)) { if ((nodePath == null) || (nodePath.length() == 0)) { UIApplication uiApp = uiForm.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIJcrExplorerEditForm.msg.notNullPath", null, ApplicationMessage.WARNING)); return; } } if (useCase.equals(UIJCRExplorerPortlet.SELECTION)) { //driveName = pref.getValue("driveName", ""); nodePath = "/"; } else { // uiForm.setFlagSelectRender(true); } uiForm.setFlagSelectRender(true); pref.setValue(UIJCRExplorerPortlet.USECASE, useCase); pref.setValue(UIJCRExplorerPortlet.DRIVE_NAME, driveName); pref.setValue(UIJCRExplorerPortlet.PARAMETERIZE_PATH, nodePath); pref.setValue(UIJCRExplorerPortlet.SHOW_ACTION_BAR, String.valueOf(uiFormCheckBoxAction.getValue())); pref.setValue(UIJCRExplorerPortlet.SHOW_TOP_BAR, String.valueOf(uiFormCheckBoxTop.getValue())); pref.setValue(UIJCRExplorerPortlet.SHOW_SIDE_BAR, String.valueOf(uiFormCheckBoxSide.getValue())); pref.setValue(UIJCRExplorerPortlet.SHOW_FILTER_BAR, String.valueOf(uiFormCheckBoxFilter.getValue())); pref.store(); UIApplication uiApp = uiForm.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIJcrExplorerEditForm.msg.fields-saved", null)); event.getRequestContext().addUIComponentToUpdateByAjax(uiForm); } } public static class SelectDriveActionListener extends EventListener<UIJcrExplorerEditForm>{ public void execute(Event<UIJcrExplorerEditForm> event) throws Exception { UIJcrExplorerEditForm uiForm = event.getSource(); UIJcrExplorerEditContainer editContainer = uiForm.getParent(); UIPopupWindow popupWindow = editContainer.initPopup("PopUpSelectDrive"); UIDriveSelector driveSelector = editContainer.createUIComponent(UIDriveSelector.class, null, null); driveSelector.updateGrid(); popupWindow.setUIComponent(driveSelector); event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getParent()); } } public static class SelectNodePathActionListener extends EventListener<UIJcrExplorerEditForm>{ public void execute(Event<UIJcrExplorerEditForm> event) throws Exception { UIJcrExplorerEditForm uiForm = event.getSource(); UIJcrExplorerEditContainer editContainer = uiForm.getParent(); UIFormInputSetWithAction driveNameInput = uiForm.getChildById("DriveNameInput"); UIFormStringInput stringInputDrive = driveNameInput.getUIStringInput(UIJCRExplorerPortlet.DRIVE_NAME); String driveName = stringInputDrive.getValue(); if (driveName == null || driveName.length() == 0) { UIApplication uiApp = uiForm.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIJcrExplorerEditForm.msg.personal-usecase", null, ApplicationMessage.WARNING)); return; } editContainer.initPopupDriveBrowser(POPUP_SELECT_PATH_INPUT, driveName); event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getParent()); } } public void doSelect(String selectField, Object value) throws Exception { String stValue = null; if ("/".equals(String.valueOf(value))) { stValue = "/"; } else { if (String.valueOf(value).split(":/").length > 1) stValue = String.valueOf(value).split(":/")[1]; else stValue = "/"; } ((UIFormStringInput)findComponentById(selectField)).setValue(stValue); UIJcrExplorerEditContainer uiContainer = getParent(); for (UIComponent uiChild : uiContainer.getChildren()) { if (uiChild.getId().equals(POPUP_SELECT_PATH_INPUT)) { UIPopupWindow uiPopup = uiContainer.getChildById(uiChild.getId()); uiPopup.setRendered(false); uiPopup.setShow(false); } } } }
19,006
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIJCRExplorer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIJCRExplorer.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.explorer ; import java.net.URLDecoder; import java.security.AccessControlException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.jcr.Item; 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.NodeType; import javax.portlet.PortletPreferences; import org.exoplatform.ecm.jcr.TypeNodeComparator; import org.exoplatform.ecm.jcr.model.Preference; import org.exoplatform.ecm.resolver.JCRResourceResolver; import org.exoplatform.ecm.utils.comparator.PropertyValueComparator; import org.exoplatform.ecm.utils.lock.LockUtil; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.ecm.webui.comparator.DateComparator; import org.exoplatform.ecm.webui.comparator.NodeSizeComparator; import org.exoplatform.ecm.webui.comparator.NodeTitleComparator; import org.exoplatform.ecm.webui.comparator.StringComparator; import org.exoplatform.ecm.webui.component.explorer.control.UIActionBar; import org.exoplatform.ecm.webui.component.explorer.control.UIAddressBar; import org.exoplatform.ecm.webui.component.explorer.control.UIControl; import org.exoplatform.ecm.webui.component.explorer.popup.actions.UIDocumentForm; import org.exoplatform.ecm.webui.component.explorer.popup.actions.UIDocumentFormController; import org.exoplatform.ecm.webui.component.explorer.popup.actions.UISelectDocumentForm; import org.exoplatform.ecm.webui.component.explorer.sidebar.UISideBar; import org.exoplatform.ecm.webui.component.explorer.sidebar.UITreeExplorer; import org.exoplatform.ecm.webui.component.explorer.sidebar.UITreeNodePageIterator; import org.exoplatform.ecm.webui.utils.PermissionUtil; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.documents.TrashService; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.folksonomy.NewFolksonomyService; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.services.cms.impl.DMSRepositoryConfiguration; import org.exoplatform.services.cms.link.ItemLinkAware; import org.exoplatform.services.cms.link.LinkUtils; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.cms.link.NodeLinkAware; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.core.ExtendedNode; 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.core.NodetypeConstant; import org.exoplatform.services.wcm.utils.WCMCoreUtils; 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.core.UIApplication; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPageIterator; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; import org.exoplatform.webui.event.Event; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; /** * Created by The eXo Platform SARL * Author : nqhungvn * nguyenkequanghung@yahoo.com * July 3, 2006 * 10:07:15 AM */ @ComponentConfig(lifecycle = UIContainerLifecycle.class) public class UIJCRExplorer extends UIContainer { /** * Logger. */ private static final Log LOG = ExoLogger.getLogger(UIJCRExplorer.class.getName()); /** * The constant CONTEXT_NODE. */ public static final String CONTEXT_NODE = "UIJCRExplorer.contextNode"; private LinkedList<String> nodesHistory_ = new LinkedList<String>() ; private LinkedList<String> wsHistory_ = new LinkedList<String>(); private PortletPreferences pref_ ; private Preference preferences_; private Map<String, Integer> pageIndexHistory_ = new HashMap<String, Integer>(); private Map<String, HistoryEntry> addressPath_ = new HashMap<String, HistoryEntry>() ; private JCRResourceResolver jcrTemplateResourceResolver_ ; private String currentRootPath_ ; private String currentPath_ ; private String currentStatePath_ ; private String currentStateWorkspaceName_ ; private String lastWorkspaceName_ ; private String currentDriveRootPath_ ; private String currentDriveWorkspaceName_ ; private String currentDriveRepositoryName_ ; private String documentInfoTemplate_ ; private String language_ ; private Set<String> tagPaths_ = new HashSet<>(); private String referenceWorkspace_ ; private boolean isViewTag_; private boolean isHidePopup_; private boolean isReferenceNode_; private DriveData driveData_ ; private boolean isFilterSave_ ; private boolean isShowDocumentViewForFile_ = true; private boolean preferencesSaved_ = false; private int tagScope; private List<String> checkedSupportType = new ArrayList<String>(); private Set<String> allItemFilterMap = new HashSet<String>(); private Set<String> allItemByTypeFilterMap = new HashSet<String>(); public Set<String> getAllItemFilterMap() { return allItemFilterMap; } public Set<String> getAllItemByTypeFilterMap() { return allItemByTypeFilterMap; } public int getTagScope() { return tagScope; } public void setTagScope(int scope) { tagScope = scope; } public boolean isFilterSave() { return isFilterSave_; } public void setFilterSave(boolean isFilterSave) { isFilterSave_ = isFilterSave; } public boolean isShowDocumentViewForFile() { return isShowDocumentViewForFile_; } public void setShowDocumentViewForFile(boolean value) { isShowDocumentViewForFile_ = value; } public boolean isPreferencesSaved() { return preferencesSaved_; } public void setPreferencesSaved(boolean value) { preferencesSaved_ = value; } public boolean isAddingDocument() { UIPopupContainer uiPopupContainer = this.getChild(UIPopupContainer.class); UIPopupWindow uiPopup = uiPopupContainer.getChild(UIPopupWindow.class); UIWorkingArea uiWorkingArea = this.getChild(UIWorkingArea.class); UIDocumentWorkspace uiDocumentWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class); //check if edit with popup UIComponent uiComp = uiPopup.getUIComponent(); if (uiComp instanceof UIDocumentFormController && ((UIDocumentFormController)uiComp).isRendered()) { return ((UIDocumentFormController)uiComp).getChild(UIDocumentForm.class).isAddNew(); } //check if edit without popup if (uiDocumentWorkspace.isRendered()) { UIDocumentFormController controller = uiDocumentWorkspace.getChild(UIDocumentFormController.class); if (controller != null && controller.isRendered()) { return controller.getChild(UIDocumentForm.class).isAddNew(); } } return false; } public boolean isEditingDocument() { UIPopupContainer uiPopupContainer = this.getChild(UIPopupContainer.class); UIPopupWindow uiPopup = uiPopupContainer.getChild(UIPopupWindow.class); UIWorkingArea uiWorkingArea = this.getChild(UIWorkingArea.class); UIDocumentWorkspace uiDocumentWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class); //check if edit with popup UIComponent uiComp = uiPopup.getUIComponent(); if (uiPopup.isShow() && uiPopup.isRendered() && uiComp instanceof UIDocumentFormController && ((UIDocumentFormController)uiComp).isRendered()) { return true; } //check if edit without popup if (uiDocumentWorkspace.isRendered()) { UIDocumentFormController controller = uiDocumentWorkspace.getChild(UIDocumentFormController.class); if (controller != null && controller.isRendered()) { return true; } } return false; } public List<String> getCheckedSupportType() { return checkedSupportType; } public void setCheckedSupportType(List<String> checkedSupportType) { this.checkedSupportType = checkedSupportType; } public UIJCRExplorer() throws Exception { addChild(UIControl.class, null, null); addChild(UIWorkingArea.class, null, null); addChild(UIPopupContainer.class, null, null); UIPopupWindow uiPopup = addChild(UIPopupWindow.class, null, null); uiPopup.setId(uiPopup.getId() + "-" + UUID.randomUUID().toString().replaceAll("-", "")); PortletRequestContext pcontext = (PortletRequestContext)WebuiRequestContext.getCurrentInstance() ; pref_ = pcontext.getRequest().getPreferences(); getChild(UIWorkingArea.class).initialize(); } public String filterPath(String currentPath) throws Exception { if(LinkUtils.getDepth(currentRootPath_) == 0) return currentPath ; if(currentRootPath_.equals(currentPath_)) return "/" ; return currentPath.replaceFirst(currentRootPath_, "") ; } /** * Sets the root path */ public void setRootPath(String rootPath) { currentDriveRootPath_ = rootPath; setCurrentRootPath(rootPath); } private void setCurrentRootPath(String rootPath) { currentRootPath_ = rootPath ; } /** * @return the root node itself if it is not a link otherwise the target node (= resolve the link) */ public Node getRootNode() throws Exception { return getNodeByPath(currentRootPath_, getSystemSession()) ; } /** * @return the root path */ public String getRootPath() { return currentRootPath_; } private String getDefaultRootPath() { return "/"; } /** * @return the current node itself if it is not a link otherwise the target node (= resolve the link) */ public Node getCurrentNode() throws Exception { return getNodeByPath(currentPath_, getSession()) ; } /** * @return the current node even if it is a link (= don't resolve the link) */ public Node getRealCurrentNode() throws Exception { return getNodeByPath(currentPath_, getSession(), false); } /** * @return the virtual current path */ public String getCurrentPath() { return currentPath_ ; } /** * Sets the virtual current path */ public void setCurrentPath(String currentPath) { WebuiRequestContext ctx = WebuiRequestContext.getCurrentInstance(); if (currentPath_ == null || !currentPath_.equals(currentPath)) { isShowDocumentViewForFile_ = true; } currentPath_ = currentPath; } /** * Init UIJCRExplorer.contextNode attribute in order to use it for clouddrives. * It allows to exclude cycle dependencies on webui-explorer */ public void initContext() { WebuiRequestContext ctx = WebuiRequestContext.getCurrentInstance(); try { ctx.setAttribute(CONTEXT_NODE, getCurrentNode()); } catch (Exception e) { LOG.warn("Exception while getting the current node for saving in WebuiRequestContext", e); } } /** * Indicates if the current node is a referenced node */ public boolean isReferenceNode() { return isReferenceNode_ ; } /** * Tells that the current node is a referenced node */ public void setIsReferenceNode(boolean isReferenceNode) { isReferenceNode_ = isReferenceNode ; } /** * Sets the workspace name the referenced node */ public void setReferenceWorkspace(String referenceWorkspace) { referenceWorkspace_ = referenceWorkspace ; } public String getReferenceWorkspace() { return referenceWorkspace_ ; } private String setTargetWorkspaceProperties(String workspaceName) { if (workspaceName != null && workspaceName.length() > 0) { if (!workspaceName.equals(getCurrentDriveWorkspace())) { setIsReferenceNode(true); setReferenceWorkspace(workspaceName); setCurrentRootPath(getDefaultRootPath()); return workspaceName; } else if(isReferenceNode()) { setIsReferenceNode(false); setCurrentRootPath(currentDriveRootPath_); } } return getCurrentDriveWorkspace(); } /** * Tells to go back to the given location */ public void setBackNodePath(String previousWorkspaceName, String previousPath) throws Exception { setBackSelectNode(previousWorkspaceName, previousPath); refreshExplorer(); // Back to last pageIndex if previous path has paginator if (pageIndexHistory_.containsKey(previousPath) && hasPaginator(previousPath, previousWorkspaceName)) { UIPageIterator contentPageIterator = this.findComponentById(UIDocumentInfo.CONTENT_PAGE_ITERATOR_ID); if (contentPageIterator != null ) { // Get last pageIndex int previousPageIndex = pageIndexHistory_.get(previousPath); int avaiablePage = contentPageIterator.getAvailablePage(); previousPageIndex = (avaiablePage >= previousPageIndex)? previousPageIndex : avaiablePage; // Set last pageIndex for paginator of UIDocumentInfo contentPageIterator.setCurrentPage(previousPageIndex); // Set last pageIndex for UITreeNodePageIterator UITreeExplorer uiTreeExplorer = this.findFirstComponentOfType(UITreeExplorer.class); if (uiTreeExplorer != null) { UITreeNodePageIterator extendedPageIterator = uiTreeExplorer.getUIPageIterator(previousPath); if (extendedPageIterator != null) { extendedPageIterator.setCurrentPage(previousPageIndex); } } } } } /** * Check if node has paginator when viewing it's children. * * @param nodePath * @param workspaceName * @return * @throws Exception */ public boolean hasPaginator(String nodePath, String workspaceName) throws Exception { int nodePerPages = this.getPreference().getNodesPerPage(); Node node = getNodeByPath(nodePath, this.getSessionByWorkspace(workspaceName)); if (node != null) { return node.getNodes().getSize() > nodePerPages; } else { return false; } } public void setDriveData(DriveData driveData) { driveData_ = driveData ; } public DriveData getDriveData() { return driveData_ ; } public void setLanguage(String language) { language_ = language ; } public String getLanguage() { return language_ ; } public LinkedList<String> getNodesHistory() { return nodesHistory_ ; } public LinkedList<String> getWorkspacesHistory() { return wsHistory_; } public Collection<HistoryEntry> getHistory() { return addressPath_.values() ; } public SessionProvider getSessionProvider() { return WCMCoreUtils.getUserSessionProvider(); } public SessionProvider getSystemProvider() { return WCMCoreUtils.getSystemSessionProvider(); } /** * @return the session of the current node (= UIJCRExplorer.getCurrentNode()) */ public Session getTargetSession() throws Exception { return getCurrentNode().getSession(); } public Session getSession() throws Exception { return getSessionProvider().getSession(getWorkspaceName(), getRepository()) ; } public String getWorkspaceName() { return (isReferenceNode_ ? referenceWorkspace_ : currentDriveWorkspaceName_); } public Session getSystemSession() throws Exception { return getSystemProvider().getSession(getWorkspaceName(), getRepository()) ; } public String getDocumentInfoTemplate() { return documentInfoTemplate_ ; } public void setRenderTemplate(String template) { newJCRTemplateResourceResolver() ; documentInfoTemplate_ = template ; } public void setCurrentState() { setCurrentState(currentDriveWorkspaceName_, currentPath_); } public void setCurrentState(String currentStateWorkspaceName, String currentStatePath) { currentStateWorkspaceName_ = currentStateWorkspaceName; currentStatePath_ = currentStatePath ; } public String getCurrentStatePath() { return currentStatePath_;}; public void setCurrentStatePath(String currentStatePath) { setCurrentState(currentDriveWorkspaceName_, currentStatePath); } public Node getCurrentStateNode() throws Exception { return getNodeByPath(currentStatePath_, getSessionProvider().getSession(currentStateWorkspaceName_, getRepository())) ; } public JCRResourceResolver getJCRTemplateResourceResolver() { return jcrTemplateResourceResolver_; } public void newJCRTemplateResourceResolver() { try{ DMSConfiguration dmsConfiguration = getApplicationComponent(DMSConfiguration.class); DMSRepositoryConfiguration dmsRepoConfig = dmsConfiguration.getConfig(); String workspace = dmsRepoConfig.getSystemWorkspace(); jcrTemplateResourceResolver_ = new JCRResourceResolver(workspace) ; } catch(Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Cannot instantiate the JCRResourceResolver", e); } } } /** * Sets the repository of the current drive */ public void setRepositoryName(String repositoryName) { currentDriveRepositoryName_ = repositoryName ; } /** * @return the repository of the current drive */ public String getRepositoryName() { try { return getApplicationComponent(RepositoryService.class).getCurrentRepository().getConfiguration().getName(); } catch (RepositoryException e) { String repoName = System.getProperty("gatein.tenant.repository.name"); if (repoName!=null) return repoName; return currentDriveRepositoryName_; } } /** * Sets the workspace of the current drive */ public void setWorkspaceName(String workspaceName) { currentDriveWorkspaceName_ = workspaceName ; if (lastWorkspaceName_ == null) { setLastWorkspace(workspaceName); } } private void setLastWorkspace(String lastWorkspaceName) { lastWorkspaceName_ = lastWorkspaceName; } /** * @return the workspace of the current drive */ public String getCurrentDriveWorkspace() { return currentDriveWorkspaceName_ ; } /** * @return the workspace of the session of the current node (= UIJCRExplorer.getCurrentNode()) */ public String getCurrentWorkspace() { try { return getCurrentNode().getSession().getWorkspace().getName(); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn("The workspace of the current node cannot be found, the workspace of the drive will be used", e); } } return getCurrentDriveWorkspace(); } public ManageableRepository getRepository() throws Exception{ RepositoryService repositoryService = getApplicationComponent(RepositoryService.class) ; return repositoryService.getCurrentRepository(); } public Session getSessionByWorkspace(String wsName) throws Exception{ if(wsName == null ) return getSession() ; return getSessionProvider().getSession(wsName,getRepository()) ; } public boolean isSystemWorkspace() throws Exception { RepositoryService repositoryService = getApplicationComponent(RepositoryService.class) ; String systemWS = repositoryService.getCurrentRepository() .getConfiguration() .getSystemWorkspaceName(); if(getCurrentWorkspace().equals(systemWS)) return true ; return false ; } public void refreshExplorer() throws Exception { refreshExplorer(null, true); } public void refreshExplorerWithoutClosingPopup() throws Exception { refreshExplorer(null, false); } public void setPathToAddressBar(String path) throws Exception { findFirstComponentOfType(UIAddressBar.class).getUIStringInput( UIAddressBar.FIELD_ADDRESS).setValue(Text.unescapeIllegalJcrChars(filterPath(path))) ; findFirstComponentOfType(UIAddressBar.class).getUIInput( UIAddressBar.FIELD_ADDRESS_HIDDEN).setValue(filterPath(path)) ; } private void refreshExplorer(Node currentNode) throws Exception { refreshExplorer(currentNode, true); } public void refreshExplorer(Node currentNode, boolean closePopup) throws Exception { try { Node nodeGet = currentNode == null ? getCurrentNode() : currentNode; if(nodeGet.hasProperty(Utils.EXO_LANGUAGE)) { setLanguage(nodeGet.getProperty(Utils.EXO_LANGUAGE).getValue().getString()); } } catch(PathNotFoundException path) { if (LOG.isErrorEnabled()) { LOG.error("The node cannot be found ", path); } setCurrentPath(currentRootPath_); } findFirstComponentOfType(UIAddressBar.class).getUIStringInput(UIAddressBar.FIELD_ADDRESS). setValue(Text.unescapeIllegalJcrChars(filterPath(currentPath_))) ; findFirstComponentOfType(UIAddressBar.class).getUIInput(UIAddressBar.FIELD_ADDRESS_HIDDEN). setValue(filterPath(currentPath_)) ; UIWorkingArea uiWorkingArea = getChild(UIWorkingArea.class); UIDocumentWorkspace uiDocumentWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class); UIDocumentContainer uiDocumentContainer = uiDocumentWorkspace.getChild(UIDocumentContainer.class); UIDocumentWithTree uiDocumentWithTree = uiDocumentContainer.getChildById("UIDocumentWithTree"); UIDocumentInfo uiDocumentInfo = uiDocumentContainer.getChildById("UIDocumentInfo") ; uiDocumentInfo.updatePageListData(); if(uiDocumentWorkspace.isRendered()) { if (uiDocumentWorkspace.getChild(UIDocumentFormController.class) == null || !uiDocumentWorkspace.getChild(UIDocumentFormController.class).isRendered()) { if(isShowViewFile() && !(isShowDocumentViewForFile())) { uiDocumentContainer.setRenderedChild("UIDocumentWithTree"); } else { uiDocumentContainer.setRenderedChild("UIDocumentInfo") ; } if(getCurrentNode().isNodeType(Utils.NT_FOLDER) || getCurrentNode().isNodeType(Utils.NT_UNSTRUCTURED)) uiDocumentWorkspace.setRenderedChild(UIDocumentContainer.class) ; } else { UIDocumentFormController uiDocController = uiDocumentWorkspace.getChild(UIDocumentFormController.class); UISelectDocumentForm uiSelectDoc = uiDocController.getChild(UISelectDocumentForm.class); if (uiSelectDoc != null && uiSelectDoc.isRendered()) { uiSelectDoc.updatePageListData(); } } } UISideBar uiSideBar = uiWorkingArea.findFirstComponentOfType(UISideBar.class); uiSideBar.setRendered(preferences_.isShowSideBar()); if(preferences_.isShowSideBar()) { UITreeExplorer treeExplorer = findFirstComponentOfType(UITreeExplorer.class); if (treeExplorer.equals(uiSideBar.getChildById(uiSideBar.getCurrentComp()))) { treeExplorer.buildTree(); } uiSideBar.updateSideBarView(); } if (closePopup) { UIPopupContainer popupAction = getChild(UIPopupContainer.class); popupAction.deActivate(); } } public boolean nodeIsLocked(String path, Session session) throws Exception { Node node = getNodeByPath(path, session) ; return nodeIsLocked(node); } public boolean nodeIsLocked(Node node) throws Exception { if(!node.isLocked()) return false; String lockToken = LockUtil.getLockTokenOfUser(node); if(lockToken != null) { node.getSession().addLockToken(LockUtil.getLockToken(node)); return false; } return true; } /** * Allows you to add a lock token to the given node */ public void addLockToken(Node node) throws Exception { org.exoplatform.wcm.webui.Utils.addLockToken(node); } public boolean hasAddPermission() { try { ((ExtendedNode)getCurrentNode()).checkPermission(PermissionType.ADD_NODE) ; } catch(Exception e) { return false ; } return true ; } public boolean hasEditPermission() { try { ((ExtendedNode)getCurrentNode()).checkPermission(PermissionType.SET_PROPERTY) ; } catch(Exception e) { return false ; } return true ; } public boolean hasRemovePermission() { try { ((ExtendedNode)getCurrentNode()).checkPermission(PermissionType.REMOVE) ; } catch(Exception e) { return false ; } return true ; } public boolean hasReadPermission() { try { ((ExtendedNode)getCurrentNode()).checkPermission(PermissionType.READ) ; } catch(Exception e) { return false ; } return true ; } public Node getViewNode(String nodeType) throws Exception { try { Item primaryItem = getCurrentNode().getPrimaryItem() ; if(primaryItem == null || !primaryItem.isNode()) return getCurrentNode() ; if(primaryItem != null && primaryItem.isNode()) { Node primaryNode = (Node) primaryItem ; if(primaryNode.isNodeType(nodeType)) return primaryNode ; } } catch(ItemNotFoundException item) { if (LOG.isErrorEnabled()) { LOG.error("Primary item not found for " + getCurrentNode().getPath()); } return getCurrentNode() ; } catch(Exception e) { if (LOG.isErrorEnabled()) { LOG.error("The node cannot be seen", e); } return getCurrentNode() ; } return getCurrentNode() ; } public List<String> getMultiValues(Node node, String name) throws Exception { List<String> list = new ArrayList<String>(); if(!node.hasProperty(name)) return list; if (!node.getProperty(name).getDefinition().isMultiple()) { try { if (node.hasProperty(name)) { list.add(node.getProperty(name).getString()); } } catch(Exception e) { if (LOG.isErrorEnabled()) { LOG.error("The property '" + name + "' cannot be found ", e); } list.add("") ; } return list; } Value[] values = node.getProperty(name).getValues(); for (Value value : values) { list.add(value.getString()); } return list; } public void setIsHidePopup(boolean isHidePopup) { isHidePopup_ = isHidePopup ; } public void updateAjax(Event<?> event) throws Exception { UIJCRExplorerPortlet uiPortlet = getAncestorOfType(UIJCRExplorerPortlet.class); UIAddressBar uiAddressBar = findFirstComponentOfType(UIAddressBar.class) ; UIWorkingArea uiWorkingArea = getChild(UIWorkingArea.class) ; UIActionBar uiActionBar = findFirstComponentOfType(UIActionBar.class) ; UISideBar uiSideBar = findFirstComponentOfType(UISideBar.class); UITreeExplorer uiTreeExplorer = findFirstComponentOfType(UITreeExplorer.class); uiAddressBar.getUIStringInput(UIAddressBar.FIELD_ADDRESS).setValue( Text.unescapeIllegalJcrChars(filterPath(URLDecoder.decode(URLDecoder.decode(currentPath_))))) ; uiAddressBar.getUIInput(UIAddressBar.FIELD_ADDRESS_HIDDEN).setValue( filterPath(URLDecoder.decode(URLDecoder.decode(currentPath_)))) ; event.getRequestContext().addUIComponentToUpdateByAjax(getChild(UIControl.class)) ; UIPageIterator contentPageIterator = this.findComponentById(UIDocumentInfo.CONTENT_PAGE_ITERATOR_ID); int currentPage = contentPageIterator.getCurrentPage(); int currentPageInTree = 1; UITreeNodePageIterator extendedPageIterator = uiTreeExplorer.findFirstComponentOfType(UITreeNodePageIterator.class); if(extendedPageIterator != null) currentPageInTree = extendedPageIterator.getCurrentPage(); if(preferences_.isShowSideBar()) { UITreeExplorer treeExplorer = findFirstComponentOfType(UITreeExplorer.class); if (treeExplorer.equals(uiSideBar.getChildById(uiSideBar.getCurrentComp()))) { treeExplorer.buildTree(); } } UIDocumentWorkspace uiDocWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class); if(uiDocWorkspace.isRendered()) { if (uiDocWorkspace.getChild(UIDocumentFormController.class) == null || !uiDocWorkspace.getChild(UIDocumentFormController.class).isRendered()) { UIDocumentContainer uiDocumentContainer = uiDocWorkspace.getChild(UIDocumentContainer.class) ; UIDocumentWithTree uiDocumentWithTree = uiDocumentContainer.getChildById("UIDocumentWithTree"); if(isShowViewFile() && !(isShowDocumentViewForFile())) { uiDocumentContainer.setRenderedChild("UIDocumentWithTree"); } else { UIDocumentInfo uiDocumentInfo = uiDocumentContainer.getChildById("UIDocumentInfo") ; uiDocumentInfo.updatePageListData(); if(contentPageIterator.getAvailablePage() < currentPage) currentPage = contentPageIterator.getAvailablePage(); contentPageIterator.setCurrentPage(currentPage); uiDocumentContainer.setRenderedChild("UIDocumentInfo") ; } if(getCurrentNode().isNodeType(Utils.NT_FOLDER) || getCurrentNode().isNodeType(Utils.NT_UNSTRUCTURED)) uiDocumentWithTree.updatePageListData(); uiDocWorkspace.setRenderedChild(UIDocumentContainer.class) ; } else { UIDocumentFormController uiDocController = uiDocWorkspace.getChild(UIDocumentFormController.class); UISelectDocumentForm uiSelectDoc = uiDocController.getChild(UISelectDocumentForm.class); if (uiSelectDoc != null && uiSelectDoc.isRendered()) { uiSelectDoc.updatePageListData(); } } } uiActionBar.setRendered(uiPortlet.isShowActionBar()); uiAddressBar.setRendered(uiPortlet.isShowTopBar()); uiSideBar.setRendered(preferences_.isShowSideBar()); if(extendedPageIterator != null) extendedPageIterator.setCurrentPage(currentPageInTree); event.getRequestContext().addUIComponentToUpdateByAjax(uiWorkingArea); if (uiSideBar.isRendered()) event.getRequestContext().addUIComponentToUpdateByAjax(uiSideBar); event.getRequestContext().addUIComponentToUpdateByAjax(getChild(UIControl.class)) ; if(!isHidePopup_) { UIPopupContainer popupAction = getChild(UIPopupContainer.class) ; if(popupAction.isRendered()) { popupAction.deActivate(); event.getRequestContext().addUIComponentToUpdateByAjax(popupAction) ; } UIPopupWindow popupWindow = getChild(UIPopupWindow.class) ; if(popupWindow != null && popupWindow.isShow()) { popupWindow.setShow(false); event.getRequestContext().addUIComponentToUpdateByAjax(popupWindow); } } isHidePopup_ = false ; } public boolean isShowViewFile() throws Exception { TemplateService templateService = getApplicationComponent(TemplateService.class) ; NodeType nodeType = getCurrentNode().getPrimaryNodeType() ; NodeType[] superTypes = nodeType.getSupertypes() ; boolean isFolder = false ; for(NodeType superType : superTypes) { if(superType.getName().equals(Utils.NT_FOLDER) || superType.getName().equals(Utils.NT_UNSTRUCTURED)) { isFolder = true ; } } if(isFolder && templateService.getDocumentTemplates().contains(nodeType.getName())) { return true ; } return false; } public void cancelAction() throws Exception { WebuiRequestContext context = WebuiRequestContext.getCurrentInstance() ; UIPopupContainer popupAction = getChild(UIPopupContainer.class) ; popupAction.deActivate() ; context.addUIComponentToUpdateByAjax(popupAction); context.getJavascriptManager().require("SHARED/uiFileView", "uiFileView"). addScripts("uiFileView.UIFileView.clearCheckboxes();"); } public void record(String str, String ws) { /** * Uncomment this line if you have problem with the history * */ //LOG.info("record(" + str + ", " + ws + ")", new Exception()); nodesHistory_.add(str); wsHistory_.add(ws); addressPath_.put(str, new HistoryEntry(ws, str)); } public void record(String str, String ws, int pageIndex) { record(str, ws); pageIndexHistory_.put(str, pageIndex); } public void clearNodeHistory(String currentPath) { nodesHistory_.clear(); wsHistory_.clear(); pageIndexHistory_.clear(); addressPath_.clear(); currentPath_ = currentPath; } public void clearTagSelection() { tagPaths_.clear(); } public String rewind() { return nodesHistory_.removeLast() ; } public String previousWsName() { return wsHistory_.removeLast(); } public void setSelectNode(String workspaceName, String uri) throws Exception { String lastWorkspaceName = setTargetWorkspaceProperties(workspaceName); setSelectNode(uri); setLastWorkspace(lastWorkspaceName); } public void setSelectNode(String workspaceName, String uri, String homePath) throws Exception { String lastWorkspaceName = setTargetWorkspaceProperties(workspaceName); setSelectNode(uri, homePath, false); setLastWorkspace(lastWorkspaceName); } public void setBackSelectNode(String workspaceName, String uri) throws Exception { String lastWorkspaceName = setTargetWorkspaceProperties(workspaceName); setSelectNode(uri, true); setLastWorkspace(lastWorkspaceName); } public void setSelectRootNode() throws Exception { setSelectNode(getCurrentDriveWorkspace(), getRootPath()); } public void setSelectNode(String uri) throws Exception { setSelectNode(uri, false); } private boolean checkTargetForSymlink(String uri) throws Exception { Node testedNode; NodeFinder nodeFinder = getApplicationComponent(NodeFinder.class); try { testedNode = (Node) nodeFinder.getItem(this.getSession(), uri, true); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn("Cannot find the node at " + uri); } UIApplication uiApp = this.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIJCRExplorer.msg.target-path-not-found", null, ApplicationMessage.WARNING)); return false; } TrashService trashService = getApplicationComponent(TrashService.class) ; if (testedNode.isNodeType(Utils.EXO_RESTORELOCATION)) { //if testedNode is not in trash, then testedNode is in quarantine folder //we allow access only if the user read the node from the real location (quarantine folder) //else it is an user which read a link to the node in quarantine, so we should not display it if (trashService.isInTrash(testedNode) || !uri.equals(testedNode.getPath())) { UIApplication uiApp = this.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIJCRExplorer.msg.target-path-not-found", null, ApplicationMessage.WARNING)); return false; } else { return true; } } return true; } public void setSelectNode(String uri, boolean back) throws Exception { Node currentNode = null; if(uri == null || uri.length() == 0) uri = "/"; String previousPath = currentPath_; if (checkTargetForSymlink(uri)) { try { setCurrentPath(uri); currentNode = getCurrentNode(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Cannot find the node at " + uri, e); } setCurrentPath(LinkUtils.getParentPath(currentPath_)); currentNode = getCurrentNode(); } } else { currentNode = getCurrentNode(); } if(currentNode.hasProperty(Utils.EXO_LANGUAGE)) { setLanguage(currentNode.getProperty(Utils.EXO_LANGUAGE).getValue().getString()); } // Store previous node path to history for backing if(previousPath != null && !currentPath_.equals(previousPath) && !back) { // If previous node path has paginator, store last page index to history try{ if(this.hasPaginator(previousPath, lastWorkspaceName_)){ UIPageIterator pageIterator = this.findComponentById(UIDocumentInfo.CONTENT_PAGE_ITERATOR_ID); if (pageIterator != null) { record(previousPath, lastWorkspaceName_, pageIterator.getCurrentPage()); } }else{ record(previousPath, lastWorkspaceName_); } }catch(PathNotFoundException e){ LOG.info("This node " + previousPath +" is no longer accessible "); } } } public void setSelectNode(String uri, String homePath, boolean back) throws Exception { Node currentNode = null; if(uri == null || uri.length() == 0) uri = "/"; // retrieve the path history to node from uri String previousPath = uri.substring(0, uri.lastIndexOf("/")); if (checkTargetForSymlink(uri)) { try { setCurrentPath(uri); currentNode = getCurrentNode(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Cannot find the node at " + uri, e); } setCurrentPath(LinkUtils.getParentPath(currentPath_)); currentNode = getCurrentNode(); } } else { currentNode = getCurrentNode(); } if(currentNode.hasProperty(Utils.EXO_LANGUAGE)) { setLanguage(currentNode.getProperty(Utils.EXO_LANGUAGE).getValue().getString()); } // Store previous node path to history for backing if(previousPath != null && !previousPath.isEmpty() && !back) { try { String historyPath = ""; // get the home path if the node is in personal drive of a user if (homePath.contains("${userId}")) { homePath = org.exoplatform.services.cms.impl.Utils.getPersonalDrivePath(homePath, previousPath.split("/")[5]); } if (!(uri.equals(homePath) || homePath.equals("/"))) { // retrieve the relaive path to node from the home path // (the logic is previousPath = previousPath - homePath) previousPath = previousPath.replace(homePath, ""); historyPath = homePath; } // Store the home path at the head of history if (this.hasPaginator(homePath, lastWorkspaceName_)) { UIPageIterator pageIterator = this.findComponentById(UIDocumentInfo.CONTENT_PAGE_ITERATOR_ID); if (pageIterator != null) { record(homePath, lastWorkspaceName_, pageIterator.getCurrentPage()); } } else { record(homePath, lastWorkspaceName_); } // for each folder from the relative path to node, store the path to history for (String folder : previousPath.split("/")) { if (folder == null || folder.isEmpty()) continue; historyPath += "/" + folder; if (this.hasPaginator(historyPath, lastWorkspaceName_)) { UIPageIterator pageIterator = this.findComponentById(UIDocumentInfo.CONTENT_PAGE_ITERATOR_ID); if (pageIterator != null) { record(historyPath, lastWorkspaceName_, pageIterator.getCurrentPage()); } } else { record(historyPath, lastWorkspaceName_); } } }catch(PathNotFoundException e){ LOG.info("This node " + previousPath +" is no longer accessible "); } } } public List<Node> getChildrenList(String path, boolean isReferences) throws Exception { RepositoryService repositoryService = getApplicationComponent(RepositoryService.class) ; TemplateService templateService = getApplicationComponent(TemplateService.class) ; Node node = (Node) ItemLinkAware.newInstance(getWorkspaceName(), path, getNodeByPath(path, getSession())); NodeIterator childrenIterator = node.getNodes(); List<Node> childrenList = new ArrayList<Node>() ; NodeType nodeType = node.getPrimaryNodeType(); boolean isFolder = node.isNodeType(Utils.NT_FOLDER) || node.isNodeType(Utils.NT_UNSTRUCTURED) ; if(!preferences_.isJcrEnable() && templateService.isManagedNodeType(nodeType.getName()) && !isFolder) { return childrenList ; } if(!preferences_.isShowNonDocumentType()) { List<String> documentTypes = templateService.getDocumentTemplates() ; while(childrenIterator.hasNext()){ Node child = (Node)childrenIterator.next() ; if(PermissionUtil.canRead(child)) { NodeType type = child.getPrimaryNodeType() ; String typeName = type.getName(); String primaryTypeName = typeName; if(typeName.equals(Utils.EXO_SYMLINK)) { primaryTypeName = child.getProperty(Utils.EXO_PRIMARYTYPE).getString(); } if(child.isNodeType(Utils.NT_UNSTRUCTURED) || child.isNodeType(Utils.NT_FOLDER)) { childrenList.add(child) ; } else if(typeName.equals(Utils.EXO_SYMLINK) && documentTypes.contains(primaryTypeName)) { childrenList.add(child); } else if(documentTypes.contains(typeName)) { childrenList.add(child) ; } } } } else { while(childrenIterator.hasNext()) { Node child = (Node)childrenIterator.next() ; if(PermissionUtil.canRead(child)) childrenList.add(child) ; } } List<Node> childList = new ArrayList<Node>() ; if(!preferences_.isShowHiddenNode()) { for(Node child : childrenList) { Node realChild = child instanceof NodeLinkAware ? ((NodeLinkAware) child).getRealNode() : child; if(PermissionUtil.canRead(child) && !realChild.isNodeType(Utils.EXO_HIDDENABLE)) { childList.add(child) ; } } } else { childList = childrenList ; } sort(childList); return childList ; } private void sort(List<Node> childrenList) { if (NodetypeConstant.SORT_BY_NODENAME.equals(preferences_.getSortType())) { Collections.sort(childrenList, new NodeTitleComparator(preferences_.getOrder())) ; } else if (NodetypeConstant.SORT_BY_NODETYPE.equals(preferences_.getSortType())) { Collections.sort(childrenList, new TypeNodeComparator(preferences_.getOrder())) ; } else if (NodetypeConstant.SORT_BY_NODESIZE.equals(preferences_.getSortType())) { Collections.sort(childrenList, new NodeSizeComparator(preferences_.getOrder())) ; } else if (NodetypeConstant.SORT_BY_VERSIONABLE.equals(preferences_.getSortType())) { Collections.sort(childrenList, new StringComparator(preferences_.getOrder(), NodetypeConstant.SORT_BY_VERSIONABLE)); } else if (NodetypeConstant.SORT_BY_AUDITING.equals(preferences_.getSortType())) { Collections.sort(childrenList, new StringComparator(preferences_.getOrder(), NodetypeConstant.SORT_BY_AUDITING)); } else if (NodetypeConstant.SORT_BY_CREATED_DATE.equals(preferences_.getSortType())) { Collections.sort(childrenList, new PropertyValueComparator(Utils.EXO_CREATED_DATE, preferences_.getOrder())); } else if (NodetypeConstant.SORT_BY_MODIFIED_DATE.equals(preferences_.getSortType())) { Collections.sort(childrenList, new PropertyValueComparator(NodetypeConstant.EXO_LAST_MODIFIED_DATE, preferences_.getOrder())); } else if (NodetypeConstant.SORT_BY_DATE.equals(preferences_.getSortType())) { Collections.sort(childrenList, new DateComparator(preferences_.getOrder())); } else { Collections.sort(childrenList, new PropertyValueComparator(preferences_.getSortType(), preferences_.getOrder())); } } public boolean isReferenceableNode(Node node) throws Exception { return node.isNodeType(Utils.MIX_REFERENCEABLE) ; } public boolean isPreferenceNode(Node node) { try { return (getCurrentNode().hasNode(node.getName())) ? false : true ; } catch(Exception e) { return false ; } } public Node getNodeByPath(String nodePath, Session session) throws Exception { return getNodeByPath(nodePath, session, true); } public Node getNodeByPath(String nodePath, Session session, boolean giveTarget) throws Exception { return getNodeByPath(nodePath.trim(), session, giveTarget, true); } private Node getNodeByPath(String nodePath, Session session, boolean giveTarget, boolean firstTime) throws Exception { NodeFinder nodeFinder = getApplicationComponent(NodeFinder.class); Node node = null; if (nodeFinder.itemExists(session, nodePath)) { node = (Node) nodeFinder.getItem(session, nodePath, giveTarget); } else { if (nodePath.equals(currentPath_) && !nodePath.equals(currentRootPath_)) { setCurrentPath(LinkUtils.getParentPath(currentPath_)); return getNodeByPath(currentPath_, session, giveTarget, false); } try { if (nodeFinder.itemExists(session, nodePath)) { node = (Node) nodeFinder.getItem(session, nodePath, !giveTarget); return node; } } catch (Exception e3) { if (LOG.isWarnEnabled()) { LOG.warn(e3.getMessage()); } } if (firstTime) { String workspace = session.getWorkspace().getName(); if (LOG.isWarnEnabled()) { LOG.warn("The node cannot be found at " + nodePath + " into the workspace " + workspace); } } } if (node != null && !firstTime) { refreshExplorer(node); } return node; } public void setTagPath(String tagPath) { if (tagPaths_.contains(tagPath)) { tagPaths_.remove(tagPath); } else { tagPaths_.add(tagPath); } } public Set<String> getTagPaths() { return tagPaths_; } public String getTagPath() { return tagPaths_.size() == 0 ? null : tagPaths_.iterator().next(); } public void removeTagPath(String tagPath) { tagPaths_.remove(tagPath); } public List<Node> getDocumentByTag()throws Exception { NewFolksonomyService newFolksonomyService = getApplicationComponent(NewFolksonomyService.class) ; TemplateService templateService = getApplicationComponent(TemplateService.class) ; List<String> documentsType = templateService.getDocumentTemplates() ; List<Node> documentsOnTag = new ArrayList<Node>() ; WebuiRequestContext ctx = WebuiRequestContext.getCurrentInstance(); SessionProvider sessionProvider = (ctx.getRemoteUser() == null) ? WCMCoreUtils.createAnonimProvider() : WCMCoreUtils.getUserSessionProvider(); for (Node node : newFolksonomyService.getAllDocumentsByTagsAndPath(getCurrentPath(), tagPaths_, getRepository().getConfiguration().getDefaultWorkspaceName(), sessionProvider)) { if (documentsType.contains(node.getPrimaryNodeType().getName()) && PermissionUtil.canRead(node)) { documentsOnTag.add(node); } } return documentsOnTag ; } public void setIsViewTag(boolean isViewTag) { isViewTag_ = isViewTag; if (!isViewTag_) { tagPaths_.clear(); } } public boolean isViewTag() { return isViewTag_ ; } public PortletPreferences getPortletPreferences() { return pref_ ; } public boolean isReadAuthorized(ExtendedNode node) throws RepositoryException { try { node.checkPermission(PermissionType.READ); return true; } catch(AccessControlException e) { return false; } } public static Cookie getCookieByCookieName(String cookieName, Cookie[] cookies) { String userId = Util.getPortalRequestContext().getRemoteUser(); cookieName += userId; for(int loopIndex = 0; loopIndex < cookies.length; loopIndex++) { Cookie cookie1 = cookies[loopIndex]; if (cookie1.getName().equals(cookieName)) return cookie1; } return null; } public Preference getPreference() { if (preferencesSaved_) { if (preferences_ != null && !this.getAncestorOfType(UIJCRExplorerPortlet.class).isShowSideBar()) preferences_.setShowSideBar(false); return preferences_; } HttpServletRequest request = Util.getPortalRequestContext().getRequest(); Cookie[] cookies = request.getCookies(); Cookie getCookieForUser; getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_ENABLESTRUCTURE, cookies); if ((getCookieForUser != null) && (preferences_ != null)) { if (getCookieForUser.getValue().equals("true")) preferences_.setJcrEnable(true); else preferences_.setJcrEnable(false); } getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_SHOWSIDEBAR, cookies); if ((getCookieForUser != null) && (preferences_ != null)) { if (getCookieForUser.getValue().equals("true")) preferences_.setShowSideBar(true); else preferences_.setShowSideBar(false); } if (preferences_ != null && !this.getAncestorOfType(UIJCRExplorerPortlet.class).isShowSideBar()) preferences_.setShowSideBar(false); getCookieForUser = getCookieByCookieName(Preference.SHOW_NON_DOCUMENTTYPE, cookies); if ((getCookieForUser != null) && (preferences_ != null)) { if (getCookieForUser.getValue().equals("true")) preferences_.setShowNonDocumentType(true); else preferences_.setShowNonDocumentType(false); } getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_SHOWREFDOCUMENTS, cookies); if ((getCookieForUser != null) && (preferences_ != null)) { if (getCookieForUser.getValue().equals("true")) preferences_.setShowPreferenceDocuments(true); else preferences_.setShowPreferenceDocuments(false); } getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_SHOW_HIDDEN_NODE, cookies); if ((getCookieForUser != null) && (preferences_ != null)) { if (getCookieForUser.getValue().equals("true")) preferences_.setShowHiddenNode(true); else preferences_.setShowHiddenNode(false); } getCookieForUser = getCookieByCookieName(Preference.ENABLE_DRAG_AND_DROP, cookies); if ((getCookieForUser != null) && (preferences_ != null)) { if (getCookieForUser.getValue().equals("true")) preferences_.setEnableDragAndDrop(true); else preferences_.setEnableDragAndDrop(false); } getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_QUERY_TYPE, cookies); if ((getCookieForUser != null) && (preferences_ != null)) preferences_.setQueryType(getCookieForUser.getValue()); getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_SORT_BY, cookies); if ((getCookieForUser != null) && (preferences_ != null)) preferences_.setSortType(getCookieForUser.getValue()); getCookieForUser = getCookieByCookieName(Preference.PREFERENCE_ORDER_BY, cookies); if ((getCookieForUser != null) && (preferences_ != null)) preferences_.setOrder(getCookieForUser.getValue()); getCookieForUser = getCookieByCookieName(Preference.NODES_PER_PAGE, cookies); if ((getCookieForUser != null) && (preferences_ != null)) preferences_.setNodesPerPage(Integer.parseInt(getCookieForUser.getValue())); return preferences_; } public void setPreferences(Preference preference) {this.preferences_ = preference; } public void closeEditingFile() throws Exception { UIPopupContainer uiPopupContainer = this.getChild(UIPopupContainer.class); UIPopupWindow uiPopup = uiPopupContainer.getChild(UIPopupWindow.class); UIWorkingArea uiWorkingArea = this.getChild(UIWorkingArea.class); UIDocumentWorkspace uiDocumentWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class); //check if edit with popup UIComponent uiComp = uiPopup.getUIComponent(); if (uiComp instanceof UIDocumentFormController && ((UIDocumentFormController)uiComp).isRendered()) { uiPopupContainer.deActivate(); this.refreshExplorer(); return; } //check if edit without popup if (uiDocumentWorkspace.isRendered()) { UIDocumentFormController controller = uiDocumentWorkspace.getChild(UIDocumentFormController.class); if (controller != null) { uiDocumentWorkspace.removeChild(UIDocumentFormController.class).deActivate(); uiDocumentWorkspace.setRenderedChild(UIDocumentContainer.class); this.refreshExplorer(); } } } public static class HistoryEntry { private final String workspace; private final String path; private HistoryEntry(String workspace, String path) { this.workspace = workspace; this.path = path; } public String getWorkspace() { return workspace; } public String getPath() { return path; } } }
54,396
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIJCRExplorerPortlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIJCRExplorerPortlet.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.explorer; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.jcr.model.Preference; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.ecm.webui.component.explorer.control.UIActionBar; import org.exoplatform.ecm.webui.component.explorer.control.UIAddressBar; import org.exoplatform.ecm.webui.component.explorer.control.UIControl; import org.exoplatform.ecm.webui.component.explorer.control.action.AddDocumentActionComponent; import org.exoplatform.ecm.webui.component.explorer.control.action.EditDocumentActionComponent; import org.exoplatform.ecm.webui.component.explorer.control.action.EditPropertyActionComponent; import org.exoplatform.ecm.webui.component.explorer.sidebar.UITreeExplorer; import org.exoplatform.ecm.webui.component.explorer.versions.UIVersionInfo; import org.exoplatform.ecm.webui.utils.JCRExceptionManager; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.documents.AutoVersionService; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.drives.impl.ManageDriveServiceImpl; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.cms.views.ManageViewService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.web.application.ApplicationMessage; 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.UIApplication; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.UIPortletApplication; import org.exoplatform.webui.core.UIRightClickPopupMenu; import org.exoplatform.webui.core.lifecycle.UIApplicationLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import javax.jcr.*; import javax.portlet.PortletMode; import javax.portlet.PortletPreferences; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @ComponentConfig( lifecycle = UIApplicationLifecycle.class ) public class UIJCRExplorerPortlet extends UIPortletApplication { /** * Logger. */ private static final Log LOG = ExoLogger.getLogger(UIJCRExplorerPortlet.class.getName()); final static public String ISDIRECTLY_DRIVE = "isDirectlyDrive"; final static public String DRIVE_NAME = "driveName"; final static public String USECASE = "usecase"; final static public String JAILED = "jailed"; final static public String SELECTION = "selection"; final static public String PERSONAL = "personal"; final static public String PARAMETERIZE = "parameterize"; final static public String PARAMETERIZE_PATH = "nodePath"; final static public String SHOW_TOP_BAR = "showTopBar"; final static public String SHOW_ACTION_BAR = "showActionBar"; final static public String SHOW_SIDE_BAR = "showSideBar"; final static public String SHOW_FILTER_BAR = "showFilterBar"; final static private String DOC_NOT_FOUND = "doc-not-found"; private NodeFinder nodeFinder; private String backTo =""; private boolean flagSelect = false; private Pattern driveParameteriedPathPattern = Pattern.compile(".*\\$\\{(.*)\\}.*"); public UIJCRExplorerPortlet() throws Exception { if (Util.getPortalRequestContext().getRemoteUser() != null) { UIJcrExplorerContainer explorerContainer = addChild(UIJcrExplorerContainer.class, null, null); explorerContainer.initExplorer(); addChild(UIJcrExplorerEditContainer.class, null, null).setRendered(false); } nodeFinder = getApplicationComponent(NodeFinder.class); } public boolean isFlagSelect() { return flagSelect; } public void setFlagSelect(boolean flagSelect) { this.flagSelect = flagSelect; } public boolean isShowTopBar() { PortletPreferences portletpref = getPortletPreferences(); return Boolean.valueOf(portletpref.getValue(UIJCRExplorerPortlet.SHOW_TOP_BAR, "false")); } public boolean isShowActionBar() { PortletPreferences portletpref = getPortletPreferences(); return Boolean.valueOf(portletpref.getValue(UIJCRExplorerPortlet.SHOW_ACTION_BAR, "false")) && (!this.findFirstComponentOfType(UIJCRExplorer.class).isAddingDocument() || this.findFirstComponentOfType(UIWorkingArea.class).getChild(UIActionBar.class).hasBackButton()); } public boolean isShowSideBar() { PortletPreferences portletpref = getPortletPreferences(); return Boolean.valueOf(portletpref.getValue(UIJCRExplorerPortlet.SHOW_SIDE_BAR, "false")); } public boolean isShowFilterBar() { PortletPreferences portletpref = getPortletPreferences(); return Boolean.valueOf(portletpref.getValue(UIJCRExplorerPortlet.SHOW_FILTER_BAR, "false")); } public String getBacktoValue() { return backTo; } public void processRender(WebuiApplication app, WebuiRequestContext context) throws Exception { if (Util.getPortalRequestContext().getRemoteUser() == null) { ((PortletRequestContext)context).getWriter().write( String.format("<p style='text-align:center'>%s</p>", context.getApplicationResourceBundle().getString("UIJCRExplorerPortlet.msg.anonymous-access-denied"))); return; } UIJcrExplorerContainer explorerContainer = getChild(UIJcrExplorerContainer.class); UIJcrExplorerEditContainer editContainer = getChild(UIJcrExplorerEditContainer.class); PortletRequestContext portletReqContext = (PortletRequestContext) context ; Map<String, String> map = getElementByContext(context); PortalRequestContext pcontext = Util.getPortalRequestContext(); String backToValue = Util.getPortalRequestContext().getRequestParameter(org.exoplatform.ecm.webui.utils.Utils.URL_BACKTO); if (!portletReqContext.useAjax()) { backTo = backToValue; } HashMap<String, String> changeDrive = (HashMap<String, String>)pcontext.getAttribute("jcrexplorer-show-document"); if (changeDrive!=null) { map = changeDrive; context.setAttribute("jcrexplorer-show-document", null); } if (portletReqContext.getApplicationMode() == PortletMode.VIEW) { if (map.size() > 0) { showDocument(context, map); } else { initwhenDirect(explorerContainer, editContainer); } explorerContainer.setRendered(true); UIJCRExplorer uiExplorer = explorerContainer.getChild(UIJCRExplorer.class); if(uiExplorer != null) { try { uiExplorer.getSession(); try { uiExplorer.getSession().getItem(uiExplorer.getRootPath()); } catch(PathNotFoundException e) { reloadWhenBroken(uiExplorer); super.processRender(app, context); return; } } catch(RepositoryException repo) { super.processRender(app, context); } } getChild(UIJcrExplorerEditContainer.class).setRendered(false); } else if(portletReqContext.getApplicationMode() == PortletMode.HELP) { if (LOG.isDebugEnabled()) LOG.debug("\n\n>>>>>>>>>>>>>>>>>>> IN HELP MODE \n"); } else if(portletReqContext.getApplicationMode() == PortletMode.EDIT) { explorerContainer.setRendered(false); getChild(UIJcrExplorerEditContainer.class).setRendered(true); } // RenderResponse response = context.getResponse(); // Element elementS = response.createElement("script"); // elementS.setAttribute("type", "text/javascript"); // elementS.setAttribute("src", "/eXoWCMResources/javascript/eXo/wcm/backoffice/public/Components.js"); // response.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT,elementS); UIJCRExplorer uiExplorer = explorerContainer.getChild(UIJCRExplorer.class); UITreeExplorer uiTreeExplorer = uiExplorer.findFirstComponentOfType(UITreeExplorer.class); AutoVersionService autoVersionService = WCMCoreUtils.getService(AutoVersionService.class); context.getJavascriptManager(). require("SHARED/multiUpload", "multiUpload").require("SHARED/jquery", "gj") .addScripts("multiUpload.setLocation('" + uiExplorer.getWorkspaceName() + "','" + uiExplorer.getDriveData().getName() + "','" + uiTreeExplorer.getLabel().replaceAll("\'", "") + "','" + Text.escapeIllegalJcrChars(uiExplorer.getCurrentPath()) + "','" + org.exoplatform.services.cms.impl.Utils.getPersonalDrivePath(uiExplorer.getDriveData().getHomePath(), ConversationState.getCurrent().getIdentity().getUserId())+ "', '"+ autoVersionService.isVersionSupport(uiExplorer.getCurrentPath(), uiExplorer.getCurrentWorkspace())+"');") .addScripts("gj(document).ready(function() { gj(\"*[rel='tooltip']\").tooltip();});"); super.processRender(app, context); } public void initwhenDirect(UIJcrExplorerContainer explorerContainer, UIJcrExplorerEditContainer editContainer) throws Exception { if (editContainer.getChild(UIJcrExplorerEditForm.class).isFlagSelectRender()) { explorerContainer.initExplorer(); editContainer.getChild(UIJcrExplorerEditForm.class).setFlagSelectRender(false); } UIJCRExplorer uiExplorer = explorerContainer.getChild(UIJCRExplorer.class); if (uiExplorer != null) { // Init UIJCRExplorer.contextNode attribute for explorer navigation and the file refreshing // (when open a file in explorer or space documents; // when refresh the session (refresh button) for current file in explorer or space documents) uiExplorer.initContext(); } } public String getPreferenceRepository() { PortletRequestContext pcontext = (PortletRequestContext)WebuiRequestContext.getCurrentInstance() ; PortletPreferences portletPref = pcontext.getRequest().getPreferences() ; String repository = portletPref.getValue(Utils.REPOSITORY, "") ; return repository ; } public String getPreferenceTrashHomeNodePath() { return getPortletPreferences().getValue(Utils.TRASH_HOME_NODE_PATH, ""); } public String getPreferenceTrashRepository() { return getPortletPreferences().getValue(Utils.TRASH_REPOSITORY, ""); } public String getPreferenceTrashWorkspace() { return getPortletPreferences().getValue(Utils.TRASH_WORKSPACE, ""); } public PortletPreferences getPortletPreferences() { PortletRequestContext pcontext = (PortletRequestContext)WebuiRequestContext.getCurrentInstance(); return pcontext.getRequest().getPreferences(); } public DriveData getUserDrive() throws Exception { ManageDriveService manageDriveService = getApplicationComponent(ManageDriveService.class); String userId = Util.getPortalRequestContext().getRemoteUser(); for(DriveData userDrive : manageDriveService.getPersonalDrives(userId)) { if(userDrive.getHomePath().endsWith("/Private")) { return userDrive; } } return null; } public boolean canUseConfigDrive(String driveName) throws Exception { ManageDriveService dservice = getApplicationComponent(ManageDriveService.class); String userId = Util.getPortalRequestContext().getRemoteUser(); List<String> userRoles = Utils.getMemberships(); for(DriveData drive : dservice.getDriveByUserRoles(userId, userRoles)) { if(drive.getName().equals(driveName)) return true; } return false; } public void reloadWhenBroken(UIJCRExplorer uiExplorer) { uiExplorer.getChild(UIControl.class).setRendered(false); UIWorkingArea uiWorkingArea = uiExplorer.getChild(UIWorkingArea.class); uiWorkingArea.setRenderedChild(UIDrivesArea.class); UIRightClickPopupMenu uiRightClickPopupMenu = uiWorkingArea.getChild(UIRightClickPopupMenu.class); if(uiRightClickPopupMenu!=null) uiRightClickPopupMenu.setRendered(true); } private Map<String, String> getElementByContext(WebuiRequestContext context) { HashMap<String, String> mapParam = new HashMap<>(); //In case access by ajax request if (context.useAjax()) return mapParam; PortalRequestContext pcontext = Util.getPortalRequestContext(); Matcher matcher; Map<String, String[]> requestParams = pcontext.getRequest().getParameterMap(); for(String requestParamName : requestParams.keySet()) { if (requestParamName.equals("path")) { String nodePathParam = pcontext.getRequestParameter("path"); String currentRepo = WCMCoreUtils.getRepository().getConfiguration().getName(); String userId = Util.getPortalRequestContext().getRemoteUser(); if (nodePathParam != null && nodePathParam.length() > 0) { Pattern patternUrl = Pattern.compile("([^/]+)/(.*)"); matcher = patternUrl.matcher(nodePathParam); if (matcher.find()) { mapParam.put("repository", currentRepo); mapParam.put("drive", matcher.group(1)); mapParam.put("path", matcher.group(2)); mapParam.put("userId",userId); } else { patternUrl = Pattern.compile("(.*)"); matcher = patternUrl.matcher(nodePathParam); if (matcher.find()) { mapParam.put("repository", currentRepo); mapParam.put("drive", matcher.group(1)); mapParam.put("path", "/"); } } } } else { mapParam.put(requestParamName, pcontext.getRequest().getParameter(requestParamName)); } } return mapParam; } private void showDocument(WebuiRequestContext context, Map<String, String> map) throws Exception { String repositoryName = String.valueOf(map.get("repository")); String driveName = String.valueOf(map.get("drive")); if (driveName.equals(DOC_NOT_FOUND)) { UIApplication uiApp = findFirstComponentOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIDrivesArea.msg.not-found", null, ApplicationMessage.WARNING)); return; } String path = String.valueOf(map.get("path")); if (path.indexOf("&") > 0) { path = path.substring(0, path.indexOf("&")); } if(!path.equals("/")) { ArrayList<String> encodeNameArr = new ArrayList<String>(); for(String name : path.split("/")) { if(name.length() > 0) { encodeNameArr.add(Text.escapeIllegalJcrChars(name)); } } StringBuilder encodedPath = new StringBuilder(); for(String encodedName : encodeNameArr) { encodedPath.append("/").append(encodedName); } path = encodedPath.toString(); } UIApplication uiApp = findFirstComponentOfType(UIApplication.class); ManageDriveService manageDrive = getApplicationComponent(ManageDriveService.class); DriveData driveData = null; try { driveData = manageDrive.getDriveByName(driveName); if (driveData == null) throw new PathNotFoundException(); } catch (PathNotFoundException e) { Object[] args = { driveName }; return; } RepositoryService rservice = getApplicationComponent(RepositoryService.class); String userId = Util.getPortalRequestContext().getRemoteUser(); List<String> viewList = new ArrayList<String>(); for (String role : Utils.getMemberships()) { for (String viewName : driveData.getViews().split(",")) { if (!viewList.contains(viewName.trim())) { Node viewNode = getApplicationComponent(ManageViewService.class).getViewByName(viewName.trim(), WCMCoreUtils.getSystemSessionProvider()); String permiss = viewNode.getProperty("exo:accessPermissions").getString(); if (permiss.contains("${userId}")) permiss = permiss.replace("${userId}", userId); String[] viewPermissions = permiss.split(","); if (permiss.equals("*")) viewList.add(viewName.trim()); if (driveData.hasPermission(viewPermissions, role)) viewList.add(viewName.trim()); } } } StringBuffer viewListStr = new StringBuffer(); List<SelectItemOption<String>> viewOptions = new ArrayList<SelectItemOption<String>>(); ResourceBundle res = context.getApplicationResourceBundle(); String viewLabel = null; for (String viewName : viewList) { try { viewLabel = res.getString("Views.label." + viewName); } catch (MissingResourceException e) { viewLabel = viewName; } viewOptions.add(new SelectItemOption<String>(viewLabel, viewName)); if (viewListStr.length() > 0) viewListStr.append(",").append(viewName); else viewListStr.append(viewName); } driveData.setViews(viewListStr.toString()); String homePath = driveData.getHomePath(); Matcher matcher = driveParameteriedPathPattern.matcher(homePath); if(matcher.matches()) { // if the drive is a virtual drive containing, the paramterized value is available as request parameter String drivePathParamName = matcher.group(1); String drivePathParamValue = map.get(drivePathParamName); driveData.getParameters().put(drivePathParamName, drivePathParamValue); // we need to get the real drive home path if(StringUtils.isNotEmpty(drivePathParamValue)) { if(ManageDriveServiceImpl.DRIVE_PARAMATER_USER_ID.equals(drivePathParamName)) { // User id parameter is a special case since it must be replaced by its distributed format homePath = org.exoplatform.services.cms.impl.Utils.getPersonalDrivePath(homePath, drivePathParamValue); } else { // we update the drive homePath with the real value homePath = StringUtils.replaceOnce(homePath, "${" + drivePathParamName + "}", drivePathParamValue); } } } // we extract the absolute path of the file (remove the drive name) String contentRealPath = path; int firstSlash = path.indexOf("/"); if(firstSlash >= 0) { contentRealPath = path.substring(firstSlash); } setFlagSelect(true); UIJCRExplorer uiExplorer = findFirstComponentOfType(UIJCRExplorer.class); uiExplorer.setDriveData(driveData); uiExplorer.setIsReferenceNode(false); try { Session session = WCMCoreUtils.getUserSessionProvider().getSession(driveData.getWorkspace(), rservice.getCurrentRepository()); nodeFinder.getItem(session, contentRealPath); } catch(AccessDeniedException ace) { Object[] args = { driveName }; uiApp.addMessage(new ApplicationMessage("UIDrivesArea.msg.access-denied", args, ApplicationMessage.WARNING)); return; } catch(NoSuchWorkspaceException nosuchWS) { Object[] args = { driveName }; uiApp.addMessage(new ApplicationMessage("UIDrivesArea.msg.workspace-not-exist", args, ApplicationMessage.WARNING)); return; } catch(Exception e) { JCRExceptionManager.process(uiApp, e); return; } uiExplorer.setRepositoryName(repositoryName); uiExplorer.setWorkspaceName(driveData.getWorkspace()); uiExplorer.setRootPath(homePath); String addressPath = contentRealPath.replaceAll("/+", "/"); // handle special case of docs in Public Personal Documents and the symlink "Public" if(driveData.getName().equals(ManageDriveServiceImpl.PERSONAL_DRIVE_NAME) && !addressPath.startsWith(homePath)) { String publicHomePath = homePath.replace("/" + ManageDriveServiceImpl.PERSONAL_DRIVE_PRIVATE_FOLDER_NAME, "/" + ManageDriveServiceImpl.PERSONAL_DRIVE_PUBLIC_FOLDER_NAME); if(addressPath.startsWith(publicHomePath)) { addressPath = addressPath.replace("/" + ManageDriveServiceImpl.PERSONAL_DRIVE_PUBLIC_FOLDER_NAME, "/Private/" + ManageDriveServiceImpl.PERSONAL_DRIVE_PUBLIC_FOLDER_NAME); } } Preference pref = uiExplorer.getPreference(); pref.setShowSideBar(driveData.getViewSideBar()); pref.setShowNonDocumentType(driveData.getViewNonDocument()); pref.setShowPreferenceDocuments(driveData.getViewPreferences()); pref.setAllowCreateFoder(driveData.getAllowCreateFolders()); pref.setShowHiddenNode(driveData.getShowHiddenNode()); uiExplorer.setIsReferenceNode(false); UIControl uiControl = uiExplorer.getChild(UIControl.class); UIAddressBar uiAddressBar = uiControl.getChild(UIAddressBar.class); uiAddressBar.setViewList(viewList); uiAddressBar.setSelectedViewName(viewList.get(0)); uiAddressBar.setRendered(isShowTopBar()); UIWorkingArea uiWorkingArea = findFirstComponentOfType(UIWorkingArea.class); UIActionBar uiActionbar = uiWorkingArea.getChild(UIActionBar.class); boolean isShowActionBar = isShowActionBar() ; uiActionbar.setTabOptions(viewList.get(0)); uiActionbar.setRendered(isShowActionBar); uiExplorer.clearNodeHistory(addressPath); uiExplorer.setSelectNode(driveData.getWorkspace(), addressPath, homePath); // Init UIJCRExplorer.contextNode attribute for the file refreshing and opening by link // (when refresh the file current page (update browser page) in explorer or space documents; // when open a file by link) uiExplorer.initContext(); UIDocumentWorkspace uiDocWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class); uiDocWorkspace.setRenderedChild(UIDocumentContainer.class); uiDocWorkspace.setRendered(true); UIDrivesArea uiDrive = uiWorkingArea.getChild(UIDrivesArea.class); if (uiDrive != null) uiDrive.setRendered(false); context.addUIComponentToUpdateByAjax(uiDocWorkspace); UIPopupContainer popupAction = getChild(UIPopupContainer.class); if (popupAction != null && popupAction.isRendered()) { popupAction.deActivate(); context.addUIComponentToUpdateByAjax(popupAction); } Boolean isEdit = Boolean.valueOf(Util.getPortalRequestContext().getRequestParameter("edit")); Node selectedNode = uiExplorer.getCurrentNode(); if (isEdit) { if (uiExplorer.getCurrentPath().equals(addressPath)) { if(canManageNode(selectedNode, uiApp, uiExplorer, uiActionbar, context, EditDocumentActionComponent.getFilters())) { EditDocumentActionComponent.editDocument(null, context, this, uiExplorer, selectedNode, uiApp); }else if(canManageNode(selectedNode, uiApp, uiExplorer, uiActionbar, context, EditPropertyActionComponent.getFilters())) { EditPropertyActionComponent.editDocument(null, context, this, uiExplorer, selectedNode, uiApp); } } else { uiApp.addMessage(new ApplicationMessage("UIJCRExplorerPortlet.msg.file-access-denied", null, ApplicationMessage.WARNING)); } } boolean isAddNew = Boolean.valueOf(Util.getPortalRequestContext().getRequestParameter("addNew")); if(!isAddNew && !isEdit) { showVersionHistory(selectedNode, uiWorkingArea); } if (!isEdit && isAddNew) { if (canManageNode(selectedNode, uiApp, uiExplorer, uiActionbar, context, AddDocumentActionComponent.getFilters())) { AddDocumentActionComponent.addDocument(null, uiExplorer, uiApp, this, context); } else { uiApp.addMessage(new ApplicationMessage("UIJCRExplorerPortlet.msg.file-access-denied", null, ApplicationMessage.WARNING)); } } uiExplorer.refreshExplorer(null, (isAddNew && isEdit)); } private void showVersionHistory(Node selectedNode, UIWorkingArea uiWorkingArea) throws Exception { Boolean isDisplayVersionHistory = Boolean.valueOf(Util.getPortalRequestContext().getRequestParameter("versions")); if (isDisplayVersionHistory && selectedNode.isNodeType(Utils.MIX_VERSIONABLE)) { UIDocumentWorkspace uiDocumentWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class); if (uiDocumentWorkspace != null) { UIVersionInfo uiVersionInfo = uiDocumentWorkspace.getChild(UIVersionInfo.class); if (uiVersionInfo != null) { uiVersionInfo.setCurrentNode(selectedNode); uiVersionInfo.setRootOwner(selectedNode.getProperty(Utils.EXO_LASTMODIFIER).getString()); uiVersionInfo.activate(); uiDocumentWorkspace.setRenderedChild(UIVersionInfo.class); } } } } private boolean canManageNode(Node selectedNode, UIApplication uiApp, UIJCRExplorer uiExplorer, UIActionBar uiActionBar, Object context, List<UIExtensionFilter> filters) throws Exception { Map<String, Object> ctx = new HashMap<String, Object>(); ctx.put(UIActionBar.class.getName(), uiActionBar); ctx.put(UIJCRExplorer.class.getName(), uiExplorer); ctx.put(UIApplication.class.getName(), uiApp); ctx.put(Node.class.getName(), selectedNode); ctx.put(WebuiRequestContext.class.getName(), context); for (UIExtensionFilter filter : filters) try { if (!filter.accept(ctx)) return false; } catch (Exception e) { return false; } return true; } }
26,935
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDriveSelector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIDriveSelector.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.explorer; import java.util.Collections; import java.util.Comparator; 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.form.UIFormInputSetWithAction; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; 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; import org.exoplatform.webui.form.UIFormSelectBox; /** * Created by The eXo Platform SARL * Author : Ly Dinh Quang * quang.ly@exoplatform.com * xxx5669@gmail.com * 10 févr. 09 */ @ComponentConfig( template = "app:/groovy/webui/component/explorer/UIDriveSelector.gtmpl", events = { @EventConfig(listeners = UIDriveSelector.AddDriveActionListener.class), @EventConfig(listeners = UIDriveSelector.CancelActionListener.class) } ) public class UIDriveSelector extends UIContainer { private UIPageIterator uiPageIterator_; public UIDriveSelector() throws Exception { uiPageIterator_ = addChild(UIPageIterator.class, null, "DriveSelectorList"); } public UIPageIterator getUIPageIterator() { return uiPageIterator_; } public List getListDrive() throws Exception { return uiPageIterator_.getCurrentPageData(); } public void updateGrid() throws Exception { ListAccess<DriveData> driveList = new ListAccessImpl<DriveData>(DriveData.class, getDrives()); LazyPageList<DriveData> dataPageList = new LazyPageList<DriveData>(driveList, 10); uiPageIterator_.setPageList(dataPageList); } public List<DriveData> getDrives() throws Exception { ManageDriveService driveService = getApplicationComponent(ManageDriveService.class) ; List<DriveData> driveList = driveService.getDriveByUserRoles(Util.getPortalRequestContext().getRemoteUser(), Utils.getMemberships()); Collections.sort(driveList, new DriveComparator()) ; return driveList ; } static public class DriveComparator implements Comparator<DriveData> { public int compare(DriveData d1, DriveData d2) throws ClassCastException { String name1 = d1.getName(); String name2 = d2.getName(); return name1.compareToIgnoreCase(name2); } } static public class CancelActionListener extends EventListener<UIDriveSelector> { public void execute(Event<UIDriveSelector> event) throws Exception { UIDriveSelector driveSelector = event.getSource(); UIComponent uiComponent = driveSelector.getParent(); if (uiComponent != null) { if (uiComponent instanceof UIPopupWindow) { ((UIPopupWindow)uiComponent).setShow(false); ((UIPopupWindow)uiComponent).setRendered(false); event.getRequestContext().addUIComponentToUpdateByAjax(((UIPopupWindow)uiComponent).getParent()); return; } } } } static public class AddDriveActionListener extends EventListener<UIDriveSelector> { public void execute(Event<UIDriveSelector> event) throws Exception { String driveName = event.getRequestContext().getRequestParameter(OBJECTID); UIDriveSelector driveSelector = event.getSource(); UIJcrExplorerEditContainer editContainer = driveSelector.getAncestorOfType(UIJcrExplorerEditContainer.class); UIJcrExplorerEditForm form = editContainer.getChild(UIJcrExplorerEditForm.class); UIFormInputSetWithAction driveNameInput = form.getChildById("DriveNameInput"); driveNameInput.getUIStringInput(UIJCRExplorerPortlet.DRIVE_NAME).setValue(driveName); UIComponent uiComponent = driveSelector.getParent(); UIFormSelectBox typeSelectBox = form.getChildById(UIJCRExplorerPortlet.USECASE); if (UIJCRExplorerPortlet.PARAMETERIZE.equals(typeSelectBox.getValue())) { UIFormInputSetWithAction uiParamPathInput = form.getChildById(UIJcrExplorerEditForm.PARAM_PATH_ACTION); uiParamPathInput.setRendered(true); } if (uiComponent != null) { if (uiComponent instanceof UIPopupWindow) { ((UIPopupWindow)uiComponent).setShow(false); ((UIPopupWindow)uiComponent).setRendered(false); event.getRequestContext().addUIComponentToUpdateByAjax(((UIPopupWindow)uiComponent).getParent()); return; } } } } }
5,670
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIWorkingArea.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIWorkingArea.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.explorer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.jcr.ItemNotFoundException; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.webui.component.explorer.control.UIActionBar; import org.exoplatform.ecm.webui.component.explorer.popup.actions.UIDocumentFormController; import org.exoplatform.ecm.webui.component.explorer.popup.actions.UISelectDocumentForm; import org.exoplatform.ecm.webui.component.explorer.rightclick.manager.RestoreFromTrashManageComponent; import org.exoplatform.ecm.webui.component.explorer.sidebar.UISideBar; import org.exoplatform.ecm.webui.component.explorer.sidebar.UITreeExplorer; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.actions.ActionServiceContainer; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.cms.link.NodeLinkAware; 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.security.Identity; import org.exoplatform.services.security.IdentityConstants; import org.exoplatform.services.security.IdentityRegistry; import org.exoplatform.services.security.MembershipEntry; import org.exoplatform.services.wcm.utils.WCMCoreUtils; 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.UIApplication; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIRightClickPopupMenu; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.ext.UIExtension; import org.exoplatform.webui.ext.UIExtensionManager; import org.exoplatform.webui.ext.manager.UIAbstractManagerComponent; /** * Created by The eXo Platform SARL Author : Tran The Trong trongtt@gmail.com * July 3, 2006 10:07:15 AM */ @ComponentConfigs( { @ComponentConfig(template = "app:/groovy/webui/component/explorer/UIWorkingArea.gtmpl", events = {@EventConfig(listeners = UIWorkingArea.RefreshActionListener.class)}), @ComponentConfig( type = UIRightClickPopupMenu.class, id = "ECMContextMenu", template = "app:/groovy/webui/component/explorer/UIRightClickPopupMenu.gtmpl" ) }) public class UIWorkingArea extends UIContainer { /** * Logger. */ private static final Log LOG = ExoLogger.getLogger(UIWorkingArea.class.getName()); public static final Pattern FILE_EXPLORER_URL_SYNTAX = Pattern.compile("([^:/]+):(/.*)"); public static final String WS_NAME = "workspaceName"; public static final String EXTENSION_TYPE = "org.exoplatform.ecm.dms.UIWorkingArea"; public static final String ITEM_CONTEXT_MENU = "ItemContextMenu"; public static final String MULTI_ITEM_CONTEXT_MENU = "MultiItemContextMenu"; public static final String GROUND_CONTEXT_MENU = "GroundContextMenu"; public static final String ITEM_GROUND_CONTEXT_MENU = "ItemGroundContextMenu"; public static final String MOVE_NODE = "MoveNode"; public static final String CREATE_LINK = "CreateLink"; public static final String CUSTOM_ACTIONS = "CustomActions"; public static final String PERMLINK = "PermlinkContextMenu"; public static final String PERM_LINK_ACTION = "Permlink"; private String nodePathDelete = ""; private String deleteNotice = ""; private String wcmNotice = ""; public void setNodePathDelete(String nodePathDelete) { this.nodePathDelete = nodePathDelete; } public String getNodePathDelete() { return nodePathDelete; } public String getWCMNotice() { return wcmNotice; } public void setWCMNotice(String wcmNotice) { this.wcmNotice = wcmNotice; } public void setDeleteNotice(String deleteNotice) { this.deleteNotice = deleteNotice; } public String getDeleteNotice() { return this.deleteNotice; } public static final String REFRESH_ACTION = "Refresh"; public static final String RENAME_ACTION = "Rename"; private List<UIAbstractManagerComponent> managers = Collections.synchronizedList(new ArrayList<UIAbstractManagerComponent>()); public UIWorkingArea() throws Exception { addChild(UIRightClickPopupMenu.class, "ECMContextMenu", null); addChild(UISideBar.class, null, null); addChild(UIActionBar.class, null, null) ; addChild(UISelectDocumentTemplateTitle.class, null, null); addChild(UIDocumentWorkspace.class, null, null); addChild(UIDrivesArea.class, null, null).setRendered(false); } private List<UIExtension> getUIExtensionList() { UIExtensionManager manager = getApplicationComponent(UIExtensionManager.class); return manager.getUIExtensions(EXTENSION_TYPE); } public synchronized UITreeExplorer getTreeExplorer() { UISideBar uiSideBar = getChild(UISideBar.class); return uiSideBar.getChild(UITreeExplorer.class); } public void initialize() throws Exception { List<UIExtension> extensions = getUIExtensionList(); if (extensions == null) { return; } managers.clear(); for (UIExtension extension : extensions) { UIComponent component = addUIExtension(extension, null); if (component !=null && !managers.contains(component)) managers.add((UIAbstractManagerComponent)component); } } private UIComponent addUIExtension(UIExtension extension, Map<String, Object> context) throws Exception { UIExtensionManager manager = getApplicationComponent(UIExtensionManager.class); UIComponent component = manager.addUIExtension(extension, context, this); if(component == null) return null; synchronized(component) { if (component instanceof UIAbstractManagerComponent) { // You can access to the given extension and the extension is valid UIAbstractManagerComponent uiAbstractManagerComponent = (UIAbstractManagerComponent) component; uiAbstractManagerComponent.setUIExtensionName(extension.getName()); uiAbstractManagerComponent.setUIExtensionCategory(extension.getCategory()); return component; } else if (component != null) { // You can access to the given extension but the extension is not valid if (LOG.isWarnEnabled()) { LOG.warn("All the extension '" + extension.getName() + "' of type '" + EXTENSION_TYPE + "' must be associated to a component of type " + UIAbstractManagerComponent.class); } removeChild(component.getClass()); } } return null; } public RestoreFromTrashManageComponent getThrashManageComponent(){ for(UIAbstractManagerComponent c : getManagers()){ if(c instanceof RestoreFromTrashManageComponent){ return (RestoreFromTrashManageComponent)c; } } return null; } public List<UIAbstractManagerComponent> getManagers() { List<UIAbstractManagerComponent> managers = new ArrayList<UIAbstractManagerComponent>(); managers.addAll(this.managers); return managers; } public void unregister(UIAbstractManagerComponent component) { managers.remove(component); } //Should use this method to check for when execute Actions in Working Area instead in UIEditingTagsForm (line 120) public boolean isShowSideBar() throws Exception { UIJCRExplorer jcrExplorer = getParent(); return jcrExplorer.getPreference().isShowSideBar() && getAncestorOfType(UIJCRExplorerPortlet.class).isShowSideBar(); } public void setShowSideBar(boolean b) throws Exception { UIJCRExplorer jcrExplorer = getParent(); jcrExplorer.getPreference().setShowSideBar(b); } public Node getNodeByUUID(String uuid) throws Exception { ManageableRepository repo = getApplicationComponent(RepositoryService.class).getCurrentRepository(); String workspace = repo.getConfiguration().getDefaultWorkspaceName(); return getNodeByUUID(uuid, workspace); } public Node getNodeByUUID(String uuid, String workspaceName) throws Exception { ManageableRepository repo = getApplicationComponent(RepositoryService.class).getCurrentRepository(); Session session = WCMCoreUtils.getSystemSessionProvider().getSession(workspaceName, repo); return session.getNodeByUUID(uuid); } public boolean isPreferenceNode(Node node) { return getAncestorOfType(UIJCRExplorer.class).isPreferenceNode(node); } public String getVersionNumber(Node node) throws RepositoryException { if (!Utils.isVersionable(node)) return "-"; return node.getBaseVersion().getName(); } public boolean isJcrViewEnable() throws Exception { UIJCRExplorer uiExplorer = getAncestorOfType(UIJCRExplorer.class); return uiExplorer.getPreference().isJcrEnable(); } private Map<String, Object> createContext(Node currentNode) throws Exception { Map<String, Object> context = new HashMap<String, Object>(); WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance() ; UIJCRExplorer uiExplorer = getAncestorOfType(UIJCRExplorer.class); UIApplication uiApp = getAncestorOfType(UIApplication.class); context.put(Node.class.getName(), currentNode); context.put(UIWorkingArea.class.getName(), this); context.put(UIApplication.class.getName(), uiApp); context.put(UIJCRExplorer.class.getName(), uiExplorer); context.put(WebuiRequestContext.class.getName(), requestContext); return context; } List<UIComponent> getGroundActionsExtensionList() throws Exception { List<UIComponent> uiGroundActionList = new ArrayList<UIComponent>(); List<UIExtension> uiExtensionList = getUIExtensionList(); UIJCRExplorer uiExplorer = getAncestorOfType(UIJCRExplorer.class); Node currentNode = uiExplorer.getCurrentNode(); UIComponent uiAddedActionManage; for (UIExtension uiextension : uiExtensionList) { if (GROUND_CONTEXT_MENU.equals(uiextension.getCategory()) || ITEM_GROUND_CONTEXT_MENU.equals(uiextension.getCategory())) { uiAddedActionManage = addUIExtension(uiextension, createContext(currentNode)); if (uiAddedActionManage != null) { if (!uiGroundActionList.contains(uiAddedActionManage)) uiGroundActionList.add(uiAddedActionManage); } } } return uiGroundActionList; } List<UIComponent> getMultiActionsExtensionList() throws Exception { List<UIComponent> uiActionList = new ArrayList<UIComponent>(); List<UIExtension> uiExtensionList = getUIExtensionList(); UIComponent uiAddedActionManage; for (UIExtension uiextension : uiExtensionList) { if (ITEM_CONTEXT_MENU.equals(uiextension.getCategory()) || ITEM_GROUND_CONTEXT_MENU.equals(uiextension.getCategory()) || MULTI_ITEM_CONTEXT_MENU.equals(uiextension.getCategory())) { uiAddedActionManage = addUIExtension(uiextension, null); if (uiAddedActionManage != null) { if (!uiActionList.contains(uiAddedActionManage)) uiActionList.add(uiAddedActionManage); } } } return uiActionList; } public String getActionsExtensionList(Node node) throws Exception { StringBuffer actionsList = new StringBuffer(1024); List<UIExtension> uiExtensionList = getUIExtensionList(); UIComponent uiAddedActionManage; try { NodeFinder nodeFinder = getApplicationComponent(NodeFinder.class); nodeFinder.getItem(getAncestorOfType(UIJCRExplorer.class).getSession(), node.getPath()); } catch(PathNotFoundException pne) { return ""; } for (UIExtension uiextension : uiExtensionList) { if (uiextension.getCategory().startsWith(ITEM_CONTEXT_MENU) || ITEM_GROUND_CONTEXT_MENU.equals(uiextension.getCategory())) { uiAddedActionManage = addUIExtension(uiextension, createContext(node)); if (uiAddedActionManage != null) { actionsList.append(uiextension.getName()).append(","); } } } if (actionsList.length() > 0) { return actionsList.substring(0, actionsList.length() - 1); } return actionsList.toString(); } public UIComponent getJCRMoveAction() throws Exception { UIExtensionManager manager = getApplicationComponent(UIExtensionManager.class); UIExtension extension = manager.getUIExtension(EXTENSION_TYPE, MOVE_NODE); return addUIExtension(extension, null); } public UIComponent getCreateLinkAction() throws Exception { UIExtensionManager manager = getApplicationComponent(UIExtensionManager.class); UIExtension extension = manager.getUIExtension(EXTENSION_TYPE, CREATE_LINK); return addUIExtension(extension, null); } public UIComponent getPermlink(Node node) throws Exception { UIComponent uicomponent = null; List<UIExtension> uiExtensionList = getUIExtensionList(); for (UIExtension uiextension : uiExtensionList) { if (PERMLINK.equals(uiextension.getCategory())) { uicomponent = addUIExtension(uiextension, createContext(node)); } } return uicomponent; } public UIComponent getCustomAction() throws Exception { UIComponent uicomponent = null; List<UIExtension> uiExtensionList = getUIExtensionList(); for (UIExtension uiextension : uiExtensionList) { if (CUSTOM_ACTIONS.equals(uiextension.getCategory())) { uicomponent = addUIExtension(uiextension, null); } } return uicomponent; } private boolean hasPermission(String userName, Value[] roles) throws Exception { IdentityRegistry identityRegistry = getApplicationComponent(IdentityRegistry.class); if (IdentityConstants.SYSTEM.equalsIgnoreCase(userName)) { return true; } Identity identity = identityRegistry.getIdentity(userName); if (identity == null) { return false; } for (int i = 0; i < roles.length; i++) { String role = roles[i].getString(); if ("*".equalsIgnoreCase(role)) return true; MembershipEntry membershipEntry = MembershipEntry.parse(role); if (membershipEntry == null) return false; if (identity.isMemberOf(membershipEntry)) { return true; } } return false; } public List<Node> getCustomActions(Node node) throws Exception { if (node instanceof NodeLinkAware) { NodeLinkAware nodeLA = (NodeLinkAware) node; try { node = nodeLA.getTargetNode().getRealNode(); } catch (Exception e) { // The target of the link is not reachable } } List<Node> safeActions = new ArrayList<Node>(); WebuiRequestContext context = WebuiRequestContext.getCurrentInstance(); String userName = context.getRemoteUser(); ActionServiceContainer actionContainer = getApplicationComponent(ActionServiceContainer.class); List<Node> unsafeActions = actionContainer.getCustomActionsNode(node, "read"); if (unsafeActions == null) return new ArrayList<Node>(); for (Node actionNode : unsafeActions) { Value[] roles = actionNode.getProperty(Utils.EXO_ROLES).getValues(); if (hasPermission(userName, roles)) safeActions.add(actionNode); } return safeActions; } /** * Gets the title. * * @param node the node * * @return the title * * @throws Exception the exception */ public String getTitle(Node node) throws Exception { return Utils.getTitle(node); } public void processRender(WebuiRequestContext context) throws Exception { UIJCRExplorerPortlet uiPortlet = getAncestorOfType(UIJCRExplorerPortlet.class); UIActionBar uiActionBar = findFirstComponentOfType(UIActionBar.class); uiActionBar.setRendered(uiPortlet.isShowActionBar()); UISelectDocumentTemplateTitle uiTemplateTitle = findFirstComponentOfType(UISelectDocumentTemplateTitle.class); boolean isUITemplateTitleRendered = isUISelectDocumentTemplateTitleRendered(); uiTemplateTitle.setRendered(isUITemplateTitleRendered); if(!context.useAjax()) { if (isShowSideBar()) { UITreeExplorer uiTreeExplorer = this.findFirstComponentOfType(UITreeExplorer.class); if (uiTreeExplorer != null) uiTreeExplorer.buildTree(); } } super.processRender(context); } public boolean isUISelectDocumentTemplateTitleRendered() { UIDocumentFormController uiDocumentController = findFirstComponentOfType(UIDocumentFormController.class); boolean isUITemplateTitleRendered = (uiDocumentController != null && uiDocumentController.isRendered() && uiDocumentController.getChild(UISelectDocumentForm.class).isRendered()); return isUITemplateTitleRendered; } /** * Refresh UIWorkingArea after renaming.UIPresentationContainer */ public static class RefreshActionListener extends EventListener<UIWorkingArea> { public void execute(Event<UIWorkingArea> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); // Get path before renaming String pathBeforeRename = event.getRequestContext().getRequestParameter("oldPath"); // Get path after renaming String renamedNodeUUID = event.getRequestContext().getRequestParameter("uuid"); String pathAfterRename = null; Node renamedNode = null; try { renamedNode = uiExplorer.getSession().getNodeByUUID(renamedNodeUUID); } catch (ItemNotFoundException e) { // Try to find node in other workspaces String[] workspaceNames = uiExplorer.getRepository().getWorkspaceNames(); String currentWorkSpaceName = uiExplorer.getWorkspaceName(); for (String workspaceName : workspaceNames) { if (!workspaceName.equals(currentWorkSpaceName)) { try { renamedNode = uiExplorer.getSessionByWorkspace(workspaceName).getNodeByUUID(renamedNodeUUID); break; } catch (ItemNotFoundException infE) { renamedNode = null; } } } } if (renamedNode != null) { pathAfterRename = renamedNode.getPath(); } else { LOG.warn("Can not find renamed node with old path: [%s]", pathBeforeRename); return; } // Update content explorer String currentPath = uiExplorer.getCurrentPath(); if (currentPath.equals(pathBeforeRename)) { uiExplorer.setCurrentPath(pathAfterRename) ; } else if(currentPath.startsWith(pathBeforeRename)) { uiExplorer.setCurrentPath(pathAfterRename + currentPath.replace(pathBeforeRename, StringUtils.EMPTY)); } uiExplorer.updateAjax(event); } } }
20,755
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDocumentInfo.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIDocumentInfo.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.explorer; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.utils.LazyPageList; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.commons.utils.ListAccessImpl; import org.exoplatform.commons.utils.PageList; import org.exoplatform.container.component.ComponentPlugin; import org.exoplatform.download.DownloadService; import org.exoplatform.download.InputStreamDownloadResource; import org.exoplatform.ecm.jcr.model.Preference; import org.exoplatform.ecm.utils.lock.LockUtil; import org.exoplatform.ecm.webui.component.explorer.control.UIActionBar; import org.exoplatform.ecm.webui.component.explorer.sidebar.UITreeExplorer; import org.exoplatform.ecm.webui.component.explorer.sidebar.UITreeNodePageIterator; 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.ecm.webui.utils.JCRExceptionManager; import org.exoplatform.ecm.webui.utils.PermissionUtil; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.portal.webui.workspace.UIPortalApplication; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.clipboard.ClipboardService; import org.exoplatform.services.cms.comments.CommentsService; import org.exoplatform.services.cms.documents.AutoVersionService; import org.exoplatform.services.cms.documents.DocumentTypeService; import org.exoplatform.services.cms.documents.FavoriteService; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.i18n.MultiLanguageService; import org.exoplatform.services.cms.link.*; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.cms.thumbnail.ThumbnailPlugin; import org.exoplatform.services.cms.thumbnail.ThumbnailService; import org.exoplatform.services.cms.timeline.TimelineService; import org.exoplatform.services.cms.voting.VotingService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.audit.AuditHistory; import org.exoplatform.services.jcr.ext.audit.AuditService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.IdentityConstants; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.web.application.Parameter; import org.exoplatform.web.application.RequireJS; 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.*; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.exception.MessageException; import org.exoplatform.webui.ext.UIExtensionManager; import javax.imageio.ImageIO; import javax.jcr.*; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.nodetype.NodeDefinition; import javax.jcr.nodetype.NodeType; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import javax.jcr.version.VersionException; import java.awt.*; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; import java.util.regex.Matcher; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Sep 3, 2006 * 10:07:15 AM * Editor : Pham Tuan * phamtuanchip@gmail.com * Nov 10, 2006 */ @ComponentConfig( events = { @EventConfig(listeners = UIDocumentInfo.ChangeNodeActionListener.class, csrfCheck = false), @EventConfig(listeners = UIDocumentInfo.ViewNodeActionListener.class, csrfCheck = false), @EventConfig(listeners = UIDocumentInfo.SortActionListener.class, csrfCheck = false), @EventConfig(listeners = UIDocumentInfo.VoteActionListener.class), @EventConfig(listeners = UIDocumentInfo.ChangeLanguageActionListener.class), @EventConfig(listeners = UIDocumentInfo.DownloadActionListener.class, csrfCheck = false), @EventConfig(listeners = UIDocumentInfo.StarClickActionListener.class), @EventConfig(listeners = UIDocumentInfo.ShowPageActionListener.class), @EventConfig(listeners = UIDocumentInfo.SortTimelineASCActionListener.class), @EventConfig(listeners = UIDocumentInfo.SortTimelineDESCActionListener.class), @EventConfig(listeners = UIDocumentInfo.ExpandTimelineCatergoryActionListener.class, csrfCheck = false), @EventConfig(listeners = UIDocumentInfo.CollapseTimelineCatergoryActionListener.class, csrfCheck = false), @EventConfig(listeners = UIDocumentInfo.SwitchToAudioDescriptionActionListener.class), @EventConfig(listeners = UIDocumentInfo.SwitchToOriginalActionListener.class), @EventConfig(listeners = UIBaseNodePresentation.OpenDocInDesktopActionListener.class) } ) public class UIDocumentInfo extends UIBaseNodePresentation { final protected static String NO = "NO"; final protected static String YES = "YES"; final protected static String COMMENT_COMPONENT = "Comment"; final protected static String Contents_Document_Type = "Content"; final protected static String CATEGORY_ALL = "All"; final protected static String CATEGORY_TODAY = "UIDocumentInfo.label.Today"; final protected static String CATEGORY_YESTERDAY = "UIDocumentInfo.label.Yesterday"; final protected static String CATEGORY_WEEK = "UIDocumentInfo.label.EarlierThisWeek"; final protected static String CATEGORY_MONTH = "UIDocumentInfo.label.EarlierThisMonth"; final protected static String CATEGORY_YEAR = "UIDocumentInfo.label.EarlierThisYear"; final public static String CONTENT_PAGE_ITERATOR_ID = "ContentPageIterator"; final protected static String CONTENT_TODAY_PAGE_ITERATOR_ID = "ContentTodayPageIterator"; final protected static String CONTENT_YESTERDAY_PAGE_ITERATOR_ID = "ContentYesterdayPageIterator"; final protected static String CONTENT_WEEK_PAGE_ITERATOR_ID = "ContentWeekPageIterator"; final protected static String CONTENT_MONTH_PAGE_ITERATOR_ID = "ContentMonthPageIterator"; final protected static String CONTENT_YEAR_PAGE_ITERATOR_ID = "ContentYearPageIterator"; protected UIDocumentNodeList documentNodeList_; private static final Log LOG = ExoLogger.getLogger(UIDocumentInfo.class.getName()); private String typeSort_ = NodetypeConstant.SORT_BY_NODENAME; private String sortOrder_ = Preference.BLUE_DOWN_ARROW; private String displayCategory_; private int itemsPerTimeline; private NodeLocation currentNode_; private UIPageIterator pageIterator_; private UIPageIterator todayPageIterator_; private UIPageIterator yesterdayPageIterator_; private UIPageIterator earlierThisWeekPageIterator_; private UIPageIterator earlierThisMonthPageIterator_; private UIPageIterator earlierThisYearPageIterator_; private String timeLineSortByFavourite = ""; private String timeLineSortByName = ""; private String timeLineSortByDate = Preference.BLUE_UP_ARROW; private FavoriteService favoriteService; private DocumentTypeService documentTypeService; private TemplateService templateService; //used for timeline view, indicating which type of content is shown(daily, this week, this month, this year) private HashMap<String, String> isExpanded_; //flag indicating if we need to update data for Timeline private boolean updateTimeLineData_ = false; //used in File View, indicating which folders are expanded private Set<String> expandedFolders_; public UIDocumentInfo() throws Exception { pageIterator_ = addChild(UIPageIterator.class, null, CONTENT_PAGE_ITERATOR_ID); documentNodeList_ = addChild(UIDocumentNodeList.class, null, null); documentNodeList_.setShowMoreButton(false); todayPageIterator_ = addChild(UIPageIterator.class, null, CONTENT_TODAY_PAGE_ITERATOR_ID); yesterdayPageIterator_ = addChild(UIPageIterator.class, null, CONTENT_YESTERDAY_PAGE_ITERATOR_ID); earlierThisWeekPageIterator_ = addChild(UIPageIterator.class, null, CONTENT_WEEK_PAGE_ITERATOR_ID); earlierThisMonthPageIterator_ = addChild(UIPageIterator.class, null, CONTENT_MONTH_PAGE_ITERATOR_ID); earlierThisYearPageIterator_ = addChild(UIPageIterator.class, null, CONTENT_YEAR_PAGE_ITERATOR_ID); favoriteService = this.getApplicationComponent(FavoriteService.class); documentTypeService = this.getApplicationComponent(DocumentTypeService.class); templateService = getApplicationComponent(TemplateService.class) ; displayCategory_ = UIDocumentInfo.CATEGORY_ALL; isExpanded_ = new HashMap<String, String>(); expandedFolders_ = new HashSet<String>(); } /** * checks if the data for Timeline view is needed to update * @throws Exception */ public void checkTimelineUpdate() throws Exception { if (this.updateTimeLineData_) { updateNodeLists(); this.updateTimeLineData_ = false; } } public String getTimeLineSortByFavourite() { return timeLineSortByFavourite; } public void setTimeLineSortByFavourite(String timeLineSortByFavourite) { this.timeLineSortByFavourite = timeLineSortByFavourite; } public String getTimeLineSortByName() { return timeLineSortByName; } public void setTimeLineSortByName(String timeLineSortByName) { this.timeLineSortByName = timeLineSortByName; } public String getTimeLineSortByDate() { return timeLineSortByDate; } public void setTimeLineSortByDate(String timeLineSortByDate) { this.timeLineSortByDate = timeLineSortByDate; } public void updateNodeLists() throws Exception { TimelineService timelineService = getApplicationComponent(TimelineService.class); itemsPerTimeline = timelineService.getItemPerTimeline(); UIJCRExplorer uiExplorer = this.getAncestorOfType(UIJCRExplorer.class); SessionProvider sessionProvider = uiExplorer.getSessionProvider(); Session session = uiExplorer.getSession(); String workspace = this.getWorkspaceName(); String userName = session.getUserID(); String nodePath = uiExplorer.getCurrentPath(); String tagPath = uiExplorer.getTagPath(); boolean isViewTag = uiExplorer.isViewTag(); boolean isLimit = false; int nodesPerPage; List<NodeLocation> todayNodes = new ArrayList<NodeLocation>(); List<NodeLocation> yesterdayNodes = new ArrayList<NodeLocation>(); List<NodeLocation> earlierThisWeekNodes = new ArrayList<NodeLocation>(); List<NodeLocation> earlierThisMonthNodes = new ArrayList<NodeLocation>(); List<NodeLocation> earlierThisYearNodes = new ArrayList<NodeLocation>(); isExpanded_ = new HashMap<String, String>(); if (CATEGORY_ALL.equalsIgnoreCase(displayCategory_)) { nodesPerPage = Integer.MAX_VALUE; // always display in one page (no paginator) todayNodes = NodeLocation.getLocationsByNodeList(timelineService. getDocumentsOfToday(nodePath, workspace, sessionProvider, userName, false, isLimit)); if (todayNodes.size() > this.getItemsPerTimeline()) { isExpanded_.put(UIDocumentInfo.CATEGORY_TODAY, YES); todayNodes = todayNodes.subList(0, this.getItemsPerTimeline()); } else { isExpanded_.put(UIDocumentInfo.CATEGORY_TODAY, NO); } yesterdayNodes = NodeLocation.getLocationsByNodeList(timelineService.getDocumentsOfYesterday(nodePath, workspace, sessionProvider, userName, false, isLimit)); if (yesterdayNodes.size() > this.getItemsPerTimeline()) { isExpanded_.put(UIDocumentInfo.CATEGORY_YESTERDAY, YES); yesterdayNodes = yesterdayNodes.subList(0, this.getItemsPerTimeline()); } else { isExpanded_.put(UIDocumentInfo.CATEGORY_YESTERDAY, NO); } earlierThisWeekNodes = NodeLocation.getLocationsByNodeList(timelineService. getDocumentsOfEarlierThisWeek(nodePath, workspace, sessionProvider, userName, false, isLimit)); if (earlierThisWeekNodes.size() > this.getItemsPerTimeline()) { isExpanded_.put(UIDocumentInfo.CATEGORY_WEEK, YES); earlierThisWeekNodes = earlierThisWeekNodes.subList(0, this.getItemsPerTimeline()); } else { isExpanded_.put(UIDocumentInfo.CATEGORY_WEEK, NO); } earlierThisMonthNodes = NodeLocation.getLocationsByNodeList(timelineService. getDocumentsOfEarlierThisMonth(nodePath, workspace, sessionProvider, userName, false, isLimit)); if (earlierThisMonthNodes.size() > this.getItemsPerTimeline()) { isExpanded_.put(UIDocumentInfo.CATEGORY_MONTH, YES); earlierThisMonthNodes = earlierThisMonthNodes.subList(0, this.getItemsPerTimeline()); } else { isExpanded_.put(UIDocumentInfo.CATEGORY_MONTH, NO); } earlierThisYearNodes = NodeLocation.getLocationsByNodeList(timelineService. getDocumentsOfEarlierThisYear(nodePath, workspace, sessionProvider, userName, false, isLimit)); if (earlierThisYearNodes.size() > this.getItemsPerTimeline()) { isExpanded_.put(UIDocumentInfo.CATEGORY_YEAR, YES); earlierThisYearNodes = earlierThisYearNodes.subList(0, this.getItemsPerTimeline()); } else { isExpanded_.put(UIDocumentInfo.CATEGORY_YEAR, NO); } } else { nodesPerPage = uiExplorer.getPreference().getNodesPerPage(); if (CATEGORY_TODAY.equalsIgnoreCase(displayCategory_)) { todayNodes = NodeLocation.getLocationsByNodeList(timelineService.getDocumentsOfToday(nodePath, workspace, sessionProvider, userName, false, isLimit)); } else if (CATEGORY_YESTERDAY.equalsIgnoreCase(displayCategory_)) { yesterdayNodes = NodeLocation.getLocationsByNodeList(timelineService.getDocumentsOfYesterday(nodePath, workspace, sessionProvider, userName, false, isLimit)); } else if (CATEGORY_WEEK.equalsIgnoreCase(displayCategory_)) { earlierThisWeekNodes = NodeLocation.getLocationsByNodeList(timelineService. getDocumentsOfEarlierThisWeek(nodePath, workspace, sessionProvider, userName, false, isLimit)); } else if (CATEGORY_MONTH.equalsIgnoreCase(displayCategory_)) { earlierThisMonthNodes = NodeLocation.getLocationsByNodeList(timelineService. getDocumentsOfEarlierThisMonth(nodePath, workspace, sessionProvider, userName, false, isLimit)); } else if (CATEGORY_YEAR.equalsIgnoreCase(displayCategory_)) { earlierThisYearNodes = NodeLocation.getLocationsByNodeList(timelineService. getDocumentsOfEarlierThisYear(nodePath, workspace, sessionProvider, userName, false, isLimit)); } } if(isViewTag && tagPath != null) { if(todayNodes.size() > 0) todayNodes = filterDocumentsByTag(todayNodes, tagPath); if(yesterdayNodes.size() > 0) yesterdayNodes = filterDocumentsByTag(yesterdayNodes, tagPath); if(earlierThisWeekNodes.size() > 0) earlierThisWeekNodes = filterDocumentsByTag(earlierThisWeekNodes, tagPath); if(earlierThisMonthNodes.size() > 0) earlierThisMonthNodes = filterDocumentsByTag(earlierThisMonthNodes, tagPath); if(earlierThisYearNodes.size() > 0) earlierThisYearNodes = filterDocumentsByTag(earlierThisYearNodes, tagPath); } Collections.sort(todayNodes, new SearchComparator()); Collections.sort(yesterdayNodes, new SearchComparator()); Collections.sort(earlierThisWeekNodes, new SearchComparator()); Collections.sort(earlierThisMonthNodes, new SearchComparator()); Collections.sort(earlierThisYearNodes, new SearchComparator()); ListAccess<NodeLocation> todayNodesList = new ListAccessImpl<NodeLocation>(NodeLocation.class, todayNodes); todayPageIterator_.setPageList(new LazyPageList<NodeLocation>(todayNodesList, nodesPerPage)); ListAccess<NodeLocation> yesterdayNodesList = new ListAccessImpl<NodeLocation>(NodeLocation.class, yesterdayNodes); yesterdayPageIterator_.setPageList(new LazyPageList<NodeLocation>(yesterdayNodesList, nodesPerPage)); ListAccess<NodeLocation> earlierThisWeekList = new ListAccessImpl<NodeLocation>(NodeLocation.class, earlierThisWeekNodes); earlierThisWeekPageIterator_.setPageList(new LazyPageList<NodeLocation>(earlierThisWeekList, nodesPerPage)); ListAccess<NodeLocation> earlierThisMonthList = new ListAccessImpl<NodeLocation>(NodeLocation.class, earlierThisMonthNodes); earlierThisMonthPageIterator_.setPageList(new LazyPageList<NodeLocation>(earlierThisMonthList, nodesPerPage)); ListAccess<NodeLocation> earlierThisYearList = new ListAccessImpl<NodeLocation>(NodeLocation.class, earlierThisYearNodes); earlierThisYearPageIterator_.setPageList(new LazyPageList<NodeLocation>(earlierThisYearList, nodesPerPage)); } public List<NodeLocation> filterDocumentsByTag(List<NodeLocation> nodes, String path) throws Exception { List<Node> documents = new ArrayList<Node>(); Session session = null; Node node = null; QueryManager queryManager = null; QueryResult queryResult = null; Query query = null; NodeIterator nodeIterator = null; for (int i = 0; i < nodes.size(); i++) { node = NodeLocation.getNodeByLocation(nodes.get(i)); if (node.isNodeType(NodetypeConstant.MIX_REFERENCEABLE)) { session = node.getSession(); String queryString = "SELECT * FROM exo:symlink where jcr:path like '" + path + "/%' and exo:uuid = '" + node.getUUID() + "' and exo:workspace='" + node.getSession().getWorkspace().getName() + "'"; queryManager = session.getWorkspace().getQueryManager(); query = queryManager.createQuery(queryString, Query.SQL); queryResult = query.execute(); nodeIterator = queryResult.getNodes(); if (nodeIterator.getSize() > 0) documents.add(node); } } return NodeLocation.getLocationsByNodeList(documents); } public String getDisplayCategory() { if (displayCategory_ == null || displayCategory_.trim().length() == 0) { return CATEGORY_ALL; } return displayCategory_; } public UIPageIterator getContentPageIterator() { return pageIterator_; } /** * @return the todayPageIterator_ */ public UIPageIterator getTodayPageIterator() { return todayPageIterator_; } public UIPageIterator getYesterdayPageIterator() { return yesterdayPageIterator_; } public UIPageIterator getWeekPageIterator() { return earlierThisWeekPageIterator_; } public UIPageIterator getMonthPageIterator() { return earlierThisMonthPageIterator_; } public UIPageIterator getYearPageIterator() { return earlierThisYearPageIterator_; } public UIComponent getUIComponent(String mimeType) throws Exception { return Utils.getUIComponent(mimeType, this); } public String getTemplate() { UIJCRExplorer uiExplorer = getAncestorOfType(UIJCRExplorer.class) ; if(uiExplorer.getPreference().isJcrEnable()) return uiExplorer.getDocumentInfoTemplate(); try { Node node = uiExplorer.getCurrentNode(); String template = templateService.getTemplatePath(node,false) ; if(template != null) return template ; } catch(AccessDeniedException ace) { try { uiExplorer.setSelectRootNode() ; Object[] args = { uiExplorer.getCurrentNode().getName() } ; throw new MessageException(new ApplicationMessage("UIDocumentInfo.msg.access-denied", args, ApplicationMessage.WARNING)) ; } catch(Exception exc) { if (LOG.isWarnEnabled()) { LOG.warn(exc.getMessage()); } } } catch(Exception e) { return uiExplorer.getDocumentInfoTemplate(); } return uiExplorer.getDocumentInfoTemplate(); } public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context, String template) { return getAncestorOfType(UIJCRExplorer.class).getJCRTemplateResourceResolver(); } public UIRightClickPopupMenu getContextMenu() { return getAncestorOfType(UIWorkingArea.class).getChild(UIRightClickPopupMenu.class) ; } public Node getNodeByUUID(String uuid) { ManageableRepository manageRepo = WCMCoreUtils.getRepository(); String[] workspaces = manageRepo.getWorkspaceNames() ; for(String ws : workspaces) { try{ return WCMCoreUtils.getSystemSessionProvider().getSession(ws, manageRepo).getNodeByUUID(uuid) ; } catch(Exception e) { continue; } } return null; } public String getCapacityOfFile(Node file) throws Exception { Node contentNode = file.getNode(Utils.JCR_CONTENT); long size = contentNode.getProperty(Utils.JCR_DATA).getLength() ; long capacity = size/1024 ; String strCapacity = Long.toString(capacity) ; if(strCapacity.indexOf(".") > -1) return strCapacity.substring(0, strCapacity.lastIndexOf(".")) ; return strCapacity ; } public List<String> getMultiValues(Node node, String name) throws Exception { return getAncestorOfType(UIJCRExplorer.class).getMultiValues(node, name) ; } public boolean isSystemWorkspace() throws Exception { UIJCRExplorer uiExplorer = getAncestorOfType(UIJCRExplorer.class) ; ManageableRepository manaRepoService = getApplicationComponent(RepositoryService.class).getCurrentRepository(); String systemWsName = manaRepoService.getConfiguration().getSystemWorkspaceName() ; if(systemWsName.equals(uiExplorer.getCurrentWorkspace())) return true ; return false ; } public boolean isSupportedThumbnailImage(Node node) throws Exception { if(node.isNodeType(Utils.NT_FILE)) { Node contentNode = node.getNode(Utils.JCR_CONTENT); ThumbnailService thumbnailService = getApplicationComponent(ThumbnailService.class); for(ComponentPlugin plugin : thumbnailService.getComponentPlugins()) { if(plugin instanceof ThumbnailPlugin) { ThumbnailPlugin thumbnailPlugin = (ThumbnailPlugin) plugin; if(thumbnailPlugin.getMimeTypes().contains( contentNode.getProperty(Utils.JCR_MIMETYPE).getString())) { return true; } } } return false; } return false; } public boolean isImageType(Node node) throws Exception { if(node.isNodeType(Utils.NT_FILE)) { Node contentNode = node.getNode(Utils.JCR_CONTENT); if(contentNode.getProperty(Utils.JCR_MIMETYPE).getString().startsWith("image")) return true; } return false; } public String getThumbnailImage(Node node) throws Exception { node = node instanceof NodeLinkAware ? ((NodeLinkAware) node).getTargetNode().getRealNode() : node; return Utils.getThumbnailImage(node, ThumbnailService.MEDIUM_SIZE); } public Node getThumbnailNode(Node node) throws Exception { ThumbnailService thumbnailService = getApplicationComponent(ThumbnailService.class); LinkManager linkManager = this.getApplicationComponent(LinkManager.class); if (!linkManager.isLink(node) || linkManager.isTargetReachable(node)) node = node instanceof NodeLinkAware ? ((NodeLinkAware) node).getTargetNode().getRealNode() : node; return thumbnailService.getThumbnailNode(node); } public String getDownloadLink(Node node) throws Exception { return org.exoplatform.wcm.webui.Utils.getDownloadLink(node); } public String getImage(Node node) throws Exception { return getImage(node, Utils.EXO_IMAGE); } public String getImage(Node node, String nodeTypeName) throws Exception { DownloadService dservice = getApplicationComponent(DownloadService.class) ; InputStreamDownloadResource dresource ; Node imageNode = node.getNode(nodeTypeName) ; InputStream input = imageNode.getProperty(Utils.JCR_DATA).getStream() ; dresource = new InputStreamDownloadResource(input, "image") ; dresource.setDownloadName(node.getName()) ; return dservice.getDownloadLink(dservice.addDownloadResource(dresource)) ; } public String getImage(InputStream input, String nodeName) throws Exception { DownloadService dservice = getApplicationComponent(DownloadService.class); InputStreamDownloadResource dresource = new InputStreamDownloadResource(input, "image"); dresource.setDownloadName(nodeName); return dservice.getDownloadLink(dservice.addDownloadResource(dresource)); } public String getWebDAVServerPrefix() throws Exception { PortletRequestContext portletRequestContext = PortletRequestContext.getCurrentInstance() ; String prefixWebDAV = portletRequestContext.getRequest().getScheme() + "://" + portletRequestContext.getRequest().getServerName() ; int serverPort = portletRequestContext.getRequest().getServerPort(); if (serverPort!=80) { prefixWebDAV += ":" + String.format("%s",serverPort); } return prefixWebDAV ; } public Node getViewNode(String nodeType) throws Exception { return getAncestorOfType(UIJCRExplorer.class).getCurrentNode().getNode(nodeType) ; } public Node getNodeByPath(String nodePath, String workspace) throws Exception { ManageableRepository manageRepo = getApplicationComponent(RepositoryService.class).getCurrentRepository(); Session session = WCMCoreUtils.getUserSessionProvider().getSession(workspace, manageRepo) ; return getAncestorOfType(UIJCRExplorer.class).getNodeByPath(nodePath, session) ; } public String getActionsList(Node node) throws Exception { return getAncestorOfType(UIWorkingArea.class).getActionsExtensionList(node) ; } public List<Node> getCustomActions(Node node) throws Exception { return getAncestorOfType(UIWorkingArea.class).getCustomActions(node) ; } public boolean isPreferenceNode(Node node) throws Exception { return getAncestorOfType(UIWorkingArea.class).isPreferenceNode(node) ; } public boolean isReadAuthorized(ExtendedNode node) throws Exception { return getAncestorOfType(UIJCRExplorer.class).isReadAuthorized(node) ; } @SuppressWarnings("unchecked") public Object getComponentInstanceOfType(String className) { Object service = null; try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class clazz = loader.loadClass(className); service = getApplicationComponent(clazz); } catch (ClassNotFoundException ex) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", ex); } } return service; } public String getNodeOwner(Node node) throws RepositoryException { if(node.hasProperty(Utils.EXO_OWNER)) { return node.getProperty(Utils.EXO_OWNER).getString(); } return IdentityConstants.ANONIM ; } public Date getDateCreated(Node node) throws Exception{ if(node.hasProperty(Utils.EXO_CREATED_DATE)) { return node.getProperty(Utils.EXO_CREATED_DATE).getDate().getTime(); } return new GregorianCalendar().getTime(); } public Date getDateModified(Node node) throws Exception { if(node.hasProperty(Utils.EXO_MODIFIED_DATE)) { return node.getProperty(Utils.EXO_MODIFIED_DATE).getDate().getTime(); } return new GregorianCalendar().getTime(); } public List<Node> getRelations() throws Exception { List<Node> relations = new ArrayList<Node>() ; Node currentNode = getCurrentNode(); if (currentNode.hasProperty(Utils.EXO_RELATION)) { Value[] vals = currentNode.getProperty(Utils.EXO_RELATION).getValues(); for (int i = 0; i < vals.length; i++) { String uuid = vals[i].getString(); Node node = getNodeByUUID(uuid); if (node != null) relations.add(node); } } return relations; } public List<Node> getAttachments() throws Exception { List<Node> attachments = new ArrayList<Node>() ; Node currentNode = getCurrentNode(); NodeIterator childrenIterator = currentNode.getNodes(); int attachData =0 ; while (childrenIterator.hasNext()) { Node childNode = childrenIterator.nextNode(); String nodeType = childNode.getPrimaryNodeType().getName(); List<String> listCanCreateNodeType = Utils.getListAllowedFileType(currentNode, templateService) ; if(listCanCreateNodeType.contains(nodeType) ) { // Case of childNode has jcr:data property if (childNode.hasProperty(Utils.JCR_DATA)) { attachData = childNode.getProperty(Utils.JCR_DATA).getStream().available(); // Case of jcr:data has content. if (attachData > 0) attachments.add(childNode); } else { attachments.add(childNode); } } } return attachments; } public String getViewableLink(Node attNode, Parameter[] params) throws Exception { return this.event("ChangeNode", Utils.formatNodeName(attNode.getPath()), params); } public boolean isNodeTypeSupported(String nodeTypeName) { try { return templateService.isManagedNodeType(nodeTypeName); } catch (Exception e) { return false; } } public String getNodeType() throws Exception { return null; } public List<String> getSupportedLocalise() throws Exception { MultiLanguageService multiLanguageService = getApplicationComponent(MultiLanguageService.class) ; return multiLanguageService.getSupportedLanguages(getCurrentNode()); } public String getTemplatePath() throws Exception { return null; } public boolean isNodeTypeSupported() { return false; } public String getVersionName(Node node) throws Exception { return node.getBaseVersion().getName() ; } /** * Method which returns true if the node has a history. */ public boolean hasAuditHistory(Node node) throws Exception{ AuditService auServ = WCMCoreUtils.getService(AuditService.class); node = node instanceof NodeLinkAware ? ((NodeLinkAware) node).getTargetNode().getRealNode() : node; return auServ.hasHistory(node); } /** * Method which returns the number of histories. */ public int getNumAuditHistory(Node node) throws Exception{ AuditService auServ = WCMCoreUtils.getService(AuditService.class); node = node instanceof NodeLinkAware ? ((NodeLinkAware) node).getTargetNode().getRealNode() : node; if (auServ.hasHistory(node)) { AuditHistory auHistory = auServ.getHistory(node); return (auHistory.getAuditRecords()).size(); } return 0; } public void setNode(Node node) { currentNode_ = NodeLocation.getNodeLocationByNode(node); } public boolean isRssLink() { return false ; } public String getRssLink() { return null ; } /** * 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 ; } public String getPortalName() { return WCMCoreUtils.getPortalName(); } public String getRepository() throws Exception { return getAncestorOfType(UIJCRExplorer.class).getRepositoryName(); } public String getWorkspaceName() throws Exception { if(currentNode_ == null) { return getOriginalNode().getSession().getWorkspace().getName(); } return getCurrentNode().getSession().getWorkspace().getName(); } public Node getDisplayNode() throws Exception { Node currentNode = getAncestorOfType(UIJCRExplorer.class).getCurrentNode() ; currentNode_ = NodeLocation.getNodeLocationByNode(currentNode); if(currentNode.hasProperty(Utils.EXO_LANGUAGE)) { String defaultLang = currentNode.getProperty(Utils.EXO_LANGUAGE).getString() ; if(getLanguage() == null) setLanguage(defaultLang) ; if(!getLanguage().equals(defaultLang)) { MultiLanguageService multiServ = getApplicationComponent(MultiLanguageService.class); Node curNode = multiServ.getLanguage(currentNode, getLanguage()); if (currentNode.isNodeType(Utils.NT_FOLDER) || currentNode.isNodeType(Utils.NT_UNSTRUCTURED)) { try { return curNode.getNode(currentNode.getName()); } catch (Exception e) { return curNode; } } return curNode ; } } return currentNode; } public Node getNode() throws Exception { Node ret = getDisplayNode(); if (NodePresentation.MEDIA_STATE_DISPLAY.equals(getMediaState()) && ret.isNodeType(NodetypeConstant.EXO_ACCESSIBLE_MEDIA)) { Node audioDescription = org.exoplatform.services.cms.impl.Utils.getChildOfType(ret, NodetypeConstant.EXO_AUDIO_DESCRIPTION); if (audioDescription != null) { return audioDescription; } } return ret; } public Node getCurrentNode() { return NodeLocation.getNodeByLocation(currentNode_); } public Node getOriginalNode() throws Exception {return getAncestorOfType(UIJCRExplorer.class).getCurrentNode() ;} public String getIcons(Node node, String size) throws Exception { return Utils.getNodeTypeIcon(node, size) ; } public List<Node> getComments() throws Exception { return getApplicationComponent(CommentsService.class).getComments(getCurrentNode(), getLanguage()) ; } public String getViewTemplate(String nodeTypeName, String templateName) throws Exception { TemplateService tempServ = getApplicationComponent(TemplateService.class) ; return tempServ.getTemplatePath(false, nodeTypeName, templateName) ; } public String getTemplateSkin(String nodeTypeName, String skinName) throws Exception { TemplateService tempServ = getApplicationComponent(TemplateService.class) ; return tempServ.getSkinPath(nodeTypeName, skinName, getLanguage()) ; } public String getLanguage() { return getAncestorOfType(UIJCRExplorer.class).getLanguage() ; } public void setLanguage(String language) { getAncestorOfType(UIJCRExplorer.class).setLanguage(language) ; } public boolean isCanPaste() { ClipboardService clipboardService = WCMCoreUtils.getService(ClipboardService.class); String userId = ConversationState.getCurrent().getIdentity().getUserId(); UIJCRExplorer uiExplorer = getAncestorOfType(UIJCRExplorer.class) ; if(!clipboardService.getClipboardList(userId, false).isEmpty()) return true; return false; } public void updatePageListData() throws Exception { UIJCRExplorer uiExplorer = this.getAncestorOfType(UIJCRExplorer.class); String currentPath = uiExplorer.getCurrentPath(); PageList<Object> pageList = getPageList(currentPath); pageIterator_.setPageList(pageList); if (documentNodeList_ != null) { documentNodeList_.removeChild(UIDocumentNodeList.class); documentNodeList_.setPageList(pageList); } updateTimeLineData_ = true; } @SuppressWarnings("unchecked") public PageList<Object> getPageList(String path) throws Exception { UIJCRExplorer uiExplorer = this.getAncestorOfType(UIJCRExplorer.class); Preference pref = uiExplorer.getPreference(); DocumentProviderUtils docProviderUtil = DocumentProviderUtils.getInstance(); if (!uiExplorer.isViewTag() && docProviderUtil.canSortType(pref.getSortType()) && uiExplorer.getAllItemByTypeFilterMap().isEmpty()) { return docProviderUtil.getPageList( uiExplorer.getWorkspaceName(), uiExplorer.getCurrentPath(), pref, uiExplorer.getAllItemFilterMap(), uiExplorer.getAllItemByTypeFilterMap(), (NodeLinkAware) ItemLinkAware.newInstance(uiExplorer.getWorkspaceName(), path, uiExplorer.getNodeByPath(path, uiExplorer.getSession()))); } int nodesPerPage = pref.getNodesPerPage(); List<Node> nodeList = new ArrayList<Node>(); if (uiExplorer.isViewTag() && uiExplorer.getTagPaths() != null && !uiExplorer.getTagPaths().isEmpty()) { nodeList = uiExplorer.getDocumentByTag(); } else { Set<String> allItemByTypeFilterMap = uiExplorer.getAllItemByTypeFilterMap(); if (allItemByTypeFilterMap.size() > 0) nodeList = filterNodeList(uiExplorer.getChildrenList(path, !pref.isShowPreferenceDocuments())); else nodeList = filterNodeList(uiExplorer.getChildrenList(path, pref.isShowPreferenceDocuments())); } ListAccess<Object> nodeAccList = new ListAccessImpl<Object>(Object.class, NodeLocation.getLocationsByNodeList(nodeList)); return new LazyPageList<Object>(nodeAccList, nodesPerPage); } @SuppressWarnings("unchecked") public List<Node> getChildrenList() throws Exception { return NodeLocation.getNodeListByLocationList(pageIterator_.getCurrentPageData()); } public String getTypeSort() { return typeSort_; } public void setTypeSort(String typeSort) { typeSort_ = typeSort; } public String getSortOrder() { return sortOrder_; } public void setSortOrder(String sortOrder) { sortOrder_ = sortOrder; } public String encodeHTML(String text) { return Utils.encodeHTML(text) ; } public UIComponent getCommentComponent() { UIJCRExplorer uiExplorer = getAncestorOfType(UIJCRExplorer.class); UIActionBar uiActionBar = uiExplorer.findFirstComponentOfType(UIActionBar.class); UIComponent uicomponent = uiActionBar.getUIAction(COMMENT_COMPONENT); return (uicomponent != null ? uicomponent : this); } public boolean isEnableThumbnail() { ThumbnailService thumbnailService = getApplicationComponent(ThumbnailService.class); return thumbnailService.isEnableThumbnail(); } public String getFlowImage(Node node) throws Exception { node = node instanceof NodeLinkAware ? ((NodeLinkAware) node).getTargetNode().getRealNode() : node; return Utils.getThumbnailImage(node, ThumbnailService.BIG_SIZE); } public String getThumbnailSize(Node node) throws Exception { node = node instanceof NodeLinkAware ? ((NodeLinkAware) node).getTargetNode().getRealNode() : node; String imageSize = null; if(node.hasProperty(ThumbnailService.BIG_SIZE)) { Image image = ImageIO.read(node.getProperty(ThumbnailService.BIG_SIZE).getStream()); imageSize = Integer.toString(image.getWidth(null)) + "x" + Integer.toString(image.getHeight(null)); } return imageSize; } public DateFormat getSimpleDateFormat() { Locale locale = Util.getUIPortal().getAncestorOfType(UIPortalApplication.class).getLocale(); return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT, locale); } public boolean isSymLink(Node node) throws RepositoryException { LinkManager linkManager = getApplicationComponent(LinkManager.class); return linkManager.isLink(node); } public UIComponent getRemoveAttach() throws Exception { removeChild(RemoveAttachmentComponent.class); UIComponent uicomponent = addChild(RemoveAttachmentComponent.class, null, "DocumentInfoRemoveAttach"); ((AbstractActionComponent)uicomponent).setLstComponentupdate(Arrays.asList(new Class[] {UIDocumentContainer.class})); return uicomponent; } public UIComponent getRemoveComment() throws Exception { removeChild(RemoveCommentComponent.class); UIComponent uicomponent = addChild(RemoveCommentComponent.class, null, "DocumentInfoRemoveComment"); ((AbstractActionComponent) uicomponent).setLstComponentupdate(Arrays.asList(new Class[] { UIDocumentContainer.class, UIWorkingArea.class })); return uicomponent; } public boolean isFavouriter(Node data) throws Exception { return isFavouriteNode(WCMCoreUtils.getRemoteUser(), data); } public boolean isFavouriteNode(String userName, Node node) throws Exception { return getApplicationComponent(FavoriteService.class).isFavoriter(userName, node); } public boolean isMediaType(Node data) throws Exception { if (!data.isNodeType(Utils.NT_FILE)) return false; String mimeType = data.getNode(Utils.JCR_CONTENT).getProperty(Utils.JCR_MIMETYPE).getString(); UIExtensionManager manager = getApplicationComponent(UIExtensionManager.class); Map<String, Object> context = new HashMap<String, Object>(); context.put(Utils.MIME_TYPE, mimeType); if (manager.accept(Utils.FILE_VIEWER_EXTENSION_TYPE, "VideoAudio", context)) { return true; } return false; } public String getPropertyNameWithoutNamespace(String propertyName) { if(propertyName.indexOf(":") > -1) { return propertyName.split(":")[1]; } return propertyName; } public String getPropertyValue(Node node, String propertyName) throws Exception { try { Property property = node.getProperty(propertyName); if(property != null) { int requiredType = property.getDefinition().getRequiredType(); switch (requiredType) { case PropertyType.STRING: return property.getString(); case PropertyType.DATE: return getSimpleDateFormat().format(property.getDate().getTime()); } } } catch(PathNotFoundException PNE) { return ""; } return ""; } public DriveData getDrive(List<DriveData> lstDrive, Node node) throws RepositoryException{ DriveData driveData = null; for (DriveData drive : lstDrive) { if (node.getSession().getWorkspace().getName().equals(drive.getWorkspace()) && node.getPath().contains(drive.getHomePath()) && drive.getHomePath().equals("/")) { driveData = drive; break; } } return driveData; } public List<Node> filterNodeList(List<Node> sourceNodeList) throws Exception { List<Node> ret = new ArrayList<Node>(); if (!this.hasFilters()) { return sourceNodeList; } for (Node node : sourceNodeList) { try { if (filterOk(node)) ret.add(node); } catch (Exception ex) { if (LOG.isWarnEnabled()) { LOG.warn(ex.getMessage()); } } } return ret; } private boolean hasFilters() { UIJCRExplorer uiExplorer = this.getAncestorOfType(UIJCRExplorer.class); Set<String> allItemsFilterSet = uiExplorer.getAllItemFilterMap(); Set<String> allItemsByTypeFilterSet = uiExplorer.getAllItemByTypeFilterMap(); return (allItemsByTypeFilterSet.size() > 0 || allItemsFilterSet.size() > 0); } private boolean filterOk(Node node) throws Exception { UIJCRExplorer uiExplorer = this.getAncestorOfType(UIJCRExplorer.class); Set<String> allItemsFilterSet = uiExplorer.getAllItemFilterMap(); Set<String> allItemsByTypeFilterSet = uiExplorer.getAllItemByTypeFilterMap(); String userId = WCMCoreUtils.getRemoteUser(); //Owned by me if (allItemsFilterSet.contains(NodetypeConstant.OWNED_BY_ME) && !userId.equals(node.getProperty(NodetypeConstant.EXO_OWNER).getString())) return false; //Favorite if (allItemsFilterSet.contains(NodetypeConstant.FAVORITE) && !favoriteService.isFavoriter(userId, node)) return false; //Hidden /* Behaviour of this filter is different from the others, it shows up hidden nodes or not, not just filter them. */ //By types if(allItemsByTypeFilterSet.isEmpty()) return true; boolean found = false; try { for (String documentType : allItemsByTypeFilterSet) { for (String mimeType : documentTypeService.getMimeTypes(documentType)) { if(node.hasNode(Utils.JCR_CONTENT)){ Node content = node.getNode(Utils.JCR_CONTENT); if (content.hasProperty(Utils.JCR_MIMETYPE) && content.getProperty(Utils.JCR_MIMETYPE).getString().indexOf(mimeType) >= 0) { found = true; break; } } } } } catch (PathNotFoundException ep) { if (LOG.isErrorEnabled()) { LOG.error("Cannot found the node path in the repository. We will continue filter by content type in the next block code."); } } if(!found && allItemsByTypeFilterSet.contains(Contents_Document_Type)) { for(String contentType:templateService.getAllDocumentNodeTypes()){ if (node.isNodeType(contentType)){ found=true; break; } } } return found; } static public class ViewNodeActionListener extends EventListener<UIDocumentInfo> { public void execute(Event<UIDocumentInfo> event) throws Exception { UIDocumentInfo uicomp = event.getSource() ; UIApplication uiApp = uicomp.getAncestorOfType(UIApplication.class); UIJCRExplorer uiExplorer = uicomp.getAncestorOfType(UIJCRExplorer.class); try { String uri = event.getRequestContext().getRequestParameter(OBJECTID) ; String workspaceName = event.getRequestContext().getRequestParameter("workspaceName") ; uiExplorer.setSelectNode(workspaceName, uri) ; uiExplorer.updateAjax(event) ; event.broadcast(); } catch(RepositoryException e) { LOG.error("Error Refreshing selected node", e); uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.repository-error", null, ApplicationMessage.WARNING)) ; return ; } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } } } static public class ChangeNodeActionListener extends EventListener<UIDocumentInfo> { public void execute(Event<UIDocumentInfo> event) throws Exception { UIDocumentInfo uicomp = event.getSource(); NodeFinder nodeFinder = uicomp.getApplicationComponent(NodeFinder.class); UIJCRExplorer uiExplorer = uicomp.getAncestorOfType(UIJCRExplorer.class); UITreeExplorer uiTreeExplorer = uiExplorer.findFirstComponentOfType(UITreeExplorer.class); String uri = event.getRequestContext().getRequestParameter(OBJECTID); String workspaceName = event.getRequestContext().getRequestParameter("workspaceName"); boolean findDrive = Boolean.getBoolean(event.getRequestContext().getRequestParameter("findDrive")); UIApplication uiApp = uicomp.getAncestorOfType(UIApplication.class); AutoVersionService autoVersionService = WCMCoreUtils.getService(AutoVersionService.class); try { // Manage ../ and ./ uri = LinkUtils.evaluatePath(uri); // Just in order to check if the node exists Item item = nodeFinder.getItem(workspaceName, uri); if ((item instanceof Node) && Utils.isInTrash((Node) item)) { return; } uiExplorer.setSelectNode(workspaceName, uri); if (findDrive) { ManageDriveService manageDriveService = uicomp.getApplicationComponent(ManageDriveService.class); List<DriveData> driveList = manageDriveService.getDriveByUserRoles(Util.getPortalRequestContext() .getRemoteUser(), Utils.getMemberships()); DriveData drive = uicomp.getDrive(driveList, uiExplorer.getCurrentNode()); String warningMSG = null; if (driveList.size() == 0) { warningMSG = "UIDocumentInfo.msg.access-denied"; } else if (drive == null) { warningMSG = "UIPopupMenu.msg.path-not-found-exception"; } if (warningMSG != null) { uiApp.addMessage(new ApplicationMessage(warningMSG, null, ApplicationMessage.WARNING)) ; return ; } uiExplorer.setDriveData(uicomp.getDrive(driveList, uiExplorer.getCurrentNode())); } uiExplorer.updateAjax(event); event.getRequestContext().getJavascriptManager(). require("SHARED/multiUpload", "multiUpload"). addScripts("multiUpload.setLocation('" + uiExplorer.getWorkspaceName() + "','" + uiExplorer.getDriveData().getName() + "','" + uiTreeExplorer.getLabel() + "','" + uiExplorer.getCurrentPath() + "','" + org.exoplatform.services.cms.impl.Utils.getPersonalDrivePath(uiExplorer.getDriveData().getHomePath(), ConversationState.getCurrent().getIdentity().getUserId())+ "', '"+ autoVersionService.isVersionSupport(uiExplorer.getCurrentPath(), uiExplorer.getCurrentWorkspace())+"');"); } catch(ItemNotFoundException nu) { uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.null-exception", null, ApplicationMessage.WARNING)) ; return ; } catch(PathNotFoundException pa) { uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.path-not-found", null, ApplicationMessage.WARNING)) ; return ; } catch(AccessDeniedException ace) { uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.access-denied", null, ApplicationMessage.WARNING)) ; return ; } catch(RepositoryException e) { LOG.error("An error occurred while accessing repository", e); uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.repository-error", null, ApplicationMessage.WARNING)) ; return ; } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } } } static public class SortActionListener extends EventListener<UIDocumentInfo> { public void execute(Event<UIDocumentInfo> event) throws Exception { UIDocumentInfo uicomp = event.getSource() ; UIJCRExplorer uiExplorer = uicomp.getAncestorOfType(UIJCRExplorer.class); UIApplication uiApp = uicomp.getAncestorOfType(UIApplication.class); try { String sortParam = event.getRequestContext().getRequestParameter(OBJECTID) ; String[] array = sortParam.split(";"); String order = Preference.ASCENDING_ORDER.equals(array[0].trim()) || !array[1].trim().equals(uicomp.getTypeSort()) ? Preference.BLUE_DOWN_ARROW : Preference.BLUE_UP_ARROW; String prefOrder = Preference.ASCENDING_ORDER.equals(array[0].trim()) || !array[1].trim().equals(uicomp.getTypeSort())? Preference.ASCENDING_ORDER : Preference.DESCENDING_ORDER; if(!uicomp.getTypeSort().equals(array[1].trim()) && array[1].trim().equals("Date")){ order = Preference.BLUE_UP_ARROW; prefOrder = Preference.DESCENDING_ORDER; } uicomp.setSortOrder(order); uicomp.setTypeSort(array[1]); Preference pref = uiExplorer.getPreference(); if (array.length == 2) { pref.setSortType(array[1].trim()); pref.setOrder(prefOrder); } else { return ; } uiExplorer.updateAjax(event) ; } catch(RepositoryException e) { LOG.error("An error occurred while accessing repository", e); uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.repository-error", null, ApplicationMessage.WARNING)) ; return ; } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } } } static public class ChangeLanguageActionListener extends EventListener<UIDocumentInfo> { public void execute(Event<UIDocumentInfo> event) throws Exception { UIDocumentInfo uiDocumentInfo = event.getSource() ; UIJCRExplorer uiExplorer = uiDocumentInfo.getAncestorOfType(UIJCRExplorer.class) ; UIApplication uiApp = uiDocumentInfo.getAncestorOfType(UIApplication.class); try { String selectedLanguage = event.getRequestContext().getRequestParameter(OBJECTID) ; uiExplorer.setLanguage(selectedLanguage) ; uiExplorer.updateAjax(event) ; } catch(RepositoryException e) { LOG.error("An error occurred while accessing repository", e); uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.repository-error", null, ApplicationMessage.WARNING)) ; return ; } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } } } static public class VoteActionListener extends EventListener<UIDocumentInfo> { public void execute(Event<UIDocumentInfo> event) throws Exception { UIDocumentInfo uiComp = event.getSource(); UIApplication uiApp = uiComp.getAncestorOfType(UIApplication.class); try { String userName = Util.getPortalRequestContext().getRemoteUser() ; double objId = Double.parseDouble(event.getRequestContext().getRequestParameter(OBJECTID)) ; VotingService votingService = uiComp.getApplicationComponent(VotingService.class) ; votingService.vote(uiComp.getCurrentNode(), objId, userName, uiComp.getLanguage()) ; } catch(RepositoryException e) { LOG.error("An error occurred while accessing repository", e); uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.repository-error", null, ApplicationMessage.WARNING)) ; return ; } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } } } static public class DownloadActionListener extends EventListener<UIDocumentInfo> { public void execute(Event<UIDocumentInfo> event) throws Exception { UIDocumentInfo uiComp = event.getSource(); UIApplication uiApp = uiComp.getAncestorOfType(UIApplication.class); try { String downloadLink = uiComp.getDownloadLink(org.exoplatform.wcm.webui.Utils.getFileLangNode(uiComp.getNode())); RequireJS requireJS = event.getRequestContext().getJavascriptManager().getRequireJS(); requireJS.require("SHARED/ecm-utils", "ecmutil").addScripts("ecmutil.ECMUtils.ajaxRedirect('" + downloadLink + "');"); } catch(RepositoryException e) { LOG.error("An error occurred while accessing repository", e); uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.repository-error", null, ApplicationMessage.WARNING)) ; return ; } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } } } static public class StarClickActionListener extends EventListener<UIDocumentInfo> { public void execute(Event<UIDocumentInfo> event) throws Exception { String srcPath = event.getRequestContext().getRequestParameter(OBJECTID); UIDocumentInfo uiDocumentInfo = event.getSource(); UIJCRExplorer uiExplorer = uiDocumentInfo.getAncestorOfType(UIJCRExplorer.class); UIApplication uiApp = uiDocumentInfo.getAncestorOfType(UIApplication.class); FavoriteService favoriteService = uiDocumentInfo.getApplicationComponent(FavoriteService.class); Matcher matcher = UIWorkingArea.FILE_EXPLORER_URL_SYNTAX.matcher(srcPath); String wsName = null; Node node = null; if (matcher.find()) { wsName = matcher.group(1); srcPath = matcher.group(2); } else { throw new IllegalArgumentException("The ObjectId is invalid '"+ srcPath + "'"); } Session session = null; try { session = uiExplorer.getSessionByWorkspace(wsName); // Use the method getNodeByPath because it is link aware node = uiExplorer.getNodeByPath(srcPath, session, false); // Reset the path to manage the links that potentially create virtual path srcPath = node.getPath(); // Reset the session to manage the links that potentially change of workspace session = node.getSession(); // Reset the workspace name to manage the links that potentially change of workspace wsName = session.getWorkspace().getName(); } catch(PathNotFoundException path) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.path-not-found-exception", null,ApplicationMessage.WARNING)); return; } catch(RepositoryException e) { LOG.error("An error occurred while accessing repository", e); uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.repository-error", null, ApplicationMessage.WARNING)) ; return ; } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } try { uiExplorer.addLockToken(node); } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } try { if (favoriteService.isFavoriter(WCMCoreUtils.getRemoteUser(), node)) { if (PermissionUtil.canRemoveNode(node)) { favoriteService.removeFavorite(node, WCMCoreUtils.getRemoteUser()); } else { throw new AccessDeniedException(); } } else { if (PermissionUtil.canSetProperty(node)) { favoriteService.addFavorite(node, WCMCoreUtils.getRemoteUser()); } else { throw new AccessDeniedException(); } } //uiStar.changeFavourite(); uiExplorer.updateAjax(event); } catch (AccessDeniedException e) { if (LOG.isErrorEnabled()) { LOG.error("Access denied! No permission for modifying property " + Utils.EXO_FAVOURITER + " of node: " + node.getPath()); } uiApp.addMessage(new ApplicationMessage("UIShowAllFavouriteResult.msg.accessDenied", null, ApplicationMessage.WARNING)); } catch (VersionException ve) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.remove-verion-exception", null, ApplicationMessage.WARNING)); uiExplorer.updateAjax(event); return; } catch (ReferentialIntegrityException ref) { session.refresh(false); uiExplorer.refreshExplorer(); uiApp .addMessage(new ApplicationMessage( "UIPopupMenu.msg.remove-referentialIntegrityException", null, ApplicationMessage.WARNING)); uiExplorer.updateAjax(event); return; } catch (ConstraintViolationException cons) { session.refresh(false); uiExplorer.refreshExplorer(); uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.constraintviolation-exception", null, ApplicationMessage.WARNING)); uiExplorer.updateAjax(event); return; } catch (LockException lockException) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.node-locked-other-person", null, ApplicationMessage.WARNING)); uiExplorer.updateAjax(event); return; } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("an unexpected error occurs while removing the node", e); } JCRExceptionManager.process(uiApp, e); return; } } } static public class SortTimelineASCActionListener extends EventListener<UIDocumentInfo> { public void execute(Event<UIDocumentInfo> event) throws Exception { UIDocumentInfo uiDocumentInfo = event.getSource(); String objectID = event.getRequestContext().getRequestParameter(OBJECTID); if (objectID.equals("favourite")) { uiDocumentInfo.timeLineSortByFavourite = Preference.BLUE_DOWN_ARROW; uiDocumentInfo.timeLineSortByName = ""; uiDocumentInfo.timeLineSortByDate = ""; } else if (objectID.equals("name")) { uiDocumentInfo.timeLineSortByFavourite = ""; uiDocumentInfo.timeLineSortByName = Preference.BLUE_DOWN_ARROW; uiDocumentInfo.timeLineSortByDate = ""; } else if (objectID.equals("dateTime")) { uiDocumentInfo.timeLineSortByFavourite = ""; uiDocumentInfo.timeLineSortByName = ""; uiDocumentInfo.timeLineSortByDate = Preference.BLUE_DOWN_ARROW; } uiDocumentInfo.updateNodeLists(); event.getRequestContext().addUIComponentToUpdateByAjax(uiDocumentInfo); } } static public class SortTimelineDESCActionListener extends EventListener<UIDocumentInfo> { public void execute(Event<UIDocumentInfo> event) throws Exception { UIDocumentInfo uiDocumentInfo = event.getSource(); String objectID = event.getRequestContext().getRequestParameter(OBJECTID); if (objectID.equals("favourite")) { uiDocumentInfo.timeLineSortByFavourite = Preference.BLUE_UP_ARROW; uiDocumentInfo.timeLineSortByName = ""; uiDocumentInfo.timeLineSortByDate = ""; } else if (objectID.equals("name")) { uiDocumentInfo.timeLineSortByFavourite = ""; uiDocumentInfo.timeLineSortByName = Preference.BLUE_UP_ARROW; uiDocumentInfo.timeLineSortByDate = ""; } else if (objectID.equals("dateTime")) { uiDocumentInfo.timeLineSortByFavourite = ""; uiDocumentInfo.timeLineSortByName = ""; uiDocumentInfo.timeLineSortByDate = Preference.BLUE_UP_ARROW; } uiDocumentInfo.updateNodeLists(); event.getRequestContext().addUIComponentToUpdateByAjax(uiDocumentInfo); } } static public class SwitchToAudioDescriptionActionListener extends EventListener<UIDocumentInfo> { public void execute(Event<UIDocumentInfo> event) throws Exception { UIDocumentInfo uiDocumentInfo = event.getSource(); UIJCRExplorer uiExplorer = uiDocumentInfo.getAncestorOfType(UIJCRExplorer.class); uiDocumentInfo.switchMediaState(); event.getRequestContext().addUIComponentToUpdateByAjax(uiExplorer); } } static public class SwitchToOriginalActionListener extends EventListener<UIDocumentInfo> { public void execute(Event<UIDocumentInfo> event) throws Exception { UIDocumentInfo uiDocumentInfo = event.getSource(); UIJCRExplorer uiExplorer = uiDocumentInfo.getAncestorOfType(UIJCRExplorer.class); uiDocumentInfo.switchMediaState(); event.getRequestContext().addUIComponentToUpdateByAjax(uiExplorer); } } // public boolean isRenderAccessibleMedia() { // Node originalNode = getOriginalNode(); // if (!originalNode.hasNode("audioDescription")) return false; // Node audioDescription = originalNode.getNode("audioDescription"); // if (!audioDescription.isNodeType("exo:audioDescription")) return false; // return true; // } static public class ShowPageActionListener extends EventListener<UIPageIterator> { public void execute(Event<UIPageIterator> event) throws Exception { UIPageIterator uiPageIterator = event.getSource() ; // If in the timeline view, then does not have the equivalent paginator on the left tree view explorer if (!UIDocumentInfo.CONTENT_PAGE_ITERATOR_ID.equalsIgnoreCase(uiPageIterator.getId())) { return; } UIApplication uiApp = uiPageIterator.getAncestorOfType(UIApplication.class); UIJCRExplorer explorer = uiPageIterator.getAncestorOfType(UIJCRExplorer.class); UITreeExplorer treeExplorer = explorer.findFirstComponentOfType(UITreeExplorer.class); try { if(treeExplorer == null) return; String componentId = explorer.getCurrentNode().getPath(); UITreeNodePageIterator extendedPageIterator = treeExplorer.getUIPageIterator(componentId); if(extendedPageIterator == null) return; int page = Integer.parseInt(event.getRequestContext().getRequestParameter(OBJECTID)) ; extendedPageIterator.setCurrentPage(page); event.getRequestContext().addUIComponentToUpdateByAjax(explorer); } catch(RepositoryException e) { LOG.error("An error occurred while accessing repository", e); uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.repository-error", null, ApplicationMessage.WARNING)) ; return ; } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } } } private class SearchComparator implements Comparator<NodeLocation> { public int compare(NodeLocation nodeA, NodeLocation nodeB) { try { Node node1 = NodeLocation.getNodeByLocation(nodeA); Node node2 = NodeLocation.getNodeByLocation(nodeB); if (timeLineSortByFavourite.length() != 0) { int factor = (timeLineSortByFavourite.equals(Preference.BLUE_DOWN_ARROW)) ? 1 : -1; if (isFavouriter(node1)) return -1 * factor; else if (isFavouriter(node2)) return 1 * factor; else return 0; } else if (timeLineSortByDate.length() != 0) { int factor = timeLineSortByDate.equals(Preference.BLUE_DOWN_ARROW) ? 1 : -1; Calendar c1 = node1.getProperty(Utils.EXO_MODIFIED_DATE).getValue().getDate(); Calendar c2 = node2.getProperty(Utils.EXO_MODIFIED_DATE).getValue().getDate(); return factor * c1.compareTo(c2); } else if (timeLineSortByName.length() != 0) { int factor = timeLineSortByName.equals(Preference.BLUE_DOWN_ARROW) ? 1 : -1; String s1 = Utils.getTitle(node1).toLowerCase(); String s2 = Utils.getTitle(node2).toLowerCase(); return factor * s1.compareTo(s2); } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Cannot compare nodes", e); } } return 0; } } static public class CollapseTimelineCatergoryActionListener extends EventListener<UIDocumentInfo> { @Override public void execute(Event<UIDocumentInfo> event) throws Exception { UIDocumentInfo uiDocumentInfo = event.getSource(); UIJCRExplorer uiExplorer = uiDocumentInfo.getAncestorOfType(UIJCRExplorer.class); uiDocumentInfo.displayCategory_ = UIDocumentInfo.CATEGORY_ALL; uiExplorer.updateAjax(event); } } static public class ExpandTimelineCatergoryActionListener extends EventListener<UIDocumentInfo> { @Override public void execute(Event<UIDocumentInfo> event) throws Exception { UIDocumentInfo uiDocumentInfo = event.getSource(); UIJCRExplorer uiExplorer = uiDocumentInfo.getAncestorOfType(UIJCRExplorer.class); String category = event.getRequestContext().getRequestParameter(OBJECTID); uiDocumentInfo.displayCategory_ = category; uiExplorer.updateAjax(event); } } public boolean isEnableComment() { return true; } public boolean isEnableVote() { return true; } public void setEnableComment(boolean value) { } public void setEnableVote(boolean value) { } 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); } /** * @return the itemsPerTimeline */ public int getItemsPerTimeline() { if (itemsPerTimeline <=0 ) { return 5; } return itemsPerTimeline; } /** * * @return */ public HashMap<String, String> getIsExpanded() { return isExpanded_; } public Set<String> getExpandedFolders() { return this.expandedFolders_; } @Override public boolean isDisplayAlternativeText() { try { Node node = this.getNode(); return node.isNodeType(NodetypeConstant.EXO_ACCESSIBLE_MEDIA) && 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) && 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); } catch (Exception e) { return false; } } /** * checks if user has permission to add nt:file to current node * @throws Exception */ public boolean canAddNode() throws Exception { Node currentNode = getAncestorOfType(UIJCRExplorer.class).getCurrentNode(); return canAddNode(currentNode); } /** * checks if user has permission to add nt:file to node * @throws Exception */ public boolean canAddNode(Node node) throws Exception { if (node == null || !PermissionUtil.canAddNode(node) || !node.isCheckedOut()) { return false; } if (node.isLocked()) { //check for lock String lockToken = LockUtil.getLockTokenOfUser(node); if(lockToken == null) { return false; } } LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class); if(linkManager.isLink(node)) { try { linkManager.getTarget(node); } catch(ItemNotFoundException ine) { return false; } } List<NodeDefinition> defs = new ArrayList<NodeDefinition>(); if(node.getPrimaryNodeType().getChildNodeDefinitions() != null) { defs.addAll(Arrays.asList(node.getPrimaryNodeType().getChildNodeDefinitions())); } for (NodeType mix : node.getMixinNodeTypes()) { if(mix.getChildNodeDefinitions() != null) { defs.addAll(Arrays.asList(mix.getChildNodeDefinitions())); } } for (NodeDefinition def : defs) { for (NodeType type : def.getRequiredPrimaryTypes()) { if ((NodetypeConstant.NT_FILE.equals(type.getName()) || NodetypeConstant.NT_BASE.equals(type.getName()) || NodetypeConstant.NT_HIERARCHY_NODE.equals(type.getName())) && "*".equals(def.getName())) { return true; } } } return false; } public String getDragAndDropEvents(Node node) throws Exception{ //define events for drag&drop files into subfolders // if (this.canAddNode(node)) { StringBuilder dragEvents = new StringBuilder().append("ondragover='eXo.ecm.MultiUpload.enableDragItemArea(event, this)' "). append("ondragleave='eXo.ecm.MultiUpload.disableDragItemArea(this)' "). append("ondragend='eXo.ecm.MultiUpload.disableDragItemArea(this)' "). append("onmouseout='eXo.ecm.MultiUpload.disableDragItemArea(this)' "); //add ondrop event dragEvents.append("ondrop='eXo.ecm.MultiUpload.doDropItemArea(event, this,\""). append(node.getPath()).append("\")' "); return dragEvents.toString(); // } else { // return ""; // } } @Override public void processRender(WebuiRequestContext context) throws Exception { if(!context.useAjax()) updatePageListData(); //check if current user can add node to current node //for MuiltUpload drag&drop feature if (canAddNode()) { context.getJavascriptManager().require("SHARED/multiUpload", "multiUpload"). addScripts("multiUpload.registerEvents('" + this.getId() +"');"); } else { context.getJavascriptManager().require("SHARED/multiUpload", "multiUpload"). addScripts("multiUpload.unregisterEvents();"); } super.processRender(context); } public boolean hasChildren(Node node) { return false; } public List<Node> getChildrenFromNode(Node node) { return null; } /** get node attribute in Icons View and Web View **/ public String getNodeAttributeInView(Node node) throws Exception { String preferenceWS = node.getSession().getWorkspace().getName(); String attr = getNodeAttributeInCommon(node); StringBuilder builder = new StringBuilder(attr); String rightClickMenu = ""; // right click menu in Icon View if(!isSystemWorkspace()) rightClickMenu = "" + getContextMenu().getJSOnclickShowPopup(preferenceWS + ":" + Utils.formatNodeName(node.getPath()), getActionsList(node)); builder.append(rightClickMenu); return builder.toString(); } /** get node attribute in Admin View **/ public String getNodeAttribute(Node node) throws Exception { StringBuilder builder = new StringBuilder(); String preferenceWS = node.getSession().getWorkspace().getName(); builder.append(getNodeAttributeInCommon(node)); // right click menu in Admin View if (!isSystemWorkspace()) { builder.append(" onmousedown=\"eXo.ecm.UIFileView.clickRightMouse(event, this, 'ECMContextMenu','"); builder.append(preferenceWS + ":"); builder.append(Utils.formatNodeName(node.getPath()) + "','" ); builder.append(getActionsList(node) + "');\""); } return builder.toString(); } /** get Attribute in common. */ private String getNodeAttributeInCommon(Node node) throws Exception { StringBuilder builder = new StringBuilder(); String preferenceWS = node.getSession().getWorkspace().getName(); // drag and drop events builder.append(" " + getDragAndDropEvents(node)); // in common builder.append(" trashHome='" + Utils.isTrashHomeNode(node) + "' "); builder.append(" locked='" + node.isLocked() + "' "); builder.append(" mediaType='" + isMediaType(node) + "' "); builder.append(" removeFavourite='" + isFavouriter(node) + "' "); builder.append(" inTrash='" + node.isNodeType("exo:restoreLocation") + "' "); builder.append(" workspacename='" + preferenceWS + "' "); builder.append(" objectId='" + org.exoplatform.services.cms.impl.Utils.getObjectId(node.getPath()) + "' "); builder.append(" isFile='" + node.isNodeType("nt:file") + "' "); builder.append(" isLinkWithTarget='" + Utils.targetNodeAndLinkInTrash(node) + "' "); builder.append(" isAbleToRestore='" + Utils.isAbleToRestore(node) + "' "); builder.append(" isExoAction='" + (Utils.EXO_ACTIONS.equals(node.getName()) && Utils.isInTrash(node)) + "' "); builder.append(" isCheckedIn='" + !node.isCheckedOut() + "' "); builder.append(" isSpecificFolder='" + org.exoplatform.services.cms.impl.Utils.isPersonalDefaultFolder(node) + "' "); return builder.toString(); } public UIPopupContainer getPopupContainer() throws Exception { return this.getAncestorOfType(UIJCRExplorer.class).getChild(UIPopupContainer.class); } }
83,446
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIJcrExplorerEditContainer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIJcrExplorerEditContainer.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.explorer; import org.exoplatform.ecm.webui.tree.selectone.UIOneNodePathSelector; import org.exoplatform.ecm.webui.tree.selectone.UIWorkspaceList; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; import org.exoplatform.webui.form.UIFormSelectBox; /** * Created by The eXo Platform SARL * Author : Ly Dinh Quang * quang.ly@exoplatform.com * xxx5669@gmail.com * 4 févr. 09 */ @ComponentConfig( lifecycle = UIContainerLifecycle.class ) public class UIJcrExplorerEditContainer extends UIContainer { public UIJcrExplorerEditContainer() throws Exception { addChild(UIJcrExplorerEditForm.class, null, null); } public UIPopupWindow initPopup(String id) throws Exception { removeChildById(id); UIPopupWindow uiPopup = addChild(UIPopupWindow.class, null, id); uiPopup.setShowMask(true); uiPopup.setWindowSize(700, 350); uiPopup.setShow(true); uiPopup.setResizable(true); return uiPopup; } public UIPopupWindow initPopupDriveBrowser(String id, String driveName) throws Exception { String repository = getAncestorOfType(UIJCRExplorerPortlet.class).getPreferenceRepository(); UIPopupWindow uiPopup = initPopup(id); UIOneNodePathSelector uiOneNodePathSelector = createUIComponent(UIOneNodePathSelector.class, null, null); UIWorkspaceList uiWorkspaceList= uiOneNodePathSelector.getChild(UIWorkspaceList.class); uiOneNodePathSelector.setShowRootPathSelect(true); uiWorkspaceList.getChild(UIFormSelectBox.class).setRendered(false); ManageDriveService manageDrive = getApplicationComponent(ManageDriveService.class); DriveData driveData = manageDrive.getDriveByName(driveName); uiOneNodePathSelector.setRootNodeLocation(repository, driveData.getWorkspace(), driveData.getHomePath()); uiOneNodePathSelector.init(WCMCoreUtils.getUserSessionProvider()); uiPopup.setUIComponent(uiOneNodePathSelector); uiOneNodePathSelector.setSourceComponent(this.getChild(UIJcrExplorerEditForm.class), new String[] { UIJcrExplorerEditForm.PARAM_PATH_INPUT }); uiPopup.setRendered(true); uiPopup.setShow(true); uiPopup.setShowMask(true); return uiPopup; } }
3,344
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDrivesArea.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/UIDrivesArea.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.component.explorer; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.stream.Collectors; import javax.jcr.AccessDeniedException; import javax.jcr.NoSuchWorkspaceException; import javax.jcr.Node; import javax.jcr.Session; import org.exoplatform.container.definition.PortalContainerConfig; import org.exoplatform.container.xml.PortalContainerInfo; import org.exoplatform.ecm.jcr.model.Preference; import org.exoplatform.ecm.webui.component.explorer.control.UIActionBar; import org.exoplatform.ecm.webui.component.explorer.control.UIAddressBar; import org.exoplatform.ecm.webui.component.explorer.control.UIControl; import org.exoplatform.ecm.webui.component.explorer.popup.actions.UIDocumentForm; import org.exoplatform.ecm.webui.component.explorer.popup.actions.UIDocumentFormController; import org.exoplatform.ecm.webui.component.explorer.sidebar.UIAllItems; import org.exoplatform.ecm.webui.component.explorer.sidebar.UISideBar; import org.exoplatform.ecm.webui.component.explorer.sidebar.UITreeExplorer; import org.exoplatform.ecm.webui.utils.JCRExceptionManager; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.documents.AutoVersionService; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.drives.impl.ManageDriveServiceImpl; import org.exoplatform.services.cms.views.ManageViewService; 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.organization.OrganizationService; import org.exoplatform.services.organization.User; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.wcm.core.NodetypeConstant; 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.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Oct 21, 2009 * 9:58:02 AM */ @ComponentConfig ( template = "app:/groovy/webui/component/explorer/UIDrivesArea.gtmpl", events = { @EventConfig(listeners = UIDrivesArea.SelectDriveActionListener.class) } ) public class UIDrivesArea extends UIContainer { final public static String FIELD_SELECTREPO = "selectRepo" ; private boolean firstVisit = true; private List<String> userRoles_ = null; public UIDrivesArea() throws Exception { } public void setFirstVisit(boolean firstVisit) { this.firstVisit = firstVisit; } public boolean isFirstVisit() { return firstVisit; } public String getLabel(String id) { RequestContext context = RequestContext.getCurrentInstance(); ResourceBundle res = context.getApplicationResourceBundle(); String userDisplayName = ""; if (ManageDriveServiceImpl.USER_DRIVE_NAME.equals(id)) { RequestContext ctx = Util.getPortalRequestContext(); if (ctx != null) { String username = ctx.getRemoteUser(); try { User user = this.getApplicationComponent(OrganizationService.class).getUserHandler().findUserByName(username); if (user != null) { userDisplayName = user.getDisplayName(); } } catch (Exception ex) { userDisplayName = username; } } } try { return res.getString("Drives.label." + id.replace(" ", "")).replace("{0}", userDisplayName); } catch (MissingResourceException ex) { return id; } } public String getGroupLabel(DriveData driveData) { try { RepositoryService repoService = WCMCoreUtils.getService(RepositoryService.class); NodeHierarchyCreator nodeHierarchyCreator = WCMCoreUtils.getService(NodeHierarchyCreator.class); String groupPath = nodeHierarchyCreator.getJcrPath(BasePath.CMS_GROUPS_PATH); Node groupNode = (Node)WCMCoreUtils.getSystemSessionProvider().getSession( repoService.getCurrentRepository().getConfiguration().getDefaultWorkspaceName(), repoService.getCurrentRepository()).getItem( groupPath + driveData.getName().replace(".", "/")); return groupNode.getProperty(NodetypeConstant.EXO_LABEL).getString(); } catch(Exception e) { return driveData.getName().replace(".", " / "); } } public String getGroupLabel(String groupId, boolean isFull) { String ret = groupId.replace(".", " / "); if (!isFull) { if (ret.startsWith(" / spaces")) { return ret.substring(ret.lastIndexOf("/") + 1).trim(); } int count = 0; int slashPosition = -1; for (int i = 0; i < ret.length(); i++) { if ('/' == ret.charAt(i)) { if (++count == 4) { slashPosition = i; break; } } } if (slashPosition > 0) { ret = ret.substring(0, slashPosition) + "..."; } else if (ret.length() > 70) { ret = ret.substring(0, 70) + "..."; } } return ret; } public String getPortalName() { PortalContainerInfo containerInfo = WCMCoreUtils.getService(PortalContainerInfo.class); return containerInfo.getContainerName(); } public String getRestName() { PortalContainerConfig portalContainerConfig = this.getApplicationComponent(PortalContainerConfig.class); return portalContainerConfig.getRestContextName(this.getPortalName()); } private List<String> getUserRoles(boolean newRoleUpdated) throws Exception { ManageDriveService driveService = getApplicationComponent(ManageDriveService.class); if (userRoles_ == null || (userRoles_ != null && newRoleUpdated)) { userRoles_ = Utils.getMemberships(); if(newRoleUpdated) driveService.setNewRoleUpdated(false); } return userRoles_; } public List<DriveData> mainDrives() throws Exception { ManageDriveService driveService = getApplicationComponent(ManageDriveService.class); List<String> userRoles = getUserRoles(false); String userId = Util.getPortalRequestContext().getRemoteUser(); return driveService.getMainDrives(userId, userRoles) .stream() .peek(x -> x.setLabel(getLabel(x.getName()))) .sorted(Comparator.comparing(DriveData::getLabel)) .collect(Collectors.toList()); } public List<DriveData> groupDrives() throws Exception { ManageDriveService driveService = getApplicationComponent(ManageDriveService.class); List<String> userRoles = getUserRoles(driveService.newRoleUpdated()); String userId = Util.getPortalRequestContext().getRemoteUser(); return driveService.getGroupDrives(userId, userRoles) .stream() .peek(x -> x.setLabel(getGroupLabel(x))) .sorted(Comparator.comparing(DriveData::getLabel)) .collect(Collectors.toList()); } public List<DriveData> personalDrives() throws Exception { ManageDriveService driveService = getApplicationComponent(ManageDriveService.class); String userId = Util.getPortalRequestContext().getRemoteUser(); return driveService.getPersonalDrives(userId) .stream() .peek(x -> x.setLabel(getLabel(x.getName()))) .sorted(Comparator.comparing(DriveData::getLabel)) .collect(Collectors.toList()); } static public class SelectDriveActionListener extends EventListener<UIDrivesArea> { public void execute(Event<UIDrivesArea> event) throws Exception { UIDrivesArea uiDrivesArea = event.getSource(); String driveName = event.getRequestContext().getRequestParameter(OBJECTID); RepositoryService rservice = uiDrivesArea.getApplicationComponent(RepositoryService.class); ManageDriveService dservice = uiDrivesArea.getApplicationComponent(ManageDriveService.class); DriveData drive = dservice.getDriveByName(driveName); String userId = Util.getPortalRequestContext().getRemoteUser(); UIApplication uiApp = uiDrivesArea.getAncestorOfType(UIApplication.class); List<String> viewList = new ArrayList<String>(); for(String role : Utils.getMemberships()){ for(String viewName : drive.getViews().split(",")) { if (!viewList.contains(viewName.trim())) { Node viewNode = uiDrivesArea.getApplicationComponent(ManageViewService.class) .getViewByName(viewName.trim(), WCMCoreUtils.getSystemSessionProvider()); String permiss = viewNode.getProperty("exo:accessPermissions").getString(); if(permiss.contains("${userId}")) permiss = permiss.replace("${userId}", userId); String[] viewPermissions = permiss.split(","); if(permiss.equals("*")) viewList.add(viewName.trim()); if(drive.hasPermission(viewPermissions, role)) viewList.add(viewName.trim()); } } } if(viewList.isEmpty()) { Object[] args = { driveName }; uiApp.addMessage(new ApplicationMessage("UIDrivesArea.msg.no-view-found", args)); return; } StringBuffer viewListStr = new StringBuffer(); for (String viewName : viewList) { if (viewListStr.length() > 0) viewListStr.append(",").append(viewName); else viewListStr.append(viewName); } drive.setViews(viewListStr.toString()); String homePath = drive.getHomePath(); if(homePath.contains("${userId}")) { homePath = org.exoplatform.services.cms.impl.Utils.getPersonalDrivePath(homePath, userId); if (drive.getParameters().get(ManageDriveServiceImpl.DRIVE_PARAMATER_USER_ID) == null) { drive.getParameters().put(ManageDriveServiceImpl.DRIVE_PARAMATER_USER_ID, homePath); } } UIJCRExplorerPortlet uiParent = uiDrivesArea.getAncestorOfType(UIJCRExplorerPortlet.class); uiParent.setFlagSelect(true); UIJcrExplorerContainer explorerContainer = uiParent.getChild(UIJcrExplorerContainer.class); UIJCRExplorer uiJCRExplorer = explorerContainer.getChild(UIJCRExplorer.class); UITreeExplorer uiTreeExplorer = uiJCRExplorer.findFirstComponentOfType(UITreeExplorer.class); Preference pref = uiJCRExplorer.getPreference(); // check if Preferences has View-Side-Bar property to be true or not. if true, set TRUE for setViewSideBar() if (!pref.isShowSideBar()) pref.setShowSideBar(drive.getViewSideBar()); pref.setShowPreferenceDocuments(drive.getViewPreferences()); pref.setAllowCreateFoder(drive.getAllowCreateFolders()); HttpServletRequest request = Util.getPortalRequestContext().getRequest(); Cookie[] cookies = request.getCookies(); Cookie getCookieForUser = UIJCRExplorer.getCookieByCookieName(Preference.PREFERENCE_SHOW_HIDDEN_NODE, cookies); if (uiJCRExplorer.findFirstComponentOfType(UIAllItems.class) == null || getCookieForUser == null) { pref.setShowHiddenNode(drive.getShowHiddenNode()); } if (getCookieForUser == null) { pref.setShowNonDocumentType(drive.getViewNonDocument()); } uiJCRExplorer.setDriveData(drive); uiJCRExplorer.setIsReferenceNode(false); uiJCRExplorer.setPreferencesSaved(true); uiJCRExplorer.clearTagSelection(); ManageableRepository repository = rservice.getCurrentRepository(); try { Session session = WCMCoreUtils.getUserSessionProvider().getSession(drive.getWorkspace(), repository); /** * check if it exists. we assume that the path is a real path */ session.getItem(homePath); } catch(AccessDeniedException ace) { Object[] args = { driveName }; uiApp.addMessage(new ApplicationMessage("UIDrivesArea.msg.access-denied", args, ApplicationMessage.WARNING)); return; } catch(NoSuchWorkspaceException nosuchWS) { Object[] args = { driveName }; uiApp.addMessage(new ApplicationMessage("UIDrivesArea.msg.workspace-not-exist", args, ApplicationMessage.WARNING)); return; } catch(Exception e) { JCRExceptionManager.process(uiApp, e); return; } uiJCRExplorer.clearNodeHistory(homePath); uiJCRExplorer.setRepositoryName(repository.getConfiguration().getName()); uiJCRExplorer.setWorkspaceName(drive.getWorkspace()); uiJCRExplorer.setRootPath(homePath); uiJCRExplorer.setSelectNode(drive.getWorkspace(), homePath); String selectedView = viewList.get(0); UIControl uiControl = uiJCRExplorer.getChild(UIControl.class).setRendered(true); UIWorkingArea uiWorkingArea = uiJCRExplorer.getChild(UIWorkingArea.class); UIActionBar uiActionbar = uiWorkingArea.getChild(UIActionBar.class); uiActionbar.setTabOptions(selectedView); UIAddressBar uiAddressBar = uiControl.getChild(UIAddressBar.class); uiAddressBar.setViewList(viewList); uiAddressBar.setSelectedViewName(selectedView); uiWorkingArea.getChild(UISideBar.class).initialize(); for(UIComponent uiComp : uiWorkingArea.getChildren()) { if(uiComp instanceof UIDrivesArea) uiComp.setRendered(false); else uiComp.setRendered(true); } UIDocumentWorkspace uiDocumentWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class); UIDocumentFormController controller = uiDocumentWorkspace.removeChild(UIDocumentFormController.class); AutoVersionService autoVersionService = WCMCoreUtils.getService(AutoVersionService.class); if (controller != null) { controller.getChild(UIDocumentForm.class).releaseLock(); } uiParent.setRenderedChild(UIJcrExplorerContainer.class); event.getRequestContext().getJavascriptManager(). require("SHARED/multiUpload", "multiUpload"). addScripts("multiUpload.setLocation('" + uiJCRExplorer.getWorkspaceName() + "','" + uiJCRExplorer.getDriveData().getName() + "','" + uiTreeExplorer.getLabel() + "','" + uiJCRExplorer.getCurrentPath() + "','" + org.exoplatform.services.cms.impl.Utils.getPersonalDrivePath(uiJCRExplorer.getDriveData().getHomePath(), ConversationState.getCurrent().getIdentity().getUserId())+ "', '"+ autoVersionService.isVersionSupport(uiJCRExplorer.getCurrentPath(), uiJCRExplorer.getCurrentWorkspace())+"');"); uiJCRExplorer.findFirstComponentOfType(UIDocumentInfo.class).getExpandedFolders().clear(); uiJCRExplorer.updateAjax(event); } } }
16,620
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDocumentWorkspaceLifeCycle.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/lifecycle/UIDocumentWorkspaceLifeCycle.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.component.explorer.lifecycle; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.webui.component.explorer.UIWorkingArea; import org.exoplatform.ecm.webui.component.explorer.control.UIActionBar; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.lifecycle.Lifecycle; /** * Created by The eXo Platform SAS * Author : eXoPlatform exo@exoplatform.com Apr * 4, 2013 */ public class UIDocumentWorkspaceLifeCycle extends Lifecycle<UIContainer> { public void processRender(UIContainer uicomponent, WebuiRequestContext context) throws Exception { UIWorkingArea uiWorkingArea = uicomponent.getAncestorOfType(UIWorkingArea.class); UIActionBar uiActionBar = uiWorkingArea.getChild(UIActionBar.class); boolean isUISelectDocumentTemplateTitleRendered = uiWorkingArea.isUISelectDocumentTemplateTitleRendered(); context.getWriter() .append("<div class=\"") .append(uicomponent.getId()) .append(isUISelectDocumentTemplateTitleRendered || uiActionBar.isRendered() ? StringUtils.EMPTY : " uiDocumentWorkspaceBox") .append("\" id=\"") .append(uicomponent.getId()) .append("\">"); uicomponent.renderChildren(context); context.getWriter().append("</div>"); } }
2,136
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIOptionBlockPanel.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/optionblocks/UIOptionBlockPanel.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.ecm.webui.component.explorer.optionblocks; import java.util.ArrayList; import java.util.List; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.ext.UIExtension; import org.exoplatform.webui.ext.UIExtensionManager; /** * Created by The eXo Platform SAS * Author : Khuong.Van.Dung * dung.khuong@exoplatform.com * Jul 22, 2010 */ @ComponentConfig( template = "app:/groovy/webui/component/explorer/optionblocks/UIOptionBlockPanel.gtmpl" ) public class UIOptionBlockPanel extends UIContainer { private String OPTION_BLOCK_EXTENSION_TYPE = "org.exoplatform.ecm.dms.UIOptionBlocks"; private List<UIComponent> listExtenstions = new ArrayList<UIComponent>(); public UIOptionBlockPanel() throws Exception { } /* * This method checks and returns true if there is at least one extension, otherwise it returns false * */ public boolean isHasOptionBlockExtension() { UIExtensionManager manager = getApplicationComponent(UIExtensionManager.class); List<UIExtension> extensions = manager.getUIExtensions(OPTION_BLOCK_EXTENSION_TYPE); if(extensions != null) { return true; } return false; } public void addOptionBlockExtension() throws Exception { UIExtensionManager manager = getApplicationComponent(UIExtensionManager.class); List<UIExtension> extensions = manager.getUIExtensions(OPTION_BLOCK_EXTENSION_TYPE); if(extensions != null ) { for (UIExtension extension : extensions) { UIComponent uicomp = manager.addUIExtension(extension, null, this); //uicomp.setRendered(false); listExtenstions.add(uicomp); } } } public void setDisplayOptionExtensions(boolean display) { for(UIComponent uicomp : listExtenstions) { uicomp.setRendered(display); } } }
2,727
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIThumbnailForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/thumbnail/UIThumbnailForm.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.explorer.thumbnail; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.jcr.AccessDeniedException; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.lock.LockException; import javax.jcr.version.VersionException; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.utils.JCRExceptionManager; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.mimetype.DMSMimeTypeResolver; import org.exoplatform.services.cms.thumbnail.ThumbnailService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.upload.UploadResource; 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.UIApplication; import org.exoplatform.webui.core.UIPopupComponent; 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.UIUploadInput; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Oct 24, 2008 10:52:13 AM */ @ComponentConfigs({ @ComponentConfig(lifecycle = UIFormLifecycle.class, template = "app:/groovy/webui/component/explorer/thumbnail/UIThumbnailForm.gtmpl", events = { @EventConfig(listeners = UIThumbnailForm.SaveActionListener.class), @EventConfig(listeners = UIThumbnailForm.CancelActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIThumbnailForm.RemoveThumbnailActionListener.class, confirm = "UIThumbnailForm.msg.confirm-delete", phase = Phase.DECODE), @EventConfig(listeners = UIThumbnailForm.PreviewActionListener.class) }), @ComponentConfig(id="mediumSize", type = UIUploadInput.class, template = "app:/groovy/webui/component/explorer/thumbnail/UIFormUploadInput.gtmpl") }) public class UIThumbnailForm extends UIForm implements UIPopupComponent { /** * Logger. */ private static final Log LOG = ExoLogger.getLogger(UIThumbnailForm.class.getName()); private static final String THUMBNAIL_FIELD = "mediumSize"; private UploadResource currentUploadResource; private BufferedImage currentUploadImage; private String currentPreviewLink; public UIThumbnailForm() throws Exception { initForm(); } private void initForm() throws Exception { currentUploadResource = null; currentUploadImage = null; currentPreviewLink = null; setMultiPart(true); UIUploadInput uiInput = new UIUploadInput(THUMBNAIL_FIELD, THUMBNAIL_FIELD); removeChild(UIUploadInput.class); addUIFormInput(uiInput); } public String getThumbnailImage(Node node) throws Exception { return Utils.getThumbnailImage(node, ThumbnailService.MEDIUM_SIZE); } public String getPreviewImage() throws Exception { UIUploadInput input = this.getUIInput(THUMBNAIL_FIELD); String uploadId = input.getUploadIds()[0]; if(input.getUploadResource(uploadId) == null) return null; return Utils.getThumbnailImage(input.getUploadDataAsStream(uploadId), input.getUploadResource(uploadId).getFileName()); } public Node getSelectedNode() throws Exception { return getAncestorOfType(UIJCRExplorer.class).getRealCurrentNode(); } /* (non-Javadoc) * @see org.exoplatform.webui.form.UIForm#processRender(org.exoplatform.webui.application.WebuiRequestContext) */ @Override public void processRender(WebuiRequestContext context) throws Exception { Node currentRealNode = getSelectedNode(); if (getThumbnailImage(currentRealNode) == null) { setActions(new String[] {"Save", "Cancel"}); } else { setActions(new String[] {"RemoveThumbnail", "Cancel"}); } super.processRender(context); } public Node getThumbnailNode(Node node) throws Exception { ThumbnailService thumbnailService = getApplicationComponent(ThumbnailService.class); return thumbnailService.getThumbnailNode(node); } /** * @return the currentUploadImage */ public BufferedImage getCurrentUploadImage() { return currentUploadImage; } /** * @param currentUploadImage the currentUploadImage to set */ public void setCurrentUploadImage(BufferedImage currentUploadImage) { this.currentUploadImage = currentUploadImage; } /** * @return the currentUploadResource */ public UploadResource getCurrentUploadResource() { return currentUploadResource; } /** * @param currentUploadResource the currentUploadResource to set */ public void setCurrentUploadResource(UploadResource currentUploadResource) { this.currentUploadResource = currentUploadResource; } /** * @param currentPreviewLink the currentPreviewLink to set */ public void setCurrentPreviewLink(String currentPreviewLink) { this.currentPreviewLink = currentPreviewLink; } /** * @return the currentPreviewLink */ public String getCurrentPreviewLink() { return currentPreviewLink; } /** * return the Modified date property of the selected node * * @param node the thumbnail node of the selected node * @return the Modified date property * @throws Exception */ public String getThumbnailModifiedTime(Node node) throws Exception { boolean hasLastModifiedProperty = node.hasProperty(ThumbnailService.THUMBNAIL_LAST_MODIFIED); if (hasLastModifiedProperty) { return node.getProperty(ThumbnailService.THUMBNAIL_LAST_MODIFIED).getDate().getTime().toString(); } else { LOG.warn("Thumbnail last modified property of the node " + node.getPath() + " doesn't exist."); return null; } } static public class SaveActionListener extends EventListener<UIThumbnailForm> { public void execute(Event<UIThumbnailForm> event) throws Exception { UIThumbnailForm uiForm = event.getSource(); UIApplication uiApp = uiForm.getAncestorOfType(UIApplication.class) ; UIJCRExplorer uiExplorer = uiForm.getAncestorOfType(UIJCRExplorer.class); // Check resource available if(uiForm.getCurrentUploadResource() == null) { uiApp.addMessage(new ApplicationMessage("UIThumbnailForm.msg.fileName-error", null, ApplicationMessage.WARNING)); event.getRequestContext().addUIComponentToUpdateByAjax(uiForm); return; } // Check if file is image String fileName = uiForm.getCurrentUploadResource().getFileName(); DMSMimeTypeResolver mimeTypeSolver = DMSMimeTypeResolver.getInstance(); String mimeType = mimeTypeSolver.getMimeType(fileName) ; if(!mimeType.startsWith("image")) { uiApp.addMessage(new ApplicationMessage("UIThumbnailForm.msg.mimetype-incorrect", null, ApplicationMessage.WARNING)); return; } // Add lock token Node selectedNode = uiExplorer.getRealCurrentNode(); uiExplorer.addLockToken(selectedNode); // Create thumbnail ThumbnailService thumbnailService = WCMCoreUtils.getService(ThumbnailService.class); try { thumbnailService.createThumbnailImage(selectedNode, uiForm.getCurrentUploadImage(), mimeType); selectedNode.getSession().save(); uiExplorer.updateAjax(event); } catch(AccessDeniedException ace) { uiApp.addMessage(new ApplicationMessage("UIThumbnailForm.msg.access-denied", null, ApplicationMessage.WARNING)); } catch(VersionException ver) { uiApp.addMessage(new ApplicationMessage("UIThumbnailForm.msg.is-checked-in", null, ApplicationMessage.WARNING)); } catch(LockException lock) { Object[] arg = { selectedNode.getPath() }; uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.node-locked", arg, ApplicationMessage.WARNING)); } catch(PathNotFoundException path) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.path-not-found-exception", null,ApplicationMessage.WARNING)); } catch(Exception e) { if (LOG.isErrorEnabled()) { LOG.error("An unexpected error occurs", e); } JCRExceptionManager.process(uiApp, e); } } } static public class PreviewActionListener extends EventListener<UIThumbnailForm> { public void execute(Event<UIThumbnailForm> event) throws Exception { UIThumbnailForm uiForm = event.getSource(); // Current review link UIUploadInput input = (UIUploadInput)uiForm.getUIInput(THUMBNAIL_FIELD); String uploadId = input.getUploadIds()[0]; if (input.getUploadDataAsStream(uploadId) != null) { uiForm.setCurrentPreviewLink(uiForm.getPreviewImage()); uiForm.setCurrentUploadImage(ImageIO.read(input.getUploadDataAsStream(uploadId))); uiForm.setCurrentUploadResource(input.getUploadResource(uploadId)); } else { uiForm.setCurrentPreviewLink(null); uiForm.setCurrentUploadImage(null); uiForm.setCurrentUploadResource(null); } } } static public class RemoveThumbnailActionListener extends EventListener<UIThumbnailForm> { public void execute(Event<UIThumbnailForm> event) throws Exception { UIThumbnailForm uiForm = event.getSource(); UIJCRExplorer uiExplorer = uiForm.getAncestorOfType(UIJCRExplorer.class); Node selectedNode = uiExplorer.getRealCurrentNode(); UIApplication uiApp = uiForm.getAncestorOfType(UIApplication.class); uiExplorer.addLockToken(selectedNode); ThumbnailService thumbnailService = uiForm.getApplicationComponent(ThumbnailService.class); Node thumbnailNode = thumbnailService.getThumbnailNode(selectedNode); if(thumbnailNode != null) { try { // Remove thumbmail thumbnailNode.remove(); selectedNode.getSession().save(); // Reset form uiForm.initForm(); event.getRequestContext().addUIComponentToUpdateByAjax(uiForm); } catch(LockException lock) { Object[] arg = { selectedNode.getPath() }; uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.node-locked", arg, ApplicationMessage.WARNING)); } catch(AccessDeniedException ace) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.access-denied", null, ApplicationMessage.WARNING)); uiExplorer.updateAjax(event); } catch(PathNotFoundException path) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.path-not-found-exception", null,ApplicationMessage.WARNING)); } catch(Exception e) { if (LOG.isErrorEnabled()) { LOG.error("An unexpected error occurs", e); } JCRExceptionManager.process(uiApp, e); } } } } static public class CancelActionListener extends EventListener<UIThumbnailForm> { public void execute(Event<UIThumbnailForm> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); uiExplorer.cancelAction(); } } public void activate() {} public void deActivate() {} }
12,582
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISymLinkContainer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/symlink/UISymLinkContainer.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.explorer.symlink; import javax.jcr.Item; import javax.jcr.Node; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; 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.UIContainer; 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 * May 25, 2007 8:59:34 AM */ @ComponentConfig( template = "app:/groovy/webui/component/explorer/UITabPaneWithAction.gtmpl", events = { @EventConfig(listeners = UISymLinkContainer.CloseActionListener.class) } ) public class UISymLinkContainer extends UIContainer { private static final Log LOG = ExoLogger.getLogger(UISymLinkContainer.class.getName()); private NodeLocation uploadedNode_ ; public UISymLinkContainer() throws Exception { } public String[] getActions() {return new String[] {"AddMetadata","Close"} ;} public Node getEditNode(String nodeType) throws Exception { Node uploadedNode = getUploadedNode(); try { Item primaryItem = uploadedNode.getPrimaryItem() ; if(primaryItem == null || !primaryItem.isNode()) return uploadedNode; if(primaryItem != null && primaryItem.isNode()) { Node primaryNode = (Node) primaryItem ; if(primaryNode.isNodeType(nodeType)) return primaryNode ; } } catch(Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } return uploadedNode; } public void setUploadedNode(Node node) throws Exception { uploadedNode_ = NodeLocation.getNodeLocationByNode(node); } public Node getUploadedNode() { return NodeLocation.getNodeByLocation(uploadedNode_); } static public class CloseActionListener extends EventListener<UISymLinkContainer> { public void execute(Event<UISymLinkContainer> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); uiExplorer.cancelAction() ; } } }
3,123
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIAddTranslationForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/symlink/UIAddTranslationForm.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.explorer.symlink; import java.security.AccessControlException; import java.util.ArrayList; import java.util.List; import javax.jcr.AccessDeniedException; import javax.jcr.ItemExistsException; import javax.jcr.ItemNotFoundException; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.UnsupportedRepositoryOperationException; import javax.jcr.nodetype.ConstraintViolationException; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.ecm.webui.tree.selectone.UIOneNodePathSelector; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.i18n.MultiLanguageService; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.exceptions.SameAsDefaultLangException; import org.exoplatform.services.jcr.util.Text; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.selector.content.one.UIContentBrowsePanelOne; import org.exoplatform.wcm.webui.selector.content.one.UIContentSelectorOne; import org.exoplatform.web.application.ApplicationMessage; 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.UIApplication; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIPopupComponent; 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.UIFormStringInput; /** * Created by The eXo Platform SARL * Author : Chien Nguyen Van * */ @ComponentConfigs( { @ComponentConfig(lifecycle = UIFormLifecycle.class, template = "app:/groovy/webui/component/explorer/thumbnail/UIAddTranslationForm.gtmpl", events = { @EventConfig(listeners = UIAddTranslationForm.SaveActionListener.class), @EventConfig(listeners = UIAddTranslationForm.CancelActionListener.class, phase = Phase.DECODE) }), @ComponentConfig(type = UITranslationFormMultiValueInputSet.class, id = "SymLinkMultipleInputset", events = { @EventConfig(listeners = UIAddTranslationForm.RemoveActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIAddTranslationForm.SelectDocumentActionListener.class, phase = Phase.DECODE) }) }) public class UIAddTranslationForm extends UIForm implements UIPopupComponent, UISelectable { public static final String FIELD_PATH = "pathNode"; public static final String FIELD_SYMLINK = "fieldPathNode"; public static final String POPUP_SYMLINK = "UIPopupSymLink"; /** * Logger. */ private static final Log LOG = ExoLogger.getLogger(UIAddTranslationForm.class.getName()); final static public byte DRIVE_SELECTOR_MODE = 0; final static public byte WORSPACE_SELECTOR_MODE = 1; private byte selectorMode=DRIVE_SELECTOR_MODE; public UIAddTranslationForm() throws Exception { } public void activate() {} public void deActivate() {} public void initFieldInput() throws Exception { UITranslationFormMultiValueInputSet uiTranslationFormMultiValue = createUIComponent(UITranslationFormMultiValueInputSet.class, "SymLinkMultipleInputset", null); uiTranslationFormMultiValue.setId(FIELD_PATH); uiTranslationFormMultiValue.setName(FIELD_PATH); uiTranslationFormMultiValue.setEditable(false); uiTranslationFormMultiValue.setType(UIFormStringInput.class); addUIFormInput(uiTranslationFormMultiValue); } public void doSelect(String selectField, Object value) throws Exception { String valueNodeName = String.valueOf(value).trim(); String workspaceName = valueNodeName.substring(0, valueNodeName.lastIndexOf(":/")); valueNodeName = valueNodeName.substring(workspaceName.lastIndexOf(":")+1); List<String> listNodeName = new ArrayList<String>(); listNodeName.add(valueNodeName); UITranslationFormMultiValueInputSet uiTranslationFormMultiValueInputSet = getChild(UITranslationFormMultiValueInputSet.class); uiTranslationFormMultiValueInputSet.setValue(listNodeName); String symLinkName = valueNodeName.substring(valueNodeName.lastIndexOf("/") + 1); int squareBracketIndex = symLinkName.indexOf('['); if (squareBracketIndex > -1) symLinkName = symLinkName.substring(0, squareBracketIndex); if (symLinkName.indexOf(".lnk") < 0) { StringBuffer sb = new StringBuffer(); sb.append(symLinkName).append(".lnk"); symLinkName = sb.toString(); } symLinkName = Text.unescapeIllegalJcrChars(symLinkName); UIAddTranslationManager uiAddTranslationManager = getParent(); uiAddTranslationManager.removeChildById(POPUP_SYMLINK); } static public class SaveActionListener extends EventListener<UIAddTranslationForm> { public void execute(Event<UIAddTranslationForm> event) throws Exception { UIAddTranslationForm uiTranslationForm = event.getSource(); UIJCRExplorer uiExplorer = uiTranslationForm.getAncestorOfType(UIJCRExplorer.class); UIApplication uiApp = uiTranslationForm.getAncestorOfType(UIApplication.class); String pathNode = ""; UITranslationFormMultiValueInputSet uiSet = uiTranslationForm.getChild(UITranslationFormMultiValueInputSet.class); List<UIComponent> listChildren = uiSet.getChildren(); for (UIComponent component : listChildren) { UIFormStringInput uiStringInput = (UIFormStringInput)component; if(uiStringInput.getValue() != null) { pathNode = uiStringInput.getValue().trim(); } } Node node = uiExplorer.getCurrentNode() ; if(uiExplorer.nodeIsLocked(node)) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.node-locked", null)) ; return ; } if(pathNode == null || pathNode.length() ==0) { uiApp.addMessage(new ApplicationMessage("UIAddTranslationForm.msg.path-node-invalid", null)); return ; } String workspaceName = pathNode.substring(0, pathNode.lastIndexOf(":/")); pathNode = pathNode.substring(pathNode.lastIndexOf(":/") + 1); NodeFinder nodeFinder = uiTranslationForm.getApplicationComponent(NodeFinder.class); try { nodeFinder.getItem(workspaceName, pathNode); } catch (ItemNotFoundException e) { uiApp.addMessage(new ApplicationMessage("UIAddTranslationForm.msg.non-node", null, ApplicationMessage.WARNING)); return; } catch (RepositoryException re) { uiApp.addMessage(new ApplicationMessage("UIAddTranslationForm.msg.non-node", null, ApplicationMessage.WARNING)); return; } catch(Exception e) { if (LOG.isErrorEnabled()) { LOG.error("An unexpected error occurs", e); } uiApp.addMessage(new ApplicationMessage("UIAddTranslationForm.msg.non-node", null, ApplicationMessage.WARNING)); return; } try { Node targetNode = (Node) nodeFinder.getItem(workspaceName, pathNode); MultiLanguageService langService = uiTranslationForm.getApplicationComponent(MultiLanguageService.class); langService.addSynchronizedLinkedLanguage(node, targetNode); uiExplorer.updateAjax(event); } catch (AccessControlException ace) { uiApp.addMessage(new ApplicationMessage("UIAddTranslationForm.msg.repository-exception", null, ApplicationMessage.WARNING)); return; } catch (AccessDeniedException ade) { uiApp.addMessage(new ApplicationMessage("UIAddTranslationForm.msg.repository-exception", null, ApplicationMessage.WARNING)); return; } catch(NumberFormatException nume) { uiApp.addMessage(new ApplicationMessage("UIAddTranslationForm.msg.numberformat-exception", null, ApplicationMessage.WARNING)); return; } catch(ConstraintViolationException cve) { uiApp.addMessage(new ApplicationMessage("UIAddTranslationForm.msg.cannot-save", null, ApplicationMessage.WARNING)); return; } catch(ItemExistsException iee) { uiApp.addMessage(new ApplicationMessage("UIAddTranslationForm.msg.item-exists-exception", null, ApplicationMessage.WARNING)); return; } catch(UnsupportedRepositoryOperationException unOperationException) { uiApp.addMessage(new ApplicationMessage("UIAddTranslationForm.msg.UnsupportedRepositoryOperationException", null, ApplicationMessage.WARNING)); return; } catch (SameAsDefaultLangException unOperationException) { uiApp.addMessage(new ApplicationMessage("UIAddTranslationForm.msg.translation-node-same-language-default", null, ApplicationMessage.WARNING)); return; } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } uiApp.addMessage(new ApplicationMessage("UIAddTranslationForm.msg.cannot-save", null, ApplicationMessage.WARNING)); return; } } } static public class CancelActionListener extends EventListener<UIAddTranslationForm> { public void execute(Event<UIAddTranslationForm> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); uiExplorer.cancelAction(); } } static public class RemoveActionListener extends EventListener<UITranslationFormMultiValueInputSet> { public void execute(Event<UITranslationFormMultiValueInputSet> event) throws Exception { UITranslationFormMultiValueInputSet uiSet = event.getSource(); UIComponent uiComponent = uiSet.getParent(); if (uiComponent instanceof UIAddTranslationForm) { UIAddTranslationForm uiTranslationForm = (UIAddTranslationForm)uiComponent; String id = event.getRequestContext().getRequestParameter(OBJECTID); uiSet.removeChildById(id); event.getRequestContext().addUIComponentToUpdateByAjax(uiTranslationForm); } } } static public class SelectDocumentActionListener extends EventListener<UITranslationFormMultiValueInputSet> { private String fixPath(String path, String driveName, String repo, UIAddTranslationForm uiAddTranslationForm) throws Exception { if (path == null || path.length() == 0 || driveName == null || driveName.length() == 0 || repo == null || repo.length() == 0) return ""; ManageDriveService managerDriveService = uiAddTranslationForm.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 void execute(Event<UITranslationFormMultiValueInputSet> event) throws Exception { UITranslationFormMultiValueInputSet uiSet = event.getSource(); UIAddTranslationForm uiTranslationForm = (UIAddTranslationForm) uiSet.getParent(); UIAddTranslationManager uiAddTranslationManager = uiTranslationForm.getParent(); UIJCRExplorer uiExplorer = uiTranslationForm.getAncestorOfType(UIJCRExplorer.class); String workspaceName = uiExplorer.getCurrentWorkspace(); String param = "returnField=" + FIELD_SYMLINK; UIPopupWindow uiPopupWindow = uiAddTranslationManager.initPopupTaxonomy(POPUP_SYMLINK); if (uiTranslationForm.isUseWorkspaceSelector()) { UIOneNodePathSelector uiNodePathSelector = uiAddTranslationManager.createUIComponent(UIOneNodePathSelector.class, null, null); uiPopupWindow.setUIComponent(uiNodePathSelector); uiNodePathSelector.setIsDisable(workspaceName, false); uiNodePathSelector.setExceptedNodeTypesInPathPanel(new String[] {Utils.EXO_SYMLINK}); uiNodePathSelector.setRootNodeLocation(uiExplorer.getRepositoryName(), workspaceName, "/"); uiNodePathSelector.setIsShowSystem(false); uiNodePathSelector.init(WCMCoreUtils.getUserSessionProvider()); uiNodePathSelector.setSourceComponent(uiTranslationForm, new String[]{param}); }else { Node node =uiExplorer.getCurrentNode(); UIContentSelectorOne uiNodePathSelector = uiTranslationForm.createUIComponent(UIContentSelectorOne.class, null, null); uiPopupWindow.setUIComponent(uiNodePathSelector); uiNodePathSelector.init(uiExplorer.getDriveData().getName(), fixPath(node == null ? "" : node.getPath(), uiExplorer.getDriveData().getName(), uiExplorer.getRepositoryName(), uiTranslationForm)); uiNodePathSelector.getChild(UIContentBrowsePanelOne.class).setSourceComponent(uiTranslationForm, new String[] { param }); } uiPopupWindow.setRendered(true); uiPopupWindow.setShow(true); event.getRequestContext().addUIComponentToUpdateByAjax(uiAddTranslationManager); } } public void useWorkspaceSelector() { this.selectorMode = WORSPACE_SELECTOR_MODE; } public void useDriveSelector() { this.selectorMode = DRIVE_SELECTOR_MODE; } public boolean isUseWorkspaceSelector() { return this.selectorMode==WORSPACE_SELECTOR_MODE; } }
16,018
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISymLinkForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/symlink/UISymLinkForm.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.explorer.symlink; import java.security.AccessControlException; import java.util.ArrayList; import java.util.List; import javax.jcr.AccessDeniedException; import javax.jcr.ItemExistsException; import javax.jcr.ItemNotFoundException; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.UnsupportedRepositoryOperationException; import javax.jcr.nodetype.ConstraintViolationException; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.ecm.webui.tree.selectone.UIOneNodePathSelector; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.i18n.MultiLanguageService; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.exceptions.SameAsDefaultLangException; import org.exoplatform.services.jcr.util.Text; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.selector.content.one.UIContentBrowsePanelOne; import org.exoplatform.wcm.webui.selector.content.one.UIContentSelectorOne; import org.exoplatform.web.application.ApplicationMessage; 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.UIApplication; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIPopupComponent; import org.exoplatform.webui.core.UIPopupWindow; 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; import org.exoplatform.webui.form.UIFormMultiValueInputSet; import org.exoplatform.webui.form.UIFormStringInput; import org.exoplatform.webui.form.validator.MandatoryValidator; /** * Created by The eXo Platform SARL * Author : Chien Nguyen Van * */ @ComponentConfigs( { @ComponentConfig(lifecycle = UIFormLifecycle.class, template = "system:/groovy/webui/form/UIForm.gtmpl", events = { @EventConfig(listeners = UISymLinkForm.SaveActionListener.class), @EventConfig(listeners = UISymLinkForm.CancelActionListener.class, phase = Phase.DECODE) }), @ComponentConfig(type = UIFormMultiValueInputSet.class, id = "SymLinkMultipleInputset", events = { @EventConfig(listeners = UISymLinkForm.RemoveActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UISymLinkForm.AddActionListener.class, phase = Phase.DECODE) }) }) public class UISymLinkForm extends UIForm implements UIPopupComponent, UISelectable { /** * Logger. */ private static final Log LOG = ExoLogger.getLogger(UISymLinkForm.class.getName()); final static public String FIELD_NAME = "symLinkName"; final static public String FIELD_PATH = "pathNode"; final static public String FIELD_SYMLINK = "fieldPathNode"; final static public String POPUP_SYMLINK = "UIPopupSymLink"; final static public String DEFAULT_NAME = "untitled"; final static public byte DRIVE_SELECTOR_MODE = 0; final static public byte WORSPACE_SELECTOR_MODE = 1; private byte selectorMode=DRIVE_SELECTOR_MODE; private boolean localizationMode = false; public UISymLinkForm() throws Exception { } public void activate() {} public void deActivate() {} public void initFieldInput() throws Exception { UIFormMultiValueInputSet uiFormMultiValue = createUIComponent(UIFormMultiValueInputSet.class, "SymLinkMultipleInputset", null); uiFormMultiValue.setId(FIELD_PATH); uiFormMultiValue.setName(FIELD_PATH); uiFormMultiValue.setEditable(false); uiFormMultiValue.setType(UIFormStringInput.class); addUIFormInput(uiFormMultiValue); if (!localizationMode) addUIFormInput(new UIFormStringInput(FIELD_NAME, FIELD_NAME, null).addValidator(MandatoryValidator.class)); } public void enableLocalizationMode() { this.localizationMode = true; } public void doSelect(String selectField, Object value) throws Exception { String valueNodeName = String.valueOf(value).trim(); String workspaceName = valueNodeName.substring(0, valueNodeName.lastIndexOf(":/")); valueNodeName = valueNodeName.substring(workspaceName.lastIndexOf(":")+1); List<String> listNodeName = new ArrayList<String>(); listNodeName.add(valueNodeName); UIFormMultiValueInputSet uiFormMultiValueInputSet = getChild(UIFormMultiValueInputSet.class); uiFormMultiValueInputSet.setValue(listNodeName); String symLinkName = valueNodeName.substring(valueNodeName.lastIndexOf("/") + 1); int squareBracketIndex = symLinkName.indexOf('['); if (squareBracketIndex > -1) symLinkName = symLinkName.substring(0, squareBracketIndex); if (symLinkName.indexOf(".lnk") < 0) { StringBuffer sb = new StringBuffer(); sb.append(symLinkName).append(".lnk"); symLinkName = sb.toString(); } symLinkName = Text.unescapeIllegalJcrChars(symLinkName); if (!localizationMode) getUIStringInput(FIELD_NAME).setValue(symLinkName); UISymLinkManager uiSymLinkManager = getParent(); uiSymLinkManager.removeChildById(POPUP_SYMLINK); } static public class SaveActionListener extends EventListener<UISymLinkForm> { public void execute(Event<UISymLinkForm> event) throws Exception { UISymLinkForm uiSymLinkForm = event.getSource(); UIJCRExplorer uiExplorer = uiSymLinkForm.getAncestorOfType(UIJCRExplorer.class); UIApplication uiApp = uiSymLinkForm.getAncestorOfType(UIApplication.class); String symLinkName = ""; String symLinkTitle = ""; if (!uiSymLinkForm.localizationMode) symLinkName = uiSymLinkForm.getUIStringInput(FIELD_NAME).getValue(); String pathNode = ""; UIFormMultiValueInputSet uiSet = uiSymLinkForm.getChild(UIFormMultiValueInputSet.class); List<UIComponent> listChildren = uiSet.getChildren(); for (UIComponent component : listChildren) { UIFormStringInput uiStringInput = (UIFormStringInput)component; if(uiStringInput.getValue() != null) { pathNode = uiStringInput.getValue().trim(); } } Node node = uiExplorer.getCurrentNode() ; if(uiExplorer.nodeIsLocked(node)) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.node-locked", null)) ; return ; } symLinkTitle = symLinkName; symLinkName = org.exoplatform.services.cms.impl.Utils.cleanString(symLinkName); if (StringUtils.isEmpty(symLinkName)) { symLinkName = DEFAULT_NAME; } if(!uiSymLinkForm.localizationMode && StringUtils.isEmpty(symLinkTitle)) { uiApp.addMessage(new ApplicationMessage("UISymLinkForm.msg.name-invalid", null)) ; return ; } if(pathNode == null || pathNode.length() ==0) { uiApp.addMessage(new ApplicationMessage("UISymLinkForm.msg.path-node-invalid", null)); return ; } String workspaceName = pathNode.substring(0, pathNode.lastIndexOf(":/")); pathNode = pathNode.substring(pathNode.lastIndexOf(":/") + 1); NodeFinder nodeFinder = uiSymLinkForm.getApplicationComponent(NodeFinder.class); try { nodeFinder.getItem(workspaceName, pathNode); } catch (ItemNotFoundException e) { uiApp.addMessage(new ApplicationMessage("UISymLinkForm.msg.non-node", null, ApplicationMessage.WARNING)); return; } catch (RepositoryException re) { uiApp.addMessage(new ApplicationMessage("UISymLinkForm.msg.non-node", null, ApplicationMessage.WARNING)); return; } catch(Exception e) { if (LOG.isErrorEnabled()) { LOG.error("An unexpected error occurs", e); } uiApp.addMessage(new ApplicationMessage("UISymLinkForm.msg.non-node", null,ApplicationMessage.WARNING)); return; } try { Node targetNode = (Node) nodeFinder.getItem(workspaceName, pathNode); if(targetNode.isLocked()) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.node-locked", new String[] {targetNode.getPath()})) ; return; } if (uiSymLinkForm.localizationMode) { MultiLanguageService langService = uiSymLinkForm.getApplicationComponent(MultiLanguageService.class); langService.addSynchronizedLinkedLanguage(node, targetNode); } else { LinkManager linkManager = uiSymLinkForm.getApplicationComponent(LinkManager.class); linkManager.createLink(node, Utils.EXO_SYMLINK, targetNode, symLinkName, symLinkTitle); } uiExplorer.updateAjax(event); } catch (AccessControlException ace) { uiApp.addMessage(new ApplicationMessage("UISymLinkForm.msg.repository-exception", null, ApplicationMessage.WARNING)); return; } catch (AccessDeniedException ade) { uiApp.addMessage(new ApplicationMessage("UISymLinkForm.msg.repository-exception", null, ApplicationMessage.WARNING)); return; } catch(NumberFormatException nume) { uiApp.addMessage(new ApplicationMessage("UISymLinkForm.msg.numberformat-exception", null, ApplicationMessage.WARNING)); return; } catch(ConstraintViolationException cve) { uiApp.addMessage(new ApplicationMessage("UISymLinkForm.msg.cannot-save", null, ApplicationMessage.WARNING)); return; } catch(ItemExistsException iee) { uiApp.addMessage(new ApplicationMessage("UISymLinkForm.msg.item-exists-exception", null, ApplicationMessage.WARNING)); return; } catch(UnsupportedRepositoryOperationException unOperationException) { uiApp.addMessage(new ApplicationMessage("UISymLinkForm.msg.UnsupportedRepositoryOperationException", null, ApplicationMessage.WARNING)); return; } catch (SameAsDefaultLangException unOperationException) { uiApp.addMessage(new ApplicationMessage("UISymLinkForm.msg.translation-node-same-language-default", null, ApplicationMessage.WARNING)); return; } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } uiApp.addMessage(new ApplicationMessage("UISymLinkForm.msg.cannot-save", null, ApplicationMessage.WARNING)); return; } } } static public class CancelActionListener extends EventListener<UISymLinkForm> { public void execute(Event<UISymLinkForm> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); uiExplorer.cancelAction(); } } static public class RemoveActionListener extends EventListener<UIFormMultiValueInputSet> { public void execute(Event<UIFormMultiValueInputSet> event) throws Exception { UIFormMultiValueInputSet uiSet = event.getSource(); UIComponent uiComponent = uiSet.getParent(); if (uiComponent instanceof UISymLinkForm) { UISymLinkForm uiSymLinkForm = (UISymLinkForm)uiComponent; String id = event.getRequestContext().getRequestParameter(OBJECTID); UIFormStringInput uiInput = uiSymLinkForm.getUIStringInput(FIELD_NAME); if (uiInput!=null) uiInput.setValue(""); uiSet.removeChildById(id); event.getRequestContext().addUIComponentToUpdateByAjax(uiSymLinkForm); } } } static public class AddActionListener extends EventListener<UIFormMultiValueInputSet> { private String fixPath(String path, String driveName, String repo, UISymLinkForm uiSymlinkForm) throws Exception { if (path == null || path.length() == 0 || driveName == null || driveName.length() == 0 || repo == null || repo.length() == 0) return ""; ManageDriveService managerDriveService = uiSymlinkForm.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 void execute(Event<UIFormMultiValueInputSet> event) throws Exception { UIFormMultiValueInputSet uiSet = event.getSource(); UISymLinkForm uiSymLinkForm = (UISymLinkForm) uiSet.getParent(); UISymLinkManager uiSymLinkManager = uiSymLinkForm.getParent(); UIJCRExplorer uiExplorer = uiSymLinkForm.getAncestorOfType(UIJCRExplorer.class); String workspaceName = uiExplorer.getCurrentWorkspace(); String param = "returnField=" + FIELD_SYMLINK; UIPopupWindow uiPopupWindow = uiSymLinkManager.initPopupTaxonomy(POPUP_SYMLINK); if (uiSymLinkForm.isUseWorkspaceSelector()) { UIOneNodePathSelector uiNodePathSelector = uiSymLinkManager.createUIComponent(UIOneNodePathSelector.class, null, null); uiPopupWindow.setUIComponent(uiNodePathSelector); uiNodePathSelector.setIsDisable(workspaceName, false); uiNodePathSelector.setExceptedNodeTypesInPathPanel(new String[] {Utils.EXO_SYMLINK, Utils.MIX_LOCKABLE}); uiNodePathSelector.setRootNodeLocation(uiExplorer.getRepositoryName(), workspaceName, "/"); uiNodePathSelector.setIsShowSystem(false); uiNodePathSelector.init(WCMCoreUtils.getUserSessionProvider()); uiNodePathSelector.setSourceComponent(uiSymLinkForm, new String[]{param}); }else { Node node =uiExplorer.getCurrentNode(); UIContentSelectorOne uiNodePathSelector = uiSymLinkForm.createUIComponent(UIContentSelectorOne.class, null, null); uiPopupWindow.setUIComponent(uiNodePathSelector); uiNodePathSelector.init(uiExplorer.getDriveData().getName(), fixPath(node == null ? "" : node.getPath(), uiExplorer.getDriveData().getName(), uiExplorer.getRepositoryName(), uiSymLinkForm)); uiNodePathSelector.getChild(UIContentBrowsePanelOne.class).setSourceComponent(uiSymLinkForm, new String[] { param }); } uiPopupWindow.setRendered(true); uiPopupWindow.setShow(true); event.getRequestContext().addUIComponentToUpdateByAjax(uiSymLinkManager); } } public void useWorkspaceSelector() { this.selectorMode = WORSPACE_SELECTOR_MODE; } public void useDriveSelector() { this.selectorMode = DRIVE_SELECTOR_MODE; } public boolean isUseWorkspaceSelector() { return this.selectorMode==WORSPACE_SELECTOR_MODE; } }
16,335
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISymLinkManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/symlink/UISymLinkManager.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.explorer.symlink; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPopupComponent; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * May 24, 2007 2:12:48 PM */ @ComponentConfig( lifecycle = UIContainerLifecycle.class ) public class UISymLinkManager extends UIContainer implements UIPopupComponent { private static final Log LOG = ExoLogger.getLogger(UISymLinkManager.class.getName()); final static public String EXTARNAL_METADATA_POPUP = "AddMetadataPopup" ; public UISymLinkManager() throws Exception { addChild(UISymLinkForm.class, null, null); addChild(UISymLinkContainer.class, null, null).setRendered(false); } public void enableLocalizationMode() { UISymLinkForm linkForm = this.getChild(UISymLinkForm.class); linkForm.enableLocalizationMode(); } public UIPopupWindow initPopupTaxonomy(String id) throws Exception { UIPopupWindow uiPopup = getChildById(id); if (uiPopup == null) { uiPopup = addChild(UIPopupWindow.class, null, id); } uiPopup.setWindowSize(700, 350); uiPopup.setShow(false); uiPopup.setResizable(true); return uiPopup; } public void activate() { try { UISymLinkForm uiUploadForm = getChild(UISymLinkForm.class); uiUploadForm.initFieldInput(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error!", e.getMessage()); } } } public void deActivate() {} public void initMetadataPopup() throws Exception { removeChildById(EXTARNAL_METADATA_POPUP) ; UIPopupWindow uiPopup = addChild(UIPopupWindow.class, null, EXTARNAL_METADATA_POPUP) ; uiPopup.setShowMask(true); uiPopup.setWindowSize(400, 400); uiPopup.setRendered(true); uiPopup.setShow(true) ; uiPopup.setResizable(true) ; } public void useWorkspaceSelector() { UISymLinkForm child = getChild(UISymLinkForm.class); if (child!=null) { child.useWorkspaceSelector(); } } public void useDriveSelector() { UISymLinkForm child = getChild(UISymLinkForm.class); if (child!=null) { child.useDriveSelector(); } } }
3,245
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UITranslationFormMultiValueInputSet.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/symlink/UITranslationFormMultiValueInputSet.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.component.explorer.symlink; import java.io.Writer; import java.util.ResourceBundle; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormInputBase; import org.exoplatform.webui.form.UIFormMultiValueInputSet; /** * Created by The eXo Platform SAS Author : eXoPlatform exo@exoplatform.com Mar * 7, 2013 */ public class UITranslationFormMultiValueInputSet extends UIFormMultiValueInputSet { /* * (non-Javadoc) * @see org.exoplatform.webui.form.UIFormMultiValueInputSet#processRender(org. * exoplatform.webui.application.WebuiRequestContext) */ @Override public void processRender(WebuiRequestContext context) throws Exception { if (getChildren() == null || getChildren().size() < 1) createUIFormInput(0); Writer writer = context.getWriter(); UIForm uiForm = getAncestorOfType(UIForm.class); int size = getChildren().size(); ResourceBundle res = context.getApplicationResourceBundle(); String addItem = res.getString("UIAddTranslationForm.action.SelectDocument"); writer.append("<div class=\"input-append\">"); for (int i = 0; i < size; i++) { UIFormInputBase uiInput = getChild(i); uiInput.setReadOnly(readonly_); uiInput.setDisabled(!enable_); uiInput.processRender(context); if (i == size - 1) { writer.append("<button type=\"button\" onclick=\""); writer.append(uiForm.event("SelectDocument", getId())).append("\" title=\"" + addItem + "\""); writer.append(" class=\"btn\" >" + addItem + "</button>"); } } writer.append("</div>"); } }
2,421
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIAddTranslationManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/symlink/UIAddTranslationManager.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.explorer.symlink; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPopupComponent; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * May 24, 2007 2:12:48 PM */ @ComponentConfig( lifecycle = UIContainerLifecycle.class ) public class UIAddTranslationManager extends UIContainer implements UIPopupComponent { private static final Log LOG = ExoLogger.getLogger(UIAddTranslationManager.class.getName()); final static public String EXTARNAL_METADATA_POPUP = "AddMetadataPopup" ; public UIAddTranslationManager() throws Exception { addChild(UIAddTranslationForm.class, null, null); addChild(UISymLinkContainer.class, null, null).setRendered(false); } public UIPopupWindow initPopupTaxonomy(String id) throws Exception { UIPopupWindow uiPopup = getChildById(id); if (uiPopup == null) { uiPopup = addChild(UIPopupWindow.class, null, id); } uiPopup.setWindowSize(700, 350); uiPopup.setShow(false); uiPopup.setResizable(true); return uiPopup; } public void activate() { try { UIAddTranslationForm uiUploadForm = getChild(UIAddTranslationForm.class); uiUploadForm.initFieldInput(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error!", e.getMessage()); } } } public void deActivate() {} public void initMetadataPopup() throws Exception { removeChildById(EXTARNAL_METADATA_POPUP) ; UIPopupWindow uiPopup = addChild(UIPopupWindow.class, null, EXTARNAL_METADATA_POPUP) ; uiPopup.setShowMask(true); uiPopup.setWindowSize(400, 400); uiPopup.setRendered(true); uiPopup.setShow(true) ; uiPopup.setResizable(true) ; } public void useWorkspaceSelector() { UIAddTranslationForm child = getChild(UIAddTranslationForm.class); if (child!=null) { child.useWorkspaceSelector(); } } }
2,992
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIAuditingInfo.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/auditing/UIAuditingInfo.java
package org.exoplatform.ecm.webui.component.explorer.auditing; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.jcr.Node; import org.exoplatform.commons.utils.LazyPageList; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.commons.utils.ListAccessImpl; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.jcr.ext.audit.AuditHistory; import org.exoplatform.services.jcr.ext.audit.AuditRecord; import org.exoplatform.services.jcr.ext.audit.AuditService; 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.UIContainer; import org.exoplatform.webui.core.UIPageIterator; import org.exoplatform.webui.core.UIPopupComponent; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Listing of the log of auditing * * @author CPop */ @ComponentConfig( template = "app:/groovy/webui/component/explorer/auditing/UIAuditingInfo.gtmpl", events = { @EventConfig(listeners = UIAuditingInfo.CloseActionListener.class) } ) public class UIAuditingInfo extends UIContainer implements UIPopupComponent { private UIPageIterator uiPageIterator_ ; private static final Log LOG = ExoLogger.getLogger(UIAuditingInfo.class.getName()); public UIAuditingInfo() throws Exception { uiPageIterator_ = addChild(UIPageIterator.class, null, "AuditingInfoIterator"); } public void activate() { } public void deActivate() { } public Node getCurrentNode() throws Exception { return getAncestorOfType(UIJCRExplorer.class).getCurrentNode(); } public UIPageIterator getUIPageIterator() { return uiPageIterator_; } public List getListRecords() throws Exception { return uiPageIterator_.getCurrentPageData(); } @SuppressWarnings("unchecked") public void updateGrid() throws Exception { ListAccess<AuditRecordData> recordList = new ListAccessImpl<AuditRecordData>(AuditRecordData.class, getRecords()); LazyPageList<AuditRecordData> dataPageList = new LazyPageList<AuditRecordData>(recordList, 10); uiPageIterator_.setPageList(dataPageList); } public List<AuditRecordData> getRecords() throws Exception { List<AuditRecordData> listRec = new ArrayList<AuditRecordData>(); Node currentNode = getCurrentNode(); try { AuditService auditService = getApplicationComponent(AuditService.class); if(Utils.isAuditable(currentNode)){ if (auditService.hasHistory(currentNode)){ AuditHistory auHistory = auditService.getHistory(currentNode); for(AuditRecord auditRecord : auHistory.getAuditRecords()) { listRec.add(new AuditRecordData(auditRecord)); } } } } catch(Exception e){ if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } return listRec; } static public class CloseActionListener extends EventListener<UIAuditingInfo> { public void execute(Event<UIAuditingInfo> event) throws Exception { UIAuditingInfo uiAuditingInfo = event.getSource(); UIJCRExplorer uiExplorer = uiAuditingInfo.getAncestorOfType(UIJCRExplorer.class); uiExplorer.cancelAction(); } } public static class AuditRecordData { private String versionName_; private String eventType_; private String userId_; private Calendar date_; public AuditRecordData(AuditRecord auditRecord) { versionName_ = null; versionName_ = auditRecord.getVersionName(); eventType_ = String.valueOf(auditRecord.getEventType()); userId_ = auditRecord.getUserId(); date_ = auditRecord.getDate(); } public String getVersionName() { return versionName_; } public void setVersionName(String versionName) { versionName_ = versionName; } public String getEventType() { return eventType_; } public void setEventType(String eventType) { eventType_ = eventType; } public String getUserId() { return userId_; } public void setUserId(String userId) { userId_ = userId; } public Calendar getDate() { return date_; } public void setDate(Calendar date) { date_ = date; } } }
4,695
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIActivateAuditing.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/auditing/UIActivateAuditing.java
package org.exoplatform.ecm.webui.component.explorer.auditing; import javax.jcr.AccessDeniedException; import javax.jcr.Node; import javax.jcr.lock.LockException; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.utils.Utils; 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; 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.UIPopupComponent; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * The dialog window to activate the auditing. * * @author CPop Bull CS */ @ComponentConfig( type = UIActivateAuditing.class, template = "app:/groovy/webui/component/explorer/auditing/UIActivateAuditing.gtmpl", events = { @EventConfig(listeners = UIActivateAuditing.EnableAuditingActionListener.class), @EventConfig(listeners = UIActivateAuditing.CancelActionListener.class) } ) public class UIActivateAuditing extends UIContainer implements UIPopupComponent { private static final Log LOG = ExoLogger.getLogger(UIActivateAuditing.class.getName()); public UIActivateAuditing() throws Exception {} public void activate() {} public void deActivate() {} /** * Event generated by "Activate" button * * @author CPop */ static public class EnableAuditingActionListener extends EventListener<UIActivateAuditing> { public void execute(Event<UIActivateAuditing> event) throws Exception { try { UIActivateAuditing uiActivateAuditing = event.getSource(); UIJCRExplorer uiExplorer = uiActivateAuditing.getAncestorOfType(UIJCRExplorer.class) ; Node currentNode = uiExplorer.getCurrentNode() ; currentNode.addMixin(Utils.EXO_AUDITABLE); AuditService auditService = WCMCoreUtils.getService(AuditService.class); if (!auditService.hasHistory(currentNode)) auditService.createHistory(currentNode); currentNode.save() ; currentNode.getSession().save(); currentNode.getSession().refresh(true) ; uiExplorer.updateAjax(event) ; } catch(LockException lockException){ UIActivateAuditing uiActivateAuditing = event.getSource(); UIJCRExplorer uiExplorer = uiActivateAuditing.getAncestorOfType(UIJCRExplorer.class) ; WebuiRequestContext contx = event.getRequestContext(); UIApplication uiApp = uiExplorer.getAncestorOfType(UIApplication.class); Object[] arg = { uiExplorer.getCurrentNode().getPath() }; uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.node-locked", arg, ApplicationMessage.WARNING)) ; } catch(AccessDeniedException accessDeniedException) { UIActivateAuditing uiActivateAuditing = event.getSource(); UIJCRExplorer uiExplorer = uiActivateAuditing.getAncestorOfType(UIJCRExplorer.class) ; WebuiRequestContext contx = event.getRequestContext(); UIApplication uiApp = uiExplorer.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.access-denied",null,ApplicationMessage.WARNING)) ; } catch(Exception e){ if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } UIActivateAuditing uiActivateAuditing = event.getSource(); UIJCRExplorer uiExplorer = uiActivateAuditing.getAncestorOfType(UIJCRExplorer.class) ; WebuiRequestContext contx = event.getRequestContext(); UIApplication uiApp = uiExplorer.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.does-not-support-auditing",null,ApplicationMessage.WARNING)) ; } } } static public class CancelActionListener extends EventListener<UIActivateAuditing> { public void execute(Event<UIActivateAuditing> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class) ; uiExplorer.cancelAction() ; } } }
4,566
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIAddMetadataForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/upload/UIAddMetadataForm.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.explorer.upload; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.Value; import javax.jcr.nodetype.NodeTypeManager; import javax.jcr.nodetype.PropertyDefinition; import org.exoplatform.services.log.Log; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.form.UIDialogForm; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.metadata.MetadataService; import org.exoplatform.services.log.ExoLogger; 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.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.UIFormDateTimeInput; import org.exoplatform.webui.form.UIFormInput; import org.exoplatform.webui.form.UIFormMultiValueInputSet; import org.exoplatform.webui.form.UIFormSelectBox; 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 * May 25, 2007 8:58:25 AM */ @ComponentConfigs( { @ComponentConfig(type = UIFormMultiValueInputSet.class, id = "WYSIWYGRichTextMultipleInputset", events = { @EventConfig(listeners = UIDialogForm.AddActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIFormMultiValueInputSet.RemoveActionListener.class, phase = Phase.DECODE) }), @ComponentConfig(lifecycle = UIFormLifecycle.class, events = { @EventConfig(listeners = UIAddMetadataForm.SaveActionListener.class), @EventConfig(listeners = UIAddMetadataForm.CancelActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIAddMetadataForm.AddActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIAddMetadataForm.RemoveActionListener.class, phase = Phase.DECODE) }) }) public class UIAddMetadataForm extends UIDialogForm { private static final Log LOG = ExoLogger.getLogger(UIAddMetadataForm.class.getName()); private String nodeType_ ; public UIAddMetadataForm() throws Exception { setActions(ACTIONS) ; } public void setNodeType(String nodeType) { nodeType_ = nodeType ; } public String getNodeType() { return nodeType_ ; } public String getDialogTemplatePath() { repositoryName = getAncestorOfType(UIJCRExplorer.class).getRepositoryName() ; MetadataService metadataService = getApplicationComponent(MetadataService.class) ; try { return metadataService.getMetadataPath(nodeType_, true) ; } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } return null ; } public String getTemplate() { return getDialogTemplatePath() ; } @SuppressWarnings("unused") public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context, String template) { return getAncestorOfType(UIJCRExplorer.class).getJCRTemplateResourceResolver() ; } @SuppressWarnings("unchecked") static public class SaveActionListener extends EventListener<UIAddMetadataForm> { public void execute(Event<UIAddMetadataForm> event) throws Exception { UIAddMetadataForm uiForm = event.getSource(); UIJCRExplorer uiJCRExplorer = uiForm.getAncestorOfType(UIJCRExplorer.class) ; UIUploadContainer uiUploadContainer = uiForm.getAncestorOfType(UIUploadContainer.class) ; Node node = uiUploadContainer.getEditNode(uiForm.nodeType_) ; NodeTypeManager ntManager = uiJCRExplorer.getSession().getWorkspace().getNodeTypeManager(); PropertyDefinition[] props = ntManager.getNodeType(uiForm.getNodeType()).getPropertyDefinitions(); List<Value> valueList = new ArrayList<Value>(); try { for (PropertyDefinition prop : props) { String name = prop.getName(); String inputName = uiForm.fieldNames.get(name) ; if (!prop.isProtected()) { int requiredType = prop.getRequiredType(); if (prop.isMultiple()) { if (requiredType == 5) { // date UIFormDateTimeInput uiFormDateTime = (UIFormDateTimeInput) uiForm.getUIInput(inputName); valueList.add(uiJCRExplorer.getSession().getValueFactory().createValue(uiFormDateTime.getCalendar())) ; node.setProperty(name, valueList.toArray(new Value[] {})); } else { if (((UIFormInput)uiForm.getUIInput(inputName)) instanceof UIFormSelectBox){ node.setProperty(name, ((UIFormSelectBox)uiForm.getUIInput(inputName)).getSelectedValues()); }else { List<String> values=(List<String>) ((UIFormMultiValueInputSet)uiForm.getUIInput(inputName)).getValue() ; node.setProperty(name, values.toArray(new String[values.size()])); } } } else { if (requiredType == 6) { // boolean UIFormInput uiInput = uiForm.getUIInput(inputName) ; boolean value = false; //2 cases to return true, UIFormSelectBox with value true or UICheckBoxInput checked if(uiInput instanceof UIFormSelectBox){ value = Boolean.parseBoolean(((UIFormSelectBox)uiInput).getValue()); }else if( uiInput instanceof UICheckBoxInput){ value = ((UICheckBoxInput)uiInput).isChecked(); } node.setProperty(name, value); } else if (requiredType == 5) { // date UIFormDateTimeInput cal = (UIFormDateTimeInput) uiForm.getUIInput(inputName); node.setProperty(name, cal.getCalendar()); } else if(requiredType == 1) { String value = ((UIFormStringInput)uiForm.getUIInput(inputName)).getValue() ; if(value == null) value = "" ; node.setProperty(name, value); } } } } } catch (Exception e) { UIUploadManager uiUploadManager = uiUploadContainer.getParent(); uiUploadManager.initMetadataPopup(); event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadManager); } node.save(); node.getSession().save(); uiUploadContainer.setRenderedChild(UIUploadContent.class) ; uiUploadContainer.removeChild(UIAddMetadataForm.class) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadContainer) ; } } static public class CancelActionListener extends EventListener<UIAddMetadataForm> { public void execute(Event<UIAddMetadataForm> event) throws Exception { UIUploadContainer uiUploadContainer = event.getSource().getParent() ; uiUploadContainer.removeChild(UIAddMetadataForm.class) ; uiUploadContainer.setRenderedChild(UIUploadContent.class) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadContainer) ; } } static public class AddActionListener extends EventListener<UIAddMetadataForm> { public void execute(Event<UIAddMetadataForm> event) throws Exception { event.getRequestContext().addUIComponentToUpdateByAjax(event.getSource().getParent()) ; } } static public class RemoveActionListener extends EventListener<UIAddMetadataForm> { public void execute(Event<UIAddMetadataForm> event) throws Exception { event.getRequestContext().addUIComponentToUpdateByAjax(event.getSource().getParent()) ; } } }
8,673
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIExternalMetadataForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/upload/UIExternalMetadataForm.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.explorer.upload; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.jcr.Node; import javax.jcr.PropertyType; import javax.jcr.Value; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeManager; import javax.jcr.nodetype.PropertyDefinition; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.metadata.MetadataService; 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.UIApplication; 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; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * May 25, 2007 3:58:09 PM */ @ComponentConfig(lifecycle = UIFormLifecycle.class, template = "system:/groovy/webui/form/UIForm.gtmpl", events = { @EventConfig(listeners = UIExternalMetadataForm.AddActionListener.class), @EventConfig(phase = Phase.DECODE, listeners = UIExternalMetadataForm.CancelActionListener.class) }) public class UIExternalMetadataForm extends UIForm { public UIExternalMetadataForm() throws Exception { } public void renderExternalList() throws Exception { MetadataService metadataService = getApplicationComponent(MetadataService.class) ; UICheckBoxInput uiCheckBox ; for(NodeType nodeType : metadataService.getAllMetadatasNodeType()) { uiCheckBox = new UICheckBoxInput(nodeType.getName(), nodeType.getName(), null) ; if(!isInternalUse(nodeType)) { if(hasExternalMetadata(nodeType.getName())) { uiCheckBox.setChecked(true); uiCheckBox.setDisabled(true) ; } else { uiCheckBox.setChecked(false) ; uiCheckBox.setDisabled(false); } addUIFormInput(uiCheckBox) ; } } } private boolean isInternalUse(NodeType nodeType) throws Exception{ for(PropertyDefinition pro : nodeType.getPropertyDefinitions()) { if(pro.getName().equals("exo:internalUse")) { return pro.getDefaultValues()[0].getBoolean(); } } return false; } private boolean hasExternalMetadata(String name) throws Exception { UIUploadManager uiUploadManager = getAncestorOfType(UIUploadManager.class) ; UIUploadContainer uiUploadContainer = uiUploadManager.getChild(UIUploadContainer.class) ; Node uploaded = uiUploadContainer.getUploadedNode() ; for(NodeType mixin : uploaded.getMixinNodeTypes()) { if(mixin.getName().equals(name)) return true ; } if(uploaded.hasNode(Utils.JCR_CONTENT)) { for(NodeType mixin : uploaded.getNode(Utils.JCR_CONTENT).getMixinNodeTypes()) { if(mixin.getName().equals(name)) return true ; } } return false ; } public String getLabel(ResourceBundle res, String id) { try { return res.getString("UIExternalMetadataForm.label." + id) ; } catch (MissingResourceException ex) { return '_' + id ; } } static public class CancelActionListener extends EventListener<UIExternalMetadataForm> { public void execute(Event<UIExternalMetadataForm> event) throws Exception { UIUploadManager uiUploadManager = event.getSource().getAncestorOfType(UIUploadManager.class) ; UIPopupWindow uiPopup = uiUploadManager.getChildById(UIUploadManager.EXTARNAL_METADATA_POPUP) ; uiPopup.setShow(false) ; uiPopup.setRendered(false) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadManager) ; } } static public class AddActionListener extends EventListener<UIExternalMetadataForm> { public void execute(Event<UIExternalMetadataForm> event) throws Exception { UIExternalMetadataForm uiExternalMetadataForm = event.getSource() ; List<UICheckBoxInput> listCheckbox = new ArrayList<UICheckBoxInput>(); uiExternalMetadataForm.findComponentOfType(listCheckbox, UICheckBoxInput.class); UIUploadManager uiUploadManager = event.getSource().getAncestorOfType(UIUploadManager.class) ; UIUploadContainer uiContainer = uiUploadManager.getChild(UIUploadContainer.class) ; String metadataName = null ; Node uploadedNode = uiContainer.getUploadedNode() ; for(int i = 0; i < listCheckbox.size(); i ++) { if(listCheckbox.get(i).isChecked() && !listCheckbox.get(i).isDisabled()) { metadataName = listCheckbox.get(i).getName() ; if(!uploadedNode.canAddMixin(metadataName)) { UIApplication uiApp = uiExternalMetadataForm.getAncestorOfType(UIApplication.class) ; uiApp.addMessage(new ApplicationMessage("UIExternalMetadataForm.msg.can-not-add", null, ApplicationMessage.WARNING)) ; return ; } uploadedNode.addMixin(metadataName); createMandatoryPropertyValue(uploadedNode, metadataName); uploadedNode.save() ; UIUploadContent uiUploadContent = uiContainer.getChild(UIUploadContent.class) ; uiUploadContent.externalList_.add(metadataName) ; } } uploadedNode.getSession().save() ; UIPopupWindow uiPopup = uiUploadManager.getChildById(UIUploadManager.EXTARNAL_METADATA_POPUP) ; uiPopup.setShow(false) ; uiPopup.setRendered(false) ; uiContainer.setRenderedChild(UIUploadContent.class) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadManager) ; } private void createMandatoryPropertyValue(Node node, String nodeTypeName) throws Exception { NodeTypeManager nodeTypeManager = node.getSession().getWorkspace().getNodeTypeManager(); NodeType nodeType = nodeTypeManager.getNodeType(nodeTypeName); for (PropertyDefinition propertyDefinition : nodeType.getPropertyDefinitions()) { if (propertyDefinition.isMandatory() && (!propertyDefinition.isAutoCreated() || !node.hasProperty(propertyDefinition.getName()))&& !propertyDefinition.isProtected()) { String propertyName = propertyDefinition.getName(); int requiredType = propertyDefinition.getRequiredType(); if (!propertyDefinition.isMultiple()) { switch (requiredType) { case PropertyType.STRING: node.setProperty(propertyName, StringUtils.EMPTY); break; case PropertyType.BINARY: node.setProperty(propertyName, ""); break; case PropertyType.BOOLEAN: node.setProperty(propertyName, false); break; case PropertyType.LONG: node.setProperty(propertyName, 0); break; case PropertyType.DOUBLE: node.setProperty(propertyName, 0); break; case PropertyType.DATE: node.setProperty(propertyName, new GregorianCalendar()); break; case PropertyType.REFERENCE: node.setProperty(propertyName, ""); break; } } else { switch (requiredType) { case PropertyType.STRING: node.setProperty(propertyName, new String[] { StringUtils.EMPTY }); break; case PropertyType.BINARY: node.setProperty(propertyName, new String[] { "" }); break; case PropertyType.BOOLEAN: node.setProperty(propertyName, new Value[] { node.getSession() .getValueFactory() .createValue(false) }); break; case PropertyType.LONG: node.setProperty(propertyName, new Value[] { node.getSession() .getValueFactory() .createValue(0L) }); break; case PropertyType.DOUBLE: node.setProperty(propertyName, new Value[] { node.getSession() .getValueFactory() .createValue(0) }); break; case PropertyType.DATE: node.setProperty(propertyName, new Value[] { node.getSession() .getValueFactory() .createValue(new GregorianCalendar()) }); break; case PropertyType.REFERENCE: node.setProperty(propertyName, new String[] {}); break; } } } } } } }
10,227
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIUploadBehaviorWithSameName.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/upload/UIUploadBehaviorWithSameName.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.component.explorer.upload; import org.exoplatform.ecm.webui.component.explorer.UIConfirmMessage; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIPopupWindow; 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 1, 2009 * 3:46:19 AM */ @ComponentConfig( template = "classpath:groovy/ecm/webui/UIConfirmMessage.gtmpl", events = { @EventConfig(listeners = UIUploadBehaviorWithSameName.ReplaceDataActionListener.class), @EventConfig(listeners = UIUploadBehaviorWithSameName.BackActionListener.class), @EventConfig(listeners = UIUploadBehaviorWithSameName.KeepfileActionListener.class) } ) public class UIUploadBehaviorWithSameName extends UIConfirmMessage { public UIUploadBehaviorWithSameName() throws Exception { } public String[] getActions() { return new String[] {"ReplaceData", "Back", "Keepfile"}; } static public class ReplaceDataActionListener extends EventListener<UIUploadBehaviorWithSameName> { public void execute(Event<UIUploadBehaviorWithSameName> event) throws Exception { UIUploadBehaviorWithSameName uiUploadBehavior = event.getSource(); UIPopupWindow uiPopup = uiUploadBehavior.getParent(); uiPopup.setShowMask(true); UIUploadManager uiUploadManager = uiPopup.getParent(); UIUploadForm uiForm = uiUploadManager.getChild(UIUploadForm.class); uiForm.doUpload(event, false); if (uiUploadManager.getChildById(UIUploadManager.SAMENAME_POPUP) != null) { uiUploadManager.removeChildById(UIUploadManager.SAMENAME_POPUP); } event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadManager); } } static public class BackActionListener extends EventListener<UIUploadBehaviorWithSameName> { public void execute(Event<UIUploadBehaviorWithSameName> event) throws Exception { UIUploadBehaviorWithSameName uiUploadBehavior = event.getSource(); UIPopupWindow uiPopup = uiUploadBehavior.getParent(); uiPopup.setRendered(false); uiPopup.setShow(false); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopup.getParent()); } } static public class KeepfileActionListener extends EventListener<UIUploadBehaviorWithSameName> { public void execute(Event<UIUploadBehaviorWithSameName> event) throws Exception { UIUploadBehaviorWithSameName uiUploadBehavior = event.getSource(); UIPopupWindow uiPopup = uiUploadBehavior.getParent(); uiPopup.setShowMask(true); UIUploadManager uiUploadManager = uiPopup.getParent(); UIUploadForm uiForm = uiUploadManager.getChild(UIUploadForm.class); uiForm.doUpload(event, true); event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadManager); } } }
3,807
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIListMetadata.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/upload/UIListMetadata.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.explorer.upload; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.PropertyDefinition; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.metadata.MetadataService; //import org.exoplatform.services.jcr.core.nodetype.ExtendedNodeType; 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.UIApplication; import org.exoplatform.webui.core.UIContainer; 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 * May 24, 2007 5:48:57 PM */ @ComponentConfig( template = "app:/groovy/webui/component/explorer/upload/UIListMetadata.gtmpl", events = { @EventConfig(listeners = UIListMetadata.EditActionListener.class) } ) public class UIListMetadata extends UIContainer { public List<String> externalList_ = new ArrayList<String>() ; private boolean isExternalMetadata = false; public void setIsExternalMetadata(boolean isExternal) { isExternalMetadata = isExternal; } public boolean getIsExternalMetadata() { return isExternalMetadata; } public Node getUploadedNode() { return ((UIUploadContainer)getParent()).getUploadedNode() ; } private boolean isInternalUse(NodeType nodeType) throws Exception{ for(PropertyDefinition pro : nodeType.getPropertyDefinitions()) { if(pro.getName().equals("exo:internalUse")) { return pro.getDefaultValues()[0].getBoolean(); } } return false; // PropertyDefinition def = // ((ExtendedNodeType)nodeType).getPropertyDefinitions("exo:internalUse").getAnyDefinition() ; // return !def.getDefaultValues()[0].getBoolean() ; } public List<String> getExternalList() throws Exception { NodeType[] mixinTypes = getUploadedNode().getMixinNodeTypes(); for(NodeType nodeType : mixinTypes) { if (nodeType.getName().equals(Utils.EXO_METADATA) && !isInternalUse(nodeType) && !externalList_.contains(nodeType.getName())) { externalList_.add(nodeType.getName()) ; } for(NodeType superType : nodeType.getSupertypes()) { if (superType.getName().equals(Utils.EXO_METADATA) && !isInternalUse(nodeType) && !externalList_.contains(nodeType.getName())) { externalList_.add(nodeType.getName()) ; } } } if(getUploadedNode().hasNode(Utils.JCR_CONTENT)) { for(NodeType nodeType : getUploadedNode().getNode(Utils.JCR_CONTENT).getMixinNodeTypes()) { if(nodeType.isNodeType(Utils.EXO_METADATA) && !isInternalUse(nodeType) && !externalList_.contains(nodeType.getName())) { externalList_.add(nodeType.getName()) ; } } } return externalList_ ; } public UIListMetadata() throws Exception { } static public class EditActionListener extends EventListener<UIListMetadata> { public void execute(Event<UIListMetadata> event) throws Exception { UIListMetadata uiUploadContent = event.getSource() ; UIUploadContainer uiUploadContainer = uiUploadContent.getParent() ; MetadataService metadataService = uiUploadContent.getApplicationComponent(MetadataService.class) ; UIJCRExplorer uiExplorer = uiUploadContent.getAncestorOfType(UIJCRExplorer.class) ; String nodeType = event.getRequestContext().getRequestParameter(OBJECTID) ; String template = metadataService.getMetadataTemplate(nodeType, true) ; if(template == null || template.trim().length() == 0) { UIApplication uiApp = uiUploadContent.getAncestorOfType(UIApplication.class) ; Object[] args = {nodeType} ; uiApp.addMessage(new ApplicationMessage("UIUploadContent.msg.has-not-template", args, ApplicationMessage.WARNING)) ; return ; } UIAddMetadataForm uiAddMetadataForm = uiUploadContainer.getChild(UIAddMetadataForm.class); if (uiAddMetadataForm == null) { uiAddMetadataForm = uiUploadContainer.createUIComponent(UIAddMetadataForm.class, null, null); uiUploadContainer.addChild(uiAddMetadataForm); } uiAddMetadataForm.getChildren().clear() ; uiAddMetadataForm.setNodeType(nodeType) ; uiAddMetadataForm.setIsNotEditNode(true) ; Node currentNode = uiExplorer.getCurrentNode() ; uiAddMetadataForm.setWorkspace(currentNode.getSession().getWorkspace().getName()) ; uiAddMetadataForm.setStoredPath(currentNode.getPath()) ; uiAddMetadataForm.setChildPath(uiUploadContainer.getEditNode(nodeType).getPath()) ; uiUploadContainer.setRenderedChild(UIAddMetadataForm.class) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadContainer) ; } } }
5,924
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIUploadContainer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/upload/UIUploadContainer.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.explorer.upload; import java.util.ArrayList; import java.util.List; import javax.jcr.Item; import javax.jcr.Node; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; 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.UIContainer; 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 * May 25, 2007 8:59:34 AM */ @ComponentConfig( template = "app:/groovy/webui/component/explorer/UITabPaneWithAction.gtmpl", events = { @EventConfig(listeners = UIUploadContainer.CloseActionListener.class), @EventConfig(listeners = UIUploadContainer.AddMetadataActionListener.class) } ) public class UIUploadContainer extends UIContainer { private static final Log LOG = ExoLogger.getLogger(UIUploadContainer.class.getName()); private NodeLocation uploadedNode_; private List<NodeLocation> listUploadedNode_ = new ArrayList<NodeLocation>(); private String[] arrayActions = new String[] {"Close"}; public UIUploadContainer() throws Exception { addChild(UIUploadContent.class, null, null) ; } public void setActions(String[] arrValueActions) { arrayActions = arrValueActions ; } public String[] getActions() { return arrayActions; } public Node getEditNode(String nodeType) throws Exception { Node uploadNode = getUploadedNode(); try { Item primaryItem = uploadNode.getPrimaryItem() ; if (primaryItem == null || !primaryItem.isNode()) return uploadNode; if (primaryItem != null && primaryItem.isNode()) { Node primaryNode = (Node) primaryItem ; if (primaryNode.isNodeType(nodeType)) return primaryNode ; } } catch(Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } return uploadNode; } public void setUploadedNode(Node node) throws Exception { uploadedNode_ = NodeLocation.getNodeLocationByNode(node); } public Node getUploadedNode() { return NodeLocation.getNodeByLocation(uploadedNode_); } public void setListUploadedNode(List<Node> listNode) throws Exception { listUploadedNode_ = NodeLocation.getLocationsByNodeList(listNode); } public List<Node> getListUploadedNode() { return NodeLocation.getNodeListByLocationList(listUploadedNode_); } static public class CloseActionListener extends EventListener<UIUploadContainer> { public void execute(Event<UIUploadContainer> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class) ; uiExplorer.cancelAction() ; } } static public class AddMetadataActionListener extends EventListener<UIUploadContainer> { public void execute(Event<UIUploadContainer> event) throws Exception { UIUploadManager uiUploadManager = event.getSource().getParent() ; uiUploadManager.initMetadataPopup() ; event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadManager) ; } } }
4,189
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIUploadContent.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/upload/UIUploadContent.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.explorer.upload; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.PropertyDefinition; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.metadata.MetadataService; //import org.exoplatform.services.jcr.core.nodetype.ExtendedNodeType; 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.UIApplication; import org.exoplatform.webui.core.UIContainer; 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 * May 24, 2007 5:48:57 PM */ @ComponentConfig( template = "app:/groovy/webui/component/explorer/upload/UIUploadContent.gtmpl", events = { @EventConfig(listeners = UIUploadContent.EditActionListener.class), @EventConfig(listeners = UIUploadContent.ManageMetadataActionListener.class) } ) public class UIUploadContent extends UIContainer { private String[] arrValues_ ; public List<String> externalList_ = new ArrayList<String>() ; private List<String[]> listArrValues_ = new ArrayList<String[]>(); private boolean isExternalMetadata = false; public UIUploadContent() throws Exception { } public Node getUploadedNode() { return ((UIUploadContainer)getParent()).getUploadedNode() ; } public List<Node> getListUploadedNode() { return ((UIUploadContainer)getParent()).getListUploadedNode(); } public List<String> getExternalList() throws Exception { NodeType[] mixinTypes = getUploadedNode().getMixinNodeTypes(); for (NodeType nodeType : mixinTypes) { if (nodeType.getName().equals(Utils.EXO_METADATA) && isExternalUse(nodeType) && !externalList_.contains(nodeType.getName())) { externalList_.add(nodeType.getName()); } for (NodeType superType : nodeType.getSupertypes()) { if (superType.getName().equals(Utils.EXO_METADATA) && isExternalUse(nodeType) && !externalList_.contains(nodeType.getName())) { externalList_.add(nodeType.getName()); } } } if (getUploadedNode().hasNode(Utils.JCR_CONTENT)) { for (NodeType nodeType : getUploadedNode().getNode(Utils.JCR_CONTENT).getMixinNodeTypes()) { if (nodeType.isNodeType(Utils.EXO_METADATA) && isExternalUse(nodeType) && !externalList_.contains(nodeType.getName())) { externalList_.add(nodeType.getName()); } } } return externalList_ ; } private boolean isExternalUse(NodeType nodeType) throws Exception{ for(PropertyDefinition pro : nodeType.getPropertyDefinitions()) { if(pro.getName().equals("exo:internalUse")) { return pro.getDefaultValues()[0].getBoolean(); } } return false; } public String[] arrUploadValues() { return arrValues_ ; } public void setUploadValues(String[] arrValues) { arrValues_ = arrValues ; } public List<String[]> listUploadValues() { return listArrValues_; } public void setListUploadValues(List<String[]> listArrValues) { listArrValues_ = listArrValues; } public void setIsExternalMetadata(boolean isExternal) { isExternalMetadata = isExternal; } public boolean getIsExternalMetadata() { return isExternalMetadata; } static public class EditActionListener extends EventListener<UIUploadContent> { public void execute(Event<UIUploadContent> event) throws Exception { UIUploadContent uiUploadContent = event.getSource() ; UIUploadContainer uiUploadContainer = uiUploadContent.getParent() ; MetadataService metadataService = uiUploadContent.getApplicationComponent(MetadataService.class) ; UIJCRExplorer uiExplorer = uiUploadContent.getAncestorOfType(UIJCRExplorer.class) ; String nodeType = event.getRequestContext().getRequestParameter(OBJECTID) ; String template = metadataService.getMetadataTemplate(nodeType, true) ; if(template == null || template.trim().length() == 0) { UIApplication uiApp = uiUploadContent.getAncestorOfType(UIApplication.class) ; Object[] args = {nodeType} ; uiApp.addMessage(new ApplicationMessage("UIUploadContent.msg.has-not-template", args, ApplicationMessage.WARNING)) ; return ; } uiUploadContainer.removeChild(UIAddMetadataForm.class) ; UIAddMetadataForm uiAddMetadataForm = uiUploadContainer.createUIComponent(UIAddMetadataForm.class, null, null) ; uiAddMetadataForm.getChildren().clear() ; uiAddMetadataForm.setNodeType(nodeType) ; uiAddMetadataForm.setIsNotEditNode(true) ; Node currentNode = uiExplorer.getCurrentNode() ; uiAddMetadataForm.setWorkspace(currentNode.getSession().getWorkspace().getName()) ; uiAddMetadataForm.setStoredPath(currentNode.getPath()) ; uiAddMetadataForm.setChildPath(uiUploadContainer.getEditNode(nodeType).getPath()) ; uiUploadContainer.addChild(uiAddMetadataForm) ; uiUploadContainer.setRenderedChild(UIAddMetadataForm.class) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadContainer) ; } } static public class ManageMetadataActionListener extends EventListener<UIUploadContent> { public void execute(Event<UIUploadContent> event) throws Exception { UIUploadContent uiUploadContent = event.getSource() ; UIUploadContainer uiUploadContainer = uiUploadContent.getParent() ; MetadataService metadataService = uiUploadContent.getApplicationComponent(MetadataService.class) ; UIJCRExplorer uiExplorer = uiUploadContent.getAncestorOfType(UIJCRExplorer.class); uiUploadContent.setIsExternalMetadata(true); String uploadedNodePath = event.getRequestContext().getRequestParameter(OBJECTID); Node uploadedNode = (Node) uiExplorer.getCurrentNode().getSession().getItem(uploadedNodePath); uiUploadContainer.setUploadedNode(uploadedNode); String nodeType = "dc:elementSet"; if(uploadedNode.hasNode(Utils.JCR_CONTENT)) { for(NodeType itemNodeType : uploadedNode.getNode(Utils.JCR_CONTENT).getMixinNodeTypes()) { if(itemNodeType.isNodeType(Utils.EXO_METADATA) && uiUploadContent.isExternalUse(itemNodeType)) { nodeType = itemNodeType.getName(); } } } String template = metadataService.getMetadataTemplate(nodeType, true) ; if(template == null || template.trim().length() == 0) { UIApplication uiApp = uiUploadContent.getAncestorOfType(UIApplication.class) ; Object[] args = {nodeType} ; uiApp.addMessage(new ApplicationMessage("UIUploadContent.msg.has-not-template", args, ApplicationMessage.WARNING)) ; return ; } uiUploadContainer.setActions(new String[] {"AddMetadata","Close"}); UIAddMetadataForm uiAddMetadataForm = uiUploadContainer.getChild(UIAddMetadataForm.class); if (uiAddMetadataForm != null) uiUploadContainer.setRenderedChild(UIAddMetadataForm.class); UIListMetadata uiListMetadata = uiUploadContainer.getChild(UIListMetadata.class); if (uiListMetadata==null) { uiListMetadata = uiUploadContainer.createUIComponent(UIListMetadata.class, null, null) ; uiUploadContainer.addChild(uiListMetadata); } uiListMetadata.setIsExternalMetadata(true); uiUploadContainer.setRenderedChild(UIListMetadata.class) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadContainer) ; } } }
8,757
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIUploadForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/upload/UIUploadForm.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.explorer.upload; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.security.AccessControlException; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.MissingResourceException; import javax.jcr.AccessDeniedException; import javax.jcr.ItemExistsException; import javax.jcr.ItemNotFoundException; import javax.jcr.NamespaceRegistry; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.portlet.PortletPreferences; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.form.validator.IllegalDMSCharValidator; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.ecm.webui.tree.selectone.UIOneTaxonomySelector; import org.exoplatform.ecm.webui.utils.JCRExceptionManager; import org.exoplatform.ecm.utils.lock.LockUtil; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.CmsService; import org.exoplatform.services.cms.JcrInputProperty; import org.exoplatform.services.cms.documents.DocumentTypeService; 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.mimetype.DMSMimeTypeResolver; import org.exoplatform.services.cms.taxonomy.TaxonomyService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.jcr.impl.core.NodeImpl; import org.exoplatform.services.listener.ListenerService; 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.utils.WCMCoreUtils; import org.exoplatform.upload.UploadResource; import org.exoplatform.upload.UploadService; 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.ComponentConfigs; 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.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.exception.MessageException; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormMultiValueInputSet; import org.exoplatform.webui.form.UIFormStringInput; import org.exoplatform.webui.form.input.UIUploadInput; import org.exoplatform.webui.form.validator.MandatoryValidator; /** * Created by The eXo Platform SARL * Author : nqhungvn * nguyenkequanghung@yahoo.com * July 3, 2006 * 10:07:15 AM */ @ComponentConfigs( { @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "app:/groovy/webui/component/explorer/upload/UIUploadForm.gtmpl", events = { @EventConfig(listeners = UIUploadForm.SaveActionListener.class), @EventConfig(listeners = UIUploadForm.CancelActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIUploadForm.AddUploadActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIUploadForm.RemoveUploadActionListener.class, phase = Phase.DECODE) } ), @ComponentConfig( type = UIFormMultiValueInputSet.class, id="UploadMultipleInputset", events = { @EventConfig(listeners = UIUploadForm.RemoveActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIUploadForm.AddActionListener.class, phase = Phase.DECODE) } ) } ) public class UIUploadForm extends UIForm implements UIPopupComponent, UISelectable { /** * Logger. */ private static final Log LOG = ExoLogger.getLogger(UIUploadForm.class.getName()); final static public String FIELD_NAME = "name" ; final static public String FIELD_UPLOAD = "upload" ; final static public String JCRCONTENT = "jcr:content"; final static public String FIELD_TAXONOMY = "fieldTaxonomy"; final static public String FIELD_LISTTAXONOMY = "fieldListTaxonomy"; final static public String POPUP_TAXONOMY = "UIPopupTaxonomy"; final static public String ACCESSIBLE_MEDIA = "accessibleMedia"; private boolean isMultiLanguage_; private List<String> listTaxonomy = new ArrayList<String>(); private List<String> listTaxonomyName = new ArrayList<String>(); private int numberUploadFile = 1; private HashMap<String, List<String>> mapTaxonomies = new HashMap<String, List<String>>(); private List<NodeLocation> listUploadedNodes = new ArrayList<NodeLocation>(); private boolean taxonomyMandatory = false; private DocumentTypeService docService; public UIUploadForm() throws Exception { setMultiPart(true) ; addUIFormInput(new UIFormStringInput(FIELD_NAME, FIELD_NAME, null). addValidator(IllegalDMSCharValidator.class)); PortletRequestContext pcontext = (PortletRequestContext)WebuiRequestContext.getCurrentInstance(); PortletPreferences portletPref = pcontext.getRequest().getPreferences(); String limitPref = portletPref.getValue(Utils.UPLOAD_SIZE_LIMIT_MB, ""); UIUploadInput uiInput = null; if (limitPref != null) { try { uiInput = new UIUploadInput(FIELD_UPLOAD, FIELD_UPLOAD, 1, Integer.parseInt(limitPref.trim())); } catch (NumberFormatException e) { uiInput = new UIUploadInput(FIELD_UPLOAD, FIELD_UPLOAD); } } else { uiInput = new UIUploadInput(FIELD_UPLOAD, FIELD_UPLOAD); } addUIFormInput(uiInput); docService = WCMCoreUtils.getService(DocumentTypeService.class); } public int getNumberUploadFile() { return numberUploadFile; } public void setNumberUploadFile(int numberUpload) { numberUploadFile = numberUpload; } public HashMap<String, List<String>> getMapTaxonomies() { return mapTaxonomies; } public void setMapTaxonomies(HashMap<String, List<String>> mapTaxonomiesAvaiable) { mapTaxonomies = mapTaxonomiesAvaiable; } public List<String> getListTaxonomy() { return listTaxonomy; } public List<String> getlistTaxonomyName() { return listTaxonomyName; } public void setListTaxonomy(List<String> listTaxonomyNew) { listTaxonomy = listTaxonomyNew; } public void setListTaxonomyName(List<String> listTaxonomyNameNew) { listTaxonomyName = listTaxonomyNameNew; } public boolean getTaxonomyMandatory() { return taxonomyMandatory; } public void setTaxonomyMandatory(boolean taxoMandatory) { taxonomyMandatory = taxoMandatory; } public String getPathTaxonomy() throws Exception { UIJCRExplorer uiExplorer = getAncestorOfType(UIJCRExplorer.class); DMSConfiguration dmsConfig = getApplicationComponent(DMSConfiguration.class); DMSRepositoryConfiguration dmsRepoConfig = dmsConfig.getConfig(); String workspaceName = dmsRepoConfig.getSystemWorkspace(); NodeHierarchyCreator nodeHierarchyCreator = getApplicationComponent(NodeHierarchyCreator.class); Session session = uiExplorer.getSessionByWorkspace(workspaceName); return ((Node)session.getItem(nodeHierarchyCreator.getJcrPath(BasePath.TAXONOMIES_TREE_STORAGE_PATH))).getPath(); } public void initFieldInput() throws Exception { PortletRequestContext pcontext = (PortletRequestContext)WebuiRequestContext.getCurrentInstance(); PortletPreferences portletPref = pcontext.getRequest().getPreferences(); String categoryMandatoryWhenFileUpload = portletPref.getValue(Utils.CATEGORY_MANDATORY, "").trim(); UIFormMultiValueInputSet uiFormMultiValue = createUIComponent(UIFormMultiValueInputSet.class, "UploadMultipleInputset", null); uiFormMultiValue.setId(FIELD_LISTTAXONOMY); uiFormMultiValue.setName(FIELD_LISTTAXONOMY); uiFormMultiValue.setType(UIFormStringInput.class); uiFormMultiValue.setEditable(false); if (categoryMandatoryWhenFileUpload.equalsIgnoreCase("true")) { uiFormMultiValue.addValidator(MandatoryValidator.class); setTaxonomyMandatory(true); } else { setTaxonomyMandatory(false); } uiFormMultiValue.setValue(listTaxonomyName); addUIFormInput(uiFormMultiValue); } public String[] getActions() { return new String[] {"Save", "Cancel"}; } public void setIsMultiLanguage(boolean isMultiLanguage, String language) { isMultiLanguage_ = isMultiLanguage ; } public void resetComponent() { removeChildById(FIELD_UPLOAD); addUIFormInput(new UIUploadInput(FIELD_UPLOAD, FIELD_UPLOAD)); } public boolean isMultiLanguage() { return isMultiLanguage_ ; } public void activate() {} public void deActivate() {} public void doSelect(String selectField, Object value) throws Exception { String valueTaxonomy = String.valueOf(value).trim(); List<String> indexMapTaxonomy = new ArrayList<String>(); if (mapTaxonomies.containsKey(selectField)){ indexMapTaxonomy = mapTaxonomies.get(selectField); mapTaxonomies.remove(selectField); } if (!indexMapTaxonomy.contains(valueTaxonomy)) indexMapTaxonomy.add(valueTaxonomy); mapTaxonomies.put(selectField, indexMapTaxonomy); updateAdvanceTaxonomy(selectField); UIUploadManager uiUploadManager = getParent(); uiUploadManager.removeChildById(POPUP_TAXONOMY); } public List<String> getListSameNames(Event<UIUploadForm> event) throws Exception { List<String> sameNameList = new ArrayList<String>(); Node selectedNode = getAncestorOfType(UIJCRExplorer.class).getCurrentNode(); int index = 0; String name = null; for (UIComponent uiComp : getChildren()) { if(uiComp instanceof UIUploadInput) { String[] arrayId = uiComp.getId().split(FIELD_UPLOAD); if ((arrayId.length > 0) && (arrayId[0].length() > 0)) index = new Integer(arrayId[0]).intValue(); UIUploadInput uiUploadInput; if (index == 0){ uiUploadInput = (UIUploadInput)getUIInput(FIELD_UPLOAD); } else { uiUploadInput = (UIUploadInput)getUIInput(index + FIELD_UPLOAD); } String uploadId = uiUploadInput.getUploadIds()[0]; if (uiUploadInput.getUploadResource(uploadId) == null) return sameNameList; String fileName = uiUploadInput.getUploadResource(uploadId).getFileName(); if (index == 0){ name = getUIStringInput(FIELD_NAME).getValue(); } else { name = getUIStringInput(index + FIELD_NAME).getValue(); } if(name == null) { name = fileName; } else { name = name.trim(); } name = Text.escapeIllegalJcrChars(name); if (!passNameValidation(name)) { return new ArrayList<String>(); } if(selectedNode.hasNode(name)) sameNameList.add(name); } } return sameNameList; } @SuppressWarnings("rawtypes") public void doUpload(Event event, boolean isKeepFile) throws Exception { UIApplication uiApp = getAncestorOfType(UIApplication.class) ; UIJCRExplorer uiExplorer = getAncestorOfType(UIJCRExplorer.class) ; UIUploadManager uiManager = getParent(); UIUploadContainer uiUploadContainer = uiManager.getChild(UIUploadContainer.class); UploadService uploadService = getApplicationComponent(UploadService.class); UIUploadContent uiUploadContent = uiManager.findFirstComponentOfType(UIUploadContent.class); List<String[]> listArrValues = new ArrayList<String[]>(); CmsService cmsService = getApplicationComponent(CmsService.class) ; List<UIComponent> listFormChildren = getChildren(); int index = 0; InputStream inputStream; String name = null; TaxonomyService taxonomyService = getApplicationComponent(TaxonomyService.class); if(uiExplorer.getCurrentNode().isLocked()) { String lockToken = LockUtil.getLockToken(uiExplorer.getCurrentNode()); if(lockToken != null) uiExplorer.getSession().addLockToken(lockToken); } PortletRequestContext pcontext = (PortletRequestContext)WebuiRequestContext.getCurrentInstance(); PortletPreferences portletPref = pcontext.getRequest().getPreferences(); String categoryMandatoryWhenFileUpload = portletPref.getValue(Utils.CATEGORY_MANDATORY, "").trim(); DMSMimeTypeResolver mimeTypeSolver = DMSMimeTypeResolver.getInstance(); Node selectedNode = uiExplorer.getCurrentNode(); if (categoryMandatoryWhenFileUpload.equalsIgnoreCase("true") && (getMapTaxonomies().size() == 0) && !uiExplorer.getCurrentNode().hasNode(JCRCONTENT)) { uiApp.addMessage(new ApplicationMessage("UIUploadForm.msg.taxonomyPath-error", null, ApplicationMessage.WARNING)) ; return ; } String pers = PermissionType.ADD_NODE + "," + PermissionType.SET_PROPERTY ; selectedNode.getSession().checkPermission(selectedNode.getPath(), pers); try { int indexValidate = 0; for (UIComponent uiCompValidate : listFormChildren) { if(uiCompValidate instanceof UIUploadInput) { String[] arrayIdValidate = uiCompValidate.getId().split(FIELD_UPLOAD); if ((arrayIdValidate.length > 0) && (arrayIdValidate[0].length() > 0)) indexValidate = new Integer(arrayIdValidate[0]).intValue(); UIUploadInput uiUploadInput; if (indexValidate == 0){ uiUploadInput = (UIUploadInput) getUIInput(FIELD_UPLOAD); } else { uiUploadInput = (UIUploadInput) getUIInput(indexValidate + FIELD_UPLOAD); } String uploadId = uiUploadInput.getUploadIds()[0]; if(uiUploadInput.getUploadResource(uploadId) == null) { uiApp.addMessage(new ApplicationMessage("UIUploadForm.msg.fileName-error", null, ApplicationMessage.WARNING)) ; return ; } String fileName = uiUploadInput.getUploadResource(uploadId).getFileName(); if(fileName == null || fileName.length() == 0) { uiApp.addMessage(new ApplicationMessage("UIUploadForm.msg.fileName-error", null, ApplicationMessage.WARNING)) ; return; } } } for (UIComponent uiComp : listFormChildren) { if(uiComp instanceof UIUploadInput) { String[] arrayId = uiComp.getId().split(FIELD_UPLOAD); if ((arrayId.length > 0) && (arrayId[0].length() > 0)) index = new Integer(arrayId[0]).intValue(); UIUploadInput uiUploadInput; if (index == 0){ uiUploadInput = (UIUploadInput) getUIInput(FIELD_UPLOAD); } else { uiUploadInput = (UIUploadInput) getUIInput(index + FIELD_UPLOAD); } String uploadId = uiUploadInput.getUploadIds()[0]; if(uiUploadInput.getUploadResource(uploadId) == null) { if ((listUploadedNodes != null) && (listUploadedNodes.size() > 0)) { for (Object uploadedNode : NodeLocation.getNodeListByLocationList(listUploadedNodes)) { ((Node)uploadedNode).remove(); } uiExplorer.getCurrentNode().save(); listUploadedNodes.clear(); } uiApp.addMessage(new ApplicationMessage("UIUploadForm.msg.fileName-error", null, ApplicationMessage.WARNING)) ; return ; } String fileName = uiUploadInput.getUploadResource(uploadId).getFileName(); if(fileName == null || fileName.length() == 0) { if ((listUploadedNodes != null) && (listUploadedNodes.size() > 0)) { for (Object uploadedNode : NodeLocation.getNodeListByLocationList(listUploadedNodes)) { ((Node)uploadedNode).remove(); } uiExplorer.getCurrentNode().save(); listUploadedNodes.clear(); } uiApp.addMessage(new ApplicationMessage("UIUploadForm.msg.fileName-error", null, ApplicationMessage.WARNING)) ; return; } try { inputStream = new BufferedInputStream(uiUploadInput.getUploadDataAsStream(uploadId)); } catch (FileNotFoundException e) { inputStream = new BufferedInputStream(new ByteArrayInputStream(new byte[] {})); } if (index == 0){ name = getUIStringInput(FIELD_NAME).getValue(); } else { name = getUIStringInput(index + FIELD_NAME).getValue(); } if(name == null) name = fileName; else name = name.trim(); if (!passNameValidation(name)) { uiApp.addMessage(new ApplicationMessage("UIUploadForm.msg.fileName-invalid-with-name", new Object[] {name}, ApplicationMessage.WARNING)); return; } name = Text.escapeIllegalJcrChars(name); // Append extension if necessary String mimeType = mimeTypeSolver.getMimeType(fileName); String ext = "." + fileName.substring(fileName.lastIndexOf(".") + 1); if (name.lastIndexOf(ext) < 0 && !mimeTypeSolver.getMimeType(name).equals(mimeType)) { StringBuffer sb = new StringBuffer(); sb.append(name).append(ext); name = sb.toString(); } List<String> listTaxonomyNameNew = new ArrayList<String>(); if (index == 0) listTaxonomyNameNew = mapTaxonomies.get(FIELD_LISTTAXONOMY); else listTaxonomyNameNew = mapTaxonomies.get(index + FIELD_LISTTAXONOMY); String taxonomyTree = null; String taxonomyPath = null; if (listTaxonomyNameNew != null) { for(String categoryPath : listTaxonomyNameNew) { try { if (categoryPath.startsWith("/")) categoryPath = categoryPath.substring(1); if(categoryPath.indexOf("/")>0) { taxonomyTree = categoryPath.substring(0, categoryPath.indexOf("/")); taxonomyPath = categoryPath.substring(categoryPath.indexOf("/") + 1); taxonomyService.getTaxonomyTree(taxonomyTree).hasNode(taxonomyPath); } else { taxonomyTree = categoryPath; taxonomyPath = ""; } } catch (ItemNotFoundException e) { uiApp.addMessage(new ApplicationMessage("UISelectedCategoriesGrid.msg.non-categories", null, ApplicationMessage.WARNING)) ; return; } catch (RepositoryException re) { uiApp.addMessage(new ApplicationMessage("UISelectedCategoriesGrid.msg.non-categories", null, ApplicationMessage.WARNING)) ; return; } catch(Exception e) { if (LOG.isErrorEnabled()) { LOG.error("An unexpected error occurs", e); } uiApp.addMessage(new ApplicationMessage("UISelectedCategoriesGrid.msg.non-categories", null, ApplicationMessage.WARNING)) ; return; } } } boolean isExist = selectedNode.hasNode(name) ; String newNodeUUID = null; if(selectedNode.getPrimaryNodeType().isNodeType(Utils.NT_FILE)) { if(!selectedNode.isCheckedOut()) selectedNode.checkout() ; Node contentNode = selectedNode.getNode(Utils.JCR_CONTENT); if(contentNode.getProperty(Utils.JCR_MIMETYPE).getString().equals(mimeType)) { contentNode.setProperty(Utils.JCR_DATA, inputStream); contentNode.setProperty(Utils.JCR_LASTMODIFIED, new GregorianCalendar()); selectedNode.save() ; uiManager.setRendered(false); uiExplorer.updateAjax(event); return; } } if(!isExist || isKeepFile) { String nodeType = contains(docService.getMimeTypes(ACCESSIBLE_MEDIA), mimeType) ? NodetypeConstant.EXO_ACCESSIBLE_MEDIA : Utils.NT_FILE; newNodeUUID = cmsService.storeNodeByUUID(nodeType, selectedNode, getInputProperties(name, inputStream, mimeType), true) ; selectedNode.save(); selectedNode.getSession().save(); if ((listTaxonomyNameNew != null) && (listTaxonomyNameNew.size() > 0)) { Node newNode = null; try { newNode = selectedNode.getSession().getNodeByUUID(newNodeUUID); } catch(ItemNotFoundException e) { newNode = Utils.findNodeByUUID(newNodeUUID); } if (newNode != null) { for (String categoryPath : listTaxonomyNameNew) { try { if (categoryPath.startsWith("/")) categoryPath = categoryPath.substring(1); if(categoryPath.indexOf("/")>0) { taxonomyTree = categoryPath.substring(0, categoryPath.indexOf("/")); taxonomyPath = categoryPath.substring(categoryPath.indexOf("/") + 1); } else { taxonomyTree = categoryPath; taxonomyPath = ""; } taxonomyService.addCategory(newNode, taxonomyTree, taxonomyPath); } catch (ItemExistsException e) { uiApp.addMessage(new ApplicationMessage("UIUploadForm.msg.ItemExistsException", null, ApplicationMessage.WARNING)); return; } catch (RepositoryException e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } JCRExceptionManager.process(uiApp, e); return; } } } } } else { Node node = selectedNode.getNode(name) ; if (isTaxonomyChildNode(node)) { LinkManager linkManager = getApplicationComponent(LinkManager.class); node = linkManager.getTarget(node); } if(!node.getPrimaryNodeType().isNodeType(Utils.NT_FILE)) { Object[] args = { name } ; uiApp.addMessage(new ApplicationMessage("UIUploadForm.msg.name-is-exist", args, ApplicationMessage.WARNING)) ; return ; } String nodetypes = System.getProperty("wcm.nodetypes.ignoreversion"); if(nodetypes == null || nodetypes.length() == 0) nodetypes = "exo:webContent"; if(Utils.isMakeVersionable(node, nodetypes.split(","))) { if(!node.isNodeType(Utils.MIX_VERSIONABLE) && node.canAddMixin(Utils.MIX_VERSIONABLE)) { node.addMixin(Utils.MIX_VERSIONABLE); } } Node contentNode = node.getNode(Utils.JCR_CONTENT); if(!node.isCheckedOut()) node.checkout() ; contentNode.setProperty(Utils.JCR_DATA, inputStream); contentNode.setProperty(Utils.JCR_MIMETYPE, mimeType); contentNode.setProperty(Utils.JCR_LASTMODIFIED, new GregorianCalendar()); if (node.isNodeType("exo:datetime")) { node.setProperty("exo:dateModified",new GregorianCalendar()) ; } node.save(); ListenerService listenerService = getApplicationComponent(ListenerService.class); listenerService.broadcast(CmsService.POST_EDIT_CONTENT_EVENT, this, node); if (listTaxonomyNameNew != null) { for (String categoryPath : listTaxonomyNameNew) { try { if (categoryPath.startsWith("/")) categoryPath = categoryPath.substring(1); if(categoryPath.indexOf("/")>0) { taxonomyTree = categoryPath.substring(0, categoryPath.indexOf("/")); taxonomyPath = categoryPath.substring(categoryPath.indexOf("/") + 1); } else { taxonomyTree = categoryPath; taxonomyPath = ""; } taxonomyService.addCategory(node, taxonomyTree, taxonomyPath); } catch (ItemExistsException e) { uiApp.addMessage(new ApplicationMessage("UIUploadForm.msg.ItemExistsException", null, ApplicationMessage.WARNING)); return; } catch (RepositoryException e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } JCRExceptionManager.process(uiApp, e); return; } } } } uiExplorer.getSession().save() ; Node uploadedNode = null; if(isMultiLanguage_) { uiUploadContainer.setUploadedNode(selectedNode); uploadedNode = selectedNode; } else { Node newNode = null ; if(!isExist) { try { newNode = selectedNode.getSession().getNodeByUUID(newNodeUUID); } catch(ItemNotFoundException e) { newNode = Utils.findNodeByUUID(newNodeUUID); } } else { newNode = selectedNode.getNode(name) ; } if(newNode != null) { uiUploadContainer.setUploadedNode(newNode); uploadedNode = newNode; } } if(mimeType.indexOf(Utils.FLASH_MIMETYPE) >= 0 && uploadedNode.canAddMixin(Utils.EXO_RISIZEABLE)) { uploadedNode.addMixin(Utils.EXO_RISIZEABLE); uploadedNode.save(); } //get file size double size = 0; if (uploadedNode.hasNode(Utils.JCR_CONTENT)) { Node contentNode = uploadedNode.getNode(Utils.JCR_CONTENT); if (contentNode.hasProperty(Utils.JCR_DATA)) { size = contentNode.getProperty(Utils.JCR_DATA).getLength(); } } else { size = uploadService.getUploadResource(uiUploadInput.getUploadIds()[0]).getEstimatedSize(); } String fileSize = Utils.calculateFileSize(size); String iconUpload = Utils.getNodeTypeIcon(uploadedNode, "16x16Icon").replaceAll("nt_file16x16Icon ", ""); String[] arrValues = {iconUpload, Text.unescapeIllegalJcrChars(fileName), Text.unescapeIllegalJcrChars(name), fileSize, mimeType, uploadedNode.getPath()}; listUploadedNodes.add(NodeLocation.getNodeLocationByNode(uploadedNode)); listArrValues.add(arrValues); inputStream.close(); } } uiUploadContent.setListUploadValues(listArrValues); uiManager.setRenderedChild(UIUploadContainer.class); uiExplorer.setIsHidePopup(true); uiExplorer.updateAjax(event); event.getRequestContext().addUIComponentToUpdateByAjax(uiManager); } catch(ConstraintViolationException con) { Object[] args = {name, } ; throw new MessageException(new ApplicationMessage("UIUploadForm.msg.contraint-violation", args, ApplicationMessage.WARNING)) ; } catch(LockException lock) { throw new MessageException(new ApplicationMessage("UIUploadForm.msg.lock-exception", null, ApplicationMessage.WARNING)) ; } catch(AccessDeniedException ade) { throw new MessageException(new ApplicationMessage("UIActionBar.msg.access-add-denied", null, ApplicationMessage.WARNING)); } catch(AccessControlException ace) { throw new MessageException(new ApplicationMessage("UIActionBar.msg.access-add-denied", null, ApplicationMessage.WARNING)); } catch (ItemExistsException iee) { uiApp.addMessage(new ApplicationMessage("UIActionBar.msg.item-existed", null, ApplicationMessage.WARNING)); } catch(Exception e) { if (LOG.isErrorEnabled()) { LOG.error("An unexpected error occurs", e); } JCRExceptionManager.process(uiApp, e); return ; } } /** * Check if a node is child node of taxonomy node or not * * @param node * @return */ private boolean isTaxonomyChildNode(Node node) throws RepositoryException { Node parrentNode = node.getParent(); while (!((NodeImpl) parrentNode).isRoot()) { if (parrentNode.isNodeType(Utils.EXO_TAXONOMY)) { return true; } parrentNode = parrentNode.getParent(); } return false; } private Map<String, JcrInputProperty> getInputProperties(String name, InputStream inputStream, String mimeType) { Map<String,JcrInputProperty> inputProperties = new HashMap<String,JcrInputProperty>() ; JcrInputProperty nodeInput = new JcrInputProperty() ; nodeInput.setJcrPath("/node") ; nodeInput.setValue(name) ; nodeInput.setMixintype("mix:i18n,mix:votable,mix:commentable") ; nodeInput.setType(JcrInputProperty.NODE) ; inputProperties.put("/node",nodeInput) ; JcrInputProperty jcrContent = new JcrInputProperty() ; jcrContent.setJcrPath("/node/jcr:content") ; jcrContent.setValue("") ; jcrContent.setMixintype("dc:elementSet") ; jcrContent.setNodetype(Utils.NT_RESOURCE) ; jcrContent.setType(JcrInputProperty.NODE) ; inputProperties.put("/node/jcr:content",jcrContent) ; JcrInputProperty jcrData = new JcrInputProperty() ; jcrData.setJcrPath("/node/jcr:content/jcr:data") ; jcrData.setValue(inputStream) ; inputProperties.put("/node/jcr:content/jcr:data",jcrData) ; JcrInputProperty jcrMimeType = new JcrInputProperty() ; jcrMimeType.setJcrPath("/node/jcr:content/jcr:mimeType") ; jcrMimeType.setValue(mimeType) ; inputProperties.put("/node/jcr:content/jcr:mimeType",jcrMimeType) ; JcrInputProperty jcrLastModified = new JcrInputProperty() ; jcrLastModified.setJcrPath("/node/jcr:content/jcr:lastModified") ; jcrLastModified.setValue(new GregorianCalendar()) ; inputProperties.put("/node/jcr:content/jcr:lastModified",jcrLastModified) ; JcrInputProperty jcrEncoding = new JcrInputProperty() ; jcrEncoding.setJcrPath("/node/jcr:content/jcr:encoding") ; jcrEncoding.setValue("UTF-8") ; inputProperties.put("/node/jcr:content/jcr:encoding",jcrEncoding) ; return inputProperties; } private void updateAdvanceTaxonomy(String selectField) throws Exception { List<UIComponent> listChildren = getChildren(); for (UIComponent uiComp : listChildren) { if (uiComp.getId().equals(selectField)) { UIFormMultiValueInputSet uiFormMultiValueInputSet = getChildById(selectField); if (mapTaxonomies.containsKey(selectField)) uiFormMultiValueInputSet.setValue(getTaxonomyLabel(mapTaxonomies.get(selectField))); } } } private List<String> getTaxonomyLabel(List<String> taxonomyPaths) { List<String> taxonomyLabels = new ArrayList<String>(); String[] taxonomyPathSplit = null; StringBuilder buildlabel; StringBuilder buildPathlabel; for (String taxonomyPath : taxonomyPaths) { if (taxonomyPath.startsWith("/")) taxonomyPath = taxonomyPath.substring(1); taxonomyPathSplit = taxonomyPath.split("/"); buildlabel = new StringBuilder(); buildPathlabel = new StringBuilder(); for (int i = 0; i < taxonomyPathSplit.length; i++) { buildlabel = new StringBuilder("eXoTaxonomies"); try { for (int j = 0; j <= i; j++) { buildlabel.append(".").append(taxonomyPathSplit[j]); } buildPathlabel.append(Utils.getResourceBundle(buildlabel.append(".label").toString())).append("/"); } catch (MissingResourceException me) { buildPathlabel.append(taxonomyPathSplit[i]).append("/"); } } taxonomyLabels.add(buildPathlabel.substring(0, buildPathlabel.length() - 1)); } return taxonomyLabels; } private boolean passNameValidation(String name) throws Exception { if (name == null || name.contains("[") || name.contains("]") || name.contains("\"") || name.contains("/")) return false; int count = 0; for (char c : name.toCharArray()) { if (c == ':') count ++; if (count > 1) return false; } if (count == 1) { if (name.split(":").length < 2) return false; String namespace = name.split(":")[0]; NamespaceRegistry namespaceRegistry = getApplicationComponent(RepositoryService.class) .getRepository(getAncestorOfType(UIJCRExplorer.class).getRepositoryName()).getNamespaceRegistry() ; String[] prefixs = namespaceRegistry.getPrefixes(); for (String prefix : prefixs) if (namespace.equals(prefix)) return true; return false; } return true; } private boolean contains(String[] arr, String item) { if (arr != null) { for (String arrItem : arr) { if (StringUtils.equals(arrItem, item)) return true; } } return false; } static public class SaveActionListener extends EventListener<UIUploadForm> { public void execute(Event<UIUploadForm> event) throws Exception { UIUploadForm uiForm = event.getSource(); UIUploadManager uiManager = uiForm.getParent(); if(uiForm.getListSameNames(event).size() > 0) { UIPopupWindow uiPopupWindow = uiManager.initPopupWhenHaveSameName(); UIUploadBehaviorWithSameName uiUploadBehavior = uiManager.createUIComponent(UIUploadBehaviorWithSameName.class, null, null); uiUploadBehavior.setMessageKey("UIUploadForm.msg.confirm-behavior"); uiUploadBehavior.setArguments( uiForm.getListSameNames(event).toArray(new String[uiForm.getListSameNames(event).size()])); uiPopupWindow.setUIComponent(uiUploadBehavior); uiPopupWindow.setShow(true); uiPopupWindow.setRendered(true); event.getRequestContext().addUIComponentToUpdateByAjax(uiManager); return; } uiForm.doUpload(event, false); } } static public class CancelActionListener extends EventListener<UIUploadForm> { public void execute(Event<UIUploadForm> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class) ; uiExplorer.cancelAction() ; } } static public class RemoveActionListener extends EventListener<UIFormMultiValueInputSet> { public void execute(Event<UIFormMultiValueInputSet> event) throws Exception { UIFormMultiValueInputSet uiSet = event.getSource(); UIComponent uiComponent = uiSet.getParent(); if (uiComponent instanceof UIUploadForm) { UIUploadForm uiUploadForm = (UIUploadForm)uiComponent; String id = event.getRequestContext().getRequestParameter(OBJECTID); String[] arrayId = id.split(FIELD_LISTTAXONOMY); int index = 0; int indexRemove = 0; if ((arrayId.length > 0) && (arrayId[0].length() > 0)) index = new Integer(arrayId[0]).intValue(); if ((arrayId.length > 0) && (arrayId[1].length() > 0)) indexRemove = new Integer(arrayId[1]).intValue(); String idFieldListTaxonomy; if (index == 0) idFieldListTaxonomy = FIELD_LISTTAXONOMY; else idFieldListTaxonomy = index + FIELD_LISTTAXONOMY; if (uiUploadForm.mapTaxonomies.containsKey(idFieldListTaxonomy)) { List<String> indexMapTaxonomy = new ArrayList<String>(); indexMapTaxonomy = uiUploadForm.mapTaxonomies.get(idFieldListTaxonomy); uiUploadForm.mapTaxonomies.remove(idFieldListTaxonomy); if (indexMapTaxonomy.size() > indexRemove) indexMapTaxonomy.remove(indexRemove); uiUploadForm.mapTaxonomies.put(idFieldListTaxonomy, indexMapTaxonomy); } uiSet.removeChildById(id); event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadForm); } } } static public class AddActionListener extends EventListener<UIFormMultiValueInputSet> { public void execute(Event<UIFormMultiValueInputSet> event) throws Exception { UIFormMultiValueInputSet uiSet = event.getSource(); UIUploadForm uiUploadForm = (UIUploadForm) uiSet.getParent(); UIApplication uiApp = uiUploadForm.getAncestorOfType(UIApplication.class); try { String fieldTaxonomyId = event.getRequestContext().getRequestParameter(OBJECTID); String[] arrayId = fieldTaxonomyId.split(FIELD_LISTTAXONOMY); int index = 0; if ((arrayId.length > 0) && (arrayId[0].length() > 0)) index = new Integer(arrayId[0]).intValue(); String idFieldUpload; if (index == 0) idFieldUpload = FIELD_UPLOAD; else idFieldUpload = index + FIELD_UPLOAD; UIUploadInput uiUploadInput = uiUploadForm.getChildById(idFieldUpload); UploadResource uploadResource = uiUploadInput.getUploadResource(uiUploadInput.getUploadIds()[0]); if (uploadResource == null) { uiApp.addMessage(new ApplicationMessage("UIUploadForm.msg.upload-not-null", null, ApplicationMessage.WARNING)); return; } UIUploadManager uiUploadManager = uiUploadForm.getParent(); UIJCRExplorer uiExplorer = uiUploadForm.getAncestorOfType(UIJCRExplorer.class); String repository = uiExplorer.getRepositoryName(); UIPopupWindow uiPopupWindow = uiUploadManager.initPopupTaxonomy(POPUP_TAXONOMY); UIOneTaxonomySelector uiOneTaxonomySelector = uiUploadManager.createUIComponent(UIOneTaxonomySelector.class, null, null); uiPopupWindow.setUIComponent(uiOneTaxonomySelector); TaxonomyService taxonomyService = uiUploadForm.getApplicationComponent(TaxonomyService.class); List<Node> lstTaxonomyTree = taxonomyService.getAllTaxonomyTrees(); if (lstTaxonomyTree.size() == 0) throw new AccessDeniedException(); String workspaceName = lstTaxonomyTree.get(0).getSession().getWorkspace().getName(); uiOneTaxonomySelector.setIsDisable(workspaceName, false); uiOneTaxonomySelector.setRootNodeLocation(repository, workspaceName, lstTaxonomyTree.get(0).getPath()); uiOneTaxonomySelector.setExceptedNodeTypesInPathPanel(new String[] {Utils.EXO_SYMLINK}); uiOneTaxonomySelector.init(uiExplorer.getSystemProvider()); String param = "returnField=" + fieldTaxonomyId; uiOneTaxonomySelector.setSourceComponent(uiUploadForm, new String[]{param}); uiPopupWindow.setRendered(true); uiPopupWindow.setShow(true); event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadManager); } catch (AccessDeniedException accessDeniedException) { uiApp.addMessage(new ApplicationMessage("Taxonomy.msg.AccessDeniedException", null, ApplicationMessage.WARNING)); return; } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } } } static public class AddUploadActionListener extends EventListener<UIUploadForm> { public void execute(Event<UIUploadForm> event) throws Exception { UIUploadForm uiUploadForm = event.getSource(); List<UIComponent> listChildren = uiUploadForm.getChildren(); int index = 0; int numberUploadFile = 0; String fieldFieldUpload = null; for (UIComponent uiComp : listChildren) { if(uiComp instanceof UIUploadInput) { fieldFieldUpload = uiComp.getId(); numberUploadFile++; } } if (fieldFieldUpload != null) { String[] arrayId = fieldFieldUpload.split(FIELD_UPLOAD); if ((arrayId.length > 0) && (arrayId[0].length() > 0)) index = new Integer(arrayId[0]).intValue(); } index++; uiUploadForm.addUIFormInput(new UIFormStringInput(index + FIELD_NAME, index + FIELD_NAME, null)); PortletRequestContext pcontext = (PortletRequestContext)WebuiRequestContext.getCurrentInstance(); PortletPreferences portletPref = pcontext.getRequest().getPreferences(); String limitPref = portletPref.getValue(Utils.UPLOAD_SIZE_LIMIT_MB, ""); UIUploadInput uiInput = null; if (limitPref != null) { try { uiInput = new UIUploadInput(index + FIELD_UPLOAD, index + FIELD_UPLOAD, Integer.parseInt(limitPref.trim())); } catch (NumberFormatException e) { uiInput = new UIUploadInput(index + FIELD_UPLOAD, index + FIELD_UPLOAD); } } else { uiInput = new UIUploadInput(index + FIELD_UPLOAD, index + FIELD_UPLOAD); } uiUploadForm.addUIFormInput(uiInput); UIFormMultiValueInputSet uiFormMultiValue = uiUploadForm.createUIComponent(UIFormMultiValueInputSet.class, "UploadMultipleInputset", null); uiFormMultiValue.setId(index + FIELD_LISTTAXONOMY); uiFormMultiValue.setName(index + FIELD_LISTTAXONOMY); uiFormMultiValue.setType(UIFormStringInput.class); uiFormMultiValue.setEditable(false); uiUploadForm.addUIFormInput(uiFormMultiValue); uiUploadForm.setNumberUploadFile(numberUploadFile + 1); uiUploadForm.setRendered(true); event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadForm.getParent()); } } static public class RemoveUploadActionListener extends EventListener<UIUploadForm> { public void execute(Event<UIUploadForm> event) throws Exception { String id = event.getRequestContext().getRequestParameter(OBJECTID); UIUploadForm uiUploadForm = event.getSource(); List<UIComponent> listChildren = uiUploadForm.getChildren(); int index = 0; for (UIComponent uiComp : listChildren) { if(uiComp instanceof UIUploadInput) index++; } String[] arrayId = id.split(FIELD_NAME); int indexRemove = 0; if ((arrayId.length > 0) && (arrayId[0].length() > 0)) indexRemove = new Integer(arrayId[0]).intValue(); if (indexRemove == 0) { uiUploadForm.removeChildById(FIELD_NAME); uiUploadForm.removeChildById(FIELD_UPLOAD); uiUploadForm.removeChildById(FIELD_LISTTAXONOMY); if (uiUploadForm.mapTaxonomies.containsKey(FIELD_LISTTAXONOMY)) uiUploadForm.mapTaxonomies.remove(FIELD_LISTTAXONOMY); } else { uiUploadForm.removeChildById(indexRemove + FIELD_NAME); uiUploadForm.removeChildById(indexRemove + FIELD_UPLOAD); uiUploadForm.removeChildById(indexRemove + FIELD_LISTTAXONOMY); if (uiUploadForm.mapTaxonomies.containsKey(indexRemove + FIELD_LISTTAXONOMY)) uiUploadForm.mapTaxonomies.remove(indexRemove + FIELD_LISTTAXONOMY); } uiUploadForm.setNumberUploadFile(index - 1); uiUploadForm.setRendered(true); event.getRequestContext().addUIComponentToUpdateByAjax(uiUploadForm.getParent()); } } }
46,151
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIUploadManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/upload/UIUploadManager.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.explorer.upload; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.webui.core.UIPopupComponent; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * May 24, 2007 2:12:48 PM */ @ComponentConfig( lifecycle = UIContainerLifecycle.class ) public class UIUploadManager extends UIContainer implements UIPopupComponent { private static final Log LOG = ExoLogger.getLogger(UIUploadManager.class.getName()); final static public String EXTARNAL_METADATA_POPUP = "AddMetadataPopup" ; final static public String SAMENAME_POPUP = "SameNamePopup" ; public UIUploadManager() throws Exception { addChild(UIUploadForm.class, null, null); addChild(UIUploadContainer.class, null, null).setRendered(false); } public UIPopupWindow initPopupTaxonomy(String id) throws Exception { UIPopupWindow uiPopup = getChildById(id); if (uiPopup == null) { uiPopup = addChild(UIPopupWindow.class, null, id); } uiPopup.setWindowSize(800, 350); uiPopup.setShow(false); uiPopup.setResizable(true); return uiPopup; } public UIPopupWindow initPopupWhenHaveSameName() throws Exception { UIPopupWindow uiPopup = getChildById(SAMENAME_POPUP); if (uiPopup == null) { uiPopup = addChild(UIPopupWindow.class, null, SAMENAME_POPUP); } uiPopup.setWindowSize(500, 180); uiPopup.setShow(false); uiPopup.setResizable(true); return uiPopup; } public void activate() { try { UIUploadForm uiUploadForm = getChild(UIUploadForm.class); uiUploadForm.initFieldInput(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error!", e.getMessage()); } } } public void deActivate() {} public void initMetadataPopup() throws Exception { removeChildById(EXTARNAL_METADATA_POPUP) ; UIPopupWindow uiPopup = addChild(UIPopupWindow.class, null, EXTARNAL_METADATA_POPUP) ; uiPopup.setShowMask(true); uiPopup.setWindowSize(400, 400); UIExternalMetadataForm uiExternalMetadataForm = createUIComponent(UIExternalMetadataForm.class, null, null) ; uiPopup.setUIComponent(uiExternalMetadataForm) ; uiExternalMetadataForm.renderExternalList() ; uiPopup.setRendered(true); uiPopup.setShow(true) ; uiPopup.setResizable(true) ; } }
3,399
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UINodeProperty.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/versions/UINodeProperty.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.explorer.versions; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.PropertyIterator; import javax.jcr.PropertyType; import javax.jcr.Session; import javax.jcr.Value; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeManager; import javax.jcr.nodetype.PropertyDefinition; import org.exoplatform.container.PortalContainer; import org.exoplatform.ecm.webui.component.explorer.UIDocumentWorkspace; 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.lifecycle.UIFormLifecycle; import org.exoplatform.webui.form.UIForm; /** * Created by The eXo Platform SARL * Author : Le Bien Thuy * lebienthuy@gmail.com * Oct 20, 2006 */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "app:/groovy/webui/component/explorer/versions/UINodeProperty.gtmpl" ) public class UINodeProperty extends UIForm{ public UINodeProperty() {} public List<Property> getVersionedNodeProperties() throws Exception{ RepositoryService repositoryService = (RepositoryService)PortalContainer.getComponent(RepositoryService.class) ; List<Property> list = new ArrayList<Property>() ; NodeTypeManager nodeTypeManager = repositoryService.getCurrentRepository().getNodeTypeManager(); NodeType jcrFrozenNode = nodeTypeManager.getNodeType("nt:frozenNode") ; NodeType ntVersion = nodeTypeManager.getNodeType("nt:version") ; NodeType ntVersionHistory = nodeTypeManager.getNodeType("nt:versionHistory") ; NodeType mixVersionable = nodeTypeManager.getNodeType("mix:versionable") ; UIVersionInfo uiVersionInfo = getAncestorOfType(UIDocumentWorkspace.class).getChild(UIVersionInfo.class) ; Node frozenNode = uiVersionInfo.getCurrentVersionNode().getNode("jcr:frozenNode") ; for(PropertyIterator propertyIter = frozenNode.getProperties(); propertyIter.hasNext() ;) { Property property = propertyIter.nextProperty() ; boolean isDefinition = false ; for(PropertyDefinition propDef : jcrFrozenNode.getPropertyDefinitions()) { if(propDef.getName().equals(property.getName())) isDefinition = true ; } for(PropertyDefinition propDef : ntVersion.getPropertyDefinitions()) { if(propDef.getName().equals(property.getName())) isDefinition = true ; } for(PropertyDefinition propDef : ntVersionHistory.getPropertyDefinitions()) { if(propDef.getName().equals(property.getName())) isDefinition = true ; } for(PropertyDefinition propDef : mixVersionable.getPropertyDefinitions()) { if(propDef.getName().equals(property.getName())) isDefinition = true ; } if(!isDefinition) list.add(property) ; } return list ; } public String getPropertyValue(Property property) throws Exception{ switch(property.getType()) { case PropertyType.BINARY: return Integer.toString(PropertyType.BINARY) ; case PropertyType.BOOLEAN :return Boolean.toString(property.getValue().getBoolean()) ; case PropertyType.DATE : return property.getValue().getDate().getTime().toString() ; case PropertyType.DOUBLE : return Double.toString(property.getValue().getDouble()) ; case PropertyType.LONG : return Long.toString(property.getValue().getLong()) ; case PropertyType.NAME : return property.getValue().getString() ; case PropertyType.STRING : return property.getValue().getString() ; case PropertyType.REFERENCE : { if(property.getName().equals("exo:category") || property.getName().equals("exo:relation")) { Session session = getSystemSession() ; Node referenceNode = session.getNodeByUUID(property.getValue().getString()) ; String path = referenceNode.getPath(); return path ; } return property.getValue().getString() ; } } return null ; } public List<String> getPropertyMultiValues(Property property) throws Exception { String propName = property.getName() ; if(propName.equals("exo:category")) return getCategoriesValues(property) ; else if(propName.equals("exo:relation")) return getRelationValues(property) ; List<String> values = new ArrayList<String>() ; for(Value value:property.getValues()) { values.add(value.getString()) ; } return values ; } public boolean isMultiValue(Property prop) throws Exception{ PropertyDefinition propDef = prop.getDefinition() ; return propDef.isMultiple() ; } private List<String> getReferenceValues(Property property) throws Exception { Session session = getSystemSession() ; List<String> pathList = new ArrayList<String>() ; Value[] values = property.getValues() ; for(Value value:values) { Node referenceNode = session.getNodeByUUID(value.getString()) ; pathList.add(referenceNode.getPath()) ; } return pathList ; } private List<String> getRelationValues(Property relationProp) throws Exception { return getReferenceValues(relationProp) ; } private List<String> getCategoriesValues(Property categoryProp) throws Exception { return getReferenceValues(categoryProp) ; } private Session getSystemSession() throws Exception { ManageableRepository manageableRepository = getApplicationComponent(RepositoryService.class).getCurrentRepository(); String systemWorksapce = manageableRepository.getConfiguration().getDefaultWorkspaceName(); Session session = WCMCoreUtils.getSystemSessionProvider().getSession(systemWorksapce, manageableRepository) ; return session ; } }
6,653
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDiff.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/versions/UIDiff.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.explorer.versions; import java.text.DateFormat; import java.util.Calendar; import java.util.Locale; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.Property; import javax.jcr.RepositoryException; import javax.jcr.version.Version; import javax.jcr.version.VersionHistory; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.diff.DiffResult; import org.exoplatform.commons.diff.DiffService; import org.exoplatform.ecm.webui.component.explorer.UIDocumentWorkspace; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.document.DocumentReader; import org.exoplatform.services.document.DocumentReaderService; import org.exoplatform.services.document.HandlerNotFoundException; 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.UIComponent; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SARL Author : Pham Tuan tuan.pham@exoplatform.com * May 3, 2007 */ @ComponentConfig(template = "app:/groovy/webui/component/explorer/versions/UIDiff.gtmpl", events = { @EventConfig(listeners = UIDiff.CompareActionListener.class), @EventConfig(listeners = UIDiff.CloseCompareActionListener.class) }) public class UIDiff extends UIComponent { private static final String EXO_LAST_MODIFIED_DATE = "exo:lastModifiedDate"; private static final Log LOG = ExoLogger.getLogger(UIDiff.class.getName()); public static final String FROM_PARAM = "from"; public static final String TO_PARAM = "to"; private String baseVersionName_; private String baseVersionDate_; private String baseVersionAuthor_; private String baseVersionLabel_; private String versionName_; private String versionDate_; private String versionAuthor_; private String versionLabel_; private String previousText_ = null; private String currentText_ = null; private boolean versionCompareable_ = true; private String diffResultHTML_ = null; private boolean isImage_ = false; private String baseImage_ = null; private String currentImage_ = null; public void setVersions(Node baseVersion, Node version) throws Exception { UIDocumentWorkspace uiDocumentWorkspace = getAncestorOfType(UIDocumentWorkspace.class); UIVersionInfo uiVersionInfo = uiDocumentWorkspace.getChild(UIVersionInfo.class); versionCompareable_ = baseVersion != null && version != null && !baseVersion.getUUID().equals(version.getUUID()); if (!versionCompareable_) { throw new IllegalStateException("Can't compare both versions"); } else { Node versionRootVersion = null; if (version instanceof Version) { versionRootVersion = ((Version) version).getContainingHistory().getRootVersion(); } else { versionRootVersion = version.getVersionHistory().getRootVersion(); } Node baseVersionRootVersion = null; if (baseVersion instanceof Version) { baseVersionRootVersion = ((Version) baseVersion).getContainingHistory().getRootVersion(); } else { baseVersionRootVersion = baseVersion.getVersionHistory().getRootVersion(); } versionCompareable_ = baseVersionRootVersion.getUUID().endsWith(versionRootVersion.getUUID()); if (!versionCompareable_) { throw new IllegalStateException("Versions to compare are the same"); } } Node currentNode = uiVersionInfo.getCurrentNode(); VersionHistory versionHistory = currentNode.getVersionHistory(); Version rootVersion = versionHistory.getRootVersion(); // Make baseVersion parameter always the oldest version if (currentNode.getUUID().equals(baseVersion.getUUID())) { // switch version and baseVersion to make sure that baseVersion is the // oldest Node tmpNode = baseVersion; baseVersion = version; version = tmpNode; } else if (currentNode.getUUID().equals(version.getUUID())) { // It's ok, the version' indice > baseVersion indice } else if (baseVersion instanceof Version && version instanceof Version) { // compare versions by indice int baseVersionIndice = Integer.parseInt(baseVersion.getName()); int versionNumIndice = Integer.parseInt(version.getName()); if (baseVersionIndice == versionNumIndice) { throw new IllegalStateException("Can't compare the same version"); } else if (baseVersionIndice > versionNumIndice) { Node tmpNode = baseVersion; baseVersion = version; version = tmpNode; } } // Base version is of type Version all the time baseVersionName_ = ((Version) baseVersion).getName(); // Current version can be of type Version or Node (draft node) versionName_ = version instanceof Version ? version.getName() : uiVersionInfo.getRootVersionNum(); // Base version is of type Version all the time Calendar modifiedDate = getModifiedDate(baseVersion); baseVersionDate_ = formatDate(modifiedDate); // Current version can be of type Version or Node (draft node) modifiedDate = getModifiedDate(version); versionDate_ = formatDate(modifiedDate); baseVersionAuthor_ = getLastModifier(baseVersion); versionAuthor_ = getLastModifier(version); // Base version is of type Version all the time String[] baseVersionLabels = versionHistory.getVersionLabels((Version) baseVersion); baseVersionLabel_ = baseVersionLabels == null || baseVersionLabels.length == 0 ? null : baseVersionLabels[0]; // Current version can be of type Version or Node (draft node) if (version instanceof Version) { String[] versionLabels = versionHistory.getVersionLabels((Version) version); versionLabel_ = versionLabels == null || versionLabels.length == 0 ? null : versionLabels[0]; } else { String[] versionLabels = versionHistory.getVersionLabels(rootVersion); versionLabel_ = versionLabels == null || versionLabels.length == 0 ? null : versionLabels[0]; } isImage_ = isOriginalNodeImage(version) && isOriginalNodeImage(baseVersion); previousText_ = null; currentText_ = null; diffResultHTML_ = null; currentImage_ = null; baseImage_ = null; isImage_ = isOriginalNodeImage(version) && isOriginalNodeImage(baseVersion); if (isImage_) { String wsName = currentNode.getSession().getWorkspace().getName(); String originalNodePath = currentNode.getPath(); String basePath = "/" + WCMCoreUtils.getPortalName() + "/" + WCMCoreUtils.getRestContextName() + "/jcr/" + WCMCoreUtils.getRepository().getConfiguration().getName() + "/" + wsName + originalNodePath; long timeInMS = Calendar.getInstance().getTimeInMillis(); currentImage_ = basePath + (currentNode.getUUID().equals(version.getUUID()) ? "?" + timeInMS : ("?version=" + version.getName() + "&" + timeInMS)); baseImage_ = basePath + (currentNode.getUUID().equals(baseVersion.getUUID()) ? "?" + timeInMS : "?version=" + baseVersion.getName() + "&" + timeInMS); } else { try { previousText_ = getText(baseVersion); currentText_ = getText(version); } catch (HandlerNotFoundException e) { versionCompareable_ = false; } if (versionCompareable_) { if (StringUtils.isBlank(previousText_) && StringUtils.isBlank(currentText_)) { versionCompareable_ = false; } else if ((previousText_ != null) && (currentText_ != null)) { DiffService diffService = WCMCoreUtils.getService(DiffService.class); DiffResult diffResult = diffService.getDifferencesAsHTML(previousText_, currentText_, true); diffResultHTML_ = diffResult.getDiffHTML(); } } } } public String getBaseVersionNum() throws Exception { return baseVersionName_; } public String getCurrentVersionNum() throws Exception { return versionName_; } public String getBaseVersionDate() throws Exception { return baseVersionDate_; } public String getCurrentVersionDate() throws Exception { return versionDate_; } public String getBaseVersionAuthor() { return baseVersionAuthor_; } public String getCurrentVersionAuthor() { return versionAuthor_; } public String getBaseVersionLabel() { return baseVersionLabel_; } public String getCurrentVersionLabel() { return versionLabel_; } public String getBaseImage() throws Exception { return baseImage_; } public String getCurrentImage() throws Exception { return currentImage_; } public boolean isCompareable() { return versionCompareable_; } public String getDifferences() throws Exception { return diffResultHTML_; } public boolean isImage() { return isImage_; } private Calendar getModifiedDate(Node node) throws RepositoryException { Property property = getProperty(node, EXO_LAST_MODIFIED_DATE); return property == null ? null : property.getDate(); } private String getLastModifier(Node node) throws RepositoryException { Property property = getProperty(node, Utils.EXO_LASTMODIFIER); return property == null ? null : property.getString(); } private boolean isOriginalNodeImage(Node node) throws Exception { Property mimeProperty = getProperty(node, Utils.JCR_MIMETYPE); String mimeType = mimeProperty == null ? null : mimeProperty.getString(); return StringUtils.isNotBlank(mimeType) && mimeType.startsWith("image"); } private String getText(Node node) throws Exception { Property mimeProperty = getProperty(node, Utils.JCR_MIMETYPE); Property dataProperty = getProperty(node, Utils.JCR_DATA); if (mimeProperty != null && dataProperty != null) { String mimeType = mimeProperty.getString(); if (mimeType.startsWith("text")) { return dataProperty.getString(); } DocumentReaderService readerService = getApplicationComponent(DocumentReaderService.class); DocumentReader documentReader = readerService.getDocumentReader(mimeType); if (documentReader != null) { try { return documentReader.getContentAsText(dataProperty.getStream()); } catch (Exception e) { LOG.warn("An error occured while getting text from file " + node.getPath() + " with mimeType " + mimeType + " with document reader = " + documentReader + ". File comparaison will be disabled", e); } } } throw new HandlerNotFoundException(); } private Property getProperty(Node node, String propertyName) throws RepositoryException, PathNotFoundException { Property property = null; if (node instanceof Version) { if (node.hasNode(Utils.JCR_FROZEN)) { node = node.getNode(Utils.JCR_FROZEN); } else { return null; } } if (node.hasProperty(propertyName)) { property = node.getProperty(propertyName); } else if (node.hasNode(Utils.JCR_CONTENT)) { Node content = node.getNode(Utils.JCR_CONTENT); if (content.hasProperty(propertyName)) { property = content.getProperty(propertyName); } } return property; } private String formatDate(Calendar calendar) { Locale currentLocale = Util.getPortalRequestContext().getLocale(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, currentLocale); return dateFormat.format(calendar.getTime()); } static public class CloseCompareActionListener extends EventListener<UIDiff> { public void execute(Event<UIDiff> event) throws Exception { UIDiff uiDiff = event.getSource(); if (uiDiff.isRendered()) { uiDiff.setRendered(false); } UIDocumentWorkspace uiDocumentWorkspace = uiDiff.getAncestorOfType(UIDocumentWorkspace.class); UIVersionInfo uiVersionInfo = uiDocumentWorkspace.getChild(UIVersionInfo.class); uiVersionInfo.setRendered(true); event.getRequestContext().addUIComponentToUpdateByAjax(uiDocumentWorkspace); } } static public class CompareActionListener extends EventListener<UIDiff> { public void execute(Event<UIDiff> event) throws Exception { UIDiff uiDiff = (UIDiff) event.getSource(); String fromVersionName = event.getRequestContext().getRequestParameter(FROM_PARAM); String toVersionName = event.getRequestContext().getRequestParameter(TO_PARAM); UIDocumentWorkspace uiDocumentWorkspace = uiDiff.getAncestorOfType(UIDocumentWorkspace.class); UIVersionInfo uiVersionInfo = uiDocumentWorkspace.getChild(UIVersionInfo.class); uiDiff.setVersions(uiVersionInfo.getVersion(fromVersionName), uiVersionInfo.getVersion(toVersionName)); } } }
14,335
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIViewVersion.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/versions/UIViewVersion.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.explorer.versions; import java.io.InputStream; 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.jcr.Value; import org.exoplatform.container.xml.PortalContainerInfo; import org.exoplatform.download.DownloadService; import org.exoplatform.download.InputStreamDownloadResource; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.control.UIActionBar; import org.exoplatform.ecm.webui.presentation.AbstractActionComponent; 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.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.comments.CommentsService; import org.exoplatform.services.cms.i18n.MultiLanguageService; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.web.application.Parameter; import org.exoplatform.web.application.RequireJS; 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.UIPopupWindow; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SARL * Author : lxchiati * lebienthuy@gmail.com * Oct 19, 2006 * 10:07:15 AM */ @ComponentConfig( type = UIViewVersion.class, template = "system:/groovy/webui/core/UITabPane.gtmpl", events = { @EventConfig(listeners = UIViewVersion.ChangeLanguageActionListener.class), @EventConfig(listeners = UIViewVersion.ChangeNodeActionListener.class), @EventConfig(listeners = UIViewVersion.DownloadActionListener.class) } ) public class UIViewVersion extends UIBaseNodePresentation { private NodeLocation node_ ; protected NodeLocation originalNode_ ; private String language_ ; private static final Log LOG = ExoLogger.getLogger(UIViewVersion.class.getName()); final private static String COMMENT_COMPONENT = "Comment"; public UIViewVersion() throws Exception { addChild(UINodeInfo.class, null, null) ; addChild(UINodeProperty.class, null, null).setRendered(false) ; } public String getTemplate() { TemplateService templateService = getApplicationComponent(TemplateService.class); String userName = Util.getPortalRequestContext().getRemoteUser() ; try { Node node = getAncestorOfType(UIJCRExplorer.class).getCurrentNode() ; originalNode_ = NodeLocation.getNodeLocationByNode(node); String nodeType = node.getPrimaryNodeType().getName(); if(isNodeTypeSupported(node)) return templateService.getTemplatePathByUser(false, nodeType, userName) ; } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } return null ; } public UIComponent getCommentComponent() { UIJCRExplorer uiExplorer = getAncestorOfType(UIJCRExplorer.class); UIActionBar uiActionBar = uiExplorer.findFirstComponentOfType(UIActionBar.class); UIComponent uicomponent = uiActionBar.getUIAction(COMMENT_COMPONENT); return (uicomponent != null ? uicomponent : this); } public UIComponent getRemoveAttach() throws Exception { removeChild(RemoveAttachmentComponent.class); UIComponent uicomponent = addChild(RemoveAttachmentComponent.class, null, "UIViewVersionRemoveAttach"); ((AbstractActionComponent) uicomponent).setLstComponentupdate(Arrays.asList(new Class[] {UIPopupWindow.class})); return uicomponent; } public UIComponent getRemoveComment() throws Exception { removeChild(RemoveCommentComponent.class); UIComponent uicomponent = addChild(RemoveCommentComponent.class, null, "UIViewVersionRemoveComment"); ((AbstractActionComponent) uicomponent).setLstComponentupdate(Arrays.asList(new Class[] {UIPopupWindow.class})); return uicomponent; } public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context, String template) { return getAncestorOfType(UIJCRExplorer.class).getJCRTemplateResourceResolver() ; } public boolean isNodeTypeSupported(Node node) { try { TemplateService templateService = getApplicationComponent(TemplateService.class) ; String nodeTypeName = node.getPrimaryNodeType().getName(); return templateService.isManagedNodeType(nodeTypeName); } catch (Exception e) { return false; } } public Node getNode() throws RepositoryException { return NodeLocation.getNodeByLocation(node_); } public Node getOriginalNode() throws Exception { return NodeLocation.getNodeByLocation(originalNode_); } public void setNode(Node node) { node_ = NodeLocation.getNodeLocationByNode(node); } public Node getNodeByUUID(String uuid) { ManageableRepository manageRepo = WCMCoreUtils.getRepository(); String[] workspaces = manageRepo.getWorkspaceNames() ; for(String ws : workspaces) { try{ return WCMCoreUtils.getSystemSessionProvider().getSession(ws, manageRepo).getNodeByUUID(uuid) ; } catch(Exception e) { continue; } } return null; } public List<Node> getRelations() throws Exception { List<Node> relations = new ArrayList<Node>() ; Node node = getNode(); if (node.hasProperty(Utils.EXO_RELATION)) { Value[] vals = node.getProperty(Utils.EXO_RELATION).getValues(); for (int i = 0; i < vals.length; i++) { String uuid = vals[i].getString(); Node nodeToAdd = getNodeByUUID(uuid); relations.add(nodeToAdd); } } return relations; } public List<Node> getAttachments() throws Exception { List<Node> attachments = new ArrayList<Node>() ; Node node = getNode(); NodeIterator childrenIterator = node.getNodes(); TemplateService templateService = getApplicationComponent(TemplateService.class) ; int attachData = 0 ; while(childrenIterator.hasNext()) { Node childNode = childrenIterator.nextNode(); String nodeType = childNode.getPrimaryNodeType().getName(); List<String> listCanCreateNodeType = Utils.getListAllowedFileType(node, templateService) ; if(listCanCreateNodeType.contains(nodeType)) { // Case of childNode has jcr:data property if (childNode.hasProperty(Utils.JCR_DATA)) { attachData = childNode.getProperty(Utils.JCR_DATA).getStream().available(); // Case of jcr:data has content if (attachData > 0) attachments.add(childNode); } else { attachments.add(childNode); } } } return attachments; } public String getViewableLink(Node attNode, Parameter[] params) throws Exception { return this.event("ChangeNode", Utils.formatNodeName(attNode.getPath()), params); } public String getIcons(Node node, String type) throws Exception { return Utils.getNodeTypeIcon(node, type) ; } public boolean hasPropertyContent(Node node, String property){ try { String value = node.getProperty(property).getString() ; if(value.length() > 0) return true ; } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } return false ; } public boolean isRssLink() { return false ; } public String getRssLink() { return null ; } public void update() throws Exception { getChild(UINodeInfo.class).update(); } public List<Node> getComments() throws Exception { return getApplicationComponent(CommentsService.class).getComments(getNode(), getLanguage()) ; } @SuppressWarnings("unchecked") 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; } public String getDownloadLink(Node node) throws Exception { DownloadService dservice = getApplicationComponent(DownloadService.class) ; InputStreamDownloadResource dresource ; if(!node.getPrimaryNodeType().getName().equals(Utils.NT_FILE)) { node = NodeLocation.getNodeByLocation(originalNode_); } Node jcrContentNode = node.getNode(Utils.JCR_CONTENT) ; InputStream input = jcrContentNode.getProperty(Utils.JCR_DATA).getStream() ; dresource = new InputStreamDownloadResource(input, "image") ; dresource.setDownloadName(node.getName()) ; return dservice.getDownloadLink(dservice.addDownloadResource(dresource)) ; } 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)) ; } public void setLanguage(String language) { language_ = language ; } public String getLanguage() { return language_ ; } public String getNodeType() throws Exception { return getNode().getPrimaryNodeType().getName() ; } public String getPortalName() { PortalContainerInfo containerInfo = WCMCoreUtils.getService(PortalContainerInfo.class); return containerInfo.getContainerName(); } public List<String> getSupportedLocalise() throws Exception { MultiLanguageService multiLanguageService = getApplicationComponent(MultiLanguageService.class) ; return multiLanguageService.getSupportedLanguages(getNode()) ; } public String getTemplatePath() throws Exception { return null; } public String getViewTemplate(String nodeTypeName, String templateName) throws Exception { TemplateService tempServ = getApplicationComponent(TemplateService.class) ; return tempServ.getTemplatePath(false, nodeTypeName, templateName) ; } public String getTemplateSkin(String nodeTypeName, String skinName) throws Exception { TemplateService tempServ = getApplicationComponent(TemplateService.class) ; return tempServ.getSkinPath(nodeTypeName, skinName, getLanguage()) ; } 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 ; } public String getWorkspaceName() throws Exception { return getNode().getSession().getWorkspace().getName(); } public boolean isNodeTypeSupported() { try { TemplateService templateService = getApplicationComponent(TemplateService.class); return templateService.isManagedNodeType(getNodeType()); } catch (Exception e) { return false; } } public String getRepository() throws Exception{ return getAncestorOfType(UIJCRExplorer.class).getRepositoryName() ; } public String encodeHTML(String text) throws Exception { return Utils.encodeHTML(text) ; } static public class ChangeLanguageActionListener extends EventListener<UIViewVersion>{ public void execute(Event<UIViewVersion> event) throws Exception { UIViewVersion uiViewVersion = event.getSource() ; UIApplication uiApp = uiViewVersion.getAncestorOfType(UIApplication.class) ; uiApp.addMessage(new ApplicationMessage("UIViewVersion.msg.not-supported", null)) ; return ; } } static public class DownloadActionListener extends EventListener<UIViewVersion> { public void execute(Event<UIViewVersion> event) throws Exception { UIViewVersion uiComp = event.getSource() ; String downloadLink = uiComp.getDownloadLink(org.exoplatform.wcm.webui.Utils.getFileLangNode(uiComp.getNode())); RequireJS requireJS = event.getRequestContext().getJavascriptManager().getRequireJS(); requireJS.require("SHARED/ecm-utils", "ecmutil").addScripts("ecmutil.ECMUtils.ajaxRedirect('" + downloadLink + "');"); } } static public class ChangeNodeActionListener extends EventListener<UIViewVersion> { public void execute(Event<UIViewVersion> event) throws Exception { UIViewVersion uiViewVersion = event.getSource() ; UIApplication uiApp = uiViewVersion.getAncestorOfType(UIApplication.class) ; uiApp.addMessage(new ApplicationMessage("UIViewVersion.msg.not-supported", null)) ; return ; } } public UIComponent getUIComponent(String mimeType) throws Exception { return Utils.getUIComponent(mimeType, this); } public boolean isEnableComment() { return false; } public boolean isEnableVote() { return false; } public void setEnableComment(boolean value) { } public void setEnableVote(boolean value) { } 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); } }
15,887
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UINodeInfo.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/versions/UINodeInfo.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.explorer.versions; import java.util.Calendar; import org.exoplatform.ecm.webui.component.explorer.UIDocumentWorkspace; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.form.UIForm; /** * Created by The eXo Platform SARL * Author : Tran The Trong * trongtt@gmail.com * Oct 20, 2006 */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "app:/groovy/webui/component/explorer/versions/UINodeInfo.gtmpl" ) public class UINodeInfo extends UIForm { private NodeLocation node_ ; private String versionCreatedDate_ ; public UINodeInfo() { } public void update() throws Exception { UIVersionInfo uiVersionInfo = getAncestorOfType(UIDocumentWorkspace.class).getChild(UIVersionInfo.class); node_ = NodeLocation.getNodeLocationByNode(uiVersionInfo.getCurrentNode()); Calendar createdTime = uiVersionInfo.getCurrentVersionNode().getCreatedTime(); if (createdTime != null) { versionCreatedDate_ = createdTime.getTime().toString(); } } public String getNodeType() throws Exception { return NodeLocation.getNodeByLocation(node_).getPrimaryNodeType().getName(); } public String getNodeName() throws Exception { return NodeLocation.getNodeByLocation(node_).getName(); } public String getVersionName() throws Exception { return getAncestorOfType(UIDocumentWorkspace.class).getChild(UIVersionInfo.class) .getCurrentVersionNode().getName(); } public String getVersionLabels() throws Exception{ UIVersionInfo uiVersionInfo = getAncestorOfType(UIDocumentWorkspace.class).getChild(UIVersionInfo.class) ; String[] labels = uiVersionInfo.getVersionLabels(uiVersionInfo.getCurrentVersionNode()); StringBuilder label = new StringBuilder() ; if(labels.length == 0 ) return "N/A" ; for(String temp : labels) { label.append(temp).append(" ") ; } return label.toString() ; } public String getVersionCreatedDate() throws Exception { return versionCreatedDate_; } }
2,979
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIVersionInfo.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/versions/UIVersionInfo.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.explorer.versions; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import javax.jcr.Node; import javax.jcr.ReferentialIntegrityException; import javax.jcr.RepositoryException; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import javax.jcr.version.VersionHistory; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.utils.LazyPageList; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.commons.utils.ListAccessImpl; import org.exoplatform.ecm.jcr.model.VersionNode; import org.exoplatform.ecm.webui.component.explorer.UIDocumentWorkspace; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cache.CacheService; import org.exoplatform.services.cache.ExoCache; import org.exoplatform.services.cms.documents.AutoVersionService; import org.exoplatform.services.cms.documents.DocumentService; import org.exoplatform.services.cms.documents.VersionHistoryUtils; import org.exoplatform.services.cms.jcrext.activity.ActivityCommonService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.impl.storage.JCRInvalidItemStateException; import org.exoplatform.services.listener.ListenerService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.pdfviewer.ObjectKey; import org.exoplatform.services.pdfviewer.PDFViewerService; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.MembershipEntry; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.connector.viewer.PDFViewerRESTService; 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.UIApplication; import org.exoplatform.webui.core.UIComponent; 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 SARL * Implement: lxchiati * lebienthuy@gmail.com * July 3, 2006 * 10:07:15 AM */ @ComponentConfig( template = "app:/groovy/webui/component/explorer/versions/UIVersionInfo.gtmpl", events = { @EventConfig(listeners = UIVersionInfo.SelectActionListener.class), @EventConfig(listeners = UIVersionInfo.RestoreVersionActionListener.class, confirm = "UIVersionInfo.msg.confirm-restore"), @EventConfig(listeners = UIVersionInfo.CompareVersionActionListener.class, csrfCheck = false), @EventConfig(listeners = UIVersionInfo.DeleteVersionActionListener.class, confirm = "UIVersionInfo.msg.confirm-delete"), @EventConfig(listeners = UIVersionInfo.CloseActionListener.class), @EventConfig(listeners = UIVersionInfo.AddSummaryActionListener.class) } ) public class UIVersionInfo extends UIContainer { private static final Log LOG = ExoLogger.getLogger(UIVersionInfo.class.getName()); protected VersionNode rootVersion_ ; protected String rootOwner_; protected String rootVersionNum_; protected VersionNode curentVersion_; protected NodeLocation node_ ; private UIPageIterator uiPageIterator_ ; private List<VersionNode> listVersion = new ArrayList<VersionNode>() ; private static final String CACHE_NAME = "ecms.PDFViewerRestService"; public UIVersionInfo() throws Exception { uiPageIterator_ = addChild(UIPageIterator.class, null, "VersionInfoIterator").setRendered(false); } public UIPageIterator getUIPageIterator() { return uiPageIterator_; } @SuppressWarnings("rawtypes") public List getListRecords() throws Exception { return uiPageIterator_.getCurrentPageData(); } public void updateGrid() throws Exception { listVersion.clear(); Node currentNode = getCurrentNode(); rootVersion_ = new VersionNode(currentNode, currentNode.getSession()); curentVersion_ = rootVersion_; listVersion = getNodeVersions(getRootVersionNode().getChildren()); VersionNode currentNodeTuple = new VersionNode(currentNode, currentNode.getSession()); if(!listVersion.isEmpty()) { int lastVersionNum = Integer.parseInt(listVersion.get(0).getName()); setRootVersionNum(String.valueOf(++lastVersionNum)); } else { setRootVersionNum("1"); } listVersion.add(0, currentNodeTuple); ListAccess<VersionNode> recordList = new ListAccessImpl<VersionNode>(VersionNode.class, listVersion); LazyPageList<VersionNode> dataPageList = new LazyPageList<VersionNode>(recordList, 10); uiPageIterator_.setPageList(dataPageList); } public String getTitle(Node node) throws Exception { return org.exoplatform.ecm.webui.utils.Utils.getTitle(node); } private boolean isRestoredVersions(List<VersionNode> list) { try { for (int i = 0; i < list.size(); i++) { if (getVersionLabels(list.get(i)).length > 0) { if (isRestoredLabel(getVersionLabels(list.get(i))[0])) return true; } } } catch (Exception e) { return false; } return false; } private boolean isRestoredLabel(String label) { try { String from = label.substring(label.indexOf("_") - 1).split("_")[0]; String to = label.substring(label.indexOf("_") - 1).split("_")[1]; Integer.parseInt(from); Integer.parseInt(to); return true; } catch (Exception e) { return false; } } public String[] getVersionLabels(VersionNode version) throws Exception { VersionHistory vH = NodeLocation.getNodeByLocation(node_).getVersionHistory(); String[] labels; if (StringUtils.isNotBlank(version.getName()) && !getRootVersionNum().equals(version.getName())) { Version versionNode = vH.getVersion(version.getName()); labels = vH.getVersionLabels(versionNode); } else { labels= vH.getVersionLabels(vH.getRootVersion()); } return labels; } public boolean isBaseVersion(VersionNode versionNode) throws Exception { if (!isRestoredVersions(listVersion)) { return isRootVersion(versionNode); } else { return versionNode.getPath().equals(getCurrentNode().getPath()); } } public boolean hasPermission(Node node) throws Exception { if (getCurrentNode().getPath().startsWith("/Groups/spaces")) { MembershipEntry mem = new MembershipEntry("/spaces/" + getCurrentNode().getPath().split("/")[3], "manager"); return (ConversationState.getCurrent().getIdentity().getMemberships().contains(mem) || ConversationState.getCurrent().getIdentity().getUserId().equals(node.getProperty("exo:lastModifier").getString())); } else { return true; } } public boolean isRootVersion(VersionNode versionNode) throws Exception { return (versionNode.getUUID().equals(getCurrentNode().getUUID())); } public VersionNode getRootVersionNode() throws Exception { return rootVersion_ ; } public String getRootOwner() throws Exception { return rootOwner_ ; } public void setRootOwner(String user) { this.rootOwner_ = user; } private List<VersionNode> getNodeVersions(List<VersionNode> children) throws Exception { List<VersionNode> child = new ArrayList<VersionNode>() ; for(int i = 0; i < children.size(); i ++){ listVersion.add(children.get(i)); child = children.get(i).getChildren() ; if(!child.isEmpty()) getNodeVersions(child) ; } listVersion.sort(new Comparator<VersionNode>() { @Override public int compare(VersionNode v1, VersionNode v2) { try { if (Integer.parseInt(v1.getName()) < Integer.parseInt(v2.getName())) return 1; else return 0; }catch (Exception e) { return 0; } } }); return listVersion; } public void activate() { try { UIJCRExplorer uiExplorer = getAncestorOfType(UIJCRExplorer.class); if (node_ == null) { node_ = NodeLocation.getNodeLocationByNode(uiExplorer.getCurrentNode()); } updateGrid(); } catch (Exception e) { LOG.error("Unexpected error!", e); } } public VersionNode getCurrentVersionNode() { return curentVersion_ ;} public Node getVersion(String versionName) throws RepositoryException { Node currentNode = getCurrentNode(); if ((StringUtils.isBlank(versionName) && StringUtils.isBlank(getCurrentVersionNode().getName())) || (StringUtils.isNotBlank(versionName) && StringUtils.isNotBlank(getCurrentVersionNode().getName()) && getCurrentVersionNode().getName().equals(versionName))) { return currentNode; } for (VersionNode versionNode : listVersion) { if(versionNode.getName().equals(versionName)) { return currentNode.getVersionHistory().getVersion(versionName); } } return null; } public Node getCurrentNode() { return NodeLocation.getNodeByLocation(node_); } public void setCurrentNode(Node node) { node_ = NodeLocation.getNodeLocationByNode(node); } public List<VersionNode> getListVersion() { return listVersion; } public void setListVersion(List<VersionNode> listVersion) { this.listVersion = listVersion; } public String getLinkInDocumentsApp(String nodePath) throws Exception { DocumentService documentService = WCMCoreUtils.getService(DocumentService.class); return documentService.getLinkInDocumentsApp(nodePath); } public void setRootVersionNum(String rootVersionNum) { this.rootVersionNum_ = rootVersionNum; } public String getRootVersionNum() { return rootVersionNum_; } private boolean isWebContent() throws Exception { Node currentNode = getCurrentNode(); if (currentNode != null) { return currentNode.isNodeType(Utils.EXO_WEBCONTENT); } return false; } static public class RestoreVersionActionListener extends EventListener<UIVersionInfo> { public void execute(Event<UIVersionInfo> event) throws Exception { UIVersionInfo uiVersionInfo = event.getSource(); UIJCRExplorer uiExplorer = uiVersionInfo.getAncestorOfType(UIJCRExplorer.class) ; PDFViewerService pdfViewerService = WCMCoreUtils.getService(PDFViewerService.class); CacheService caService = WCMCoreUtils.getService(CacheService.class); ExoCache<Serializable, Object> pdfCache; if(pdfViewerService != null){ pdfCache = pdfViewerService.getCache(); }else{ pdfCache = caService.getCacheInstance(CACHE_NAME); } for(UIComponent uiChild : uiVersionInfo.getChildren()) { uiChild.setRendered(false) ; } String objectId = event.getRequestContext().getRequestParameter(OBJECTID) ; VersionNode currentVersionNode = uiVersionInfo.rootVersion_.findVersionNode(objectId); String fromVersionName = currentVersionNode.getName() ; UIApplication uiApp = uiVersionInfo.getAncestorOfType(UIApplication.class) ; Node currentNode = uiVersionInfo.getCurrentNode(); uiExplorer.addLockToken(currentNode); try { if(!currentNode.isCheckedOut()) { currentNode.checkout(); } AutoVersionService autoVersionService = WCMCoreUtils.getService(AutoVersionService.class); Version addedVersion = autoVersionService.autoVersion(currentNode); currentNode.restore(fromVersionName,true); if(!currentNode.isCheckedOut()) { currentNode.checkout(); } StringBuilder bd = new StringBuilder(); bd.append(((ManageableRepository)currentNode.getSession().getRepository()).getConfiguration().getName()). append("/").append(currentNode.getSession().getWorkspace().getName()).append("/"). append(currentNode.getUUID()); StringBuilder bd1 = new StringBuilder().append(bd).append("/jcr:lastModified"); StringBuilder bd2 = new StringBuilder().append(bd).append("/jcr:baseVersion"); pdfCache.remove(new ObjectKey(bd.toString())); pdfCache.remove(new ObjectKey(bd1.toString())); pdfCache.remove(new ObjectKey(bd2.toString())); int lastVersionIndice = Integer.parseInt(addedVersion.getName()); String restoredFromMsg = "UIDiff.label.restoredFrom_" + fromVersionName + "_" + (lastVersionIndice + 1); VersionHistory versionHistory = currentNode.getVersionHistory(); versionHistory.addVersionLabel(versionHistory.getRootVersion().getName(), restoredFromMsg, false); ListenerService listenerService = WCMCoreUtils.getService(ListenerService.class); ActivityCommonService activityService = WCMCoreUtils.getService(ActivityCommonService.class); try { if (listenerService!=null && activityService !=null && activityService.isAcceptedNode(currentNode)) { listenerService.broadcast(ActivityCommonService.NODE_REVISION_CHANGED, currentNode, fromVersionName); } }catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Can not notify NodeMovedActivity: " + e.getMessage()); } } } catch(JCRInvalidItemStateException invalid) { uiApp.addMessage(new ApplicationMessage("UIVersionInfo.msg.invalid-item-state", null, ApplicationMessage.WARNING)) ; LOG.error("Unable to restore version",invalid); return ; } catch(NullPointerException nuException){ uiApp.addMessage(new ApplicationMessage("UIVersionInfo.msg.invalid-item-state", null, ApplicationMessage.WARNING)) ; LOG.error("Unable to restore version",nuException); return; } catch(Exception e) { //JCRExceptionManager.process(uiApp, e); uiApp.addMessage(new ApplicationMessage("UIVersionInfo.msg.invalid-item-state", null, ApplicationMessage.WARNING)) ; LOG.error("Unable to restore version",e); return; } uiVersionInfo.activate(); event.getRequestContext().addUIComponentToUpdateByAjax(uiVersionInfo) ; uiExplorer.setIsHidePopup(true) ; } } static public class DeleteVersionActionListener extends EventListener<UIVersionInfo> { public void execute(Event<UIVersionInfo> event) throws Exception { UIVersionInfo uiVersionInfo = event.getSource(); UIJCRExplorer uiExplorer = uiVersionInfo.getAncestorOfType(UIJCRExplorer.class); for (UIComponent uiChild : uiVersionInfo.getChildren()) { uiChild.setRendered(false); } String objectId = event.getRequestContext().getRequestParameter(OBJECTID); uiVersionInfo.curentVersion_ = uiVersionInfo.getRootVersionNode().findVersionNode(objectId); Node node = uiVersionInfo.getCurrentNode(); UIApplication app = uiVersionInfo.getAncestorOfType(UIApplication.class); try { node.getSession().save(); node.getSession().refresh(false); VersionHistoryUtils.removeVersion(uiVersionInfo.getCurrentNode(), uiVersionInfo.curentVersion_.getName() ); uiVersionInfo.rootVersion_ = new VersionNode(node, uiExplorer.getSession()); uiVersionInfo.curentVersion_ = uiVersionInfo.rootVersion_; if (!node.isCheckedOut()) node.checkout(); uiExplorer.getSession().save(); uiVersionInfo.activate(); event.getRequestContext().addUIComponentToUpdateByAjax(uiVersionInfo); } catch (ReferentialIntegrityException rie) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", rie); } app.addMessage(new ApplicationMessage("UIVersionInfo.msg.error-removing-referenced-version", null, ApplicationMessage.ERROR)); return; } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } app.addMessage(new ApplicationMessage("UIVersionInfo.msg.error-removing-version", null, ApplicationMessage.ERROR)); return; } } } static public class CompareVersionActionListener extends EventListener<UIVersionInfo> { public void execute(Event<UIVersionInfo> event) throws Exception { UIVersionInfo uiVersionInfo = event.getSource(); UIDocumentWorkspace uiDocumentWorkspace = uiVersionInfo.getAncestorOfType(UIDocumentWorkspace.class); for (UIComponent uiChild : uiDocumentWorkspace.getChildren()) { uiChild.setRendered(false); } String fromVersionName = event.getRequestContext().getRequestParameter("versions").split(",")[0]; String toVersionName = event.getRequestContext().getRequestParameter("versions").split(",")[1]; UIDiff uiDiff = uiDocumentWorkspace.getChild(UIDiff.class); uiDiff.setVersions(uiVersionInfo.getVersion(fromVersionName), uiVersionInfo.getVersion(toVersionName)); uiDiff.setRendered(true); event.getRequestContext().addUIComponentToUpdateByAjax(uiDocumentWorkspace); } } static public class SelectActionListener extends EventListener<UIVersionInfo> { public void execute(Event<UIVersionInfo> event) throws Exception { UIVersionInfo uiVersionInfo = event.getSource() ; String path = event.getRequestContext().getRequestParameter(OBJECTID) ; VersionNode root = uiVersionInfo.getRootVersionNode() ; VersionNode selectedVersion= root.findVersionNode(path); selectedVersion.setExpanded(!selectedVersion.isExpanded()) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiVersionInfo) ; } } static public class CloseActionListener extends EventListener<UIVersionInfo> { public void execute(Event<UIVersionInfo> event) throws Exception { UIVersionInfo uiVersionInfo = event.getSource(); for(UIComponent uiChild : uiVersionInfo.getChildren()) { if (uiChild.isRendered()) { uiChild.setRendered(false); return ; } } UIJCRExplorer uiExplorer = uiVersionInfo.getAncestorOfType(UIJCRExplorer.class) ; uiExplorer.updateAjax(event) ; } } public static class AddSummaryActionListener extends EventListener<UIVersionInfo> { public void execute(Event<UIVersionInfo> event) throws Exception { UIVersionInfo uiVersionInfo = event.getSource(); String objectId = event.getRequestContext().getRequestParameter(OBJECTID) ; uiVersionInfo.curentVersion_ = uiVersionInfo.rootVersion_.findVersionNode(objectId) ; String currentVersionName = uiVersionInfo.curentVersion_.getName(); if(StringUtils.isBlank(currentVersionName)) { currentVersionName = uiVersionInfo.getRootVersionNum(); } String summary = event.getRequestContext().getRequestParameter("value") + "_" + currentVersionName; UIJCRExplorer uiExplorer = uiVersionInfo.getAncestorOfType(UIJCRExplorer.class) ; UIApplication uiApp = uiVersionInfo.getAncestorOfType(UIApplication.class) ; Node currentNode = uiExplorer.getCurrentNode() ; if(!Utils.isNameValid(summary, Utils.SPECIALCHARACTER)) { uiApp.addMessage(new ApplicationMessage("UILabelForm.msg.label-invalid", null, ApplicationMessage.WARNING)) ; return ; } try{ if(StringUtils.isNotBlank(summary) && !currentNode.getVersionHistory().hasVersionLabel(summary)) { Version currentVersion = null; if(currentVersionName.equals(uiVersionInfo.getRootVersionNum())) { currentVersion = currentNode.getVersionHistory().getRootVersion(); } else { currentVersion = currentNode.getVersionHistory().getVersion(currentVersionName); } String[] versionLabels = currentNode.getVersionHistory().getVersionLabels(currentVersion); for(String label : versionLabels) { currentNode.getVersionHistory().removeVersionLabel(label); } currentNode.getVersionHistory().addVersionLabel(currentVersion.getName(), summary, false); } } catch (VersionException ve) { uiApp.addMessage(new ApplicationMessage("UILabelForm.msg.label-exist", new Object[]{summary})) ; return ; } event.getRequestContext().addUIComponentToUpdateByAjax(uiVersionInfo) ; } } }
21,688
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIActivateVersion.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/versions/UIActivateVersion.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.explorer.versions; import org.exoplatform.ecm.webui.component.explorer.UIDocumentWorkspace; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.UIWorkingArea; import org.exoplatform.ecm.webui.utils.Utils; 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.UIApplication; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPopupComponent; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import javax.jcr.AccessDeniedException; import javax.jcr.Node; /** * Created by The eXo Platform SARL * Author : trongtt * trongtt@gmail.com * Oct 16, 2006 * 14:07:15 */ @ComponentConfig( type = UIActivateVersion.class, template = "app:/groovy/webui/component/explorer/versions/UIActivateVersion.gtmpl", events = { @EventConfig(listeners = UIActivateVersion.EnableVersionActionListener.class), @EventConfig(listeners = UIActivateVersion.CancelActionListener.class) } ) public class UIActivateVersion extends UIContainer implements UIPopupComponent { public UIActivateVersion() throws Exception {} public void activate() {} public void deActivate() {} static public class EnableVersionActionListener extends EventListener<UIActivateVersion> { public void execute(Event<UIActivateVersion> event) throws Exception { UIActivateVersion uiActivateVersion = event.getSource(); UIJCRExplorer uiExplorer = uiActivateVersion.getAncestorOfType(UIJCRExplorer.class) ; Node currentNode = uiExplorer.getCurrentNode() ; uiExplorer.addLockToken(currentNode); try { currentNode.addMixin(Utils.MIX_VERSIONABLE); currentNode.save() ; UIWorkingArea uiWorkingArea = uiExplorer.getChild(UIWorkingArea.class); UIDocumentWorkspace uiDocumentWorkspace = uiWorkingArea.getChild(UIDocumentWorkspace.class); UIVersionInfo uiVersionInfo = uiDocumentWorkspace.getChild(UIVersionInfo.class); uiVersionInfo.setCurrentNode(currentNode); uiVersionInfo.setRootOwner(currentNode.getProperty("exo:lastModifier").getString()); uiVersionInfo.activate(); uiDocumentWorkspace.setRenderedChild(UIVersionInfo.class); UIPopupContainer UIPopupContainer = uiExplorer.getChild(UIPopupContainer.class); UIPopupContainer.deActivate(); event.getRequestContext().addUIComponentToUpdateByAjax(uiExplorer); } catch (AccessDeniedException ex) { UIApplication uiApp = uiExplorer.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIActivateVersion.msg.access-denied",null,ApplicationMessage.WARNING)) ; } } } static public class CancelActionListener extends EventListener<UIActivateVersion> { public void execute(Event<UIActivateVersion> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class) ; uiExplorer.cancelAction() ; } } }
4,015
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UINodeTypeInfo.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/popup/info/UINodeTypeInfo.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.explorer.popup.info; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import javax.jcr.Node; import javax.jcr.PropertyType; import javax.jcr.Value; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.PropertyDefinition; import javax.jcr.version.OnParentVersionAction; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.utils.JCRExceptionManager; import org.exoplatform.services.jcr.core.ExtendedPropertyType; 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.UIApplication; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPopupComponent; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SARL * Author : Tran The Trong * trongtt@gmail.com * July 3, 2006 * 10:07:15 AM * Editor : phan tuan Oct 27, 2006 */ @ComponentConfig( template = "app:/groovy/webui/component/explorer/popup/info/UINodeTypeInfo.gtmpl", events = {@EventConfig(listeners = UINodeTypeInfo.CloseActionListener.class)} ) public class UINodeTypeInfo extends UIContainer implements UIPopupComponent { private static final Log LOG = ExoLogger.getLogger(UINodeTypeInfo.class.getName()); private Collection nodeTypes ; public UINodeTypeInfo() throws Exception {} public void activate() { UIJCRExplorer uiJCRExplorer = getAncestorOfType(UIJCRExplorer.class) ; try { Node node = uiJCRExplorer.getCurrentNode() ; NodeType nodetype = node.getPrimaryNodeType() ; Collection<NodeType> types = new ArrayList<NodeType>() ; types.add(nodetype) ; NodeType[] mixins = node.getMixinNodeTypes() ; if (mixins != null) { List<NodeType> list = Arrays.asList(mixins) ; types.addAll(list) ; } nodeTypes = types ; } catch (Exception e) { UIApplication uiApp = uiJCRExplorer.getAncestorOfType(UIApplication.class) ; try { JCRExceptionManager.process(uiApp, e); } catch (Exception e1) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error!", e.getMessage()); } } } } public String getPropertyValue(Value value) throws Exception{ switch(value.getType()) { case PropertyType.BINARY: return Integer.toString(PropertyType.BINARY) ; case PropertyType.BOOLEAN :return Boolean.toString(value.getBoolean()) ; case PropertyType.DATE : return value.getDate().getTime().toString() ; case PropertyType.DOUBLE : return Double.toString(value.getDouble()) ; case PropertyType.LONG : return Long.toString(value.getLong()) ; case PropertyType.NAME : return value.getString() ; case PropertyType.STRING : return value.getString() ; } return null ; } public void deActivate() {} public String[] getActions() {return new String[] {"Close"} ;} public String resolveType(int type) { return ExtendedPropertyType.nameFromValue(type) ; } public String resolveOnParentVersion(int opv) { return OnParentVersionAction.nameFromValue(opv) ; } public String getDefaultValue(PropertyDefinition proDef) throws Exception { StringBuilder defaultValue = new StringBuilder() ; Value[] values = proDef.getDefaultValues() ; if(values == null || values.length < 0) return "" ; for(Value value : values) { if(value == null) continue ; if(defaultValue.length() > 0) defaultValue.append(",") ; defaultValue.append(getPropertyValue(value)) ; } return defaultValue.toString() ; } public Collection getNodeTypes() { return nodeTypes ;} static public class CloseActionListener extends EventListener<UINodeTypeInfo> { public void execute(Event<UINodeTypeInfo> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class) ; uiExplorer.cancelAction() ; } } }
4,915
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-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/popup/info/UIPermissionManager.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.explorer.popup.info; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.core.UIPermissionManagerBase; 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; @ComponentConfig(template = "classpath:groovy/wcm/webui/core/UIPermissionManager.gtmpl", events = { @EventConfig(listeners = UIPermissionManager.CloseActionListener.class) }) public class UIPermissionManager extends UIPermissionManagerBase { public UIPermissionManager() throws Exception { this.addChild(UIPermissionInfo.class, null, null); this.addChild(UIPermissionForm.class, null, null); } static public class CloseActionListener extends EventListener<UIPermissionManager> { public void execute(Event<UIPermissionManager> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); uiExplorer.cancelAction(); } } }
1,834
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIViewMetadataForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-explorer/src/main/java/org/exoplatform/ecm/webui/component/explorer/popup/info/UIViewMetadataForm.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.explorer.popup.info; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.utils.HTMLSanitizer; import org.exoplatform.ecm.utils.lock.LockUtil; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.form.UIDialogForm; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.jcrext.activity.ActivityCommonService; import org.exoplatform.services.cms.metadata.MetadataService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.core.NodetypeConstant; 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.UIApplication; 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.*; import org.exoplatform.webui.form.input.UICheckBoxInput; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.ValueFormatException; import javax.jcr.nodetype.NodeTypeManager; import javax.jcr.nodetype.PropertyDefinition; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Jan 25, 2007 * 1:47:55 PM */ @ComponentConfigs( { @ComponentConfig(type = UIFormMultiValueInputSet.class, id = "WYSIWYGRichTextMultipleInputset", events = { @EventConfig(listeners = UIDialogForm.AddActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIFormMultiValueInputSet.RemoveActionListener.class, phase = Phase.DECODE) } ), @ComponentConfig(lifecycle = UIFormLifecycle.class, events = { @EventConfig(listeners = UIViewMetadataForm.SaveActionListener.class), @EventConfig(listeners = UIViewMetadataForm.CancelActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIViewMetadataForm.AddActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIViewMetadataForm.RemoveActionListener.class, phase = Phase.DECODE) }) }) public class UIViewMetadataForm extends UIDialogForm { private String nodeType_; private static final Log LOG = ExoLogger.getLogger(UIViewMetadataForm.class.getName()); public UIViewMetadataForm() throws Exception { setActions(ACTIONS); } public void setNodeType(String nodeType) { nodeType_ = nodeType; } public String getNodeType() { return nodeType_; } public String getDialogTemplatePath() { repositoryName = getAncestorOfType(UIJCRExplorer.class).getRepositoryName(); MetadataService metadataService = getApplicationComponent(MetadataService.class); try { return metadataService.getMetadataPath(nodeType_, true); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } return null; } public String getTemplate() { return getDialogTemplatePath(); } public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context, String template) { return getAncestorOfType(UIJCRExplorer.class).getJCRTemplateResourceResolver(); } @SuppressWarnings("unchecked") static public class SaveActionListener extends EventListener<UIViewMetadataForm> { public void execute(Event<UIViewMetadataForm> event) throws Exception { UIViewMetadataForm uiForm = event.getSource(); UIJCRExplorer uiJCRExplorer = uiForm.getAncestorOfType(UIJCRExplorer.class); UIViewMetadataManager uiViewManager = uiForm.getAncestorOfType(UIViewMetadataManager.class); Node node = uiViewManager.getViewNode(uiForm.getNodeType()); Node parent=node.getParent(); if(parent.isLocked()) { parent.getSession().addLockToken(LockUtil.getLockToken(parent)); } //Add MIX_COMMENT before update property Node activityNode = node; if(node.isNodeType(NodetypeConstant.NT_RESOURCE)) activityNode = node.getParent(); if (activityNode.canAddMixin(ActivityCommonService.MIX_COMMENT)) { activityNode.addMixin(ActivityCommonService.MIX_COMMENT); } NodeTypeManager ntManager = uiJCRExplorer.getSession().getWorkspace().getNodeTypeManager(); PropertyDefinition[] props = ntManager.getNodeType(uiForm.getNodeType()).getPropertyDefinitions(); List<Value> valueList = new ArrayList<Value>(); for (PropertyDefinition prop : props) { String name = prop.getName(); String inputName = name.substring(name.indexOf(":") + 1); if (!prop.isProtected()) { int requiredType = prop.getRequiredType(); if (prop.isMultiple()) { if (requiredType == 5) { // date UIFormDateTimeInput uiFormDateTime = (UIFormDateTimeInput) uiForm.getUIInput(inputName); if(uiFormDateTime == null) continue; valueList.add(uiJCRExplorer.getSession().getValueFactory().createValue(uiFormDateTime.getCalendar())); if(! node.hasProperty(name) || node.getProperty(name).getValues()[0].getDate().compareTo(valueList.get(0).getDate()) != 0){ node.setProperty(name, valueList.toArray(new Value[] {})); } } else { UIFormInput uiInput = uiForm.getUIInput(inputName); if(uiInput instanceof UIFormSelectBox) { String[] valuesReal = ((UIFormSelectBox)uiInput).getSelectedValues(); if((!node.hasProperty(name) && valuesReal.length > 0) || (node.hasProperty(name) && !uiForm.isEqualsValueStringArrays(node.getProperty(name).getValues(), valuesReal))) node.setProperty(name, valuesReal); } else { List<String> values = (List<String>) ((UIFormMultiValueInputSet) uiInput).getValue(); if ((!node.hasProperty(name) && values.size() > 0) || (node.hasProperty(name) && !uiForm.isEqualsValueStringArrays(node.getProperty(name).getValues(), values.toArray(new String[values.size()])))){ //--- Sanitize HTML input to avoid XSS attacks for (int i = 0; i < values.size(); i++) { values.set(i, HTMLSanitizer.sanitize(values.get(i))); } node.setProperty(name, values.toArray(new String[values.size()])); }} } } else { if (requiredType == 6) { // boolean UIFormInput uiInput = uiForm.getUIInput(inputName); if(uiInput == null) continue; boolean value = false; //2 cases to return true, UIFormSelectBox with value true or UICheckBoxInput checked if(uiInput instanceof UIFormSelectBox){ value = Boolean.parseBoolean(((UIFormSelectBox)uiInput).getValue()); }else if( uiInput instanceof UICheckBoxInput){ value = ((UICheckBoxInput)uiInput).isChecked(); } if(!node.hasProperty(name) || (node.hasProperty(name) && node.getProperty(name).getBoolean() != value)) { node.setProperty(name, value); } } else if (requiredType == 5) { // date UIFormDateTimeInput cal = (UIFormDateTimeInput) uiForm.getUIInput(inputName); if(cal == null) continue; if( !node.hasProperty(name) || cal.getCalendar().compareTo(node.getProperty(name).getDate()) != 0){ node.setProperty(name, cal.getCalendar()); } } else if(requiredType == 1){ String value = ""; if (uiForm.getUIInput(inputName) != null) { value = ((UIFormStringInput)uiForm.getUIInput(inputName)).getValue(); if (value == null) value = ""; } //--- Sanitize HTML input to avoid XSS attacks value = HTMLSanitizer.sanitize(value); if(!node.hasProperty(name) || (node.hasProperty(name) && !node.getProperty(name).getString().equals(value))) node.setProperty(name, value); } else if (requiredType == 4) { // double UIFormInput uiInput = uiForm.getUIInput(inputName); double value = 0; if((uiInput == null || StringUtils.isBlank((String) uiInput.getValue())) && node.hasProperty(name)) { node.setProperty(name, (Value) null); } else { try { value = Double.parseDouble((String) uiInput.getValue()); if(node.getProperty(name).getDouble() != value){ node.setProperty(name, value); } } catch (NumberFormatException e) { UIApplication uiapp = uiForm.getAncestorOfType(UIApplication.class); uiapp.addMessage(new ApplicationMessage("UIViewMetadataForm.msg.Invalid-number", null, ApplicationMessage.WARNING)); LOG.error("Cannot save field '" + name + "'. The value '" + value + "' is not a number", e); } } } } } } //Remove MIX_COMMENT after update property if (activityNode.isNodeType(ActivityCommonService.MIX_COMMENT)) { activityNode.removeMixin(ActivityCommonService.MIX_COMMENT); } node.getSession().save(); event.getRequestContext().addUIComponentToUpdateByAjax(uiViewManager); UIPopupWindow uiPopup = uiViewManager.getChildById(UIViewMetadataManager.METADATAS_POPUP); uiPopup.setShow(false); uiPopup.setShowMask(true); } } static public class CancelActionListener extends EventListener<UIViewMetadataForm> { public void execute(Event<UIViewMetadataForm> event) throws Exception { UIViewMetadataForm uiForm = event.getSource(); UIPopupWindow uiPopup = uiForm.getAncestorOfType(UIPopupWindow.class); uiPopup.setShow(false); uiPopup.setRendered(false); event.getRequestContext().addUIComponentToUpdateByAjax(event.getSource().getParent()); } } static public class AddActionListener extends EventListener<UIViewMetadataForm> { public void execute(Event<UIViewMetadataForm> event) throws Exception { event.getRequestContext().addUIComponentToUpdateByAjax(event.getSource().getParent()); } } static public class RemoveActionListener extends EventListener<UIViewMetadataForm> { public void execute(Event<UIViewMetadataForm> event) throws Exception { event.getRequestContext().addUIComponentToUpdateByAjax(event.getSource().getParent()); } } public boolean isEqualsValueStringArrays(Value[] arrayValue1, String[] arrayValue2) throws ValueFormatException, IllegalStateException, RepositoryException { if(arrayValue1 != null) { String[] stringArray = new String[arrayValue1.length]; int i = 0; for (Value valueItem : arrayValue1) { if(valueItem != null && valueItem.getString() != null) stringArray[i] = valueItem.getString(); i++; } if(stringArray != null && stringArray.length > 0) Arrays.sort(stringArray); if(arrayValue2 != null && arrayValue2.length > 0) Arrays.sort(arrayValue2); return ArrayUtils.isEquals(stringArray, arrayValue2); } else { if(arrayValue2 != null) return false; else return true; } } }
12,991
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z