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
WCMActivityUpdaterListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/addons/rdbms/listener/WCMActivityUpdaterListener.java
package org.exoplatform.wcm.addons.rdbms.listener; import javax.jcr.*; import org.exoplatform.services.jcr.ext.ActivityTypeUtils; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.plugin.doc.UIDocActivity; import org.exoplatform.wcm.ext.component.activity.listener.Utils; public class WCMActivityUpdaterListener extends Listener<ExoSocialActivity, String> { private static final Log LOG = ExoLogger.getLogger(WCMActivityUpdaterListener.class); public static final String LINK_ACTIVITY_TYPE = "LINK_ACTIVITY"; public WCMActivityUpdaterListener() { } @Override public void onEvent(Event<ExoSocialActivity, String> event) throws Exception { ExoSocialActivity oldActivity = event.getSource(); String type = (oldActivity.getType() == null) ? "" : oldActivity.getType(); switch (type) { case LINK_ACTIVITY_TYPE: migrationLinkActivity(oldActivity, event.getData()); break; case Utils.CONTENT_SPACES: migrationContentSpaceActivity(oldActivity, event.getData()); break; case Utils.FILE_SPACES: migrationFileSpaceActivity(oldActivity, event.getData()); break; default: break; } } private void migrationLinkActivity(ExoSocialActivity oldActivity, String newId) { } private void migrationContentSpaceActivity(ExoSocialActivity oldActivity, String newId) { } private void migrationFileSpaceActivity(ExoSocialActivity activity, String newId) throws RepositoryException { if (activity.isComment()) { // TODO: Needs to confirm with ECMS team about the comment type // Utils.CONTENT_SPACES = "contents:spaces" Asks ECMS team to update the comment // There is new mixin type define to keep the CommentId // private static String MIX_COMMENT = "exo:activityComment"; // private static String MIX_COMMENT_ID = "exo:activityCommentID"; LOG.info(String.format("Migration file-spaces comment '%s' with new id's %s", activity.getTitle(), newId)); // migrationDoc(activity, newId); } else { LOG.info(String.format("Migration file-spaces activity '%s' with new id's %s", activity.getTitle(), newId)); // migrationDoc(activity, newId); } } private void migrationDoc(ExoSocialActivity activity, String newId) throws RepositoryException { String workspace = activity.getTemplateParams().get(UIDocActivity.WORKSPACE); if(workspace == null) { workspace = activity.getTemplateParams().get(UIDocActivity.WORKSPACE.toLowerCase()); } String docId = activity.getTemplateParams().get(UIDocActivity.ID); Node docNode = getDocNode(workspace, activity.getUrl(), docId); if (docNode != null && docNode.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO)) { LOG.info("Migration doc: " + docNode.getPath()); try { ActivityTypeUtils.attachActivityId(docNode, newId); docNode.getSession().save(); } catch (RepositoryException e) { LOG.warn("Updates the file-spaces activity is unsuccessful!"); LOG.debug("Updates the file-spaces activity is unsuccessful!", e); } } else { LOG.info(String.format("Missing document's path/Id on template-parameters. Do not migrate this file-spaces activity width old id %s - new id %s" , activity.getId(), newId)); } } /** * This method is target to get the Document node. * * @param workspace * @param path * @param nodeId * @return */ private Node getDocNode(String workspace, String path, String nodeId) { if (workspace == null || (nodeId == null && path == null)) { return null; } try { Session session = SessionProviderService.getSystemSessionProvider().getSession(workspace, SessionProviderService.getRepository()); try { return session.getNodeByUUID(nodeId); } catch (Exception e) { return (Node) session.getItem(path); } } catch (RepositoryException e) { return null; } } }
4,264
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIShareDocuments.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/ecm/webui/component/explorer/popup/actions/UIShareDocuments.java
/* * Copyright (C) 2003-2014 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.popup.actions; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.container.*; import org.exoplatform.ecm.utils.permission.PermissionUtil; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.impl.Utils; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.jcr.access.*; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.jcr.impl.core.SessionImpl; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.resources.ResourceBundleService; import org.exoplatform.services.security.*; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; import org.exoplatform.social.core.manager.IdentityManager; 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.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.UIPopupComponent; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.*; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Nov 18, 2014 */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "war:/groovy/ecm/social-integration/share-document/UIShareDocuments.gtmpl", events = { @EventConfig(listeners = UIShareDocuments.ConfirmActionListener.class), @EventConfig(listeners = UIShareDocuments.CancelActionListener.class), @EventConfig(listeners = UIShareDocuments.TextChangeActionListener.class), @EventConfig(listeners = UIShareDocuments.ChangeActionListener.class), @EventConfig(listeners = UIShareDocuments.ChangePermissionActionListener.class) } ) public class UIShareDocuments extends UIForm implements UIPopupComponent{ private static final Log LOG = ExoLogger.getLogger(UIShareDocuments.class); private static final String SHARECONTENT_BUNDLE_LOCATION = "locale.extension.SocialIntegration"; private static final String SHARE_OPTION_CANVEW = "UIShareDocuments.label.option.read"; private static final String SHARE_OPTION_CANMODIFY = "UIShareDocuments.label.option.modify"; private static final String SHARE_PERMISSION_VIEW = PermissionType.READ; private static final String SHARE_PERMISSION_MODIFY = "modify"; private static final String SPACE_PREFIX1 = "space::"; private static final String SPACE_PREFIX2 = "*:/spaces/"; private static final String LOGIN_INITIALURI = "/login?initialURI=/"; private String permission = SHARE_PERMISSION_VIEW; private boolean permDropDown = false; public boolean hasPermissionDropDown() { return permDropDown; } public void setPermissionDropDown(boolean permDropDown) { this.permDropDown = permDropDown; } public void removePermission(String id) { this.permissions.remove(id); if (this.entries.contains(id)) { this.entries.remove(id); } } public void updatePermission(String id, String permission) { this.permissions.put(id,permission); } /** * @return true if given name is a Group type, not a Space */ public boolean isGroupType(String name) { return name != null && name.startsWith("*:/") && !name.startsWith(SPACE_PREFIX2); } public static class ChangeActionListener extends EventListener<UIShareDocuments> { @Override public void execute(Event<UIShareDocuments> event) throws Exception { String permission = "read"; UIShareDocuments uiform = event.getSource(); if (uiform.getChild(UIFormSelectBox.class).getValue().equals(SHARE_PERMISSION_MODIFY)) { uiform.getChild(UIFormSelectBox.class).setValue(SHARE_PERMISSION_VIEW); } else { uiform.getChild(UIFormSelectBox.class).setValue(SHARE_PERMISSION_MODIFY); permission = SHARE_PERMISSION_MODIFY; } UIWhoHasAccess uiWhoHasAccess = uiform.getParent(); uiWhoHasAccess.updateEntry(uiform.getId(), permission); event.getRequestContext().addUIComponentToUpdateByAjax(uiform); } } public static class CancelActionListener extends EventListener<UIShareDocuments>{ @Override public void execute(Event<UIShareDocuments> event) throws Exception { event.getSource().getAncestorOfType(UIJCRExplorer.class).cancelAction() ; } } public static class TextChangeActionListener extends EventListener<UIShareDocuments>{ @Override public void execute(Event<UIShareDocuments> event) throws Exception { UIShareDocuments uiform = event.getSource(); uiform.comment = event.getSource().getChild(UIFormTextAreaInput.class).getValue(); event.getRequestContext().addUIComponentToUpdateByAjax(event.getSource().getChild(UIFormTextAreaInput.class)); } } public static class ConfirmActionListener extends EventListener<UIShareDocuments>{ @Override public void execute(Event<UIShareDocuments> event) throws Exception { UIShareDocuments uiform = event.getSource(); IShareDocumentService service = WCMCoreUtils.getService(IShareDocumentService.class); UIApplication uiApp = uiform.getAncestorOfType(UIApplication.class); try { uiform.addPermission(); } catch (PermissionException ex) { switch (ex.getError()) { case INVALID_OWNER: uiApp.addMessage(new ApplicationMessage("UIShareDocuments.label.InvalidOwner", null, ApplicationMessage.WARNING)); break; case NOT_FOUND: uiApp.addMessage(new ApplicationMessage("UIShareDocuments.label.Invalid", new String[]{ex.getData() .replace("[","").replace("]","")}, ApplicationMessage.WARNING)); break; case NO_PERMISSION: uiApp.addMessage(new ApplicationMessage("UIShareDocuments.label.NoPermission", null, ApplicationMessage.WARNING)); break; default: uiApp.addMessage(new ApplicationMessage("Error during add permission", null, ApplicationMessage.WARNING)); } return; } List<String> entries = uiform.entries; Map<String,String> permissions = uiform.permissions; Set<String> accessList = uiform.getWhoHasAccess(); Node node = uiform.getNode(); String message = ""; Identity identity = ConversationState.getCurrent().getIdentity(); boolean isShared = false; if (uiform.isOwner(identity.getUserId()) || uiform.canEdit(identity)) { if (uiform.getChild(UIFormTextAreaInput.class).getValue() != null) message = uiform.getChild(UIFormTextAreaInput.class).getValue(); for (String name : accessList) { if (permissions.containsKey(name)) { String perm = permissions.get(name); if (!name.startsWith(SPACE_PREFIX2)) { service.unpublishDocumentToUser(name, (ExtendedNode) node); service.publishDocumentToUser(name, node, message, perm); } else { String groupId = name.substring("*:".length()); service.unpublishDocumentToSpace(groupId, (ExtendedNode) node); service.publishDocumentToSpace(groupId, node, message, perm); } isShared = true; } else if (!name.startsWith(SPACE_PREFIX2)) { service.unpublishDocumentToUser(name, (ExtendedNode) node); } else { String groupId = name.substring("*:".length()); service.unpublishDocumentToSpace(groupId, (ExtendedNode) node); } } if (entries.size() > 0) { for (String entry : entries) { if (entry.equals("") || uiform.isOwner(entry)) continue; else { String perm = permissions.get(entry); if (entry.startsWith(SPACE_PREFIX2)) { isShared = true; } else { service.publishDocumentToUser(entry, node, message, perm); isShared = true; } } } } if (isShared) { uiApp.addMessage(new ApplicationMessage("UIShareDocuments.label.success", null, ApplicationMessage.INFO)); } uiform.getAncestorOfType(UIJCRExplorer.class).cancelAction(); } else { uiApp.addMessage(new ApplicationMessage("UIShareDocuments.label.NoPermission", null, ApplicationMessage.WARNING)); } } } public static String getPortalLoginRedirectURL() { String portal = PortalContainer.getCurrentPortalContainerName(); return new StringBuffer(CommonsUtils.getCurrentDomain()).append("/").append(portal).append(LOGIN_INITIALURI).append(portal).append("/").toString(); } public void addPermission() throws Exception { List<String> entries = this.entries; UIFormStringInput input = this.getUIStringInput(USER_SUGGESTER); String value = input.getValue(); if (value != null && !value.trim().isEmpty()) { input.setValue(null); String[] selectedIdentities = value.split(","); String name = null; Identity identity = ConversationState.getCurrent().getIdentity(); if (this.hasPermissionDropDown() && (this.canEdit(identity) || this.isOwner(identity.getUserId()))) { String permission = this.getPermission(); List<String> notFound = new LinkedList<String>(); int i=0; if (selectedIdentities != null) { for (int idx = 0; idx < selectedIdentities.length; idx++) { name = selectedIdentities[idx].trim(); if (name.length() > 0) { if (isExisting(name) && !this.isOwner(name)) { if (name.startsWith(SPACE_PREFIX1)) name = name.replace(SPACE_PREFIX1, SPACE_PREFIX2); if (!this.hasPermission(name, permission)) { this.updatePermission(name, permission); this.getChild(UIWhoHasAccess.class).update(name, permission); if (!entries.contains(name)) entries.add(name); } } else if (this.isOwner(name)) { throw new PermissionException(PermissionException.Code.INVALID_OWNER); } else { notFound.add(name); } } } } WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance(); requestContext.addUIComponentToUpdateByAjax(this); requestContext.getJavascriptManager() .require("SHARED/share-content", "shareContent") .addScripts("eXo.ecm.ShareContent.checkSelectedEntry('" + entries + "');"); if (notFound.size() > 0) { throw new PermissionException(PermissionException.Code.NOT_FOUND, notFound.toString()); } } else { throw new PermissionException(PermissionException.Code.NO_PERMISSION); } } } public static class PermissionException extends Exception { public enum Code { NOT_FOUND, NO_PERMISSION, INVALID_OWNER } private Code error; private String data; public PermissionException(Code error) { this(error, null); } public PermissionException(Code error, String data) { this.error = error; this.data = data; } public Code getError() { return error; } public String getData() { return data; } } public static class ChangePermissionActionListener extends EventListener<UIShareDocuments> { @Override public void execute(Event<UIShareDocuments> event) throws Exception { UIShareDocuments uicomponent = event.getSource(); if (uicomponent.getPermission().equals(SHARE_PERMISSION_MODIFY)) uicomponent.setPermission(SHARE_PERMISSION_VIEW); else uicomponent.setPermission(SHARE_PERMISSION_MODIFY); event.getRequestContext().addUIComponentToUpdateByAjax(uicomponent); event.getRequestContext().getJavascriptManager() .require("SHARED/share-content", "shareContent") .addScripts("eXo.ecm.ShareContent.checkSelectedEntry('" + uicomponent.entries + "');"); } } private void setPermission(String permission) { this.permission = permission; } private String getPermission() { return permission; } private static boolean isExisting(String name) { if (name.contains("space::")) { SpaceService service = WCMCoreUtils.getService(SpaceService.class); return (service.getSpaceByPrettyName(name.split("::")[1]) != null); } else { ExoContainer container = ExoContainerContext.getCurrentContainer(); IdentityManager identityManager = (IdentityManager) container.getComponentInstanceOfType(IdentityManager.class); return (identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, name, true) != null); } } private boolean hasPermission(String name, String permission) { if (permissions.containsKey(name)) { return permissions.get(name).equals(permission); } return false; } List<String> entries = new ArrayList<String>(); public String comment = ""; private NodeLocation node; private static final String USER_SUGGESTER = "userSuggester"; private Map<String, String> permissions; public UIShareDocuments(){ } public String getValue() { return getUIStringInput(USER_SUGGESTER).getValue(); } public void init() { try { addChild(UIWhoHasAccess.class, null, null); getChild(UIWhoHasAccess.class).init(); addChild(new UIFormTextAreaInput("textAreaInput", "textAreaInput", "")); Node currentNode = this.getNode(); ResourceBundleService resourceBundleService = WCMCoreUtils.getService(ResourceBundleService.class); ResourceBundle resourceBundle = resourceBundleService.getResourceBundle(SHARECONTENT_BUNDLE_LOCATION, Util.getPortalRequestContext().getLocale()); String canView = resourceBundle.getString(SHARE_OPTION_CANVEW); String canModify = resourceBundle.getString(SHARE_OPTION_CANMODIFY); setPermissionDropDown(PermissionUtil.canSetProperty(currentNode)); addUIFormInput(new UIFormStringInput(USER_SUGGESTER, null, null)); permissions = getAllPermissions(); } catch (Exception e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } } public ExtendedNode getNode(){ ExtendedNode node = (ExtendedNode)NodeLocation.getNodeByLocation(this.node); try { if (node.isNodeType("exo:symlink") && node.hasProperty("exo:uuid")) { LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class); return (ExtendedNode)linkManager.getTarget(node); } } catch (RepositoryException e) { LOG.error(e.getMessage(), e); } return node; } public String getIconURL(){ try { return Utils.getNodeTypeIcon(getNode(), "uiIcon24x24"); } catch (RepositoryException e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } return null; } public void setSelectedNode(NodeLocation node) { this.node = node; } public Set<String> getWhoHasAccess() { Set<String> set = new HashSet<String>(); try { for (AccessControlEntry t : getNode().getACL().getPermissionEntries()) { set.add(t.getIdentity()); } } catch (Exception e) { LOG.error(e.getMessage(), e); return null; } return set; } /** * Used to check edit permission on the current document node for users, spaces members * @param username * @return True if the given username has Edit permission on the current node. */ public boolean canEdit(String username) { try { AccessControlList controlList = getNode().getACL(); return controlList.getPermissions(username).contains(PermissionType.ADD_NODE) && controlList.getPermissions(username).contains(PermissionType.SET_PROPERTY); } catch (Exception e) { LOG.error(e.getMessage(), e); return false; } } /** * Used to check edit permission on the current document node for the logged in user. * @param identity * @return True if the given identity has Edit permission on the current node. */ public boolean canEdit(Identity identity) { try { AccessManager accessManager = ((SessionImpl)getNode().getSession()).getAccessManager(); return accessManager.hasPermission(getNode().getACL(), new String[]{PermissionType.ADD_NODE, PermissionType.SET_PROPERTY}, identity); } catch (Exception e) { LOG.error(e.getMessage(), e); return false; } } public String getPermission(String name) { return canEdit(name) ? SHARE_PERMISSION_MODIFY : SHARE_PERMISSION_VIEW; } public boolean isOwner(String username) { try { return username.equals(getNode().getACL().getOwner()); } catch (Exception e) { LOG.error(e.getMessage(), e); return false; } } public String getOwner() { try { return getNode().getACL().getOwner(); } catch (Exception e) { LOG.error(e.getMessage(), e); } return null; } public Map<String, String> getAllPermissions() { return getWhoHasAccess().stream() .filter(identity -> !IdentityConstants.ANY.equals(identity) && !IdentityConstants.SYSTEM.equals(identity) && !isOwner(identity)).filter(identity -> !isGroupType(identity)) .collect(Collectors.toMap(Function.identity(), identity -> getPermission(identity))); } public String getComment(){ if(this.comment == null) return ""; return this.comment; } @Override public void activate() { } @Override public void deActivate() {} }
19,291
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIWhoHasAccess.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/ecm/webui/component/explorer/popup/actions/UIWhoHasAccess.java
/* * Copyright (C) 2003-2014 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.popup.actions; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.organization.OrganizationService; import org.exoplatform.services.organization.User; import org.exoplatform.services.security.IdentityConstants; import org.exoplatform.social.core.identity.model.Identity; import org.exoplatform.social.core.identity.model.Profile; import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; import org.exoplatform.social.core.service.LinkProvider; import org.exoplatform.social.core.space.model.Space; import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.social.notification.Utils; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIContainer; /** * Created by The eXo Platform SAS * Author : Walid Khessairi * wkhessairi@exoplatform.com * Aug 11, 2016 */ @ComponentConfig( template = "war:/groovy/ecm/social-integration/share-document/UIWhoHasAccess.gtmpl" ) public class UIWhoHasAccess extends UIContainer { private static final Log LOG = ExoLogger.getLogger(UIWhoHasAccess.class); private static final String SPACE_PREFIX1 = "space::"; private static final String SPACE_PREFIX2 = "*:/spaces/"; private static final String GROUP_PREFIX = "*:/"; public void close() { for(UIComponent uicomp : getChildren()) { removeChild(UIWhoHasAccessEntry.class); } } public UIWhoHasAccess() { } public void init() { UIShareDocuments uishareDocuments = getAncestorOfType(UIShareDocuments.class); for (String id : uishareDocuments.getAllPermissions().keySet()) { try { // Mange only Spaces (without memberships) and users if (IdentityConstants.ANY.equals(id) || IdentityConstants.SYSTEM.equals(id) || (id.contains(":/") && !isSpace(id))) { continue; } // if id is not a valid user nor a space, ignore it if (!isSpace(id)) { User user = getApplicationComponent(OrganizationService.class).getUserHandler().findUserByName(id); if (user == null) { continue; } } UIWhoHasAccessEntry uiWhoHasAccessEntry = getChildById(id); if (uiWhoHasAccessEntry == null) { uiWhoHasAccessEntry = addChild(UIWhoHasAccessEntry.class, null, id); } uiWhoHasAccessEntry.init(id, uishareDocuments.getPermission(id)); } catch (Exception e) { LOG.error("Error initializing Share documents permission entry for id = " + id, e); } } } public void update(String name, String permission) { try { if (getChildById(name) == null) addChild(UIWhoHasAccessEntry.class, null, name); UIWhoHasAccessEntry uiWhoHasAccessEntry = getChildById(name); uiWhoHasAccessEntry.init(name, permission); } catch (Exception e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } } public void removeEntry(String id) { try { removeChildById(id); UIShareDocuments uiShareDocuments = getParent(); uiShareDocuments.removePermission(id); } catch (Exception e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } } public void updateEntry(String id, String permission) { try { UIShareDocuments uiShareDocuments = getParent(); uiShareDocuments.updatePermission(id, permission); } catch (Exception e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } } public String getProfileUrl(String name) { return CommonsUtils.getCurrentDomain() + LinkProvider.getProfileUri(name); } private boolean isSpace(String name) { return (name.startsWith(SPACE_PREFIX1) || name.startsWith(SPACE_PREFIX2)); } public String getUserFullName(String name) throws Exception { String userFullName = name; User user = getApplicationComponent(OrganizationService.class).getUserHandler().findUserByName(name); if(user != null) { userFullName = user.getDisplayName(); } return userFullName; } public String getPrettySpaceName(String name) { SpaceService spaceService = getApplicationComponent(SpaceService.class); if (name.startsWith(SPACE_PREFIX1)) return spaceService.getSpaceByPrettyName(name.substring(SPACE_PREFIX1.length())).getDisplayName(); else return spaceService.getSpaceByPrettyName(name.substring(SPACE_PREFIX2.length())).getDisplayName(); } public String getSpaceUrl(String name) { String space; if (name.startsWith(SPACE_PREFIX1)) space = name.substring(SPACE_PREFIX1.length()); else space = name.substring(SPACE_PREFIX2.length()); return CommonsUtils.getCurrentDomain() + LinkProvider.getSpaceUri(space.replace(" ","_")); } /** * Return the URL of the entry's avatar * @param name Entry name * @return Entry's avatar URL */ public String getAvatar(String name) { try { if (isSpace(name)) { SpaceService spaceService = getApplicationComponent(SpaceService.class); Space space; if (name.startsWith(SPACE_PREFIX1)) space = spaceService.getSpaceByPrettyName(name.substring(SPACE_PREFIX1.length())); else space = spaceService.getSpaceByPrettyName(name.substring(SPACE_PREFIX2.length())); return space.getAvatarUrl() != null ? space.getAvatarUrl() : LinkProvider.SPACE_DEFAULT_AVATAR_URL; } else { Identity identity = Utils.getIdentityManager().getOrCreateIdentity(OrganizationIdentityProvider.NAME, name, true); Profile profile = identity.getProfile(); return profile.getAvatarUrl() != null ? profile.getAvatarUrl() : LinkProvider.PROFILE_DEFAULT_AVATAR_URL; } } catch (Exception e) { return LinkProvider.SPACE_DEFAULT_AVATAR_URL; } } /** * Return the display name of the entry. * @param name Entry name * @return Entry's display name */ public String getDisplayName(String name) { String displayName = name; try { if(this.isSpace(name)) { displayName = this.getPrettySpaceName(name); } else { displayName = this.getUserFullName(name); } } catch (Exception e) { LOG.error("Cannot display name for entry " + name + " : " + e.getMessage(), e); } return displayName; } /** * Return the entry URL * @param name Entry name * @return Entry's URL */ public String getEntryURL(String name) { String url = null; try { if(this.isSpace(name)) { url = this.getSpaceUrl(name); } else { url = this.getProfileUrl(name); } } catch (Exception e) { LOG.error("Cannot URL for entry " + name + " : " + e.getMessage(), e); } return url; } public String getPrettyGroupName(String name) { return name.split(":")[1]; } }
7,736
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIWhoHasAccessEntry.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/ecm/webui/component/explorer/popup/actions/UIWhoHasAccessEntry.java
/* * Copyright (C) 2003-2014 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.popup.actions; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.security.ConversationState; 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 SAS * Author : Walid Khessairi * wkhessairi@exoplatform.com * Aug 11, 2016 */ @ComponentConfig( template = "war:/groovy/ecm/social-integration/share-document/UIWhoHasAccessEntry.gtmpl", events = { @EventConfig(listeners = UIWhoHasAccessEntry.RemoveEntryActionListener.class), @EventConfig(listeners = UIWhoHasAccessEntry.ChangeEntryActionListener.class) } ) public class UIWhoHasAccessEntry extends UIContainer { private static final Log LOG = ExoLogger.getLogger(UIWhoHasAccessEntry.class); private static final String SHARE_PERMISSION_VIEW = PermissionType.READ; private static final String SHARE_PERMISSION_MODIFY = "modify"; private static final String SPACE_PREFIX1 = "space::"; private static final String SPACE_PREFIX2 = "*:/spaces/"; private boolean permissionDropDown = false; public boolean hasPermissionDropDown() { return permissionDropDown; } public void setPermissionDropDown(boolean permissionDropDown) { this.permissionDropDown = permissionDropDown; } private String name; private String permission; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setPermission(String permission) { this.permission = permission; } public String getPermission() { return permission; } public static class RemoveEntryActionListener extends EventListener<UIWhoHasAccessEntry> { @Override public void execute(Event<UIWhoHasAccessEntry> event) throws Exception { UIWhoHasAccessEntry uiform = event.getSource(); UIWhoHasAccess uiWhoHasAccess = uiform.getParent(); UIShareDocuments uiShareDocuments = uiWhoHasAccess.getParent(); String user = ConversationState.getCurrent().getIdentity().getUserId(); if (uiShareDocuments.isOwner(user) || uiShareDocuments.getNode().getACL().getPermissions(user).contains("remove")) { if (!user.equals(uiform.getId())) { uiWhoHasAccess.removeEntry(uiform.getId()); } else { UIApplication uiApp = uiShareDocuments.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIShareDocuments.label.InvalidDeletion", null, ApplicationMessage.WARNING)); } } else { UIApplication uiApp = uiShareDocuments.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIShareDocuments.label.NoPermissionDelete", null, ApplicationMessage.WARNING)); } event.getRequestContext().getJavascriptManager() .require("SHARED/share-content", "shareContent") .addScripts("eXo.ecm.ShareContent.checkUpdatedEntry();"); event.getRequestContext().addUIComponentToUpdateByAjax(uiShareDocuments); } } public static class ChangeEntryActionListener extends EventListener<UIWhoHasAccessEntry> { @Override public void execute(Event<UIWhoHasAccessEntry> event) throws Exception { UIWhoHasAccessEntry uiform = event.getSource(); if (!uiform.getPermission().equals(SHARE_PERMISSION_MODIFY)) { uiform.setPermission(SHARE_PERMISSION_MODIFY); } else { uiform.setPermission(SHARE_PERMISSION_VIEW); } UIWhoHasAccess uiWhoHasAccess = uiform.getParent(); uiWhoHasAccess.updateEntry(uiform.getId(), uiform.getPermission()); event.getRequestContext().getJavascriptManager() .require("SHARED/share-content", "shareContent") .addScripts("eXo.ecm.ShareContent.checkUpdatedEntry();"); event.getRequestContext().addUIComponentToUpdateByAjax(uiform.getParent().getParent()); } } public void init(String id, String permission) { try { setName(id); setPermission(permission); } catch (Exception e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } } }
5,326
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ShareDocumentsComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/ecm/webui/component/explorer/rightclick/manager/ShareDocumentsComponent.java
/* * Copyright (C) 2003-2014 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.rightclick.manager; import java.util.Arrays; import java.util.List; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.control.filter.CanSetPropertyFilter; import org.exoplatform.ecm.webui.component.explorer.control.filter.IsDocumentFilter; import org.exoplatform.ecm.webui.component.explorer.control.filter.ShareDocumentFilter; import org.exoplatform.ecm.webui.component.explorer.control.listener.UIWorkingAreaActionListener; import org.exoplatform.ecm.webui.component.explorer.popup.actions.UIShareDocuments; 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.UIPopupContainer; import org.exoplatform.webui.event.Event; 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 : eXoPlatform * exo@exoplatform.com * Nov 17, 2014 */ @ComponentConfig( events = { @EventConfig(listeners = ShareDocumentsComponent.ShareDocumentsActionListener.class) } ) public class ShareDocumentsComponent extends UIAbstractManagerComponent{ public static class ShareDocumentsActionListener extends UIWorkingAreaActionListener<ShareDocumentsComponent>{ @Override protected void processEvent(Event<ShareDocumentsComponent> event) throws Exception { String nodePath = event.getRequestContext().getRequestParameter(OBJECTID); UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); if(nodePath == null){ //rise from UIActionBar nodePath = uiExplorer.getCurrentNode().getPath(); }else{ //rise from ContextMenu nodePath = nodePath.split(":")[1]; } UIPopupContainer objUIPopupContainer = uiExplorer.getChild(UIPopupContainer.class); UIShareDocuments uiShareDocuments = uiExplorer.createUIComponent(UIShareDocuments.class, null, null); NodeLocation location = new NodeLocation(uiExplorer.getRepositoryName(),uiExplorer.getWorkspaceName(),nodePath); uiShareDocuments.setSelectedNode(location); uiShareDocuments.init(); objUIPopupContainer.activate(uiShareDocuments, 520, 0); event.getRequestContext().addUIComponentToUpdateByAjax(objUIPopupContainer); } } private static final List<UIExtensionFilter> FILTERS = Arrays.asList(new UIExtensionFilter[] { new IsDocumentFilter(), new ShareDocumentFilter(), new CanSetPropertyFilter() }); @UIExtensionFilters public List<UIExtensionFilter> getFilters() { return FILTERS; } @Override public Class<? extends UIAbstractManager> getUIAbstractManagerClass() { return null; } }
3,829
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TaskAttachmentACLPlugin.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/services/attachments/plugin/task/TaskAttachmentACLPlugin.java
/* * Copyright (C) 2021 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.services.attachments.plugin.task; import org.apache.commons.lang3.StringUtils; import org.exoplatform.services.attachments.plugin.AttachmentACLPlugin; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.task.dto.TaskDto; import org.exoplatform.task.exception.EntityNotFoundException; import org.exoplatform.task.service.TaskService; import org.exoplatform.task.util.TaskUtil; public class TaskAttachmentACLPlugin extends AttachmentACLPlugin { private static final Log LOG = ExoLogger.getLogger(TaskAttachmentACLPlugin.class.getName()); private static final String TASK_ATTACHMENT_TYPE = "task"; private TaskService taskService; public TaskAttachmentACLPlugin(TaskService taskService) { this.taskService = taskService; } @Override public String getEntityType() { return TASK_ATTACHMENT_TYPE; } @Override public boolean canView(long userIdentityId, String entityType, String entityId) { return isProjectParticipant(userIdentityId, entityType, entityId); } @Override public boolean canEdit(long userIdentityId, String entityType, String entityId) { return isProjectParticipant(userIdentityId, entityType, entityId); } @Override public boolean canDetach(long userIdentityId, String entityType, String entityId) { return isProjectParticipant(userIdentityId, entityType, entityId); } private boolean isProjectParticipant(long userIdentityId, String entityType, String entityId) { if (!entityType.equals(TASK_ATTACHMENT_TYPE)) { throw new IllegalArgumentException("Entity type must be" + TASK_ATTACHMENT_TYPE); } if (StringUtils.isEmpty(entityId)) { throw new IllegalArgumentException("Entity id must not be Empty"); } if (userIdentityId <= 0) { throw new IllegalArgumentException("User identity must be positive"); } boolean isParticipant = false; try { TaskDto task = taskService.getTask(Long.parseLong(entityId)); isParticipant = TaskUtil.hasEditPermission(taskService, task); } catch (EntityNotFoundException e) { LOG.error("Can not find task with ID: " + entityId); } return isParticipant; } }
2,955
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TaskAttachmentEntityTypePlugin.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/services/attachments/plugins/TaskAttachmentEntityTypePlugin.java
/* * Copyright (C) 2022 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.services.attachments.plugins; import org.apache.commons.lang3.StringUtils; import org.exoplatform.services.attachments.service.AttachmentEntityTypePlugin; import org.exoplatform.services.attachments.utils.Utils; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.access.AccessControlEntry; import org.exoplatform.services.jcr.access.AccessControlList; 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.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.task.dto.TaskDto; import org.exoplatform.task.service.ProjectService; import org.exoplatform.task.service.TaskService; import javax.jcr.*; import java.util.*; import static org.exoplatform.services.attachments.utils.Utils.EXO_SYMLINK_UUID; import static org.exoplatform.services.wcm.core.NodetypeConstant.*; /** * Plugin to define how and where files attached to tasks are stored */ public class TaskAttachmentEntityTypePlugin extends AttachmentEntityTypePlugin { private static final Log LOG = ExoLogger.getExoLogger(TaskAttachmentEntityTypePlugin.class); private final TaskService taskService; private final ProjectService projectService; private final NodeHierarchyCreator nodeHierarchyCreator; private final SessionProviderService sessionProviderService; private final RepositoryService repositoryService; public static final String DOCUMENTS_NODE = "Documents"; private static final String DEFAULT_GROUPS_HOME_PATH = "/Groups"; //NOSONAR public static final String GROUPS_PATH_ALIAS = "groupsPath"; public TaskAttachmentEntityTypePlugin(TaskService taskService, ProjectService projectService, NodeHierarchyCreator nodeHierarchyCreator, SessionProviderService sessionProviderService, RepositoryService repositoryService) { this.taskService = taskService; this.projectService = projectService; this.nodeHierarchyCreator = nodeHierarchyCreator; this.repositoryService = repositoryService; this.sessionProviderService = sessionProviderService; } @Override public List<String> getlinkedAttachments(String entityType, long entityId, String attachmentId) { SessionProvider sessionProvider = sessionProviderService.getSessionProvider(null); try { TaskDto task = taskService.getTask(entityId); Set<String> taskPermittedIdentities = projectService.getParticipator(task.getStatus().getProject().getId()); ManageableRepository repository = repositoryService.getCurrentRepository(); Session userSession = sessionProvider.getSession(repository.getConfiguration().getDefaultWorkspaceName(), repository); // check if content is still there Node attachmentNode = Utils.getNodeByIdentifier(userSession, attachmentId); if (attachmentNode == null) { return Collections.singletonList(attachmentId); } // Check if the content is symlink, then get the original content if (attachmentNode.isNodeType(EXO_SYMLINK)) { String sourceNodeId = attachmentNode.getProperty(EXO_SYMLINK_UUID).getString(); Node originalNode = Utils.getNodeByIdentifier(userSession, sourceNodeId); if (originalNode != null) { attachmentNode = originalNode; } } List<String> linkNodes = new ArrayList<>(); for (String permittedIdentity : taskPermittedIdentities) { if (permittedIdentity.contains(":/spaces/")) { String groupId = permittedIdentity.split(":")[1]; if (attachmentNode.getPath().contains(groupId + "/") && !linkNodes.contains(attachmentId)) { linkNodes.add(attachmentId); } else { // Create a symlink in Document app of the space if the task belongs to a // project of a space Node rootNode = getGroupNode(nodeHierarchyCreator, userSession, groupId); if (rootNode != null) { Node parentNode = getDestinationFolder(rootNode, task.getId()); // We won't add the file symlink as attachment if another file exists with the same name if(!parentNode.hasNode(attachmentNode.getName())) { Node linkNode = Utils.createSymlink(attachmentNode, parentNode, permittedIdentity); if (linkNode != null) { linkNodes.add(((ExtendedNode) linkNode).getIdentifier()); } } } } } // set read permission for users or groups different from spaces if (attachmentNode.canAddMixin(EXO_PRIVILEGEABLE)) { attachmentNode.addMixin(EXO_PRIVILEGEABLE); } AccessControlList permsList = ((ExtendedNode) attachmentNode).getACL(); if (permsList == null || (permsList != null && permsList.getPermissions(permittedIdentity).isEmpty())) { ((ExtendedNode) attachmentNode).setPermission(permittedIdentity, new String[] { PermissionType.READ }); } attachmentNode.save(); } if(linkNodes.isEmpty()) { return Collections.singletonList(attachmentId); } return linkNodes; } catch (Exception e) { LOG.error("Error getting linked documents {}", attachmentId, e); } return Collections.singletonList(attachmentId); } @Override public String getEntityType() { return "task"; } private Node getDestinationFolder(Node rootNode, Long entityId) { Node parentNode; try { if (rootNode.hasNode("task")) { parentNode = rootNode.getNode("task"); } else { parentNode = rootNode.addNode("task", NT_FOLDER); rootNode.save(); } if (parentNode.hasNode(String.valueOf(entityId))) { return parentNode.getNode(String.valueOf(entityId)); } else { Node taskNode = parentNode.addNode(String.valueOf(entityId), NT_FOLDER); parentNode.save(); return taskNode; } } catch (RepositoryException repositoryException) { LOG.error("Could not create and return parent folder for task {} under root folder {}", entityId, rootNode, repositoryException); return rootNode; } } private static Node getGroupNode(NodeHierarchyCreator nodeHierarchyCreator, Session session, String groupId) throws RepositoryException { String groupsHomePath = getGroupsPath(nodeHierarchyCreator); String groupPath = groupsHomePath + groupId + "/" + DOCUMENTS_NODE; if (session.itemExists(groupPath)) { return (Node) session.getItem(groupPath); } return null; } private static String getGroupsPath(NodeHierarchyCreator nodeHierarchyCreator) { String groupsPath = nodeHierarchyCreator.getJcrPath(GROUPS_PATH_ALIAS); if (StringUtils.isBlank(groupsPath)) { groupsPath = DEFAULT_GROUPS_HOME_PATH; } return groupsPath; } }
8,235
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FileActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/ecms/activity/listener/FileActivityListener.java
package org.exoplatform.ecms.activity.listener; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.social.core.activity.ActivityLifeCycleEvent; import org.exoplatform.social.core.activity.ActivityListenerPlugin; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.wcm.ext.component.document.service.IShareDocumentService; /** * A listener to share documents from original Activity to the shared space * location */ public class FileActivityListener extends ActivityListenerPlugin { public static final String DOCPATH = "DOCPATH"; public static final String NODEPATH_NAME = "nodePath"; private static final Log LOG = ExoLogger.getLogger(FileActivityListener.class); private IShareDocumentService shareDocumentService; private ActivityManager activityManager; public FileActivityListener(ActivityManager activityManager, IShareDocumentService shareDocumentService) { this.shareDocumentService = shareDocumentService; this.activityManager = activityManager; } @Override public void shareActivity(ActivityLifeCycleEvent event) { ExoSocialActivity sharedActivity = event.getActivity(); if (sharedActivity != null && sharedActivity.getTemplateParams() != null && sharedActivity.getTemplateParams().containsKey("originalActivityId")) { String originalActivityId = sharedActivity.getTemplateParams().get("originalActivityId"); ExoSocialActivity originalActivity = activityManager.getActivity(originalActivityId); if (originalActivity != null && originalActivity.getTemplateParams() != null && !sharedActivity.isComment() && sharedActivity.getActivityStream() != null && (originalActivity.getTemplateParams().containsKey(DOCPATH) || originalActivity.getTemplateParams().containsKey(NODEPATH_NAME))) { try { shareDocumentService.shareDocumentActivityToSpace(sharedActivity); } catch (Exception e) { LOG.error("Error while sharing files of activity {}", sharedActivity.getId(), e); } } } } }
2,237
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ActivityAttachmentProcessor.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/ecms/activity/processor/ActivityAttachmentProcessor.java
/* * Copyright (C) 2003-2021 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.ecms.activity.processor; import static org.exoplatform.social.plugin.doc.UIDocActivity.*; import static org.exoplatform.wcm.ext.component.activity.FileUIActivity.NODE_PATH; import static org.exoplatform.wcm.ext.component.activity.FileUIActivity.SEPARATOR_REGEX; import java.util.ArrayList; import java.util.Map; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.apache.commons.lang3.StringUtils; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.attachments.model.ActivityFileAttachment; import org.exoplatform.services.attachments.utils.Utils; import org.exoplatform.services.cms.documents.TrashService; 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.social.core.BaseActivityProcessorPlugin; import org.exoplatform.social.core.activity.model.ExoSocialActivity; public class ActivityAttachmentProcessor extends BaseActivityProcessorPlugin { private static final Log LOG = ExoLogger.getLogger(ActivityAttachmentProcessor.class); private TrashService trashService; public ActivityAttachmentProcessor(TrashService trashService, InitParams initParams) { super(initParams); this.trashService = trashService; } @Override public void processActivity(ExoSocialActivity activity) { Map<String, String> activityParams = activity.getTemplateParams(); if (activityParams == null || activityParams.isEmpty() || (!activityParams.containsKey(WORKSPACE) && !activityParams.containsKey(WORKSPACE.toLowerCase()))) { return; } String[] repositories = getParameterValues(activityParams, REPOSITORY); String[] workspaces = getParameterValues(activityParams, WORKSPACE); String[] mimeTypes = getParameterValues(activityParams, MIME_TYPE); String[] nodeUUIDs = getParameterValues(activityParams, ID); String[] docPaths = activityParams.containsKey(DOCPATH) ? getParameterValues(activityParams, DOCPATH) : getParameterValues(activityParams, NODE_PATH); if (docPaths == null) { return; } activity.setFiles(new ArrayList<>()); for (int i = 0; i < docPaths.length; i++) { String docPath = docPaths[i]; ActivityFileAttachment fileAttachment = new ActivityFileAttachment(); try { String repository = "repository"; if (repositories != null && repositories.length == docPaths.length && StringUtils.isNotBlank(repositories[i])) { repository = repositories[i]; } String workspace = "collaboration"; if (workspaces != null && workspaces.length == docPaths.length && StringUtils.isNotBlank(workspaces[i])) { workspace = workspaces[i]; } String mimeType = null; if (mimeTypes != null && mimeTypes.length == docPaths.length && StringUtils.isNotBlank(mimeTypes[i])) { mimeType = mimeTypes[i]; } String nodeUUID = null; if (nodeUUIDs != null && nodeUUIDs.length == docPaths.length && StringUtils.isNotBlank(nodeUUIDs[i])) { nodeUUID = nodeUUIDs[i]; } fileAttachment.setRepository(repository); fileAttachment.setWorkspace(workspace); fileAttachment.setId(nodeUUID); fileAttachment.setDocPath(docPath); fileAttachment.setMimeType(mimeType); activity.getFiles().add(fileAttachment); NodeLocation nodeLocation = new NodeLocation(repository, workspace, docPath, nodeUUID, true); Node contentNode = NodeLocation.getNodeByLocation(nodeLocation); if (contentNode == null || !contentNode.isNodeType(NodetypeConstant.MIX_REFERENCEABLE)) { fileAttachment.setDeleted(true); continue; } if (nodeUUID == null) { fileAttachment.setId(contentNode.getUUID()); } fileAttachment.setName(getTitle(contentNode)); fileAttachment.setDeleted(trashService.isInTrash(contentNode) || isQuarantinedItem(contentNode)); } catch (Exception e) { fileAttachment.setDeleted(true); LOG.warn("Error while geting attached file: {}. Continue retrieving the other attachments anyway.", docPath, e); } } } private String getTitle(Node contentNode) throws RepositoryException { String nodeTitle; try { nodeTitle = org.exoplatform.ecm.webui.utils.Utils.getTitle(contentNode); } catch (Exception e) { nodeTitle = contentNode.getName(); } return nodeTitle; } private boolean isQuarantinedItem(Node node) throws RepositoryException { return node.getPath().startsWith("/" + Utils.QUARANTINE_FOLDER + "/"); } private String[] getParameterValues(Map<String, String> activityParams, String paramName) { String[] values = null; String value = activityParams.get(paramName); if (value == null) { value = activityParams.get(paramName.toLowerCase()); } if (value != null) { values = value.split(SEPARATOR_REGEX); } return values; } }
5,893
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
JCRNodeListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/ecms/listener/analytics/JCRNodeListener.java
package org.exoplatform.ecms.listener.analytics; import static org.exoplatform.analytics.utils.AnalyticsUtils.addSpaceStatistics; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.HashSet; import java.util.Set; import java.util.concurrent.*; import javax.jcr.*; import javax.jcr.observation.Event; import org.apache.commons.chain.Context; import org.apache.commons.lang3.StringUtils; import org.exoplatform.analytics.model.StatisticData; import org.exoplatform.analytics.utils.AnalyticsUtils; import org.exoplatform.commons.utils.PropertyManager; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.component.RequestLifeCycle; import org.exoplatform.services.cms.documents.TrashService; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.command.action.Action; import org.exoplatform.services.ext.action.InvocationContext; 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.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.social.core.space.model.Space; import org.exoplatform.social.core.space.spi.SpaceService; public class JCRNodeListener implements Action { private static final String GROUPS_SPACES_PARENT_FOLDER = "/Groups/spaces/"; private static final String DOCUMENT_NAME_PARAM = "documentName"; private static final Log LOG = ExoLogger.getLogger(JCRNodeListener.class); private static final String DEFAULT_CHARSET = Charset.defaultCharset().name(); private static final ScheduledExecutorService SCHEDULER = new ScheduledThreadPoolExecutor(0); // NOSONAR private static final Executor DEFAULT_DELAYED_EXECUTOR = delayedExecutor(3, TimeUnit.SECONDS); private static final String FILE_EXTENSION_PARAM = "fileExtension"; private static final String DOCUMENT_TYPE_PARAM = "documentType"; private static final String UUID_PARAM = "uuid"; private static final String FILE_SIZE_PARAM = "fileSize"; private static final String FILE_MIME_TYPE_PARAM = "fileMimeType"; private static final String DOCUMENT_UPDATED_OPERATION = "documentUpdated"; private static final String FILE_UPDATED_OPERATION = "fileUpdated"; private static final String DOCUMENT_CREATED_OPERATION = "documentCreated"; private static final String FILE_CREATED_OPERATION = "fileCreated"; private static final String DOCUMENT_MOVED_TO_TRASH_OPERATION = "documentMovedToTrash"; private static final String FILE_MOVED_TO_TRASH_OPERATION = "fileMovedToTrash"; private static final String MODULE_DOCUMENT = "Document"; private static final String SUB_MODULE_CONTENT = "Content"; private static final String MODULE_DRIVE = "Drive"; private static final String SEPARATOR = "@@"; private static final Set<String> CURRENTLY_PROCESSING_NODE_PATH_QUEUE = new HashSet<>(); private static final String EXO_USER_PREFERENCES = "exo:userPrefferences"; private PortalContainer container; private TemplateService templateService; private SpaceService spaceService; private TrashService trashService; public JCRNodeListener() { this.container = PortalContainer.getInstance(); } @Override public boolean execute(Context context) throws Exception { // NOSONAR try { String username = AnalyticsUtils.getUsername(ConversationState.getCurrent()); boolean unkownUser = AnalyticsUtils.isUnkownUser(username); if (unkownUser) { return true; } Object item = context.get(InvocationContext.CURRENT_ITEM); Node node = (item instanceof Property) ? ((Property) item).getParent() : (Node) item; if (node == null) { return true; } Node managedNode = getManagedNodeFromParents(node); if (managedNode == null) { return true; } int eventType = (Integer) context.get(InvocationContext.EVENT); if (eventType == Event.NODE_ADDED && node.isNodeType(EXO_USER_PREFERENCES)) { return true; } String nodePath = managedNode.getPath(); String queueKey = username + SEPARATOR + nodePath; if (CURRENTLY_PROCESSING_NODE_PATH_QUEUE.contains(queueKey)) { // Ignore multiple action invocations when adding new node or updating a // node return true; } CURRENTLY_PROCESSING_NODE_PATH_QUEUE.add(queueKey); ManageableRepository repository = SessionProviderService.getRepository(); String workspace = managedNode.getSession().getWorkspace().getName(); boolean isNew = node.isNew(); DEFAULT_DELAYED_EXECUTOR.execute(() -> { ExoContainerContext.setCurrentContainer(container); RequestLifeCycle.begin(container); SessionProvider systemProvider = SessionProvider.createSystemProvider(); try { CURRENTLY_PROCESSING_NODE_PATH_QUEUE.remove(queueKey); Session session = systemProvider.getSession(workspace, repository); if (!session.itemExists(nodePath)) { return; } Node changedNode = (Node) session.getItem(nodePath); boolean isFile = changedNode.isNodeType(NodetypeConstant.NT_FILE); StatisticData statisticData = addModuleName(isFile); addOperationName(node, statisticData, isNew, isFile); addUUID(changedNode, statisticData); if (isFile) { addFileProperties(statisticData, changedNode); } statisticData.setUserId(AnalyticsUtils.getUserIdentityId(username)); statisticData.addParameter(DOCUMENT_TYPE_PARAM, changedNode.getPrimaryNodeType().getName()); addDocumentTitle(changedNode, statisticData); addSpaceStatistic(statisticData, nodePath); AnalyticsUtils.addStatisticData(statisticData); } catch (Exception e) { LOG.warn("Error computing jcr statistics", e); } finally { systemProvider.close(); RequestLifeCycle.end(); ExoContainerContext.setCurrentContainer(null); } return; }); } catch (Exception e) { if (LOG.isDebugEnabled() || PropertyManager.isDevelopping()) { LOG.warn("Error computing jcr statistics", e); } else { LOG.warn("Error computing jcr statistics: {}", e.getMessage()); } } return true; } private void addFileProperties(StatisticData statisticData, Node changedNode) throws RepositoryException { if (changedNode.hasNode(NodetypeConstant.JCR_CONTENT)) { Node fileMetadataNode = changedNode.getNode(NodetypeConstant.JCR_CONTENT); if (fileMetadataNode.hasProperty(NodetypeConstant.JCR_MIME_TYPE)) { statisticData.addParameter(FILE_MIME_TYPE_PARAM, fileMetadataNode.getProperty(NodetypeConstant.JCR_MIME_TYPE).getString()); } if (fileMetadataNode.hasProperty(NodetypeConstant.JCR_DATA)) { statisticData.addParameter(FILE_SIZE_PARAM, fileMetadataNode.getProperty(NodetypeConstant.JCR_DATA).getLength()); } } String nodeName = changedNode.getName(); int index = nodeName.lastIndexOf('.'); if (index != -1) { statisticData.addParameter(FILE_EXTENSION_PARAM, nodeName.substring(index + 1)); } } private void addUUID(Node changedNode, StatisticData statisticData) throws RepositoryException { if (changedNode.hasProperty(NodetypeConstant.JCR_UUID)) { statisticData.addParameter(UUID_PARAM, changedNode.getProperty(NodetypeConstant.JCR_UUID).getString()); } } private StatisticData addModuleName(boolean isFile) { StatisticData statisticData = new StatisticData(); statisticData.setModule(MODULE_DRIVE); if (isFile) { statisticData.setSubModule(MODULE_DOCUMENT); } else { statisticData.setSubModule(SUB_MODULE_CONTENT); } return statisticData; } private void addOperationName(Node node, StatisticData statisticData, boolean isNew, boolean isFile) throws RepositoryException { boolean movedToTrash = getTrashService().isInTrash(node); String operation = null; if (movedToTrash) { if (isFile) { operation = FILE_MOVED_TO_TRASH_OPERATION; } else { operation = DOCUMENT_MOVED_TO_TRASH_OPERATION; } } else if (isNew) { if (!isFile) { operation = DOCUMENT_CREATED_OPERATION; } } else { if (isFile) { operation = FILE_UPDATED_OPERATION; } else { operation = DOCUMENT_UPDATED_OPERATION; } } statisticData.setOperation(operation); } private void addDocumentTitle(Node managedNode, StatisticData statisticData) throws RepositoryException, UnsupportedEncodingException { String title = null; if (managedNode.hasProperty(NodetypeConstant.EXO_TITLE)) { title = managedNode.getProperty(NodetypeConstant.EXO_TITLE).getString(); } else if (managedNode.hasProperty(NodetypeConstant.EXO_NAME)) { title = managedNode.getProperty(NodetypeConstant.EXO_NAME).getString(); } else { title = managedNode.getName(); } try { title = URLDecoder.decode(URLDecoder.decode(title, DEFAULT_CHARSET), DEFAULT_CHARSET); } catch (Exception e) { // Nothing to do the title contains a % character } statisticData.addParameter(DOCUMENT_NAME_PARAM, title); } private Node getManagedNodeFromParents(Node changedNode) throws RepositoryException { Node nodeIndex = changedNode; Node managedNode = getManagedNode(changedNode); do { if (StringUtils.equals("/", nodeIndex.getPath())) { break; } else { try { nodeIndex = nodeIndex.getParent(); Node managedNodeTmp = getManagedNode(nodeIndex); if (managedNodeTmp != null) { // A parent node has Managed Template, thus, use it in Analytics // reference instead of node itself managedNode = managedNodeTmp; } } catch (AccessDeniedException e) { LOG.trace("User doesn't have access to parent node of '{}'", nodeIndex.getPath(), e); break; } } } while (true); return managedNode; } private Node getManagedNode(Node node) throws RepositoryException { String nodeType = node.getPrimaryNodeType().getName(); if (!node.isNodeType(NodetypeConstant.NT_RESOURCE) && (node.isNodeType(NodetypeConstant.NT_FILE) || getTemplateService().isManagedNodeType(nodeType))) { // Found parent managed node return node; } return null; } private void addSpaceStatistic(StatisticData statisticData, String nodePath) { if (nodePath.startsWith(GROUPS_SPACES_PARENT_FOLDER)) { String[] nodePathParts = nodePath.split("/"); if (nodePathParts.length > 3) { String groupId = "/spaces/" + nodePathParts[3]; Space space = getSpaceService().getSpaceByGroupId(groupId); addSpaceStatistics(statisticData, space); } } } private TemplateService getTemplateService() { if (templateService == null) { templateService = this.container.getComponentInstanceOfType(TemplateService.class); } return templateService; } private SpaceService getSpaceService() { if (spaceService == null) { spaceService = this.container.getComponentInstanceOfType(SpaceService.class); } return spaceService; } private TrashService getTrashService() { if (trashService == null) { trashService = this.container.getComponentInstanceOfType(TrashService.class); } return trashService; } private static Executor delayedExecutor(long delay, TimeUnit unit) { return delayedExecutor(delay, unit, ForkJoinPool.commonPool()); } private static Executor delayedExecutor(long delay, TimeUnit unit, Executor executor) { return r -> SCHEDULER.schedule(() -> executor.execute(r), delay, unit); } }
13,373
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
AnalyticsDocumentsListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/ecms/listener/analytics/AnalyticsDocumentsListener.java
package org.exoplatform.ecms.listener.analytics; import org.exoplatform.analytics.model.StatisticData; import org.exoplatform.analytics.utils.AnalyticsUtils; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.services.jcr.impl.core.NodeImpl; import org.exoplatform.services.listener.Asynchronous; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.social.core.identity.model.Identity; import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; import org.exoplatform.social.core.manager.IdentityManager; import org.exoplatform.social.core.space.model.Space; import org.exoplatform.social.core.space.spi.SpaceService; import javax.jcr.Node; import static org.exoplatform.analytics.utils.AnalyticsUtils.addSpaceStatistics; @Asynchronous public class AnalyticsDocumentsListener extends Listener<String, Node> { private static final String UPLOAD_DOCUMENT_NEW_APP_OPERATION_NAME = "documentUploadedNewApp"; private static final String UPLOAD_DOCUMENT_OLD_APP_OPERATION_NAME = "documentUploadedOldApp"; private static final String GROUPS_SPACES_PARENT_FOLDER = "/Groups/spaces/"; private IdentityManager identityManager; private SpaceService spaceService; @Override public void onEvent(Event<String, Node> event) throws Exception { Node data = event.getData(); String operation = event.getEventName().equals("exo.upload.doc.newApp") ? UPLOAD_DOCUMENT_NEW_APP_OPERATION_NAME : UPLOAD_DOCUMENT_OLD_APP_OPERATION_NAME; long userId = 0; Identity identity = getIdentityManager().getOrCreateIdentity(OrganizationIdentityProvider.NAME, event.getSource()); if (identity != null) { userId = Long.parseLong(identity.getId()); } StatisticData statisticData = new StatisticData(); statisticData.setModule("documents"); statisticData.setSubModule("event"); statisticData.setOperation(operation); statisticData.setUserId(userId); statisticData.addParameter("documentsName", data.getName()); statisticData.addParameter("documentsPath", data.getPath()); statisticData.addParameter("documentsOwner", ((NodeImpl) data).getACL().getOwner()); String nodePath = data.getPath(); addSpaceStatistic(statisticData, nodePath); AnalyticsUtils.addStatisticData(statisticData); } public IdentityManager getIdentityManager() { if (identityManager == null) { identityManager = ExoContainerContext.getService(IdentityManager.class); } return identityManager; } public SpaceService getSpaceService() { if (spaceService == null) { spaceService = ExoContainerContext.getService(SpaceService.class); } return spaceService; } private void addSpaceStatistic(StatisticData statisticData, String nodePath) { if (nodePath.startsWith(GROUPS_SPACES_PARENT_FOLDER)) { String[] nodePathParts = nodePath.split("/"); if (nodePathParts.length > 3) { String groupId = "/spaces/" + nodePathParts[3]; Space space = getSpaceService().getSpaceByGroupId(groupId); addSpaceStatistics(statisticData, space); } } } }
3,220
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CssClassManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/ecms/css/CssClassManager.java
/* * Copyright (C) 2003-2023 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.ecms.css; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.picocontainer.Startable; public class CssClassManager implements Startable { private static final Log LOG = ExoLogger.getLogger(CssClassManager.class); private static final String UI_ICON = "uiIcon"; public static final String DEFAULT_CSS_ICON_FILE = "nt_file"; private List<CssClassPlugin> plugins = new ArrayList<CssClassPlugin>(); private Map<String, CssClassIconFile> cssClassIconFileData = new HashMap<String, CssClassIconFile>(); private String dataJsonIconFileType = null; public enum ICON_SIZE { ICON_16("16x16"), ICON_24("24x24"), ICON_48("48x48"), ICON_64("64x64"); private final String name; ICON_SIZE(String name) { this.name = name; } public String getName() { return this.name; } } public CssClassManager(InitParams params) { } @Override public void start() { try { LOG.info("initializing CSS class icon files..."); initCssClassIconFile(); } catch (Exception e) { LOG.warn("Error while initializing CSS class icon files: " + e.getMessage()); } } @Override public void stop() { } /** * Register ComponentPlugin for initialize icon CSS class of files. * * @param classPlugin * * @since 4.0.1 */ public void registerCssClassPlugin(CssClassPlugin classPlugin) { plugins.add(classPlugin); } /** * Initialize icon CSS class of files by ComponentPlugin. * * @since 4.0.1 */ public void initCssClassIconFile() { cssClassIconFileData.put(CssClassIconFile.DEFAULT_TYPE, CssClassIconFile.getDefault()); // for (CssClassPlugin cssClassPlugin : plugins) { for (CssClassIconFile cssClass : cssClassPlugin.getCssClassIconFile()) { cssClassIconFileData.put(cssClass.getType(), cssClass); } } } /** * Returns the icon CSS class name of file. * * @param fileType - The file's type * @param size - The size of icon, if it is null, the value default is 16x16 * @return * * @since 4.0.1 */ public String getCSSClassByFileType(String fileType, ICON_SIZE size) { Collection<CssClassIconFile> classIconFiles = cssClassIconFileData.values(); for (CssClassIconFile cssFile : classIconFiles) { // if (cssFile.containInGroupFileTypes(fileType)) { return buildCssClass(cssFile, size); } } return buildCssClass(null, size); } /** * Returns the icon CSS class name of file. * * @param fileName - The name of file contain file extension * @param size - The size of icon, if it is null, the value default is 16x16 * @return * * @since 4.0.1 */ public String getCSSClassByFileName(String fileName, ICON_SIZE size) { String fileExtension = CssClassUtils.getFileExtension(fileName); CssClassIconFile cssFile = cssClassIconFileData.get(fileExtension); if (cssFile == null || cssFile.equals(CssClassIconFile.getDefault())) { String fileType = new StringBuffer("File").append(fileExtension.substring(0, 1).toUpperCase()) .append(fileExtension.substring(1).toLowerCase()).toString(); return getCSSClassByFileType(fileType, size); } return buildCssClass(cssFile, size); } private static String buildCssClass(CssClassIconFile cssFile, ICON_SIZE size) { if(cssFile == null) { cssFile = CssClassIconFile.getDefault(); } if (size == null) { size = ICON_SIZE.ICON_16; } return String.format("%s%s%s %s%s%s", UI_ICON, size.getName(), cssFile.getCssClass(), UI_ICON, size.getName(), DEFAULT_CSS_ICON_FILE); } public String getClassIconJsonData() { if (dataJsonIconFileType == null) { dataJsonIconFileType = cssClassIconFileData.values().toString(); } return dataJsonIconFileType; } }
4,914
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CssClassUtils.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/ecms/css/CssClassUtils.java
/* * Copyright (C) 2003-2023 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.ecms.css; import org.exoplatform.container.PortalContainer; public class CssClassUtils { public static CssClassManager getCssClassManager() { return (CssClassManager) PortalContainer.getInstance().getComponentInstanceOfType(CssClassManager.class); } public static String getCSSClassByFileType(String fileType, CssClassManager.ICON_SIZE size) { return getCssClassManager().getCSSClassByFileType(fileType, size); } public static String getCSSClassByFileName(String fileName, CssClassManager.ICON_SIZE size) { return getCssClassManager().getCSSClassByFileName(fileName, size); } public static String getCSSClassByFileNameAndFileType(String fileName, String fileType, CssClassManager.ICON_SIZE size) { String cssClass = getCSSClassByFileName(fileName, size); if (cssClass.indexOf(CssClassIconFile.DEFAULT_CSS) >= 0) { cssClass = getCSSClassByFileType(fileType, size); } return cssClass; } public static String getFileExtension(String fileName) { if (fileName != null && fileName.trim().length() > 0) { return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); } else { return CssClassIconFile.DEFAULT_TYPE; } } }
1,955
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CssClassPlugin.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/ecms/css/CssClassPlugin.java
/* * Copyright (C) 2003-2023 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.ecms.css; import java.util.ArrayList; import java.util.List; import org.exoplatform.container.component.BaseComponentPlugin; import org.exoplatform.container.xml.InitParams; public class CssClassPlugin extends BaseComponentPlugin { private List<CssClassIconFile> cssClassIconFile = new ArrayList<CssClassIconFile>(); public CssClassPlugin(InitParams params) { cssClassIconFile = params.getObjectParamValues(CssClassIconFile.class); } public List<CssClassIconFile> getCssClassIconFile() { return cssClassIconFile; } public List<String> getCssClasss() { List<String> result = new ArrayList<String>(); List<CssClassIconFile> data = getCssClassIconFile(); for (CssClassIconFile cssClassIconFile : data) { result.add(cssClassIconFile.getType()); } return result; } }
1,562
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CssClassIconFile.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/ecms/css/CssClassIconFile.java
/* * Copyright (C) 2003-2023 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.ecms.css; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; public class CssClassIconFile { public static final String DEFAULT_TYPE = "default"; public static final String DEFAULT_CSS = "FileDefault"; private String type; private String cssClass; private String groupFileTypes = ""; private List<String> listGroupFileTypes = null; private static CssClassIconFile defaultType; public CssClassIconFile() { } /** * Return default CssClassIconFile. * * @return */ public static synchronized CssClassIconFile getDefault() { if (defaultType == null) { defaultType = new CssClassIconFile(); defaultType.setType(DEFAULT_TYPE); defaultType.setCssClass(DEFAULT_CSS); } return defaultType; } /** * @return the type */ public String getType() { return type; } /** * @param type the type to set */ public void setType(String type) { this.type = type; } /** * @return the cssClass */ public String getCssClass() { return cssClass; } /** * @param cssClass the cssClass to set */ public void setCssClass(String cssClass) { this.cssClass = cssClass; } /** * @return the groupFileTypes */ public String getGroupFileTypes() { if(groupFileTypes == null) { groupFileTypes = ""; } groupFileTypes = groupFileTypes.replaceAll("\\s", ""); return groupFileTypes; } /** * @param groupFileTypes the groupFileTypes to set */ public void setGroupFileTypes(String groupFileTypes) { this.groupFileTypes = groupFileTypes; } /** * @return the listGroupFileTypes */ public List<String> getListGroupFileTypes() { return listGroupFileTypes; } private void setListGroupFileTypes() { listGroupFileTypes = new ArrayList<String>(Arrays.asList(getGroupFileTypes().split(","))); } /** * To check the fileType has contain in group fileTypes or not * * @param fileType * @return */ public boolean containInGroupFileTypes(String fileType) { if (fileType == null || fileType.isEmpty()){ return false; } if(listGroupFileTypes == null) { setListGroupFileTypes(); } for (String cssClass : listGroupFileTypes) { // if (cssClass.indexOf(fileType) >= 0 || cssClass.indexOf(getFileType(fileType)) >= 0) { return true; } } return false; } private String getFileType(String fileType) { fileType = fileType.replaceAll("\\.", ""); return fileType.substring((fileType.indexOf("/") + 1)).toLowerCase(); } @Override public boolean equals(Object object) { if (object instanceof CssClassIconFile) { CssClassIconFile binCSSFile = (CssClassIconFile) object; return (binCSSFile.getType().equals(type) || binCSSFile.getCssClass().equals(cssClass)) ? true : false; } return false; } @Override public int hashCode() { return Objects.hash(type, cssClass); } @Override public String toString() { return new StringBuilder("{type:'").append(type) .append("', cssClass:'").append(cssClass).append("', groupFileTypes:'") .append(getGroupFileTypes()).append("'}").toString(); } }
4,115
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
HTMLUploadImageProcessorImpl.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/ecms/uploads/HTMLUploadImageProcessorImpl.java
package org.exoplatform.ecms.uploads; import java.io.*; import java.net.URLConnection; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.exoplatform.container.PortalContainer; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.services.cms.impl.Utils; import org.exoplatform.services.cms.link.LinkManager; 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.ext.app.SessionProviderService; 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.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.core.WCMService; import org.exoplatform.social.common.service.HTMLUploadImageProcessor; import org.exoplatform.upload.UploadResource; import org.exoplatform.upload.UploadService; /** * Service to parse an HTML content, extract temporary uploaded files, store * them in a permanent location and replace URLs in the HTML content with the * permanent URLs */ public class HTMLUploadImageProcessorImpl implements HTMLUploadImageProcessor { public static final String IP_REGEX = "(((((25[0-5])|(2[0-4][0-9])|([01]?[0-9]?[0-9]))\\.){3}((25[0-4])|(2[0-4][0-9])|((1?[1-9]?[1-9])|([1-9]0))))|(0\\.){3}0)"; public static final String URL_OR_URI_REGEX = "^(((ht|f)tp(s?)://)" + "(\\w+(:\\w+)?@)?" + "(" + IP_REGEX + "|([0-9a-z_!~*'()-]+\\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\.[a-z]{2,6}" + "|([a-zA-Z][-a-zA-Z0-9]+))" + "(:[0-9]{1,5})?)?" + "((/?)|(/[0-9a-zA-Z_!~*'().;?:@&=+$,%#-]+)+/?)$"; private static final Log LOG = ExoLogger.getLogger(HTMLUploadImageProcessorImpl.class); private static final Pattern UPLOAD_ID_PATTERN = Pattern.compile("uploadId=(([0-9]|[a-f]|[A-F])*)"); private static final Pattern IMPORT_PATTERN = Pattern.compile("[//]|.*?|[-//]"); private static final Pattern UPLOAD_URL_PATTERN = Pattern.compile(URL_OR_URI_REGEX); private static final String IMAGE_URL_REPLACEMENT_PREFIX = "//-"; private static final String IMAGE_URL_REPLACEMENT_SUFFIX = "-//"; private final PortalContainer portalContainer; private final UploadService uploadService; private final RepositoryService repositoryService; private final LinkManager linkManager; private final SessionProviderService sessionProviderService; private final NodeHierarchyCreator nodeHierarchyCreator; private final WCMService wcmService; private String repositoryName; public HTMLUploadImageProcessorImpl(PortalContainer portalContainer, UploadService uploadService, RepositoryService repositoryService, LinkManager linkManager, SessionProviderService sessionProviderService, NodeHierarchyCreator nodeHierarchyCreator, WCMService wcmService) { this.portalContainer = portalContainer; this.uploadService = uploadService; this.repositoryService = repositoryService; this.linkManager = linkManager; this.sessionProviderService = sessionProviderService; this.nodeHierarchyCreator = nodeHierarchyCreator; this.wcmService = wcmService; } private static String getURLToReplace(String body, String uploadId, int uploadIdIndex) { int srcBeginIndex = body.lastIndexOf("\"", uploadIdIndex); int srcEndIndex = -1; if (srcBeginIndex < 0) { srcBeginIndex = body.lastIndexOf("'", uploadIdIndex); if (srcBeginIndex < 0) { LOG.warn("Cannot find src start delimiter in URL for uploadId " + uploadId + " ignore URL replacing"); } else { srcEndIndex = body.indexOf("'", srcBeginIndex + 1); } } else { srcEndIndex = body.indexOf("\"", srcBeginIndex + 1); } String urlToReplace = null; if (srcEndIndex < 0) { LOG.warn("Cannot find src end delimiter in URL for uploadId " + uploadId + " ignore URL replacing"); } else { urlToReplace = body.substring(srcBeginIndex + 1, srcEndIndex); } return urlToReplace; } /** * Process the given HTML content, extract temporary uploaded files, store them * in a permanent location and replace URLs in the HTML content with the * permanent URLs * * @param content The HTML content * @param parentNodeId The parent node to store the images. This node must * exist. * @param imagesSubFolderPath The subpath of the folder under parentNode to * store the images. If the nodes of this path do not exist, they are * automatically created, only if there are images to store. * @return The updated HTML content with the permanent images URLs * @throws IllegalArgumentException When Content location cannot be found or * File cannot be created */ /** * @since 6.3.0 * @deprecated Deprecated, Since the uploaded images will be stored in the document storage by the Ckeditor * */ @Deprecated public String processImages(String content, String parentNodeId, String imagesSubFolderPath) throws IllegalArgumentException { if (StringUtils.isBlank(content)) { return content; } SessionProvider sessionProvider = null; try { sessionProvider = sessionProviderService.getSystemSessionProvider(null); Session session = sessionProvider.getSession( repositoryService.getCurrentRepository() .getConfiguration() .getDefaultWorkspaceName(), repositoryService.getCurrentRepository()); Node parentNode = session.getNodeByUUID(parentNodeId); Set<String> processedUploads = new HashSet<>(); Map<String, String> urlToReplaces = new HashMap<>(); Matcher matcher = UPLOAD_ID_PATTERN.matcher(content); if (!matcher.find()) { return content; } Node imagesFolderNode = parentNode; if (StringUtils.isNotEmpty(imagesSubFolderPath)) { for (String folder : imagesSubFolderPath.split("/")) { if (StringUtils.isBlank(folder)) { continue; } if (imagesFolderNode.hasNode(folder)) { imagesFolderNode = imagesFolderNode.getNode(folder); if (imagesFolderNode.isNodeType(NodetypeConstant.EXO_SYMLINK)) { imagesFolderNode = linkManager.getTarget(imagesFolderNode); } } else if (imagesFolderNode.isNodeType(NodetypeConstant.EXO_SYMLINK)) { imagesFolderNode = linkManager.getTarget(imagesFolderNode).getNode(folder); } else { imagesFolderNode = imagesFolderNode.addNode(folder, "nt:unstructured"); } } } String processedContent = content; do { String uploadId = matcher.group(matcher.groupCount() - 1); if (!processedUploads.contains(uploadId)) { UploadResource uploadedResource = uploadService.getUploadResource(uploadId); if (uploadedResource == null) { continue; } String fileName = uploadedResource.getFileName(); int i = 1; String originalFileName = fileName; while (imagesFolderNode.hasNode(fileName)) { if (originalFileName.contains(".")) { int indexOfPoint = originalFileName.indexOf("."); fileName = originalFileName.substring(0, indexOfPoint) + "(" + i + ")" + originalFileName.substring(indexOfPoint); } else { fileName = originalFileName + "(" + i + ")"; } i++; } fileName = Text.escapeIllegalJcrChars(fileName); fileName = Utils.cleanName(fileName); Node imageNode = imagesFolderNode.addNode(fileName, "nt:file"); Node resourceNode = imageNode.addNode("jcr:content", "nt:resource"); resourceNode.setProperty("jcr:mimeType", uploadedResource.getMimeType()); resourceNode.setProperty("jcr:lastModified", Calendar.getInstance()); String fileDiskLocation = uploadedResource.getStoreLocation(); try (InputStream inputStream = new FileInputStream(fileDiskLocation)) { resourceNode.setProperty("jcr:data", inputStream); resourceNode.getSession().save(); parentNode.getSession().save(); } uploadService.removeUploadResource(uploadId); int uploadIdIndex = matcher.start(); String urlToReplace = getURLToReplace(processedContent, uploadId, uploadIdIndex); if (!UPLOAD_URL_PATTERN.matcher(urlToReplace).matches()) { LOG.warn("Unrecognized URL to replace in activity body {}", urlToReplace); continue; } String fileURI = getJcrURI(imageNode); if (StringUtils.isNotBlank(urlToReplace)) { urlToReplaces.put(urlToReplace, fileURI); processedUploads.add(uploadId); } } } while (matcher.find()); processedContent = replaceUrl(content, urlToReplaces); return processedContent; } catch (RepositoryException e) { throw new IllegalArgumentException("Cannot find File location, content will not be changed", e); } catch (IOException e) { throw new IllegalArgumentException("Cannot create the image, content will not be changed", e); } } /** * @since 6.3.0 * @deprecated Deprecated, Since the uploaded images will be stored in the document storage by the Ckeditor * */ @Override @Deprecated public String processSpaceImages(String content, String spaceGroupId, String imagesSubLocationPath) throws IllegalArgumentException { if (StringUtils.isBlank(content)) { return content; } boolean uploadMode = false; boolean importMode = false; SessionProvider sessionProvider = null; try { sessionProvider = sessionProviderService.getSystemSessionProvider(null); Session session = sessionProvider.getSession("collaboration", repositoryService.getCurrentRepository()); Node groupNode = session.getRootNode().getNode("Groups"); if (spaceGroupId.startsWith("/")) { spaceGroupId = spaceGroupId.substring(1); } Node parentNode = groupNode.getNode(spaceGroupId); Matcher matcher = UPLOAD_ID_PATTERN.matcher(content); Matcher matcherImport = IMPORT_PATTERN.matcher(content); if (matcher.find()) { uploadMode = true; } else { if (matcherImport.find()) { importMode = true; } } if (!uploadMode && !importMode) { return content; } if (parentNode == null) { throw new IllegalArgumentException("Container node for uploaded processed images in HTML content must not be null"); } Node imagesFolderNode = parentNode; if (StringUtils.isNotEmpty(imagesSubLocationPath)) { for (String folder : imagesSubLocationPath.split("/")) { if (imagesFolderNode.canAddMixin("exo:privilegeable")) { imagesFolderNode.addMixin("exo:privilegeable"); } Map<String, String[]> permissions = new HashMap<>(); permissions.put("*:" + "/" + spaceGroupId, PermissionType.ALL); ((ExtendedNode) imagesFolderNode).setPermissions(permissions); if (StringUtils.isBlank(folder)) { continue; } if (imagesFolderNode.hasNode(folder)) { imagesFolderNode = imagesFolderNode.getNode(folder); if (imagesFolderNode.isNodeType(NodetypeConstant.EXO_SYMLINK)) { imagesFolderNode = linkManager.getTarget(imagesFolderNode); } } else if (imagesFolderNode.isNodeType(NodetypeConstant.EXO_SYMLINK)) { imagesFolderNode = linkManager.getTarget(imagesFolderNode).getNode(folder); } else { imagesFolderNode = imagesFolderNode.addNode(folder, "nt:unstructured"); } } } if (uploadMode) { content = createImagesfromUpload(content, imagesFolderNode, parentNode); } if (importMode) { content = createImagesfromImport(content, imagesFolderNode, parentNode); } return content; } catch (RepositoryException e) { throw new IllegalArgumentException("Cannot find File location", e); } catch (IOException e) { throw new IllegalArgumentException("Cannot create the image", e); } } /** * @since 6.3.0 * @deprecated Deprecated, Since the uploaded images will be stored in the document storage by the Ckeditor * */ @Override @Deprecated public String processUserImages(String content, String userId, String imagesSubLocationPath) throws IllegalArgumentException { if (StringUtils.isBlank(content)) { return content; } boolean uploadMode = false; boolean importMode = false; SessionProvider sessionProvider = null; try { sessionProvider = sessionProviderService.getSystemSessionProvider(null); Node parentNode = nodeHierarchyCreator.getUserNode(sessionProvider, userId); Node imagesFolderNode = parentNode; Matcher matcher = UPLOAD_ID_PATTERN.matcher(content); Matcher matcherImport = IMPORT_PATTERN.matcher(content); if (matcher.find()) { uploadMode = true; } else { if (matcherImport.find()) { importMode = true; } } if (!uploadMode && !importMode) { return content; } if (StringUtils.isNotEmpty(imagesSubLocationPath)) { for (String folder : imagesSubLocationPath.split("/")) { if (StringUtils.isBlank(folder)) { continue; } if (imagesFolderNode.hasNode(folder)) { imagesFolderNode = imagesFolderNode.getNode(folder); if (imagesFolderNode.isNodeType(NodetypeConstant.EXO_SYMLINK)) { imagesFolderNode = linkManager.getTarget(imagesFolderNode); } } else if (imagesFolderNode.isNodeType(NodetypeConstant.EXO_SYMLINK)) { imagesFolderNode = linkManager.getTarget(imagesFolderNode).getNode(folder); } else { imagesFolderNode = imagesFolderNode.addNode(folder, "nt:unstructured"); } } } if (uploadMode) { content = createImagesfromUpload(content, imagesFolderNode, parentNode); } if (importMode) { content = createImagesfromImport(content, imagesFolderNode, parentNode); } return content; } catch (IOException e) { throw new IllegalArgumentException("Cannot create the image", e); } catch (Exception e) { throw new IllegalArgumentException("Cannot find user data location", e); } } @Override public void uploadSpaceFile(String filePath, String spaceGroupId, String fileName, String imagesSubLocationPath) throws IllegalArgumentException { if (StringUtils.isBlank(filePath)) { return ; } SessionProvider sessionProvider = null; try { sessionProvider = sessionProviderService.getSystemSessionProvider(null); Session session = sessionProvider.getSession("collaboration", repositoryService.getCurrentRepository()); Node groupNode = session.getRootNode().getNode("Groups"); if (spaceGroupId.startsWith("/")) { spaceGroupId = spaceGroupId.substring(1); } Node folderNode = groupNode.getNode(spaceGroupId); if (folderNode == null) { throw new IllegalArgumentException("Container node for uploaded processed images in HTML content must not be null"); } if (StringUtils.isNotEmpty(imagesSubLocationPath)) { for (String folder : imagesSubLocationPath.split("/")) { if (StringUtils.isBlank(folder)) { continue; } if (folderNode.hasNode(folder)) { folderNode = folderNode.getNode(folder); if (folderNode.isNodeType(NodetypeConstant.EXO_SYMLINK)) { folderNode = linkManager.getTarget(folderNode); } } else if (folderNode.isNodeType(NodetypeConstant.EXO_SYMLINK)) { folderNode = linkManager.getTarget(folderNode).getNode(folder); } else { folderNode = folderNode.addNode(folder, "nt:unstructured"); } } } File file = new File(filePath); if (!file.exists()) { return; } int i = 1; String originalFileName = fileName; while (folderNode.hasNode(fileName)) { if (originalFileName.contains(".")) { int indexOfPoint = originalFileName.indexOf("."); fileName = originalFileName.substring(0, indexOfPoint) + "(" + i + ")" + originalFileName.substring(indexOfPoint); } else { fileName = originalFileName + "(" + i + ")"; } i++; } fileName = Text.escapeIllegalJcrChars(fileName); fileName = Utils.cleanName(fileName); Node imageNode = folderNode.addNode(fileName, "nt:file"); Node resourceNode = imageNode.addNode("jcr:content", "nt:resource"); resourceNode.setProperty("jcr:mimeType", URLConnection.guessContentTypeFromName(file.getName())); resourceNode.setProperty("jcr:lastModified", Calendar.getInstance()); try (InputStream inputStream = new FileInputStream(file)) { resourceNode.setProperty("jcr:data", inputStream); resourceNode.getSession().save(); folderNode.getSession().save(); } } catch (IOException e) { throw new IllegalArgumentException("Cannot create the image", e); } catch (Exception e) { throw new IllegalArgumentException("Cannot find user data location", e); } } @Override public void uploadUserFile(String filePath, String userId, String fileName, String imagesSubLocationPath) throws IllegalArgumentException { if (StringUtils.isBlank(filePath)) { return ; } SessionProvider sessionProvider = null; try { sessionProvider = sessionProviderService.getSystemSessionProvider(null); Node parentNode = nodeHierarchyCreator.getUserNode(sessionProvider, userId); Node folderNode = parentNode; if (StringUtils.isNotEmpty(imagesSubLocationPath)) { for (String folder : imagesSubLocationPath.split("/")) { if (StringUtils.isBlank(folder)) { continue; } if (folderNode.hasNode(folder)) { folderNode = folderNode.getNode(folder); if (folderNode.isNodeType(NodetypeConstant.EXO_SYMLINK)) { folderNode = linkManager.getTarget(folderNode); } } else if (folderNode.isNodeType(NodetypeConstant.EXO_SYMLINK)) { folderNode = linkManager.getTarget(folderNode).getNode(folder); } else { folderNode = folderNode.addNode(folder, "nt:unstructured"); } } } File file = new File(filePath); if (!file.exists()) { return; } int i = 1; String originalFileName = fileName; while (folderNode.hasNode(fileName)) { if (originalFileName.contains(".")) { int indexOfPoint = originalFileName.indexOf("."); fileName = originalFileName.substring(0, indexOfPoint) + "(" + i + ")" + originalFileName.substring(indexOfPoint); } else { fileName = originalFileName + "(" + i + ")"; } i++; } fileName = Text.escapeIllegalJcrChars(fileName); fileName = Utils.cleanName(fileName); Node imageNode = folderNode.addNode(fileName, "nt:file"); Node resourceNode = imageNode.addNode("jcr:content", "nt:resource"); resourceNode.setProperty("jcr:mimeType", URLConnection.guessContentTypeFromName(file.getName())); resourceNode.setProperty("jcr:lastModified", Calendar.getInstance()); try (InputStream inputStream = new FileInputStream(file)) { resourceNode.setProperty("jcr:data", inputStream); resourceNode.getSession().save(); parentNode.getSession().save(); } } catch (IOException e) { throw new IllegalArgumentException("Cannot create the image", e); } catch (Exception e) { throw new IllegalArgumentException("Cannot find user data location", e); } } /** * Process the given HTML content, export Files and replace URLs in the HTML * content with files name * * @param content_ The HTML content * @return The updated HTML content with the images names */ @Override public String processImagesForExport(String content_) throws IllegalArgumentException { SessionProvider sessionProvider = null; try { Map<String, String> urlToReplaces = new HashMap<>(); String content = content_; sessionProvider = sessionProviderService.getSystemSessionProvider(null); String restUploadUrl = "/" + portalContainer.getName() + "/" + portalContainer.getRestContextName() + "/images/" + getRepositoryName() + "/"; while (content.contains(restUploadUrl)) { String check_content = content; String workspace = content.split(restUploadUrl)[1].split("\"")[0]; String nodeIdentifier = workspace.split("/")[1].split("\\?")[0]; workspace = workspace.split("/")[0]; String urlToReplace = restUploadUrl + workspace + "/" + nodeIdentifier; try { Node dataNode = wcmService.getReferencedContent(sessionProvider, workspace, nodeIdentifier); if(dataNode!=null){ String fileName = dataNode.getName(); Node jcrContentNode = dataNode.getNode("jcr:content"); InputStream jcrData = jcrContentNode.getProperty("jcr:data").getStream(); File tempFile = new File(System.getProperty("java.io.tmpdir") + File.separator + fileName); try (OutputStream outputStream = new FileOutputStream(tempFile)) { IOUtils.copy(jcrData, outputStream); } catch (Exception e) { throw new IllegalArgumentException("Cannot create the image", e); } urlToReplaces.put(urlToReplace, IMAGE_URL_REPLACEMENT_PREFIX + tempFile.getName() + IMAGE_URL_REPLACEMENT_SUFFIX); } content = content.replace(urlToReplace, ""); } catch (Exception e) { throw new IllegalArgumentException("Cannot create the image from workspace: "+workspace+" node id "+nodeIdentifier,e); } if(check_content.equals(content)){ break; } } if (!urlToReplaces.isEmpty()) { content_ = replaceUrl(content_, urlToReplaces); } } catch (Exception e) { throw new IllegalArgumentException("Cannot process the content", e); } return content_; } private String replaceUrl(String body, Map<String, String> urlToReplaces) { for (String url : urlToReplaces.keySet()) { while (body.contains(url)) { String check_content = body; body = body.replace(url, urlToReplaces.get(url)); if(body.equals(check_content)){ break; } } } return body; } private String getJcrURI(Node imageNode) throws RepositoryException { if (!imageNode.isNodeType(NodetypeConstant.MIX_REFERENCEABLE)) { imageNode.addMixin(NodetypeConstant.MIX_REFERENCEABLE); } return "/" + portalContainer.getName() + "/" + portalContainer.getRestContextName() + "/images/" + getRepositoryName() + "/" + imageNode.getSession().getWorkspace().getName() + "/" + imageNode.getUUID(); } public String getRepositoryName() { if (repositoryName == null) { try { this.repositoryName = repositoryService.getCurrentRepository().getConfiguration().getName(); } catch (RepositoryException e) { this.repositoryName = repositoryService.getConfig().getDefaultRepositoryName(); } } return repositoryName; } private String createImagesfromUpload(String content, Node imagesFolderNode, Node parentNode) throws RepositoryException, IOException { Set<String> processedUploads = new HashSet<>(); Map<String, String> urlToReplaces = new HashMap<>(); String processedContent = content; Matcher matcher = UPLOAD_ID_PATTERN.matcher(content); matcher.find(); do { String uploadId = matcher.group(matcher.groupCount() - 1); if (!processedUploads.contains(uploadId)) { UploadResource uploadedResource = uploadService.getUploadResource(uploadId); if (uploadedResource == null) { continue; } String fileName = uploadedResource.getFileName(); int i = 1; String originalFileName = fileName; while (imagesFolderNode.hasNode(fileName)) { if (originalFileName.contains(".")) { int indexOfPoint = originalFileName.indexOf("."); fileName = originalFileName.substring(0, indexOfPoint) + "(" + i + ")" + originalFileName.substring(indexOfPoint); } else { fileName = originalFileName + "(" + i + ")"; } i++; } fileName = Text.escapeIllegalJcrChars(fileName); fileName = Utils.cleanName(fileName); Node imageNode = imagesFolderNode.addNode(fileName, "nt:file"); Node resourceNode = imageNode.addNode("jcr:content", "nt:resource"); resourceNode.setProperty("jcr:mimeType", uploadedResource.getMimeType()); resourceNode.setProperty("jcr:lastModified", Calendar.getInstance()); String fileDiskLocation = uploadedResource.getStoreLocation(); try (InputStream inputStream = new FileInputStream(fileDiskLocation)) { resourceNode.setProperty("jcr:data", inputStream); resourceNode.getSession().save(); parentNode.getSession().save(); } uploadService.removeUploadResource(uploadId); int uploadIdIndex = matcher.start(); String urlToReplace = getURLToReplace(processedContent, uploadId, uploadIdIndex); if (!UPLOAD_URL_PATTERN.matcher(urlToReplace).matches()) { LOG.warn("Unrecognized URL to replace in activity body {}", urlToReplace); continue; } String fileURI = getJcrURI(imageNode); if (StringUtils.isNotBlank(urlToReplace)) { urlToReplaces.put(urlToReplace, fileURI); processedUploads.add(uploadId); } } } while (matcher.find()); return replaceUrl(content, urlToReplaces); } private String createImagesfromImport(String content, Node imagesFolderNode, Node parentNode) throws RepositoryException, IOException { Set<String> processedUploads = new HashSet<>(); String processedContent = content; while (processedContent.contains("src=\"" + IMAGE_URL_REPLACEMENT_PREFIX)) { String check_content = processedContent; String fileName = processedContent.split("src=\"//-")[1].split("-//")[0]; if (!processedUploads.contains(fileName)) { File file = new File(System.getProperty("java.io.tmpdir") + File.separator + fileName); if (!file.exists()) { String urlToReplace = IMAGE_URL_REPLACEMENT_PREFIX + fileName + IMAGE_URL_REPLACEMENT_SUFFIX; processedContent = processedContent.replace(urlToReplace, ""); continue; } fileName = file.getName(); int i = 1; String originalFileName = fileName; while (imagesFolderNode.hasNode(fileName)) { if (originalFileName.contains(".")) { int indexOfPoint = originalFileName.indexOf("."); fileName = originalFileName.substring(0, indexOfPoint) + "(" + i + ")" + originalFileName.substring(indexOfPoint); } else { fileName = originalFileName + "(" + i + ")"; } i++; } fileName = Text.escapeIllegalJcrChars(fileName); fileName = Utils.cleanName(fileName); Node imageNode = imagesFolderNode.addNode(fileName, "nt:file"); Node resourceNode = imageNode.addNode("jcr:content", "nt:resource"); resourceNode.setProperty("jcr:mimeType", URLConnection.guessContentTypeFromName(file.getName())); resourceNode.setProperty("jcr:lastModified", Calendar.getInstance()); try (InputStream inputStream = new FileInputStream(file)) { resourceNode.setProperty("jcr:data", inputStream); resourceNode.getSession().save(); parentNode.getSession().save(); } String urlToReplace = IMAGE_URL_REPLACEMENT_PREFIX + file.getName() + IMAGE_URL_REPLACEMENT_SUFFIX; String fileURI = getJcrURI(imageNode); if (StringUtils.isNotBlank(urlToReplace)) { processedContent = processedContent.replace(urlToReplace, fileURI); } file.delete(); } if(processedContent.equals(check_content)){ break; } } return processedContent; } }
30,239
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
EditorSupportPortlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/apps/portlet-editors/src/main/java/org/exoplatform/editors/portlet/EditorSupportPortlet.java
package org.exoplatform.editors.portlet; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import javax.portlet.GenericPortlet; import javax.portlet.PortletException; import javax.portlet.PortletRequestDispatcher; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.PortalContainer; import org.exoplatform.services.cms.documents.DocumentService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.resources.ResourceBundleService; import org.exoplatform.wcm.connector.collaboration.cometd.CometdConfig; import org.exoplatform.wcm.connector.collaboration.cometd.CometdDocumentsService; import org.exoplatform.web.application.JavascriptManager; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.ws.frameworks.json.impl.JsonException; import org.exoplatform.ws.frameworks.json.impl.JsonGeneratorImpl; /** * The Class EditorSupportPortlet. */ public class EditorSupportPortlet extends GenericPortlet { /** The Constant LOG. */ private static final Log LOG = ExoLogger.getLogger(EditorSupportPortlet.class); /** The Constant CLIENT_RESOURCE_PREFIX. */ private static final String CLIENT_RESOURCE_PREFIX = "editors."; /** * Do view. * * @param request the request * @param response the response * @throws IOException Signals that an I/O exception has occurred. * @throws PortletException the portlet exception */ @Override public void doView(RenderRequest request, RenderResponse response) throws IOException, PortletException { try { PortletRequestDispatcher prDispatcher = getPortletContext().getRequestDispatcher("/WEB-INF/pages/editors-admin.jsp"); prDispatcher.include(request, response); WebuiRequestContext context = WebuiRequestContext.getCurrentInstance(); CometdDocumentsService cometdService = ExoContainerContext.getCurrentContainer() .getComponentInstanceOfType(CometdDocumentsService.class); JavascriptManager js = ((WebuiRequestContext) WebuiRequestContext.getCurrentInstance()).getJavascriptManager(); CometdConfig cometdConf = new CometdConfig(cometdService.getCometdServerPath(), cometdService.getUserToken(context.getRemoteUser()), PortalContainer.getCurrentPortalContainerName()); DocumentService documentService = ExoContainerContext.getCurrentContainer() .getComponentInstanceOfType(DocumentService.class); long idleTimeout = documentService.getEditorsIdleTimeout(); js.require("SHARED/editorsupport", "editorsupport") .addScripts("editorsupport.initConfig('" + context.getRemoteUser() + "' ," + cometdConf.toJSON() + ", " + getI18n(request.getLocale()) + ", " + idleTimeout + ");"); } catch (Exception e) { LOG.error("Error processing editor support portlet for user " + request.getRemoteUser(), e); } } /** * Gets the i 18 n. * * @param locale the locale * @return the i 18 n */ protected String getI18n(Locale locale) { String messagesJson; try { ResourceBundleService i18nService = ExoContainerContext.getCurrentContainer() .getComponentInstanceOfType(ResourceBundleService.class); ResourceBundle res = i18nService.getResourceBundle("locale.portlet.EditorsAdmin", locale); Map<String, String> resMap = new HashMap<String, String>(); for (Enumeration<String> keys = res.getKeys(); keys.hasMoreElements();) { String key = keys.nextElement(); String bundleKey; if (key.startsWith(CLIENT_RESOURCE_PREFIX)) { bundleKey = key.substring(CLIENT_RESOURCE_PREFIX.length()); } else { bundleKey = key; } resMap.put(bundleKey, res.getString(key)); } messagesJson = new JsonGeneratorImpl().createJsonObjectFromMap(resMap).toString(); } catch (JsonException e) { LOG.warn("Cannot serialize messages bundle JSON", e); messagesJson = "{}"; } catch (Exception e) { LOG.warn("Cannot build messages bundle", e); messagesJson = "{}"; } return messagesJson; } }
4,561
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
EditorsAdminPortlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/apps/portlet-editors/src/main/java/org/exoplatform/editors/portlet/EditorsAdminPortlet.java
package org.exoplatform.editors.portlet; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.portlet.GenericPortlet; import javax.portlet.PortletException; import javax.portlet.PortletRequestDispatcher; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import org.exoplatform.container.PortalContainer; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.web.application.JavascriptManager; import org.exoplatform.webui.application.WebuiRequestContext; public class EditorsAdminPortlet extends GenericPortlet { /** The Constant LOG. */ private static final Log LOG = ExoLogger.getLogger(EditorsAdminPortlet.class); protected static final String ERROR_RESOURCE_BASE = "editors.admin.error"; @Override public void doView(RenderRequest request, RenderResponse response) throws IOException, PortletException { try { PortletRequestDispatcher prDispatcher = getPortletContext().getRequestDispatcher("/WEB-INF/pages/editors-admin.jsp"); prDispatcher.include(request, response); String providersUrl = buildRestUrl(request.getScheme(), request.getServerName(), request.getServerPort(), "/documents/editors"); String identitiesUrl = buildRestUrl(request.getScheme(), request.getServerName(), request.getServerPort(), "/identity/search"); String settingsJson = new StringBuilder().append("{\"services\": {\"providers\": \"") .append(providersUrl) .append("\",") .append("\"identities\": \"") .append(identitiesUrl) .append("\",") .append("\"errorResourceBase\": \"") .append(ERROR_RESOURCE_BASE) .append("\"}}") .toString(); JavascriptManager js = ((WebuiRequestContext) WebuiRequestContext.getCurrentInstance()).getJavascriptManager(); js.require("SHARED/editorsadmin", "editorsadmin").addScripts("editorsadmin.init(" + settingsJson + ");"); } catch (Exception e) { LOG.error("Error processing editors admin portlet for user " + request.getRemoteUser(), e); } } private String buildRestUrl(String protocol, String hostname, int port, String path) throws MalformedURLException { return new URL(protocol, hostname, port, new StringBuilder("/").append(PortalContainer.getCurrentRestContextName()).append(path).toString()).toString(); } }
3,073
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISearchForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/apps/portlet-search/src/main/java/org/exoplatform/wcm/webui/search/UISearchForm.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. This program is free software; you * can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. This program * is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. You * should have received a copy of the GNU General Public License along with this * program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.search; import java.text.Normalizer; import java.util.ArrayList; import java.util.List; import javax.portlet.PortletPreferences; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.config.DataStorage; import org.exoplatform.portal.config.Query; import org.exoplatform.portal.config.model.PortalConfig; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.services.wcm.search.QueryCriteria; import org.exoplatform.services.wcm.search.ResultNode; import org.exoplatform.services.wcm.search.SiteSearchService; import org.exoplatform.services.wcm.search.base.AbstractPageList; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormHiddenInput; import org.exoplatform.webui.form.UIFormRadioBoxInput; import org.exoplatform.webui.form.UIFormSelectBox; import org.exoplatform.webui.form.UIFormStringInput; /* * Created by The eXo Platform SAS Author : Anh Do Ngoc anh.do@exoplatform.com * Oct 31, 2008 */ @ComponentConfig(lifecycle = UIFormLifecycle.class, events = { @EventConfig(listeners = UISearchForm.SearchActionListener.class) }) public class UISearchForm extends UIForm { /** The template path. */ private String templatePath; /** The resource resolver. */ private ResourceResolver resourceResolver; /** The Constant KEYWORD_INPUT. */ public static final String KEYWORD_INPUT = "keywordInput"; /** The Constant SEARCH_OPTION. */ public static final String SEARCH_OPTION = "searchOption"; /** The Constant DOCUMENT_CHECKING. */ public static final String DOCUMENT_CHECKING = "documentCheckBox"; /** The Constant PAGE_CHECKING. */ public static final String PAGE_CHECKING = "pageCheckBox"; /** The Constant PORTALS_SELECTOR. */ public static final String PORTALS_SELECTOR = "portalSelector"; /** The Constant ALL_OPTION. */ public static final String ALL_OPTION = "all"; /** The Constant SORT_FIELD_HIDDEN_INPUT */ public static final String SORT_FIELD_HIDDEN_INPUT = "sortHiddenInputField"; /** The Constant ORDER_TYPE_HIDDEN_INPUT */ public static final String ORDER_TYPE_HIDDEN_INPUT = "orderTypeHiddenInputField"; /** The Constant MESSAGE_NOT_CHECKED_TYPE_SEARCH. */ public static final String MESSAGE_NOT_CHECKED_TYPE_SEARCH = "UISearchForm.message.not-checked"; /** The Constant MESSAGE_NOT_SUPPORT_KEYWORD. */ public static final String MESSAGE_NOT_SUPPORT_KEYWORD = "UISearchForm.message.keyword-not-support"; /** The Constant MESSAGE_NOT_EMPTY_KEYWORD. */ public static final String MESSAGE_NOT_EMPTY_KEYWORD = "UISearchForm.message.keyword-not-empty"; /** * Instantiates a new uI search form. * * @throws Exception the exception */ @SuppressWarnings("unchecked") public UISearchForm() throws Exception { UIFormStringInput uiKeywordInput = new UIFormStringInput(KEYWORD_INPUT, KEYWORD_INPUT, null); UIFormSelectBox uiPortalSelectBox = new UIFormSelectBox(PORTALS_SELECTOR, PORTALS_SELECTOR, getPortalList()); List<SelectItemOption<String>> searchOptionList = new ArrayList<SelectItemOption<String>>(); SelectItemOption<String> pageOption = new SelectItemOption<String>(PAGE_CHECKING, PAGE_CHECKING); SelectItemOption<String> docOption = new SelectItemOption<String>(DOCUMENT_CHECKING, DOCUMENT_CHECKING); searchOptionList.add(docOption); searchOptionList.add(pageOption); UIFormRadioBoxInput searchOptionRadioBox = new UIFormRadioBoxInput(SEARCH_OPTION, SEARCH_OPTION, searchOptionList); searchOptionRadioBox.setDefaultValue(DOCUMENT_CHECKING); searchOptionRadioBox.setValue(DOCUMENT_CHECKING); addUIFormInput(uiKeywordInput); addUIFormInput(uiPortalSelectBox); addUIFormInput(searchOptionRadioBox); // Hidden fields for storing order criteria from user addUIFormInput(new UIFormHiddenInput(SORT_FIELD_HIDDEN_INPUT, SORT_FIELD_HIDDEN_INPUT, null)); addUIFormInput(new UIFormHiddenInput(ORDER_TYPE_HIDDEN_INPUT, ORDER_TYPE_HIDDEN_INPUT, null)); } /** * Inits the. * * @param templatePath the template path * @param resourceResolver the resource resolver */ public void init(String templatePath, ResourceResolver resourceResolver) { this.templatePath = templatePath; this.resourceResolver = resourceResolver; } /* * (non-Javadoc) * @see org.exoplatform.webui.core.UIComponent#getTemplate() */ public String getTemplate() { return templatePath; } public void setKeyword() { PortalRequestContext portalRequestContext = Util.getPortalRequestContext(); String keyword = portalRequestContext.getRequestParameter("keyword"); if (keyword != null && keyword.length() > 0) { getUIStringInput(UISearchForm.KEYWORD_INPUT).setValue(keyword); } } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIComponent#getTemplateResourceResolver(org. * exoplatform.webui.application.WebuiRequestContext, java.lang.String) */ public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context, String template) { return resourceResolver; } /** * Gets the portal list. * * @return the portal list * @throws Exception the exception */ @SuppressWarnings("unchecked") private List getPortalList() throws Exception { List<SelectItemOption<String>> portals = new ArrayList<SelectItemOption<String>>(); DataStorage service = getApplicationComponent(DataStorage.class); Query<PortalConfig> query = new Query<PortalConfig>(null, null, null, null, PortalConfig.class); List<PortalConfig> list = service.find(query, null).getAll(); portals.add(new SelectItemOption<String>(ALL_OPTION, ALL_OPTION)); for (PortalConfig portalConfig : list) { portals.add(new SelectItemOption<String>(portalConfig.getName(), portalConfig.getName())); } return portals; } /** * The listener interface for receiving searchAction events. The class that is * interested in processing a searchAction event implements this interface, * and the object created with that class is registered with a component using * the component's <code>addSearchActionListener</code> method. When * the searchAction event occurs, that object's appropriate * method is invoked. * */ public static class SearchActionListener extends EventListener<UISearchForm> { /* * (non-Javadoc) * @see * org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui * .event.Event) */ @SuppressWarnings({ "deprecation" }) public void execute(Event<UISearchForm> event) throws Exception { UISearchForm uiSearchForm = event.getSource(); PortletRequestContext portletRequestContext = (PortletRequestContext) event.getRequestContext(); PortletPreferences portletPreferences = portletRequestContext.getRequest().getPreferences(); UIApplication uiApp = uiSearchForm.getAncestorOfType(UIApplication.class); SiteSearchService siteSearchService = uiSearchForm.getApplicationComponent(SiteSearchService.class); UISearchPageLayout uiSearchPageContainer = uiSearchForm.getParent(); UISearchResult uiSearchResult = uiSearchPageContainer.getChild(UISearchResult.class); UIFormStringInput uiKeywordInput = uiSearchForm.getUIStringInput(UISearchForm.KEYWORD_INPUT); UIFormSelectBox uiPortalSelectBox = uiSearchForm.getUIFormSelectBox(UISearchForm.PORTALS_SELECTOR); String keyword = uiKeywordInput.getValue(); UIFormRadioBoxInput uiSearchOptionRadioBox = uiSearchForm.getUIFormRadioBoxInput(SEARCH_OPTION); String searchOption = uiSearchOptionRadioBox.getValue(); String sortField = ((UIFormHiddenInput)uiSearchForm.getUIInput(UISearchForm.SORT_FIELD_HIDDEN_INPUT)).getValue(); String orderType = ((UIFormHiddenInput)uiSearchForm.getUIInput(UISearchForm.ORDER_TYPE_HIDDEN_INPUT)).getValue(); boolean pageChecked = false; boolean documentChecked = false; if (PAGE_CHECKING.equals(searchOption)) { pageChecked = true; } else if (DOCUMENT_CHECKING.equals(searchOption)) { documentChecked = true; } uiSearchResult.clearResult(); uiSearchResult.setKeyword(keyword); if (keyword == null || keyword.trim().length() == 0) { uiApp.addMessage(new ApplicationMessage(MESSAGE_NOT_EMPTY_KEYWORD, null, ApplicationMessage.WARNING)); portletRequestContext.addUIComponentToUpdateByAjax(uiSearchResult); return; } if (!pageChecked && !documentChecked) { uiApp.addMessage(new ApplicationMessage(MESSAGE_NOT_CHECKED_TYPE_SEARCH, null, ApplicationMessage.WARNING)); return; } String resultType = null; if (pageChecked) { resultType = UIWCMSearchPortlet.SEARCH_PAGE_MODE; } else { resultType = UIWCMSearchPortlet.SEARCH_CONTENT_MODE; } String newKey = event.getRequestContext().getRequestParameter(OBJECTID); if (newKey != null) { keyword = newKey; uiKeywordInput.setValue(newKey); } keyword = Normalizer.normalize(keyword, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); //keyword = keyword.replaceAll("'","''"); uiSearchResult.setResultType(resultType); String selectedPortal = uiPortalSelectBox.getValue(); QueryCriteria queryCriteria = new QueryCriteria(); List<String> documentNodeTypes = new ArrayList<String>(); if (documentChecked) { TemplateService templateService = WCMCoreUtils.getService(TemplateService.class); documentNodeTypes = templateService.getAllDocumentNodeTypes(); selectedPortal = Util.getPortalRequestContext().getPortalOwner(); } else { documentNodeTypes.add("gtn:language"); documentNodeTypes.add("exo:pageMetadata"); queryCriteria.setFulltextSearchProperty(new String[] {"exo:metaKeywords", "exo:metaDescription", "gtn:name"}); } queryCriteria.setContentTypes(documentNodeTypes.toArray(new String[documentNodeTypes.size()])); queryCriteria.setSiteName(selectedPortal); queryCriteria.setKeyword( org.exoplatform.services.cms.impl.Utils.escapeIllegalCharacterInQuery(keyword)); if (documentChecked) { queryCriteria.setSearchDocument(true); queryCriteria.setSearchWebContent(true); } else { queryCriteria.setSearchDocument(false); queryCriteria.setSearchWebContent(false); } queryCriteria.setSearchWebpage(pageChecked); queryCriteria.setLiveMode(WCMComposer.MODE_LIVE.equals(Utils.getCurrentMode())); int itemsPerPage = Integer.parseInt(portletPreferences.getValue(UIWCMSearchPortlet.ITEMS_PER_PAGE, null)); queryCriteria.setPageMode(portletPreferences.getValue(UIWCMSearchPortlet.PAGE_MODE, null)); queryCriteria.setSortBy(sortField); queryCriteria.setOrderBy(orderType); try { AbstractPageList<ResultNode> pageList = null; if (pageChecked) { pageList = siteSearchService.searchPageContents(WCMCoreUtils.getSystemSessionProvider(), queryCriteria, portletRequestContext.getLocale(), itemsPerPage, false); } else { pageList = siteSearchService.searchSiteContents(WCMCoreUtils.getUserSessionProvider(), queryCriteria, portletRequestContext.getLocale(), itemsPerPage, false); } uiSearchResult.setPageList(pageList); float timeSearch = pageList.getQueryTime() / 1000; uiSearchResult.setSearchTime(timeSearch); if (pageList.getAvailable() <= 0) { String suggestion = pageList.getSpellSuggestion(); uiSearchResult.setSuggestion(suggestion); uiSearchForm.setSubmitAction(suggestion); } portletRequestContext.addUIComponentToUpdateByAjax(uiSearchResult); } catch (Exception e) { uiApp.addMessage(new ApplicationMessage(MESSAGE_NOT_SUPPORT_KEYWORD, null, ApplicationMessage.WARNING)); return; } portletRequestContext.addUIComponentToUpdateByAjax(uiSearchPageContainer); } } public UIFormRadioBoxInput getUIFormRadioBoxInput(String name) { return findComponentById(name); } }
15,226
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIWCMSearchPortlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/apps/portlet-search/src/main/java/org/exoplatform/wcm/webui/search/UIWCMSearchPortlet.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. This program is free software; you * can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. This program * is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. You * should have received a copy of the GNU General Public License along with this * program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.search; import javax.portlet.PortletMode; import org.exoplatform.wcm.webui.search.config.UIPortletConfig; import org.exoplatform.webui.application.WebuiApplication; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.UIPortletApplication; import org.exoplatform.webui.core.lifecycle.UIApplicationLifecycle; /* * Created by The eXo Platform SAS Author : Anh Do Ngoc anh.do@exoplatform.com * Oct 31, 2008 */ @ComponentConfig(lifecycle = UIApplicationLifecycle.class) public class UIWCMSearchPortlet extends UIPortletApplication { /** The mode. */ private PortletMode mode = PortletMode.VIEW; /** The Constant SEARCH_FORM_TEMPLATE_PATH. */ public static final String SEARCH_FORM_TEMPLATE_PATH = "searchFormTemplatePath"; /** The Constant SEARCH_RESULT_TEMPLATE_PATH. */ public static final String SEARCH_RESULT_TEMPLATE_PATH = "searchResultTemplatePath"; /** The Constant SEARCH_PAGINATOR_TEMPLATE_PATH. */ public static final String SEARCH_PAGINATOR_TEMPLATE_PATH = "searchPaginatorTemplatePath"; /** The Constant SEARCH_PAGE_LAYOUT_TEMPLATE_PATH. */ public static final String SEARCH_PAGE_LAYOUT_TEMPLATE_PATH = "searchPageLayoutTemplatePath"; /** The Constant REPOSITORY. */ public static final String REPOSITORY = "repository"; /** The Constant WORKSPACE. */ public static final String WORKSPACE = "workspace"; /** The Constant ITEMS_PER_PAGE. */ public final static String ITEMS_PER_PAGE = "itemsPerPage"; /** The Constant PAGE_MODE. */ public final static String PAGE_MODE = "pageMode"; /** The Constant SHOW_DATE_CREATED. */ public final static String BASE_PATH = "basePath"; /** The Constant DETAIL_PARAMETER_NAME. */ public final static String DETAIL_PARAMETER_NAME = "detailParameterName"; /** Search Page Mode **/ public static final String SEARCH_PAGE_MODE = "Page"; /** Search Content Mode **/ public static final String SEARCH_CONTENT_MODE = "Document"; /** * Instantiates a new uIWCM search portlet. * * @throws Exception the exception */ public UIWCMSearchPortlet() throws Exception { activateMode(mode); } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIPortletApplication#processRender(org.exoplatform * .webui.application.WebuiApplication, * org.exoplatform.webui.application.WebuiRequestContext) */ public void processRender(WebuiApplication app, WebuiRequestContext context) throws Exception { PortletRequestContext pContext = (PortletRequestContext) context; PortletMode newMode = pContext.getApplicationMode(); if (!mode.equals(newMode)) { activateMode(newMode); mode = newMode; } super.processRender(app, context); } /** * Activate mode. * * @param mode the mode * @throws Exception the exception */ private void activateMode(PortletMode mode) throws Exception { getChildren().clear(); addChild(UIPopupContainer.class, null, "UISearchedContentEdittingPopup"); if (PortletMode.VIEW.equals(mode)) { addChild(UISearchPageLayout.class, null, UIPortletApplication.VIEW_MODE); } else if (PortletMode.EDIT.equals(mode)) { addChild(UIPortletConfig.class, null, UIPortletApplication.EDIT_MODE); } } }
4,476
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISearchBox.java
/FileExtraction/Java_unseen/exoplatform_ecms/apps/portlet-search/src/main/java/org/exoplatform/wcm/webui/search/UISearchBox.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. This program is free software; you * can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. This program * is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. You * should have received a copy of the GNU General Public License along with this * program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.search; import org.exoplatform.ecm.resolver.JCRResourceResolver; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.mop.SiteType; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.web.url.navigation.NavigationResource; import org.exoplatform.web.url.navigation.NodeURL; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormStringInput; /* * Created by The eXo Platform SAS Author : Anh Do Ngoc anh.do@exoplatform.com * Oct 31, 2008 */ @ComponentConfig( lifecycle = UIFormLifecycle.class, events = { @EventConfig(listeners = UISearchBox.SearchActionListener.class) } ) public class UISearchBox extends UIForm { /** The template path. */ private String templatePath; /** The Constant KEYWORD_INPUT. */ public static final String KEYWORD_INPUT = "keywordInput"; /** The Constant PORTAL_NAME_PARAM. */ public static final String PORTAL_NAME_PARAM = "portal"; /** The Constant KEYWORD_PARAM. */ public static final String KEYWORD_PARAM = "keyword"; /** * Instantiates a new uI search box. * * @throws Exception the exception */ public UISearchBox() throws Exception { UIFormStringInput uiKeywordInput = new UIFormStringInput(KEYWORD_INPUT, KEYWORD_INPUT, null); addChild(uiKeywordInput); } /** * Sets the template path. * * @param templatePath the new template path */ public void setTemplatePath(String templatePath) { this.templatePath = templatePath; } /* * (non-Javadoc) * @see org.exoplatform.webui.core.UIComponent#getTemplate() */ public String getTemplate() { return templatePath; } public ResourceResolver getTemplateResourceResolver() { try { DMSConfiguration dmsConfiguration = getApplicationComponent(DMSConfiguration.class); String workspace = dmsConfiguration.getConfig().getSystemWorkspace(); return new JCRResourceResolver(workspace); } catch (Exception e) { return null; } } /** * The listener interface for receiving searchAction events. The class that is * interested in processing a searchAction event implements this interface, * and the object created with that class is registered with a component using * the component's * <code>addSearchActionListener</code> method. When the searchAction * event occurs, that object's appropriate method is invoked. */ public static class SearchActionListener extends EventListener<UISearchBox> { /* * (non-Javadoc) * @see * org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui * .event.Event) */ public void execute(Event<UISearchBox> event) throws Exception { UISearchBox uiSearchBox = event.getSource(); String keyword = uiSearchBox.getUIStringInput(UISearchBox.KEYWORD_INPUT).getValue(); String portalName = Util.getPortalRequestContext().getPortalOwner(); PortalRequestContext prContext = Util.getPortalRequestContext(); prContext.setResponseComplete(true); NodeURL nodeURL = Util.getPortalRequestContext().createURL(NodeURL.TYPE); NavigationResource resource = new NavigationResource(SiteType.PORTAL, portalName, "searchResult"); nodeURL.setResource(resource); nodeURL.setQueryParameterValue(PORTAL_NAME_PARAM, portalName); nodeURL.setQueryParameterValue(KEYWORD_PARAM, keyword); prContext.getResponse().sendRedirect(nodeURL.toString()); } } }
4,748
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISearchPageLayout.java
/FileExtraction/Java_unseen/exoplatform_ecms/apps/portlet-search/src/main/java/org/exoplatform/wcm/webui/search/UISearchPageLayout.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.search; import javax.portlet.PortletMode; import javax.portlet.PortletPreferences; import org.exoplatform.ecm.resolver.JCRResourceResolver; import org.exoplatform.portal.webui.container.UIContainer; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.lifecycle.Lifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /* * Created by The eXo Platform SAS Author : Anh Do Ngoc anh.do@exoplatform.com * Oct 31, 2008 */ @ComponentConfig( lifecycle = Lifecycle.class, events = { @EventConfig(listeners = UISearchPageLayout.QuickEditActionListener.class) } ) public class UISearchPageLayout extends UIContainer { /** The Constant SEARCH_FORM. */ public static final String SEARCH_FORM = "uiSearchForm"; /** The Constant SEARCH_RESULT. */ public static final String SEARCH_RESULT = "uiSearchResult"; /** * Instantiates a new uI search page layout. * * @throws Exception the exception */ public UISearchPageLayout() throws Exception { WebuiRequestContext context = WebuiRequestContext.getCurrentInstance(); UISearchForm uiSearchForm = addChild(UISearchForm.class, null, null); UISearchResult uiSearchResult = addChild(UISearchResult.class, null, null); String searchFormTemplatePath = getTemplatePath(UIWCMSearchPortlet.SEARCH_FORM_TEMPLATE_PATH); uiSearchForm.init(searchFormTemplatePath, getTemplateResourceResolver(context, searchFormTemplatePath)); String searchResultTemplatePath = getTemplatePath(UIWCMSearchPortlet.SEARCH_RESULT_TEMPLATE_PATH); uiSearchResult.init(searchResultTemplatePath, getTemplateResourceResolver(context, searchResultTemplatePath)); } /** * Gets the portlet preference. * * @return the portlet preference */ private PortletPreferences getPortletPreference() { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); return portletRequestContext.getRequest().getPreferences(); } /** * Gets the template path. * * @param templateType the template type * * @return the template path */ private String getTemplatePath(String templateType) { return getPortletPreference().getValue(templateType, null); } /* * (non-Javadoc) * @see org.exoplatform.portal.webui.portal.UIPortalComponent#getTemplate() */ public String getTemplate() { String template = getPortletPreference().getValue(UIWCMSearchPortlet.SEARCH_PAGE_LAYOUT_TEMPLATE_PATH, null); return template; } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIComponent#getTemplateResourceResolver(org. * exoplatform.webui.application.WebuiRequestContext, java.lang.String) */ public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context, String template) { try { DMSConfiguration dmsConfiguration = getApplicationComponent(DMSConfiguration.class); String workspace = dmsConfiguration.getConfig().getSystemWorkspace(); return new JCRResourceResolver(workspace); } catch (Exception e) { return null; } } /** * Gets the portlet id. * * @return the portlet id */ public String getPortletId() { PortletRequestContext pContext = (PortletRequestContext) WebuiRequestContext.getCurrentInstance(); return pContext.getWindowId(); } /** * The listener interface for receiving quickEditAction events. The class that * is interested in processing a quickEditAction event implements this * interface, and the object created with that class is registered with a * component using the component's * <code>addQuickEditActionListener</code> method. When * the quickEditAction event occurs, that object's appropriate * method is invoked. */ public static class QuickEditActionListener extends EventListener<UISearchPageLayout> { /* * (non-Javadoc) * @see * org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui * .event.Event) */ public void execute(Event<UISearchPageLayout> event) throws Exception { PortletRequestContext context = (PortletRequestContext) event.getRequestContext(); context.setApplicationMode(PortletMode.EDIT); } } }
5,623
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISearchResult.java
/FileExtraction/Java_unseen/exoplatform_ecms/apps/portlet-search/src/main/java/org/exoplatform/wcm/webui/search/UISearchResult.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.search; import java.text.DateFormat; import java.text.Normalizer; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashSet; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; import javax.jcr.Node; import javax.jcr.Session; import javax.jcr.Value; import javax.portlet.PortletPreferences; import javax.portlet.PortletRequest; import org.exoplatform.commons.utils.ISO8601; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.utils.ObjectPageList; import org.exoplatform.commons.utils.PageList; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.mop.SiteType; import org.exoplatform.portal.webui.container.UIContainer; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.portal.LivePortalManagerService; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.services.wcm.search.QueryCriteria; import org.exoplatform.services.wcm.search.ResultNode; import org.exoplatform.services.wcm.search.SiteSearchService; import org.exoplatform.services.wcm.search.base.AbstractPageList; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.paginator.UICustomizeablePaginator; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.web.url.navigation.NavigationResource; import org.exoplatform.web.url.navigation.NodeURL; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.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.lifecycle.Lifecycle; import org.exoplatform.webui.form.UIFormHiddenInput; import org.exoplatform.webui.form.UIFormRadioBoxInput; /* * Created by The eXo Platform SAS Author : Anh Do Ngoc anh.do@exoplatform.com * Oct 31, 2008 */ @SuppressWarnings("deprecation") @ComponentConfigs( { @ComponentConfig(lifecycle = Lifecycle.class), @ComponentConfig(type = UICustomizeablePaginator.class, events = @EventConfig(listeners = UICustomizeablePaginator.ShowPageActionListener.class)) }) public class UISearchResult extends UIContainer { /** The template path. */ private String templatePath; /** The resource resolver. */ private ResourceResolver resourceResolver; /** The ui paginator. */ private UICustomizeablePaginator uiPaginator; /** The keyword. */ private String keyword; /** The result type. */ private String resultType; /** The suggestion. */ private String suggestion; /** The suggestion. */ private String suggestionURL; /** The PageMode */ private String pageMode; /** The date formatter. */ private SimpleDateFormat dateFormatter = new SimpleDateFormat(ISO8601.SIMPLE_DATETIME_FORMAT); /** The search time. */ private float searchTime; /** The search result in "More" mode */ private List<ResultNode> moreListResult; /** The page that already queried (used only in "More" mode */ private Set<Integer> morePageSet; /** The Constant PARAMETER_REGX. */ public final static String PARAMETER_REGX = "(portal=.*)&(keyword=.*)"; /** The Constant RESULT_NOT_FOUND. */ public final static String RESULT_NOT_FOUND = "UISearchResult.msg.result-not-found"; /** * Inits the. * * @param templatePath the template path * @param resourceResolver the resource resolver * @throws Exception the exception */ public void init(String templatePath, ResourceResolver resourceResolver) throws Exception { PortletRequestContext portletRequestContext = (PortletRequestContext) WebuiRequestContext.getCurrentInstance(); PortletPreferences portletPreferences = portletRequestContext.getRequest().getPreferences(); String paginatorTemplatePath = portletPreferences.getValue(UIWCMSearchPortlet.SEARCH_PAGINATOR_TEMPLATE_PATH, null); this.pageMode = portletPreferences.getValue(UIWCMSearchPortlet.PAGE_MODE, SiteSearchService.PAGE_MODE_NONE); this.templatePath = templatePath; this.resourceResolver = resourceResolver; uiPaginator = addChild(UICustomizeablePaginator.class, null, null); uiPaginator.setTemplatePath(paginatorTemplatePath); uiPaginator.setResourceResolver(resourceResolver); uiPaginator.setPageMode(pageMode); clearResult(); } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIComponent#processRender(org.exoplatform.webui * .application.WebuiRequestContext) */ public void processRender(WebuiRequestContext context) throws Exception { PortletRequestContext porletRequestContext = (PortletRequestContext) context; PortletPreferences portletPreferences = porletRequestContext.getRequest().getPreferences(); if (resultType == null || resultType.trim().length() == 0) { resultType = "Document"; } PortalRequestContext portalRequestContext = Util.getPortalRequestContext(); String portal = portalRequestContext.getRequestParameter("portal"); String keyword = portalRequestContext.getRequestParameter("keyword"); if ((portal != null) && (keyword != null) && (keyword.length() > 0)) { UISearchPageLayout uiSearchPageContainer = getAncestorOfType(UISearchPageLayout.class); UISearchForm searchForm = uiSearchPageContainer.getChild(UISearchForm.class); // searchForm.getUIFormSelectBox(UISearchForm.PORTALS_SELECTOR).setSelectedValues(new // String[] {portal}); searchForm.getUIStringInput(UISearchForm.KEYWORD_INPUT).setValue(keyword); if (searchForm.getUIFormSelectBox(UISearchForm.PORTALS_SELECTOR).getValue() != null) { portal = searchForm.getUIFormSelectBox(UISearchForm.PORTALS_SELECTOR).getValue(); } if (searchForm.getUIStringInput(UISearchForm.KEYWORD_INPUT).getValue() != null) { keyword = searchForm.getUIStringInput(UISearchForm.KEYWORD_INPUT).getValue(); } setKeyword(keyword); keyword = Normalizer.normalize(keyword, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); SiteSearchService siteSearchService = getApplicationComponent(SiteSearchService.class); QueryCriteria queryCriteria = new QueryCriteria(); UIFormRadioBoxInput searchOption = searchForm.getUIFormRadioBoxInput(UISearchForm.SEARCH_OPTION); boolean isSearchDocument = (searchOption.getValue().equals(UISearchForm.DOCUMENT_CHECKING)); boolean isWebPage = (searchOption.getValue().equals(UISearchForm.PAGE_CHECKING)); List<String> documentNodeTypes = new ArrayList<String>(); if (isSearchDocument) { TemplateService templateService = WCMCoreUtils.getService(TemplateService.class); documentNodeTypes = templateService.getAllDocumentNodeTypes(); portal = Util.getPortalRequestContext().getPortalOwner(); resultType = "Document"; } else { documentNodeTypes.add("gtn:language"); documentNodeTypes.add("exo:pageMetadata"); queryCriteria.setFulltextSearchProperty(new String[] {"exo:metaKeywords", "exo:metaDescription", "gtn:name"}); resultType = "Page"; } String pageMode = portletPreferences.getValue(UIWCMSearchPortlet.PAGE_MODE, SiteSearchService.PAGE_MODE_NONE); queryCriteria.setContentTypes(documentNodeTypes.toArray(new String[documentNodeTypes.size()])); queryCriteria.setSiteName(portal); queryCriteria.setKeyword( org.exoplatform.services.cms.impl.Utils.escapeIllegalCharacterInQuery(keyword).toLowerCase()); queryCriteria.setSearchWebpage(isWebPage); queryCriteria.setSearchDocument(isSearchDocument); queryCriteria.setSearchWebContent(isSearchDocument); queryCriteria.setPageMode(pageMode); queryCriteria.setLiveMode(WCMComposer.MODE_LIVE.equals(Utils.getCurrentMode())); queryCriteria.setSortBy(this.getSortField()); queryCriteria.setOrderBy(this.getOrderType()); int itemsPerPage = Integer.parseInt(portletPreferences.getValue(UIWCMSearchPortlet.ITEMS_PER_PAGE, null)); try { AbstractPageList<ResultNode> pageList = null; if (isWebPage) { pageList = siteSearchService.searchPageContents(WCMCoreUtils.getSystemSessionProvider(), queryCriteria, porletRequestContext.getLocale(), itemsPerPage, false); } else { pageList = siteSearchService.searchSiteContents(WCMCoreUtils.getUserSessionProvider(), queryCriteria, porletRequestContext.getLocale(), itemsPerPage, false); } setSearchTime(pageList.getQueryTime() / 1000); setSuggestion(pageList.getSpellSuggestion()); if (pageList.getAvailable() <= 0) { String suggestion = pageList.getSpellSuggestion(); setSuggestionURL(suggestion); searchForm.setSubmitAction(suggestion); } setPageList(pageList); } catch (Exception e) { UIApplication uiApp = getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage(UISearchForm.MESSAGE_NOT_SUPPORT_KEYWORD, null, ApplicationMessage.WARNING)); } } super.processRender(context); } /** * Sets the page list. * * @param dataPageList the new page list */ @SuppressWarnings("unchecked") public void setPageList(PageList dataPageList) { uiPaginator.setPageList(dataPageList); moreListResult = new ArrayList<ResultNode>(); morePageSet = new HashSet<Integer>(); } /** * Gets the total item. * * @return the total item */ public int getTotalItem() { return uiPaginator.getPageList().getAvailable(); } /** * Gets the items per page. * * @return the items per page */ public int getItemsPerPage() { return uiPaginator.getPageList().getPageSize(); } /** * Gets the current page. * * @return the current page */ public int getCurrentPage() { return uiPaginator.getCurrentPage(); } /** * Gets the page mode * @return the page mode */ public String getPageMode() { return pageMode; } /* * (non-Javadoc) * @see org.exoplatform.portal.webui.portal.UIPortalComponent#getTemplate() */ public String getTemplate() { return templatePath; } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIComponent#getTemplateResourceResolver(org. * exoplatform.webui.application.WebuiRequestContext, java.lang.String) */ public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context, String template) { return resourceResolver; } /** * Gets the current page data. * * @return the current page data * @throws Exception the exception */ @SuppressWarnings("unchecked") public List getCurrentPageData() throws Exception { return uiPaginator.getCurrentPageData(); } /** * Gets the title. * * @param node the node * @return the title * @throws Exception the exception */ public String getTitle(Node node) throws Exception { return org.exoplatform.ecm.webui.utils.Utils.getTitle(node); } /** * Gets the uRL. * * @param node the node * @return the uRL * @throws Exception the exception */ public List<String> getURLs(Node node) throws Exception { List<String> urls = new ArrayList<String>(); if (!node.hasProperty("publication:navigationNodeURIs")) { urls.add(getURL(node)); } else { for (Value value : node.getProperty("publication:navigationNodeURIs").getValues()) { urls.add(value.getString()); } } return urls; } /** * Gets the published node uri. * * @param navNodeURI the nav node uri * @return the published node uri */ public String getPublishedNodeURI(String navNodeURI) { PortalRequestContext portalRequestContext = Util.getPortalRequestContext(); PortletRequest portletRequest = getPortletRequest(); StringBuffer baseURI = new StringBuffer(); baseURI.append(portletRequest.getScheme()).append("://").append(portletRequest.getServerName()); if (portletRequest.getServerPort() != 80) { baseURI.append(":").append(String.format("%s", portletRequest.getServerPort())); } if (navNodeURI.startsWith(baseURI.toString())) return navNodeURI; NodeURL nodeURL = portalRequestContext.createURL(NodeURL.TYPE); NavigationResource resource = new NavigationResource(portalRequestContext.getSiteType(), portalRequestContext.getSiteName(), navNodeURI); nodeURL.setResource(resource); return baseURI + nodeURL.toString(); } /** * Gets the uRL. * * @param node the node * @return the uRL * @throws Exception the exception */ public String getURL(Node node) throws Exception { PortletRequest portletRequest = getPortletRequest(); PortletPreferences portletPreferences = portletRequest.getPreferences(); String repository = WCMCoreUtils.getRepository().getConfiguration().getName(); String workspace = portletPreferences.getValue(UIWCMSearchPortlet.WORKSPACE, null); String basePath = portletPreferences.getValue(UIWCMSearchPortlet.BASE_PATH, null); String detailParameterName = portletPreferences.getValue(UIWCMSearchPortlet.DETAIL_PARAMETER_NAME, null); StringBuffer path = new StringBuffer(); path.append("/").append(repository).append("/").append(workspace); NodeURL nodeURL = Util.getPortalRequestContext().createURL(NodeURL.TYPE); NavigationResource resource = new NavigationResource(SiteType.PORTAL, Util.getPortalRequestContext() .getPortalOwner(), basePath); nodeURL.setResource(resource); if (node.isNodeType("nt:frozenNode")) { String uuid = node.getProperty("jcr:frozenUuid").getString(); Node originalNode = node.getSession().getNodeByUUID(uuid); path.append(originalNode.getPath()); nodeURL.setQueryParameterValue("version", node.getParent().getName()); } else { path.append(node.getPath()); } nodeURL.setQueryParameterValue(detailParameterName, path.toString()); nodeURL.setSchemeUse(true); return nodeURL.toString(); } private PortletRequest getPortletRequest() { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); return portletRequestContext.getRequest(); } /** * Gets the created date. * * @param node the node * @return the created date * @throws Exception the exception */ public String getCreatedDate(Node node) throws Exception { if (node.hasProperty("exo:dateCreated")) { Calendar calendar = node.getProperty("exo:dateCreated").getValue().getDate(); return dateFormatter.format(calendar.getTime()); } return null; } /** * Gets the mofified date of search result node. * * @param node the node * @return the mofified date * @throws Exception the exception */ private String getModifiedDate(Node node) throws Exception { Calendar calendar = node.hasProperty(NodetypeConstant.EXO_LAST_MODIFIED_DATE) ? node.getProperty(NodetypeConstant.EXO_LAST_MODIFIED_DATE).getDate() : node.getProperty(NodetypeConstant.EXO_DATE_CREATED).getDate(); DateFormat simpleDateFormat = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.FULL, SimpleDateFormat.SHORT); return simpleDateFormat.format(calendar.getTime()); } /** * Checks if is show paginator. * * @return true, if is show paginator * @throws Exception the exception */ public boolean isShowPaginator() throws Exception { PortletPreferences portletPreferences = ((PortletRequestContext) WebuiRequestContext.getCurrentInstance()).getRequest() .getPreferences(); String itemsPerPage = portletPreferences.getValue(UIWCMSearchPortlet.ITEMS_PER_PAGE, null); int totalItems = uiPaginator.getTotalItems(); if (totalItems > Integer.parseInt(itemsPerPage)) { return true; } return false; } /** * Gets the search time. * * @return the search time */ public float getSearchTime() { return searchTime; } /** * Sets the search time. * * @param searchTime the new search time */ public void setSearchTime(float searchTime) { this.searchTime = searchTime; } /** * Gets the suggestion. * * @return the suggestion */ public String getSuggestion() { return suggestion; } /** * Sets the suggestion. * * @param suggestion the suggestion */ public void setSuggestion(String suggestion) { this.suggestion = suggestion; } /** * Gets the suggestion URL. * * @return the suggestion URL */ public String getSuggestionURL() { return suggestionURL; } /** * Sets the suggestion URL. * * @param suggestionURL the suggestion url */ public void setSuggestionURL(String suggestionURL) { this.suggestionURL = suggestionURL; } /** * Gets the keyword. * * @return the keyword */ public String getKeyword() { return this.keyword; } /** * Sets the keyword. * * @param keyword the new keyword */ public void setKeyword(String keyword) { this.keyword = keyword; } /** * Gets the result type. * * @return the result type */ public String getResultType() { return this.resultType; } /** * Sets the result type. * * @param resultType the new result type */ public void setResultType(String resultType) { this.resultType = resultType; } /** * Gets the number of page. * * @return the number of page */ public int getNumberOfPage() { return uiPaginator.getPageList().getAvailablePage(); } /** * Clears the displayed result list */ @SuppressWarnings("unchecked") public void clearResult() { moreListResult = new ArrayList<ResultNode>(); morePageSet = new HashSet<Integer>(); PortletPreferences portletPreferences = ((PortletRequestContext) WebuiRequestContext.getCurrentInstance()).getRequest() .getPreferences(); String itemsPerPage = portletPreferences.getValue(UIWCMSearchPortlet.ITEMS_PER_PAGE, null); setPageList(new ObjectPageList(new ArrayList<ResultNode>(), Integer.parseInt(itemsPerPage))); } /** * Gets the real node list to display * * @return the real node list */ public List<ResultNode> getRealCurrentPageData() throws Exception { int currentPage = getCurrentPage(); if (SiteSearchService.PAGE_MODE_MORE.equals(pageMode)) { if (!morePageSet.contains(currentPage)) { morePageSet.add(currentPage); moreListResult.addAll(getCurrentPageData()); } } return SiteSearchService.PAGE_MODE_MORE.equals(pageMode) ? moreListResult : getCurrentPageData(); } /** * Get string used to describe search result node. * * @param resultNode ResultNode * @return result node description * @throws Exception */ private String getDetail(ResultNode resultNode) throws Exception { Node realNode = org.exoplatform.wcm.webui.Utils.getRealNode(resultNode.getNode()); String resultType = this.getResultType(); if (UIWCMSearchPortlet.SEARCH_CONTENT_MODE.equals(resultType)) { return WCMCoreUtils.getService(LivePortalManagerService.class).getLivePortalByChild(realNode).getName() .concat(org.exoplatform.services.cms.impl.Utils.fileSize(realNode)) .concat(" - ") .concat(getModifiedDate(realNode)); } else { return resultNode.getName() .concat(" - ") .concat(resultNode.getUserNavigationURI()); } } /** * Get resource bundle from given key. * * @param key Key * @return */ private String getLabel(String key) { try { ResourceBundle rs = WebuiRequestContext.getCurrentInstance().getApplicationResourceBundle(); return rs.getString(key); } catch (MissingResourceException e) { return key; } } /** * Get Order Type ("asc" or "desc") from user criteria. * * @return order type * @throws Exception */ private String getOrderType() throws Exception { UISearchForm uiSearchForm = this.getParent().findFirstComponentOfType(UISearchForm.class); String orderType = ((UIFormHiddenInput)uiSearchForm.getUIInput(UISearchForm.ORDER_TYPE_HIDDEN_INPUT)).getValue(); return StringUtils.isEmpty(orderType) ? "asc" : orderType; } /** * Get Sort Field from user criteria. * * @return sort field used to sort result */ private String getSortField() { UISearchForm uiSearchForm = this.getParent().findFirstComponentOfType(UISearchForm.class); String sortField = ((UIFormHiddenInput)uiSearchForm.getUIInput(UISearchForm.SORT_FIELD_HIDDEN_INPUT)).getValue(); return StringUtils.isEmpty(sortField) ? "relevancy" : sortField; } }
23,994
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UISearchPageLayoutManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/apps/portlet-search/src/main/java/org/exoplatform/wcm/webui/search/config/UISearchPageLayoutManager.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.search.config; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.portlet.PortletMode; import javax.portlet.PortletPreferences; import org.exoplatform.ecm.webui.form.UIFormInputSetWithAction; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.services.cms.views.ApplicationTemplateManagerService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.wcm.webui.search.UIWCMSearchPortlet; import org.exoplatform.wcm.webui.selector.page.UIPageSelector; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormSelectBox; import org.exoplatform.webui.form.UIFormStringInput; /* * Created by The eXo Platform SAS Author : Anh Do Ngoc anh.do@exoplatform.com * Oct 31, 2008 */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "app:/groovy/webui/search/config/UISearchPageLayoutManager.gtmpl", events = { @EventConfig(listeners = UISearchPageLayoutManager.SaveActionListener.class), @EventConfig(listeners = UISearchPageLayoutManager.SelectBasePathActionListener.class), @EventConfig(listeners = UISearchPageLayoutManager.CancelActionListener.class) } ) public class UISearchPageLayoutManager extends UIForm implements UISelectable { /** The Constant PORTLET_NAME. */ public static final String PORTLET_NAME = "search"; /** The Constant SEARCH_PAGE_LAYOUT_CATEGORY. */ public static final String SEARCH_PAGE_LAYOUT_CATEGORY = "search-page-layout"; /** The Constant SEARCH_PAGE_LAYOUT_SELECTOR. */ public static final String SEARCH_PAGE_LAYOUT_SELECTOR = "searchPageLayoutSelector"; /** The Constant SEARCH_FORM_TEMPLATE_CATEGORY. */ public static final String SEARCH_FORM_TEMPLATE_CATEGORY = "search-form"; // /** The Constant SEARCH_PAGINATOR_TEMPLATE_CATEGORY. */ // public static final String SEARCH_PAGINATOR_TEMPLATE_CATEGORY = "search-paginator"; /** The Constant SEARCH_RESULT_TEMPLATE_CATEGORY. */ public static final String SEARCH_RESULT_TEMPLATE_CATEGORY = "search-result"; /** The Constant SEARCH_FORM_TEMPLATE_SELECTOR. */ public static final String SEARCH_FORM_TEMPLATE_SELECTOR = "searchFormSelector"; /** The Constant SEARCH_PAGINATOR_TEMPLATE_SELECTOR. */ public static final String SEARCH_PAGINATOR_TEMPLATE_SELECTOR = "searchPaginatorSelector"; /** The Constant SEARCH_RESULT_TEMPLATE_SELECTOR. */ public static final String SEARCH_RESULT_TEMPLATE_SELECTOR = "searchResultSelector"; /** The Constant ITEMS_PER_PAGE_SELECTOR. */ public final static String ITEMS_PER_PAGE_SELECTOR = "itemsPerPageSelector"; /** The Constant PAGE_MODE_SELECTOR. */ public final static String PAGE_MODE_SELECTOR = "pageMode"; /** The Constant BASE_PATH_INPUT. */ public final static String BASE_PATH_INPUT = "searchResultBasePathInput"; /** The Constant BASE_PATH_SELECTOR_POPUP_WINDOW. */ public final static String BASE_PATH_SELECTOR_POPUP_WINDOW = "searchResultBasePathPopupWindow"; /** The Constant BASE_PATH_INPUT_SET_ACTION. */ public final static String BASE_PATH_INPUT_SET_ACTION = "searchResultBasePathInputSetAction"; /** The popup id. */ private String popupId; /** * @return the popupId */ public String getPopupId() { return popupId; } /** * @param popupId the popupId to set */ public void setPopupId(String popupId) { this.popupId = popupId; } /** * Instantiates a new uI search page layout manager. * * @throws Exception the exception */ public UISearchPageLayoutManager() throws Exception { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); PortletPreferences portletPreferences = portletRequestContext.getRequest().getPreferences(); String itemsPerpage = portletPreferences.getValue(UIWCMSearchPortlet.ITEMS_PER_PAGE, null); String pageMode = portletPreferences.getValue(UIWCMSearchPortlet.PAGE_MODE, null); String searchFormTemplate = portletPreferences.getValue(UIWCMSearchPortlet.SEARCH_FORM_TEMPLATE_PATH, null); String searchResultTemplate = portletPreferences.getValue(UIWCMSearchPortlet.SEARCH_RESULT_TEMPLATE_PATH, null); // String searchPaginatorTemplate = portletPreferences.getValue(UIWCMSearchPortlet.SEARCH_PAGINATOR_TEMPLATE_PATH, // null); String searchPageLayoutTemplate = portletPreferences.getValue(UIWCMSearchPortlet.SEARCH_PAGE_LAYOUT_TEMPLATE_PATH, null); List<SelectItemOption<String>> searchFormTemplateList = createTemplateList(PORTLET_NAME, SEARCH_FORM_TEMPLATE_CATEGORY); List<SelectItemOption<String>> searchResultTemplateList = createTemplateList(PORTLET_NAME, SEARCH_RESULT_TEMPLATE_CATEGORY); // List<SelectItemOption<String>> searchPaginatorTemplateList = createTemplateList(PORTLET_NAME, // SEARCH_PAGINATOR_TEMPLATE_CATEGORY); List<SelectItemOption<String>> searchPageLayoutTemplateList = createTemplateList(PORTLET_NAME, SEARCH_PAGE_LAYOUT_CATEGORY); List<SelectItemOption<String>> itemsPerPageList = new ArrayList<SelectItemOption<String>>(); itemsPerPageList.add(new SelectItemOption<String>("5", "5")); itemsPerPageList.add(new SelectItemOption<String>("10", "10")); itemsPerPageList.add(new SelectItemOption<String>("20", "20")); List<SelectItemOption<String>> pageModeList = new ArrayList<SelectItemOption<String>>(); pageModeList.add(new SelectItemOption<String>("none", "none")); pageModeList.add(new SelectItemOption<String>("more", "more")); pageModeList.add(new SelectItemOption<String>("pagination", "pagination")); UIFormSelectBox pageModeSelector = new UIFormSelectBox(PAGE_MODE_SELECTOR, PAGE_MODE_SELECTOR, pageModeList); UIFormSelectBox itemsPerPageSelector = new UIFormSelectBox(ITEMS_PER_PAGE_SELECTOR, ITEMS_PER_PAGE_SELECTOR, itemsPerPageList); UIFormSelectBox searchFormTemplateSelector = new UIFormSelectBox(SEARCH_FORM_TEMPLATE_SELECTOR, SEARCH_FORM_TEMPLATE_SELECTOR, searchFormTemplateList); UIFormSelectBox searchResultTemplateSelector = new UIFormSelectBox(SEARCH_RESULT_TEMPLATE_SELECTOR, SEARCH_RESULT_TEMPLATE_SELECTOR, searchResultTemplateList); // UIFormSelectBox searchPaginatorTemplateSelector = new UIFormSelectBox(SEARCH_PAGINATOR_TEMPLATE_SELECTOR, // SEARCH_PAGINATOR_TEMPLATE_SELECTOR, // searchPaginatorTemplateList); UIFormSelectBox searchPageLayoutTemplateSelector = new UIFormSelectBox(SEARCH_PAGE_LAYOUT_SELECTOR, SEARCH_PAGE_LAYOUT_SELECTOR, searchPageLayoutTemplateList); String preferenceBasePath = portletPreferences.getValue(UIWCMSearchPortlet.BASE_PATH, null); UIFormInputSetWithAction targetPathFormInputSet = new UIFormInputSetWithAction(BASE_PATH_INPUT_SET_ACTION); UIFormStringInput targetPathFormStringInput = new UIFormStringInput(BASE_PATH_INPUT, BASE_PATH_INPUT, preferenceBasePath); targetPathFormStringInput.setValue(preferenceBasePath); targetPathFormStringInput.setReadOnly(true); targetPathFormInputSet.setActionInfo(BASE_PATH_INPUT, new String[] {"SelectBasePath"}) ; targetPathFormInputSet.addUIFormInput(targetPathFormStringInput); pageModeSelector.setValue(pageMode); itemsPerPageSelector.setValue(itemsPerpage); searchFormTemplateSelector.setValue(searchFormTemplate); searchResultTemplateSelector.setValue(searchResultTemplate); // searchPaginatorTemplateSelector.setValue(searchPaginatorTemplate); searchPageLayoutTemplateSelector.setValue(searchPageLayoutTemplate); addChild(pageModeSelector); addChild(itemsPerPageSelector); addChild(searchFormTemplateSelector); addChild(searchResultTemplateSelector); // addChild(searchPaginatorTemplateSelector); addChild(searchPageLayoutTemplateSelector); addChild(targetPathFormInputSet); setActions(new String[] { "Save", "Cancel" }); } /** * Creates the template list. * * @param portletName the portlet name * @param category the category * * @return the list< select item option< string>> * * @throws Exception the exception */ private List<SelectItemOption<String>> createTemplateList(String portletName, String category) throws Exception { List<SelectItemOption<String>> templateList = new ArrayList<SelectItemOption<String>>(); ApplicationTemplateManagerService templateManagerService = getApplicationComponent(ApplicationTemplateManagerService.class); List<Node> templateNodeList = templateManagerService.getTemplatesByCategory(portletName, category, WCMCoreUtils.getUserSessionProvider()); for (Node templateNode : templateNodeList) { String templateName = templateNode.getName(); String templatePath = templateNode.getPath(); templateList.add(new SelectItemOption<String>(templateName, templatePath)); } return templateList; } /** * The listener interface for receiving saveAction events. The class that is * interested in processing a saveAction event implements this interface, and * the object created with that class is registered with a component using the * component's <code>addSaveActionListener</code> method. When * the saveAction event occurs, that object's appropriate * method is invoked. * */ public static class SaveActionListener extends EventListener<UISearchPageLayoutManager> { /* * (non-Javadoc) * @see * org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui * .event.Event) */ public void execute(Event<UISearchPageLayoutManager> event) throws Exception { UISearchPageLayoutManager uiSearchLayoutManager = event.getSource(); UIApplication uiApp = uiSearchLayoutManager.getAncestorOfType(UIApplication.class); RepositoryService repositoryService = uiSearchLayoutManager.getApplicationComponent(RepositoryService.class); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); String repository = manageableRepository.getConfiguration().getName(); String workspace = manageableRepository.getConfiguration().getDefaultWorkspaceName(); PortletRequestContext portletRequestContext = (PortletRequestContext) event.getRequestContext(); PortletPreferences portletPreferences = portletRequestContext.getRequest().getPreferences(); String searchResultTemplatePath = uiSearchLayoutManager. getUIFormSelectBox(UISearchPageLayoutManager.SEARCH_RESULT_TEMPLATE_SELECTOR).getValue(); String searchFormTemplatePath = uiSearchLayoutManager. getUIFormSelectBox(UISearchPageLayoutManager.SEARCH_FORM_TEMPLATE_SELECTOR).getValue(); // String searchPaginatorTemplatePath = uiSearchLayoutManager. // getUIFormSelectBox(UISearchPageLayoutManager.SEARCH_PAGINATOR_TEMPLATE_SELECTOR).getValue(); String searchPageLayoutTemplatePath = uiSearchLayoutManager. getUIFormSelectBox(UISearchPageLayoutManager.SEARCH_PAGE_LAYOUT_SELECTOR).getValue(); String itemsPerPage = uiSearchLayoutManager. getUIFormSelectBox(UISearchPageLayoutManager.ITEMS_PER_PAGE_SELECTOR).getValue(); String pageMode = uiSearchLayoutManager.getUIFormSelectBox(UISearchPageLayoutManager.PAGE_MODE_SELECTOR).getValue(); String basePath = uiSearchLayoutManager.getUIStringInput(UISearchPageLayoutManager.BASE_PATH_INPUT) .getValue(); portletPreferences.setValue(UIWCMSearchPortlet.REPOSITORY, repository); portletPreferences.setValue(UIWCMSearchPortlet.WORKSPACE, workspace); portletPreferences.setValue(UIWCMSearchPortlet.SEARCH_RESULT_TEMPLATE_PATH, searchResultTemplatePath); portletPreferences.setValue(UIWCMSearchPortlet.SEARCH_FORM_TEMPLATE_PATH, searchFormTemplatePath); // portletPreferences.setValue(UIWCMSearchPortlet.SEARCH_PAGINATOR_TEMPLATE_PATH, // searchPaginatorTemplatePath); portletPreferences.setValue(UIWCMSearchPortlet.SEARCH_PAGE_LAYOUT_TEMPLATE_PATH, searchPageLayoutTemplatePath); portletPreferences.setValue(UIWCMSearchPortlet.ITEMS_PER_PAGE, itemsPerPage); portletPreferences.setValue(UIWCMSearchPortlet.PAGE_MODE, pageMode); portletPreferences.setValue(UIWCMSearchPortlet.BASE_PATH, basePath); portletPreferences.store(); if (Utils.isEditPortletInCreatePageWizard()) { uiApp.addMessage(new ApplicationMessage("UISearchConfig.msg.saving-success", null, ApplicationMessage.INFO)); } else { portletRequestContext.setApplicationMode(PortletMode.VIEW); } } } /** * The listener interface for receiving cancelAction events. The class that is * interested in processing a cancelAction event implements this interface, * and the object created with that class is registered with a component using * the component's <code>addCancelActionListener</code> method. When * the cancelAction event occurs, that object's appropriate * method is invoked. * */ public static class CancelActionListener extends EventListener<UISearchPageLayoutManager> { /* * (non-Javadoc) * @see * org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui * .event.Event) */ public void execute(Event<UISearchPageLayoutManager> event) throws Exception { PortletRequestContext context = (PortletRequestContext) event.getRequestContext(); context.setApplicationMode(PortletMode.VIEW); } } /* * (non-Javadoc) * * @see org.exoplatform.ecm.webui.selector.UISelectable#doSelect(java.lang.String, * java.lang.Object) */ public void doSelect(String selectField, Object value) throws Exception { getUIStringInput(selectField).setValue((String) value); Utils.closePopupWindow(this, popupId); } /** * The listener interface for receiving selectTargetPageAction events. * The class that is interested in processing a selectTargetPageAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addSelectTargetPageActionListener</code> method. When * the selectTargetPageAction event occurs, that object's appropriate * method is invoked. * */ public static class SelectBasePathActionListener extends EventListener<UISearchPageLayoutManager> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UISearchPageLayoutManager> event) throws Exception { UISearchPageLayoutManager viewerManagementForm = event.getSource(); UIPageSelector pageSelector = viewerManagementForm.createUIComponent(UIPageSelector.class, null, null); pageSelector.setSourceComponent(viewerManagementForm, new String[] {BASE_PATH_INPUT}); Utils.createPopupWindow(viewerManagementForm, pageSelector, BASE_PATH_SELECTOR_POPUP_WINDOW, 800); viewerManagementForm.setPopupId(BASE_PATH_SELECTOR_POPUP_WINDOW); } } }
18,587
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIPortletConfig.java
/FileExtraction/Java_unseen/exoplatform_ecms/apps/portlet-search/src/main/java/org/exoplatform/wcm/webui/search/config/UIPortletConfig.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.search.config; import org.exoplatform.portal.webui.container.UIContainer; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; /* * Created by The eXo Platform SAS * Author : Anh Do Ngoc * anh.do@exoplatform.com * Oct 31, 2008 */ @ComponentConfig(lifecycle = UIContainerLifecycle.class) public class UIPortletConfig extends UIContainer { /** * Instantiates a new uI portlet config. * * @throws Exception the exception */ public UIPortletConfig() throws Exception { addChild(UISearchPageLayoutManager.class, null, null); } }
1,411
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CloudDrivePortlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/apps/portlet-clouddrives/src/main/java/org/exoplatform/services/cms/clouddrives/portlet/CloudDrivePortlet.java
/* * Copyright (C) 2003-2022 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.portlet; import java.io.IOException; import javax.portlet.GenericPortlet; import javax.portlet.PortletException; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import org.exoplatform.ecm.webui.clouddrives.CloudDriveContext; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.webui.application.WebuiRequestContext; /** * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CloudDrivePortlet.java 00000 Jul 6, 2018 pnedonosko $ */ public class CloudDrivePortlet extends GenericPortlet { /** The Constant LOG. */ private static final Log LOG = ExoLogger.getLogger(CloudDrivePortlet.class); /** * {@inheritDoc} */ @Override protected void doView(final RenderRequest request, final RenderResponse response) throws PortletException, IOException { final String remoteUser = request.getRemoteUser(); try { // We init core script w/o context workspace and path, this will init // global UI enhancements (for Search etc.) CloudDriveContext.init(WebuiRequestContext.getCurrentInstance()); } catch (Exception e) { LOG.error("Error processing Cloud Drive portlet for user " + remoteUser, e); } } }
2,192
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PostUpdateStateEventListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/webui/src/main/java/org/exoplatform/wcm/authoring/listener/PostUpdateStateEventListener.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.authoring.listener; import java.util.Collection; import java.util.Iterator; import javax.jcr.Node; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.portal.webui.workspace.UIPortalApplication; import org.exoplatform.portal.webui.workspace.UIWorkingWorkspace; import org.exoplatform.services.cms.CmsService; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.organization.Membership; import org.exoplatform.services.organization.MembershipHandler; import org.exoplatform.services.organization.OrganizationService; import org.exoplatform.services.organization.User; import org.exoplatform.services.organization.UserHandler; import org.exoplatform.services.wcm.extensions.publication.PublicationManager; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.Lifecycle; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.State; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Created by The eXo Platform SAS * Author : Benjamin Paillereau * benjamin.paillereau@exoplatform.com * May 31, 2010 */ public class PostUpdateStateEventListener extends Listener<CmsService, Node> { private static final Log LOG = ExoLogger.getLogger(PostUpdateStateEventListener.class.getName()); /** The pservice. */ private PublicationManager publicationManager; /** * Instantiates a new post edit content event listener. * * @param publicationManager the publication manager */ public PostUpdateStateEventListener(PublicationManager publicationManager) { this.publicationManager = publicationManager; } /* * (non-Javadoc) * @see * org.exoplatform.services.listener.Listener#onEvent(org.exoplatform.services * .listener.Event) */ public void onEvent(Event<CmsService, Node> event) throws Exception { Node node = event.getData(); String userId; try { userId = Util.getPortalRequestContext().getRemoteUser(); } catch (Exception e) { userId = node.getSession().getUserID(); } String currentState = node.getProperty("publication:currentState").getString(); if (!"enrolled".equals(currentState)) { String nodeLifecycle = node.getProperty("publication:lifecycle").getString(); // if (log.isInfoEnabled()) // log.info(userId+"::"+currentState+"::"+nodeLifecycle); if (LOG.isInfoEnabled()) LOG.info("@@@ " + currentState + " @@@@@@@@@@@@@@@@@@@ " + node.getPath()); Lifecycle lifecycle = publicationManager.getLifecycle(nodeLifecycle); Iterator<State> states = lifecycle.getStates().iterator(); State prevState = null; while (states.hasNext()) { State state = states.next(); if (state.getState().equals(currentState)) { sendMail(node, state, userId, false, false); if ("published".equals(state.getState()) && prevState != null) { sendMail(node, prevState, userId, false, true); } if (states.hasNext()) { State nextState = states.next(); sendMail(node, nextState, userId, true, false); break; } } prevState = state; } try { UIPortalApplication portalApplication = Util.getUIPortalApplication(); PortalRequestContext portalRequestContext = Util.getPortalRequestContext(); UIWorkingWorkspace uiWorkingWS = portalApplication.getChildById(UIPortalApplication.UI_WORKING_WS_ID); portalRequestContext.addUIComponentToUpdateByAjax(uiWorkingWS); portalRequestContext.ignoreAJAXUpdateOnPortlets(true); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } } } private void sendMail(Node node, State state, String userId, boolean isNextState, boolean isPublished) throws Exception { if (state.getMembership().contains(":")) { String[] membership = state.getMembership().split(":"); String membershipType = membership[0]; String group = membership[1]; OrganizationService orgService = WCMCoreUtils.getService(OrganizationService.class); UserHandler userh = orgService.getUserHandler(); MembershipHandler msh = orgService.getMembershipHandler(); ListAccess<User> userList = userh.findUsersByGroupId(group); User currentUser = null; try { currentUser = userh.findUserByName(userId); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } String username = userId; if (currentUser != null) username = currentUser.getFirstName() + " " + currentUser.getLastName(); for (User user : userList.load(0, userList.getSize())) { Collection<Membership> mss = msh.findMembershipsByUserAndGroup(user.getUserName(), group); for (Membership ms : mss) { if (membershipType.equals(ms.getMembershipType())) { String from = "\"" + username + "\" <exocontent@exoplatform.com>"; String to = user.getEmail(); String subject, body; String editUrl = "http://localhost:8080/ecmdemo/private/classic/siteExplorer/repository/collaboration" + node.getPath(); if (isPublished) { subject = "[eXo Content] Published : (published) " + node.getName(); } else { if (isNextState) { subject = "[eXo Content] Request : (" + state.getState() + ") " + node.getName(); } else { subject = "[eXo Content] Updated : (" + state.getState() + ") " + node.getName(); } } body = "[ <a href=\"" + editUrl + "\">" + editUrl + "</a> ]<br/>" + "updated by " + username; // mailService.sendMessage(from, to, subject, body); if (LOG.isInfoEnabled()) { LOG.info("\n################ SEND MAIL TO USER :: " + user.getUserName() + "\nfrom: " + from + "\nto: " + to + "\nsubject: " + subject + "\nbody: " + body + "\n######################################################"); } } } } } } }
7,531
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CanPublishFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/webui/src/main/java/org/exoplatform/wcm/extensions/ui/CanPublishFilter.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.extensions.ui; import java.util.List; import java.util.Map; import javax.jcr.Node; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.extensions.publication.PublicationManager; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.Lifecycle; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilterType; /** * Created by The eXo Platform SAS * Author : eXoPlatform * nicolas.filotto@exoplatform.com * 2 juillet 2009 */ public class CanPublishFilter implements UIExtensionFilter { private static final Log LOG = ExoLogger.getLogger(CanPublishFilter.class.getName()); /** * This method checks if the current node is of the right type */ public boolean accept(Map<String, Object> context) throws Exception { // Retrieve the current node from the context Node currentNode = (Node) context.get(Node.class.getName()); if (currentNode.hasProperty("publication:currentState") && currentNode.hasProperty("publication:lifecycle")) { String currentState = currentNode.getProperty("publication:currentState").getString(); if (!"published".equals(currentState)) { String userId; try { userId = Util.getPortalRequestContext().getRemoteUser(); } catch (Exception e) { userId = currentNode.getSession().getUserID(); } String nodeLifecycle = currentNode.getProperty("publication:lifecycle").getString(); PublicationManager publicationManager = WCMCoreUtils.getService(PublicationManager.class); List<Lifecycle> lifecycles = publicationManager.getLifecyclesFromUser(userId, "published"); for (Lifecycle lifecycle:lifecycles) { if (nodeLifecycle.equals(lifecycle.getName())) { return true; } } } } return false; } /** * This is the type of the filter */ public UIExtensionFilterType getType() { return UIExtensionFilterType.MANDATORY; } /** * This is called when the filter has failed */ public void onDeny(Map<String, Object> context) throws Exception { if (LOG.isWarnEnabled()) { LOG.warn("You can add a category in a exo:taxonomy node only."); } } }
3,319
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ShowDrivesAction.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/webui/src/main/java/org/exoplatform/wcm/extensions/ui/ShowDrivesAction.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.extensions.ui; import java.util.Arrays; import java.util.List; import org.exoplatform.ecm.webui.component.explorer.UIDocumentWorkspace; import org.exoplatform.ecm.webui.component.explorer.UIDrivesArea; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.UIWorkingArea; 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.event.Event; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilters; /** * Created by The eXo Platform SAS * Author : eXoPlatform * benjamin.paillereau@exoplatform.com * 27 june 2010 */ @ComponentConfig( events = { @EventConfig(listeners = ShowDrivesAction.ShowDrivesActionListener.class) } ) public class ShowDrivesAction extends UIComponent { private static final List<UIExtensionFilter> FILTERS = Arrays.asList( new UIExtensionFilter[] {}); @UIExtensionFilters public List<UIExtensionFilter> getFilters() { return FILTERS; } public static class ShowDrivesActionListener extends UIActionBarActionListener<ShowDrivesAction> { @Override protected void processEvent(Event<ShowDrivesAction> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); UIWorkingArea uiWorkingArea = uiExplorer.getChild(UIWorkingArea.class); UIDrivesArea uiDriveArea = uiWorkingArea.getChild(UIDrivesArea.class); if (uiDriveArea.isRendered()) { uiDriveArea.setRendered(false); uiWorkingArea.getChild(UIDocumentWorkspace.class).setRendered(true); } else { uiDriveArea.setRendered(true); uiWorkingArea.getChild(UIDocumentWorkspace.class).setRendered(false); } event.getRequestContext().addUIComponentToUpdateByAjax(uiWorkingArea) ; } } }
2,922
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CanValidateFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/webui/src/main/java/org/exoplatform/wcm/extensions/ui/CanValidateFilter.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.extensions.ui; import java.util.List; import java.util.Map; import javax.jcr.Node; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.extensions.publication.PublicationManager; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.Lifecycle; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilterType; /** * Created by The eXo Platform SAS * Author : eXoPlatform * nicolas.filotto@exoplatform.com * 2 juillet 2009 */ public class CanValidateFilter implements UIExtensionFilter { private static final Log LOG = ExoLogger.getLogger(CanValidateFilter.class.getName()); /** * This method checks if the current node is of the right type */ public boolean accept(Map<String, Object> context) throws Exception { // Retrieve the current node from the context Node currentNode = (Node) context.get(Node.class.getName()); if (currentNode.hasProperty("publication:currentState") && currentNode.hasProperty("publication:lifecycle")) { String currentState = currentNode.getProperty("publication:currentState").getString(); if ("draft".equals(currentState)) { String userId; try { userId = Util.getPortalRequestContext().getRemoteUser(); } catch (Exception e) { userId = currentNode.getSession().getUserID(); } String nodeLifecycle = currentNode.getProperty("publication:lifecycle").getString(); PublicationManager publicationManager = WCMCoreUtils.getService(PublicationManager.class); List<Lifecycle> lifecycles = publicationManager.getLifecyclesFromUser(userId, "pending"); for (Lifecycle lifecycle:lifecycles) { if (nodeLifecycle.equals(lifecycle.getName())) { return true; } } } } return false; } /** * This is the type of the filter */ public UIExtensionFilterType getType() { return UIExtensionFilterType.MANDATORY; } /** * This is called when the filter has failed */ public void onDeny(Map<String, Object> context) throws Exception { if (LOG.isWarnEnabled()) { LOG.warn("You can add a category in a exo:taxonomy node only."); } } }
3,312
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PublicationPublishAction.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/webui/src/main/java/org/exoplatform/wcm/extensions/ui/PublicationPublishAction.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.extensions.ui; import java.util.Arrays; import java.util.HashMap; import java.util.List; import javax.jcr.Node; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.control.filter.CanAddNodeFilter; import org.exoplatform.ecm.webui.component.explorer.control.filter.IsCheckedOutFilter; import org.exoplatform.ecm.webui.component.explorer.control.filter.IsNotEditingDocumentFilter; import org.exoplatform.ecm.webui.component.explorer.control.filter.IsNotLockedFilter; import org.exoplatform.ecm.webui.component.explorer.control.listener.UIActionBarActionListener; import org.exoplatform.ecm.utils.lock.LockUtil; import org.exoplatform.services.ecm.publication.PublicationService; 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.UIPopupContainer; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilters; /** * Created by The eXo Platform SAS * Author : eXoPlatform * benjamin.paillereau@exoplatform.com * 27 june 2010 */ @ComponentConfig( events = { @EventConfig(listeners = PublicationPublishAction.PublicationPublishActionListener.class) } ) public class PublicationPublishAction extends UIComponent { private static final List<UIExtensionFilter> FILTERS = Arrays.asList( new UIExtensionFilter[] { new CanAddNodeFilter(), new IsNotLockedFilter(), new IsCheckedOutFilter(), new CanPublishFilter(), new IsNotEditingDocumentFilter()}); @UIExtensionFilters public List<UIExtensionFilter> getFilters() { return FILTERS; } public static class PublicationPublishActionListener extends UIActionBarActionListener<PublicationPublishAction> { @Override protected void processEvent(Event<PublicationPublishAction> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); PublicationService publicationService = WCMCoreUtils.getService(PublicationService.class); Node node = uiExplorer.getCurrentNode(); if(node.isLocked()) { node.getSession().addLockToken(LockUtil.getLockToken(node)); } HashMap<String,String> context = new HashMap<String,String>(); publicationService.changeState(node, "published", context); UIPopupContainer UIPopupContainer = uiExplorer.getChild(UIPopupContainer.class); event.getRequestContext().addUIComponentToUpdateByAjax(UIPopupContainer); event.getRequestContext().addUIComponentToUpdateByAjax(uiExplorer); } } }
3,633
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CanApproveFilter.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/webui/src/main/java/org/exoplatform/wcm/extensions/ui/CanApproveFilter.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.extensions.ui; import java.util.List; import java.util.Map; import javax.jcr.Node; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.extensions.publication.PublicationManager; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.Lifecycle; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilterType; /** * Created by The eXo Platform SAS * Author : eXoPlatform * nicolas.filotto@exoplatform.com * 2 juillet 2009 */ public class CanApproveFilter implements UIExtensionFilter { private static final Log LOG = ExoLogger.getLogger(CanApproveFilter.class.getName()); /** * This method checks if the current node is of the right type */ public boolean accept(Map<String, Object> context) throws Exception { // Retrieve the current node from the context Node currentNode = (Node) context.get(Node.class.getName()); if (currentNode.hasProperty("publication:currentState") && currentNode.hasProperty("publication:lifecycle")) { String currentState = currentNode.getProperty("publication:currentState").getString(); if ("pending".equals(currentState)) { String userId; try { userId = Util.getPortalRequestContext().getRemoteUser(); } catch (Exception e) { userId = currentNode.getSession().getUserID(); } String nodeLifecycle = currentNode.getProperty("publication:lifecycle").getString(); PublicationManager publicationManager = WCMCoreUtils.getService(PublicationManager.class); List<Lifecycle> lifecycles = publicationManager.getLifecyclesFromUser(userId, "approved"); for (Lifecycle lifecycle:lifecycles) { if (nodeLifecycle.equals(lifecycle.getName())) { return true; } } } } return false; } /** * This is the type of the filter */ public UIExtensionFilterType getType() { return UIExtensionFilterType.MANDATORY; } /** * This is called when the filter has failed */ public void onDeny(Map<String, Object> context) throws Exception { if (LOG.isWarnEnabled()) { LOG.warn("You can add a category in a exo:taxonomy node only."); } } }
3,309
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PublicationRequestApprovalAction.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/webui/src/main/java/org/exoplatform/wcm/extensions/ui/PublicationRequestApprovalAction.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.extensions.ui; import java.util.Arrays; import java.util.HashMap; import java.util.List; import javax.jcr.Node; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.control.filter.CanAddNodeFilter; import org.exoplatform.ecm.webui.component.explorer.control.filter.IsCheckedOutFilter; import org.exoplatform.ecm.webui.component.explorer.control.filter.IsNotLockedFilter; import org.exoplatform.ecm.webui.component.explorer.control.filter.IsNotEditingDocumentFilter; import org.exoplatform.ecm.webui.component.explorer.control.listener.UIActionBarActionListener; import org.exoplatform.services.ecm.publication.PublicationService; 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.UIPopupContainer; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilters; /** * Created by The eXo Platform SAS * Author : eXoPlatform * benjamin.paillereau@exoplatform.com * 27 june 2010 */ @ComponentConfig(events = { @EventConfig(listeners = PublicationRequestApprovalAction.PublicationRequestApprovalActionListener.class) }) public class PublicationRequestApprovalAction extends UIComponent { private static final List<UIExtensionFilter> FILTERS = Arrays.asList(new UIExtensionFilter[] { new CanAddNodeFilter(), new IsNotLockedFilter(), new IsCheckedOutFilter(), new CanValidateFilter(), new IsNotEditingDocumentFilter()}); @UIExtensionFilters public List<UIExtensionFilter> getFilters() { return FILTERS; } public static class PublicationRequestApprovalActionListener extends UIActionBarActionListener<PublicationRequestApprovalAction> { @Override protected void processEvent(Event<PublicationRequestApprovalAction> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); PublicationService publicationService = WCMCoreUtils.getService(PublicationService.class); Node node = uiExplorer.getCurrentNode(); HashMap<String, String> context = new HashMap<String, String>(); publicationService.changeState(node, "pending", context); UIPopupContainer UIPopupContainer = uiExplorer.getChild(UIPopupContainer.class); event.getRequestContext().addUIComponentToUpdateByAjax(UIPopupContainer); event.getRequestContext().addUIComponentToUpdateByAjax(uiExplorer); } } }
3,631
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PublicationApproveContentAction.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/webui/src/main/java/org/exoplatform/wcm/extensions/ui/PublicationApproveContentAction.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.extensions.ui; import java.util.Arrays; import java.util.HashMap; import java.util.List; import javax.jcr.Node; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.component.explorer.control.filter.CanAddNodeFilter; import org.exoplatform.ecm.webui.component.explorer.control.filter.IsCheckedOutFilter; import org.exoplatform.ecm.webui.component.explorer.control.filter.IsNotEditingDocumentFilter; import org.exoplatform.ecm.webui.component.explorer.control.filter.IsNotLockedFilter; import org.exoplatform.ecm.webui.component.explorer.control.listener.UIActionBarActionListener; import org.exoplatform.services.ecm.publication.PublicationService; 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.UIPopupContainer; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.ext.filter.UIExtensionFilter; import org.exoplatform.webui.ext.filter.UIExtensionFilters; /** * Created by The eXo Platform SAS * Author : eXoPlatform * benjamin.paillereau@exoplatform.com * 27 june 2010 */ @ComponentConfig( events = { @EventConfig(listeners = PublicationApproveContentAction.PublicationApproveContentActionListener.class) } ) public class PublicationApproveContentAction extends UIComponent { private static final List<UIExtensionFilter> FILTERS = Arrays.asList( new UIExtensionFilter[] { new CanAddNodeFilter(), new IsNotLockedFilter(), new IsCheckedOutFilter(), new CanApproveFilter(), new IsNotEditingDocumentFilter()}); @UIExtensionFilters public List<UIExtensionFilter> getFilters() { return FILTERS; } public static class PublicationApproveContentActionListener extends UIActionBarActionListener<PublicationApproveContentAction> { @Override protected void processEvent(Event<PublicationApproveContentAction> event) throws Exception { UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); PublicationService publicationService = WCMCoreUtils.getService(PublicationService.class); Node node = uiExplorer.getCurrentNode(); HashMap<String,String> context = new HashMap<String,String>(); publicationService.changeState(node, "approved", context); UIPopupContainer UIPopupContainer = uiExplorer.getChild(UIPopupContainer.class); event.getRequestContext().addUIComponentToUpdateByAjax(UIPopupContainer); event.getRequestContext().addUIComponentToUpdateByAjax(uiExplorer); } } }
3,647
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIWCMDashboardPortlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/apps/src/main/java/org/exoplatform/wcm/webui/authoring/UIWCMDashboardPortlet.java
package org.exoplatform.wcm.webui.authoring; import javax.portlet.PortletMode; 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.UIPortletApplication; import org.exoplatform.webui.core.lifecycle.UIApplicationLifecycle; @ComponentConfig( lifecycle = UIApplicationLifecycle.class, template = "app:/groovy/authoring/UIDashboardPortlet.gtmpl" ) public class UIWCMDashboardPortlet extends UIPortletApplication { public UIWCMDashboardPortlet() throws Exception { addChild(UIDashboardForm.class, null, null); } /* * (non-Javadoc) * @see * org.exoplatform.webui.core.UIPortletApplication#processRender(org.exoplatform * .webui.application.WebuiApplication, * org.exoplatform.webui.application.WebuiRequestContext) */ public void processRender(WebuiApplication app, WebuiRequestContext context) throws Exception { PortletRequestContext pContext = (PortletRequestContext) context; PortletMode newMode = pContext.getApplicationMode(); super.processRender(app, context); } }
1,271
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDashBoardColumn.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/apps/src/main/java/org/exoplatform/wcm/webui/authoring/UIDashBoardColumn.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.wcm.webui.authoring; import java.util.List; import javax.jcr.Node; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.wcm.core.NodeLocation; 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.UIContainer; import org.exoplatform.webui.core.UIPageIterator; import org.exoplatform.webui.core.lifecycle.Lifecycle; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Aug 22, 2012 */ @ComponentConfigs( { @ComponentConfig(lifecycle = Lifecycle.class, template = "app:/groovy/authoring/UIDashboardColumn.gtmpl", events = { @EventConfig(listeners = UIDashboardForm.ShowDocumentActionListener.class), @EventConfig(listeners = UIDashboardForm.RefreshActionListener.class) }), @ComponentConfig(type = UIPageIterator.class, template = "app:/groovy/authoring/UIDashBoardColumnIterator.gtmpl", events = {@EventConfig(listeners = UIPageIterator.ShowPageActionListener.class)}) }) public class UIDashBoardColumn extends UIContainer { private static final String locale = "locale.portlet.AuthoringDashboard.AuthoringDashboardPortlet"; private UIPageIterator uiPageIterator_; private String label_; public UIDashBoardColumn() throws Exception { uiPageIterator_ = addChild(UIPageIterator.class, null, "UIDashboardColumnIterator" + Math.random()); } public UIPageIterator getUIPageIterator() { return uiPageIterator_; } public List<Node> getNodes() throws Exception { return NodeLocation.getNodeListByLocationList(uiPageIterator_.getCurrentPageData()); } public void setLabel(String value) { label_ = Utils.getResourceBundle(locale, value, this.getClass().getClassLoader()); } public String getLabel() { return label_; } }
2,834
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDashboardForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/apps/src/main/java/org/exoplatform/wcm/webui/authoring/UIDashboardForm.java
/* * Copyright (C) 2003-2010 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.webui.authoring; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; 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.portal.application.PortalRequestContext; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.extensions.publication.PublicationManager; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.webui.Utils; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.lifecycle.Lifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Feb 2, 2010 */ @ComponentConfig(lifecycle = Lifecycle.class, template = "app:/groovy/authoring/UIDashboardForm.gtmpl", events = { @EventConfig(listeners = UIDashboardForm.ShowDocumentActionListener.class), @EventConfig(listeners = UIDashboardForm.RefreshActionListener.class) }) public class UIDashboardForm extends UIContainer { private int pageSize_ = 10; public UIDashboardForm() throws Exception { addChild(UIDashBoardColumn.class, null, "UIDashboardDraft").setLabel("UIDashboardForm.label.mydraft"); addChild(UIDashBoardColumn.class, null, "UIDashboardWaiting").setLabel("UIDashboardForm.label.waitingapproval"); addChild(UIDashBoardColumn.class, null, "UIDashboardPublish").setLabel("UIDashboardForm.label.publishedtomorrow"); refreshData(); } public List<Node> getContents(String fromstate) { return getContents(fromstate, null, null); } public List<Node> getContents(String fromstate, String tostate) { return getContents(fromstate, tostate, null); } public List<Node> getContents(String fromstate, String tostate, String date) { PublicationManager manager = WCMCoreUtils.getService(PublicationManager.class); String user = PortalRequestContext.getCurrentInstance().getRemoteUser(); String lang = Util.getPortalRequestContext().getLocale().getLanguage(); List<Node> nodes = new ArrayList<Node>(); List<Node> temp = new ArrayList<Node>(); try { nodes = manager.getContents(fromstate, tostate, date, user, lang, WCMCoreUtils.getRepository().getConfiguration().getDefaultWorkspaceName()); Set<String> uuidList = new HashSet<String>(); for(Node node : nodes) { String currentState = null; if(node.hasProperty("publication:currentState")) currentState = node.getProperty("publication:currentState").getString(); if(currentState == null || !currentState.equals("published")) { if(!org.exoplatform.services.cms.impl.Utils.isInTrash(node) && !uuidList.contains(node.getSession().getWorkspace().getName() + node.getUUID())) { uuidList.add(node.getSession().getWorkspace().getName() + node.getUUID()); temp.add(node); } } } } catch (Exception e) { temp = new ArrayList<Node>(); } return temp; } private void refreshData() { List<UIDashBoardColumn> children = new ArrayList<UIDashBoardColumn>(); for (UIComponent component : getChildren()) { if (component instanceof UIDashBoardColumn) { children.add((UIDashBoardColumn)component); } } ListAccess<NodeLocation> draftNodes = new ListAccessImpl<NodeLocation>(NodeLocation.class, NodeLocation.getLocationsByNodeList(getContents("draft"))); children.get(0).getUIPageIterator().setPageList( new LazyPageList<NodeLocation>(draftNodes, pageSize_)); ListAccess<NodeLocation> waitingNodes = new ListAccessImpl<NodeLocation>(NodeLocation.class, NodeLocation.getLocationsByNodeList(getContents("pending"))); children.get(1).getUIPageIterator().setPageList( new LazyPageList<NodeLocation>(waitingNodes, pageSize_)); ListAccess<NodeLocation> publishedNodes = new ListAccessImpl<NodeLocation>(NodeLocation.class, NodeLocation.getLocationsByNodeList(getContents("staged", null, "2"))); children.get(2).getUIPageIterator().setPageList( new LazyPageList<NodeLocation>(publishedNodes, pageSize_)); } public void processRender(WebuiRequestContext context) throws Exception { refreshData(); super.processRender(context); } /** * The listener interface for receiving ShowDocumentAction events. * The class that is interested in processing a changeRepositoryAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addShowDocumentActionListener</code> method. When * the ShowDocumentAction event occurs, that object's appropriate * method is invoked. */ public static class ShowDocumentActionListener extends EventListener<UIDashboardForm> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIDashboardForm> event) throws Exception { PortalRequestContext context = Util.getPortalRequestContext(); String path = event.getRequestContext().getRequestParameter(OBJECTID); HashMap<String, String> map = new HashMap<String, String>(); ManageDriveService driveService = WCMCoreUtils.getService(ManageDriveService.class); map.put("repository", "repository"); map.put("drive", driveService.getDriveOfDefaultWorkspace()); map.put("path", path); context.setAttribute("jcrexplorer-show-document", map); Utils.updatePortal((PortletRequestContext) event.getRequestContext()); } } /** * The listener interface for receiving RefreshAction events. * The class that is interested in processing a changeRepositoryAction * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>RefreshActionListener</code> method. When * the RefreshAction event occurs, that object's appropriate * method is invoked. */ public static class RefreshActionListener extends EventListener<UIDashboardForm> { /* (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform.webui.event.Event) */ public void execute(Event<UIDashboardForm> event) throws Exception { UIDashboardForm src = event.getSource(); Utils.updatePortal((PortletRequestContext) event.getRequestContext()); } } }
8,048
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestCopyContentFile.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/test/java/org/exoplatform/wcm/connector/authoring/TestCopyContentFile.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.wcm.connector.authoring; import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.exoplatform.services.rest.impl.ContainerResponse; import org.exoplatform.services.rest.wadl.research.HTTPMethods; /** * Created by The eXo Platform SAS * Author : Lai Trung Hieu * hieult@exoplatform.com * Aug 6, 2012 */ public class TestCopyContentFile extends BaseConnectorTestCase { public void setUp() throws Exception { super.setUp(); // Bind CopyContentFile REST service CopyContentFile restService = (CopyContentFile) this.container.getComponentInstanceOfType(CopyContentFile.class); this.binder.addResource(restService, null); } /** * Test method TestCopyContentFile.copyFile() * Input: /copyfile/copy/ * Expect: connector return data ok * @throws Exception */ public void testCopyFile() throws Exception{ String restPath = "/copyfile/copy/"; ContainerResponse response = service(HTTPMethods.POST.toString(), restPath, StringUtils.EMPTY, null, null); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); } public void tearDown() throws Exception { super.tearDown(); } }
1,942
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
MockPublicationManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/test/java/org/exoplatform/wcm/connector/authoring/MockPublicationManager.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.wcm.connector.authoring; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.Value; import org.exoplatform.container.component.ComponentPlugin; import org.exoplatform.services.wcm.extensions.publication.PublicationManager; import org.exoplatform.services.wcm.extensions.publication.context.impl.ContextConfig.Context; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.Lifecycle; import org.mockito.Mockito; /** * Created by The eXo Platform SAS * Author : Lai Trung Hieu * hieult@exoplatform.com * Aug 3, 2012 */ public class MockPublicationManager implements PublicationManager { /* (non-Javadoc) * @see org.exoplatform.services.wcm.extensions.publication.PublicationManager#addLifecycle(org.exoplatform.container.component.ComponentPlugin) */ @Override public void addLifecycle(ComponentPlugin plugin) { } /* (non-Javadoc) * @see org.exoplatform.services.wcm.extensions.publication.PublicationManager#removeLifecycle(org.exoplatform.container.component.ComponentPlugin) */ @Override public void removeLifecycle(ComponentPlugin plugin) { } /* (non-Javadoc) * @see org.exoplatform.services.wcm.extensions.publication.PublicationManager#addContext(org.exoplatform.container.component.ComponentPlugin) */ @Override public void addContext(ComponentPlugin plugin) { } /* (non-Javadoc) * @see org.exoplatform.services.wcm.extensions.publication.PublicationManager#removeContext(org.exoplatform.container.component.ComponentPlugin) */ @Override public void removeContext(ComponentPlugin plugin) { } /* (non-Javadoc) * @see org.exoplatform.services.wcm.extensions.publication.PublicationManager#getLifecycles() */ @Override public List<Lifecycle> getLifecycles() { return null; } /* (non-Javadoc) * @see org.exoplatform.services.wcm.extensions.publication.PublicationManager#getContexts() */ @Override public List<Context> getContexts() { return null; } /* (non-Javadoc) * @see org.exoplatform.services.wcm.extensions.publication.PublicationManager#getContext(java.lang.String) */ @Override public Context getContext(String name) { return null; } /* (non-Javadoc) * @see org.exoplatform.services.wcm.extensions.publication.PublicationManager#getLifecycle(java.lang.String) */ @Override public Lifecycle getLifecycle(String name) { return null; } /* (non-Javadoc) * @see org.exoplatform.services.wcm.extensions.publication.PublicationManager#getLifecyclesFromUser(java.lang.String, java.lang.String) */ @Override public List<Lifecycle> getLifecyclesFromUser(String remoteUser, String state) { return null; } /** * Mock data for testing APIs of REST service LifecycleConnector * @return a collection of nodes that contains 2 nodes: * Node 1: name is Mock node1 * path is /node1 * Node 2: name is Mock node2 * path is /node2 * title is Mock node 2 * publication:startPublishedDate is 03/18/2012 * @throws Exception */ @Override public List<Node> getContents(String fromstate, String tostate, String date, String user, String lang, String workspace) throws Exception { List<Node> result = new ArrayList<Node>(); Node node1 = Mockito.mock(Node.class); Mockito.when(node1.getName()).thenReturn("Mock node1"); Mockito.when(node1.getPath()).thenReturn("/node1"); result.add(node1); Node node2 = Mockito.mock(Node.class); Mockito.when(node2.getName()).thenReturn("Mock node2"); Mockito.when(node2.getPath()).thenReturn("/node2"); Value titleValue = Mockito.mock(Value.class); Mockito.when(titleValue.getString()).thenReturn("Mock node2"); Property titleProperty = Mockito.mock(Property.class); Mockito.when(titleProperty.getValue()).thenReturn(titleValue); Mockito.when(node2.hasProperty("exo:title")).thenReturn(true); Mockito.when(node2.getProperty("exo:title")).thenReturn(titleProperty); Mockito.when(node2.getProperty("exo:title").getString()).thenReturn("Mock node2"); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); Date valueDate =(formatter.parse("03/18/2012")); Value startPublishedDateValue = Mockito.mock(Value.class); Calendar valueCalendar = new GregorianCalendar(); valueCalendar.setTime(valueDate); Mockito.when(startPublishedDateValue.getDate()).thenReturn(valueCalendar); Property startPublishedDateProperty = Mockito.mock(Property.class); Mockito.when(startPublishedDateProperty.getValue()).thenReturn(startPublishedDateValue); Mockito.when(node2.hasProperty("publication:startPublishedDate")).thenReturn(true); Mockito.when(node2.getProperty("publication:startPublishedDate")).thenReturn(startPublishedDateProperty); Mockito.when(node2.getProperty("publication:startPublishedDate").getString()).thenReturn("03/18/2012"); result.add(node2); return result; } }
5,969
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
BaseConnectorTestCase.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/test/java/org/exoplatform/wcm/connector/authoring/BaseConnectorTestCase.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.wcm.connector.authoring; import org.exoplatform.component.test.ConfigurationUnit; import org.exoplatform.component.test.ConfiguredBy; import org.exoplatform.component.test.ContainerScope; import org.exoplatform.ecms.test.BaseECMSResourceTestCase; /** * Created by The eXo Platform SAS * Author : Lai Trung Hieu * hieult@exoplatform.com * Aug 6, 2012 */ @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/standalone/ecms-core-connector-test-configuration.xml") }) public abstract class BaseConnectorTestCase extends BaseECMSResourceTestCase { }
1,675
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestChangeStateCronJob.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/test/java/org/exoplatform/services/wcm/extensions/scheduler/impl/TestChangeStateCronJob.java
package org.exoplatform.services.wcm.extensions.scheduler.impl; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jcr.*; import javax.jcr.query.InvalidQueryException; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import org.apache.commons.lang3.StringUtils; import org.exoplatform.services.cms.queries.impl.NewUserConfig; import org.exoplatform.services.ecm.publication.PublicationPlugin; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.impl.core.value.DateValue; import org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring.AuthoringPublicationConstant; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Matchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.quartz.*; import org.exoplatform.services.cms.documents.TrashService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) @PowerMockIgnore({ "javax.management.*", "javax.xml.*", "org.apache.xerces.*", "org.xml.*" }) @PrepareForTest(value = { ChangeStateCronJobImpl.class, SessionProvider.class, WCMCoreUtils.class }) public class TestChangeStateCronJob { @Test public void testChangeStateOnContentInTrash() throws Exception { PowerMockito.mockStatic(ManagementFactory.class, new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { String methodName = invocation.getMethod().getName(); if (StringUtils.equals(methodName, "getRuntimeMXBean")) { RuntimeMXBean mxBean = Mockito.mock(RuntimeMXBean.class); Mockito.when(mxBean.getUptime()).thenReturn(150000L); return mxBean; } return invocation.callRealMethod(); } }); Session session = Mockito.mock(Session.class); PublicationPlugin publicationPlugin = Mockito.mock(PublicationPlugin.class); PowerMockito.mockStatic(SessionProvider.class, new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { String methodName = invocation.getMethod().getName(); if (StringUtils.equals(methodName, "createSystemProvider")) { SessionProvider sessionProvider = Mockito.mock(SessionProvider.class); Mockito.when(sessionProvider.getSession(Mockito.anyString(), Mockito.any())).thenReturn(session); QueryManager queryManager = Mockito.mock(QueryManager.class); Workspace workspace = Mockito.mock(Workspace.class); Mockito.when(session.getWorkspace()).thenReturn(workspace); Mockito.when(session.getWorkspace().getQueryManager()).thenReturn(queryManager); Query query = Mockito.mock(Query.class); Mockito.when(queryManager.createQuery(Mockito.anyString(), Mockito.eq(Query.SQL))).thenReturn(query); QueryResult queryResult = Mockito.mock(QueryResult.class); Mockito.when(query.execute()).thenReturn(queryResult); Property dateProperty = Mockito.mock(Property.class); Mockito.when(dateProperty.getDate()).thenReturn(Calendar.getInstance()); //Create Node Iterator Node nodeInTrash = mock(Node.class); when(nodeInTrash.getPath()).thenReturn("/Trash/nodeInTrash"); when (nodeInTrash.getProperty(Mockito.eq("publication:startPublishedDate"))).thenReturn(dateProperty); Node nodeUnderJCRSystem = mock(Node.class); when(nodeUnderJCRSystem.getPath()).thenReturn("/jcr:system/nodeUnderJCRSystem"); when(nodeUnderJCRSystem.getProperty(Mockito.eq("publication:startPublishedDate"))).thenReturn(dateProperty); Node nodeToPublish = mock(Node.class); when(nodeToPublish.getPath()).thenReturn("/sites/sample/nodeToPublish"); when (nodeToPublish.getProperty(Mockito.eq("publication:startPublishedDate"))).thenReturn(dateProperty); Node nodeToPublishWithoutStartDate = mock(Node.class); when(nodeToPublishWithoutStartDate.getPath()).thenReturn("/sites/sample/nodeToPublishWithoutStartDate"); when (nodeToPublishWithoutStartDate.getProperty(Mockito.eq("publication:startPublishedDate"))).thenReturn(null); when (nodeToPublishWithoutStartDate.getProperty(Mockito.eq("publication:endPublishedDate"))).thenReturn(dateProperty); Node nodeToPublishWithoutEndDate = mock(Node.class); when(nodeToPublishWithoutEndDate.getPath()).thenReturn("/sites/sample/nodeToPublishWithoutEndDate"); when (nodeToPublishWithoutEndDate.getProperty(Mockito.eq("publication:startPublishedDate"))).thenReturn(dateProperty); when (nodeToPublishWithoutEndDate.getProperty(Mockito.eq("publication:endPublishedDate"))).thenReturn(null); NodeIterator nodeIterator = Mockito.mock(NodeIterator.class); Boolean [] hasNextReturns = new Boolean[] {true, true, true, false, true, true, false}; Node[] nextReturnedNodes = new Node[] {nodeInTrash, nodeUnderJCRSystem, nodeToPublish, nodeToPublishWithoutStartDate, nodeToPublishWithoutEndDate}; Mockito.when(nodeIterator.hasNext()).thenReturn(true,hasNextReturns); Mockito.when(nodeIterator.nextNode()).thenReturn(nodeInTrash,nextReturnedNodes); Mockito.when(queryResult.getNodes()).thenReturn(nodeIterator); return sessionProvider; } return invocation.callRealMethod(); } }); PowerMockito.mockStatic(WCMCoreUtils.class, new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { String methodName = invocation.getMethod().getName(); if (StringUtils.equals(methodName, "getService") && invocation.getArgument(0, Class.class) != null) { Class<?> serviceClass = invocation.getArgument(0, Class.class); if (serviceClass.equals(TrashService.class)) { return new TrashService() { @Override public String moveToTrash(Node node, SessionProvider sessionProvider) throws Exception { return null; } @Override public String moveToTrash(Node node, SessionProvider sessionProvider, int deep) throws Exception { return null; } @Override public void restoreFromTrash(String trashNodePath, SessionProvider sessionProvider) throws Exception { } @Override public List<Node> getAllNodeInTrash(SessionProvider sessionProvider) throws Exception { return null; } @Override public List<Node> getAllNodeInTrashByUser(SessionProvider sessionProvider, String userName) throws Exception { return null; } @Override public void removeRelations(Node node, SessionProvider sessionProvider) throws Exception { } @Override public boolean isInTrash(Node node) throws RepositoryException { return node.getPath().startsWith("/Trash") && !node.getPath().equals("/Trash"); } @Override public Node getTrashHomeNode() { return null; } @Override public Node getNodeByTrashId(String trashId) throws InvalidQueryException, RepositoryException { return null; } }; } if (serviceClass.equals(PublicationService.class)) { PublicationService publicationService = Mockito.mock(PublicationService.class); Map<String,PublicationPlugin> publicationPlugins = new HashMap<>(); publicationPlugins.put(AuthoringPublicationConstant.LIFECYCLE_NAME, publicationPlugin); Mockito.when(publicationService.getPublicationPlugins()).thenReturn(publicationPlugins); return publicationService; } if (serviceClass.equals(RepositoryService.class)) { RepositoryService repositoryService = Mockito.mock(RepositoryService.class); ManageableRepository manageableRepository = mock(ManageableRepository.class); when(repositoryService.getCurrentRepository()).thenReturn(manageableRepository); return repositoryService; } } return invocation.callRealMethod(); } }); JobExecutionContext context = Mockito.mock(JobExecutionContext.class); JobDetail jobDetail = Mockito.mock(JobDetail.class); JobDataMap jobDataMap = Mockito.mock(JobDataMap.class); Mockito.when(context.getJobDetail()).thenReturn(jobDetail); Mockito.when(jobDetail.getJobDataMap()).thenReturn(jobDataMap); Mockito.when(jobDataMap.getString(Mockito.eq("fromState"))).thenReturn("staged"); Mockito.when(jobDataMap.getString(Mockito.eq("toState"))).thenReturn("published"); Mockito.when(jobDataMap.getString(Mockito.eq("predefinedPath"))).thenReturn("collaboration:/"); ChangeStateCronJobImpl cronJobImpl = new ChangeStateCronJobImpl(); cronJobImpl.execute(context); Mockito.verify(session, Mockito.times(0)).save(); Mockito.verify(publicationPlugin, Mockito.times(1)). changeState(Mockito.any(), Mockito.anyString(), Matchers.<HashMap<String, String>>any()); } }
10,129
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestUIPublicationPanel.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/test/java/org/exoplatform/services/wcm/extensions/publication/lifecycle/authoring/ui/TestUIPublicationPanel.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.services.wcm.extensions.publication.lifecycle.authoring.ui; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.exoplatform.services.jcr.access.AccessControlEntry; import org.exoplatform.services.jcr.access.AccessControlList; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.impl.core.NodeImpl; import org.exoplatform.services.security.Identity; import org.exoplatform.services.security.IdentityRegistry; import org.exoplatform.services.security.MembershipEntry; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.State; import junit.framework.TestCase; import static org.mockito.Mockito.*; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Mar 10, 2010 */ public class TestUIPublicationPanel extends TestCase { public void testIsAuthorizedByRole() throws Exception { UIPublicationPanel panel = mock(UIPublicationPanel.class); Identity tom = createIdentity("tom","validator:/org/human-resources"); Identity bill = createIdentity("bill","redactor:/org/human-resources","validator:/org/finances"); // configuring a mock node with the expected ACL List<AccessControlEntry> entries = new ArrayList<AccessControlEntry>(); entries.add(new AccessControlEntry("*:/org/finance", PermissionType.READ)); entries.add(new AccessControlEntry("*:/org/human-resources", PermissionType.SET_PROPERTY)); AccessControlList acl = new AccessControlList("foo", entries); NodeImpl node = mock(NodeImpl.class); when(node.getACL()).thenReturn(acl); State state = new State(); state.setRole("validator"); // // make sure the actual code we test is not mocked! when(panel.isAuthorizedByRole(any(State.class), any(Identity.class), any(NodeImpl.class))).thenCallRealMethod(); assertTrue("tom should be allowed", panel.isAuthorizedByRole(state, tom, node)); assertFalse("bill should not be allowed", panel.isAuthorizedByRole(state, bill, node)); } public void testIsAuthorizedByRoles() throws Exception { UIPublicationPanel panel = mock(UIPublicationPanel.class); Identity tom = createIdentity("tom","validator:/org/human-resources"); Identity bill = createIdentity("bill","redactor:/org/human-resources","validator:/org/finances"); Identity bart = createIdentity("bart","member:/org/human-resources"); // configuring a mock node with the expected ACL List<AccessControlEntry> entries = new ArrayList<AccessControlEntry>(); entries.add(new AccessControlEntry("*:/org/finance", PermissionType.READ)); entries.add(new AccessControlEntry("*:/org/human-resources", PermissionType.SET_PROPERTY)); AccessControlList acl = new AccessControlList("foo", entries); NodeImpl node = mock(NodeImpl.class); when(node.getACL()).thenReturn(acl); State state = new State(); state.setRoles(Arrays.asList(new String[] {"validator", "redactor"})); // // make sure the actual code we test is not mocked! when(panel.isAuthorizedByRole(any(State.class), any(Identity.class), any(NodeImpl.class))).thenCallRealMethod(); assertTrue("tom should be allowed", panel.isAuthorizedByRole(state, tom, node)); assertTrue("bill should be allowed", panel.isAuthorizedByRole(state, bill, node)); assertFalse("bart should not be allowed", panel.isAuthorizedByRole(state, bart, node)); } public void testIsAuthorizedByMemberships() throws Exception { UIPublicationPanel panel = mock(UIPublicationPanel.class); Identity tom = createIdentity("tom","validator:/org/human-resources"); Identity bill = createIdentity("bill","author:/CA/alerteInformatique","validator:/CA/informations"); List<String> memberships = new ArrayList<String>(); memberships.add("author:/CA/communicationDG"); memberships.add("author:/CA/alerteSanitaire"); memberships.add("author:/CA/alerteInformatique"); memberships.add("author:/CA/informations"); State state = new State(); state.setMemberships(memberships); // make sure the actual code we test is not mocked! when(panel.isAuthorizedByMembership(any(State.class), any(Identity.class))).thenCallRealMethod(); assertFalse("tom should not be allowed", panel.isAuthorizedByMembership(state, tom)); assertTrue("bill should be allowed", panel.isAuthorizedByMembership(state, bill)); } public void testIsAuthorizedByMembership() throws Exception { UIPublicationPanel panel = mock(UIPublicationPanel.class); Identity tom = createIdentity("tom","validator:/org/human-resources"); Identity bill = createIdentity("bill","redactor:/org/human-resources","redactor:/org/finance"); State state = new State(); state.setMembership("redactor:/org/finance"); // make sure the actual code we test is not mocked! when(panel.isAuthorizedByMembership(any(State.class), any(Identity.class))).thenCallRealMethod(); assertFalse("tom should not be allowed", panel.isAuthorizedByMembership(state, tom)); assertTrue("bill should be allowed", panel.isAuthorizedByMembership(state, bill)); } public void testCheckAllowed() throws Exception { UIPublicationPanel panel = mock(UIPublicationPanel.class); // mock the identity registry by our users IdentityRegistry registry = new IdentityRegistry(null); registerUser(registry, "tom","validator:/org/human-resources"); registerUser(registry, "bill","redactor:/org/human-resources","validator:/org/finances"); when(panel.getApplicationComponent(IdentityRegistry.class)).thenReturn(registry); // configuring a mock node with the expected ACL List<AccessControlEntry> entries = new ArrayList<AccessControlEntry>(); entries.add(new AccessControlEntry("*:/org/finances", PermissionType.READ)); entries.add(new AccessControlEntry("*:/org/human-resources", PermissionType.SET_PROPERTY)); AccessControlList acl = new AccessControlList("foo", entries); NodeImpl node = mock(NodeImpl.class); when(node.getACL()).thenReturn(acl); State state = new State(); state.setMembership("redactor:/org/finances"); state.setRole("validator"); // make sure the actual code we test is not mocked! when(panel.canReachState(any(State.class), anyString(), any(NodeImpl.class))).thenCallRealMethod(); when(panel.isAuthorizedByMembership(any(State.class), any(Identity.class))).thenCallRealMethod(); when(panel.isAuthorizedByRole(any(State.class), any(Identity.class), any(NodeImpl.class))).thenCallRealMethod(); assertTrue("tom should be allowed", panel.canReachState(state, "tom", node)); // not // allowed // by // membership, // allowed // by // role assertFalse("bill should be allowed", panel.canReachState(state, "bill", node)); // not // allowed // by // membership, // not // allowed // by // role } /** * Creates a new identity into an identity registry. Identity contains memberships. * @param registry the registry when to register the identity * @param userId for the identity to register * @param memberships list of memberships to assign to this user */ private void registerUser(IdentityRegistry registry, String userId, String ... memberships) { Identity identity = createIdentity(userId, memberships); registry.register(identity); } private Identity createIdentity(String userId, String... memberships) { Collection<MembershipEntry> membershipEntries = new ArrayList<MembershipEntry>(); for (String membership : memberships) { membershipEntries.add(new MembershipEntry(membership.split(":")[1], membership.split(":")[0])); } Identity identity = new Identity(userId,membershipEntries); return identity; } }
9,621
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
BasePublicationTestCase.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/test/java/exo/exoplatform/services/wcm/extensions/publication/BasePublicationTestCase.java
package exo.exoplatform.services.wcm.extensions.publication; import java.util.Date; import javax.jcr.Node; import org.exoplatform.component.test.ConfigurationUnit; import org.exoplatform.component.test.ConfiguredBy; import org.exoplatform.component.test.ContainerScope; import org.exoplatform.ecms.test.BaseECMSTestCase; @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/wcm/test-publication-configuration.xml") }) public abstract class BasePublicationTestCase extends BaseECMSTestCase { /** * Creates the webcontent node. * * @param parentNode the parent node * @param nodeName the node name * @param htmlData the html data * @param cssData the css data * @param jsData the js data * @return the node * @throws Exception the exception */ protected Node createWebcontentNode(Node parentNode, String nodeName, String htmlData, String cssData, String jsData) throws Exception { Node webcontent = parentNode.addNode(nodeName, "exo:webContent"); webcontent.setProperty("exo:title", nodeName); Node htmlNode; try { htmlNode = webcontent.getNode("default.html"); } catch (Exception ex) { htmlNode = webcontent.addNode("default.html", "nt:file"); } if (!htmlNode.isNodeType("exo:htmlFile")) htmlNode.addMixin("exo:htmlFile"); Node htmlContent; try { htmlContent = htmlNode.getNode("jcr:content"); } catch (Exception ex) { htmlContent = htmlNode.addNode("jcr:content", "nt:resource"); } htmlContent.setProperty("jcr:encoding", "UTF-8"); htmlContent.setProperty("jcr:mimeType", "text/html"); htmlContent.setProperty("jcr:lastModified", new Date().getTime()); if (htmlData == null) htmlData = "This is the default.html file."; htmlContent.setProperty("jcr:data", htmlData); Node jsFolder; try { jsFolder = webcontent.getNode("js"); } catch (Exception ex) { jsFolder = webcontent.addNode("js", "exo:jsFolder"); } Node documentsFolder; try { documentsFolder = webcontent.getNode("documents"); } catch (Exception ex) { documentsFolder = webcontent.addNode("documents", "nt:folder"); } Node jsNode; try { jsNode = jsFolder.getNode("default.js"); } catch (Exception ex) { jsNode = jsFolder.addNode("default.js", "nt:file"); } if (!jsNode.isNodeType("exo:jsFile")) jsNode.addMixin("exo:jsFile"); jsNode.setProperty("exo:active", true); jsNode.setProperty("exo:priority", 1); jsNode.setProperty("exo:sharedJS", true); Node jsContent; try { jsContent = jsNode.getNode("jcr:content"); } catch (Exception ex) { jsContent = jsNode.addNode("jcr:content", "nt:resource"); } jsContent.setProperty("jcr:encoding", "UTF-8"); jsContent.setProperty("jcr:mimeType", "text/javascript"); jsContent.setProperty("jcr:lastModified", new Date().getTime()); if (jsData == null) jsData = "This is the default.js file."; jsContent.setProperty("jcr:data", jsData); Node cssFolder; try { cssFolder = webcontent.getNode("css"); } catch (Exception ex) { cssFolder = webcontent.addNode("css", "exo:cssFolder"); } Node cssNode; try { cssNode = cssFolder.getNode("default.css"); } catch (Exception ex) { cssNode = cssFolder.addNode("default.css", "nt:file"); } if (!cssNode.isNodeType("exo:cssFile")) cssNode.addMixin("exo:cssFile"); cssNode.setProperty("exo:active", true); cssNode.setProperty("exo:priority", 1); cssNode.setProperty("exo:sharedCSS", true); Node cssContent; try { cssContent = cssNode.getNode("jcr:content"); } catch (Exception ex) { cssContent = cssNode.addNode("jcr:content", "nt:resource"); } cssContent.setProperty("jcr:encoding", "UTF-8"); cssContent.setProperty("jcr:mimeType", "text/css"); cssContent.setProperty("jcr:lastModified", new Date().getTime()); if (cssData == null) cssData = "This is the default.css file."; cssContent.setProperty("jcr:data", cssData); Node mediaFolder; try { mediaFolder = webcontent.getNode("medias"); } catch (Exception ex) { mediaFolder = webcontent.addNode("medias"); } if (!mediaFolder.hasNode("images")) mediaFolder.addNode("images", "nt:folder"); if (!mediaFolder.hasNode("videos")) mediaFolder.addNode("videos", "nt:folder"); if (!mediaFolder.hasNode("audio")) mediaFolder.addNode("audio", "nt:folder"); session.save(); return webcontent; } }
5,064
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestPublicationManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/test/java/exo/exoplatform/services/wcm/extensions/publication/TestPublicationManager.java
package exo.exoplatform.services.wcm.extensions.publication; import java.util.List; import javax.jcr.Node; import org.exoplatform.container.component.RequestLifeCycle; import org.exoplatform.services.security.*; import org.exoplatform.services.wcm.extensions.publication.PublicationManager; import org.exoplatform.services.wcm.publication.PublicationDefaultStates; import org.exoplatform.services.wcm.publication.WCMPublicationService; public class TestPublicationManager extends BasePublicationTestCase { private static final String SITE_NODE_NAME = "test"; private static final String USER = "root"; private static final String WORKSPACE = "collaboration"; private static final String LANG = "en"; private PublicationManager publicationManager; private WCMPublicationService publicationService; private Node siteNode; @Override public void setUp() throws Exception { // NOSONAR super.setUp(); publicationManager = getService(PublicationManager.class); publicationService = getService(WCMPublicationService.class); RequestLifeCycle.begin(getContainer()); applyUserSession(USER, "gtn", WORKSPACE); startSessionAs(USER); Node rootSite = (Node) session.getItem("/sites content/live"); siteNode = rootSite.addNode(SITE_NODE_NAME); siteNode.addNode("documents"); session.save(); } @Override public void tearDown() throws Exception {// NOSONAR if (siteNode != null && session.itemExists(siteNode.getPath())) { session.getItem(siteNode.getPath()).remove(); session.save(); } RequestLifeCycle.end(); super.tearDown(); } public void testFromStateParamJCRSQLInjection() throws Exception {// NOSONAR String user = USER; Node webContentNode = createWebcontentNode(siteNode.getNode("documents"), "testcontent", "Test html", "Test css", "test js"); publicationService.updateLifecyleOnChangeContent(webContentNode, SITE_NODE_NAME, user); assertEquals(PublicationDefaultStates.DRAFT, publicationService.getContentState(webContentNode)); String fromstate = "draft"; List<Node> contents = publicationManager.getContents(fromstate, null, null, user, LANG, WORKSPACE); assertNotNull(contents); assertEquals(1, contents.size()); fromstate = "draft' OR publication:currentState IS NULL OR publication:currentState = 'enrolled"; contents = publicationManager.getContents(fromstate, null, null, user, LANG, WORKSPACE); assertNotNull(contents); assertTrue(contents.isEmpty()); } public void testUserParamJCRSQLInjection() throws Exception {// NOSONAR String user = USER; Node webContentNode = createWebcontentNode(siteNode.getNode("documents"), "testcontent", "Test html", "Test css", "test js"); publicationService.updateLifecyleOnChangeContent(webContentNode, SITE_NODE_NAME, user); assertEquals(PublicationDefaultStates.DRAFT, publicationService.getContentState(webContentNode)); String fromstate = "draft"; List<Node> contents = publicationManager.getContents(fromstate, null, null, user, LANG, WORKSPACE); assertNotNull(contents); assertEquals(1, contents.size()); user = "root' OR publication:lastUser IS NULL OR publication:lastUser = 'any"; contents = publicationManager.getContents(fromstate, null, null, user, LANG, WORKSPACE); assertNotNull(contents); assertTrue(contents.isEmpty()); } private void startSessionAs(String user) { try { Authenticator authenticator = getContainer().getComponentInstanceOfType(Authenticator.class); Identity userIdentity = authenticator.createIdentity(user); ConversationState.setCurrent(new ConversationState(userIdentity)); } catch (Exception e) { throw new IllegalStateException(e); } } }
3,825
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestWCMPublicationService.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/test/java/exo/exoplatform/services/wcm/extensions/publication/TestWCMPublicationService.java
package exo.exoplatform.services.wcm.extensions.publication; import java.util.Date; import java.util.LinkedList; import javax.jcr.Node; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.component.RequestLifeCycle; import org.exoplatform.portal.config.DataStorage; import org.exoplatform.portal.config.model.Page; import org.exoplatform.portal.config.model.PortalConfig; import org.exoplatform.portal.mop.EventType; import org.exoplatform.portal.mop.navigation.NavigationService; import org.exoplatform.portal.pom.spi.portlet.Portlet; import org.exoplatform.services.ecm.publication.PublicationPlugin; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.listener.ListenerService; import org.exoplatform.services.organization.OrganizationService; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.Identity; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.publication.PublicationDefaultStates; import org.exoplatform.services.wcm.publication.WCMPublicationService; import org.exoplatform.services.wcm.publication.WebpagePublicationPlugin; import org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring.AuthoringPublicationPlugin; import org.exoplatform.services.wcm.utils.WCMCoreUtils; public class TestWCMPublicationService extends BasePublicationTestCase { private static final String CURRENT_STATE = "publication:currentState"; private static final String TEST = "test"; private static final String ENROLLED = "enrolled"; private static final String PUBLISHED = "published"; private WCMPublicationService publicationService_; private WebpagePublicationPlugin plugin_; private Node node_; private Node testSite; private Node documentTest; // ----------------- /** . */ private final String testPage = "portal::classic::testPage"; /** . */ private final String testPortletPreferences = "portal#classic:/web/BannerPortlet/testPortletPreferences"; /** . */ private DataStorage storage_; /** . */ private NavigationService navService; /** . */ private LinkedList<Event> events; /** . */ private ListenerService listenerService; /** . */ private OrganizationService org; public void setUp() throws Exception { super.setUp(); publicationService_ = WCMCoreUtils.getService(WCMPublicationService.class); RequestLifeCycle.begin(PortalContainer.getInstance()); applySystemSession(); Node rootSite = (Node) session.getItem("/sites content/live"); testSite = rootSite.addNode(TEST); documentTest = testSite.addNode("documents"); node_ = testSite.addNode(TEST); node_.addMixin(NodetypeConstant.MIX_REFERENCEABLE); session.save(); ConversationState c = new ConversationState(new Identity(session.getUserID())); ConversationState.setCurrent(c); plugin_ = new AuthoringPublicationPlugin(); plugin_.setName("Authoring publication"); plugin_.setDescription("Authoring publication"); publicationService_.addPublicationPlugin(plugin_); // -------------------------------- Listener listener = new Listener() { @Override public void onEvent(Event event) throws Exception { events.add(event); } }; PortalContainer container = PortalContainer.getInstance(); storage_ = (DataStorage) container.getComponentInstanceOfType(DataStorage.class); navService = (NavigationService) container.getComponentInstanceOfType(NavigationService.class); events = new LinkedList<Event>(); listenerService = (ListenerService) container.getComponentInstanceOfType(ListenerService.class); org = WCMCoreUtils.getService(OrganizationService.class); listenerService.addListener(DataStorage.PAGE_CREATED, listener); listenerService.addListener(DataStorage.PAGE_REMOVED, listener); listenerService.addListener(DataStorage.PAGE_UPDATED, listener); listenerService.addListener(EventType.NAVIGATION_CREATED, listener); listenerService.addListener(EventType.NAVIGATION_DESTROYED, listener); listenerService.addListener(EventType.NAVIGATION_UPDATED, listener); listenerService.addListener(DataStorage.PORTAL_CONFIG_CREATED, listener); listenerService.addListener(DataStorage.PORTAL_CONFIG_UPDATED, listener); listenerService.addListener(DataStorage.PORTAL_CONFIG_REMOVED, listener); } public void tearDown() throws Exception { publicationService_.getWebpagePublicationPlugins().clear(); node_.remove(); testSite.remove(); session.save(); RequestLifeCycle.end(); super.tearDown(); } /** * Test if a node is enrolled into a lifecycle * * @result current state of enrolled node is "enrolled" */ public void testEnrollNodeInLifecycle1() throws Exception { publicationService_.enrollNodeInLifecycle(node_, plugin_.getLifecycleName()); assertEquals(ENROLLED, node_.getProperty(CURRENT_STATE).getString()); } /** * Test if a node in site is enrolled into a lifecycle * * @result current state of enrolled is node "draft" */ public void testEnrollNodeInLifecycle2() throws Exception { publicationService_.enrollNodeInLifecycle(node_, "test", node_.getSession().getUserID()); assertEquals(PublicationDefaultStates.DRAFT, node_.getProperty(CURRENT_STATE).getString()); } /** * Test if a node is enrolled into WCM Lifecyle * * @result node is enrolled into WCM Lifecycle */ public void testIsEnrolledWCMInLifecycle() throws Exception { assertFalse(publicationService_.isEnrolledInWCMLifecycle(node_)); publicationService_.enrollNodeInLifecycle(node_, plugin_.getLifecycleName()); assertTrue(publicationService_.isEnrolledInWCMLifecycle(node_)); } /** * Test the getContentState function * * @result getContentState returns the "enrolled" status when a node is * enrolled into a lifecycle. */ public void testGetContentState() throws Exception { publicationService_.enrollNodeInLifecycle(node_, plugin_.getLifecycleName()); assertEquals(ENROLLED, publicationService_.getContentState(node_)); } /** * Test the unsubcribeLifecycle function * * @result Node is no longer enrolled into any lifecycle */ public void testUnsubscribeLifecycle() throws Exception { publicationService_.enrollNodeInLifecycle(node_, plugin_.getLifecycleName()); publicationService_.unsubcribeLifecycle(node_); assertFalse(publicationService_.isEnrolledInWCMLifecycle(node_)); } /** * Test if the state of a node can be changed in a lifecycle * * @result state of node can be changed */ public void testUpdateLifecyleOnChangeContent1() throws Exception { publicationService_.updateLifecyleOnChangeContent(node_, "test", node_.getSession().getUserID(), PublicationDefaultStates.PUBLISHED); assertEquals(PublicationDefaultStates.PUBLISHED, publicationService_.getContentState(node_)); publicationService_.updateLifecyleOnChangeContent(node_, "test", node_.getSession().getUserID(), PublicationDefaultStates.DRAFT); assertEquals(PublicationDefaultStates.DRAFT, publicationService_.getContentState(node_)); } /** * Test if the state of a node can be changed into default state * * @result state of node is in "draft" */ public void testUpdateLifecyleOnChangeContent2() throws Exception { publicationService_.updateLifecyleOnChangeContent(node_, "test", node_.getSession().getUserID()); assertEquals(PublicationDefaultStates.DRAFT, publicationService_.getContentState(node_)); } /** * Test if child node of webcontent cannot be enrolled into a lifecycle * * @result child node of webcontent cannot be enrolled into a lifecyle */ public void testUpdateLifecyleOnChangeContent3() throws Exception { String htmlData = "This is the default.html file."; Node webContent = createWebcontentNode(documentTest, "webcontent", "html", "css", "js"); Node documentFolder = webContent.getNode("documents"); Node htmlNode; try { htmlNode = documentFolder.getNode("default.html"); } catch (Exception ex) { htmlNode = documentFolder.addNode("default.html", "nt:file"); } if (!htmlNode.isNodeType("exo:htmlFile")) htmlNode.addMixin("exo:htmlFile"); Node htmlContent; try { htmlContent = htmlNode.getNode("jcr:content"); } catch (Exception ex) { htmlContent = htmlNode.addNode("jcr:content", "nt:resource"); } htmlContent.setProperty("jcr:encoding", "UTF-8"); htmlContent.setProperty("jcr:mimeType", "text/html"); htmlContent.setProperty("jcr:lastModified", new Date().getTime()); htmlContent.setProperty("jcr:data", htmlData); documentFolder.save(); publicationService_.updateLifecyleOnChangeContent(webContent, "test", webContent.getSession().getUserID()); assertEquals(PublicationDefaultStates.DRAFT, publicationService_.getContentState(webContent)); publicationService_.updateLifecyleOnChangeContent(htmlNode, "test", webContent.getSession().getUserID()); // ECMS-6460: Do not allow publishing children of webcontent assertEquals(null, publicationService_.getContentState(htmlNode)); } }
9,340
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CopyContentFile.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/wcm/connector/authoring/CopyContentFile.java
package org.exoplatform.wcm.connector.authoring; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.extensions.security.SHAMessageDigester; /** * Copies a file. * * @LevelAPI Provisional * * @anchor CopyContentFile */ @Path("/copyfile/") public class CopyContentFile implements ResourceContainer { private static final Log LOG = ExoLogger.getLogger(CopyContentFile.class.getName()); private static final String OK_RESPONSE = "OK"; private static final String KO_RESPONSE = "KO"; private String stagingStorage; private String targetKey; /** The Constant LAST_MODIFIED_PROPERTY. */ private static final String LAST_MODIFIED_PROPERTY = "Last-Modified"; /** The Constant IF_MODIFIED_SINCE_DATE_FORMAT. */ private static final String IF_MODIFIED_SINCE_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z"; public CopyContentFile(InitParams params) { stagingStorage = params.getValueParam("stagingStorage").getValue(); targetKey = params.getValueParam("targetKey").getValue(); } /** * Copies a file. * * @param param The file path. * @return Response inputstream. * @throws Exception The exception * * @anchor CopyContentFile.copyFile */ @POST @Path("/copy/") public Response copyFile(String param) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug("Start Execute CopyContentFile Web Service"); } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); try { String[] tabParam = param.split("&&"); String timesTamp = tabParam[0].split("=")[1]; String clientHash = tabParam[1].split("=")[1]; String contents = tabParam[2].split("contentsfile=")[1]; String[] tab = targetKey.split("$TIMESTAMP"); StringBuffer resultKey = new StringBuffer(); for (int k = 0; k < tab.length; k++) { resultKey.append(tab[k]); if (k != (tab.length - 1)) resultKey.append(timesTamp); } String serverHash = SHAMessageDigester.getHash(resultKey.toString()); if (serverHash != null && serverHash.equals(clientHash)) { Date date = new Date(); long time = date.getTime(); File stagingFolder = new File(stagingStorage); if (!stagingFolder.exists()) stagingFolder.mkdirs(); File contentsFile = new File(stagingStorage + File.separator + clientHash + "-" + time + ".xml"); OutputStream ops = new FileOutputStream(contentsFile); ops.write(contents.getBytes()); ops.close(); } else { if (LOG.isWarnEnabled()) { LOG.warn("Anthentification failed..."); } return Response.ok(KO_RESPONSE + "...Anthentification failed", "text/plain") .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } } catch (Exception ex) { if (LOG.isErrorEnabled()) { LOG.error("error when copying content file" + ex.getMessage()); } return Response.ok(KO_RESPONSE + "..." + ex.getMessage(), "text/plain") .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } if (LOG.isDebugEnabled()) { LOG.debug("Start Execute CopyContentFile Web Service"); } return Response.ok(OK_RESPONSE + "...content has been successfully copied in the production server", "text/plain") .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } }
4,192
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ContextComparator.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/utils/ContextComparator.java
package org.exoplatform.services.wcm.extensions.utils; import java.util.Comparator; import org.exoplatform.services.wcm.extensions.publication.context.impl.ContextConfig.Context; /** * Created by The eXo Platform MEA Author : * haikel.thamri@exoplatform.com */ public class ContextComparator implements Comparator{ public int compare(Object arg0, Object arg1) { Context context1=(Context)arg1; Context context0=(Context)arg0; int priority0=Integer.parseInt(context0.getPriority()); int priority1=Integer.parseInt(context1.getPriority()); if(priority0<priority1) { return -1; } else if (priority0>priority1) { return 1; } return 0; } }
708
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PublicationUtils.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/utils/PublicationUtils.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.services.wcm.extensions.utils; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import javax.jcr.Node; import javax.jcr.Session; import org.apache.commons.lang3.StringUtils; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ObjectParameter; import org.exoplatform.container.xml.PortalContainerInfo; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.extensions.deployment.PublicationDeploymentDescriptor; import org.exoplatform.services.wcm.publication.WCMPublicationService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Mar 16, 2012 */ public class PublicationUtils { private static final Log LOG = ExoLogger.getLogger(PublicationUtils.class.getName()); public static void deployPublicationToPortal(InitParams initParams, RepositoryService repositoryService, WCMPublicationService wcmPublicationService, SessionProvider sessionProvider, String portalName) throws Exception { Iterator iterator = initParams.getObjectParamIterator(); PublicationDeploymentDescriptor deploymentDescriptor = null; try { while (iterator.hasNext()) { ObjectParameter objectParameter = (ObjectParameter) iterator.next(); deploymentDescriptor = (PublicationDeploymentDescriptor) objectParameter.getObject(); List<String> contents = deploymentDescriptor.getContents(); // sourcePath should looks like : collaboration:/sites // content/live/acme HashMap<String, String> context_ = new HashMap<String, String>(); PublicationService publicationService = WCMCoreUtils.getService(PublicationService.class); PortalContainerInfo containerInfo = WCMCoreUtils.getService(PortalContainerInfo.class); String containerName = containerInfo.getContainerName(); context_.put("containerName", containerName); for (String sourcePath:contents) { try { if (portalName != null && portalName.length() > 0) { sourcePath = StringUtils.replace(sourcePath, "{portalName}", portalName); } String[] src = sourcePath.split(":"); if (src.length == 2) { ManageableRepository repository = repositoryService.getCurrentRepository(); Session session = sessionProvider.getSession(src[0], repository); Node nodeSrc = (Node) session.getItem(src[1]); if(publicationService.isNodeEnrolledInLifecycle(nodeSrc)) publicationService.unsubcribeLifecycle(nodeSrc); wcmPublicationService.updateLifecyleOnChangeContent(nodeSrc, "default", "__system", "published"); nodeSrc.save(); } if (LOG.isInfoEnabled()) { LOG.info(sourcePath + " has been published."); } } catch (Exception ex) { if (LOG.isErrorEnabled()) { LOG.error("publication for " + sourcePath + " FAILED at " + new Date().toString() + "\n", ex); } } } } } catch (Exception ex) { if (LOG.isErrorEnabled()) { LOG.error("publication plugin FAILED at " + new Date().toString() + "\n", ex); } throw ex; } } }
4,594
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
WCMPublicationDeploymentPlugin.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/deployment/WCMPublicationDeploymentPlugin.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.services.wcm.extensions.deployment; import java.io.InputStream; import java.util.Date; import java.util.Iterator; import java.util.Map; import javax.jcr.ImportUUIDBehavior; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Session; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ObjectParameter; import org.exoplatform.services.cms.documents.TrashService; import org.exoplatform.services.deployment.DeploymentPlugin; import org.exoplatform.services.deployment.Utils; import org.exoplatform.services.deployment.DeploymentUtils; import org.exoplatform.services.ecm.publication.NotInPublicationLifecycleException; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.publication.WCMPublicationService; /** * Created by The eXo Platform SAS * Author : eXoPlatform * tanhq@exoplatform.com * Oct 3, 2013 */ public class WCMPublicationDeploymentPlugin extends DeploymentPlugin{ /** The configuration manager. */ private ConfigurationManager configurationManager; /** The repository service. */ private RepositoryService repositoryService; /** The publication service */ private PublicationService publicationService; /** The publication service */ private WCMPublicationService wcmPublicationService; private TrashService trashService; /** The log. */ private static final Log LOG = ExoLogger.getLogger(WCMPublicationDeploymentPlugin.class.getName()); private static final String CLEAN_PUBLICATION = "clean-publication"; private static final String PUBLISH_FIRST_PUBLICATION = "publish-first-publication"; private static final String KEEP_PUBLICATION = "keep-publication"; /** * Instantiates a new xML deployment plugin. * * @param initParams the init params * @param configurationManager the configuration manager * @param repositoryService the repository service * @param publicationService the publication service */ public WCMPublicationDeploymentPlugin(InitParams initParams, ConfigurationManager configurationManager, RepositoryService repositoryService, PublicationService publicationService, WCMPublicationService wcmPublicationService, TrashService trashService) { super(initParams); this.configurationManager = configurationManager; this.repositoryService = repositoryService; this.publicationService = publicationService; this.wcmPublicationService = wcmPublicationService; this.trashService = trashService; } /* * (non-Javadoc) * @see * org.exoplatform.services.deployment.DeploymentPlugin#deploy(org.exoplatform * .services.jcr.ext.common.SessionProvider) */ public void deploy(SessionProvider sessionProvider) throws Exception { ManageableRepository repository = repositoryService.getCurrentRepository(); Iterator iterator = initParams.getObjectParamIterator(); WCMPublicationDeploymentDescriptor deploymentDescriptor = null; while (iterator.hasNext()) { try { ObjectParameter objectParameter = (ObjectParameter) iterator.next(); deploymentDescriptor = (WCMPublicationDeploymentDescriptor) objectParameter.getObject(); String sourcePath = deploymentDescriptor.getSourcePath(); // sourcePath should start with: war:/, jar:/, classpath:/, file:/ String versionHistoryPath = deploymentDescriptor.getVersionHistoryPath(); String cleanupPublicationType = deploymentDescriptor.getCleanupPublicationType(); InputStream inputStream = configurationManager.getInputStream(sourcePath); Session session = sessionProvider.getSession(deploymentDescriptor.getTarget().getWorkspace(), repository); String nodeName = DeploymentUtils.getNodeName(configurationManager.getInputStream(sourcePath)); //remove old resources if (this.isOverride()) { Node parent = (Node)session.getItem(deploymentDescriptor.getTarget().getNodePath()); if (parent.hasNode(nodeName)) { trashService.moveToTrash(parent.getNode(nodeName), sessionProvider); } } session.importXML(deploymentDescriptor.getTarget().getNodePath(), inputStream, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW); if (CLEAN_PUBLICATION.equalsIgnoreCase(cleanupPublicationType) || PUBLISH_FIRST_PUBLICATION.equalsIgnoreCase(cleanupPublicationType)) { /** * This code allows to cleanup the publication lifecycle and publish the first version in the target * folder after importing the data. By using this, the publication * live revision property will be re-initialized and the content will * be set as published directly. Thus, the content will be visible in * front side. */ Node parent = (Node)session.getItem(deploymentDescriptor.getTarget().getNodePath() + "/" + nodeName); cleanPublication(parent, cleanupPublicationType, true); } else if (versionHistoryPath != null && versionHistoryPath.length() > 0) { // process import version history Node currentNode = (Node) session.getItem(deploymentDescriptor.getTarget().getNodePath()); Map<String, String> mapHistoryValue = Utils.getMapImportHistory(configurationManager.getInputStream(versionHistoryPath)); Utils.processImportHistory(currentNode, configurationManager.getInputStream(versionHistoryPath), mapHistoryValue); } session.save(); } catch (Exception ex) { if (LOG.isErrorEnabled()) { LOG.error("deploy " + deploymentDescriptor.getSourcePath() + " into " + deploymentDescriptor.getTarget().getNodePath() + " is FAILURE at " + new Date().toString() + "\n", ex); } } } if (LOG.isInfoEnabled()) { LOG.info(deploymentDescriptor.getSourcePath() + " is deployed succesfully into " + deploymentDescriptor.getTarget().getNodePath()); } } /** * This method implement cleaning publication based on cleanPublicationType. The cleanPublicationType can accept one of three values as following: - clean-publication: This code allows to cleanup the publication lifecycle. - keep-publication : This option allows to keep all current publications - publish-first-publication: This option allows to cleanup the publication lifecycle and publish the first version in the target folder * @param cleanupPublicationType the type of cleaning publication * @throws Exception * @throws NotInPublicationLifecycleException */ private void cleanPublication(Node node, String cleanupPublicationType, boolean updateLifecycle) throws NotInPublicationLifecycleException, Exception { if (node.hasProperty("publication:liveRevision") && node.hasProperty("publication:currentState")) { if (LOG.isInfoEnabled()) { LOG.info("\"" + node.getName() + "\" publication lifecycle has been cleaned up"); } node.setProperty("publication:liveRevision", (javax.jcr.Value) null); node.setProperty("publication:currentState", "published"); } node.getSession().save(); if(updateLifecycle && PUBLISH_FIRST_PUBLICATION.equalsIgnoreCase(cleanupPublicationType) && org.exoplatform.services.cms.impl.Utils.isDocument(node)) { if(publicationService.isNodeEnrolledInLifecycle(node)) publicationService.unsubcribeLifecycle(node); wcmPublicationService.updateLifecyleOnChangeContent(node, "default", "__system", "published"); node.save(); } NodeIterator iter = node.getNodes(); while (iter.hasNext()) { Node childNode = iter.nextNode(); cleanPublication(childNode, cleanupPublicationType, false); } } }
9,286
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PublicationDeploymentDescriptor.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/deployment/PublicationDeploymentDescriptor.java
package org.exoplatform.services.wcm.extensions.deployment; import java.util.List; public class PublicationDeploymentDescriptor { private List<String> contents; public List<String> getContents() { return contents; } public void setContents(List<String> contents) { this.contents = contents; } }
318
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PublicationDeploymentPlugin.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/deployment/PublicationDeploymentPlugin.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.services.wcm.extensions.deployment; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.deployment.DeploymentPlugin; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.RepositoryService; 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.extensions.utils.PublicationUtils; import org.exoplatform.services.wcm.publication.WCMPublicationService; /** * Created by The eXo Platform SAS * Author : Hoa Pham * hoa.pham@exoplatform.com * Sep 6, 2008 */ public class PublicationDeploymentPlugin extends DeploymentPlugin { /** The repository service. */ private RepositoryService repositoryService; /** The publication service */ private WCMPublicationService wcmPublicationService; /** The publication service */ private PublicationService publicationService; /** The log. */ private static final Log LOG = ExoLogger.getLogger(PublicationDeploymentPlugin.class.getName()); public static final String UPDATE_EVENT = "WCMPublicationService.event.updateState"; /** * Instantiates a new xML deployment plugin. * * @param initParams the init params * @param repositoryService the repository service * @param publicationService the publication service */ public PublicationDeploymentPlugin(InitParams initParams, RepositoryService repositoryService, PublicationService publicationService, WCMPublicationService wcmPublicationService) { super(initParams); this.repositoryService = repositoryService; this.publicationService = publicationService; this.wcmPublicationService = wcmPublicationService; } /* (non-Javadoc) * @see org.exoplatform.services.deployment.DeploymentPlugin#deploy(org.exoplatform.services.jcr.ext.common.SessionProvider) */ public void deploy(SessionProvider sessionProvider) throws Exception { PublicationUtils.deployPublicationToPortal(initParams, repositoryService, wcmPublicationService, sessionProvider, null); } }
2,975
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CreatePortalPublicationPlugin.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/deployment/CreatePortalPublicationPlugin.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.services.wcm.extensions.deployment; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.wcm.extensions.utils.PublicationUtils; import org.exoplatform.services.wcm.portal.artifacts.CreatePortalPlugin; import org.exoplatform.services.wcm.publication.WCMPublicationService; /** * Created by The eXo Platform SAS * Author : Hoa Pham * hoa.pham@exoplatform.com * Sep 6, 2008 */ public class CreatePortalPublicationPlugin extends CreatePortalPlugin { /** The init params. */ private InitParams initParams; /** The repository service. */ private RepositoryService repositoryService; /** The publication service */ private WCMPublicationService wcmPublicationService; /** The publication service */ private PublicationService publicationService; public static final String UPDATE_EVENT = "WCMPublicationService.event.updateState"; /** * Instantiates a new xML deployment plugin. * * @param initParams the init params * @param repositoryService the repository service * @param publicationService the publication service */ public CreatePortalPublicationPlugin(InitParams initParams, ConfigurationManager configurationManager, RepositoryService repositoryService, PublicationService publicationService, WCMPublicationService wcmPublicationService) { super(initParams, configurationManager, repositoryService); this.initParams = initParams; this.repositoryService = repositoryService; this.publicationService = publicationService; this.wcmPublicationService = wcmPublicationService; } /* (non-Javadoc) * @see org.exoplatform.services.deployment.DeploymentPlugin#deploy(org.exoplatform.services.jcr.ext.common.SessionProvider) */ public void deployToPortal(SessionProvider sessionProvider, String portalName) throws Exception { PublicationUtils.deployPublicationToPortal(initParams, repositoryService, wcmPublicationService, sessionProvider, portalName); } }
3,102
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
WCMPublicationDeploymentDescriptor.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/deployment/WCMPublicationDeploymentDescriptor.java
package org.exoplatform.services.wcm.extensions.deployment; import org.exoplatform.services.deployment.DeploymentDescriptor; /* * 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/>. */ /** * Created by The eXo Platform SAS * Author : eXoPlatform * tanhq@exoplatform.com * Oct 3, 2013 */ public class WCMPublicationDeploymentDescriptor extends DeploymentDescriptor{ private String cleanupPublicationType = "clean-publication"; public String getCleanupPublicationType() { return cleanupPublicationType; } public void setCleanupPublicationType(String cleanupPublicationType) { this.cleanupPublicationType = cleanupPublicationType; } }
1,335
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
SHAMessageDigester.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/security/SHAMessageDigester.java
package org.exoplatform.services.wcm.extensions.security; import java.security.MessageDigest; /** * Created by The eXo Platform MEA Author : * haikel.thamri@exoplatform.com */ public class SHAMessageDigester { public static String getHash(String message) throws Exception { MessageDigest msgDigest = MessageDigest.getInstance("SHA-1"); msgDigest.update(message.getBytes()); byte[] aMessageDigest = msgDigest.digest(); StringBuffer ticket = new StringBuffer(); String tmp = null; for (int i = 0; i < aMessageDigest.length; i++) { tmp = Integer.toHexString(0xFF & aMessageDigest[i]); if (tmp.length() == 2) { ticket.append(tmp); } else { ticket.append("0"); ticket.append(tmp); } } return ticket.toString(); } }
802
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
BackCronJob.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/scheduler/BackCronJob.java
package org.exoplatform.services.wcm.extensions.scheduler; import org.exoplatform.commons.utils.ExoProperties; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.scheduler.CronJob; import org.quartz.JobDataMap; /** * Created by The eXo Platform MEA Author : * haikel.thamri@exoplatform.com */ public class BackCronJob extends CronJob { private static final Log LOG = ExoLogger.getLogger(BackCronJob.class.getName()); private JobDataMap jobDataMap; public BackCronJob(InitParams params) throws Exception { super(params); if (LOG.isInfoEnabled()) { LOG.info("Start Init BackCronJob"); } ExoProperties props = params.getPropertiesParam("exportContentJob.generalParams").getProperties(); jobDataMap = new JobDataMap(); String fromState = props.getProperty("fromState"); jobDataMap.put("fromState", fromState); String toState = props.getProperty("toState"); jobDataMap.put("toState", toState); String localTempDir = props.getProperty("localTempDir"); jobDataMap.put("localTempDir", localTempDir); String targetServerUrl = props.getProperty("targetServerUrl"); jobDataMap.put("targetServerUrl", targetServerUrl); String targetKey = props.getProperty("targetKey"); jobDataMap.put("targetKey", targetKey); String predefinedPath = props.getProperty("predefinedPath"); jobDataMap.put("predefinedPath", predefinedPath); if (LOG.isInfoEnabled()) { LOG.info("CronJob Param...fromState : " + fromState + ", toState : " + toState + ", localTempDir : " + localTempDir + ", targetServerUrl : " + targetServerUrl); LOG.info("End Init BackCronJob"); } } public JobDataMap getJobDataMap() { return jobDataMap; } }
1,858
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FrontCronJob.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/scheduler/FrontCronJob.java
package org.exoplatform.services.wcm.extensions.scheduler; import org.exoplatform.commons.utils.ExoProperties; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.scheduler.CronJob; import org.quartz.JobDataMap; /** * Created by The eXo Platform MEA Author : * haikel.thamri@exoplatform.com */ public class FrontCronJob extends CronJob { private static final Log LOG = ExoLogger.getLogger(FrontCronJob.class.getName()); private JobDataMap jobDataMap; /** * * @param params * : les parametres d'init pour le plugin * @throws Exception */ public FrontCronJob(InitParams params) throws Exception { super(params); if (LOG.isInfoEnabled()) { LOG.info("Start Init CronJob"); } jobDataMap = new JobDataMap(); ExoProperties props = params.getPropertiesParam("importContentJob.generalParams").getProperties(); String stagingStorage = props.getProperty("stagingStorage"); String temporaryStorge = props.getProperty("temporaryStorge"); jobDataMap.put("stagingStorage", stagingStorage); jobDataMap.put("temporaryStorge", temporaryStorge); if (LOG.isInfoEnabled()) { LOG.info("CronJob Params...stagingStorage : " + stagingStorage + ", temporaryStorge :" + temporaryStorge); LOG.info("End Init CronJob"); } } /** * * @return JobDataMap */ public JobDataMap getJobDataMap() { return jobDataMap; } }
1,651
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ChangeStateCronJob.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/scheduler/ChangeStateCronJob.java
package org.exoplatform.services.wcm.extensions.scheduler; import org.exoplatform.commons.utils.ExoProperties; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.scheduler.CronJob; import org.quartz.JobDataMap; /** * Created by The eXo Platform MEA Author : haikel.thamri@exoplatform.com */ public class ChangeStateCronJob extends CronJob { private static final Log LOG = ExoLogger.getLogger(ChangeStateCronJob.class.getName()); private JobDataMap jobDataMap; public ChangeStateCronJob(InitParams params) throws Exception { super(params); if (LOG.isInfoEnabled()) { LOG.info("Start Init ChangeStateCronJob"); } ExoProperties props = params.getPropertiesParam("changeStateCronJob.generalParams") .getProperties(); jobDataMap = new JobDataMap(); String fromState = props.getProperty("fromState"); jobDataMap.put("fromState", fromState); String toState = props.getProperty("toState"); jobDataMap.put("toState", toState); String predefinedPath = props.getProperty("predefinedPath"); jobDataMap.put("predefinedPath", predefinedPath); if (LOG.isInfoEnabled()) { LOG.info("CronJob Param...fromState : " + fromState + ", toState : " + toState + ", predefinedPath : " + predefinedPath); LOG.info("End Init ChangeStateCronJob"); } } public JobDataMap getJobDataMap() { return jobDataMap; } }
1,589
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ChangeStateCronJobImpl.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/scheduler/impl/ChangeStateCronJobImpl.java
package org.exoplatform.services.wcm.extensions.scheduler.impl; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import javax.jcr.Node; import javax.jcr.NodeIterator; 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.services.cms.documents.TrashService; import org.exoplatform.services.ecm.publication.PublicationPlugin; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring.AuthoringPublicationConstant; import org.exoplatform.services.wcm.publication.PublicationDefaultStates; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; /** * Created by The eXo Platform MEA Author : haikel.thamri@exoplatform.com */ public class ChangeStateCronJobImpl implements Job { private static final Log LOG = ExoLogger.getLogger(ChangeStateCronJobImpl.class.getName()); private static final String START_TIME_PROPERTY = "publication:startPublishedDate"; private static final String END_TIME_PROPERTY = "publication:endPublishedDate"; private static final int NORMAL_NODE = 0; private static final int STAGED_NODE = 1; private String fromState = null; private String toState = null; private String predefinedPath = null; private String workspace = null; private String contentPath = null; public void execute(JobExecutionContext context) throws JobExecutionException { SessionProvider sessionProvider = null; try { RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean(); if (mx.getUptime()>120000) { if (LOG.isDebugEnabled()) LOG.debug("Start Execute ChangeStateCronJob"); if (fromState == null) { JobDataMap jdatamap = context.getJobDetail().getJobDataMap(); fromState = jdatamap.getString("fromState"); toState = jdatamap.getString("toState"); predefinedPath = jdatamap.getString("predefinedPath"); String[] pathTab = predefinedPath.split(":"); workspace = pathTab[0]; contentPath = pathTab[1]; } if (LOG.isDebugEnabled()) LOG.debug("Start Execute ChangeStateCronJob: change the State from " + fromState + " to " + toState); sessionProvider = SessionProvider.createSystemProvider(); String property = null; if ("staged".equals(fromState) && "published".equals(toState)) { property = START_TIME_PROPERTY; } else if ("published".equals(fromState) && "unpublished".equals(toState)) { property = END_TIME_PROPERTY; } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); Date now = Calendar.getInstance().getTime(); String currentTime = format.format(now); if (property != null) { // appends trailing / if missing if (contentPath != null) { if (!contentPath.endsWith("/")) { contentPath += "/"; } } StringBuilder normalNodesStatement = new StringBuilder().append("select * from nt:base where "). append("(publication:currentState='").append(fromState).append("') "). append(" and (").append(property).append(" IS NOT NULL )"). append(" and (").append(property).append(" < TIMESTAMP '").append(currentTime).append("') "). append(" and (jcr:path like '").append(contentPath).append("%' )"); StringBuilder stagedNodesStatement = new StringBuilder().append("select * from nt:base where "). append("(publication:currentState='").append(fromState).append("') "). append(" and (").append(property).append(" IS NULL ) "). append(" and (jcr:path like '").append(contentPath).append("%' )"); long normalCount = changeStateForNodes(sessionProvider, property, NORMAL_NODE, normalNodesStatement.toString()); long stagedCount = (START_TIME_PROPERTY.equals(property)) ? changeStateForNodes(sessionProvider, property, STAGED_NODE, stagedNodesStatement.toString()) : 0; long numberOfItemsToChange = normalCount + stagedCount; if (numberOfItemsToChange > 0) { if (LOG.isDebugEnabled()) { LOG.debug(numberOfItemsToChange + " '" + fromState + "' candidates for state '" + toState + "' found in " + predefinedPath); } } else { if (LOG.isDebugEnabled()) { LOG.debug("no '" + fromState + "' content found in " + predefinedPath); } } } if (LOG.isDebugEnabled()) LOG.debug("End Execute ChangeStateCronJob"); } } catch (RepositoryException ex) { if (LOG.isErrorEnabled()) LOG.error("Repository not found. Ignoring : " + ex.getMessage(), ex); } catch (Exception ex) { if (LOG.isErrorEnabled()) LOG.error("error when changing nodes states : " + ex.getMessage(), ex); } finally { if (sessionProvider != null) sessionProvider.close(); } } private long changeStateForNodes(SessionProvider sessionProvider, String property, int nodeType, String statement) throws Exception { long ret = 0; RepositoryService repositoryService_ = WCMCoreUtils.getService(RepositoryService.class); PublicationService publicationService = WCMCoreUtils.getService(PublicationService.class); TrashService trashService = WCMCoreUtils.getService(TrashService.class); PublicationPlugin publicationPlugin = publicationService.getPublicationPlugins() .get(AuthoringPublicationConstant.LIFECYCLE_NAME); HashMap<String, String> context_ = new HashMap<String, String>(); ManageableRepository manageableRepository = repositoryService_.getCurrentRepository(); if (manageableRepository == null) { if (LOG.isDebugEnabled()) LOG.debug("Repository not found. Ignoring"); return 0; } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); Session session = sessionProvider.getSession(workspace, manageableRepository); QueryManager queryManager = session.getWorkspace().getQueryManager(); Query query = queryManager.createQuery(statement, Query.SQL); QueryResult queryResult = query.execute(); for (NodeIterator iter = queryResult.getNodes(); iter.hasNext();) { Node node_ = iter.nextNode(); String path = node_.getPath(); try { if (!path.startsWith("/jcr:system") && !trashService.isInTrash(node_)) { if (NORMAL_NODE == nodeType) { Date nodeDate = node_.getProperty(property).getDate().getTime(); if (LOG.isInfoEnabled()) LOG.info("'" + toState + "' " + node_.getPath() + " (" + property + "=" + format.format(nodeDate) + ")"); if (PublicationDefaultStates.UNPUBLISHED.equals(toState)) { if (node_.hasProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP)) { String liveRevisionProperty = node_.getProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP) .getString(); if (!"".equals(liveRevisionProperty)) { Node liveRevision = session.getNodeByUUID(liveRevisionProperty); if (liveRevision != null) { context_.put(AuthoringPublicationConstant.CURRENT_REVISION_NAME, liveRevision.getName()); } } } } publicationPlugin.changeState(node_, toState, context_); ret++; } else if (!PublicationDefaultStates.STAGED.equals(fromState)){ LOG.info("'{}' {}", toState, node_.getPath()); publicationPlugin.changeState(node_, toState, context_); } if (START_TIME_PROPERTY.equals(property) && node_.hasProperty(START_TIME_PROPERTY)) { node_.getProperty(START_TIME_PROPERTY).remove(); node_.save(); } if (END_TIME_PROPERTY.equals(property) && node_.hasProperty(END_TIME_PROPERTY)) { node_.getProperty(END_TIME_PROPERTY).remove(); node_.save(); } } } catch ( Exception e ) { if (LOG.isErrorEnabled()) LOG.error("error when changing the state of the content : "+ node_.getPath() , e); } } return ret; } }
9,744
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ExportContentJob.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/scheduler/impl/ExportContentJob.java
package org.exoplatform.services.wcm.extensions.scheduler.impl; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.sql.Timestamp; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import org.exoplatform.services.cms.taxonomy.TaxonomyService; import org.exoplatform.services.ecm.publication.PublicationPlugin; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring.AuthoringPublicationConstant; import org.exoplatform.services.wcm.extensions.security.SHAMessageDigester; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; /** * Created by The eXo Platform MEA Author : haikel.thamri@exoplatform.com */ public class ExportContentJob implements Job { private static final Log LOG = ExoLogger.getLogger(ExportContentJob.class.getName()); private static final String MIX_TARGET_PATH = "mix:targetPath"; private static final String MIX_TARGET_WORKSPACE = "mix:targetWorkspace"; private static final String URL = "http://www.w3.org/2001/XMLSchema"; private static final String START_TIME_PROPERTY = "publication:startPublishedDate"; private String fromState = null; private String toState = null; private String localTempDir = null; private String targetServerUrl = null; private String targetKey = null; private String predefinedPath = null; private String workspace = null; private String contentPath = null; public void execute(JobExecutionContext context) throws JobExecutionException { Session session = null; try { if (LOG.isInfoEnabled()) { LOG.info("Start Execute ExportContentJob"); } if (fromState == null) { JobDataMap jdatamap = context.getJobDetail().getJobDataMap(); fromState = jdatamap.getString("fromState"); toState = jdatamap.getString("toState"); localTempDir = jdatamap.getString("localTempDir"); targetServerUrl = jdatamap.getString("targetServerUrl"); targetKey = jdatamap.getString("targetKey"); predefinedPath = jdatamap.getString("predefinedPath"); String[] pathTab = predefinedPath.split(":"); workspace = pathTab[1]; contentPath = pathTab[2]; if (LOG.isDebugEnabled()) { LOG.debug("Init parameters first time :"); LOG.debug("\tFromState = " + fromState); LOG.debug("\tToState = " + toState); LOG.debug("\tLocalTempDir = " + localTempDir); LOG.debug("\tTargetServerUrl = " + targetServerUrl); } } SessionProvider sessionProvider = SessionProvider.createSystemProvider(); String containerName = WCMCoreUtils.getContainerNameFromJobContext(context); RepositoryService repositoryService = WCMCoreUtils.getService(RepositoryService.class, containerName); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); PublicationService publicationService = WCMCoreUtils.getService(PublicationService.class, containerName); PublicationPlugin publicationPlugin = publicationService.getPublicationPlugins() .get(AuthoringPublicationConstant.LIFECYCLE_NAME); session = sessionProvider.getSession(workspace, manageableRepository); QueryManager queryManager = session.getWorkspace().getQueryManager(); boolean isExported = false; Query query = queryManager.createQuery("select * from nt:base where publication:currentState='" + fromState + "' and jcr:path like '" + contentPath + "/%'", Query.SQL); File exportFolder = new File(localTempDir); if (!exportFolder.exists()) exportFolder.mkdirs(); Date date = new Date(); long time = date.getTime(); File file = new File(localTempDir + File.separatorChar + time + ".xml"); ByteArrayOutputStream bos = null; List<Node> categorySymLinks = null; XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); FileOutputStream output = new FileOutputStream(file); XMLStreamWriter xmlsw = outputFactory.createXMLStreamWriter(output, "UTF-8"); xmlsw.writeStartDocument("UTF-8", "1.0"); xmlsw.writeStartElement("xs", "contents", URL); xmlsw.writeNamespace("xs", URL); QueryResult queryResult = query.execute(); if (queryResult.getNodes().getSize() > 0) { TaxonomyService taxonomyService = WCMCoreUtils.getService(TaxonomyService.class, containerName); Date nodeDate = null; Date now = null; xmlsw.writeStartElement("xs", "published-contents", URL); for (NodeIterator iter = queryResult.getNodes(); iter.hasNext();) { Node node = iter.nextNode(); nodeDate = null; if (node.hasProperty(START_TIME_PROPERTY)) { now = Calendar.getInstance().getTime(); nodeDate = node.getProperty(START_TIME_PROPERTY).getDate().getTime(); } if (nodeDate == null || now.compareTo(nodeDate) >= 0) { if (node.canAddMixin(MIX_TARGET_PATH)) node.addMixin(MIX_TARGET_PATH); node.setProperty(MIX_TARGET_PATH, node.getPath()); if (node.canAddMixin(MIX_TARGET_WORKSPACE)) node.addMixin(MIX_TARGET_WORKSPACE); node.setProperty(MIX_TARGET_WORKSPACE, workspace); node.save(); HashMap<String, String> context_ = new HashMap<>(); context_.put("containerName", containerName); publicationPlugin.changeState(node, toState, context_); if (LOG.isInfoEnabled()) { LOG.info("change the status of the node " + node.getPath() + " to " + toState); } bos = new ByteArrayOutputStream(); NodeLocation nodeLocation = NodeLocation.getNodeLocationByNode(node); StringBuilder contenTargetPath = new StringBuilder(); contenTargetPath.append(nodeLocation.getRepository()); contenTargetPath.append(":"); contenTargetPath.append(nodeLocation.getWorkspace()); contenTargetPath.append(":"); contenTargetPath.append(nodeLocation.getPath()); session.exportSystemView(node.getPath(), bos, false, false); if (!isExported) isExported = true; xmlsw.writeStartElement("xs", "published-content", URL); xmlsw.writeAttribute("targetPath", contenTargetPath.toString()); xmlsw.writeStartElement("xs", "data", URL); xmlsw.writeCData(bos.toString()); xmlsw.writeEndElement(); xmlsw.writeStartElement("xs", "links", URL); categorySymLinks = taxonomyService.getAllCategories(node, true); for (Node nodeSymlink : categorySymLinks) { NodeLocation symlinkLocation = NodeLocation.getNodeLocationByNode(nodeSymlink); StringBuilder symlinkTargetPath = new StringBuilder(); symlinkTargetPath.append(symlinkLocation.getRepository()); symlinkTargetPath.append(":"); symlinkTargetPath.append(symlinkLocation.getWorkspace()); symlinkTargetPath.append(":"); symlinkTargetPath.append(symlinkLocation.getPath()); xmlsw.writeStartElement("xs", "link", URL); xmlsw.writeStartElement("xs", "type", URL); xmlsw.writeCharacters("exo:taxonomyLink"); xmlsw.writeEndElement(); xmlsw.writeStartElement("xs", "title", URL); xmlsw.writeCharacters(node.getName()); xmlsw.writeEndElement(); xmlsw.writeStartElement("xs", "targetPath", URL); xmlsw.writeCharacters(symlinkTargetPath.toString()); xmlsw.writeEndElement(); xmlsw.writeEndElement(); } xmlsw.writeEndElement(); xmlsw.writeEndElement(); } } xmlsw.writeEndElement(); } query = queryManager.createQuery("select * from nt:base where publication:currentState='unpublished' and jcr:path like '" + contentPath + "/%'", Query.SQL); queryResult = query.execute(); if (queryResult.getNodes().getSize() > 0) { xmlsw.writeStartElement("xs", "unpublished-contents", URL); for (NodeIterator iter = queryResult.getNodes(); iter.hasNext();) { Node node = iter.nextNode(); if (node.isNodeType("nt:frozenNode")) continue; NodeLocation nodeLocation = NodeLocation.getNodeLocationByNode(node); StringBuilder contenTargetPath = new StringBuilder(); contenTargetPath.append(nodeLocation.getRepository()); contenTargetPath.append(":"); contenTargetPath.append(nodeLocation.getWorkspace()); contenTargetPath.append(":"); contenTargetPath.append(nodeLocation.getPath()); xmlsw.writeStartElement("xs", "unpublished-content", URL); xmlsw.writeAttribute("targetPath", contenTargetPath.toString()); xmlsw.writeEndElement(); if (!isExported) isExported = true; } xmlsw.writeEndElement(); } xmlsw.writeEndElement(); if (bos != null) { bos.close(); } xmlsw.flush(); output.close(); xmlsw.close(); if (!isExported) file.delete(); File[] files = exportFolder.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { // connect URI uri = new URI(targetServerUrl + "/copyfile/copy/"); URL url = uri.toURL(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // initialize the connection connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setRequestProperty("Content-type", "text/plain"); connection.setRequestProperty("Connection", "Keep-Alive"); OutputStream out = connection.getOutputStream(); BufferedReader reader = new BufferedReader(new FileReader(files[i].getPath())); char[] buf = new char[1024]; int numRead = 0; Date date_ = new Date(); Timestamp time_ = new Timestamp(date_.getTime()); String[] tab = targetKey.split("$TIMESTAMP"); StringBuilder resultKey = new StringBuilder(); for (int k = 0; k < tab.length; k++) { resultKey.append(tab[k]); if (k != (tab.length - 1)) resultKey.append(time_.toString()); } String hashCode = SHAMessageDigester.getHash(resultKey.toString()); StringBuilder param = new StringBuilder(); param.append("timestamp=" + time_.toString() + "&&hashcode=" + hashCode + "&&contentsfile="); while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); param.append(readData); } reader.close(); out.write(param.toString().getBytes()); out.flush(); connection.connect(); BufferedReader inStream = new BufferedReader(new InputStreamReader(connection.getInputStream())); out.close(); String string = null; while ((string = inStream.readLine()) != null) { if (LOG.isDebugEnabled()) { LOG.debug("The response of the production server:" + string); } } connection.disconnect(); files[i].delete(); } } if (LOG.isInfoEnabled()) { LOG.info("End Execute ExportContentJob"); } } catch (RepositoryException ex) { if (LOG.isErrorEnabled()) { LOG.error("Repository 'repository ' not found.", ex); } } catch (ConnectException ex) { if (LOG.isErrorEnabled()) { LOG.error("The front server is down.", ex); } } catch (Exception ex) { if (LOG.isErrorEnabled()) { LOG.error("Error when exporting content : ", ex); } } finally { if (session != null) session.logout(); } } }
14,157
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ImportContentsJob.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/scheduler/impl/ImportContentsJob.java
package org.exoplatform.services.wcm.extensions.scheduler.impl; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; import org.exoplatform.commons.utils.MimeTypeResolver; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.ecm.publication.PublicationPlugin; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring.AuthoringPublicationConstant; import org.exoplatform.services.wcm.publication.PublicationDefaultStates; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; /** * Created by The eXo Platform MEA Author : haikel.thamri@exoplatform.com */ public class ImportContentsJob implements Job { private static final Log LOG = ExoLogger.getLogger(ImportContentsJob.class.getName()); private static final String MIX_TARGET_PATH = "mix:targetPath"; private static final String MIX_TARGET_WORKSPACE = "mix:targetWorkspace"; private static final String JCR_File_SEPARATOR = "/"; public void execute(JobExecutionContext context) throws JobExecutionException { Session session = null; try { if (LOG.isInfoEnabled()) { LOG.info("Start Execute ImportXMLJob"); } JobDataMap jdatamap = context.getJobDetail().getJobDataMap(); String stagingStorage = jdatamap.getString("stagingStorage"); String temporaryStorge = jdatamap.getString("temporaryStorge"); if (LOG.isDebugEnabled()) { LOG.debug("Init parameters first time :"); } SessionProvider sessionProvider = SessionProvider.createSystemProvider(); String containerName = WCMCoreUtils.getContainerNameFromJobContext(context); RepositoryService repositoryService_ = WCMCoreUtils.getService(RepositoryService.class, containerName); ManageableRepository manageableRepository = repositoryService_.getCurrentRepository(); PublicationService publicationService = WCMCoreUtils.getService(PublicationService.class, containerName); PublicationPlugin publicationPlugin = publicationService.getPublicationPlugins() .get(AuthoringPublicationConstant.LIFECYCLE_NAME); XMLInputFactory factory = XMLInputFactory.newInstance(); File stagingFolder = new File(stagingStorage); File tempfolder = new File(temporaryStorge); File[] files = null; File xmlFile = null; XMLStreamReader reader = null; InputStream xmlInputStream = null; int eventType; List<LinkObject> listLink = new ArrayList<LinkObject>(); LinkObject linkObj = new LinkObject(); boolean hasNewContent = false; if (stagingFolder.exists()) { files = stagingFolder.listFiles(); if (files != null) { hasNewContent = true; for (int i = 0; i < files.length; i++) { xmlFile = files[i]; if (xmlFile.isFile()) { MimeTypeResolver resolver = new MimeTypeResolver(); String fileName = xmlFile.getName(); String hashCode = fileName.split("-")[0]; String mimeType = resolver.getMimeType(xmlFile.getName()); if ("text/xml".equals(mimeType)) { xmlInputStream = new FileInputStream(xmlFile); reader = factory.createXMLStreamReader(xmlInputStream); while (reader.hasNext()) { eventType = reader.next(); if (eventType == XMLEvent.START_ELEMENT && "data".equals(reader.getLocalName())) { String data = reader.getElementText(); if (!tempfolder.exists()) tempfolder.mkdirs(); long time = System.currentTimeMillis(); File file = new File(temporaryStorge + File.separator + "-" + hashCode + "-" + time + ".xml.tmp"); InputStream inputStream = new ByteArrayInputStream(data.getBytes()); OutputStream out = new FileOutputStream(file); byte[] buf = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); } try { if (eventType == XMLEvent.START_ELEMENT && "published-content".equals(reader.getLocalName())) { linkObj.setSourcePath(reader.getAttributeValue(0)); // --Attribute // number // 0 = // targetPath } if (eventType == XMLEvent.START_ELEMENT && "type".equals(reader.getLocalName())) { linkObj.setLinkType(reader.getElementText()); } if (eventType == XMLEvent.START_ELEMENT && "title".equals(reader.getLocalName())) { linkObj.setLinkTitle(reader.getElementText()); } if (eventType == XMLEvent.START_ELEMENT && "targetPath".equals(reader.getLocalName())) { linkObj.setLinkTargetPath(reader.getElementText()); listLink.add(linkObj); } if (eventType == XMLEvent.START_ELEMENT && "unpublished-content".equals(reader.getLocalName())) { String contentTargetPath = reader.getAttributeValue(0); String[] strContentPath = contentTargetPath.split(":"); StringBuffer sbContPath = new StringBuffer(); boolean flag = true; for (int index = 2; index < strContentPath.length; index++) { if (flag) { sbContPath.append(strContentPath[index]); flag = false; } else { sbContPath.append(":").append(strContentPath[index]); } } sessionProvider = SessionProvider.createSystemProvider(); manageableRepository = repositoryService_.getCurrentRepository(); String workspace = strContentPath[1]; session = sessionProvider.getSession(workspace, manageableRepository); String contentPath = sbContPath.toString(); if (session.itemExists(contentPath)) { Node currentContent = (Node) session.getItem(contentPath); HashMap<String, String> variables = new HashMap<String, String>(); variables.put("nodePath", contentTargetPath); variables.put("workspaceName", workspace); if (currentContent.hasProperty(AuthoringPublicationConstant.PUBLICATION_LIFECYCLE_NAME) && AuthoringPublicationConstant.LIFECYCLE_NAME.equals( currentContent.getProperty( AuthoringPublicationConstant.PUBLICATION_LIFECYCLE_NAME).getString()) && PublicationDefaultStates.PUBLISHED.equals( currentContent.getProperty(AuthoringPublicationConstant.CURRENT_STATE).getString())) { publicationPlugin.changeState(currentContent, PublicationDefaultStates.UNPUBLISHED, variables); if (LOG.isInfoEnabled()) { LOG.info("Change the status of the node " + currentContent.getPath() + " from " + PublicationDefaultStates.PUBLISHED + " to " + PublicationDefaultStates.UNPUBLISHED); } } } else { if (LOG.isWarnEnabled()) { LOG.warn("The node " + contentPath + " does not exist"); } } } } catch (Exception ie) { if (LOG.isWarnEnabled()) { LOG.warn("Error in ImportContentsJob: " + ie.getMessage()); } } } reader.close(); xmlInputStream.close(); xmlFile.delete(); } } } } } files = tempfolder.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { xmlFile = files[i]; InputStream inputStream = new FileInputStream(xmlFile); reader = factory.createXMLStreamReader(inputStream); String workspace = null; String nodePath = new String(); while (reader.hasNext()) { eventType = reader.next(); if (eventType == XMLEvent.START_ELEMENT) { if (reader.getLocalName().equals("property")) { String value = reader.getAttributeValue(0); if (MIX_TARGET_PATH.equals(value)) { eventType = reader.next(); if (eventType == XMLEvent.START_ELEMENT) { reader.next(); nodePath = reader.getText(); } } else if (MIX_TARGET_WORKSPACE.equals(value)) { eventType = reader.next(); if (eventType == XMLEvent.START_ELEMENT) { reader.next(); workspace = reader.getText(); } } } } } reader.close(); inputStream.close(); session = sessionProvider.getSession(workspace, manageableRepository); if (session.itemExists(nodePath)) session.getItem(nodePath).remove(); session.save(); String path = nodePath.substring(0, nodePath.lastIndexOf(JCR_File_SEPARATOR)); if (!session.itemExists(path)) { String[] pathTab = path.split(JCR_File_SEPARATOR); Node node_ = session.getRootNode(); StringBuffer path_ = new StringBuffer(JCR_File_SEPARATOR); for (int j = 1; j < pathTab.length; j++) { path_ = path_.append(pathTab[j] + JCR_File_SEPARATOR); if (!session.itemExists(path_.toString())) { node_.addNode(pathTab[j], "nt:unstructured"); } node_ = (Node) session.getItem(path_.toString()); } } session.importXML(path, new FileInputStream(xmlFile), 0); session.save(); xmlFile.delete(); if (hasNewContent) { for (LinkObject obj : listLink) { String[] linkTarget = obj.getLinkTargetPath().split(":"); StringBuffer itemPath = new StringBuffer(); boolean flag = true; for (int index = 2; index < linkTarget.length; index++) { if (flag) { itemPath.append(linkTarget[index]); flag = false; } else { itemPath.append(":"); itemPath.append(linkTarget[index]); } } String[] linkSource = obj.getSourcePath().split(":"); session = sessionProvider.getSession(linkTarget[1], manageableRepository); Node parentNode = (Node) session.getItem(itemPath.toString()); StringBuffer sourcePath = new StringBuffer(); boolean flagSource = true; for (int index = 2; index < linkSource.length; index++) { if (flagSource) { sourcePath.append(linkSource[index]); flagSource = false; } else { sourcePath.append(":"); sourcePath.append(linkSource[index]); } } if (parentNode.hasNode(obj.getLinkTitle())) { Node existedNode = (Node) session.getItem(itemPath + "/" + obj.getLinkTitle()); existedNode.remove(); } session = sessionProvider.getSession(linkSource[1], manageableRepository); Node targetNode = (Node) session.getItem(sourcePath.toString()); LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class, containerName); linkManager.createLink(parentNode, obj.getLinkType(), targetNode, obj.getLinkTitle()); } } } } if (LOG.isInfoEnabled()) { LOG.info("End Execute ImportXMLJob"); } } catch (RepositoryException ex) { if (LOG.isDebugEnabled()) { LOG.debug("Repository 'repository ' not found."); } } catch (Exception ex) { if (LOG.isErrorEnabled()) { LOG.error("Error when importing Contents : " + ex.getMessage(), ex); } } finally { if (session != null) session.logout(); } } private class LinkObject { private String linkType; private String linkTitle; private String linkTargetPath; private String sourcePath; public String getLinkType() { return linkType; } public void setLinkType(String linkType) { this.linkType = linkType; } public String getLinkTitle() { return linkTitle; } public void setLinkTitle(String linkTitle) { this.linkTitle = linkTitle; } public String getLinkTargetPath() { return linkTargetPath; } public void setLinkTargetPath(String linkTargetPath) { this.linkTargetPath = linkTargetPath; } public String getSourcePath() { return sourcePath; } public void setSourcePath(String sourcePath) { this.sourcePath = sourcePath; } } }
15,372
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
package-info.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/package-info.java
/** * Provides the Publication Manager to handle all actions related to lifecycle and publication on content. */ package org.exoplatform.services.wcm.extensions.publication;
175
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
WCMPublicationServiceImpl.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/WCMPublicationServiceImpl.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.services.wcm.extensions.publication; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.TreeSet; import javax.jcr.Node; import javax.jcr.lock.Lock; import org.apache.commons.lang3.StringUtils; import org.exoplatform.container.xml.InitParams; import org.exoplatform.ecm.utils.lock.LockUtil; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.ecm.publication.PublicationPlugin; import org.exoplatform.services.ecm.publication.PublicationService; 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.IdentityRegistry; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.extensions.publication.context.impl.ContextConfig.Context; import org.exoplatform.services.wcm.extensions.publication.impl.PublicationManagerImpl; import org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring.AuthoringPublicationConstant; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.Lifecycle; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.State; import org.exoplatform.services.wcm.extensions.utils.ContextComparator; import org.exoplatform.services.wcm.publication.WebpagePublicationPlugin; import org.exoplatform.services.wcm.utils.WCMCoreUtils; public class WCMPublicationServiceImpl extends org.exoplatform.services.wcm.publication.WCMPublicationServiceImpl { private static final Log LOG = ExoLogger.getLogger(WCMPublicationServiceImpl.class.getName()); private String publicationLocation = "collaboration:/"; private String[] notAllowChildNodeEnrollInPubliction = new String[] { NodetypeConstant.EXO_WEBCONTENT }; /** * Instantiates a new WCM publication service. This service delegate to * PublicationService to manage the publication */ public WCMPublicationServiceImpl(InitParams initParams) { super(); this.publicationService = WCMCoreUtils.getService(PublicationService.class); if(initParams.getValueParam("publicationLocation") != null) { publicationLocation = initParams.getValueParam("publicationLocation").getValue(); } if(initParams.getValueParam("notAllowChildNodeEnrollInPubliction") != null) { if(initParams.getValueParam("notAllowChildNodeEnrollInPubliction").getValue().indexOf(";") > -1) { notAllowChildNodeEnrollInPubliction = initParams.getValueParam("notAllowChildNodeEnrollInPubliction").getValue().split(";"); } } } /** * This default implementation uses "States and versions based publication" as * a default lifecycle for all sites and "Simple Publishing" for the root * user. */ public void enrollNodeInLifecycle(Node node, String siteName, String remoteUser) { try { if (LOG.isInfoEnabled()) LOG.info(node.getPath() + "::" + siteName + "::"+remoteUser); PublicationManagerImpl publicationManagerImpl = WCMCoreUtils.getService(PublicationManagerImpl.class); ContextComparator comparator = new ContextComparator(); TreeSet<Context> treeSetContext = new TreeSet<Context>(comparator); treeSetContext.addAll(publicationManagerImpl.getContexts()); for (Context context : treeSetContext) { boolean pathVerified = true; boolean nodetypeVerified = true; boolean siteVerified = true; boolean membershipVerified = true; String path = context.getPath(); String nodetype = context.getNodetype(); String site = context.getSite(); List<String> memberships = new ArrayList<String>(); if (context.getMembership() != null) { memberships.add(context.getMembership()); } if (context.getMemberships() != null) { memberships.addAll(context.getMemberships()); } if (path != null) { String workspace = node.getSession().getWorkspace().getName(); ManageableRepository manaRepository = (ManageableRepository) node.getSession() .getRepository(); String repository = manaRepository.getConfiguration().getName(); String[] pathTab = path.split(":"); pathVerified = node.getPath().contains(pathTab[2]) && (repository.equals(pathTab[0])) && (workspace.equals(pathTab[1])); } if (nodetype != null) nodetypeVerified = nodetype.equals(node.getPrimaryNodeType().getName()); if (site != null) siteVerified = site.equals(siteName); if (memberships.size() > 0) { for (String membership : memberships) { String[] membershipTab = membership.split(":"); IdentityRegistry identityRegistry = WCMCoreUtils.getService(IdentityRegistry.class); Identity identity = identityRegistry.getIdentity(remoteUser); membershipVerified = identity.isMemberOf(membershipTab[1], membershipTab[0]); if (membershipVerified) break; } } if (pathVerified && nodetypeVerified && siteVerified && membershipVerified) { Lifecycle lifecycle = publicationManagerImpl.getLifecycle(context.getLifecycle()); String lifecycleName = this.getWebpagePublicationPlugins() .get(lifecycle.getPublicationPlugin()) .getLifecycleName(); if (node.canAddMixin("publication:authoring")) { node.addMixin("publication:authoring"); node.setProperty("publication:lastUser", remoteUser); node.setProperty("publication:lifecycle", lifecycle.getName()); } enrollNodeInLifecycle(node, lifecycleName); setInitialState(node, lifecycle, remoteUser); break; } } } catch (Exception ex) { if (LOG.isErrorEnabled()) { LOG.error("Couldn't complete the enrollement : ", ex); } } } /** * Automatically move to initial state if 'automatic' * * @param node * @param lifecycle * @throws Exception */ private void setInitialState(Node node, Lifecycle lifecycle, String remoteUser) throws Exception { List<State> states = lifecycle.getStates(); if (states == null || states.size() <= 0) { if (LOG.isWarnEnabled()) { LOG.warn("could not find an initial state in lifecycle " + lifecycle.getName()); } } else { String initialState = states.get(0).getState(); PublicationPlugin publicationPlugin = publicationService.getPublicationPlugins() .get(AuthoringPublicationConstant.LIFECYCLE_NAME); HashMap<String, String> context = new HashMap<String, String>(); NodeLocation currentRevisionLocation = NodeLocation.getNodeLocationByNode(node); Node currentRevision = getCurrentRevision(currentRevisionLocation); if (currentRevision != null) { context.put(AuthoringPublicationConstant.CURRENT_REVISION_NAME, currentRevision.getName()); } try { if (node.isLocked()) { Lock lock = node.getLock(); String owner = lock.getLockOwner(); if (LOG.isInfoEnabled()) LOG.info("node is locked by owner, unlocking it for enrollement"); if (node.holdsLock() && remoteUser.equals(owner)) { String lockToken = LockUtil.getLockToken(node); if (lockToken != null) { node.getSession().addLockToken(lockToken); } node.unlock(); node.removeMixin(Utils.MIX_LOCKABLE); // remove lock from Cache LockUtil.removeLock(node); } } context.put(AuthoringPublicationConstant.IS_INITIAL_PHASE, "true"); node.setProperty("publication:lastUser", remoteUser); publicationPlugin.changeState(node, initialState, context); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error setting staged state : ", e); } } } } public Node getCurrentRevision(NodeLocation currentRevisionLocation) { return NodeLocation.getNodeByLocation(currentRevisionLocation); } /** * This default implementation checks if the state is valid then delegates the * update to the node WebpagePublicationPlugin. */ public void updateLifecyleOnChangeContent(Node node, String siteName, String remoteUser, String newState) throws Exception { if(!node.getPath().startsWith(publicationLocation.split(":")[1]) && !publicationService.isNodeEnrolledInLifecycle(node)) return; if(node.getPrimaryNodeType().getName().equals(NodetypeConstant.NT_FILE)) { for(String nodeType : notAllowChildNodeEnrollInPubliction) { if(!allowEnrollInPublication(node, nodeType)) return; } } if (!publicationService.isNodeEnrolledInLifecycle(node)) { enrollNodeInLifecycle(node, siteName, remoteUser); } String lifecycleName = publicationService.getNodeLifecycleName(node); WebpagePublicationPlugin publicationPlugin = this.getWebpagePublicationPlugins() .get(lifecycleName); publicationPlugin.updateLifecyleOnChangeContent(node, remoteUser, newState); listenerService.broadcast(UPDATE_EVENT, cmsService, node); } private boolean allowEnrollInPublication(Node node, String nodeType) throws Exception { String path = node.getPath(); Node parentNode = node.getParent(); while(!path.equals("/") && path.length() > 0) { parentNode = (Node)node.getSession().getItem(path); if(parentNode.isNodeType(nodeType)) return false; path = path.substring(0, path.lastIndexOf("/")); } return true; } }
11,271
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PublicationManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/PublicationManager.java
package org.exoplatform.services.wcm.extensions.publication; import java.util.List; import javax.jcr.Node; import org.exoplatform.container.component.ComponentPlugin; import org.exoplatform.services.wcm.extensions.publication.context.impl.ContextConfig.Context; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.Lifecycle; /** * Manages lifecycle and context of the publication. * * @LevelAPI Platform */ public interface PublicationManager { /** * Adds definitions of a lifecycle to the publication plugin. * * @param plugin The component plugin that defines the lifecycle. */ public void addLifecycle(ComponentPlugin plugin); /** * Removes definitions of a lifecycle from the publication plugin. * * @param plugin The component plugin that defines the lifecycle. */ public void removeLifecycle(ComponentPlugin plugin); /** * Adds definitions of a context to the publication plugin. * * @param plugin The component plugin that defines the context. */ public void addContext(ComponentPlugin plugin); /** * Removes definitions of a context from the publication plugin. * * @param plugin The component plugin that defines the context. */ public void removeContext(ComponentPlugin plugin); /** * Gets all lifecycles. * * @return The list of lifecycles. */ public List<Lifecycle> getLifecycles(); /** * Gets all contexts. * * @return The list of contexts. */ public List<Context> getContexts(); /** * Gets a context by a given name. * * @param name Name of the context. * @return The context. */ public Context getContext(String name); /** * Gets a lifecycle by a given name. * * @return The lifecycle. */ public Lifecycle getLifecycle(String name); /** * Gets all lifecycles of a user by a specified state. * * @param remoteUser The given user. * @param state The specified state by which all lifecycles are got. * @return The list of lifecycles. */ public List<Lifecycle> getLifecyclesFromUser(String remoteUser, String state); /** * Gets all content nodes. * * @param fromstate The current state of the content. * @param tostate The state by which lifecycles are retrieved from a user. * @param date Any given date. * The publication dates of returned content nodes are smaller than this given date. * @param user The last user who changes the state. * @param lang Language of the content nodes. * @param workspace The workspace where content nodes are got. * @return The list of content nodes. * @throws Exception */ public List<Node> getContents(String fromstate, String tostate, String date, String user, String lang, String workspace) throws Exception; }
2,943
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
StatesLifecyclePlugin.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/lifecycle/StatesLifecyclePlugin.java
package org.exoplatform.services.wcm.extensions.publication.lifecycle; import org.exoplatform.container.component.BaseComponentPlugin; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ObjectParameter; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig; /** * Created by The eXo Platform MEA Author : * haikel.thamri@exoplatform.com */ public class StatesLifecyclePlugin extends BaseComponentPlugin { private LifecyclesConfig lifecyclesConfig; public StatesLifecyclePlugin(InitParams params) { ObjectParameter param = params.getObjectParam("lifecycles"); if (param != null) { lifecyclesConfig = (LifecyclesConfig) param.getObject(); } } public LifecyclesConfig getLifecyclesConfig() { return lifecyclesConfig; } public void setLifecyclesConfig(LifecyclesConfig lifecyclesConfig) { this.lifecyclesConfig = lifecyclesConfig; } }
984
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
AuthoringPublicationPlugin.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/lifecycle/authoring/AuthoringPublicationPlugin.java
package org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.jcr.Node; import javax.jcr.Value; import javax.jcr.ValueFactory; import javax.jcr.version.Version; import javax.portlet.PortletMode; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.utils.PageList; import org.exoplatform.container.PortalContainer; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.config.DataStorage; import org.exoplatform.portal.config.Query; import org.exoplatform.portal.config.UserACL; import org.exoplatform.portal.config.UserPortalConfig; import org.exoplatform.portal.config.UserPortalConfigService; import org.exoplatform.portal.config.model.Page; import org.exoplatform.portal.config.model.PortalConfig; import org.exoplatform.portal.mop.navigation.Scope; import org.exoplatform.portal.mop.user.UserNavigation; import org.exoplatform.portal.mop.user.UserNode; import org.exoplatform.portal.mop.user.UserPortal; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.cms.CmsService; import org.exoplatform.services.cms.jcrext.activity.ActivityCommonService; import org.exoplatform.services.ecm.publication.IncorrectStateUpdateLifecycleException; import org.exoplatform.services.listener.ListenerService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.resources.ResourceBundleService; import org.exoplatform.services.security.IdentityConstants; import org.exoplatform.services.wcm.extensions.publication.impl.PublicationManagerImpl; import org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring.ui.UIPublicationContainer; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.Lifecycle; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.State; import org.exoplatform.services.wcm.publication.PublicationDefaultStates; import org.exoplatform.services.wcm.publication.PublicationUtil; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.services.wcm.publication.WCMPublicationService; import org.exoplatform.services.wcm.publication.WebpagePublicationPlugin; import org.exoplatform.services.wcm.publication.lifecycle.stageversion.config.VersionData; import org.exoplatform.services.wcm.publication.lifecycle.stageversion.config.VersionLog; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.form.UIForm; /** * Created by The eXo Platform MEA Author : haikel.thamri@exoplatform.com */ public class AuthoringPublicationPlugin extends WebpagePublicationPlugin { /** The log. */ private static final Log LOG = ExoLogger.getLogger(AuthoringPublicationPlugin.class.getName()); private ListenerService listenerService; private ActivityCommonService activityService; /** * Instantiates a new stage and version publication plugin. */ public AuthoringPublicationPlugin() { listenerService = WCMCoreUtils.getService(ListenerService.class); activityService = WCMCoreUtils.getService(ActivityCommonService.class); } /* * (non-Javadoc) * @see org.exoplatform.services.ecm.publication.PublicationPlugin#changeState * (javax.jcr.Node, java.lang.String, java.util.HashMap) */ public void changeState(Node node, String newState, HashMap<String, String> context) throws IncorrectStateUpdateLifecycleException, Exception { // Add mixin mix:versionable if (node.canAddMixin(Utils.MIX_VERSIONABLE)) { node.addMixin(Utils.MIX_VERSIONABLE); node.save(); } if (node.hasProperty(AuthoringPublicationConstant.CURRENT_STATE) && node.getProperty(AuthoringPublicationConstant.CURRENT_STATE) .getString().equals(PublicationDefaultStates.UNPUBLISHED) && node.hasProperty("exo:titlePublished")) { node.setProperty("exo:titlePublished",(Value)null); } String versionName = context.get(AuthoringPublicationConstant.CURRENT_REVISION_NAME); String logItemName = versionName; String userId = ""; try { userId = Util.getPortalRequestContext().getRemoteUser(); } catch (Exception e) { userId = node.getSession().getUserID(); } Node selectedRevision = null; if (node.getName().equals(versionName) || versionName == null) { selectedRevision = node; logItemName = node.getName(); } else { selectedRevision = node.getVersionHistory().getVersion(versionName); } Map<String, VersionData> revisionsMap = getRevisionData(node); VersionLog versionLog = null; ValueFactory valueFactory = node.getSession().getValueFactory(); String containerName = context.get("containerName"); if (containerName==null) containerName = PortalContainer.getCurrentPortalContainerName(); if (PublicationDefaultStates.PENDING.equals(newState)) { node.setProperty(AuthoringPublicationConstant.CURRENT_STATE, newState); versionLog = new VersionLog(logItemName, newState, userId, GregorianCalendar.getInstance(), AuthoringPublicationConstant.CHANGE_TO_PENDING); addLog(node, versionLog); VersionData versionData = revisionsMap.get(node.getUUID()); if (versionData != null) { versionData.setAuthor(userId); versionData.setState(newState); } else { versionData = new VersionData(node.getUUID(), newState, userId); } revisionsMap.put(node.getUUID(), versionData); addRevisionData(node, revisionsMap.values()); } else if (PublicationDefaultStates.APPROVED.equals(newState)) { node.setProperty(AuthoringPublicationConstant.CURRENT_STATE, newState); versionLog = new VersionLog(logItemName, newState, userId, GregorianCalendar.getInstance(), AuthoringPublicationConstant.CHANGE_TO_APPROVED); addLog(node, versionLog); VersionData versionData = revisionsMap.get(node.getUUID()); if (versionData != null) { versionData.setAuthor(userId); versionData.setState(newState); } else { versionData = new VersionData(node.getUUID(), newState, userId); } revisionsMap.put(node.getUUID(), versionData); addRevisionData(node, revisionsMap.values()); } else if (PublicationDefaultStates.STAGED.equals(newState)) { node.setProperty(AuthoringPublicationConstant.CURRENT_STATE, newState); versionLog = new VersionLog(logItemName, newState, userId, GregorianCalendar.getInstance(), AuthoringPublicationConstant.CHANGE_TO_STAGED); addLog(node, versionLog); VersionData versionData = revisionsMap.get(node.getUUID()); if (versionData != null) { versionData.setAuthor(userId); versionData.setState(newState); } else { versionData = new VersionData(node.getUUID(), newState, userId); } revisionsMap.put(node.getUUID(), versionData); addRevisionData(node, revisionsMap.values()); } else if (PublicationDefaultStates.ENROLLED.equalsIgnoreCase(newState)) { versionLog = new VersionLog(logItemName, newState, userId, GregorianCalendar.getInstance(), AuthoringPublicationConstant.ENROLLED_TO_LIFECYCLE); node.setProperty(AuthoringPublicationConstant.CURRENT_STATE, newState); VersionData revisionData = new VersionData(node.getUUID(), newState, userId); revisionsMap.put(node.getUUID(), revisionData); addRevisionData(node, revisionsMap.values()); addLog(node, versionLog); } else if (PublicationDefaultStates.UNPUBLISHED.equalsIgnoreCase(newState)) { versionLog = new VersionLog(selectedRevision.getName(), PublicationDefaultStates.UNPUBLISHED, userId, new GregorianCalendar(), AuthoringPublicationConstant.CHANGE_TO_UNPUBLISHED); VersionData selectedVersionData = revisionsMap.get(selectedRevision.getUUID()); if (selectedVersionData != null) { selectedVersionData.setAuthor(userId); selectedVersionData.setState(PublicationDefaultStates.UNPUBLISHED); } else { selectedVersionData = new VersionData(selectedRevision.getUUID(), PublicationDefaultStates.UNPUBLISHED, userId); } VersionData versionData = revisionsMap.get(node.getUUID()); if (versionData != null) { versionData.setAuthor(userId); versionData.setState(PublicationDefaultStates.UNPUBLISHED); } else { versionData = new VersionData(selectedRevision.getUUID(), PublicationDefaultStates.UNPUBLISHED, userId); } revisionsMap.put(node.getUUID(), versionData); revisionsMap.put(selectedRevision.getUUID(), selectedVersionData); addLog(node, versionLog); // change base version to unpublished state if (node.hasProperty("exo:titlePublished")) { node.setProperty("exo:titlePublished",(Value)null); } node.setProperty(AuthoringPublicationConstant.CURRENT_STATE, PublicationDefaultStates.UNPUBLISHED); Value value = valueFactory.createValue(selectedRevision); Value liveRevision = null; if (node.hasProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP)) { liveRevision = node.getProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP) .getValue(); } if (liveRevision != null && value.getString().equals(liveRevision.getString())) { node.setProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP, (javax.jcr.Value) null); } addRevisionData(node, revisionsMap.values()); } else if (PublicationDefaultStates.OBSOLETE.equals(newState)) { node.setProperty(AuthoringPublicationConstant.CURRENT_STATE, newState); versionLog = new VersionLog(selectedRevision.getName(), newState, userId, GregorianCalendar.getInstance(), AuthoringPublicationConstant.CHANGE_TO_OBSOLETED); addLog(node, versionLog); VersionData versionData = revisionsMap.get(selectedRevision.getUUID()); if (versionData != null) { versionData.setAuthor(userId); versionData.setState(newState); } else { versionData = new VersionData(selectedRevision.getUUID(), newState, userId); } revisionsMap.put(selectedRevision.getUUID(), versionData); addRevisionData(node, revisionsMap.values()); } else if (PublicationDefaultStates.ARCHIVED.equalsIgnoreCase(newState)) { Value value = valueFactory.createValue(selectedRevision); Value liveRevision = null; if (node.hasProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP)) { liveRevision = node.getProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP).getValue(); } if (liveRevision != null && value.getString().equals(liveRevision.getString())) { node.setProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP, (javax.jcr.Value) null); } versionLog = new VersionLog(selectedRevision.getName(), PublicationDefaultStates.ARCHIVED, userId, new GregorianCalendar(), AuthoringPublicationConstant.CHANGE_TO_ARCHIVED); VersionData versionData = revisionsMap.get(selectedRevision.getUUID()); if (versionData != null) { versionData.setAuthor(userId); versionData.setState(PublicationDefaultStates.ARCHIVED); } else { versionData = new VersionData(selectedRevision.getUUID(), PublicationDefaultStates.ARCHIVED, userId); } revisionsMap.put(selectedRevision.getUUID(), versionData); addLog(node, versionLog); // change base version to archived state node.setProperty(AuthoringPublicationConstant.CURRENT_STATE, PublicationDefaultStates.ARCHIVED); addRevisionData(node, revisionsMap.values()); } else if (PublicationDefaultStates.DRAFT.equalsIgnoreCase(newState)) { node.setProperty(AuthoringPublicationConstant.CURRENT_STATE, newState); versionLog = new VersionLog(logItemName, newState, userId, GregorianCalendar.getInstance(), AuthoringPublicationConstant.CHANGE_TO_DRAFT); addLog(node, versionLog); VersionData versionData = revisionsMap.get(node.getUUID()); if (versionData != null) { versionData.setAuthor(userId); versionData.setState(newState); } else { versionData = new VersionData(node.getUUID(), newState, userId); } revisionsMap.put(node.getUUID(), versionData); addRevisionData(node, revisionsMap.values()); } else if (PublicationDefaultStates.PUBLISHED.equals(newState)) { if (!node.isCheckedOut()) { node.checkout(); } if (context == null || !context.containsKey("context.action") || !context.get("context.action").equals("delete")) { node.setProperty(AuthoringPublicationConstant.LIVE_DATE_PROP, new GregorianCalendar()); node.save(); } Version liveVersion = node.checkin(); node.checkout(); // Change current live revision to unpublished Node oldLiveRevision = getLiveRevision(node); if (oldLiveRevision != null) { VersionData versionData = revisionsMap.get(oldLiveRevision.getUUID()); if (versionData != null) { versionData.setAuthor(userId); versionData.setState(PublicationDefaultStates.UNPUBLISHED); } else { versionData = new VersionData(oldLiveRevision.getUUID(), PublicationDefaultStates.UNPUBLISHED, userId); } revisionsMap.put(oldLiveRevision.getUUID(), versionData); versionLog = new VersionLog(oldLiveRevision.getName(), PublicationDefaultStates.UNPUBLISHED, userId, new GregorianCalendar(), AuthoringPublicationConstant.CHANGE_TO_UNPUBLISHED); addLog(node, versionLog); } versionLog = new VersionLog(liveVersion.getName(), newState, userId, new GregorianCalendar(), AuthoringPublicationConstant.CHANGE_TO_LIVE); addLog(node, versionLog); // change base version to published state node.setProperty(AuthoringPublicationConstant.CURRENT_STATE, PublicationDefaultStates.PUBLISHED); VersionData editableRevision = revisionsMap.get(node.getUUID()); if (editableRevision != null) { PublicationManagerImpl publicationManagerImpl = WCMCoreUtils.getService(PublicationManagerImpl.class, containerName); String lifecycleName = node.getProperty("publication:lifecycle").getString(); Lifecycle lifecycle = publicationManagerImpl.getLifecycle(lifecycleName); List<State> states = lifecycle.getStates(); if (states == null || states.size() <= 0) { editableRevision.setState(PublicationDefaultStates.ENROLLED); } else { editableRevision.setState(states.get(0).getState()); } editableRevision.setAuthor(userId); } else { editableRevision = new VersionData(node.getUUID(), PublicationDefaultStates.ENROLLED, userId); } revisionsMap.put(node.getUUID(), editableRevision); versionLog = new VersionLog(node.getBaseVersion().getName(), PublicationDefaultStates.DRAFT, userId, new GregorianCalendar(), AuthoringPublicationConstant.ENROLLED_TO_LIFECYCLE); Value liveVersionValue = valueFactory.createValue(liveVersion); node.setProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP, liveVersionValue); VersionData liveRevisionData = new VersionData(liveVersion.getUUID(), PublicationDefaultStates.PUBLISHED, userId); revisionsMap.put(liveVersion.getUUID(), liveRevisionData); addRevisionData(node, revisionsMap.values()); } if (!IdentityConstants.SYSTEM.equals(userId)) { node.setProperty("publication:lastUser", userId); } if (!node.isNew()) node.save(); //raise event to notify that state is changed if (!PublicationDefaultStates.ENROLLED.equalsIgnoreCase(newState)) { CmsService cmsService = WCMCoreUtils.getService(CmsService.class); if ("true".equalsIgnoreCase(context.get(AuthoringPublicationConstant.IS_INITIAL_PHASE))) { listenerService.broadcast(AuthoringPublicationConstant.POST_INIT_STATE_EVENT, cmsService, node); } else { listenerService.broadcast(AuthoringPublicationConstant.POST_CHANGE_STATE_EVENT, cmsService, node); if (activityService.isAcceptedNode(node)) { listenerService.broadcast(ActivityCommonService.STATE_CHANGED_ACTIVITY, node, newState); } } } listenerService.broadcast(AuthoringPublicationConstant.POST_UPDATE_STATE_EVENT, null, node); } /* * (non-Javadoc) * @see * org.exoplatform.services.ecm.publication.PublicationPlugin#getPossibleStates * () */ public String[] getPossibleStates() { return new String[] { PublicationDefaultStates.ENROLLED, PublicationDefaultStates.DRAFT, PublicationDefaultStates.PENDING, PublicationDefaultStates.PUBLISHED, PublicationDefaultStates.OBSOLETE }; } public String getLifecycleName() { return AuthoringPublicationConstant.LIFECYCLE_NAME; } public String getLifecycleType() { return AuthoringPublicationConstant.PUBLICATION_LIFECYCLE_TYPE; } /* * (non-Javadoc) * @see org.exoplatform.services.ecm.publication.PublicationPlugin#getStateUI * (javax.jcr.Node, org.exoplatform.webui.core.UIComponent) */ public UIForm getStateUI(Node node, UIComponent component) throws Exception { UIPublicationContainer publicationContainer = component.createUIComponent(UIPublicationContainer.class, null, null); publicationContainer.initContainer(node); return publicationContainer; } /* * (non-Javadoc) * @see * org.exoplatform.services.ecm.publication.PublicationPlugin#addMixin(javax * .jcr.Node) */ public void addMixin(Node node) throws Exception { node.addMixin(AuthoringPublicationConstant.PUBLICATION_LIFECYCLE_TYPE); String nodetypes = System.getProperty("wcm.nodetypes.ignoreversion"); if(nodetypes == null || nodetypes.length() == 0) nodetypes = "exo:webContent"; if(!Utils.NT_FILE.equals(node.getPrimaryNodeType().getName()) || Utils.isMakeVersionable(node, nodetypes.split(","))) { if (!node.isNodeType(AuthoringPublicationConstant.MIX_VERSIONABLE)) { node.addMixin(AuthoringPublicationConstant.MIX_VERSIONABLE); } } } /* * (non-Javadoc) * @see org.exoplatform.services.ecm.publication.PublicationPlugin#canAddMixin * (javax.jcr.Node) */ public boolean canAddMixin(Node node) throws Exception { return node.canAddMixin(AuthoringPublicationConstant.PUBLICATION_LIFECYCLE_TYPE); } /** * Adds the log. * * @param node the node * @param versionLog the version log * @throws Exception the exception */ private void addLog(Node node, VersionLog versionLog) throws Exception { Value[] values = node.getProperty(AuthoringPublicationConstant.HISTORY).getValues(); ValueFactory valueFactory = node.getSession().getValueFactory(); List<Value> list = new ArrayList<Value>(Arrays.asList(values)); list.add(valueFactory.createValue(versionLog.toString())); node.setProperty(AuthoringPublicationConstant.HISTORY, list.toArray(new Value[] {})); } /** * Adds the revision data. * * @param node the node * @param list the list * @throws Exception the exception */ private void addRevisionData(Node node, Collection<VersionData> list) throws Exception { List<Value> valueList = new ArrayList<Value>(); ValueFactory factory = node.getSession().getValueFactory(); for (VersionData versionData : list) { valueList.add(factory.createValue(versionData.toStringValue())); } node.setProperty(AuthoringPublicationConstant.REVISION_DATA_PROP, valueList.toArray(new Value[] {})); } /** * Gets the revision data. * * @param node the node * @return the revision data * @throws Exception the exception */ private Map<String, VersionData> getRevisionData(Node node) throws Exception { Map<String, VersionData> map = new HashMap<String, VersionData>(); try { for (Value v : node.getProperty(AuthoringPublicationConstant.REVISION_DATA_PROP).getValues()) { VersionData versionData = VersionData.toVersionData(v.getString()); map.put(versionData.getUUID(), versionData); } } catch (Exception e) { return map; } return map; } /** * In this publication process, we put the content in Draft state when editing * it. */ public void updateLifecyleOnChangeContent(Node node, String remoteUser, String newState) throws Exception { String state = node.getProperty(AuthoringPublicationConstant.CURRENT_STATE).getString(); if (newState == null) { PublicationManagerImpl publicationManagerImpl = WCMCoreUtils.getService(PublicationManagerImpl.class); Lifecycle lifecycle = publicationManagerImpl.getLifecycle(node.getProperty("publication:lifecycle") .getString()); List<State> states = lifecycle.getStates(); if (states != null && states.size() > 0) { newState = states.get(0).getState(); } } if (state.equals(newState)) return; HashMap<String, String> context = new HashMap<String, String>(); changeState(node, newState, context); } /** * Gets the live revision. * * @param node the node * @return the live revision */ private Node getLiveRevision(Node node) { try { String nodeVersionUUID = (node.hasProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP)) ? node.getProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP).getString() : null; if (StringUtils.isEmpty(nodeVersionUUID) && PublicationDefaultStates.PUBLISHED.equals(node.getProperty(AuthoringPublicationConstant.CURRENT_STATE) .getString())) return node; return node.getVersionHistory().getSession().getNodeByUUID(nodeVersionUUID); } catch (Exception e) { return null; } } /* * (non-Javadoc) * @see * org.exoplatform.services.ecm.publication.PublicationPlugin#getNodeView( * javax.jcr.Node, java.util.Map) */ public Node getNodeView(Node node, Map<String, Object> context) throws Exception { // don't display content if state is enrolled or obsolete WCMPublicationService wcmPublicationService = WCMCoreUtils.getService(WCMPublicationService.class); String currentState = wcmPublicationService.getContentState(node); if (PublicationDefaultStates.ENROLLED.equals(currentState) || PublicationDefaultStates.UNPUBLISHED.equals(currentState)) return null; // if current mode is edit mode if (context==null || WCMComposer.MODE_EDIT.equals(context.get(WCMComposer.FILTER_MODE)) || PortletMode.EDIT.toString().equals(context.get(WCMComposer.PORTLET_MODE))) return node; // if current mode is live mode Node liveNode = getLiveRevision(node); if (liveNode != null) { if (liveNode.hasNode("jcr:frozenNode")) { return liveNode.getNode("jcr:frozenNode"); } return liveNode; } return null; } @Override /** * In this publication process, we put the content in Draft state when editing it. */ public void updateLifecyleOnChangeContent(Node node, String remoteUser) throws Exception { updateLifecyleOnChangeContent(node, remoteUser, PublicationDefaultStates.DRAFT); } @Override public List<String> getListUserNavigationUri(Page page, String remoteUser) throws Exception { List<String> listPageNavigationUri = new ArrayList<String>(); for (String portalName : getRunningPortals(remoteUser)) { UserPortalConfigService userPortalConfigService = WCMCoreUtils.getService(UserPortalConfigService.class); UserPortalConfig userPortalCfg = userPortalConfigService.getUserPortalConfig(portalName, remoteUser, PortalRequestContext.USER_PORTAL_CONTEXT); UserPortal userPortal = userPortalCfg.getUserPortal(); // get nodes List<UserNavigation> navigationList = userPortal.getNavigations(); for (UserNavigation nav : navigationList) { UserNode root = userPortal.getNode(nav, Scope.ALL, null, null); List<UserNode> userNodeList = PublicationUtil.findUserNodeByPageId(root, page.getPageId()); for (UserNode node : userNodeList) { listPageNavigationUri.add(PublicationUtil.setMixedNavigationUri(portalName, node.getURI())); } } } return listPageNavigationUri; } @Override public byte[] getStateImage(Node node, Locale locale) throws IOException, FileNotFoundException, Exception { // TODO Auto-generated method stub return null; } @Override public String getUserInfo(Node node, Locale locale) throws Exception { // TODO Auto-generated method stub return null; } @Override public String getLocalizedAndSubstituteMessage(Locale locale, String key, String[] values) throws Exception { ClassLoader cl=this.getClass().getClassLoader(); ResourceBundleService bundleService = WCMCoreUtils.getService(ResourceBundleService.class); ResourceBundle resourceBundle= bundleService.getResourceBundle(AuthoringPublicationConstant.LOCALIZATION, locale, cl); String result = ""; try { result = resourceBundle.getString(key); } catch (MissingResourceException e) { result = key; } if(values != null) { return String.format(result, (Object[])values); } return result; } private List<String> getRunningPortals(String userId) throws Exception { List<String> listPortalName = new ArrayList<String>(); DataStorage service = WCMCoreUtils.getService(DataStorage.class); Query<PortalConfig> query = new Query<PortalConfig>(null, null, null, null, PortalConfig.class) ; PageList pageList = service.find(query, null) ; UserACL userACL = WCMCoreUtils.getService(UserACL.class); for(Object object:pageList.getAll()) { PortalConfig portalConfig = (PortalConfig)object; if(userACL.hasPermission(portalConfig)) { listPortalName.add(portalConfig.getName()); } } return listPortalName; } }
29,195
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
AuthoringPublicationConstant.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/lifecycle/authoring/AuthoringPublicationConstant.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.services.wcm.extensions.publication.lifecycle.authoring; /** * Created by The eXo Platform SAS Author : Hoa Pham hoa.phamvu@exoplatform.com * Mar 4, 2009 */ public interface AuthoringPublicationConstant { /** The Constant PUBLICATION_LIFECYCLE_TYPE. */ public static final String PUBLICATION_LIFECYCLE_TYPE = "publication:authoringPublication"; /** The Constant LIFECYCLE_NAME. */ public static final String LIFECYCLE_NAME = "Authoring publication"; /** The Constant LOCALIZATION. */ public static final String LOCALIZATION = "artifacts.lifecycle.stageversion.StageAndVersionPublication"; /** The Constant ENROLLED_TO_LIFECYCLE. */ public static final String ENROLLED_TO_LIFECYCLE = "Publication.log.description.enrolled"; /** The Constant CHANGE_TO_DRAFT. */ public static final String CHANGE_TO_DRAFT = "PublicationService.AuthoringPublicationPlugin.changeState.draft"; /** The Constant CHANGE_TO_LIVE. */ public static final String CHANGE_TO_LIVE = "PublicationService.AuthoringPublicationPlugin.changeState.published"; /** The Constant CHANGE_TO_PENDING. */ public static final String CHANGE_TO_PENDING = "PublicationService.AuthoringPublicationPlugin.changeState.pending"; /** The Constant CHANGE_TO_APPROVED. */ public static final String CHANGE_TO_APPROVED = "PublicationService.AuthoringPublicationPlugin.changeState.approved"; /** The Constant CHANGE_TO_OBSOLETE. */ public static final String CHANGE_TO_OBSOLETED = "PublicationService.AuthoringPublicationPlugin.changeState.obsoleted"; /** The Constant CHANGE_TO_STAGED. */ public static final String CHANGE_TO_STAGED = "PublicationService.AuthoringPublicationPlugin.changeState.staged"; /** The Constant CHANGE_TO_UNPUBLISHED. */ public static final String CHANGE_TO_UNPUBLISHED = "PublicationService.AuthoringPublicationPlugin.changeState.unpublished"; /** The Constant CHANGE_TO_ARCHIVED. */ public static final String CHANGE_TO_ARCHIVED = "PublicationService.AuthoringPublicationPlugin.changeState.archived"; /** The Constant PUBLICATION_LIFECYCLE_NAME. */ public static final String PUBLICATION_LIFECYCLE_NAME = "publication:lifecycleName"; /** The Constant CURRENT_STATE. */ public static final String CURRENT_STATE = "publication:currentState"; /** The Constant MIX_VERSIONABLE. */ public static final String MIX_VERSIONABLE = "mix:versionable"; /** The Constant HISTORY. */ public static final String HISTORY = "publication:history"; /** The Constant LIVE_REVISION_PROP. */ public static final String LIVE_REVISION_PROP = "publication:liveRevision"; /** The Constant LIVE_DATE_PROP. */ public static final String LIVE_DATE_PROP = "publication:liveDate"; /** The Constant REVISION_DATA_PROP. */ public static final String REVISION_DATA_PROP = "publication:revisionData"; /** The Constant RUNTIME_MODE. */ public static final String RUNTIME_MODE = "wcm.runtime.mode"; /** The Constant CURRENT_REVISION_NAME. */ public static final String CURRENT_REVISION_NAME = "Publication.context.currentVersion"; /** The Constant START_TIME_PROPERTY. */ public static final String START_TIME_PROPERTY = "publication:startPublishedDate"; /** The Constant START_TIME_PROPERTY. */ public static final String END_TIME_PROPERTY = "publication:endPublishedDate"; /** The Constant POST_UPDATE_STATE_EVENT. */ public static final String POST_UPDATE_STATE_EVENT = "PublicationService.event.postUpdateState"; public static final String IS_INITIAL_PHASE = "Publication.context.isInitialPhase"; public static final String DONT_BROADCAST_EVENT = "Publication.context.dontBroadcastEvent"; public static final String POST_INIT_STATE_EVENT = "PublicationService.event.postInitState"; public static final String POST_CHANGE_STATE_EVENT = "PublicationService.event.postChangeState"; /** * The Enum SITE_MODE. */ public static enum SITE_MODE { /** The LIVE. */ LIVE, /** The EDITING. */ EDITING }; }
4,900
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIPublicationAction.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/lifecycle/authoring/ui/UIPublicationAction.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.services.wcm.extensions.publication.lifecycle.authoring.ui; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.Value; import org.exoplatform.portal.config.UserPortalConfigService; import org.exoplatform.portal.mop.user.UserNavigation; import org.exoplatform.portal.mop.user.UserNode; import org.exoplatform.portal.mop.user.UserPortal; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.portal.webui.util.NavigationUtils; import org.exoplatform.services.wcm.publication.PublicationUtil; import org.exoplatform.services.wcm.publication.lifecycle.stageversion.ui.UIPortalNavigationExplorer; import org.exoplatform.services.wcm.publication.lifecycle.stageversion.ui.UIPublicationHistory; import org.exoplatform.services.wcm.publication.lifecycle.stageversion.ui.UIPublicationPages; import org.exoplatform.services.wcm.publication.lifecycle.stageversion.ui.UIPublicationPagesContainer; import org.exoplatform.services.wcm.publication.lifecycle.stageversion.ui.UIPublicationTree.TreeNode; import org.exoplatform.services.wcm.publication.lifecycle.stageversion.ui.UIPublishedPages; 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.lifecycle.UIFormLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; /** * Created by The eXo Platform SAS Author : Phan Le Thanh Chuong * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com Sep 25, 2008 */ @ComponentConfig(lifecycle = UIFormLifecycle.class, template = "classpath:groovy/wcm/webui/publication/lifecycle/stageversion/ui/UIPublicationAction.gtmpl", events = { @EventConfig(listeners = UIPublicationAction.AddActionListener.class), @EventConfig(listeners = UIPublicationAction.RemoveActionListener.class) }) public class UIPublicationAction extends UIForm { /** * Update ui. * * @throws Exception the exception */ public void updateUI() throws Exception { UIPublicationPages publicationPages = getAncestorOfType(UIPublicationPages.class); UIPublishedPages publishedPages = publicationPages.getChild(UIPublishedPages.class); Node node = publicationPages.getNode(); List<String> listPublishedPage = new ArrayList<String>(); if (node.hasProperty("publication:navigationNodeURIs")) { Value[] navigationNodeURIs = node.getProperty("publication:navigationNodeURIs").getValues(); for (Value navigationNodeURI : navigationNodeURIs) { if (PublicationUtil.isNodeContentPublishedToPageNode(node, navigationNodeURI.getString())) { listPublishedPage.add(navigationNodeURI.getString()); } } publishedPages.setListNavigationNodeURI(listPublishedPage); UIPublicationContainer publicationContainer = getAncestorOfType(UIPublicationContainer.class); UIPublicationHistory publicationHistory = publicationContainer.getChild(UIPublicationHistory.class); UIPublicationPanel publicationPanel = publicationContainer.getChild(UIPublicationPanel.class); publicationHistory.init(publicationPanel.getCurrentNode()); publicationHistory.updateGrid(); } } /** * The listener interface for receiving addAction events. The class that is * interested in processing a addAction event implements this interface, and * the object created with that class is registered with a component using * the component's <code>addAddActionListener</code> method. When * the addAction event occurs, that object's appropriate * method is invoked. */ public static class AddActionListener extends EventListener<UIPublicationAction> { /* * (non-Javadoc) * * @see * org.exoplatform.webui.event.EventListener#execute(org.exoplatform * .webui.event.Event) */ public void execute(Event<UIPublicationAction> event) throws Exception { UIPublicationAction publicationAction = event.getSource(); UIPublicationPages publicationPages = publicationAction.getAncestorOfType(UIPublicationPages.class); UIApplication application = publicationAction.getAncestorOfType(UIApplication.class); UIPortalNavigationExplorer portalNavigationExplorer = publicationPages.getChild(UIPortalNavigationExplorer.class); TreeNode selectedNode = portalNavigationExplorer.getSelectedNode(); if (selectedNode == null) { application.addMessage(new ApplicationMessage("UIPublicationAction.msg.none", null, ApplicationMessage.WARNING)); return; } String selectedNavigationNodeURI = selectedNode.getUri(); Node node = publicationPages.getNode(); if (node.hasProperty("publication:navigationNodeURIs") && PublicationUtil.isNodeContentPublishedToPageNode(node, selectedNavigationNodeURI)) { Value[] navigationNodeURIs = node.getProperty("publication:navigationNodeURIs").getValues(); for (Value navigationNodeURI : navigationNodeURIs) { if (navigationNodeURI.getString().equals(selectedNavigationNodeURI)) { application.addMessage(new ApplicationMessage("UIPublicationAction.msg.duplicate", null, ApplicationMessage.WARNING)); return; } } } UserNode userNode = selectedNode.getUserNode(); if (userNode == null) { application.addMessage(new ApplicationMessage("UIPublicationAction.msg.wrongNode", null, ApplicationMessage.WARNING)); return; } UIPublicationPagesContainer publicationPagesContainer = publicationPages. getAncestorOfType(UIPublicationPagesContainer.class); publicationAction.updateUI(); UIPublicationContainer publicationContainer = publicationAction.getAncestorOfType(UIPublicationContainer.class); publicationContainer.setActiveTab(publicationPagesContainer, event.getRequestContext()); } } /** * The listener interface for receiving removeAction events. The class that * is interested in processing a removeAction event implements this * interface, and the object created with that class is registered with a * component using the component's * <code>addRemoveActionListener</code> method. When * the removeAction event occurs, that object's appropriate * method is invoked. */ public static class RemoveActionListener extends EventListener<UIPublicationAction> { /* * (non-Javadoc) * * @see * org.exoplatform.webui.event.EventListener#execute(org.exoplatform * .webui.event.Event) */ public void execute(Event<UIPublicationAction> event) throws Exception { UIPublicationAction publicationAction = event.getSource(); UIPublicationPages publicationPages = publicationAction.getAncestorOfType(UIPublicationPages.class); UserPortalConfigService userPortalConfigService = publicationAction.getApplicationComponent(UserPortalConfigService.class); UIPublishedPages publishedPages = publicationPages.getChild(UIPublishedPages.class); String selectedNavigationNodeURI = publishedPages.getSelectedNavigationNodeURI(); if (selectedNavigationNodeURI == null) { UIApplication application = publicationAction.getAncestorOfType(UIApplication.class); application.addMessage(new ApplicationMessage("UIPublicationAction.msg.none", null, ApplicationMessage.WARNING)); return; } String portalName = selectedNavigationNodeURI.substring(1, selectedNavigationNodeURI.indexOf("/", 1)); String pageNodeUri = selectedNavigationNodeURI.replaceFirst("/\\w+/", ""); UserPortal userPortal = Util.getPortalRequestContext().getUserPortalConfig().getUserPortal(); UserNavigation navigation = NavigationUtils.getUserNavigationOfPortal(userPortal, portalName); Node contentNode = null; if (navigation != null) { contentNode = publicationPages.getNode(); if (contentNode.hasProperty("publication:applicationIDs")) { UserNode userNode = getUserNodeByUri(navigation, pageNodeUri); userPortalConfigService.getPage(userNode.getPageRef()); } } publicationAction.updateUI(); UIPublicationPagesContainer publicationPagesContainer = publicationPages. getAncestorOfType(UIPublicationPagesContainer.class); UIPublicationContainer publicationContainer = publicationAction.getAncestorOfType(UIPublicationContainer.class); publicationContainer.setActiveTab(publicationPagesContainer, event.getRequestContext()); } /** * Gets the user node by uri. * @param pageNav * @param uri * @return */ private UserNode getUserNodeByUri(UserNavigation pageNav, String uri) { if(pageNav == null || uri == null) return null; UserPortal userPortal = Util.getPortalRequestContext().getUserPortalConfig().getUserPortal(); return userPortal.resolvePath(pageNav, null, uri); } } }
10,734
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIPublicationContainer.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/lifecycle/authoring/ui/UIPublicationContainer.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring.ui; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Locale; import javax.jcr.Node; import org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring.AuthoringPublicationConstant; import org.exoplatform.services.wcm.publication.PublicationDefaultStates; import org.exoplatform.services.wcm.publication.lifecycle.stageversion.ui.UIPublicationHistory; 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.UIPopupContainer; import org.exoplatform.webui.core.lifecycle.Lifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS Author : eXoPlatform * chuong_phan@exoplatform.com Mar 4, 2009 */ @ComponentConfig(lifecycle = Lifecycle.class, template = "app:/groovy/webui/component/explorer/popup/action/UITabPane.gtmpl", events = { @EventConfig(listeners = UIPublicationContainer.CloseActionListener.class) }) public class UIPublicationContainer extends org.exoplatform.services.wcm.publication.lifecycle.stageversion.ui.UIPublicationContainer { /** * Instantiates a new uI publication container. */ public UIPublicationContainer() { } /** The date time formater. */ private DateFormat dateTimeFormater; /** * Inits the container. * * @param node the node * @throws Exception the exception */ public void initContainer(Node node) throws Exception { UIPublicationPanel publicationPanel = addChild(UIPublicationPanel.class, null, null); publicationPanel.init(node); this.checkToShowPublicationScheduleAndPublicationHistory(node); setSelectedTab(1); Locale locale = org.exoplatform.portal.webui.util.Util.getPortalRequestContext().getLocale(); dateTimeFormater = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM, SimpleDateFormat.MEDIUM, locale); } private void checkToShowPublicationScheduleAndPublicationHistory(Node node) throws Exception { String currentState = node.getProperty(AuthoringPublicationConstant.CURRENT_STATE).getString(); this.removeChild(UIPublicationSchedule.class); if (PublicationDefaultStates.STAGED.equals(currentState)) { UIPublicationSchedule publicationSchedule = addChild(UIPublicationSchedule.class, null, null); publicationSchedule.init(node); publicationSchedule.setRendered(false); } this.removeChild(UIPublicationHistory.class); UIPublicationHistory publicationHistory = addChild(UIPublicationHistory.class, null, null); publicationHistory.init(node); publicationHistory.updateGrid(); publicationHistory.setRendered(false); } /** * Gets the date time formater. * * @return the date time formater */ public DateFormat getDateTimeFormater() { return dateTimeFormater; } /* (non-Javadoc) * @see org.exoplatform.webui.form.UIForm#processRender(org.exoplatform.webui.application.WebuiRequestContext) */ @Override public void processRender(WebuiRequestContext context) throws Exception { Node currentNode = this.getChild(UIPublicationPanel.class).getCurrentNode(); this.checkToShowPublicationScheduleAndPublicationHistory(currentNode); super.processRender(context); } public static class CloseActionListener extends EventListener<UIPublicationContainer> { public void execute(Event<UIPublicationContainer> event) throws Exception { UIPublicationContainer publicationContainer = event.getSource(); UIPopupContainer uiPopupContainer = publicationContainer.getAncestorOfType(UIPopupContainer.class); uiPopupContainer.deActivate(); event.getRequestContext().addUIComponentToUpdateByAjax(uiPopupContainer); } } }
4,983
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIPublicationPanel.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/lifecycle/authoring/ui/UIPublicationPanel.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring.ui; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.exoplatform.ecm.utils.lock.LockUtil; import org.exoplatform.ecm.webui.utils.JCRExceptionManager; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.ecm.publication.PublicationPlugin; import org.exoplatform.services.ecm.publication.PublicationService; import org.exoplatform.services.jcr.access.AccessControlEntry; import org.exoplatform.services.jcr.access.AccessControlList; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.impl.core.NodeImpl; import org.exoplatform.services.security.Identity; import org.exoplatform.services.security.IdentityRegistry; import org.exoplatform.services.wcm.extensions.publication.PublicationManager; import org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring.AuthoringPublicationConstant; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.Lifecycle; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.State; import org.exoplatform.services.wcm.publication.PublicationDefaultStates; import org.exoplatform.services.wcm.publication.WCMPublicationService; import org.exoplatform.services.wcm.publication.lifecycle.stageversion.ui.UIPublicationContainer; 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.lifecycle.UIFormLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import javax.jcr.Node; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by The eXo Platform MEA Author : haikel.thamri@exoplatform.com */ @ComponentConfig(lifecycle = UIFormLifecycle.class, template = "app:/groovy/webui/component/explorer/popup/action/UIPublicationPanel.gtmpl", events = { @EventConfig(listeners = UIPublicationPanel.ChangeStateActionListener.class), @EventConfig(listeners = UIPublicationPanel.ChangeVersionActionListener.class), @EventConfig(listeners = UIPublicationPanel.PreviewVersionActionListener.class), @EventConfig(listeners = UIPublicationPanel.RestoreVersionActionListener.class), @EventConfig(listeners = UIPublicationPanel.SeeAllVersionActionListener.class)}) public class UIPublicationPanel extends org.exoplatform.services.wcm.publication.lifecycle.stageversion.ui.UIPublicationPanel { private static final Log LOG = LogFactory.getLog(UIPublicationPanel.class.getName()); /** * Instantiates a new uI publication panel. * * @throws Exception the exception */ public UIPublicationPanel() throws Exception { } public void init(Node node) throws Exception { String nodeVersionUUID = null; super.init(node); String currentState = node.getProperty(AuthoringPublicationConstant.CURRENT_STATE).getString(); if (PublicationDefaultStates.PUBLISHED.equals(currentState) || PublicationDefaultStates.UNPUBLISHED.equals(currentState) || PublicationDefaultStates.OBSOLETE.equals(currentState)) { if (node.hasProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP)) { nodeVersionUUID = node.getProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP).getString(); } if (StringUtils.isNotEmpty(nodeVersionUUID)) { Node revision = this.getRevisionByUUID(nodeVersionUUID); this.setCurrentRevision(revision); } } } /** * The listener interface for receiving draftAction events. The class that is * interested in processing a draftAction event implements this interface, and * the object created with that class is registered with a component using the * component's <code>addDraftActionListener</code> method. When * the draftAction event occurs, that object's appropriate * method is invoked. */ public static class ChangeStateActionListener extends EventListener<UIPublicationPanel> { /* * (non-Javadoc) * @see org.exoplatform.webui.event.EventListener#execute(org.exoplatform * .webui.event.Event) */ public void execute(Event<UIPublicationPanel> event) throws Exception { UIPublicationPanel publicationPanel = event.getSource(); String state = event.getRequestContext().getRequestParameter(OBJECTID) ; Node currentNode = publicationPanel.getCurrentNode(); PublicationService publicationService = publicationPanel.getApplicationComponent(PublicationService.class); WCMPublicationService wcmPublicationService = publicationPanel.getApplicationComponent(WCMPublicationService.class); PublicationPlugin publicationPlugin = publicationService.getPublicationPlugins() .get(AuthoringPublicationConstant.LIFECYCLE_NAME); HashMap<String, String> context = new HashMap<String, String>(); Node currentRevision = publicationPanel.getCurrentRevision(); if (currentRevision != null) { context.put(AuthoringPublicationConstant.CURRENT_REVISION_NAME, currentRevision.getName()); } try { if(currentNode.isLocked()) { currentNode.getSession().addLockToken(LockUtil.getLockToken(currentNode)); } publicationPlugin.changeState(currentNode, state, context); currentNode.setProperty("publication:lastUser", event.getRequestContext().getRemoteUser()); String nodeVersionUUID = null; String currentState = currentNode.getProperty(AuthoringPublicationConstant.CURRENT_STATE).getString(); if (PublicationDefaultStates.PUBLISHED.equals(currentState) || PublicationDefaultStates.UNPUBLISHED.equals(currentState) || PublicationDefaultStates.OBSOLETE.equals(currentState)) { if(currentNode.hasProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP)){ nodeVersionUUID = currentNode.getProperty(AuthoringPublicationConstant.LIVE_REVISION_PROP).getString(); } if (nodeVersionUUID != null && !nodeVersionUUID.isEmpty()) { publicationPanel.setCurrentRevision(publicationPanel.getRevisionByUUID(nodeVersionUUID)); } } String siteName = Util.getPortalRequestContext().getPortalOwner(); String remoteUser = Util.getPortalRequestContext().getRemoteUser(); wcmPublicationService.updateLifecyleOnChangeContent(currentNode, siteName, remoteUser, state); publicationPanel.updatePanel(); } catch (Exception e) { UIApplication uiApp = publicationPanel.getAncestorOfType(UIApplication.class); JCRExceptionManager.process(uiApp, e); } UIPublicationContainer publicationContainer = publicationPanel.getAncestorOfType(UIPublicationContainer.class); publicationContainer.setActiveTab(publicationPanel, event.getRequestContext()); } } public List<State> getStates(Node cNode) throws Exception { List<State> states = new ArrayList<State>(); String lifecycleName = getLifeCycle(cNode); PublicationManager publicationManagerImpl = getApplicationComponent(PublicationManager.class); Lifecycle lifecycle = publicationManagerImpl.getLifecycle(lifecycleName); states = lifecycle.getStates(); return states; } private String getLifeCycle(Node cNode) throws Exception { String lifecycleName = null; try { lifecycleName = cNode.getProperty("publication:lifecycle").getString(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Failed to get States for node " + cNode, e); } } return lifecycleName; } /** * Check if a user is authorized to reach the given state of a given node. * The user must satisfy the constraints defined by state (memberships or role) * @param state * @param remoteUser * @param node * @return */ public boolean canReachState(State state, String remoteUser, NodeImpl node) { IdentityRegistry identityRegistry = getApplicationComponent(IdentityRegistry.class); Identity currentUser = identityRegistry.getIdentity(remoteUser); if (isAuthorizedByMembership(state, currentUser)) { return true; } if (isAuthorizedByRole(state, currentUser, node)) { return true; } return false; } /** * Check if the user has the memberships defined in the state * @param state * @param currentUser * @return */ boolean isAuthorizedByMembership(State state, Identity currentUser) { String membership = state.getMembership(); List<String> memberships = new ArrayList<String>(); if (membership != null) { memberships.add(membership); } if (state.getMemberships() != null) { memberships.addAll(state.getMemberships()); } for (String membership_ : memberships) { String[] membershipTab = membership_.split(":"); String expectedRole = membershipTab[0]; String expectedGroup = membershipTab[1]; if (currentUser.isMemberOf(expectedGroup, expectedRole)) { return true; } } return false; } /** * Check if a user is authorized to reach the state based on the state's role. * The user must have the role * @param state * @param currentUser * @param node * @return */ boolean isAuthorizedByRole(State state, Identity currentUser, NodeImpl node) { try { String role_ = state.getRole(); List<String> roles = new ArrayList<String>(); if (role_ != null) { roles.add(role_); } if (state.getRoles() != null) { roles.addAll(state.getRoles()); } for (String role : roles) { AccessControlList acl = node.getACL(); if (acl.hasPermissions()) { List<AccessControlEntry> entries = acl.getPermissionEntries(); for (AccessControlEntry accessControlEntry : entries) { String identity = accessControlEntry.getIdentity(); if (identity.indexOf(':') > 0) { // write access on node is defined by 'set_property' in exo JCR if (PermissionType.SET_PROPERTY.equals(accessControlEntry.getPermission())) { String authorizedGroup = identity.split(":")[1]; // user must have the configured role in one of the node's // authorized groups if (currentUser.isMemberOf(authorizedGroup, role)) { return true; } } } } } } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Failed to extract node permissions", e); } } return false; } }
11,841
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIPublicationSchedule.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/lifecycle/authoring/ui/UIPublicationSchedule.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.services.wcm.extensions.publication.lifecycle.authoring.ui; import java.text.SimpleDateFormat; import java.util.Calendar; import javax.jcr.ItemExistsException; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.exoplatform.ecm.utils.lock.LockUtil; import org.exoplatform.services.wcm.extensions.publication.lifecycle.authoring.AuthoringPublicationConstant; 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.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.UIFormDateTimeInput; import org.exoplatform.webui.form.validator.DateTimeValidator; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Mar 7, 2013 */ @ComponentConfig(lifecycle = UIFormLifecycle.class, template = "app:/groovy/webui/component/explorer/popup/action/UIPublicationSchedule.gtmpl", events = { @EventConfig(listeners = UIPublicationSchedule.SaveActionListener.class), @EventConfig(listeners = UIPublicationSchedule.ResetActionListener.class) }) public class UIPublicationSchedule extends UIForm { public static final String START_PUBLICATION = "UIPublicationPanelStartDateInput"; public static final String END_PUBLICATION = "UIPublicationPanelEndDateInput"; private static final Log LOG = LogFactory.getLog(UIPublicationSchedule.class.getName()); public UIPublicationSchedule() throws Exception { addUIFormInput(new UIFormDateTimeInput(START_PUBLICATION, START_PUBLICATION, null).addValidator(DateTimeValidator.class)); addUIFormInput(new UIFormDateTimeInput(END_PUBLICATION, END_PUBLICATION, null).addValidator(DateTimeValidator.class)); setActions(new String[] { "Save", "Reset" }); } public void init(Node node) throws Exception { Calendar startDate = null; Calendar endDate = null; if (node.hasProperty(AuthoringPublicationConstant.END_TIME_PROPERTY)) { endDate = node.getProperty(AuthoringPublicationConstant.END_TIME_PROPERTY).getDate(); } if (node.hasProperty(AuthoringPublicationConstant.START_TIME_PROPERTY)) { startDate = node.getProperty(AuthoringPublicationConstant.START_TIME_PROPERTY).getDate(); } if (startDate != null) { ((UIFormDateTimeInput) getChildById(START_PUBLICATION)).setCalendar(startDate); } if (endDate != null) { ((UIFormDateTimeInput) getChildById(END_PUBLICATION)).setCalendar(endDate); } } public boolean hasPublicationSchedule() throws RepositoryException { Node currentNode = this.getAncestorOfType(UIPublicationContainer.class).getChild(UIPublicationPanel.class).getCurrentNode(); if (currentNode == null) return false; return (currentNode.hasProperty(AuthoringPublicationConstant.END_TIME_PROPERTY) || currentNode.hasProperty(AuthoringPublicationConstant.START_TIME_PROPERTY)); } public static class SaveActionListener extends EventListener<UIPublicationSchedule> { public void execute(Event<UIPublicationSchedule> event) throws Exception { UIPublicationSchedule publicationSchedule = event.getSource(); UIApplication uiApp = publicationSchedule.getAncestorOfType(UIApplication.class); UIPublicationPanel publicationPanel = publicationSchedule.getAncestorOfType(UIPublicationContainer.class).getChild(UIPublicationPanel.class); UIFormDateTimeInput startPublication = publicationSchedule.getChildById(START_PUBLICATION); UIFormDateTimeInput endPublication = publicationSchedule.getChildById(END_PUBLICATION); String startValue = startPublication.getValue(); String endValue = endPublication.getValue(); if (startValue.isEmpty() || endValue.isEmpty()) { uiApp.addMessage(new ApplicationMessage("UIPublicationPanel.msg.invalid-format", null, ApplicationMessage.WARNING)); event.getRequestContext().addUIComponentToUpdateByAjax(publicationSchedule); return; } Calendar startDate = startPublication.getCalendar(); Calendar endDate = endPublication.getCalendar(); SimpleDateFormat format = new SimpleDateFormat(startPublication.getDatePattern_() + "Z"); startDate.setTime(format.parse(startValue)); endDate.setTime(format.parse(endValue)); Node node = publicationPanel.getCurrentNode(); try { if ((startDate == null && StringUtils.isNotEmpty(startValue)) || (endDate == null && StringUtils.isNotEmpty(endValue))) { uiApp.addMessage(new ApplicationMessage("UIPublicationPanel.msg.invalid-format", null, ApplicationMessage.ERROR)); event.getRequestContext().addUIComponentToUpdateByAjax(publicationSchedule); return; } if (startDate != null && endDate != null && startDate.after(endDate)) { uiApp.addMessage(new ApplicationMessage("UIPublicationPanel.msg.fromDate-after-toDate", null, ApplicationMessage.ERROR)); event.getRequestContext().addUIComponentToUpdateByAjax(publicationSchedule); return; } if(node.isLocked()) { node.getSession().addLockToken(LockUtil.getLockToken(node)); } if (StringUtils.isNotEmpty(startValue) || StringUtils.isNotEmpty(endValue)) { if (StringUtils.isNotEmpty(startValue)) node.setProperty(AuthoringPublicationConstant.START_TIME_PROPERTY, startDate); if (StringUtils.isNotEmpty(endValue)) node.setProperty(AuthoringPublicationConstant.END_TIME_PROPERTY, endDate); node.getSession().save(); // Show message save success uiApp.addMessage(new ApplicationMessage("UIPublicationSchedule.msg.save-finished", null, ApplicationMessage.INFO)); event.getRequestContext().addUIComponentToUpdateByAjax(publicationSchedule); } } catch (ItemExistsException iee) { if (LOG.isErrorEnabled()) { LOG.error("Error when adding properties to node"); } } } } public static class ResetActionListener extends EventListener<UIPublicationSchedule> { public void execute(Event<UIPublicationSchedule> event) throws Exception { UIPublicationSchedule publicationSchedule = event.getSource(); UIPublicationPanel publicationPanel = publicationSchedule.getAncestorOfType(UIPublicationContainer.class).getChild(UIPublicationPanel.class); Node node = publicationPanel.getCurrentNode(); UIFormDateTimeInput startPublication = publicationSchedule.getChildById(START_PUBLICATION); startPublication.setCalendar(null); if (node.hasProperty(AuthoringPublicationConstant.START_TIME_PROPERTY)) { node.getProperty(AuthoringPublicationConstant.START_TIME_PROPERTY).remove(); node.save(); } UIFormDateTimeInput endPublication = publicationSchedule.getChildById(END_PUBLICATION); endPublication.setCalendar(null); if (node.hasProperty(AuthoringPublicationConstant.END_TIME_PROPERTY)) { node.getProperty(AuthoringPublicationConstant.END_TIME_PROPERTY).remove(); node.save(); } event.getRequestContext().addUIComponentToUpdateByAjax(publicationSchedule); } } }
8,597
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
LifecyclesConfig.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/lifecycle/impl/LifecyclesConfig.java
package org.exoplatform.services.wcm.extensions.publication.lifecycle.impl; import java.util.ArrayList; import java.util.List; /** * Created by The eXo Platform MEA Author : haikel.thamri@exoplatform.com */ public class LifecyclesConfig { private List<Lifecycle> lifecycles = new ArrayList<Lifecycle>(); public List<Lifecycle> getLifecycles() { return lifecycles; } public void setActions(List<Lifecycle> lifecycles) { this.lifecycles = lifecycles; } public static class Lifecycle { private String name; private String publicationPlugin; private List<State> states = new ArrayList<State>(); public List<State> getStates() { return states; } public void setStates(List<State> states) { this.states = states; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPublicationPlugin() { return publicationPlugin; } public void setPublicationPlugin(String publicationPlugin) { this.publicationPlugin = publicationPlugin; } } public static class State { private String state; private String membership; private String role; private List<String> roles; public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } private List<String> memberships; public String getState() { return state; } public void setState(String state) { this.state = state; } public String getMembership() { return membership; } public void setMembership(String membership) { this.membership = membership; } public List<String> getMemberships() { return memberships; } public void setMemberships(List<String> memberships) { this.memberships = memberships; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } } }
2,188
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PostUpdateStateEventListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/listener/post/PostUpdateStateEventListener.java
package org.exoplatform.services.wcm.extensions.publication.listener.post; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; public class PostUpdateStateEventListener extends Listener { private static final Log LOG = ExoLogger.getLogger(PostUpdateStateEventListener.class.getName()); @Override public void onEvent(Event event) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug("this listener will be called every time a content changes its current state"); } } }
655
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PublicationManagerImpl.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/impl/PublicationManagerImpl.java
package org.exoplatform.services.wcm.extensions.publication.impl; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jcr.Node; import org.exoplatform.container.component.ComponentPlugin; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.security.Identity; import org.exoplatform.services.security.IdentityRegistry; import org.exoplatform.services.wcm.extensions.publication.PublicationManager; import org.exoplatform.services.wcm.extensions.publication.context.ContextPlugin; import org.exoplatform.services.wcm.extensions.publication.context.impl.ContextConfig.Context; import org.exoplatform.services.wcm.extensions.publication.lifecycle.StatesLifecyclePlugin; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.Lifecycle; import org.exoplatform.services.wcm.extensions.publication.lifecycle.impl.LifecyclesConfig.State; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.picocontainer.Startable; /** * PublicationManager is to manage the publication. */ public class PublicationManagerImpl implements PublicationManager, Startable { private Map<String, Lifecycle> lifecycles = new HashMap<String, Lifecycle>(); private Map<String, Context> contexts = new HashMap<String, Context>(); private static final Log LOG = ExoLogger.getLogger(PublicationManagerImpl.class.getName()); public void addLifecycle(ComponentPlugin plugin) { if (plugin instanceof StatesLifecyclePlugin) { if (((StatesLifecyclePlugin) plugin).getLifecyclesConfig() != null) { for (Lifecycle l:((StatesLifecyclePlugin) plugin).getLifecyclesConfig().getLifecycles()) { if (LOG.isInfoEnabled()) { LOG.info("Adding Lifecyle : "+l.getName()); } lifecycles.put(l.getName(), l); } } } } public void removeLifecycle(ComponentPlugin plugin) { if (plugin instanceof StatesLifecyclePlugin) { if (((StatesLifecyclePlugin) plugin).getLifecyclesConfig() != null) { for (Lifecycle l:((StatesLifecyclePlugin) plugin).getLifecyclesConfig().getLifecycles()) { if (lifecycles.get(l.getName())!=null) { if (LOG.isInfoEnabled()) { LOG.info("Removing Lifecyle : "+l.getName()); } lifecycles.remove(l.getName()); } } } } } public void addContext(ComponentPlugin plugin) { if (plugin instanceof ContextPlugin) { if (((ContextPlugin) plugin).getContextConfig() != null) { for (Context c:((ContextPlugin) plugin).getContextConfig().getContexts()) { if (LOG.isInfoEnabled()) { LOG.info("Adding Context : "+c.getName()); } contexts.put(c.getName(), c); } } } } public void removeContext(ComponentPlugin plugin) { if (plugin instanceof ContextPlugin) { if (((ContextPlugin) plugin).getContextConfig() != null) { for (Context c:((ContextPlugin) plugin).getContextConfig().getContexts()) { if (contexts.get(c.getName())!=null) { if (LOG.isInfoEnabled()) { LOG.info("Removing Context : "+c.getName()); } contexts.remove(c.getName()); } } } } } public void start() { } public void stop() { } public Context getContext(String name) { if (contexts.containsKey(name)) return contexts.get(name); return null; } public List<Context> getContexts() { return new ArrayList<Context>(contexts.values()); } public Lifecycle getLifecycle(String name) { if (lifecycles.containsKey(name)) return lifecycles.get(name); return null; } public List<Lifecycle> getLifecycles() { return new ArrayList<Lifecycle>(lifecycles.values()); } public List<Lifecycle> getLifecyclesFromUser(String remoteUser, String state) { List<Lifecycle> lifecycles = null; for (Lifecycle lifecycle : getLifecycles()) { if (lifecycles == null) lifecycles = new ArrayList<Lifecycle>(); IdentityRegistry identityRegistry = WCMCoreUtils.getService(IdentityRegistry.class); Identity identity = identityRegistry.getIdentity(remoteUser); for (State state_ : lifecycle.getStates()) { if (state.equals(state_.getState())) { List<String> memberships = new ArrayList<String>(); if (state_.getMembership() != null && !"automatic".equals(state_.getMembership())) { memberships.add(state_.getMembership()); } if (state_.getMemberships() != null) memberships.addAll(state_.getMemberships()); for (String membership : memberships) { String[] membershipTab = membership.split(":"); if (identity.isMemberOf(membershipTab[1], membershipTab[0])) { lifecycles.add(lifecycle); break; } } } } } return lifecycles; } public List<Node> getContents(String fromstate, String tostate, String date, String user, String lang, String workspace) throws Exception { WCMComposer wcmComposer = WCMCoreUtils.getService(WCMComposer.class); HashMap<String, String> filters = new HashMap<String, String>(); filters.put(WCMComposer.FILTER_MODE, WCMComposer.MODE_EDIT); filters.put(WCMComposer.FILTER_LANGUAGE, lang); String fromstateEscaped = org.exoplatform.services.cms.impl.Utils.escapeIllegalCharacterInQuery(fromstate); StringBuffer query = new StringBuffer("select * from nt:base where publication:currentState='" + fromstateEscaped + "'"); if (tostate!=null) { List<Lifecycle> lifecycles = this.getLifecyclesFromUser(user, tostate); if (lifecycles!=null && !lifecycles.isEmpty()) { query.append(" and ("); boolean first = true; for (Lifecycle lifecycle:lifecycles) { if (!first) query.append(" or "); first = false; query.append("publication:lifecycle='"+lifecycle.getName()+"'"); } query.append(")"); } else { query.append(" and publication:lifecycle='_no_lifecycle'"); } } else if (user!=null) { String userEscaped = org.exoplatform.services.cms.impl.Utils.escapeIllegalCharacterInQuery(user); query.append(" and publication:lastUser='" + userEscaped + "'"); } if (date!=null) { OffsetDateTime startPublishedDateTime = OffsetDateTime.now().plusDays(Integer.parseInt(date)); query.append(" and publication:startPublishedDate<=TIMESTAMP '"); query.append(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(startPublishedDateTime)); query.append("' order by publication:startPublishedDate asc"); } else { query.append(" order by exo:dateModified desc"); } filters.put(WCMComposer.FILTER_QUERY_FULL, query.toString()); if (LOG.isDebugEnabled()) LOG.debug("query="+query.toString()); List<Node> nodes = wcmComposer.getContents(workspace, "/", filters, WCMCoreUtils.getUserSessionProvider()); return nodes; } }
7,668
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ContextPlugin.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/context/ContextPlugin.java
package org.exoplatform.services.wcm.extensions.publication.context; import org.exoplatform.container.component.BaseComponentPlugin; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ObjectParameter; import org.exoplatform.services.wcm.extensions.publication.context.impl.ContextConfig; /** * Created by The eXo Platform MEA Author : * haikel.thamri@exoplatform.com */ public class ContextPlugin extends BaseComponentPlugin { private ContextConfig contextConfig; public ContextPlugin(InitParams params) { ObjectParameter param = params.getObjectParam("contexts"); if (param != null) { contextConfig = (ContextConfig) param.getObject(); } } public ContextConfig getContextConfig() { return contextConfig; } public void setContextConfig(ContextConfig contextConfig) { this.contextConfig = contextConfig; } }
925
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ContextConfig.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/authoring/services/src/main/java/org/exoplatform/services/wcm/extensions/publication/context/impl/ContextConfig.java
package org.exoplatform.services.wcm.extensions.publication.context.impl; import java.util.List; /** * Created by The eXo Platform MEA Author : * haikel.thamri@exoplatform.com */ public class ContextConfig { private List<Context> contexts; public List<Context> getContexts() { return contexts; } public void setContexts(List<Context> contexts) { this.contexts = contexts; } public static class Context { private String name; private String priority; private String lifecycle; private String membership; private List<String> memberships; private String path; private String nodetype; private String site; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } public String getLifecycle() { return lifecycle; } public void setLifecycle(String lifecycle) { this.lifecycle = lifecycle; } public String getMembership() { return membership; } public void setMembership(String membership) { this.membership = membership; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getNodetype() { return nodetype; } public void setNodetype(String nodetype) { this.nodetype = nodetype; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public List<String> getMemberships() { return memberships; } public void setMemberships(List<String> memberships) { this.memberships = memberships; } } }
1,874
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ViewInfoActionComponent.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/webui/src/main/java/org/exoplatform/ecm/webui/component/explorer/rightclick/action/ViewInfoActionComponent.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.rightclick.action; import java.util.regex.Matcher; import javax.jcr.AccessDeniedException; 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.control.listener.UIWorkingAreaActionListener; import org.exoplatform.ecm.webui.component.explorer.rightclick.viewinfor.UIViewInfoManager; import org.exoplatform.ecm.webui.utils.JCRExceptionManager; 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.UIPopupContainer; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.ext.manager.UIAbstractManager; import org.exoplatform.webui.ext.manager.UIAbstractManagerComponent; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Oct 29, 2010 */ @ComponentConfig(events = { @EventConfig(listeners = ViewInfoActionComponent.ViewInfoActionListener.class) }) public class ViewInfoActionComponent extends UIAbstractManagerComponent{ /** * @author hai_lethanh * class used to handle event raised on ViewFileInfoActionComponent */ public static class ViewInfoActionListener extends UIWorkingAreaActionListener<ViewInfoActionComponent> { @Override protected void processEvent(Event<ViewInfoActionComponent> event) throws Exception { ViewInfoActionComponent uicomp = event.getSource(); UIJCRExplorer uiExplorer = event.getSource().getAncestorOfType(UIJCRExplorer.class); UIPopupContainer objUIPopupContainer = uiExplorer.getChild(UIPopupContainer.class); String nodePath = event.getRequestContext().getRequestParameter(OBJECTID); Node selectedNode = null; if (nodePath != null && nodePath.length() != 0) { //get workspace & selected node path Matcher matcher = UIWorkingArea.FILE_EXPLORER_URL_SYNTAX.matcher(nodePath); String wsName = null; if (matcher.find()) { wsName = matcher.group(1); nodePath = matcher.group(2); } else { throw new IllegalArgumentException("The ObjectId is invalid '" + nodePath + "'"); } //get session Session session = uiExplorer.getSessionByWorkspace(wsName); //get UIApplication UIApplication uiApp = uicomp.getAncestorOfType(UIApplication.class); //get selected node try { // Use the method getNodeByPath because it is link aware selectedNode = uiExplorer.getNodeByPath(nodePath, session); } catch (PathNotFoundException path) { uiApp.addMessage(new ApplicationMessage("UIPopupMenu.msg.path-not-found-exception", null, ApplicationMessage.WARNING)); return; } catch (AccessDeniedException ace) { uiApp.addMessage(new ApplicationMessage("UIDocumentInfo.msg.null-exception", null, ApplicationMessage.WARNING)); return; } catch (Exception e) { JCRExceptionManager.process(uiApp, e); return; } } if (selectedNode == null) selectedNode = uiExplorer.getCurrentNode(); //show popup UIViewInfoManager uiViewInfoManager = uiExplorer.createUIComponent(UIViewInfoManager.class, null, null); uiViewInfoManager.setSelectedNode(selectedNode); objUIPopupContainer.activate(uiViewInfoManager, 600, 0); event.getRequestContext().addUIComponentToUpdateByAjax(objUIPopupContainer); } } @Override public Class<? extends UIAbstractManager> getUIAbstractManagerClass() { return null; } }
4,765
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIViewInfoContainer.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/webui/src/main/java/org/exoplatform/ecm/webui/component/explorer/rightclick/viewinfor/UIViewInfoContainer.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.rightclick.viewinfor; import java.net.URLDecoder; import java.util.LinkedHashMap; import java.util.Map; import javax.jcr.*; import javax.jcr.nodetype.NodeType; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Nov 3, 2010 */ @ComponentConfig ( template = "classpath:templates/viewinfo/UIViewInfoContainer.gtmpl", events = { @EventConfig(listeners = UIViewInfoContainer.CloseActionListener.class) } ) public class UIViewInfoContainer extends UIContainer { /** * the hash map which contains information of node */ private Map<String, String> inforMap; //constains private static final String NAME = "name"; private static final String TITLE = "title"; private static final String TYPE = "type"; private static final String SIZE = "size"; private static final String OWNER = "owner"; private static final String LAST_MODIFIER = "lastModifier"; private static final String CREATED = "created"; private static final String LAST_MODIFIED = "lastModified"; private static final String PUBLICATION_STATE = "publicationState"; private static final String DC_TITLE = "dc:title"; private static final String PUBLICATION_CURRENT_STATE = "publication:currentState"; private static final String EXO_LAST_MODIFIED_DATE = "exo:lastModifiedDate"; /** * checking selected node is a folder or not */ private boolean isFolder = false; /** * constructor * @throws RepositoryException */ public UIViewInfoContainer() throws RepositoryException { inforMap = new LinkedHashMap<String, String>(); } /** * get inforMap value * @return inforMap value */ public Map<String, String> getInforMap() { return inforMap; } /** * set value for inforMap * @param inforMap */ public void setInforMap(Map<String, String> inforMap) { this.inforMap = inforMap; } /** * checking selected node is a folder or not * @return */ public boolean isFolder() { return isFolder; } /** * read node properties, put value in to inforMap * @throws Exception */ public void readNodeInformation() throws Exception { Node selectedNode = getSelectedNode(); //get name String name = Utils.getName(selectedNode); // decode name for cyrillic chars name = URLDecoder.decode(name, "UTF-8"); inforMap.put(NAME, name); //get title inforMap.put(TITLE, Utils.getTitle(selectedNode)); //get Type inforMap.put(TYPE, getType(selectedNode)); //get file size if (selectedNode.hasNode(Utils.JCR_CONTENT)) { Node contentNode = selectedNode.getNode(Utils.JCR_CONTENT); if (contentNode.hasProperty(Utils.JCR_DATA)) { double size = contentNode.getProperty(Utils.JCR_DATA).getLength(); String fileSize = Utils.calculateFileSize(size); inforMap.put(SIZE, fileSize); } } //get owner if (selectedNode.hasProperty(Utils.EXO_OWNER)) { inforMap.put(OWNER, selectedNode.getProperty(Utils.EXO_OWNER).getString()); } //get last modifier if (selectedNode.hasProperty(Utils.EXO_LASTMODIFIER)) { inforMap.put(LAST_MODIFIER, selectedNode.getProperty(Utils.EXO_LASTMODIFIER).getString()); } //get created date if (selectedNode.hasProperty(Utils.EXO_CREATED_DATE)) { inforMap.put(CREATED, selectedNode.getProperty(Utils.EXO_CREATED_DATE).getString()); } //get last modified date if (selectedNode.hasProperty(EXO_LAST_MODIFIED_DATE)) { inforMap.put(LAST_MODIFIED, selectedNode.getProperty(EXO_LAST_MODIFIED_DATE).getString()); } //get publication state if (selectedNode.hasProperty(PUBLICATION_CURRENT_STATE)) { inforMap.put(PUBLICATION_STATE, selectedNode.getProperty(PUBLICATION_CURRENT_STATE).getString()); } } /** * get type of node * @param node * @return type of node * @throws Exception */ private String getType(Node node) throws Exception { TemplateService templateService = getApplicationComponent(TemplateService.class); NodeType nodeType = node.getPrimaryNodeType(); String strNodeTypeName = nodeType.getName(); String strType = ""; isFolder = false; if (nodeType.isNodeType(Utils.NT_FILE)) { // is file that is uploaded by // user if (!node.isCheckedOut()) node.checkout(); Node contentNode = node.getNode(Utils.JCR_CONTENT); strType = contentNode.getProperty(Utils.JCR_MIMETYPE).getString(); } else if (templateService.isManagedNodeType(strNodeTypeName)) { // is Document which is created by user on web strType = templateService.getTemplateLabel(strNodeTypeName); } else if (nodeType.isNodeType(Utils.NT_UNSTRUCTURED) || nodeType.isNodeType(Utils.NT_FOLDER)) { // is a folder isFolder = true; } else { // other strType = strNodeTypeName; } return strType; } /** * get name of action * @return */ public String getCloseAction() { return "Close"; } /** * get selected node * @return */ private Node getSelectedNode() { UIViewInfoManager uiManager = getParent(); return uiManager.getSelectedNode(); } /** * @author hai_lethanh * class used for handling Close event */ static public class CloseActionListener extends EventListener<UIViewInfoContainer> { @Override public void execute(Event<UIViewInfoContainer> event) throws Exception { event.getSource().getAncestorOfType(UIJCRExplorer.class).cancelAction() ; } } }
7,257
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIViewInfoManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/ext/webui/src/main/java/org/exoplatform/ecm/webui/component/explorer/rightclick/viewinfor/UIViewInfoManager.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.rightclick.viewinfor; import javax.jcr.Node; 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.core.UIContainer; import org.exoplatform.webui.core.UIPopupComponent; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; /** * Created by The eXo Platform SAS Author : eXoPlatform exo@exoplatform.com Nov * 3, 2010 */ @ComponentConfig ( lifecycle = UIContainerLifecycle.class ) public class UIViewInfoManager extends UIContainer implements UIPopupComponent { private static final Log LOG = ExoLogger.getLogger(UIViewInfoManager.class.getName()); /** * the node that is selected by right clicking */ private NodeLocation selectedNode; /** * the constructor * @throws Exception */ public UIViewInfoManager() throws Exception { addChild(UIViewInfoContainer.class, null, null); } /** * get selected node * @return selected node */ public Node getSelectedNode() { return NodeLocation.getNodeByLocation(selectedNode); } /** * set value for selected node * @param selectedNode */ public void setSelectedNode(Node selectedNode) { this.selectedNode = NodeLocation.getNodeLocationByNode(selectedNode); } public void activate() { try { getChild(UIViewInfoContainer.class).readNodeInformation(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error!", e.getMessage()); } } } public void deActivate() { } }
2,484
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DummyECMSTestCase.java
/FileExtraction/Java_unseen/exoplatform_ecms/testsuite/test/src/test/java/org/exoplatform/ecms/test/DummyECMSTestCase.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.ecms.test; import java.io.StringWriter; import javax.jcr.RepositoryException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.exoplatform.common.http.HTTPMethods; import org.exoplatform.component.test.ConfigurationUnit; import org.exoplatform.component.test.ConfiguredBy; import org.exoplatform.component.test.ContainerScope; import org.exoplatform.ecms.test.mock.MockRestService; import org.exoplatform.services.jcr.config.RepositoryConfigurationException; import org.exoplatform.services.resources.LocaleConfigService; import org.exoplatform.services.rest.impl.ContainerResponse; import org.exoplatform.services.rest.impl.MultivaluedMapImpl; import org.exoplatform.services.security.IdentityConstants; /** * Created by The eXo Platform SAS * @author : Pham Duy Dong * dongpd@exoplatform.com */ @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") }) public class DummyECMSTestCase extends BaseECMSResourceTestCase { private final String MOCK_RESOURCE_URL = "/mock/guest"; public void setUp() throws Exception { super.setUp(); MockRestService restService = (MockRestService) this.container.getComponentInstanceOfType(MockRestService.class); this.binder.addResource(restService, null); applySystemSession(); } public void testInitServices() throws Exception { assertNotNull(repositoryService); assertEquals(repositoryService.getDefaultRepository().getConfiguration().getName(), "repository"); assertEquals(repositoryService.getDefaultRepository() .getConfiguration() .getDefaultWorkspaceName(), "collaboration"); assertNotNull(container); // assertEquals(repositoryService.getCurrentRepository().getWorkspaceNames().length, 4); assertNotNull(getService(LocaleConfigService.class)); // System.out.println("Num of workspace: " + repositoryService.getCurrentRepository().getWorkspaceNames().length); // System.out.println("Num of node types: " + repositoryService.getCurrentRepository().getNodeTypeManager().getAllNodeTypes().getSize()); // System.out.println("Num of locales: " + getService(LocaleConfigService.class).getLocalConfigs().size()); // System.out.println("hibernate" + (getService(HibernateService.class) == null)); // System.out.println("Cache: " + (getService(CacheService.class) == null)); // System.out.println("Document Reader : " + (getService(DocumentReaderService.class) == null)); // System.out.println("DescriptionService : " + (getService(DescriptionService.class) == null)); // System.out.println("DataStorage : " + (getService(DataStorage.class) == null)); // System.out.println("TransactionManagerLookup : " + (getService(TransactionManagerLookup.class))); // System.out.println("TransactionService : " + (getService(TransactionService.class))); // System.out.println("POMSessionManager : " + (getService(POMSessionManager.class))); // System.out.println("PicketLinkIDMService : " + (getService(PicketLinkIDMService.class))); // System.out.println("PicketLinkIDMCacheService : " + (getService(PicketLinkIDMCacheService.class))); // System.out.println("ResourceCompressor : " + (getService(ResourceCompressor.class))); // System.out.println("ModelDataStorage : " + (getService(ModelDataStorage.class))); // System.out.println("NavigationService : " + (getService(NavigationService.class))); // System.out.println("JTAUserTransactionLifecycleService : " + (getService(JTAUserTransactionLifecycleService.class))); // System.out.println("SkinService : " + (getService(SkinService.class))); // System.out.println("PortalContainerInfo : " + (getService(PortalContainerInfo.class))); // System.out.println("LogConfigurationInitializer : " + (getService(LogConfigurationInitializer.class))); } public void testInitializedServices() { assertNotNull(this.container); assertNotNull(this.orgService); assertNotNull(this.repositoryService); assertNotNull(this.sessionProviderService_); } public void testApplySession() throws RepositoryConfigurationException, RepositoryException{ assertNotNull(this.session); assertNotNull(this.repository); assertEquals(IdentityConstants.SYSTEM, session.getUserID()); applyUserSession("john", "gtn", COLLABORATION_WS); assertNotNull(this.session); assertEquals("john", session.getUserID()); applyUserSession("john", "gtn", DMSSYSTEM_WS); assertNotNull(this.session); assertEquals("john", session.getUserID()); } public void testAchieveResource() throws Exception{ StringWriter writer = new StringWriter().append("name=guest"); byte[] data = writer.getBuffer().toString().getBytes("UTF-8"); MultivaluedMap<String, String> h = new MultivaluedMapImpl(); h.putSingle("content-type", MediaType.APPLICATION_FORM_URLENCODED.toString()); h.putSingle("content-length", "" + data.length); ContainerResponse response = service(HTTPMethods.POST.toString(), MOCK_RESOURCE_URL, StringUtils.EMPTY, h, data); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals("Registed guest", response.getEntity().toString()); response = service(HTTPMethods.GET.toString(), MOCK_RESOURCE_URL + "?name=guest", StringUtils.EMPTY, null, null); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals("Hello guest", response.getEntity().toString()); response = service(HTTPMethods.DELETE.toString(), MOCK_RESOURCE_URL + "?name=guest", StringUtils.EMPTY, null, null); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals("Removed guest", response.getEntity().toString()); } public void tearDown() throws Exception { super.tearDown(); } }
7,085
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
MockRestService.java
/FileExtraction/Java_unseen/exoplatform_ecms/testsuite/test/src/test/java/org/exoplatform/ecms/test/mock/MockRestService.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.ecms.test.mock; import java.util.ArrayList; import java.util.List; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.exoplatform.services.rest.resource.ResourceContainer; /** * Created by The eXo Platform SAS * Author : Lai Trung Hieu * hieult@exoplatform.com * Jun 6, 2012 */ @Path("/mock") public class MockRestService implements ResourceContainer { private List<String> guests = new ArrayList<String>(); private final CacheControl cc; public MockRestService() { this.cc = new CacheControl(); this.cc.setNoCache(true); this.cc.setNoStore(true); } @GET @Path("/guest") @Produces(MediaType.APPLICATION_XHTML_XML) public Response getGuest(@QueryParam("name") @DefaultValue("anonymous") String name) { if (!guests.contains(name)) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return Response.ok("Hello " + name, MediaType.APPLICATION_XHTML_XML).cacheControl(cc).build(); } @POST @Path("/guest") @Produces(MediaType.APPLICATION_JSON) public Response register(@FormParam("name") @DefaultValue("anonymous") String name) { guests.add(name); return Response.ok("Registed " + name, MediaType.APPLICATION_JSON).cacheControl(cc).build(); } @DELETE @Path("/guest") @Produces(MediaType.TEXT_PLAIN) public Response remove(@QueryParam("name") @DefaultValue("anonymous") String name) { if (!guests.contains(name)) { throw new WebApplicationException(Response.Status.NOT_FOUND); } guests.remove(name); return Response.ok("Removed " + name, MediaType.TEXT_PLAIN).cacheControl(cc).build(); } }
2,711
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
BaseECMSResourceTestCase.java
/FileExtraction/Java_unseen/exoplatform_ecms/testsuite/test/src/main/java/org/exoplatform/ecms/test/BaseECMSResourceTestCase.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.ecms.test; import java.io.ByteArrayInputStream; import java.net.URI; import java.util.List; import java.util.Map; import javax.ws.rs.core.MultivaluedMap; import org.exoplatform.services.rest.ContainerResponseWriter; import org.exoplatform.services.rest.impl.ContainerRequest; import org.exoplatform.services.rest.impl.ContainerResponse; import org.exoplatform.services.rest.impl.EnvironmentContext; import org.exoplatform.services.rest.impl.InputHeadersMap; import org.exoplatform.services.rest.impl.MultivaluedMapImpl; import org.exoplatform.services.rest.tools.DummyContainerResponseWriter; import org.exoplatform.services.test.mock.MockHttpServletRequest; import jakarta.servlet.http.HttpServletRequest; /** * Created by The eXo Platform SAS * Author : Lai Trung Hieu * hieult@exoplatform.com * Jun 6, 2012 */ public abstract class BaseECMSResourceTestCase extends BaseECMSTestCase { /** * Get response with provided writer * @param method * @param requestURI * @param baseURI * @param headers * @param data * @param writer * @return * @throws Exception */ public ContainerResponse service(String method, String requestURI, String baseURI, Map<String, List<String>> headers, byte[] data, ContainerResponseWriter writer) throws Exception{ if (headers == null) { headers = new MultivaluedMapImpl(); } ByteArrayInputStream in = null; if (data != null) { in = new ByteArrayInputStream(data); } EnvironmentContext envctx = new EnvironmentContext(); HttpServletRequest httpRequest = new MockHttpServletRequest(requestURI, in, in != null ? in.available() : 0, method, headers); envctx.put(HttpServletRequest.class, httpRequest); EnvironmentContext.setCurrent(envctx); ContainerRequest request = new ContainerRequest(method, new URI(requestURI), new URI(baseURI), in, new InputHeadersMap(headers)); ContainerResponse response = new ContainerResponse(writer); requestHandler.handleRequest(request, response); return response; } /** * Get response without provided writer * @param method * @param requestURI * @param baseURI * @param headers * @param data * @return * @throws Exception */ public ContainerResponse service(String method, String requestURI, String baseURI, MultivaluedMap<String, String> headers, byte[] data) throws Exception { return service(method, requestURI, baseURI, headers, data, new DummyContainerResponseWriter()); } /** * Register supplied class as per-request root resource if it has valid * JAX-RS annotations and no one resource with the same UriPattern already * registered. * * @param resourceClass class of candidate to be root resource * @param properties optional resource properties. It may contains additional * info about resource, e.g. description of resource, its * responsibility, etc. This info can be retrieved * {@link org.exoplatform.services.rest.ObjectModel#getProperties()}. * This parameter may be <code>null</code> */ public void addResource(final Class<?> resourceClass, MultivaluedMap<String, String> properties) { this.binder.addResource(resourceClass, properties); } /** * Register supplied Object as singleton root resource if it has valid JAX-RS * annotations and no one resource with the same UriPattern already * registered. * * @param resource candidate to be root resource * @param properties optional resource properties. It may contains additional * info about resource, e.g. description of resource, its * responsibility, etc. This info can be retrieved * {@link org.exoplatform.services.rest.ObjectModel#getProperties()}. * This parameter may be <code>null</code> */ public void addResource(final Object resource, MultivaluedMap<String, String> properties) { this.binder.addResource(resource, properties); } /** * Remove the resource instance of provided class from root resource * container. * * @param clazz the class of resource */ public void removeResource(Class clazz) { this.binder.removeResource(clazz); } }
5,494
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DumpThreadLocalSessionProviderService.java
/FileExtraction/Java_unseen/exoplatform_ecms/testsuite/test/src/main/java/org/exoplatform/ecms/test/DumpThreadLocalSessionProviderService.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.ecms.test; import javax.jcr.Session; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.app.ThreadLocalSessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.Identity; import org.exoplatform.services.security.IdentityConstants; /** * Created by The eXo Platform SAS * Author : Lai Trung Hieu * hieult@exoplatform.com * Jun 6, 2012 */ public class DumpThreadLocalSessionProviderService extends ThreadLocalSessionProviderService { private DumpSessionProvider userSessionProvider; public DumpThreadLocalSessionProviderService(){ super(); } public SessionProvider getSessionProvider(Object key) { return userSessionProvider; } /** * Apply an user session * @param userSession */ public void applyUserSession(Session userSession) { // create user session provider if (userSession != null) { userSessionProvider = new DumpSessionProvider(new ConversationState(new Identity(userSession.getUserID()))); } else { userSessionProvider = new DumpSessionProvider(new ConversationState(new Identity(IdentityConstants.ANONIM))); } userSessionProvider.setSession(userSession); } public static class DumpSessionProvider extends SessionProvider { private Session session = null; public DumpSessionProvider(ConversationState userState) { super(userState); } public void setSession(Session value) { session = value; } public Session getSession(String workspace, ManageableRepository repo) { return session; } } }
2,467
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
BaseECMSTestCase.java
/FileExtraction/Java_unseen/exoplatform_ecms/testsuite/test/src/main/java/org/exoplatform/ecms/test/BaseECMSTestCase.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.ecms.test; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.exoplatform.commons.testing.BaseExoTestCase; import org.exoplatform.component.test.ConfigurationUnit; import org.exoplatform.component.test.ConfiguredBy; import org.exoplatform.component.test.ContainerScope; import org.exoplatform.container.PortalContainer; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.config.RepositoryConfigurationException; import org.exoplatform.services.jcr.core.CredentialsImpl; 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.impl.core.SessionImpl; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.organization.OrganizationService; import org.exoplatform.services.rest.impl.ApplicationContextImpl; import org.exoplatform.services.rest.impl.ProviderBinder; import org.exoplatform.services.rest.impl.RequestHandlerImpl; import org.exoplatform.services.rest.impl.ResourceBinder; import org.exoplatform.services.security.ConversationState; import org.exoplatform.social.metadata.favorite.FavoriteService; /** * Created by The eXo Platform SAS * @author : Pham Duy Dong * dongpd@exoplatform.com */ @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") }) public abstract class BaseECMSTestCase extends BaseExoTestCase { protected static Log log = ExoLogger.getLogger(BaseECMSTestCase.class.getName()); protected PortalContainer container; protected ProviderBinder providers; protected ResourceBinder binder; protected RequestHandlerImpl requestHandler; protected OrganizationService orgService; protected CredentialsImpl credentials; protected RepositoryService repositoryService; protected SessionProvider sessionProvider; protected Session session; protected ManageableRepository repository; protected SessionProviderService sessionProviderService_; protected final String REPO_NAME = "repository"; protected final String DMSSYSTEM_WS = "dms-system"; protected final String SYSTEM_WS = "system"; protected final String COLLABORATION_WS = "collaboration"; @Override public void setUp() throws Exception { begin(); initServices(); } @Override public void tearDown() throws Exception { removeAllData(); end(); } private void removeAllData() { } @SuppressWarnings("unchecked") public <T> T getService(Class<T> clazz) { return (T) getContainer().getComponentInstanceOfType(clazz); } /** * Apply a system session * @throws RepositoryConfigurationException * @throws RepositoryException */ public void applySystemSession() throws RepositoryConfigurationException, RepositoryException { System.setProperty("gatein.tenant.repository.name", REPO_NAME); container = PortalContainer.getInstance(); repositoryService.setCurrentRepositoryName(REPO_NAME); repository = repositoryService.getCurrentRepository(); closeOldSession(); sessionProvider = sessionProviderService_.getSystemSessionProvider(null); session = sessionProvider.getSession(COLLABORATION_WS, repository); sessionProvider.setCurrentRepository(repository); sessionProvider.setCurrentWorkspace(COLLABORATION_WS); } /** * Apply an user session with a given user name, password and workspace name * @param username name of user * @param password password of user * @param workspaceName workspace name * @throws RepositoryConfigurationException * @throws RepositoryException */ public void applyUserSession(String username, String password, String workspaceName) throws RepositoryConfigurationException, RepositoryException { repositoryService.setCurrentRepositoryName(REPO_NAME); repository = repositoryService.getCurrentRepository(); credentials = new CredentialsImpl(username, password.toCharArray()); closeOldSession(); session = (SessionImpl) repository.login(credentials, workspaceName); ((DumpThreadLocalSessionProviderService)sessionProviderService_).applyUserSession(session); } private void initServices(){ container = PortalContainer.getInstance(); orgService = (OrganizationService) container.getComponentInstanceOfType(OrganizationService.class); repositoryService = (RepositoryService) container.getComponentInstanceOfType(RepositoryService.class); binder = (ResourceBinder) container.getComponentInstanceOfType(ResourceBinder.class); requestHandler = (RequestHandlerImpl) container.getComponentInstanceOfType(RequestHandlerImpl.class); ProviderBinder.setInstance(new ProviderBinder()); providers = ProviderBinder.getInstance(); ApplicationContextImpl.setCurrent(new ApplicationContextImpl(null, null, providers)); binder.clear(); sessionProviderService_ = (SessionProviderService) container.getComponentInstanceOfType(SessionProviderService.class); String loginConf = this.getClass().getResource("/conf/standalone/login.conf").toString(); System.setProperty("java.security.auth.login.config", loginConf); try { applySystemSession(); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } fail(); } } /** * End current session */ protected void endSession() { sessionProviderService_.removeSessionProvider(null); ConversationState.setCurrent(null); } /** * Close current session */ private void closeOldSession() { if (session != null && session.isLive()) { session.logout(); // remove user session ((DumpThreadLocalSessionProviderService) sessionProviderService_).applyUserSession(null); } } }
7,185
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIECMAdminWorkingArea.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/UIECMAdminWorkingArea.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin; import java.util.ArrayList; import java.util.List; import javax.portlet.PortletPreferences; import org.exoplatform.services.log.Log; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.log.ExoLogger; 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.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.ext.manager.UIAbstractManager; import org.exoplatform.webui.ext.manager.UIAbstractManagerComponent; /** * Created by The eXo Platform SARL * Author : Tran The Trong * trongtt@gmail.com * Sep 19, 2006 * 8:30:33 AM */ @ComponentConfig( template = "app:/groovy/webui/component/admin/UIECMAdminWorkingArea.gtmpl" ) public class UIECMAdminWorkingArea extends UIContainer { /** * Logger. */ private static final Log LOG = ExoLogger.getLogger(UIECMAdminWorkingArea.class.getName()); private String renderedCompId_ ; public String getRenderedCompId() { return renderedCompId_ ; } public void setRenderedCompId(String renderedId) { this.renderedCompId_ = renderedId ; } public <T extends UIComponent> void setChild(Class<T> type) { renderedCompId_ = getChild(type).getId(); setRenderedChild(type); } public UIECMAdminWorkingArea() throws Exception {} public void init() throws Exception { UIECMAdminPortlet portlet = getAncestorOfType(UIECMAdminPortlet.class); UIECMAdminControlPanel controlPanel = portlet.getChild(UIECMAdminControlPanel.class); List<UIAbstractManagerComponent> managers = controlPanel.getManagers(); List<UIAbstractManagerComponent> rejectedManagers = null; if (managers == null) { return; } for (UIAbstractManagerComponent manager : managers) { UIAbstractManager uiManager = getChild(manager.getUIAbstractManagerClass()); if (uiManager == null) { uiManager = addChild(manager.getUIAbstractManagerClass(), null, null); if (renderedCompId_ == null) { try { uiManager.init(); renderedCompId_ = uiManager.getId(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("The manager " + uiManager.getClass() + " cannot be initialized, it will be unregistered", e); } if (rejectedManagers == null) { rejectedManagers = new ArrayList<UIAbstractManagerComponent>(); } rejectedManagers.add(manager); removeChild(manager.getUIAbstractManagerClass()); } } else { uiManager.setRendered(false); } } else { uiManager.refresh(); } } if (rejectedManagers != null) { for (UIAbstractManagerComponent manager : rejectedManagers) { controlPanel.unregister(manager); } } } public void checkRepository() throws Exception{ PortletRequestContext pcontext = (PortletRequestContext) WebuiRequestContext .getCurrentInstance(); PortletPreferences pref = pcontext.getRequest().getPreferences(); try { getApplicationComponent(RepositoryService.class).getCurrentRepository(); } catch (Exception e) { String defaultRepo = getApplicationComponent(RepositoryService.class).getCurrentRepository() .getConfiguration().getName(); pref.setValue(Utils.REPOSITORY, defaultRepo); pref.store(); } } }
4,393
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIECMAdminPortlet.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/UIECMAdminPortlet.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin; import javax.jcr.RepositoryException; import javax.portlet.PortletPreferences; import javax.portlet.PortletRequest; import org.exoplatform.ecm.webui.component.admin.unlock.UIUnLockManager; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.services.cms.impl.DMSRepositoryConfiguration; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.webui.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.config.annotation.EventConfig; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.UIPortletApplication; import org.exoplatform.webui.core.lifecycle.UIApplicationLifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SARL * Author : Tran The Trong * trongtt@exoplatform.com * Jul 27, 2006 */ @ComponentConfig( lifecycle = UIApplicationLifecycle.class, template = "app:/groovy/webui/component/admin/UIECMAdminPortlet.gtmpl", events = { @EventConfig(listeners = UIECMAdminPortlet.ShowHideActionListener.class)} ) public class UIECMAdminPortlet extends UIPortletApplication { /** * Logger. */ private static final Log LOG = ExoLogger.getLogger(UIECMAdminPortlet.class.getName()); private boolean isShowSideBar = true ; private boolean isSelectedRepo_ = true ; private String repoName_ = "" ; public UIECMAdminPortlet() throws Exception { UIPopupContainer uiPopupAction = addChild(UIPopupContainer.class, null, "UIECMAdminUIPopupAction"); uiPopupAction.getChild(UIPopupWindow.class).setId("UIECMAdminUIPopupWindow") ; try{ UIECMAdminControlPanel controlPanel = addChild(UIECMAdminControlPanel.class, null, null) ; controlPanel.initialize(); UIECMAdminWorkingArea workingArea = addChild(UIECMAdminWorkingArea.class, null, null); workingArea.init(); } catch(Exception e) { if (LOG.isErrorEnabled()) { LOG.error("An expected error occured while initializing the portlet", e); } } } public void initChilds() throws Exception{ UIECMAdminControlPanel controlPanel = getChild(UIECMAdminControlPanel.class); if(controlPanel == null) { controlPanel = addChild(UIECMAdminControlPanel.class, null, null) ; controlPanel.initialize(); } UIECMAdminWorkingArea workingArea = getChild(UIECMAdminWorkingArea.class) ; if(workingArea == null){ workingArea = addChild(UIECMAdminWorkingArea.class, null, null) ; } workingArea.init() ; } public String getUserAgent() { PortletRequestContext requestContext = PortletRequestContext.getCurrentInstance(); PortletRequest portletRequest = requestContext.getRequest(); return portletRequest.getProperty("User-Agent"); } public ManageableRepository getRepository() throws Exception { RepositoryService rservice = getApplicationComponent(RepositoryService.class) ; return rservice.getCurrentRepository(); } public boolean isShowSideBar() { return isShowSideBar ; } public void setShowSideBar(boolean bl) { this.isShowSideBar = bl ; } public boolean isSelectedRepo() { return isSelectedRepo_ ; } public void setSelectedRepo(boolean bl) { this.isSelectedRepo_ = bl ; } public String getRepoName() {return repoName_ ;} public void setRepoName(String name){repoName_ = name ;} static public class ShowHideActionListener extends EventListener<UIECMAdminPortlet> { public void execute(Event<UIECMAdminPortlet> event) throws Exception { UIECMAdminPortlet uiECMAdminPortlet = event.getSource() ; uiECMAdminPortlet.setShowSideBar(!uiECMAdminPortlet.isShowSideBar) ; } } public String getPreferenceRepository() { try { return getApplicationComponent(RepositoryService.class).getCurrentRepository().getConfiguration().getName(); } catch (RepositoryException e) { return null; } } public String getPreferenceWorkspace() { PortletPreferences portletPref = getPortletPreferences() ; String workspace = portletPref.getValue(Utils.WORKSPACE_NAME, "") ; return workspace ; } public PortletPreferences getPortletPreferences() { PortletRequestContext pcontext = (PortletRequestContext)WebuiRequestContext.getCurrentInstance() ; PortletRequest prequest = pcontext.getRequest() ; PortletPreferences portletPref = prequest.getPreferences() ; return portletPref ; } public void processRender(WebuiApplication app, WebuiRequestContext context) throws Exception { UIECMAdminWorkingArea uiecmAdminWorkingArea = getChild(UIECMAdminWorkingArea.class); UIUnLockManager uiUnLockManager = uiecmAdminWorkingArea.getChild(UIUnLockManager.class); if (uiUnLockManager != null && uiUnLockManager.isRendered()) { uiUnLockManager.update(); } super.processRender(app, context); } public String getDMSSystemWorkspace(String repository) throws Exception { DMSConfiguration dmsConfiguration = WCMCoreUtils.getService(DMSConfiguration.class); DMSRepositoryConfiguration dmsRepoConfig = dmsConfiguration.getConfig(); return dmsRepoConfig.getSystemWorkspace(); } }
6,493
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIECMAdminControlPanel.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/UIECMAdminControlPanel.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin; import java.util.ArrayList; import java.util.List; import org.exoplatform.services.log.Log; import org.exoplatform.services.log.ExoLogger; 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; import org.exoplatform.webui.ext.manager.UIAbstractManagerComponent; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Sep 19, 2006 * 8:26:51 AM */ @ComponentConfig( template = "app:/groovy/webui/component/admin/UIECMAdminControlPanel.gtmpl" ) public class UIECMAdminControlPanel extends UIContainer { /** * Logger. */ private static final Log LOG = ExoLogger.getLogger(UIECMAdminControlPanel.class.getName()); public static final String EXTENSION_TYPE = "org.exoplatform.ecm.dms.UIECMAdminControlPanel"; private List<UIAbstractManagerComponent> managers = new ArrayList<UIAbstractManagerComponent>(); public UIECMAdminControlPanel() throws Exception {} public List<?> getEvents() { return getComponentConfig().getEvents() ; } void initialize() throws Exception { UIExtensionManager manager = getApplicationComponent(UIExtensionManager.class); List<UIExtension> extensions = manager.getUIExtensions(EXTENSION_TYPE); if (extensions == null) { return; } for (UIExtension extension : extensions) { UIComponent component = manager.addUIExtension(extension, null, this); 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()); managers.add(uiAbstractManagerComponent); } 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()); } } } List<UIAbstractManagerComponent> getManagers() { return managers; } void unregister(UIAbstractManagerComponent component) { managers.remove(component); } /** * Check whether a specified category is the same to category of current render manager item. * * @param currentCategory Current Category * @param categories List of categories of side blocks * @param managersGroup Contain managers groups * @return true: the same, false: not the same */ public boolean isSameCategoryWithCurrentRenderedManager (String currentCategory, ArrayList<String> categories, ArrayList<ArrayList<UIAbstractManagerComponent>> managersGroup) { int i = 0; UIECMAdminWorkingArea workingArea = this.getAncestorOfType(UIECMAdminPortlet.class).getChild(UIECMAdminWorkingArea.class); String currentRenderId = workingArea.getRenderedCompId(); for(String category : categories) { if (category.equals(currentCategory)) { ArrayList<UIAbstractManagerComponent> groups = managersGroup.get(i); for(UIAbstractManagerComponent group : groups) { String extensionName = group.getUIExtensionName(); if (extensionName.equals(currentRenderId)) return true; } } i++; } return false; } }
4,636
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIActionTypeList.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/action/UIActionTypeList.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.action; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.utils.LazyPageList; import org.exoplatform.commons.utils.ListAccessImpl; import org.exoplatform.ecm.webui.component.admin.UIECMAdminPortlet; import org.exoplatform.ecm.webui.core.UIPagingGrid; import org.exoplatform.services.cms.actions.ActionServiceContainer; import org.exoplatform.services.cms.impl.Utils; import org.exoplatform.services.cms.scripts.impl.ScriptServiceImpl; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.nodetype.ExtendedNodeTypeManager; 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.event.Event; import org.exoplatform.webui.event.EventListener; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeManager; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by The eXo Platform SARL * Author : pham tuan * phamtuanchip@yahoo.de * September 20, 2006 * 16:37:15 */ @ComponentConfig( template = "system:/groovy/ecm/webui/UIGridWithButton.gtmpl", events = { @EventConfig(listeners = UIActionTypeList.AddActionActionListener.class), @EventConfig(listeners = UIActionTypeList.EditActionListener.class), @EventConfig(listeners = UIActionTypeList.DeleteActionListener.class, confirm = "UIActionTypeList.msg.confirm-delete") } ) public class UIActionTypeList extends UIPagingGrid { private static String[] ACTIONTYPE_BEAN_FIELD = {"label", "name"} ; private static String[] ACTIONTYPE_ACTION = {"Edit", "Delete"} ; private static final Log LOG = ExoLogger.getLogger(UIActionTypeList.class); public UIActionTypeList() throws Exception { getUIPageIterator().setId("ActionTypeListIterator"); configure("type", ACTIONTYPE_BEAN_FIELD, ACTIONTYPE_ACTION) ; } public String[] getActions() { return new String[] {"AddAction"} ;} /* (non-Javadoc) * @see org.exoplatform.webui.core.UIComponent#processRender(org.exoplatform.webui.application.WebuiRequestContext) */ @Override public void processRender(WebuiRequestContext context) throws Exception { context.getJavascriptManager() .require("SHARED/jquery", "gj") .addScripts("gj(document).ready(function() { gj(\"*[rel='tooltip']\").tooltip();});"); super.processRender(context); } @Override public void refresh(int currentPage) throws Exception { ActionServiceContainer actionsServiceContainer = getApplicationComponent(ActionServiceContainer.class) ; String repository = getAncestorOfType(UIECMAdminPortlet.class).getPreferenceRepository() ; ScriptServiceImpl scriptService = WCMCoreUtils.getService(ScriptServiceImpl.class); Collection<NodeType> actionList = actionsServiceContainer.getCreatedActionTypes(repository) ; List<ActionData> actions = new ArrayList<ActionData>(actionList.size()) ; UIActionManager uiManager = getParent(); for(NodeType action : actionList) { ActionData bean = new ActionData(); String resourceName = scriptService.getResourceNameByNodeType(action); if(StringUtils.isEmpty(resourceName)) continue; bean.setLabel(uiManager.getScriptLabel(action)); if(resourceName.length() == 0) resourceName = action.getName(); bean.setType(action.getName()); bean.setName(StringUtils.substringAfterLast(resourceName, "/")) ; actions.add(bean) ; } Collections.sort(actions, new ActionComparator()) ; LazyPageList<ActionData> dataPageList = new LazyPageList<ActionData>(new ListAccessImpl<ActionData>(ActionData.class, actions), getUIPageIterator().getItemsPerPage()); getUIPageIterator().setTotalItems(actions.size()); getUIPageIterator().setPageList(dataPageList); if (currentPage > getUIPageIterator().getAvailablePage()) getUIPageIterator().setCurrentPage(getUIPageIterator().getAvailablePage()); else getUIPageIterator().setCurrentPage(currentPage); } static public class ActionComparator implements Comparator<ActionData> { public int compare(ActionData a1, ActionData a2) throws ClassCastException { String label1 = a1.getLabel(); String label2 = a2.getLabel(); return label1.compareToIgnoreCase(label2); } } static public class EditActionListener extends EventListener<UIActionTypeList> { public void execute(Event<UIActionTypeList> event) throws Exception { UIActionTypeList uiList = event.getSource(); UIActionManager uiActionMan = uiList.getParent() ; UIActionTypeForm uiForm = uiActionMan.findFirstComponentOfType(UIActionTypeForm.class) ; if (uiForm == null) uiForm = uiActionMan.createUIComponent(UIActionTypeForm.class, null, null) ; String name = event.getRequestContext().getRequestParameter(OBJECTID); NodeTypeManager ntManager = WCMCoreUtils.getRepository().getNodeTypeManager(); String label = uiActionMan.getScriptLabel(ntManager.getNodeType(name)); uiForm.update(name, label) ; uiActionMan.initPopup(uiForm, 600) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiActionMan) ; } } static public class DeleteActionListener extends EventListener<UIActionTypeList> { public void execute(Event<UIActionTypeList> event) throws Exception { UIActionTypeList uiList = event.getSource(); String nodeTypeName = event.getRequestContext().getRequestParameter(OBJECTID); UIActionManager uiActionMan = uiList.getParent() ; RepositoryService repoService = WCMCoreUtils.getService(RepositoryService.class); ExtendedNodeTypeManager ntManager = repoService.getCurrentRepository().getNodeTypeManager(); try { ntManager.unregisterNodeType(nodeTypeName); Utils.addEditedConfiguredData(nodeTypeName, "ActionTypeList", "EditedConfiguredActionType", true); } catch(Exception e) { UIApplication uiApp = event.getSource().getAncestorOfType(UIApplication.class) ; uiApp.addMessage(new ApplicationMessage("UIActionTypeList.msg.cannot-delete", null, ApplicationMessage.WARNING)) ; LOG.error("An error occurs while unregister node type "+nodeTypeName+"", e); return; } uiList.refresh(uiList.getUIPageIterator().getCurrentPage()); event.getRequestContext().addUIComponentToUpdateByAjax(uiActionMan) ; } } static public class AddActionActionListener extends EventListener<UIActionTypeList> { public void execute(Event<UIActionTypeList> event) throws Exception { UIActionManager uiActionMan = event.getSource().getParent() ; UIActionTypeForm uiForm = uiActionMan.findFirstComponentOfType(UIActionTypeForm.class) ; if (uiForm == null) uiForm = uiActionMan.createUIComponent(UIActionTypeForm.class, null, null) ; uiForm.refresh() ; uiActionMan.initPopup(uiForm, 600) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiActionMan) ; } } public static class ActionData { private String label ; private String name ; private String type; public String getName() { return name ; } public void setName(String s) { name = s ; } public String getLabel() { return label ; } public void setLabel(String s) { label = s ; } public String getType() { return type; } public void setType(String type) { this.type = type; } } }
8,776
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIActionManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/action/UIActionManager.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.action; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.PropertyDefinition; import org.apache.commons.lang3.StringUtils; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; import org.exoplatform.webui.ext.manager.UIAbstractManager; /** * Created by The eXo Platform SARL * Author : pham tuan * phamtuanchip@yahoo.de * September 20, 2006 * 16:37:15 AM */ @ComponentConfig( lifecycle = UIContainerLifecycle.class ) public class UIActionManager extends UIAbstractManager { public UIActionManager() throws Exception { addChild(UIActionTypeList.class, null, null) ; } public void refresh() throws Exception { UIActionTypeList list = getChild(UIActionTypeList.class) ; list.refresh(1); } public String getScriptLabel(NodeType nodeType) throws Exception { if(nodeType.isNodeType("exo:scriptAction")) { PropertyDefinition[] arrProperties = nodeType.getPropertyDefinitions(); for(PropertyDefinition property : arrProperties) { if(property.getName().equals("exo:scriptLabel")) { return property.getDefaultValues()[0].getString(); } } } return StringUtils.EMPTY; } public void initPopup(UIComponent uiActionForm, int width) throws Exception { UIPopupWindow uiPopup = getChild(UIPopupWindow.class) ; if(uiPopup == null) { uiPopup = addChild(UIPopupWindow.class, null, "ActionPopup") ; uiPopup.setUIComponent(uiActionForm) ; uiPopup.setWindowSize(width, 0) ; uiPopup.setShow(true) ; return ; } uiPopup.setRendered(true) ; uiPopup.setShow(true) ; uiPopup.setResizable(true) ; } }
2,580
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIActionTypeForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/action/UIActionTypeForm.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.action; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeManager; import javax.jcr.nodetype.PropertyDefinition; import javax.jcr.version.OnParentVersionAction; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.webui.form.validator.NodeTypeNameValidator; import org.exoplatform.services.cms.actions.ActionServiceContainer; import org.exoplatform.services.cms.scripts.impl.ScriptServiceImpl; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.web.application.ApplicationMessage; 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.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.UIFormMultiValueInputSet; import org.exoplatform.webui.form.UIFormSelectBox; import org.exoplatform.webui.form.UIFormStringInput; import org.exoplatform.webui.form.validator.MandatoryValidator; import com.ibm.icu.text.Transliterator; /** * Created by The eXo Platform SARL * Author : pham tuan * phamtuanchip@yahoo.de September 20, 2006 04:27:15 PM */ @ComponentConfig( lifecycle = UIFormLifecycle.class, template = "system:/groovy/webui/form/UIForm.gtmpl", events = { @EventConfig(listeners = UIActionTypeForm.SaveActionListener.class), @EventConfig(phase=Phase.DECODE, listeners = UIActionTypeForm.ChangeTypeActionListener.class), @EventConfig(phase=Phase.DECODE, listeners = UIActionTypeForm.CancelActionListener.class), @EventConfig(phase=Phase.DECODE, listeners = UIActionTypeForm.AddActionListener.class), @EventConfig(phase=Phase.DECODE, listeners = UIActionTypeForm.RemoveActionListener.class) } ) public class UIActionTypeForm extends UIForm { final static public String FIELD_SCRIPT = "script" ; final static public String FIELD_NAME = "name" ; final static public String FIELD_VARIABLES = "variables" ; public static final String ACTION_TYPE = "exo:scriptAction"; private String actionName_; private boolean isUpdate = false; public UIFormMultiValueInputSet uiFormMultiValue = null ; public UIActionTypeForm() throws Exception { addUIFormInput(new UIFormStringInput(FIELD_NAME, FIELD_NAME, null). addValidator(MandatoryValidator.class).addValidator(NodeTypeNameValidator.class)); UIFormSelectBox actionExecutables = new UIFormSelectBox(FIELD_SCRIPT,FIELD_SCRIPT, new ArrayList<SelectItemOption<String>>()); addUIFormInput(actionExecutables) ; setActions( new String[]{"Save", "Cancel"}) ; } private void initMultiValuesField() throws Exception { if( uiFormMultiValue != null ) removeChildById(FIELD_VARIABLES); uiFormMultiValue = createUIComponent(UIFormMultiValueInputSet.class, null, null) ; uiFormMultiValue.setId(FIELD_VARIABLES) ; uiFormMultiValue.setName(FIELD_VARIABLES) ; uiFormMultiValue.setType(UIFormStringInput.class) ; List<String> list = new ArrayList<String>() ; list.add(""); uiFormMultiValue.setValue(list) ; addUIFormInput(uiFormMultiValue) ; } private List<SelectItemOption<String>> getScriptOptions() throws Exception { List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ; ScriptServiceImpl scriptService = WCMCoreUtils.getService(ScriptServiceImpl.class); List<Node> scriptOptions = scriptService.getECMActionScripts(WCMCoreUtils.getSystemSessionProvider()); String baseScriptPath = scriptService.getBaseScriptPath(); for(Node script : scriptOptions) { SelectItemOption<String> itemOption = new SelectItemOption<String>(script.getName(), StringUtils.substringAfter(script.getPath(), baseScriptPath + "/")); options.add(itemOption); } return options ; } public void refresh() throws Exception{ reset() ; getUIStringInput(FIELD_NAME).setValue("") ; List<SelectItemOption<String>> scriptOptions = getScriptOptions() ; getUIFormSelectBox(FIELD_SCRIPT).setOptions(scriptOptions); initMultiValuesField() ; } public void update(String actionName, String actionLabel) throws Exception { isUpdate = true; ScriptServiceImpl scriptService = WCMCoreUtils.getService(ScriptServiceImpl.class); NodeTypeManager ntManager = WCMCoreUtils.getRepository().getNodeTypeManager(); NodeType nodeType = ntManager.getNodeType(actionName); actionName_ = actionName; String resourceName = scriptService.getResourceNameByNodeType(nodeType); getUIStringInput(FIELD_NAME).setValue(actionLabel); getUIFormSelectBox(FIELD_SCRIPT).setOptions(getScriptOptions()).setValue(resourceName); List<String> valueList = new ArrayList<String>(); PropertyDefinition[] proDefs = nodeType.getPropertyDefinitions(); for(PropertyDefinition pro : proDefs) { //Check if require type is STRING if(pro.isProtected() || pro.isAutoCreated() || pro.isMultiple() || pro.isMandatory()) continue; if(pro.getRequiredType() == 1 && pro.getOnParentVersion() == OnParentVersionAction.COPY) { valueList.add(pro.getName()); } } initMultiValuesField() ; uiFormMultiValue.setValue(valueList); } static public class ChangeTypeActionListener extends EventListener<UIActionTypeForm> { public void execute(Event<UIActionTypeForm> event) throws Exception { UIActionTypeForm uiForm = event.getSource() ; event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getParent()) ; } } @SuppressWarnings("unused") static public class SaveActionListener extends EventListener<UIActionTypeForm> { public void execute(Event<UIActionTypeForm> event) throws Exception { UIActionTypeForm uiForm = event.getSource() ; PortletRequestContext context = (PortletRequestContext) event.getRequestContext() ; String repository = WCMCoreUtils.getRepository().getConfiguration().getName() ; UIActionManager uiActionManager = uiForm.getAncestorOfType(UIActionManager.class) ; ActionServiceContainer actionServiceContainer = uiForm.getApplicationComponent(ActionServiceContainer.class) ; UIApplication uiApp = uiForm.getAncestorOfType(UIApplication.class) ; String actionLabel = uiForm.getUIStringInput(FIELD_NAME).getValue(); String actionName = "exo:" + cleanString(actionLabel); if(uiForm.isUpdate) actionName = uiForm.actionName_; List<String> variables = new ArrayList<String>(); List values = uiForm.uiFormMultiValue.getValue(); if(values != null && values.size() > 0) { for(Object value : values) { variables.add((String)value) ; } } if(!uiForm.isUpdate) { for(NodeType nodeType : actionServiceContainer.getCreatedActionTypes(repository)) { if(actionName.equals(nodeType.getName())) { uiApp.addMessage(new ApplicationMessage("UIActionTypeForm.msg.action-exist", null, ApplicationMessage.WARNING)) ; return ; } } } try { String script = uiForm.getUIFormSelectBox(FIELD_SCRIPT).getValue() ; actionServiceContainer.createActionType(actionName, ACTION_TYPE, script, actionLabel, variables, false, uiForm.isUpdate); uiActionManager.refresh() ; uiForm.refresh() ; uiActionManager.removeChild(UIPopupWindow.class) ; } catch(Exception e) { uiApp.addMessage(new ApplicationMessage("UIActionTypeForm.msg.action-type-create-error", new Object[] {actionLabel}, ApplicationMessage.WARNING)) ; return ; } event.getRequestContext().addUIComponentToUpdateByAjax(uiActionManager) ; } private String cleanString(String input){ Transliterator accentsconverter = Transliterator.getInstance("Latin; NFD; [:Nonspacing Mark:] Remove; NFC;"); input = accentsconverter.transliterate(input); return input.trim(); } } static public class CancelActionListener extends EventListener<UIActionTypeForm> { public void execute(Event<UIActionTypeForm> event) throws Exception { UIActionTypeForm uiForm = event.getSource(); uiForm.reset() ; UIActionManager uiActionManager = uiForm.getAncestorOfType(UIActionManager.class) ; uiActionManager.removeChild(UIPopupWindow.class) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiActionManager) ; } } static public class AddActionListener extends EventListener<UIActionTypeForm> { public void execute(Event<UIActionTypeForm> event) throws Exception { UIActionTypeForm uiForm = event.getSource(); event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getParent()) ; } } static public class RemoveActionListener extends EventListener<UIActionTypeForm> { public void execute(Event<UIActionTypeForm> event) throws Exception { UIActionTypeForm uiForm = event.getSource(); event.getRequestContext().addUIComponentToUpdateByAjax(uiForm.getParent()) ; } } }
10,332
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIECMAdminControlPanelActionListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/listener/UIECMAdminControlPanelActionListener.java
/* * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.listener; import java.util.HashMap; import java.util.Map; import org.exoplatform.ecm.webui.component.admin.UIECMAdminControlPanel; import org.exoplatform.ecm.webui.component.admin.UIECMAdminPortlet; import org.exoplatform.ecm.webui.component.admin.UIECMAdminWorkingArea; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.ext.UIExtensionEventListener; /** * Created by The eXo Platform SAS * Author : eXoPlatform * nicolas.filotto@exoplatform.com * 15 mai 2009 */ public abstract class UIECMAdminControlPanelActionListener<T extends UIComponent> extends UIExtensionEventListener<T> { /** * {@inheritDoc} */ @Override protected Map<String, Object> createContext(Event<T> event) throws Exception { Map<String, Object> context = new HashMap<String, Object>(); UIECMAdminPortlet portlet = event.getSource().getAncestorOfType(UIECMAdminPortlet.class); UIECMAdminWorkingArea uiWorkingArea = portlet.getChild(UIECMAdminWorkingArea.class); UIECMAdminControlPanel controlPanel = event.getSource().getAncestorOfType(UIECMAdminControlPanel.class); WebuiRequestContext requestContext = event.getRequestContext(); UIApplication uiApp = requestContext.getUIApplication(); context.put(UIECMAdminPortlet.class.getName(), portlet); context.put(UIECMAdminWorkingArea.class.getName(), uiWorkingArea); context.put(UIECMAdminControlPanel.class.getName(), controlPanel); context.put(UIApplication.class.getName(), uiApp); context.put(WebuiRequestContext.class.getName(), requestContext); return context; } /** * {@inheritDoc} */ @Override protected String getExtensionType() { return UIECMAdminControlPanel.EXTENSION_TYPE; } }
2,703
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIViewFormTabPane.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/views/UIViewFormTabPane.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.views; import java.util.ArrayList; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import org.apache.commons.lang3.StringUtils; import org.exoplatform.services.cms.views.ManageViewService; 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.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.ComponentConfigs; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.UITabPane; 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.UIFormInputBase; import javax.jcr.Node; /** * Created by The eXo Platform SARL * Author : Tran The Trong * trongtt@exoplatform.com * Sep 19, 2006 * 5:31:04 PM */ @ComponentConfigs({ @ComponentConfig( type = UIViewForm.class, lifecycle = UIFormLifecycle.class, template = "app:/groovy/webui/component/admin/view/UIForm.gtmpl", events = { @EventConfig(listeners = UIViewFormTabPane.SaveActionListener.class), @EventConfig(listeners = UIViewFormTabPane.RestoreActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIViewFormTabPane.CancelActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIViewFormTabPane.CloseActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIViewFormTabPane.SelectTabActionListener.class, phase = Phase.DECODE), @EventConfig(listeners = UIViewForm.ChangeVersionActionListener.class, phase = Phase.DECODE) }), @ComponentConfig( template = "app:/groovy/webui/component/admin/view/UIViewFormTabPane.gtmpl" ) }) public class UIViewFormTabPane extends UITabPane { private static final Log logger = ExoLogger.getLogger(UIViewFormTabPane.class.getName()); final static public String POPUP_PERMISSION = "PopupViewPermission" ; private String selectedTabId = "UITemplateContainer"; public static final String SAVE_BUTTON = "Save"; public static final String CANCEL_BUTTON = "Cancel"; public static final String RESTORE_BUTTON = "Restore"; private String[] actions_ = new String[] {SAVE_BUTTON, CANCEL_BUTTON}; private String primaryBtn_ = "Save"; private boolean isUpdate_ = false; public String getSelectedTabId() { return selectedTabId; } public void setSelectedTab(String renderTabId) { selectedTabId = renderTabId; } public void setSelectedTab(int index) { selectedTabId = getChild(index - 1).getId(); } public String[] getActions() { UITabList uiTabList = this.findFirstComponentOfType(UITabList.class); String viewName = uiTabList.getViewName(); if(StringUtils.isNotEmpty(viewName) && isUpdate() ) { try{ ManageViewService viewService = WCMCoreUtils.getService(ManageViewService.class); Node viewNode = viewService.getViewByName(viewName, WCMCoreUtils.getSystemSessionProvider()); if (viewNode.isNodeType(NodetypeConstant.MIX_VERSIONABLE)) actions_ = new String[]{SAVE_BUTTON, CANCEL_BUTTON, RESTORE_BUTTON}; }catch (Exception ex){ logger.error("View {0} does not exits", viewName); } } if(actions_.length == 1) primaryBtn_ = actions_[0]; return actions_; } public void setActions(String[] actions) { actions_ = actions; } public String getPrimaryButtonAction() { return primaryBtn_; } public void setPrimaryButtonAction(String primaryBtn) { primaryBtn_ = primaryBtn; } public UIViewFormTabPane() throws Exception { UIViewForm uiViewForm = addChild(UIViewForm.class, null, null) ; addChild(UITabContainer.class, null, null); addChild(UIViewPermissionContainer.class, null, null); setSelectedTab(uiViewForm.getId()) ; } public String getLabel(ResourceBundle res, String id) { try { return res.getString("UIViewForm.label." + id) ; } catch (MissingResourceException ex) { return id ; } } public void update(boolean isUpdate) { isUpdate_ = isUpdate; getChild(UIViewPermissionContainer.class).update(isUpdate); } public void view(boolean isView) { UITabContainer uiContainer = getChild(UITabContainer.class); uiContainer.getChild(UITabList.class).view(isView); getChild(UIViewPermissionContainer.class).view(isView); } public boolean isUpdate() { return isUpdate_; } static public class SaveActionListener extends EventListener<UIViewForm> { public void execute(Event<UIViewForm> event) throws Exception { UIViewFormTabPane uiViewTabPane = event.getSource().getParent(); UIViewContainer uiViewContainer = uiViewTabPane.getAncestorOfType(UIViewContainer.class) ; uiViewTabPane.getChild(UIViewForm.class).save() ; UIPopupWindow uiPopup = null; if(uiViewTabPane.isUpdate()) { uiPopup = uiViewContainer.getChildById(UIViewList.ST_EDIT); } else { uiPopup = uiViewContainer.getChildById(UIViewList.ST_ADD); } uiPopup.setShow(false); uiPopup.setRendered(false); event.getRequestContext().addUIComponentToUpdateByAjax(uiViewContainer) ; } } static public class CancelActionListener extends EventListener<UIViewForm> { public void execute(Event<UIViewForm> event) throws Exception { UIViewFormTabPane uiViewTabPane = event.getSource().getParent(); UIViewContainer uiViewContainer = uiViewTabPane.getAncestorOfType(UIViewContainer.class) ; UIPopupWindow uiPopup = null; if(uiViewTabPane.isUpdate()) { uiPopup = uiViewContainer.getChildById(UIViewList.ST_EDIT); } else { uiPopup = uiViewContainer.getChildById(UIViewList.ST_ADD); } uiPopup.setShow(false); uiPopup.setRendered(false); event.getRequestContext().addUIComponentToUpdateByAjax(uiViewContainer) ; } } static public class CloseActionListener extends EventListener<UIViewForm> { public void execute(Event<UIViewForm> event) throws Exception { UIViewFormTabPane uiViewTabPane = event.getSource().getParent(); UIViewContainer uiViewContainer = uiViewTabPane.getAncestorOfType(UIViewContainer.class) ; UIPopupWindow uiPopup = uiViewContainer.getChildById(UIViewList.ST_VIEW);; uiPopup.setShow(false); uiPopup.setRendered(false); event.getRequestContext().addUIComponentToUpdateByAjax(uiViewContainer) ; } } static public class RestoreActionListener extends EventListener<UIViewForm> { public void execute(Event<UIViewForm> event) throws Exception { UIViewFormTabPane uiViewTabPane = event.getSource().getParent(); UIViewForm uiViewForm = uiViewTabPane.getChild(UIViewForm.class) ; uiViewForm.changeVersion() ; UIViewContainer uiContainer = uiViewTabPane.getAncestorOfType(UIViewContainer.class) ; UIViewList uiViewList = uiContainer.findFirstComponentOfType(UIViewList.class) ; uiViewList.refresh(uiViewList.getUIPageIterator().getCurrentPage()); uiViewForm.refresh(true) ; uiViewTabPane.removeChildById(POPUP_PERMISSION) ; UIViewContainer uiViewContainer = uiViewTabPane.getAncestorOfType(UIViewContainer.class) ; uiViewContainer.removeChild(UIPopupWindow.class) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiViewContainer) ; } } static public class SelectTabActionListener extends EventListener<UIViewFormTabPane> { public void execute(Event<UIViewFormTabPane> event) throws Exception { WebuiRequestContext context = event.getRequestContext(); String renderTab = context.getRequestParameter(UIComponent.OBJECTID); if (renderTab == null) return; event.getSource().setSelectedTab(renderTab); WebuiRequestContext parentContext = (WebuiRequestContext)context.getParentAppRequestContext(); if (parentContext != null) { parentContext.setResponseComplete(true); } else { context.setResponseComplete(true); } } } public void processDecode(WebuiRequestContext context) throws Exception { List<UIFormInputBase> inputs = new ArrayList<UIFormInputBase>(); this.findComponentOfType(inputs, UIFormInputBase.class); String action = context.getRequestParameter(UIForm.ACTION); for (UIFormInputBase input : inputs) { if (!input.isValid()) { continue; } String inputValue = context.getRequestParameter(input.getId()); if (inputValue == null || inputValue.trim().length() == 0) { inputValue = context.getRequestParameter(input.getName()); } input.decode(inputValue, context); } Event<UIComponent> event = this.createEvent(action, Event.Phase.DECODE, context); if (event != null) { event.broadcast(); } } public String event(String name) throws Exception { StringBuilder b = new StringBuilder(); b.append("javascript:eXo.webui.UIForm.submitForm('").append("UIViewForm").append("','"); b.append(name).append("',true)"); return b.toString(); } }
10,555
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIViewPermissionList.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/views/UIViewPermissionList.java
/*************************************************************************** * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. * **************************************************************************/ package org.exoplatform.ecm.webui.component.admin.views; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; 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.core.UIPagingGrid; import org.exoplatform.services.cms.views.ManageViewService; 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.UIApplication; 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 * Feb 19, 2013 * 4:26:03 PM */ @ComponentConfig( template = "system:/groovy/ecm/webui/UIGridWithButton.gtmpl", events = { @EventConfig(listeners = UIViewPermissionList.DeleteActionListener.class, confirm = "UIViewPermissionList.msg.confirm-delete") } ) public class UIViewPermissionList extends UIPagingGrid { public static String[] PERMISSION_BEAN_FIELD = {"friendlyPermission"} ; private String viewName; public UIViewPermissionList() throws Exception { getUIPageIterator().setId("PermissionListPageIterator") ; configure("permission", UIViewPermissionList.PERMISSION_BEAN_FIELD, new String[] {"Delete"}); } public String[] getActions() { return new String[] {} ;} public String getViewName() { return viewName; } public void setViewName(String name) { viewName = name; } @Override public void refresh(int currentPage) throws Exception { UIViewPermissionContainer uiPerContainer = getParent(); UIViewFormTabPane uiTabPane = uiPerContainer.getParent(); UIViewForm uiViewForm = uiTabPane.getChild(UIViewForm.class); List<PermissionBean> permissions = new ArrayList<PermissionBean>(); if(uiPerContainer.isView()) { ManageViewService viewService = WCMCoreUtils.getService(ManageViewService.class); Node viewNode = viewService.getViewByName(viewName, WCMCoreUtils.getSystemSessionProvider()); String strPermission = viewNode.getProperty("exo:accessPermissions").getString(); permissions = getBeanList(strPermission); } else { permissions = getBeanList(uiViewForm.getPermission()); } Collections.sort(permissions, new ViewPermissionComparator()); ListAccess<PermissionBean> permissionBeanList = new ListAccessImpl<PermissionBean>(PermissionBean.class, permissions); getUIPageIterator().setPageList(new LazyPageList<PermissionBean>(permissionBeanList, getUIPageIterator().getItemsPerPage())); getUIPageIterator().setTotalItems(permissions.size()); if (currentPage > getUIPageIterator().getAvailablePage()) { getUIPageIterator().setCurrentPage(getUIPageIterator().getAvailablePage()); } else { getUIPageIterator().setCurrentPage(currentPage); } } static public class DeleteActionListener extends EventListener<UIViewPermissionList> { public void execute(Event<UIViewPermissionList> event) throws Exception { UIViewPermissionList uiPermissionList = event.getSource(); UIViewPermissionContainer uiContainer = uiPermissionList.getParent(); UIViewFormTabPane uiTabPane = uiContainer.getParent(); UIViewForm uiViewForm = uiTabPane.getChild(UIViewForm.class); String permission = event.getRequestContext().getRequestParameter(OBJECTID); String permissions = uiPermissionList.removePermission(permission, uiViewForm.getPermission()); if(permissions.length() == 0) { UIApplication uiApp = uiPermissionList.getAncestorOfType(UIApplication.class); uiApp.addMessage(new ApplicationMessage("UIViewPermissionList.msg.permission-cannot-empty", null, ApplicationMessage.WARNING)); event.getRequestContext().addUIComponentToUpdateByAjax(uiContainer); uiTabPane.setSelectedTab(uiContainer.getId()); return; } uiViewForm.setPermission(permissions); uiPermissionList.refresh(uiPermissionList.getUIPageIterator().getCurrentPage()); event.getRequestContext().addUIComponentToUpdateByAjax(uiPermissionList.getParent()); } } static public class ViewPermissionComparator implements Comparator<PermissionBean> { public int compare(PermissionBean t1, PermissionBean t2) throws ClassCastException { String per1 = t1.getPermission(); String per2 = t2.getPermission(); return per1.compareToIgnoreCase(per2); } } public static class PermissionBean { private String permssion ; private String friendlyPermission; public PermissionBean() {} public String getPermission(){ return this.permssion ; } public void setPermission( String permission) { this.permssion = permission ; } public String getFriendlyPermission() { return friendlyPermission; } public void setFriendlyPermission(String friendlyPer) { this.friendlyPermission = friendlyPer; } } private String removePermission(String removePermission, String permissions) { StringBuilder perBuilder = new StringBuilder(); if(permissions.indexOf(",") > -1) { String[] arrPer = permissions.split(","); for(String per : arrPer) { if(per.equals(removePermission)) continue; if(perBuilder.length() > 0) perBuilder.append(","); perBuilder.append(per); } } return perBuilder.toString(); } private List<PermissionBean> getBeanList(String permissions) throws Exception { UIViewContainer uiContainer = getAncestorOfType(UIViewContainer.class); List<PermissionBean> listBean = new ArrayList<PermissionBean>(); String[] arrPers = new String[] {}; if(permissions.contains(",")) { arrPers = permissions.split(","); } else if(permissions.length() > 0) { arrPers = new String[] {permissions}; } for(String per : arrPers) { PermissionBean bean = new PermissionBean(); bean.setPermission(per); bean.setFriendlyPermission(uiContainer.getFriendlyPermission(per)); listBean.add(bean); } return listBean; } }
7,311
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIViewList.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/views/UIViewList.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.views; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.jcr.Node; import org.exoplatform.commons.utils.LazyPageList; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.commons.utils.ListAccessImpl; import org.exoplatform.ecm.permission.info.UIPermissionInputSet; import org.exoplatform.ecm.webui.component.admin.UIECMAdminPortlet; import org.exoplatform.ecm.webui.core.UIPagingGrid; 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.views.ManageViewService; import org.exoplatform.services.cms.views.ViewConfig; import org.exoplatform.services.cms.views.impl.ManageViewPlugin; 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.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.input.UICheckBoxInput; /** * Created by The eXo Platform SARL * Author : Tran The Trong * trongtt@exoplatform.com * Sep 19, 2006 * 11:45:11 AM */ @ComponentConfig( template = "system:/groovy/ecm/webui/UIGridWithButton.gtmpl", events = { @EventConfig(listeners = UIViewList.DeleteActionListener.class, confirm = "UIViewList.msg.confirm-delete"), @EventConfig(listeners = UIViewList.EditInfoActionListener.class), @EventConfig(listeners = UIViewList.ViewActionListener.class), @EventConfig(listeners = UIViewList.AddViewActionListener.class) } ) public class UIViewList extends UIPagingGrid { final static public String[] ACTIONS = { "AddView" }; final static public String ST_VIEW = "ViewPopup"; final static public String ST_EDIT = "EditPopup"; final static public String ST_ADD = "AddPopup"; private static String[] VIEW_BEAN_FIELD = { "name", "permissions", "tabList", "baseVersion" }; private static String[] VIEW_ACTION = { "View", "EditInfo", "Delete" }; public UIViewList() throws Exception { getUIPageIterator().setId("UIViewsGrid") ; configure("id", VIEW_BEAN_FIELD, VIEW_ACTION) ; } private String getBaseVersion(String name) throws Exception { Node node = getApplicationComponent(ManageViewService.class).getViewByName(name, WCMCoreUtils.getSystemSessionProvider()); if(node == null) return null ; if(!node.isNodeType(Utils.MIX_VERSIONABLE) || node.isNodeType(Utils.NT_FROZEN)) return ""; return node.getBaseVersion().getName(); } public String[] getActions() { return ACTIONS ; } public void refresh(int currentPage) throws Exception { List<ViewBean> viewBean = getViewsBean(); Collections.sort(viewBean, new ViewComparator()); ListAccess<ViewBean> viewBeanList = new ListAccessImpl<ViewBean>(ViewBean.class, viewBean); getUIPageIterator().setPageList(new LazyPageList<ViewBean>(viewBeanList, getUIPageIterator().getItemsPerPage())); getUIPageIterator().setTotalItems(viewBean.size()); if (currentPage > getUIPageIterator().getAvailablePage()) getUIPageIterator().setCurrentPage(getUIPageIterator().getAvailablePage()); else getUIPageIterator().setCurrentPage(currentPage); } private List<ViewBean> getViewsBean() throws Exception { List<ViewConfig> views = getApplicationComponent(ManageViewService.class).getAllViews(); List<ViewBean> viewBeans = new ArrayList<ViewBean>(); for (ViewConfig view : views) { List<String> tabsName = new ArrayList<String>(); for (ViewConfig.Tab tab : view.getTabList()) { tabsName.add(tab.getTabName()); } ViewBean bean = new ViewBean(view.getName(), getFriendlyViewPermission(view.getPermissions()), tabsName); if (getBaseVersion(view.getName()) == null) continue; bean.setBaseVersion(getBaseVersion(view.getName())); viewBeans.add(bean); } return viewBeans; } static public class ViewComparator implements Comparator<ViewBean> { public int compare(ViewBean v1, ViewBean v2) throws ClassCastException { String name1 = v1.getName(); String name2 = v2.getName(); return name1.compareToIgnoreCase(name2); } } public boolean canDelete(List<DriveData> drivers, String viewName) { for(DriveData driver : drivers){ String views = driver.getViews() ; for(String view: views.split(",")){ if(viewName.equals(view.trim())) return false ; } } return true ; } public String getRepository() { return getAncestorOfType(UIECMAdminPortlet.class).getPreferenceRepository() ; } static public class AddViewActionListener extends EventListener<UIViewList> { public void execute(Event<UIViewList> event) throws Exception { UIViewList uiViewList = event.getSource() ; if(uiViewList.getViewsBean().size() == 0) { UIApplication uiApp = event.getSource().getAncestorOfType(UIApplication.class) ; uiApp.addMessage(new ApplicationMessage("UIViewList.msg.access-denied", null, ApplicationMessage.WARNING)) ; return ; } UIViewContainer uiViewContainer = uiViewList.getParent() ; uiViewContainer.removeChildById(UIViewList.ST_VIEW) ; uiViewContainer.removeChildById(UIViewList.ST_EDIT) ; UIViewFormTabPane uiTabPane = uiViewContainer.createUIComponent(UIViewFormTabPane.class, null, null) ; uiTabPane.update(false); UIViewPermissionForm uiPermissionForm = uiTabPane.findFirstComponentOfType(UIViewPermissionForm.class); UIPermissionInputSet uiPermissionInputSet = uiPermissionForm.getChildById(UIViewPermissionForm.TAB_PERMISSION); for(UIComponent uiComp : uiPermissionInputSet.getChildren()) { if(uiComp instanceof UICheckBoxInput) { uiPermissionInputSet.removeChildById(uiComp.getId()); } } uiViewContainer.initPopup(UIViewList.ST_ADD, uiTabPane) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiViewContainer) ; } } static public class DeleteActionListener extends EventListener<UIViewList> { public void execute(Event<UIViewList> event) throws Exception { UIViewList viewList = event.getSource(); viewList.setRenderSibling(UIViewList.class); String viewName = event.getRequestContext().getRequestParameter(OBJECTID) ; ManageDriveService manageDrive = viewList.getApplicationComponent(ManageDriveService.class); ManageViewService manageViewService = viewList.getApplicationComponent(ManageViewService.class); if(!viewList.canDelete(manageDrive.getAllDrives(), viewName)) { // Get view display name ResourceBundle res = RequestContext.getCurrentInstance().getApplicationResourceBundle(); String viewDisplayName = null; try { viewDisplayName = res.getString("Views.label." + viewName); } catch (MissingResourceException e) { viewDisplayName = viewName; } // Dis play error message UIApplication app = viewList.getAncestorOfType(UIApplication.class); Object[] args = {viewDisplayName}; app.addMessage(new ApplicationMessage("UIViewList.msg.template-in-use", args)); event.getRequestContext().addUIComponentToUpdateByAjax(viewList.getParent()); return; } manageViewService.removeView(viewName); org.exoplatform.services.cms.impl.Utils.addEditedConfiguredData(viewName, ManageViewPlugin.class.getSimpleName(), ManageViewPlugin.EDITED_CONFIGURED_VIEWS, true); viewList.refresh(viewList.getUIPageIterator().getCurrentPage()); event.getRequestContext().addUIComponentToUpdateByAjax(viewList.getParent()); } } static public class EditInfoActionListener extends EventListener<UIViewList> { public void execute(Event<UIViewList> event) throws Exception { UIViewList uiViewList = event.getSource() ; uiViewList.setRenderSibling(UIViewList.class) ; String viewName = event.getRequestContext().getRequestParameter(OBJECTID) ; Node viewNode = uiViewList.getApplicationComponent(ManageViewService.class). getViewByName(viewName, WCMCoreUtils.getSystemSessionProvider()) ; UIViewContainer uiViewContainer = uiViewList.getParent() ; uiViewContainer.removeChildById(UIViewList.ST_VIEW) ; uiViewContainer.removeChildById(UIViewList.ST_ADD) ; UIViewFormTabPane viewTabPane = uiViewContainer.createUIComponent(UIViewFormTabPane.class, null, null) ; viewTabPane.update(true); UIViewForm viewForm = viewTabPane.getChild(UIViewForm.class) ; viewForm.refresh(true) ; viewForm.update(viewNode, false, null) ; if(viewForm.getUICheckBoxInput(UIViewForm.FIELD_ENABLEVERSION).isChecked()) { viewForm.getUICheckBoxInput(UIViewForm.FIELD_ENABLEVERSION).setDisabled(true); } else { viewForm.getUICheckBoxInput(UIViewForm.FIELD_ENABLEVERSION).setDisabled(false); } UIViewPermissionList uiPerList = viewTabPane.findFirstComponentOfType(UIViewPermissionList.class); uiPerList.setViewName(viewName); UIViewPermissionForm uiPermissionForm = viewTabPane.findFirstComponentOfType(UIViewPermissionForm.class); UIPermissionInputSet uiPermissionInputSet = uiPermissionForm.getChildById(UIViewPermissionForm.TAB_PERMISSION); for(UIComponent uiComp : uiPermissionInputSet.getChildren()) { if(uiComp instanceof UICheckBoxInput) { uiPermissionInputSet.removeChildById(uiComp.getId()); } } uiViewContainer.initPopup(UIViewList.ST_EDIT, viewTabPane) ; uiPerList.refresh(uiPerList.getUIPageIterator().getCurrentPage()); UITabContainer uiTabContainer = viewTabPane.getChild(UITabContainer.class); UITabList uiTab = uiTabContainer.getChild(UITabList.class); uiTab.setViewName(viewName); uiTab.refresh(uiTab.getUIPageIterator().getCurrentPage()); event.getRequestContext().addUIComponentToUpdateByAjax(uiViewContainer) ; } } static public class ViewActionListener extends EventListener<UIViewList> { public void execute(Event<UIViewList> event) throws Exception { UIViewList uiViewList = event.getSource() ; uiViewList.setRenderSibling(UIViewList.class) ; String viewName = event.getRequestContext().getRequestParameter(OBJECTID) ; Node viewNode = uiViewList.getApplicationComponent(ManageViewService.class).getViewByName( viewName, WCMCoreUtils.getSystemSessionProvider()) ; UIViewContainer uiViewContainer = uiViewList.getParent() ; uiViewContainer.removeChildById(UIViewList.ST_EDIT) ; uiViewContainer.removeChildById(UIViewList.ST_ADD) ; UIViewFormTabPane viewTabPane = uiViewContainer.createUIComponent(UIViewFormTabPane.class, null, null) ; viewTabPane.update(false); viewTabPane.view(true); UIViewPermissionList uiPerList = viewTabPane.findFirstComponentOfType(UIViewPermissionList.class); uiPerList.configure("permission", UIViewPermissionList.PERMISSION_BEAN_FIELD, null); uiPerList.setViewName(viewName); UIViewPermissionContainer uiPerContainer = uiPerList.getParent(); uiPerContainer.setRenderedChild(UIViewPermissionList.class); uiViewContainer.initPopup(UIViewList.ST_VIEW, viewTabPane) ; uiPerList.refresh(uiPerList.getUIPageIterator().getCurrentPage()); UITabContainer uiTabContainer = viewTabPane.getChild(UITabContainer.class); UITabList uiTab = uiTabContainer.getChild(UITabList.class); uiTab.setViewName(viewName); uiTab.setActions(new String[] {}); uiTab.configure("tabName", UITabList.TAB_BEAN_FIELD, null) ; uiTab.refresh(uiTab.getUIPageIterator().getCurrentPage()); UIViewForm uiViewForm = viewTabPane.getChild(UIViewForm.class) ; uiViewForm.refresh(false) ; uiViewForm.update(viewNode, true, null) ; viewTabPane.setActions(new String[] {"Close"}); event.getRequestContext().addUIComponentToUpdateByAjax(uiViewContainer) ; } } public class ViewBean { private String id; private String name ; private String permissions ; private String tabList ; private String baseVersion = ""; public ViewBean(String n, String per, List<String> tabs) { id = n; name = n ; permissions = per ; StringBuilder str = new StringBuilder() ; for(int i = 0; i < tabs.size(); i++) { str.append(" [").append(tabs.get(i)).append("]"); } tabList = str.toString() ; } public String getBaseVersion() { return baseVersion; } public void setBaseVersion(String s) { baseVersion = s; } public String getName() { ResourceBundle res = RequestContext.getCurrentInstance().getApplicationResourceBundle(); String label = null; try { label = res.getString("Views.label." + name); } catch (MissingResourceException e) { label = name; } return label; } public void setName(String s) { name = s; } public String getPermissions() { return permissions; } public void setPermissions(String s) { permissions = s; } public String getTabList() { return tabList; } public void setTabList(String ls) { tabList = ls; } public String getId() { return id; } } private String getFriendlyViewPermission(String permissions) throws Exception { UIViewContainer uiViewContainer = getParent() ; String[] arrPers = new String[] {}; if(permissions.contains(",")) { arrPers = permissions.split(","); } else if(permissions.length() > 0){ arrPers = new String[] {permissions}; } StringBuilder perBuilder = new StringBuilder(); for(String per : arrPers) { if(perBuilder.length() > 0) perBuilder.append(", "); perBuilder.append(uiViewContainer.getFriendlyPermission(per)); } return perBuilder.toString(); } }
15,520
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UITabForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/views/UITabForm.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.views; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.webui.form.validator.ECMNameValidator; import org.exoplatform.services.cms.views.ManageViewService; import org.exoplatform.services.cms.views.ViewConfig.Tab; import org.exoplatform.services.jcr.util.Text; import org.exoplatform.webui.form.validator.MandatoryValidator; 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.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; import org.exoplatform.webui.form.input.UICheckBoxInput; /** * Created by The eXo Platform SARL * Author : Tran The Trong * trongtt@gmail.com * Jun 28, 2006 */ @ComponentConfig( template = "app:/groovy/webui/component/admin/view/UITabForm.gtmpl", lifecycle = UIFormLifecycle.class, events = { @EventConfig(listeners = UITabForm.SaveActionListener.class), @EventConfig(listeners = UITabForm.CancelActionListener.class, phase = Phase.DECODE) } ) public class UITabForm extends UIForm { final static public String FIELD_NAME = "tabName" ; private List<?> buttons_ ; public UITabForm() throws Exception { setComponentConfig(getClass(), null) ; addUIFormInput(new UIFormStringInput(FIELD_NAME, FIELD_NAME, null).addValidator(MandatoryValidator.class) .addValidator(ECMNameValidator.class)) ; ManageViewService vservice_ = getApplicationComponent(ManageViewService.class) ; buttons_ = vservice_.getButtons(); for(Object bt : buttons_) { addUIFormInput(new UICheckBoxInput(getButtonName(bt), "", null)) ; } } private String getButtonName(Object bt) { String button = (String) bt; return button.substring(0, 1).toLowerCase() + button.substring(1); } public void processRender(WebuiRequestContext context) throws Exception { super.processRender(context) ; } public void refresh(boolean isEditable) throws Exception { getUIStringInput(FIELD_NAME).setDisabled(!isEditable).setValue(null) ; for(Object bt : buttons_){ getUICheckBoxInput(getButtonName(bt)).setChecked(false).setDisabled(!isEditable) ; } } public void update(Tab tab, boolean isView) throws Exception{ refresh(!isView) ; if(tab == null) return ; getUIStringInput(FIELD_NAME).setDisabled(true).setValue(Text.unescapeIllegalJcrChars(tab.getTabName())); String buttonsProperty = tab.getButtons() ; String[] buttonArray = StringUtils.split(buttonsProperty, ";") ; for(String bt : buttonArray){ UICheckBoxInput cbInput = getUICheckBoxInput(bt.trim()) ; if(cbInput != null) cbInput.setChecked(true) ; } } static public class SaveActionListener extends EventListener<UITabForm> { public void execute(Event<UITabForm> event) throws Exception { UITabForm uiTabForm = event.getSource(); UITabContainer uiContainer = uiTabForm.getAncestorOfType(UITabContainer.class); UIViewFormTabPane viewFormTabPane = uiContainer.getParent(); String tabName = uiTabForm.getUIStringInput(FIELD_NAME).getValue() ; UIApplication uiApp = event.getSource().getAncestorOfType(UIApplication.class) ; if(tabName == null || tabName.trim().length() == 0) { viewFormTabPane.setSelectedTab(uiTabForm.getId()) ; uiApp.addMessage(new ApplicationMessage("UITabForm.msg.tab-name-error", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiTabForm); return ; } StringBuilder selectedButton = new StringBuilder() ; boolean isSelected = false ; for(Object bt : uiTabForm.buttons_ ) { String button = uiTabForm.getButtonName(bt) ; if(uiTabForm.getUICheckBoxInput(button).isChecked()) { isSelected = true ; if(selectedButton.length() > 0) selectedButton.append(";").append(button) ; else selectedButton.append(button) ; } } if(!isSelected) { viewFormTabPane.setSelectedTab(uiTabForm.getId()); uiApp.addMessage(new ApplicationMessage("UITabForm.msg.button-select-error", null, ApplicationMessage.WARNING)); event.getRequestContext().addUIComponentToUpdateByAjax(uiTabForm); return; } UIViewForm uiViewForm = viewFormTabPane.getChild(UIViewForm.class); uiViewForm.addTab(tabName, selectedButton.toString()); UIPopupWindow uiPopup = uiContainer.getChildById(UITabList.TAPFORM_POPUP); uiPopup.setShow(false); uiPopup.setRendered(false); viewFormTabPane.setSelectedTab(viewFormTabPane.getSelectedTabId()) ; UITabList uiTabList = uiContainer.getChild(UITabList.class); uiTabList.refresh(uiTabList.getUIPageIterator().getCurrentPage()); event.getRequestContext().addUIComponentToUpdateByAjax(uiContainer); } } static public class CancelActionListener extends EventListener<UITabForm> { public void execute(Event<UITabForm> event) throws Exception { UITabForm uiTabForm = event.getSource(); UITabContainer uiContainer = uiTabForm.getAncestorOfType(UITabContainer.class); UIViewFormTabPane uiTabPane = uiContainer.getParent(); UIPopupWindow uiPopup = uiContainer.getChildById(UITabList.TAPFORM_POPUP); uiPopup.setShow(false); uiPopup.setRendered(false); uiTabPane.setSelectedTab(uiContainer.getId()); event.getRequestContext().addUIComponentToUpdateByAjax(uiContainer); } } }
6,740
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TemplateBean.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/views/TemplateBean.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.views; import java.util.MissingResourceException; import java.util.ResourceBundle; import org.exoplatform.web.application.RequestContext; /** * Created by The eXo Platform SARL * Author : Tran The Trong * trongtt@gmail.com * Oct 9, 2006 * 2:36:06 PM */ public class TemplateBean { private String name ; private String path ; public TemplateBean(String n, String p) { name = n ; path = p ; } public String getName() { ResourceBundle res = RequestContext.getCurrentInstance().getApplicationResourceBundle(); String label = null; try { label = res.getString("UIViewFormTabPane.label.option." + name); } catch (MissingResourceException e) { label = name; } return label; } public void setName(String n) { name = n ; } public String getPath() { return path ; } public void setPath(String p) { path = p ; } }
1,664
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UITabList.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/views/UITabList.java
/*************************************************************************** * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. * **************************************************************************/ package org.exoplatform.ecm.webui.component.admin.views; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import org.exoplatform.commons.utils.LazyPageList; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.commons.utils.ListAccessImpl; import org.exoplatform.ecm.webui.core.UIPagingGrid; import org.exoplatform.services.cms.views.ManageViewService; import org.exoplatform.services.cms.views.ViewConfig.Tab; 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.event.Event; import org.exoplatform.webui.event.EventListener; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Feb 18, 2013 * 12:15:50 PM */ @ComponentConfig( template = "system:/groovy/ecm/webui/UIGridWithButton.gtmpl", events = { @EventConfig(listeners = UITabList.DeleteActionListener.class, confirm = "UITabList.msg.confirm-delete"), @EventConfig(listeners = UITabList.EditActionListener.class), @EventConfig(listeners = UITabList.AddTabActionListener.class) } ) public class UITabList extends UIPagingGrid { final static public String TAPFORM_POPUP = "TabForm_Popup"; public static String[] TAB_BEAN_FIELD = {"tabName", "localizeButtons"} ; public static String TAB_LIST = "ECMTabList" ; private String[] actions_ = new String[] {"AddTab"}; private boolean isView_ = false; private String viewName; public UITabList() throws Exception { getUIPageIterator().setId("TabListPageIterator") ; configure("tabName", UITabList.TAB_BEAN_FIELD, new String[] {"Edit","Delete"}) ; } public String[] getActions() { return actions_; } public void setActions(String[] actions) { actions_ = actions; } public boolean isView() { return isView_; } public void view(boolean isView) { isView_ = isView; } @Override public void refresh(int currentPage) throws Exception { List<Tab> tabList = new ArrayList<Tab>(); UITabContainer uiTabContainer = getParent(); UIViewFormTabPane uiTabPane = uiTabContainer.getParent(); UIViewForm uiViewForm = uiTabPane.getChild(UIViewForm.class); if(isView_) { ManageViewService viewService = WCMCoreUtils.getService(ManageViewService.class); Node viewNode = viewService.getViewByName(viewName, WCMCoreUtils.getSystemSessionProvider()); NodeIterator nodeIter = viewNode.getNodes(); while(nodeIter.hasNext()) { Node tabNode = nodeIter.nextNode(); Tab tab = new Tab(); tab.setTabName(tabNode.getName()); tab.setButtons(tabNode.getProperty("exo:buttons").getValue().getString()); tab.setLocalizeButtons(uiViewForm.getLocalizationButtons(tabNode.getProperty("exo:buttons").getValue().getString())); tabList.add(tab); } } else { tabList = uiViewForm.getTabs(); } Collections.sort(tabList, new TabComparator()); ListAccess<Tab> tabBeanList = new ListAccessImpl<Tab>(Tab.class, tabList); getUIPageIterator().setPageList(new LazyPageList<Tab>(tabBeanList, getUIPageIterator().getItemsPerPage())); getUIPageIterator().setTotalItems(tabList.size()); if (currentPage > getUIPageIterator().getAvailablePage()) { getUIPageIterator().setCurrentPage(getUIPageIterator().getAvailablePage()); } else { getUIPageIterator().setCurrentPage(currentPage); } } public String getViewName() { return viewName; } public void setViewName(String name) { viewName = name; } static public class AddTabActionListener extends EventListener<UITabList> { public void execute(Event<UITabList> event) throws Exception { UITabList uiTabList = event.getSource(); UITabContainer uiContainer = uiTabList.getParent(); UITabForm uiTabForm = uiContainer.createUIComponent(UITabForm.class, null, null); uiContainer.initPopup(UITabList.TAPFORM_POPUP, uiTabForm, 760, 0); UIViewFormTabPane uiTabPane = uiContainer.getParent(); uiTabPane.setSelectedTab(uiContainer.getId()); event.getRequestContext().addUIComponentToUpdateByAjax(uiContainer); } } static public class DeleteActionListener extends EventListener<UITabList> { public void execute(Event<UITabList> event) throws Exception { UITabList uiTabList = event.getSource(); String tabName = event.getRequestContext().getRequestParameter(OBJECTID); UITabContainer uiTabContainer = uiTabList.getParent(); UIViewFormTabPane uiTabPane = uiTabContainer.getParent(); UIViewForm uiViewForm = uiTabPane.getChild(UIViewForm.class); uiViewForm.getTabMap().remove(tabName); uiTabList.refresh(uiTabList.getUIPageIterator().getCurrentPage()); uiTabPane.setSelectedTab(uiTabList.getId()); event.getRequestContext().addUIComponentToUpdateByAjax(uiTabList.getParent()); } } static public class EditActionListener extends EventListener<UITabList> { public void execute(Event<UITabList> event) throws Exception { UITabList uiTabList = event.getSource(); UITabContainer uiContainer = uiTabList.getParent(); String tabName = event.getRequestContext().getRequestParameter(OBJECTID); UIViewFormTabPane uiTabPane = uiContainer.getParent(); UIViewForm uiViewForm = uiTabPane.getChild(UIViewForm.class); Tab tab = uiViewForm.getTabMap().get(tabName); UITabForm uiTabForm = uiContainer.createUIComponent(UITabForm.class, null, null); uiTabForm.update(tab, false); uiContainer.initPopup(UITabList.TAPFORM_POPUP, uiTabForm, 760, 0); uiTabPane.setSelectedTab(uiTabList.getId()); event.getRequestContext().addUIComponentToUpdateByAjax(uiContainer); } } static public class TabComparator implements Comparator<Tab> { public int compare(Tab o1, Tab o2) throws ClassCastException { String name1 = o1.getTabName(); String name2 = o2.getTabName(); return name1.compareToIgnoreCase(name2); } } }
7,143
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIViewManager.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/views/UIViewManager.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.views; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.ext.manager.UIAbstractManager; /** * Created by The eXo Platform SARL * Author : Tran The Trong * trongtt@exoplatform.com * Sep 25, 2006 * 11:45:11 AM */ @ComponentConfig(template = "system:/groovy/webui/core/UITabPane_New.gtmpl", events = { @EventConfig(listeners = UIViewManager.SelectTabActionListener.class) }) public class UIViewManager extends UIAbstractManager { private String selectedTabId = ""; public String getSelectedTabId() { return selectedTabId; } public void setSelectedTab(String renderTabId) { selectedTabId = renderTabId; } public void setSelectedTab(int index) { selectedTabId = getChild(index - 1).getId(); } public UIViewManager() throws Exception{ addChild(UIViewContainer.class, null, null); UITemplateContainer uiECMTemp = addChild(UITemplateContainer.class, null, "ECMTemplate") ; uiECMTemp.addChild(UIECMTemplateList.class, null, null) ; setSelectedTab("UIViewContainer"); } public void refresh() throws Exception { update(); } public void update() throws Exception { getChild(UIViewContainer.class).update() ; UIECMTemplateList uiECMTemplateList = ((UITemplateContainer)getChildById("ECMTemplate")).getChild(UIECMTemplateList.class); uiECMTemplateList.refresh(uiECMTemplateList.getUIPageIterator().getCurrentPage()); } static public class SelectTabActionListener extends EventListener<UIViewManager> { public void execute(Event<UIViewManager> event) throws Exception { WebuiRequestContext context = event.getRequestContext(); String renderTab = context.getRequestParameter(UIComponent.OBJECTID); if (renderTab == null) return; event.getSource().setSelectedTab(renderTab); WebuiRequestContext parentContext = (WebuiRequestContext)context.getParentAppRequestContext(); if (parentContext != null) { parentContext.setResponseComplete(true); } else { context.setResponseComplete(true); } } } }
3,150
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIViewPermissionContainer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/views/UIViewPermissionContainer.java
/*************************************************************************** * Copyright (C) 2003-2009 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. * **************************************************************************/ package org.exoplatform.ecm.webui.component.admin.views; import org.exoplatform.ecm.webui.core.UIPermissionManagerBase; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Feb 19, 2013 * 4:30:37 PM */ @ComponentConfig(lifecycle = UIContainerLifecycle.class) public class UIViewPermissionContainer extends UIPermissionManagerBase { private boolean isUpdate_ = false; private boolean isView_ = false; public UIViewPermissionContainer() throws Exception { addChild(UIViewPermissionList.class, null, null); addChild(UIViewPermissionForm.class, null, null); } public void update(boolean isUpdate) { isUpdate_ = isUpdate; } public boolean isUpdate() { return isUpdate_; } public boolean isView() { return isView_; } public void view(boolean isView) { isView_ = isView; } }
1,883
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIViewContainer.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/views/UIViewContainer.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.views; import java.util.ResourceBundle; import org.exoplatform.web.application.RequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIContainer; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.lifecycle.UIContainerLifecycle; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Nov 23, 2006 * 2:09:18 PM */ @ComponentConfig(lifecycle = UIContainerLifecycle.class) public class UIViewContainer extends UIContainer { public UIViewContainer() throws Exception { addChild(UIViewList.class, null, null) ; } public void initPopup(String popupId, UIComponent uiComponent) throws Exception { initPopup(popupId, uiComponent, 600, 300); } public void initPopup(String popupId, UIComponent uiComponent, int width, int height) throws Exception { removeChildById(popupId) ; UIPopupWindow uiPopup = addChild(UIPopupWindow.class, null, popupId) ; uiPopup.setShowMask(true); uiPopup.setShowMask(true); uiPopup.setWindowSize(width, height) ; uiPopup.setUIComponent(uiComponent); uiPopup.setShow(true) ; uiPopup.setResizable(true); } public void update() throws Exception { UIViewList uiViewList = getChild(UIViewList.class); uiViewList.refresh(uiViewList.getUIPageIterator().getCurrentPage()); } public String getFriendlyPermission(String permission) throws Exception { RequestContext context = RequestContext.getCurrentInstance(); ResourceBundle res = context.getApplicationResourceBundle(); String permissionLabel = res.getString(getId() + ".label.permission"); if(permission.indexOf(":") > -1) { String[] arr = permission.split(":"); if(arr[0].equals("*")) { permissionLabel = permissionLabel.replace("{0}", "Any"); } else { permissionLabel = permissionLabel.replace("{0}", standardizeGroupName(arr[0])); } String groupName = arr[1]; groupName = groupName.substring(groupName.lastIndexOf("/")+1); permissionLabel = permissionLabel.replace("{1}", standardizeGroupName(groupName)); } else { permissionLabel = standardizeGroupName(permission); } return permissionLabel; } public String standardizeGroupName(String groupName) throws Exception { groupName = groupName.replaceAll("-", " "); char[] stringArray = groupName.toCharArray(); stringArray[0] = Character.toUpperCase(stringArray[0]); groupName = new String(stringArray); return groupName; } }
3,418
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIViewForm.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/webui-administration/src/main/java/org/exoplatform/ecm/webui/component/admin/views/UIViewForm.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.admin.views; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.version.VersionHistory; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.jcr.model.VersionNode; import org.exoplatform.ecm.webui.form.validator.ECMNameValidator; import org.exoplatform.ecm.webui.selector.UISelectable; import org.exoplatform.ecm.webui.utils.JCRExceptionManager; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.views.ManageViewService; import org.exoplatform.services.cms.views.ViewConfig; import org.exoplatform.services.cms.views.ViewConfig.Tab; 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.application.WebuiRequestContext; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.UIPopupWindow; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.exception.MessageException; 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; import org.exoplatform.webui.form.validator.MandatoryValidator; /** * Created by The eXo Platform SARL * Author : Tran The Trong * trongtt@yahoo.com * Jun 28, 2006 */ public class UIViewForm extends UIForm implements UISelectable { final static public String FIELD_VERSION = "version" ; final static public String FIELD_NAME = "viewName" ; final static public String FIELD_TABS = "tabs" ; final static public String FIELD_TEMPLATE = "template" ; final static public String FIELD_ENABLEVERSION = "enableVersion" ; final static public String FIELD_PERMISSION = "permission" ; final static public String FIELD_HIDE_EXPLORER_PANEL = "hideExplorerPanel" ; private boolean isView_ = true ; private NodeLocation views_; private HashMap<String, Tab> tabMap_ = new HashMap<String, Tab>() ; private ManageViewService vservice_ = null ; private String viewName_ = null; private String permission = StringUtils.EMPTY; private List<String> listVersion = new ArrayList<String>() ; private String baseVersionName_; private VersionNode selectedVersion_; private VersionNode rootVersionNode; Map<String, String> templateMap = new HashMap<String, String>(); Map<String, String> tempMap = new HashMap<String, String>(); public String getViewName() { return viewName_; } public void setViewName(String viewName) { this.viewName_ = viewName; } public String getPermission() { return permission; } public String[] getActions() { return new String[] {}; } public void setPermission(String permission) { this.permission = permission; } public UIViewForm() throws Exception { this("UIViewForm"); } public UIViewForm(String name) throws Exception { setComponentConfig(getClass(), null) ; List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ; UIFormSelectBox versions = new UIFormSelectBox(FIELD_VERSION , FIELD_VERSION, options) ; versions.setOnChange("ChangeVersion"); versions.setRendered(false) ; addUIFormInput(versions) ; addUIFormInput(new UIFormStringInput(FIELD_NAME, FIELD_NAME, null).addValidator(MandatoryValidator.class) .addValidator(ECMNameValidator.class)) ; vservice_ = getApplicationComponent(ManageViewService.class) ; Node ecmTemplateHome = vservice_.getTemplateHome(BasePath.ECM_EXPLORER_TEMPLATES, WCMCoreUtils.getSystemSessionProvider()); List<SelectItemOption<String>> temp = new ArrayList<SelectItemOption<String>>() ; if(ecmTemplateHome != null) { NodeIterator iter = ecmTemplateHome.getNodes() ; while(iter.hasNext()) { Node tempNode = iter.nextNode() ; temp.add(new SelectItemOption<String>(tempNode.getName(),tempNode.getName())) ; templateMap.put(tempNode.getName(), tempNode.getPath()); tempMap.put(tempNode.getPath(), tempNode.getName()); } } addUIFormInput(new UIFormSelectBox(FIELD_TEMPLATE,FIELD_TEMPLATE, temp)) ; UICheckBoxInput enableVersion = new UICheckBoxInput(FIELD_ENABLEVERSION, FIELD_ENABLEVERSION, null) ; enableVersion.setRendered(true) ; addUIFormInput(enableVersion) ; //prefernce: is show side bar UICheckBoxInput hideExplorerPanel = new UICheckBoxInput(FIELD_HIDE_EXPLORER_PANEL, FIELD_HIDE_EXPLORER_PANEL, false); hideExplorerPanel.setRendered(false); addUIFormInput(hideExplorerPanel); } public void processRender(WebuiRequestContext context) throws Exception { super.processRender(context) ; } public void doSelect(String selectField, Object value) { UIFormStringInput uiStringInput = getUIStringInput(selectField); uiStringInput.setValue(value.toString()); } public boolean isView() { return isView_ ; } public Node getViews() { return NodeLocation.getNodeByLocation(views_); } public boolean canEnableVersionning(Node node) throws Exception { return node.canAddMixin(Utils.MIX_VERSIONABLE); } private boolean isVersioned(Node node) throws RepositoryException { return node.isNodeType(Utils.MIX_VERSIONABLE); } private VersionNode getRootVersion(Node node) throws Exception{ VersionHistory vH = node.getVersionHistory() ; if(vH != null) return new VersionNode(vH.getRootVersion(), node.getSession()) ; return null ; } private List<String> getNodeVersions(List<VersionNode> children) throws Exception { List<VersionNode> child = new ArrayList<VersionNode>() ; for(VersionNode vNode : children){ listVersion.add(vNode.getName()); child = vNode.getChildren() ; if (!child.isEmpty()) getNodeVersions(child) ; } return listVersion ; } private List<SelectItemOption<String>> getVersionValues(Node node) throws Exception { List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ; List<VersionNode> children = getRootVersion(node).getChildren() ; listVersion.clear() ; List<String> versionList = getNodeVersions(children) ; for(int i = 0; i < versionList.size(); i++) { for(int j = i + 1; j < versionList.size(); j ++) { if( Integer.parseInt(versionList.get(j)) < Integer.parseInt(versionList.get(i))) { String temp = versionList.get(i) ; versionList.set(i, versionList.get(j)) ; versionList.set(j, temp) ; } } options.add(new SelectItemOption<String>(versionList.get(i), versionList.get(i))) ; } return options ; } public HashMap<String, Tab> getTabMap() { return tabMap_; } public void addTab(String tabName, String buttons){ Tab tab = new Tab() ; tab.setTabName(tabName) ; tab.setButtons(buttons) ; tab.setLocalizeButtons(getLocalizationButtons(buttons)); tabMap_.put(tabName, tab) ; } public String getLocalizationButtons(String buttons) { StringBuilder localizationButtons = new StringBuilder(); RequestContext context = RequestContext.getCurrentInstance(); ResourceBundle res = context.getApplicationResourceBundle(); if(buttons.contains(";")) { String[] arrButtons = buttons.split(";"); for(int i = 0; i < arrButtons.length; i++) { try { localizationButtons.append(res.getString("UITabForm.label." + arrButtons[i].trim())); } catch(MissingResourceException mre) { localizationButtons.append(arrButtons[i]); } if(i < arrButtons.length - 1) { localizationButtons.append(", "); } } } else { try { localizationButtons.append(res.getString("UITabForm.label." + buttons.trim())); } catch(MissingResourceException mre) { localizationButtons.append(buttons.trim()); } } return localizationButtons.toString(); } public String getTabList() throws Exception { StringBuilder result = new StringBuilder() ; List<Tab> tabList = new ArrayList<Tab>(tabMap_.values()); if(result != null) { for(Tab tab : tabList) { if(result.length() > 0) result.append(",") ; result.append(tab.getTabName()) ; } } return result.toString() ; } public List<Tab> getTabs() throws Exception { return new ArrayList<Tab>(tabMap_.values()); } public void refresh(boolean isAddNew) throws Exception { getUIFormSelectBox(FIELD_VERSION).setRendered(!isAddNew) ; getUIFormSelectBox(FIELD_VERSION).setDisabled(!isAddNew) ; getUIStringInput(FIELD_NAME).setDisabled(!isAddNew).setValue(null) ; getUIFormSelectBox(FIELD_TEMPLATE).setValue(null) ; getUIFormSelectBox(FIELD_TEMPLATE).setDisabled(!isAddNew) ; getUICheckBoxInput(FIELD_ENABLEVERSION).setRendered(!isAddNew) ; getUICheckBoxInput(FIELD_HIDE_EXPLORER_PANEL).setRendered(!isAddNew); setViewName(""); if(isAddNew) { tabMap_.clear() ; views_ = null ; getUICheckBoxInput(FIELD_HIDE_EXPLORER_PANEL).setValue(false); } selectedVersion_ = null ; baseVersionName_ = null ; } public void update(Node viewNode, boolean isView, VersionNode selectedVersion) throws Exception { isView_ = isView ; if(viewNode != null) { setPermission(viewNode.getProperty("exo:accessPermissions").getString()); views_ = NodeLocation.getNodeLocationByNode(viewNode); if(isVersioned(viewNode)) baseVersionName_ = viewNode.getBaseVersion().getName(); tabMap_.clear() ; for(NodeIterator iter = viewNode.getNodes(); iter.hasNext(); ) { Node tab = iter.nextNode() ; String buttons = tab.getProperty("exo:buttons").getString() ; Tab tabObj = new Tab() ; tabObj.setTabName(tab.getName()) ; tabObj.setButtons(buttons) ; tabObj.setLocalizeButtons(getLocalizationButtons(buttons)); tabMap_.put(tab.getName(), tabObj) ; } getUICheckBoxInput(FIELD_ENABLEVERSION).setRendered(true) ; if (isVersioned(viewNode)) { rootVersionNode = getRootVersion(viewNode); getUIFormSelectBox(FIELD_VERSION).setOptions(getVersionValues(viewNode)).setRendered(true) ; getUIFormSelectBox(FIELD_VERSION).setValue(baseVersionName_) ; getUICheckBoxInput(FIELD_ENABLEVERSION).setChecked(true) ; getUICheckBoxInput(FIELD_ENABLEVERSION).setDisabled(false); } else if (!isVersioned(viewNode)) { getUIFormSelectBox(FIELD_VERSION).setRendered(false) ; getUICheckBoxInput(FIELD_ENABLEVERSION).setChecked(false) ; getUICheckBoxInput(FIELD_ENABLEVERSION).setDisabled(false); } //pref is show side bar getUICheckBoxInput(FIELD_HIDE_EXPLORER_PANEL).setRendered(true); getUICheckBoxInput(FIELD_HIDE_EXPLORER_PANEL).setValue( viewNode.getProperty(NodetypeConstant.EXO_HIDE_EXPLORER_PANEL).getBoolean()); } //--------------------- Node viewsNode = NodeLocation.getNodeByLocation(views_); if (selectedVersion != null) { viewsNode.restore(selectedVersion.getName(), false) ; viewsNode.checkout() ; tabMap_.clear() ; for(NodeIterator iter = viewsNode.getNodes(); iter.hasNext(); ) { Node tab = iter.nextNode() ; String buttons = tab.getProperty("exo:buttons").getString() ; Tab tabObj = new Tab() ; tabObj.setTabName(tab.getName()) ; tabObj.setButtons(buttons) ; tabMap_.put(tab.getName(), tabObj) ; } selectedVersion_ = selectedVersion; } if(viewsNode != null) { getUIStringInput(FIELD_NAME).setDisabled(true).setValue(viewsNode.getName()) ; getUIFormSelectBox(FIELD_TEMPLATE).setValue(tempMap.get(viewsNode.getProperty("exo:template").getString())); } } public void save() throws Exception { String viewName = getUIStringInput(FIELD_NAME).getValue(); ApplicationMessage message ; if(viewName == null || viewName.trim().length() == 0){ throw new MessageException(new ApplicationMessage("UIViewForm.msg.view-name-invalid", null, ApplicationMessage.WARNING)) ; } viewName = viewName.trim(); boolean isEnableVersioning = getUICheckBoxInput(FIELD_ENABLEVERSION).isChecked() ; boolean hideExplorerPanel = getUICheckBoxInput(FIELD_HIDE_EXPLORER_PANEL).isChecked(); List<ViewConfig> viewList = vservice_.getAllViews() ; UIPopupWindow uiPopup = getAncestorOfType(UIPopupWindow.class) ; uiPopup.setShowMask(true); if(uiPopup.getId().equals(UIViewList.ST_ADD)) { for(ViewConfig view : viewList) { if(view.getName().equals(viewName) && !isEnableVersioning) { message = new ApplicationMessage("UIViewForm.msg.view-exist", null, ApplicationMessage.WARNING) ; throw new MessageException(message) ; } } } if(tabMap_.size() < 1 ){ message = new ApplicationMessage("UIViewForm.msg.mustbe-add-tab", null, ApplicationMessage.WARNING) ; throw new MessageException(message) ; } if(permission == null || permission.length() == 0){ message = new ApplicationMessage("UIViewForm.msg.mustbe-add-permission", null, ApplicationMessage.WARNING) ; throw new MessageException(message) ; } String template = templateMap.get(getUIFormSelectBox(FIELD_TEMPLATE).getValue()); List<Tab> tabList = new ArrayList<Tab>(tabMap_.values()); Node viewNode = NodeLocation.getNodeByLocation(views_); if(views_ == null || !isEnableVersioning) { vservice_.addView(viewName, permission, hideExplorerPanel, template, tabList) ; if(viewNode != null) { for(NodeIterator iter = viewNode.getNodes(); iter.hasNext(); ) { Node tab = iter.nextNode() ; if(!tabMap_.containsKey(tab.getName())) tab.remove() ; } viewNode.save() ; } } else { if (!isVersioned(viewNode)) { viewNode.addMixin(Utils.MIX_VERSIONABLE); viewNode.save(); } else { viewNode.checkout() ; } for(NodeIterator iter = viewNode.getNodes(); iter.hasNext(); ) { Node tab = iter.nextNode() ; if(!tabMap_.containsKey(tab.getName())) tab.remove() ; } vservice_.addView(viewName, permission, hideExplorerPanel, template, tabList) ; try { viewNode.save() ; viewNode.checkin(); } catch (Exception e) { UIApplication uiApp = getAncestorOfType(UIApplication.class) ; JCRExceptionManager.process(uiApp, e); return ; } } UIViewList uiViewList = getAncestorOfType(UIViewContainer.class).getChild(UIViewList.class); uiViewList.refresh(uiViewList.getUIPageIterator().getCurrentPage()); refresh(true) ; } public void editTab(String tabName) throws Exception { UIViewFormTabPane viewTabPane = getParent() ; UITabForm tabForm = viewTabPane.getChild(UITabForm.class) ; tabForm.update(tabMap_.get(tabName), isView_) ; viewTabPane.setSelectedTab(tabForm.getId()) ; } public void deleteTab(String tabName) throws Exception { UIViewFormTabPane viewTabPane = getParent() ; //String permLastest = viewTabPane.getUIStringInput(UIViewForm.FIELD_PERMISSION).getValue(); tabMap_.remove(tabName) ; update(null, false, null) ; UIViewContainer uiViewContainer = getAncestorOfType(UIViewContainer.class) ; UIViewList uiViewList = uiViewContainer.getChild(UIViewList.class) ; uiViewList.refresh(uiViewList.getUIPageIterator().getCurrentPage()); UIViewForm uiViewForm = viewTabPane.getChild(UIViewForm.class) ; viewTabPane.setSelectedTab(uiViewForm.getId()) ; } public void changeVersion() throws Exception { String path = NodeLocation.getNodeByLocation(views_) .getVersionHistory() .getVersion(getUIFormSelectBox(FIELD_VERSION).getValue()) .getPath(); VersionNode selectedVesion = rootVersionNode.findVersionNode(path); update(null, false, selectedVesion) ; } public void revertVersion() throws Exception { if (selectedVersion_ != null && !selectedVersion_.getName().equals(baseVersionName_)) { NodeLocation.getNodeByLocation(views_).restore(baseVersionName_, true); } } static public class ChangeVersionActionListener extends EventListener<UIViewForm> { public void execute(Event<UIViewForm> event) throws Exception { UIViewFormTabPane uiFormTab = event.getSource().getParent(); UIViewForm uiForm = uiFormTab.getChild(UIViewForm.class); uiForm.changeVersion(); UIViewContainer uiViewContainer = uiFormTab.getAncestorOfType(UIViewContainer.class) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiViewContainer) ; } } }
18,668
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z