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
TestDownloadConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/test/java/org/exoplatform/wcm/connector/collaboration/TestDownloadConnector.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.collaboration; import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.exoplatform.BaseConnectorTestCase; import org.exoplatform.services.rest.impl.ContainerResponse; import org.exoplatform.services.rest.wadl.research.HTTPMethods; /** * Created by The eXo Platform SAS * Author : Nguyen The Vinh From ECM Of eXoPlatform * vinh_nguyen@exoplatform.com * 24 Aug 2012 */ public class TestDownloadConnector extends BaseConnectorTestCase{ private static final String restPath = "/contents/download/collaboration/offices.jpg"; public void setUp() throws Exception { super.setUp(); // Bind DownloadConnector REST service DownloadConnector restService = (DownloadConnector) this.container.getComponentInstanceOfType(DownloadConnector.class); this.binder.addResource(restService, null); } public void testDownload() throws Exception{ // ConversationState.setCurrent(new ConversationState(new Identity("root"))); applyUserSession("john", "gtn", "collaboration"); /* Prepare the favourite nodes */ ContainerResponse response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); } public void tearDown() throws Exception { super.tearDown(); } }
2,120
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestOpenInOfficeConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/test/java/org/exoplatform/wcm/connector/collaboration/TestOpenInOfficeConnector.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.collaboration; import org.apache.commons.lang3.StringUtils; import org.exoplatform.BaseConnectorTestCase; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.rest.impl.ContainerResponse; import org.exoplatform.services.rest.wadl.research.HTTPMethods; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import javax.jcr.Node; import javax.jcr.Session; import javax.ws.rs.core.Response; import java.util.Arrays; /** * Created by The eXo Platform SAS * Author : eXoPlatform * toannh@exoplatform.com * Dec 04/01, 2015 * Test all methods of OpenInOfficeConnector */ public class TestOpenInOfficeConnector extends BaseConnectorTestCase{ private final String OPEN_DOCUMENT_ON_DESKTOP_RESOURCE_KEY = "OpenInOfficeConnector.label.exo.remote-edit.desktop"; private final String OPEN_DOCUMENT_ON_DESKTOP_CSS_CLASS = "uiIconOpenOnDesktop"; private final String OPEN_DOCUMENT_IN_WORD_CSS_CLASS = "uiIcon16x16applicationmsword"; private final String OPEN_DOCUMENT_IN_WORD_RESOURCE_KEY = "OpenInOfficeConnector.label.exo.remote-edit.word"; private final String OPEN_DOCUMENT_IN_EXCEL_CSS_CLASS = "uiIcon16x16applicationxls"; private final String OPEN_DOCUMENT_IN_EXCEL_RESOURCE_KEY = "OpenInOfficeConnector.label.exo.remote-edit.excel"; private final String OPEN_DOCUMENT_IN_PPT_CSS_CLASS = "uiIcon16x16applicationvndopenxmlformats-officedocumentpresentationmlpresentation"; private final String OPEN_DOCUMENT_IN_PPT_RESOURCE_KEY = "OpenInOfficeConnector.label.exo.remote-edit.powerpoint"; OpenInOfficeConnector openInOfficeConnector =null; private ManageableRepository manageableRepository; public void setUp() throws Exception { super.setUp(); // Bind OpenInOfficeConnector REST service openInOfficeConnector = (OpenInOfficeConnector) this.container.getComponentInstanceOfType(OpenInOfficeConnector.class); this.binder.addResource(openInOfficeConnector, null); } public void testCreateShortcut() throws Exception { String parentPath = "sites1"; String restPath = "http://localhost:8080/office/test.doc?workspace=collaboration&filePath=/" + parentPath + "/test.doc"; applyUserSession("john", "gtn", "collaboration"); manageableRepository = repositoryService.getCurrentRepository(); Session session = WCMCoreUtils.getSystemSessionProvider().getSession(COLLABORATION_WS, manageableRepository); Node rootNode = session.getRootNode(); Node sites = rootNode.addNode(parentPath); sites.addNode("test.doc"); rootNode.save(); ContainerResponse response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals("application/internet-shortcut", response.getHttpHeaders().get("Content-type").get(0)); assertEquals("attachment; filename=test.doc.url", response.getHttpHeaders().get("Content-Disposition").get(0)); } public void testCreateShortcutWithNoPermission() throws Exception { String parentPath = "sites1"; String restPath = "http://localhost:8080/office/test.doc?workspace=collaboration&filePath=/" + parentPath + "/test.doc"; applyUserSession("john", "gtn", "collaboration"); manageableRepository = repositoryService.getCurrentRepository(); Session session = WCMCoreUtils.getSystemSessionProvider().getSession(COLLABORATION_WS, manageableRepository); Node rootNode = session.getRootNode(); Node sites = rootNode.addNode(parentPath); sites.addNode("test.doc"); rootNode.save(); applyUserSession("demo", "gtn", "collaboration"); ContainerResponse response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); } public void testCheckout() throws Exception { String parentPath = "sites1"; String restPath = "/office/checkout?workspace=collaboration&filePath=/" + parentPath + "/test.doc"; applyUserSession("john", "gtn", "collaboration"); manageableRepository = repositoryService.getCurrentRepository(); Session session = WCMCoreUtils.getSystemSessionProvider().getSession(COLLABORATION_WS, manageableRepository); Node rootNode = session.getRootNode(); Node sites = rootNode.addNode(parentPath); sites.addNode("test.doc"); rootNode.save(); ContainerResponse response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals("true", response.getResponse().getEntity().toString()); } public void testCheckoutWithNoPermission() throws Exception { String parentPath = "sites1"; String restPath = "/office/checkout?workspace=collaboration&filePath=/" + parentPath + "/test.doc"; applyUserSession("john", "gtn", "collaboration"); manageableRepository = repositoryService.getCurrentRepository(); Session session = WCMCoreUtils.getSystemSessionProvider().getSession(COLLABORATION_WS, manageableRepository); Node rootNode = session.getRootNode(); Node sites = rootNode.addNode(parentPath); sites.addNode("test.doc"); rootNode.save(); applyUserSession("demo", "gtn", "collaboration"); ContainerResponse response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); } public void testUpdateDocumentTitleWithNoPermission() throws Exception { String parentPath = "sites1"; String restPath = "/office/updateDocumentTitle?objId=collaboration:/" + parentPath + "/test.doc&lang=en"; applyUserSession("john", "gtn", "collaboration"); manageableRepository = repositoryService.getCurrentRepository(); Session session = WCMCoreUtils.getSystemSessionProvider().getSession(COLLABORATION_WS, manageableRepository); Node rootNode = session.getRootNode(); Node sites = rootNode.addNode(parentPath); sites.addNode("test.doc"); rootNode.save(); applyUserSession("demo", "gtn", "collaboration"); ContainerResponse response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); } public void testUpdateDocumentTitleWithIncorrectObjId() throws Exception { String parentPath = "sites2"; String restPath = "/office/updateDocumentTitle?objId=/" + parentPath + "/test.doc&lang=en"; applyUserSession("john", "gtn", "collaboration"); manageableRepository = repositoryService.getCurrentRepository(); Session session = WCMCoreUtils.getSystemSessionProvider().getSession(COLLABORATION_WS, manageableRepository); Node rootNode = session.getRootNode(); Node sites = rootNode.addNode(parentPath); sites.addNode("test.doc"); rootNode.save(); ContainerResponse response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } public void testUpdateDocumentTitle() throws Exception{ String parentPath = "sites1"; String restPath = "/office/updateDocumentTitle?objId=collaboration:/" + parentPath + "/test.doc&lang=en"; applyUserSession("john", "gtn", "collaboration"); manageableRepository = repositoryService.getCurrentRepository(); Session session = WCMCoreUtils.getSystemSessionProvider().getSession(COLLABORATION_WS, manageableRepository); Node rootNode = session.getRootNode(); Node sites = rootNode.addNode(parentPath); sites.addNode("test.doc"); rootNode.save(); ContainerResponse response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); } public void testUpdateDocumentTitleWithDocumentNamedWithColon() throws Exception{ String parentPath = "sites3"; String restPath = "/office/updateDocumentTitle?objId=collaboration:/" + parentPath + "/exo:colon.doc&lang=en"; applyUserSession("john", "gtn", "collaboration"); manageableRepository = repositoryService.getCurrentRepository(); Session session = WCMCoreUtils.getSystemSessionProvider().getSession(COLLABORATION_WS, manageableRepository); Node rootNode = session.getRootNode(); Node sites = rootNode.addNode(parentPath); sites.addNode("exo:colon.doc"); rootNode.save(); ContainerResponse response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); } public void testGetDocumentInfos() throws Exception{ String word = "test.doc"; String excel = "test.xls"; String powerpoint = "test.ppt"; String other = "test.txt"; String[] resultWordActual = openInOfficeConnector.getDocumentInfos(word); String[] resultExcelActual = openInOfficeConnector.getDocumentInfos(excel); String[] resultPptActual = openInOfficeConnector.getDocumentInfos(powerpoint); String[] resultOtherActual = openInOfficeConnector.getDocumentInfos(other); String[] resultWordExpected = {OPEN_DOCUMENT_IN_WORD_RESOURCE_KEY, OPEN_DOCUMENT_IN_WORD_CSS_CLASS}; String[] resultExcelExpected = {OPEN_DOCUMENT_IN_EXCEL_RESOURCE_KEY, OPEN_DOCUMENT_IN_EXCEL_CSS_CLASS}; String[] resultPptExpected = {OPEN_DOCUMENT_IN_PPT_RESOURCE_KEY, OPEN_DOCUMENT_IN_PPT_CSS_CLASS}; String[] resultOtherExpected = {OPEN_DOCUMENT_ON_DESKTOP_RESOURCE_KEY, OPEN_DOCUMENT_ON_DESKTOP_CSS_CLASS}; assertTrue(Arrays.equals(resultWordActual, resultWordExpected)); assertTrue(Arrays.equals(resultExcelActual, resultExcelExpected)); assertTrue(Arrays.equals(resultPptActual, resultPptExpected)); assertTrue(Arrays.equals(resultOtherActual, resultOtherExpected)); } public void tearDown() throws Exception { super.tearDown(); } }
10,831
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestFavoriteRESTService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/test/java/org/exoplatform/wcm/connector/collaboration/TestFavoriteRESTService.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.collaboration; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import javax.jcr.Node; import javax.jcr.Session; import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.exoplatform.BaseConnectorTestCase; import org.exoplatform.services.cms.documents.FavoriteService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.rest.impl.ContainerResponse; import org.exoplatform.services.rest.wadl.research.HTTPMethods; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.Identity; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.connector.collaboration.FavoriteRESTService.ListResultNode; /** * Created by The eXo Platform SAS * Author : Nguyen The Vinh From ECM Of eXoPlatform * vinh_nguyen@exoplatform.com * 20 Aug 2012 */ public class TestFavoriteRESTService extends BaseConnectorTestCase { /** * Bind FavoriteRESTService REST service */ private FavoriteService favoriteService; private ManageableRepository manageableRepository; private static final String DATE_MODIFIED = "exo:dateModified"; private static final String restPath = "/favorite/all/repository/collaboration/john"; public void setUp() throws Exception { super.setUp(); // Bind FavoriteRESTService REST service FavoriteRESTService restService = (FavoriteRESTService) this.container.getComponentInstanceOfType(FavoriteRESTService.class); this.binder.addResource(restService, null); favoriteService = WCMCoreUtils.getService(FavoriteService.class); } public void testGetFavoriteByUser() throws Exception{ applyUserSession("john", "gtn", "collaboration"); /* Prepare the favourite nodes */ manageableRepository = repositoryService.getCurrentRepository(); Session session = WCMCoreUtils.getSystemSessionProvider().getSession(COLLABORATION_WS, manageableRepository); ConversationState c = new ConversationState(new Identity(session.getUserID())); ConversationState.setCurrent(c); Node rootNode = session.getRootNode(); Node testAddFavouriteNode1 = rootNode.addNode("testAddFavorite1"); testAddFavouriteNode1.addMixin("mix:referenceable"); testAddFavouriteNode1.addMixin("exo:datetime"); testAddFavouriteNode1.setProperty(NodetypeConstant.EXO_DATE_CREATED, Calendar.getInstance()); Node testAddFavouriteNode2 = rootNode.addNode("testAddFavorite2"); testAddFavouriteNode2.addMixin("mix:referenceable"); testAddFavouriteNode2.addMixin("exo:datetime"); testAddFavouriteNode2.setProperty(NodetypeConstant.EXO_DATE_CREATED, Calendar.getInstance()); session.save(); favoriteService.addFavorite(testAddFavouriteNode1, "john"); favoriteService.addFavorite(testAddFavouriteNode2, "john"); List<Node> listNodes = favoriteService.getAllFavoriteNodesByUser("john",0); for (Node favorite : listNodes) { favorite.addMixin("exo:datetime"); favorite.setProperty(DATE_MODIFIED, new GregorianCalendar()); favorite.getProperty(DATE_MODIFIED).setValue(new GregorianCalendar()); } session.save(); ContainerResponse response = service(HTTPMethods.GET.toString(), restPath, StringUtils.EMPTY, null, null); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); ListResultNode object = (ListResultNode) response.getEntity(); //Is Rest service properly run assertEquals(2, object.getListFavorite().size()); } public void tearDown() throws Exception { super.tearDown(); } }
4,471
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ManageDocumentServiceTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/test/java/org/exoplatform/ecm/connector/platform/ManageDocumentServiceTest.java
package org.exoplatform.ecm.connector.platform; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ValueParam; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; 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.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.Identity; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.connector.FileUploadHandler; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.MockitoJUnitRunner; import javax.jcr.Node; import javax.jcr.Session; import javax.ws.rs.core.Response; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class ManageDocumentServiceTest { @Mock private FileUploadHandler fileUploadHandler; @Mock private ManageDriveService manageDriveService; @Mock private LinkManager linkManager; @Mock private CloudDriveService cloudDriveService; @Mock private InitParams initParams; @Mock private Session session; private ManageDocumentService manageDocumentService; MockedStatic<Utils> UTILS; MockedStatic<SessionProvider> SESSION_PROVIDER; @Before public void setUp() throws Exception { MockedStatic<WCMCoreUtils> WCM_CORE_UTILS = mockStatic(WCMCoreUtils.class); ValueParam valueParam = mock(ValueParam.class); when(valueParam.getValue()).thenReturn("20"); when(initParams.getValueParam("upload.limit.size")).thenReturn(valueParam); this.manageDocumentService = new ManageDocumentService(manageDriveService,linkManager,cloudDriveService, initParams); SessionProvider userSessionProvider = mock(SessionProvider.class); SessionProvider systemSessionProvider = mock(SessionProvider.class); WCM_CORE_UTILS.when(WCMCoreUtils::getUserSessionProvider).thenReturn(userSessionProvider); WCM_CORE_UTILS.when(WCMCoreUtils::getSystemSessionProvider).thenReturn(systemSessionProvider); RepositoryService repositoryService = mock(RepositoryService.class); WCM_CORE_UTILS.when(() -> WCMCoreUtils.getService(RepositoryService.class)).thenReturn(repositoryService); ManageableRepository manageableRepository = mock(ManageableRepository.class); when(repositoryService.getCurrentRepository()).thenReturn(manageableRepository); lenient().when(systemSessionProvider.getSession("collaboration", manageableRepository)).thenReturn(session); when(userSessionProvider.getSession("collaboration", manageableRepository)).thenReturn(session); MockedStatic<ConversationState> CONVERSATION_STATE = mockStatic(ConversationState.class); ConversationState conversationState = mock(ConversationState.class); CONVERSATION_STATE.when(ConversationState::getCurrent).thenReturn(conversationState); Identity identity = mock(Identity.class); when(conversationState.getIdentity()).thenReturn(identity); when(identity.getUserId()).thenReturn("user"); DriveData driveData = mock(DriveData.class); when(manageDriveService.getDriveByName(anyString())).thenReturn(driveData); when(driveData.getHomePath()).thenReturn("path"); UTILS = mockStatic(Utils.class); UTILS.when(() -> Utils.getPersonalDrivePath("path", "user")).thenReturn("personalDrivePath"); UTILS.when(() -> Utils.cleanString(anyString())).thenCallRealMethod(); UTILS.when(() -> Utils.cleanName(anyString())).thenCallRealMethod(); UTILS.when(() -> Utils.cleanName(anyString(), anyString())).thenCallRealMethod(); UTILS.when(() -> Utils.cleanNameWithAccents(anyString())).thenCallRealMethod(); UTILS.when(() -> Utils.replaceSpecialChars(anyString(), anyString())).thenCallRealMethod(); UTILS.when(() -> Utils.replaceSpecialChars(anyString(), anyString(), anyString())).thenCallRealMethod(); SESSION_PROVIDER = mockStatic(SessionProvider.class); SESSION_PROVIDER.when(SessionProvider::createSystemProvider).thenReturn(systemSessionProvider); } @Test public void checkFileExistence() throws Exception { Response response = this.manageDocumentService.checkFileExistence(null, "testspace", "/documents", "test.docx"); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); response = this.manageDocumentService.checkFileExistence("collaboration", null, "/documents", "test.docx"); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); response = this.manageDocumentService.checkFileExistence("collaboration", "testspace", null, "test.docx"); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); response = this.manageDocumentService.checkFileExistence("collaboration", "testspace", "/documents", null); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); Node node = mock(Node.class); when(session.getItem(anyString())).thenReturn(node); lenient().when(node.hasNode("Documents")).thenReturn(true); Node targetNode = mock(Node.class); lenient().when(node.getNode("Documents")).thenReturn(targetNode); lenient().when(node.isNodeType(NodetypeConstant.EXO_SYMLINK)).thenReturn(false); Node folderNode1 = mock(Node.class); when(node.addNode(anyString(), eq(NodetypeConstant.NT_FOLDER))).thenReturn(folderNode1); lenient().when(fileUploadHandler.checkExistence(targetNode, "test.docx")).thenReturn(Response.ok().build()); response = this.manageDocumentService.checkFileExistence("collaboration", "testspace", "/documents", "test.docx"); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); response = this.manageDocumentService.checkFileExistence("collaboration", ".spaces.space_one", "DRIVE_ROOT_NODE/Documents", "test.docx"); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); } }
6,478
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/core/connector/src/test/groovy/org/exoplatform/ecm/connector/clouddrives/package-info.java
/* * Copyright (C) 2003-2014 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. */ /** * Integration specifications (BDD-style using Spock framework). */ package org.exoplatform.ecm.connector.clouddrives;
951
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FileUploadHandler.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/FileUploadHandler.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.connector; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.net.URLDecoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import javax.jcr.ItemExistsException; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import org.apache.commons.lang.StringUtils; import org.json.JSONException; import org.json.JSONObject; import org.json.simple.JSONValue; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.exoplatform.common.http.HTTPStatus; import org.exoplatform.ecm.connector.fckeditor.FCKMessage; import org.exoplatform.ecm.connector.fckeditor.FCKUtils; import org.exoplatform.ecm.utils.lock.LockUtil; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.services.cms.documents.AutoVersionService; import org.exoplatform.services.cms.documents.DocumentService; import org.exoplatform.services.cms.impl.Utils; import org.exoplatform.services.cms.jcrext.activity.ActivityCommonService; import org.exoplatform.services.cms.mimetype.DMSMimeTypeResolver; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.access.AccessControlEntry; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.core.ExtendedSession; import org.exoplatform.services.jcr.impl.core.NodeImpl; import org.exoplatform.services.listener.ListenerService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.resources.ResourceBundleService; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.publication.WCMPublicationService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.upload.UploadResource; import org.exoplatform.upload.UploadService; import org.exoplatform.upload.UploadService.UploadLimit; import jakarta.servlet.http.HttpServletRequest; /** * Created by The eXo Platform SAS * Author : Tran Nguyen Ngoc * ngoc.tran@exoplatform.com * Sep 4, 2009 */ public class FileUploadHandler { /** Logger */ private static final Log LOG = ExoLogger.getLogger(FileUploadHandler.class.getName()); /** The Constant UPLOAD_ACTION. */ public final static String UPLOAD_ACTION = "upload"; /** The Constant PROGRESS_ACTION. */ public final static String PROGRESS_ACTION = "progress"; /** The Constant ABORT_ACTION. */ public final static String ABORT_ACTION = "abort"; /** The Constant DELETE_ACTION. */ public final static String DELETE_ACTION = "delete"; /** The Constant SAVE_ACTION. */ public final static String SAVE_ACTION = "save"; /** The Constant SAVE_NEW_VERSION_ACTION. */ public final static String SAVE_NEW_VERSION_ACTION = "saveNewVersion"; /** The Constant CHECK_EXIST. */ public final static String CHECK_EXIST= "exist"; /** The Constant REPLACE. */ public final static String REPLACE= "replace"; public final static String CREATE_VERSION = "createVersion"; /** The Constant KEEP_BOTH. */ public final static String KEEP_BOTH= "keepBoth"; /** The Constant LAST_MODIFIED_PROPERTY. */ private static final String LAST_MODIFIED_PROPERTY = "Last-Modified"; /** The Constant UPLOAD_DOC_NEW_APP. */ public static final String UPLOAD_DOC_NEW_APP = "exo.upload.doc.newApp"; /** The Constant String UPLOAD_DOC_OLD_APP. */ public static final String UPLOAD_DOC_OLD_APP = "exo.upload.doc.oldApp"; private static final String OLD_APP = "oldApp"; /** 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 final static String POST_CREATE_CONTENT_EVENT = "CmsService.event.postCreate"; private final String CONNECTOR_BUNDLE_LOCATION = "locale.wcm.resources.WCMResourceBundleConnector"; private final String AUTOVERSION_ERROR_MIME_TYPE = "DocumentAutoVersion.msg.WrongMimeType"; private static final String FILE_DECODE_REGEX = "%(?![0-9a-fA-F]{2})"; /** The document service. */ private DocumentService documentService; /** The repository service. */ private RepositoryService repositoryService; /** The upload service. */ private UploadService uploadService; /** The listener service. */ ListenerService listenerService; private ActivityCommonService activityService; /** The fck message. */ private FCKMessage fckMessage; /** The uploadIds - time Map */ private Map<String, Long> uploadIdTimeMap; /** The maximal life time for an upload */ private long UPLOAD_LIFE_TIME; /** * Instantiates a new file upload handler. */ public FileUploadHandler() { uploadService = WCMCoreUtils.getService(UploadService.class); listenerService = WCMCoreUtils.getService(ListenerService.class); activityService = WCMCoreUtils.getService(ActivityCommonService.class); documentService = WCMCoreUtils.getService(DocumentService.class); repositoryService = WCMCoreUtils.getService(RepositoryService.class); fckMessage = new FCKMessage(); uploadIdTimeMap = new Hashtable<String, Long>(); UPLOAD_LIFE_TIME = System.getProperty("MULTI_UPLOAD_LIFE_TIME") == null ? 600 ://10 minutes Long.parseLong(System.getProperty("MULTI_UPLOAD_LIFE_TIME")); } /** * Upload * @param servletRequest The request to upload file * @param uploadId Upload Id * @param limit Limit size of upload file * @return * @throws Exception */ public Response upload(HttpServletRequest servletRequest, String uploadId, Integer limit) throws Exception{ uploadService.addUploadLimit(uploadId, limit); uploadService.createUploadResource(servletRequest); uploadIdTimeMap.put(uploadId, System.currentTimeMillis()); CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); cacheControl.setNoStore(true); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); //create ret DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element rootElement = doc.createElement("html"); Element head = doc.createElement("head"); Element body = doc.createElement("body"); rootElement.appendChild(head); rootElement.appendChild(body); doc.appendChild(rootElement); return Response.ok(new DOMSource(doc), MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } /** * Check status of uploaded file. * If any problem while uploading, error message is returned. * Returning null means no problem happen. * * @param uploadId upload ID * @param language language for getting message * @return Response message is returned if any problem while uploading. * @throws Exception */ public Response checkStatus(String uploadId, String language) throws Exception { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); cacheControl.setNoStore(true); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); if ((StringUtils.isEmpty(uploadId)) || (uploadService.getUploadResource(uploadId) == null)) return null; // If file size exceed limit, return message if (UploadResource.FAILED_STATUS == uploadService.getUploadResource(uploadId).getStatus()) { // Remove upload Id uploadService.removeUploadResource(uploadId); uploadIdTimeMap.remove(uploadId); // Get message warning upload exceed limit String uploadLimit = String.valueOf(uploadService.getUploadLimits().get(uploadId).getLimit()); Document fileExceedLimit = fckMessage.createMessage(FCKMessage.FILE_EXCEED_LIMIT, FCKMessage.ERROR, language, new String[]{uploadLimit}); return Response.ok(new DOMSource(fileExceedLimit), MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } return null; } /** * Control. * * @param uploadId the upload id * @param action the action * * @return the response * * @throws Exception the exception */ public Response control(String uploadId, String action) throws Exception { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); cacheControl.setNoStore(true); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); if (FileUploadHandler.PROGRESS_ACTION.equals(action)) { Document currentProgress = getProgress(uploadId); return Response.ok(new DOMSource(currentProgress), MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } else if (FileUploadHandler.ABORT_ACTION.equals(action)) { uploadService.removeUploadResource(uploadId); uploadIdTimeMap.remove(uploadId); return Response.ok(null, MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } else if (FileUploadHandler.DELETE_ACTION.equals(action)) { uploadService.removeUploadResource(uploadId); uploadIdTimeMap.remove(uploadId); return Response.ok(null, MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } return Response.status(HTTPStatus.BAD_REQUEST) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } /** * checks if file already existed in parent folder * * @param parent the parent * @param fileName the file name * @return the response * * @throws Exception the exception */ public Response checkExistence(Node parent, String fileName) throws Exception { DMSMimeTypeResolver resolver = DMSMimeTypeResolver.getInstance(); CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); //create ret DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document fileExistence = builder.newDocument(); fileName = Utils.cleanNameWithAccents(fileName); fileName = fileName.replaceAll(FILE_DECODE_REGEX, "%25"); fileName = URLDecoder.decode(fileName,"UTF-8"); fileName = fileName.replaceAll(FILE_DECODE_REGEX, "-"); Element rootElement = fileExistence.createElement( parent.hasNode(fileName) ? "Existed" : "NotExisted"); if(parent.hasNode(fileName)){ Node existNode = parent.getNode(fileName); if(existNode.isNodeType(NodetypeConstant.MIX_VERSIONABLE)){ rootElement.appendChild(fileExistence.createElement("Versioned")); } } if(parent.isNodeType(NodetypeConstant.NT_FILE) && resolver.getMimeType(parent.getName()).equals(resolver.getMimeType(fileName))){ rootElement.appendChild(fileExistence.createElement("CanVersioning")); } fileExistence.appendChild(rootElement); //return ret; return Response.ok(new DOMSource(fileExistence), MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } /** * Clean name using Transliterator * @param fileName original file name * * @return Response */ public Response cleanName(String fileName) throws Exception { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document cleanedFilename = builder.newDocument(); fileName = Utils.cleanNameWithAccents(fileName); Element rootElement = cleanedFilename.createElement("name"); cleanedFilename.appendChild(rootElement); rootElement.setTextContent(fileName); return Response.ok(new DOMSource(cleanedFilename), MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } /** * Save as nt file. * * @param parent the parent * @param uploadId the upload id * @param fileName the file name * @param language the language * @param source the source * * @return the response * * @throws Exception the exception */ public Response saveAsNTFile(String workspaceName, Node parent, String uploadId, String fileName, String language, String source, String siteName, String userId) throws Exception { return saveAsNTFile(workspaceName, parent, uploadId, fileName, language,source, siteName, userId, KEEP_BOTH); } /** * Save as nt file. * * @param parent the parent * @param uploadId the upload id * @param fileName the file name * @param language the language * @param source the source * * @return the response * * @throws Exception the exception */ public Response saveAsNTFile(String workspaceName, Node parent, String uploadId, String fileName, String language, String source, String siteName, String userId, String existenceAction) throws Exception { return saveAsNTFile(workspaceName, parent, uploadId, fileName, language,source , siteName, userId, existenceAction,false); } /** * Save already uploaded file (identified by uploadId) as nt file. * * 'synchronized' is used to avoid JCR index corruption when uploading massively files. * The JCR index (that uses a very old version of Apache lucene) * gets corrupted when doing massive modifications on the same parent node. * * Thus here we have made this central method as synchronized to avoid corruption * and ensure Data consistency in favor of performances. The upload itself is not synchronized, * we still be able to upload concurrently using org.exoplatform.web.handler.UploadHandler * but the commit of uploaded file to be stored on JCR is made using this method, thus this critical * operation has been made synchronized. * * @param parent the parent * @param uploadId the upload id * @param fileName the file name * @param language the language * @param source the source * * @return the response * * @throws Exception the exception */ public synchronized Response saveAsNTFile(String workspaceName, Node parent, String uploadId, String fileName, String language, String source, String siteName, String userId, String existenceAction, boolean isNewVersion) throws Exception { String exoTitle = Utils.normalizeFileBaseName(fileName); fileName = Utils.cleanNameWithAccents(fileName); fileName = Text.escapeIllegalJcrChars(Utils.cleanName(fileName.toLowerCase())); try { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); UploadResource resource = uploadService.getUploadResource(uploadId); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); if (parent == null) { Document fileNotUploaded = fckMessage.createMessage(FCKMessage.FILE_NOT_UPLOADED, FCKMessage.ERROR, language, null); return Response.ok(new DOMSource(fileNotUploaded), MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } if (!FCKUtils.hasAddNodePermission(parent)) { Object[] args = { parent.getPath() }; Document message = fckMessage.createMessage(FCKMessage.FILE_UPLOAD_RESTRICTION, FCKMessage.ERROR, language, args); return Response.ok(new DOMSource(message), MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } if ((fileName == null) || (fileName.length() == 0)) { fileName = resource.getFileName(); } //add lock token if(parent.isLocked()) { parent.getSession().addLockToken(LockUtil.getLockToken(parent)); } if (parent.hasNode(fileName)) { // Object args[] = { fileName, parent.getPath() }; // Document fileExisted = fckMessage.createMessage(FCKMessage.FILE_EXISTED, // FCKMessage.ERROR, // language, // args); // return Response.ok(new DOMSource(fileExisted), MediaType.TEXT_XML) // .cacheControl(cacheControl) // .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) // .build(); if (REPLACE.equals(existenceAction)) { //Broadcast the event when user move node to Trash ListenerService listenerService = WCMCoreUtils.getService(ListenerService.class); listenerService.broadcast(ActivityCommonService.FILE_REMOVE_ACTIVITY, parent, parent.getNode(fileName)); parent.getNode(fileName).remove(); parent.save(); } } AutoVersionService autoVersionService = WCMCoreUtils.getService(AutoVersionService.class); String location = resource.getStoreLocation(); //save node with name=fileName Node file = null; Node jcrContent=null; boolean fileCreated = false; DMSMimeTypeResolver mimeTypeResolver = DMSMimeTypeResolver.getInstance(); String mimetype = mimeTypeResolver.getMimeType(resource.getFileName()); String nodeName = fileName; int count = 0; if(!CREATE_VERSION.equals(existenceAction) || (!parent.hasNode(fileName) && !CREATE_VERSION.equals(existenceAction))) { if(parent.isNodeType(NodetypeConstant.NT_FILE)){ String mimeTypeParent = mimeTypeResolver.getMimeType(parent.getName()); if(mimetype != mimeTypeParent){ ResourceBundleService resourceBundleService = WCMCoreUtils.getService(ResourceBundleService.class); ResourceBundle resourceBundle = resourceBundleService.getResourceBundle(CONNECTOR_BUNDLE_LOCATION, new Locale(language)); String errorMsg = resourceBundle.getString(AUTOVERSION_ERROR_MIME_TYPE); errorMsg = errorMsg.replace("{0}", StringUtils.escape("<span style='font-weight:bold;'>" + parent.getName() + "</span>")); JSONObject jsonObject = new JSONObject(); jsonObject.put("error_type", "ERROR_MIMETYPE"); jsonObject.put("error_message", errorMsg); return Response.serverError().entity(jsonObject.toString()).build(); } parent = parent.getParent(); } boolean doIndexName = parent.hasNode(nodeName); do { try { file = parent.addNode(nodeName, FCKUtils.NT_FILE); fileCreated = true; } catch (ItemExistsException e) {//sameNameSibling is not allowed nodeName = increaseName(fileName, ++count); doIndexName = false; } } while (!fileCreated); //-------------------------------------------------------- if (exoTitle != null && count >= 1) { exoTitle = getNewName(exoTitle, "(" + count + ")"); } if(!file.isNodeType(NodetypeConstant.MIX_REFERENCEABLE)) { file.addMixin(NodetypeConstant.MIX_REFERENCEABLE); } if(!file.isNodeType(NodetypeConstant.MIX_COMMENTABLE)) file.addMixin(NodetypeConstant.MIX_COMMENTABLE); if(!file.isNodeType(NodetypeConstant.MIX_VOTABLE)) file.addMixin(NodetypeConstant.MIX_VOTABLE); if(!file.isNodeType(NodetypeConstant.MIX_I18N)) file.addMixin(NodetypeConstant.MIX_I18N); if (!file.hasProperty(NodetypeConstant.EXO_TITLE) && doIndexName) { String name = file.getName(); String path = file.getPath(); String index = path.substring(StringUtils.indexOf(path, name) + name.length()); if (exoTitle != null && StringUtils.isNotBlank(index)) { int indexSuffix = Integer.parseInt(index.substring(1, index.lastIndexOf("]"))); String suffix = "(" + (indexSuffix - 1) + ")"; exoTitle = getNewName(exoTitle, suffix); } file.setProperty(NodetypeConstant.EXO_TITLE, Utils.cleanDocumentTitle(exoTitle)); } else if (!file.hasProperty(NodetypeConstant.EXO_TITLE)) { file.setProperty(NodetypeConstant.EXO_TITLE, Utils.cleanDocumentTitle(exoTitle)); } jcrContent = file.addNode("jcr:content","nt:resource"); }else if(parent.hasNode(nodeName)){ file = parent.getNode(nodeName); jcrContent = file.hasNode("jcr:content")?file.getNode("jcr:content"):file.addNode("jcr:content","nt:resource"); } else if(parent.isNodeType(NodetypeConstant.NT_FILE)){ file = parent; autoVersionService.autoVersion(file,isNewVersion); jcrContent = file.hasNode("jcr:content")?file.getNode("jcr:content"):file.addNode("jcr:content","nt:resource"); } jcrContent.setProperty("jcr:lastModified", new GregorianCalendar()); jcrContent.setProperty("jcr:data", new BufferedInputStream(new FileInputStream(new File(location)))); jcrContent.setProperty("jcr:mimeType", mimetype); file.setProperty(NodetypeConstant.EXO_DATE_MODIFIED, new GregorianCalendar()); if(parent.hasNode(nodeName) && CREATE_VERSION.equals(existenceAction)) { file.save(); autoVersionService.autoVersion(file,isNewVersion); } if(fileCreated) { file.getParent().save(); autoVersionService.autoVersion(file,isNewVersion); if (file.isNodeType(NodetypeConstant.MIX_VERSIONABLE)) { if (!file.isCheckedOut()) { file.checkout(); } file.checkin(); file.checkout(); } } //parent.getSession().refresh(true); // Make refreshing data //parent.save(); uploadService.removeUploadResource(uploadId); uploadIdTimeMap.remove(uploadId); WCMPublicationService wcmPublicationService = WCMCoreUtils.getService(WCMPublicationService.class); wcmPublicationService.updateLifecyleOnChangeContent(file, siteName, userId); if (activityService.isBroadcastNTFileEvents(file) && !CREATE_VERSION.equals(existenceAction)) { listenerService.broadcast(ActivityCommonService.FILE_CREATED_ACTIVITY, null, file); } file.save(); // return uploaded file Document doc = getUploadedFile(workspaceName, file, mimetype); String eventName = source.equals(OLD_APP) ? UPLOAD_DOC_OLD_APP : UPLOAD_DOC_NEW_APP; try { listenerService.broadcast(eventName, userId, file); } catch (Exception e) { LOG.error("Error broadcast upload document event", e); } return Response.ok(new DOMSource(doc), MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } catch (Exception exc) { LOG.error(exc.getMessage(), exc); return Response.serverError().entity(exc.getMessage()).build(); } } private static String getNewName(String exoTitle, String newNameSuffix) { int pointIndex = exoTitle.lastIndexOf("."); String extension = pointIndex != -1 ? exoTitle.substring(pointIndex) : ""; exoTitle = pointIndex != -1 ? exoTitle.substring(0, pointIndex).concat(newNameSuffix).concat(extension) : exoTitle.concat(newNameSuffix); return exoTitle; } private Document getUploadedFile(String workspaceName, Node file, String mimetype) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element rootElement = doc.createElement("file"); LinkedHashMap<String, String> previewBreadcrumb = new LinkedHashMap<>(); ExtendedSession session = null; try { session = (ExtendedSession) WCMCoreUtils.getSystemSessionProvider().getSession("collaboration", repositoryService.getCurrentRepository()); Node node = session.getNodeByIdentifier(file.getUUID()); previewBreadcrumb = documentService.getFilePreviewBreadCrumb(node); } catch (Exception e ) { LOG.error("Error while getting file node " + file.getUUID(), e); } finally { if (session != null) { session.logout(); } } String downloadUrl = getDownloadUrl(workspaceName, file.getPath()); String url = getUrl(file.getPath()); String lastEditor = getStringProperty(file, "exo:lastModifier"); String date = getStringProperty(file, "exo:dateModified"); rootElement.setAttribute("UUID", file.getUUID()); rootElement.setAttribute("title", file.getName()); rootElement.setAttribute("path", file.getPath()); rootElement.setAttribute("mimetype", mimetype); rootElement.setAttribute("previewBreadcrumb", JSONValue.toJSONString(previewBreadcrumb)); rootElement.setAttribute("downloadUrl", downloadUrl); rootElement.setAttribute("url", url); rootElement.setAttribute("lastEditor", lastEditor); rootElement.setAttribute("date", date); List<AccessControlEntry> permissions = ((NodeImpl) file).getACL().getPermissionEntries(); rootElement.setAttribute("acl", JSONValue.toJSONString(getFileACL(permissions))); long size = file.getNode("jcr:content").getProperty("jcr:data").getLength(); rootElement.setAttribute("size", String.valueOf(size)); doc.appendChild(rootElement); return doc; } private JSONObject getFileACL(List<AccessControlEntry> permissions) throws JSONException { Boolean canRead = permissions.stream().anyMatch(perm -> perm.getPermission().equals(PermissionType.READ)); Boolean canEdit = permissions.stream().anyMatch(perm -> perm.getPermission().equals(PermissionType.SET_PROPERTY)); Boolean canRemove = permissions.stream().anyMatch(perm -> perm.getPermission().equals(PermissionType.REMOVE)); JSONObject acl = new JSONObject(); acl.put("canEdit", canEdit); acl.put("canRead", canRead); acl.put("canRemove", canRemove); return acl; } private String getStringProperty(Node node, String propertyName) throws RepositoryException { if (node.hasProperty(propertyName)) { return node.getProperty(propertyName).getString(); } return ""; } protected String getUrl(String nodePath) { String url = ""; try { url = documentService.getLinkInDocumentsApp(nodePath); } catch (Exception e) { LOG.error("Cannot get url of document " + nodePath, e); } return url; } private String getDownloadUrl(String workspace, String nodePath) { String restContextName = WCMCoreUtils.getRestContextName(); String repositoryName = getRepositoryName(); StringBuffer downloadUrl = new StringBuffer(); downloadUrl.append('/').append(restContextName).append("/jcr/"). append(repositoryName).append('/'). append(workspace).append(nodePath); return downloadUrl.toString(); } protected String getRepositoryName() { try { return repositoryService.getCurrentRepository().getConfiguration().getName(); } catch (RepositoryException e) { LOG.debug("Cannot get repository name", e); return "repository"; } } public boolean isDocumentNodeType(Node node) throws Exception { TemplateService templateService = WCMCoreUtils.getService(TemplateService.class); return templateService.isManagedNodeType(node.getPrimaryNodeType().getName()); } /** * increase the file name (not extension). * @param origin the original name * @param count the number add to file name * @return the new increased file name */ private String increaseName(String origin, int count) { int index = origin.indexOf('.'); if (index == -1) return origin + count; return origin.substring(0, index) + count + origin.substring(index); } /** * get number of files uploading * @return number of files uploading */ public long getUploadingFileCount() { removeDeadUploads(); return uploadIdTimeMap.size(); } /** * removes dead uploads */ private void removeDeadUploads() { Set<String> removedIds = new HashSet<String>(); for (String id : uploadIdTimeMap.keySet()) { if ((System.currentTimeMillis() - uploadIdTimeMap.get(id)) > UPLOAD_LIFE_TIME * 1000) { removedIds.add(id); } } for (String id : removedIds) { uploadIdTimeMap.remove(id); } } /** * Gets the progress. * * @param uploadId the upload id * * @return the progress * * @throws Exception the exception */ private Document getProgress(String uploadId) throws Exception { UploadResource resource = uploadService.getUploadResource(uploadId); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Double percent = 0.0; if(resource != null) { if (resource.getStatus() == UploadResource.UPLOADING_STATUS) { percent = (resource.getUploadedSize() * 100) / resource.getEstimatedSize(); } else { percent = 100.0; } } Element rootElement = doc.createElement("UploadProgress"); rootElement.setAttribute("uploadId", uploadId); rootElement.setAttribute("fileName", resource == null ? "" : resource.getFileName()); rootElement.setAttribute("percent", percent.intValue() + ""); rootElement.setAttribute("uploadedSize", resource == null ? "0" : resource.getUploadedSize() + ""); rootElement.setAttribute("totalSize", resource == null ? "0" : resource.getEstimatedSize() + ""); rootElement.setAttribute("fileType", resource == null ? "null" : resource.getMimeType() + ""); UploadLimit limit = uploadService.getUploadLimits().get(uploadId); if (limit != null) { rootElement.setAttribute("limit", limit.getLimit() + ""); rootElement.setAttribute("unit", limit.getUnit() + ""); } doc.appendChild(rootElement); return doc; } /** * returns a DOMSource object containing given message * @param name the message * @return DOMSource object * @throws Exception */ private DOMSource createDOMResponse(String name, String mimeType) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element rootElement = doc.createElement(name); rootElement.setAttribute("mimetype", mimeType); doc.appendChild(rootElement); return new DOMSource(doc); } }
34,249
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
BaseConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/BaseConnector.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.connector; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Session; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.transform.dom.DOMSource; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.ecm.connector.fckeditor.FCKFileHandler; import org.exoplatform.ecm.connector.fckeditor.FCKFolderHandler; import org.exoplatform.ecm.connector.fckeditor.FCKUtils; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.voting.VotingService; 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.WebSchemaConfigService; import org.exoplatform.services.wcm.portal.LivePortalManagerService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; /* * Created by The eXo Platform SAS Author : Anh Do Ngoc anh.do@exoplatform.com * Sep 10, 2008 */ /** * The Class BaseConnector. */ public abstract class BaseConnector { /** The folder handler. */ protected FCKFolderHandler folderHandler; /** The file handler. */ protected FCKFileHandler fileHandler; /** The file upload handler. */ protected FileUploadHandler fileUploadHandler; /** The repository service. */ protected RepositoryService repositoryService; /** The log. */ private static final Log LOG = ExoLogger.getLogger(BaseConnector.class.getName()); /** The voting service. */ protected VotingService votingService; /** The link manager. */ protected LinkManager linkManager; /** The live portal manager service. */ protected LivePortalManagerService livePortalManagerService; /** The web schema config service. */ protected WebSchemaConfigService webSchemaConfigService; /** The Constant LAST_MODIFIED_PROPERTY. */ protected static final String LAST_MODIFIED_PROPERTY = "Last-Modified"; /** The Constant IF_MODIFIED_SINCE_DATE_FORMAT. */ protected static final String IF_MODIFIED_SINCE_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z"; /** * Gets the root content storage. * * @param node the node * @return the root content storage * @throws Exception the exception */ protected abstract Node getRootContentStorage(Node node) throws Exception; /** * Gets the content storage type. * * @return the content storage type * @throws Exception the exception */ protected abstract String getContentStorageType() throws Exception; /** * Instantiates a new base connector. */ public BaseConnector() { livePortalManagerService = WCMCoreUtils.getService(LivePortalManagerService.class); repositoryService = WCMCoreUtils.getService(RepositoryService.class); webSchemaConfigService = WCMCoreUtils.getService(WebSchemaConfigService.class); votingService = WCMCoreUtils.getService(VotingService.class); linkManager = WCMCoreUtils.getService(LinkManager.class); ExoContainer container = ExoContainerContext.getCurrentContainer(); folderHandler = new FCKFolderHandler(container); fileHandler = new FCKFileHandler(container); fileUploadHandler = new FileUploadHandler(); } /** * Builds the xml response on expand. * * @param currentFolder the current folder * @param runningPortal The current portal instance * @param workspaceName the workspace name * @param jcrPath the jcr path * @param command the command * @return the response * @throws Exception the exception */ protected Response buildXMLResponseOnExpand(String currentFolder, String runningPortal, String workspaceName, String jcrPath, String command) throws Exception { SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); Node sharedPortalNode = livePortalManagerService.getLiveSharedPortal(sessionProvider); Node activePortalNode = getCurrentPortalNode(jcrPath, runningPortal, sharedPortalNode); if (currentFolder.length() == 0 || "/".equals(currentFolder)) return buildXMLResponseForRoot(activePortalNode, sharedPortalNode, command); String currentPortalRelPath = "/" + activePortalNode.getName() + "/"; String sharePortalRelPath = "/" + sharedPortalNode.getName() + "/"; Node webContent = getWebContent(workspaceName, jcrPath); if (!activePortalNode.getPath().equals(sharedPortalNode.getPath()) && currentFolder.startsWith(sharePortalRelPath)) { if (currentFolder.equals(sharePortalRelPath)) { return buildXMLResponseForPortal(sharedPortalNode, null, command); } Node currentContentStorageNode = getCorrectContentStorage(sharedPortalNode, null, currentFolder); return buildXMLResponseForContentStorage(currentContentStorageNode, command); } else if (!activePortalNode.getPath().equals(sharedPortalNode.getPath()) && currentFolder.startsWith(currentPortalRelPath)) { return buildXMLResponseCommon(activePortalNode, webContent, currentFolder, command); } else { return buildXMLResponseCommon(sharedPortalNode, webContent, currentFolder, command); } } /** * Builds the xml response common. * * @param activePortal the active portal * @param webContent the web content * @param currentFolder the current folder * @param command the command * @return the response * @throws Exception the exception */ protected Response buildXMLResponseCommon(Node activePortal, Node webContent, String currentFolder, String command) throws Exception { String activePortalRelPath = "/" + activePortal.getName() + "/"; if (currentFolder.equals(activePortalRelPath)) return buildXMLResponseForPortal(activePortal, webContent, command); if (webContent != null) { String webContentRelPath = activePortalRelPath + webContent.getName() + "/"; if (currentFolder.startsWith(webContentRelPath)) { if (currentFolder.equals(webContentRelPath)) return buildXMLResponseForPortal(webContent, null, command); Node contentStorageOfWebContent = getCorrectContentStorage(activePortal, webContent, currentFolder); return buildXMLResponseForContentStorage(contentStorageOfWebContent, command); } } Node correctContentStorage = getCorrectContentStorage(activePortal, null, currentFolder); return buildXMLResponseForContentStorage(correctContentStorage, command); } /** * Builds the xml response for root. * * @param currentPortal the current portal * @param sharedPortal the shared portal * @param command the command * @return the response * @throws Exception the exception */ protected Response buildXMLResponseForRoot(Node currentPortal, Node sharedPortal, String command) throws Exception { Document document = null; Node rootNode = currentPortal.getSession().getRootNode(); Element rootElement = FCKUtils.createRootElement(command, rootNode, rootNode.getPrimaryNodeType().getName()); document = rootElement.getOwnerDocument(); Element folders = document.createElement("Folders"); Element files = document.createElement("Files"); Element sharedPortalElement = null; Element currentPortalElement = null; if (sharedPortal != null) { sharedPortalElement = folderHandler.createFolderElement(document, sharedPortal, sharedPortal.getPrimaryNodeType() .getName()); folders.appendChild(sharedPortalElement); } if (currentPortal != null && !currentPortal.getPath().equals(sharedPortal.getPath())) { currentPortalElement = folderHandler.createFolderElement(document, currentPortal, currentPortal.getPrimaryNodeType() .getName()); folders.appendChild(currentPortalElement); } rootElement.appendChild(folders); rootElement.appendChild(files); return getResponse(document); } /** * Builds the xml response for portal. * * @param node the node * @param webContent the web content * @param command the command * @return the response * @throws Exception the exception */ protected Response buildXMLResponseForPortal(Node node, Node webContent, String command) throws Exception { Node storageNode = getRootContentStorage(node); Element rootElement = FCKUtils.createRootElement(command, node, folderHandler.getFolderType(node)); Document document = rootElement.getOwnerDocument(); Element folders = document.createElement("Folders"); Element files = document.createElement("Files"); Element storageElement = folderHandler.createFolderElement(document, storageNode, storageNode.getPrimaryNodeType() .getName()); folders.appendChild(storageElement); Element webContentElement = null; if (webContent != null) { webContentElement = folderHandler.createFolderElement(document, webContent, webContent.getPrimaryNodeType() .getName()); folders.appendChild(webContentElement); } rootElement.appendChild(folders); rootElement.appendChild(files); return getResponse(document); } /** * Builds the xml response for content storage. * * @param node the node * @param command the command * @return the response * @throws Exception the exception */ protected Response buildXMLResponseForContentStorage(Node node, String command) throws Exception { Element rootElement = FCKUtils.createRootElement(command, node, folderHandler.getFolderType(node)); Document document = rootElement.getOwnerDocument(); Element folders = document.createElement("Foders"); Element files = document.createElement("Files"); for (NodeIterator iterator = node.getNodes(); iterator.hasNext();) { Node child = iterator.nextNode(); if (child.isNodeType(FCKUtils.EXO_HIDDENABLE)) continue; String folderType = folderHandler.getFolderType(child); if (folderType != null) { Element folder = folderHandler.createFolderElement(document, child, folderType); folders.appendChild(folder); } String sourceType = getContentStorageType(); String fileType = fileHandler.getFileType(child, sourceType); if (fileType != null) { Element file = fileHandler.createFileElement(document, child, fileType); files.appendChild(file); } } rootElement.appendChild(folders); rootElement.appendChild(files); return getResponse(document); } protected Node getCorrectContentStorage(Node activePortal, Node webContent, String currentFolder) throws Exception { if (currentFolder == null || currentFolder.trim().length() == 0) return null; Node rootContentStorage = null; String rootContentStorageRelPath = null; if (activePortal != null && webContent == null) { rootContentStorage = getRootContentStorage(activePortal); rootContentStorageRelPath = "/" + activePortal.getName() + "/" + rootContentStorage.getName() + "/"; } else if (activePortal != null && webContent != null) { rootContentStorage = getRootContentStorage(webContent); rootContentStorageRelPath = "/" + activePortal.getName() + "/" + webContent.getName() + "/" + rootContentStorage.getName() + "/"; } if (currentFolder.equals(rootContentStorageRelPath)) return rootContentStorage; try { String correctStorageRelPath = currentFolder.replace(rootContentStorageRelPath, ""); correctStorageRelPath = correctStorageRelPath.substring(0, correctStorageRelPath.length() - 1); return rootContentStorage.getNode(correctStorageRelPath); } catch (Exception e) { return null; } } /** * Gets the response. * * @param document the document * @return the response */ protected Response getResponse(Document document) { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); cacheControl.setNoStore(true); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok(new DOMSource(document), MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } /** * Gets the jcr content. * * @param workspaceName the workspace name * @param jcrPath the jcr path * @return the jcr content * @throws Exception the exception */ protected Node getContent(String workspaceName, String jcrPath, String NodeTypeFilter, boolean isSystemSession) throws Exception { if (jcrPath == null || jcrPath.trim().length() == 0) return null; try { SessionProvider sessionProvider = isSystemSession ? WCMCoreUtils.getSystemSessionProvider() : WCMCoreUtils.getUserSessionProvider(); ManageableRepository repository = repositoryService.getCurrentRepository(); Session session = sessionProvider.getSession(workspaceName, repository); Node content = (Node) session.getItem(jcrPath); if (content.isNodeType("exo:taxonomyLink")) { content = linkManager.getTarget(content); } if (NodeTypeFilter==null || (NodeTypeFilter!=null && content.isNodeType(NodeTypeFilter)) ) return content; } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform getContent: ", e); } } return null; } /** * Gets the jcr content. * * @param workspaceName the workspace name * @param jcrPath the jcr path * @return the jcr content * @throws Exception the exception */ protected Node getContent(String workspaceName, String jcrPath) throws Exception { return getContent(workspaceName, jcrPath, null, true); } /** * Gets the web content. * * @param workspaceName the workspace name * @param jcrPath the jcr path * @return the web content * @throws Exception the exception */ protected Node getWebContent(String workspaceName, String jcrPath) throws Exception { return getContent(workspaceName, jcrPath, "exo:webContent", true); } protected Node getCurrentPortalNode(String jcrPath, String runningPortal, Node sharedPortal) throws Exception { if (jcrPath == null || jcrPath.length() == 0) return null; Node currentPortal = null; List<Node> livePortaNodes = new ArrayList<Node>(); SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); try { livePortaNodes = livePortalManagerService.getLivePortals(sessionProvider); if (sharedPortal != null) livePortaNodes.add(sharedPortal); for (Node portalNode : livePortaNodes) { String portalPath = portalNode.getPath(); if (jcrPath.startsWith(portalPath)) currentPortal = portalNode; } if (currentPortal == null) currentPortal = livePortalManagerService.getLivePortal(sessionProvider, runningPortal); return currentPortal; } catch (Exception e) { return null; } } }
18,480
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
LinkConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/fckeditor/LinkConnector.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.connector.fckeditor; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import org.exoplatform.ecm.connector.fckeditor.FCKUtils; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.portal.PortalFolderSchemaHandler; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.connector.BaseConnector; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * * @LevelAPI Experimental * * @anchor LinkConnector */ @Path("/wcmLink/") public class LinkConnector extends BaseConnector implements ResourceContainer { /** The link file handler. */ private LinkFileHandler linkFileHandler; /** The log. */ private static final Log LOG = ExoLogger.getLogger(LinkConnector.class.getName()); /** Instantiates a new link connector. */ public LinkConnector() { linkFileHandler = new LinkFileHandler(); } /** * Gets the folders and files. * * @param repositoryName The repository name. * @param workspaceName The workspace name. * @param jcrPath The JCR path. * @param currentFolder The current folder. * @param command The command. * @param type The type of folder/file. * @param currentPortal The current portal. * @return The folders and files. * @throws Exception The exception * * @anchor LinkConnector.getFoldersAndFiles */ @GET @Path("/getFoldersAndFiles/") // @OutputTransformer(XMLOutputTransformer.class) public Response getFoldersAndFiles(@QueryParam("repositoryName") String repositoryName, @QueryParam("workspaceName") String workspaceName, @QueryParam("jcrPath") String jcrPath, @QueryParam("currentFolder") String currentFolder, @QueryParam("currentPortal") String currentPortal, @QueryParam("command") String command, @QueryParam("type") String type) throws Exception { try { Response response = buildXMLResponseOnExpand(currentFolder, currentPortal, workspaceName, jcrPath, command); if (response != null) return response; } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform getFoldersAndFiles: ", e); } } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } /* * (non-Javadoc) * @see * org.exoplatform.wcm.connector.fckeditor.BaseConnector#buildXMLResponseOnExpand * (java.lang.String, java.lang.String, java.lang.String, java.lang.String, * java.lang.String) */ protected Response buildXMLResponseOnExpand(String currentFolder, String runningPortal, String workspaceName, String jcrPath, String command) throws Exception { SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); Node sharedPortal = livePortalManagerService.getLiveSharedPortal(sessionProvider); Node currentPortalNode = getCurrentPortalNode(jcrPath, runningPortal, sharedPortal); if (currentFolder.length() == 0 || "/".equals(currentFolder)) return buildXMLResponseForRoot(currentPortalNode, sharedPortal, command); String currentPortalRelPath = "/" + currentPortalNode.getName() + "/"; String sharePortalRelPath = "/" + sharedPortal.getName() + "/"; if (!currentPortalNode.getPath().equals(sharedPortal.getPath()) && currentFolder.startsWith(sharePortalRelPath)) { if (currentFolder.equals(sharePortalRelPath)) { return buildXMLResponseForPortal(sharedPortal, null, command); } Node currentContentStorageNode = getCorrectContentStorage(sharedPortal, null, currentFolder); return buildXMLResponseForContentStorage(currentContentStorageNode, command); } else if (!currentPortalNode.getPath().equals(sharedPortal.getPath()) && currentFolder.startsWith(currentPortalRelPath)) { return buildXMLResponseCommon(currentPortalNode, null, currentFolder, command); } else { return buildXMLResponseCommon(sharedPortal, null, currentFolder, command); } } /* * (non-Javadoc) * @seeorg.exoplatform.wcm.connector.fckeditor.BaseConnector# * buildXMLResponseForContentStorage(javax.jcr.Node, java.lang.String) */ protected Response buildXMLResponseForContentStorage(Node node, String command) throws Exception { Element rootElement = FCKUtils.createRootElement(command, node, folderHandler.getFolderType(node)); Document document = rootElement.getOwnerDocument(); Element folders = document.createElement("Foders"); Element files = document.createElement("Files"); for (NodeIterator iterator = node.getNodes(); iterator.hasNext();) { Node child = iterator.nextNode(); if (child.isNodeType(FCKUtils.EXO_HIDDENABLE)) continue; String folderType = folderHandler.getFolderType(child); if (folderType != null) { Element folder = folderHandler.createFolderElement(document, child, folderType); folders.appendChild(folder); } String sourceType = getContentStorageType(); String fileType = linkFileHandler.getFileType(child, sourceType); if (fileType != null) { Element file = linkFileHandler.createFileElement(document, child, fileType); files.appendChild(file); } } rootElement.appendChild(folders); rootElement.appendChild(files); return getResponse(document); } /* * (non-Javadoc) * @see * org.exoplatform.wcm.connector.fckeditor.BaseConnector#getRootContentStorage * (javax.jcr.Node) */ @Override protected Node getRootContentStorage(Node parentNode) throws Exception { try { PortalFolderSchemaHandler folderSchemaHandler = webSchemaConfigService. getWebSchemaHandlerByType(PortalFolderSchemaHandler.class); return folderSchemaHandler.getLinkFolder(parentNode); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug(e); } return null; } } /* * (non-Javadoc) * @see * org.exoplatform.wcm.connector.fckeditor.BaseConnector#getContentStorageType * () */ @Override protected String getContentStorageType() throws Exception { return FCKUtils.LINK_TYPE; } }
8,145
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DocumentLinkHandler.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/fckeditor/DocumentLinkHandler.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.connector.fckeditor; import javax.jcr.Node; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.ecm.connector.fckeditor.FCKFileHandler; 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.security.IdentityConstants; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.core.WCMConfigurationService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /* * Created by The eXo Platform SAS Author : Anh Do Ngoc anh.do@exoplatform.com * Sep 26, 2008 */ /** * The Class DocumentLinkHandler. */ public class DocumentLinkHandler extends FCKFileHandler { /** The base uri. */ private String baseURI; /** The current portal. */ private String currentPortal; /** * Instantiates a new document link handler. */ public DocumentLinkHandler() { super(ExoContainerContext.getCurrentContainer()); } /** * Sets the base uri. * * @param baseURI the new base uri */ public void setBaseURI(String baseURI) { this.baseURI = baseURI; } /* (non-Javadoc) * @see org.exoplatform.ecm.connector.fckeditor.FCKFileHandler#getFileURL(javax.jcr.Node) */ public String getFileURL(final Node node) throws Exception { String accessMode = "private"; AccessControlList acl = ((ExtendedNode) node).getACL(); for (AccessControlEntry entry : acl.getPermissionEntries()) { if (entry.getIdentity().equalsIgnoreCase(IdentityConstants.ANY) && entry.getPermission().equalsIgnoreCase(PermissionType.READ)) { accessMode = "public"; break; } } String repository = ((ManageableRepository) node.getSession().getRepository()).getConfiguration() .getName(); String workspace = node.getSession().getWorkspace().getName(); String nodePath = node.getPath(); StringBuilder builder = new StringBuilder(); if (node.isNodeType(NodetypeConstant.NT_FILE)) { if ("public".equals(accessMode)) { return builder.append(baseURI) .append("/jcr/") .append(repository) .append("/") .append(workspace) .append(nodePath) .toString(); } return builder.append(baseURI) .append("/private/jcr/") .append(repository) .append("/") .append(workspace) .append(nodePath) .toString(); } WCMConfigurationService configurationService = WCMCoreUtils.getService(WCMConfigurationService.class); String parameterizedPageViewerURI = configurationService. getRuntimeContextParam(WCMConfigurationService.PARAMETERIZED_PAGE_URI); return baseURI.replace("/rest", "") + "/" + accessMode + "/" + currentPortal + parameterizedPageViewerURI + "/" + repository + "/" + workspace + nodePath; } /** * Sets the current portal. * * @param currentPortal the new current portal */ public void setCurrentPortal(String currentPortal) { this.currentPortal = currentPortal; } /** * Gets the current portal. * * @return the current portal */ public String getCurrentPortal() { return this.currentPortal; } }
4,496
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DriverConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/fckeditor/DriverConnector.java
/* * Copyright (C) 2003-2007 eXo Platform SEA. * * 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.connector.fckeditor; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.annotation.security.RolesAllowed; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import org.apache.commons.lang3.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.exoplatform.container.xml.InitParams; import org.exoplatform.ecm.connector.fckeditor.FCKUtils; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.documents.DocumentService; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.impl.Utils; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.resources.ResourceBundleService; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.Identity; import org.exoplatform.services.security.IdentityRegistry; import org.exoplatform.services.security.MembershipEntry; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.portal.PortalFolderSchemaHandler; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.services.wcm.webcontent.WebContentSchemaHandler; import org.exoplatform.wcm.connector.BaseConnector; import org.exoplatform.wcm.connector.FileUploadHandler; import org.exoplatform.wcm.connector.handler.FCKFileHandler; import jakarta.servlet.http.HttpServletRequest; /** * Returns a list of drives/folders/documents in a specified location for a given user. Also, it processes the file uploading action. * * {{{{portalname}}}}: The name of portal. * {{{{restcontextname}}}}: The context name of REST web application which is deployed to the "{{{{portalname}}}}" portal. * * @LevelAPI Provisional * @anchor DriverConnector */ @Path("/wcmDriver/") public class DriverConnector extends BaseConnector implements ResourceContainer { /** The Constant FILE_TYPE_WEBCONTENT. */ public static final String FILE_TYPE_WEBCONTENT = "Web Contents"; /** The Constant FILE_TYPE_DMSDOC. */ public static final String FILE_TYPE_DMSDOC = "DMS Documents"; /** The Constant FILE_TYPE_MEDIAS. */ public static final String FILE_TYPE_MEDIAS = "Medias"; /** The Constant FILE_TYPE_MEDIAS. */ public static final String FILE_TYPE_ALL = "All"; /** The Constant FILE_TYPE_IMAGE. */ public static final String FILE_TYPE_IMAGE = "Image"; /** The Constant FILE_TYPE_SIMPLE_IMAGE for JPG/JPEG, PNG and GIF. */ public static final String FILE_TYPE_SIMPLE_IMAGE = "SimpleImage"; /** The Constant MEDIA_MIMETYPE. */ public static final String[] MEDIA_MIMETYPE = new String[]{"application", "image", "audio", "video"}; /** The Constant MEDIA_MIMETYPE. */ public static final String[] IMAGE_MIMETYPE = new String[]{"image"}; /** The Constant MEDIA_MIMETYPE. */ public static final String[] SIMPLE_IMAGE_MIMETYPE = new String[]{"image/png", "image/jpg", "image/jpeg", "image/gif"}; public static final String TYPE_FOLDER = "folder"; public static final String TYPE_EDITOR = "editor"; public static final String TYPE_CONTENT = "multi"; /** The log. */ private static final Log LOG = ExoLogger.getLogger(DriverConnector.class.getName()); private static final String OLD_APP = "oldApp"; /** The limit. */ private int limit; /** The file number limit on client side. */ private int limitCountClient_ = 3; /** The file number limit on server side. */ private int limitCountServer_ = 30; private List<String> browsableContent = new ArrayList<String>(); private ResourceBundleService resourceBundleService = null; private NodeFinder nodeFinder_ = null; private LinkManager linkManager_ = null; private String resourceBundleNames[]; /** Document service. */ private final DocumentService documentService; /** Cloud Drive service. */ private final CloudDriveService cloudDrives; /** * Instantiates a new driver connector. * * @param params The init parameters. * @param documentService the document service * @param cloudDrives the cloud drives */ public DriverConnector(InitParams params, DocumentService documentService, CloudDriveService cloudDrives) { this.documentService = documentService; this.cloudDrives = cloudDrives; this.limit = Integer.parseInt(params.getValueParam("upload.limit.size").getValue()); if (params.getValueParam("upload.limit.count.client") != null) { this.limitCountClient_ = Integer.parseInt(params.getValueParam("upload.limit.count.client").getValue()); } if (params.getValueParam("upload.limit.count.server") != null) { this.limitCountServer_ = Integer.parseInt(params.getValueParam("upload.limit.count.server").getValue()); } if (params.getValueParam("exo.ecms.content.browsable") != null) { this.browsableContent = Arrays.asList((params.getValueParam("exo.ecms.content.browsable").getValue()).split("\\s*,\\s*")); } } /** * Gets the maximum size of the uploaded file. * @return The file size limit. */ public int getLimitSize() { return limit; } /** * Gets the maximum number of files uploaded from the client side. * @return The maximum number of files uploaded on the client side. */ public int getMaxUploadCount() { return limitCountClient_; } /** * Returns the driveName according to the nodePath param which is composed by the driveHomePath and the path of the node * @param nodePath the path of the webContent * @return the driveName * @throws Exception */ @GET @Path("/getDriveOfNode/") @RolesAllowed("users") public Response getDriveOfNode(@QueryParam("nodePath") String nodePath) throws Exception { DriveData drive = documentService.getDriveOfNode(nodePath); String driveName = null; if (drive != null) { driveName = drive.getName(); } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok(driveName, MediaType.TEXT_PLAIN).header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } /** * Returns a list of drives for the current user. * * @param lang The language of the drive name. * @return The drives. * @throws Exception The exception * * @anchor DriverConnector.getDrivers */ @GET @Path("/getDrivers/") @RolesAllowed("users") public Response getDrivers(@QueryParam("lang") String lang) throws Exception { ConversationState conversationState = ConversationState.getCurrent(); String userId = conversationState.getIdentity().getUserId(); List<DriveData> listDriver = getDriversByUserId(userId); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element rootElement = document.createElement("Connector"); document.appendChild(rootElement); rootElement.setAttribute("isUpload", "false"); rootElement.appendChild(appendDrivers(document, generalDrivers(listDriver), "General Drives", lang)); rootElement.appendChild(appendDrivers(document, groupDrivers(listDriver), "Group Drives", lang)); rootElement.appendChild(appendDrivers(document, personalDrivers(listDriver, userId), "Personal Drives", lang)); CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); cacheControl.setNoStore(true); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok(new DOMSource(document), MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } /** * Returns all folders and files in a given location. * * @param driverName The drive name. * @param currentFolder The current folder. * @param currentPortal The current portal. * @param repositoryName The repository name. * @param workspaceName The workspace name. * @param filterBy The type of filter. * @return The folders and files. * @throws Exception The exception * * @anchor DriverConnector.getFoldersAndFiles */ @GET @Path("/getFoldersAndFiles/") @RolesAllowed("users") public Response getFoldersAndFiles( @QueryParam("driverName") String driverName, @QueryParam("currentFolder") String currentFolder, @QueryParam("currentPortal") String currentPortal, @QueryParam("repositoryName") String repositoryName, @QueryParam("workspaceName") String workspaceName, @QueryParam("filterBy") String filterBy, @QueryParam("type") String type) throws Exception { try { RepositoryService repositoryService = WCMCoreUtils.getService(RepositoryService.class); ManageDriveService manageDriveService = WCMCoreUtils.getService(ManageDriveService.class); SessionProvider sessionProvider = WCMCoreUtils.getUserSessionProvider(); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); DriveData drive = manageDriveService.getDriveByName(Text.escapeIllegalJcrChars(driverName)); workspaceName = drive.getWorkspace(); Session session = sessionProvider.getSession(workspaceName, manageableRepository); Node node = getParentFolderNode(workspaceName, Text.escapeIllegalJcrChars(driverName), Text.escapeIllegalJcrChars(currentFolder)); return buildXMLResponseForChildren(node, null, filterBy, session, currentPortal, currentFolder, Text.escapeIllegalJcrChars(driverName), type); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform getFoldersAndFiles: ", e); } } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } /** * Checks if the drive can upload a new file. * * @return Response containing the status indicating if upload is available. * @throws Exception * @anchor DriverConnector.checkUploadAvailable */ @GET @Path("/uploadFile/checkUploadAvailable/") @RolesAllowed("users") public Response checkUploadAvailable() throws Exception { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); String msg = fileUploadHandler.getUploadingFileCount() < limitCountServer_ ? "uploadAvailable" : "uploadNotAvailable"; return Response.ok(createDOMResponse(msg), MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } /** * Uploads a file. * * @param uploadId The Id of the uploaded file. * @return The response. * @throws Exception The exception * * @anchor DriverConnector.uploadFile */ @POST @Path("/uploadFile/upload/") @RolesAllowed("users") public Response uploadFile(@Context HttpServletRequest servletRequest, @QueryParam("uploadId") String uploadId) throws Exception { //check if number of file uploading is greater than the limit // if (fileUploadHandler.getUploadingFileCount() >= limitCountServer_) { // CacheControl cacheControl = new CacheControl(); // cacheControl.setNoCache(true); // DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); // return Response.ok(createDOMResponse("uploadNotAvailable"), MediaType.TEXT_XML) // .cacheControl(cacheControl) // .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) // .build(); // } return fileUploadHandler.upload(servletRequest, uploadId, limit); } /** * Check the status of uploading a file, such as aborting, deleting or progressing the file. * * @param repositoryName The repository name. * @param workspaceName The workspace name. * @param driverName The drive name. * @param currentFolder The current folder. * @param currentPortal The portal name. * @param language The language file. * @param fileName The file name. * @return The response * @throws Exception The exception * * @anchor DriverConnector.checkExistence */ @GET @Path("/uploadFile/checkExistence/") @RolesAllowed("users") public Response checkExistence( @QueryParam("repositoryName") String repositoryName, @QueryParam("workspaceName") String workspaceName, @QueryParam("driverName") String driverName, @QueryParam("currentFolder") String currentFolder, @QueryParam("currentPortal") String currentPortal, @QueryParam("language") String language, @QueryParam("fileName") String fileName) throws Exception { try { currentFolder = URLDecoder.decode(currentFolder, StandardCharsets.UTF_8); // Check file existence Node currentFolderNode = getParentFolderNode(workspaceName, Text.escapeIllegalJcrChars(driverName), Text.escapeIllegalJcrChars(currentFolder)); return fileUploadHandler.checkExistence(currentFolderNode, fileName); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform processUpload: ", e); } } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } /** * Clean file name * * @param fileName original file name * @return the response */ @GET @Path("/uploadFile/cleanName") @RolesAllowed("users") public Response cleanName (@QueryParam("fileName") String fileName) throws Exception{ return fileUploadHandler.cleanName(fileName); } /** * Controls the process of uploading a file, such as aborting, deleting or progressing the file. * * @param repositoryName The repository name. * @param workspaceName The workspace name. * @param driverName The drive name. * @param currentFolder The current folder. * @param currentPortal The current portal. * @param userId The user identity. * @param jcrPath The path of the file. * @param action The action. * @param language The language. * @param fileName The file name. * @param uploadId The Id of upload. * @param existenceAction Checks if an action exists or not. * @return The response. * @throws Exception The exception * * @anchor DriverConnector.processUpload */ @GET @Path("/uploadFile/control/") @RolesAllowed("users") public Response processUpload( @QueryParam("repositoryName") String repositoryName, @QueryParam("workspaceName") String workspaceName, @QueryParam("driverName") String driverName, @QueryParam("currentFolder") String currentFolder, @QueryParam("currentPortal") String currentPortal, @QueryParam("userId") String userId, @QueryParam("jcrPath") String jcrPath, @QueryParam("action") String action, @QueryParam("language") String language, @QueryParam("fileName") String fileName, @QueryParam("uploadId") String uploadId, @QueryParam("existenceAction") String existenceAction, @QueryParam("srcAction") String srcAction) throws Exception { try { // Check upload status Response msgResponse = fileUploadHandler.checkStatus(uploadId, language); if (msgResponse != null) return msgResponse; if ((repositoryName != null) && (workspaceName != null) && (driverName != null) && (currentFolder != null)) { ManageDriveService manageDriveService = WCMCoreUtils.getService(ManageDriveService.class); workspaceName = workspaceName != null ? workspaceName : manageDriveService.getDriveByName(Text.escapeIllegalJcrChars(driverName)) .getWorkspace(); currentFolder = URLDecoder.decode(currentFolder, StandardCharsets.UTF_8); Node currentFolderNode = getParentFolderNode(workspaceName, Text.escapeIllegalJcrChars(driverName), Text.escapeIllegalJcrChars(currentFolder)); fileName = Text.escapeIllegalJcrChars(fileName); fileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8); return createProcessUploadResponse(workspaceName, currentFolderNode, currentPortal, userId, Text.escapeIllegalJcrChars(jcrPath), action, language, fileName, uploadId, existenceAction); } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform processUpload: ", e); } } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } /** * Gets the drives by user Id. * * @param userId the user Id * * @return the drives by user Id * * @throws Exception the exception */ private List<DriveData> getDriversByUserId(String userId) throws Exception { ManageDriveService driveService = WCMCoreUtils.getService(ManageDriveService.class); List<String> userRoles = getMemberships(userId); return driveService.getDriveByUserRoles(userId, userRoles); } /** * Appends drives. * * @param document The document. * @param driversList The drivers list. * @param groupName The group name. * * @return The element. */ private Element appendDrivers(Document document, List<DriveData> driversList, String groupName, String lang) throws Exception { Element folders = document.createElement("Folders"); folders.setAttribute("name", resolveDriveLabel(groupName, lang)); folders.setAttribute("isUpload", "false"); for (DriveData driver : driversList) { String repository = WCMCoreUtils.getRepository().getConfiguration().getName(); String workspace = driver.getWorkspace(); String path = driver.getHomePath(); String name = driver.getName(); Element folder = document.createElement("Folder"); NodeLocation nodeLocation = new NodeLocation(repository, workspace, path); Node driveNode = NodeLocation.getNodeByLocation(nodeLocation); if(driveNode == null) continue; folder.setAttribute("name", name); folder.setAttribute("label", resolveDriveLabel(name, lang)); folder.setAttribute("url", FCKUtils.createWebdavURL(driveNode)); folder.setAttribute("folderType", "exo:drive"); folder.setAttribute("path", path); folder.setAttribute("repository", repository); folder.setAttribute("workspace", workspace); CloudDrive cloudDrive = cloudDrives.findDrive(driver.getWorkspace(), driver.getHomePath()); folder.setAttribute("isCloudDrive", String.valueOf(cloudDrive != null)); if (cloudDrive != null) { folder.setAttribute("cloudProvider", cloudDrive.getUser().getProvider().getId()); } folder.setAttribute("isUpload", "true"); folder.setAttribute("hasFolderChild", String.valueOf(this.hasFolderChild(driveNode))); folder.setAttribute("nodeTypeCssClass", Utils.getNodeTypeIcon(driveNode, "uiIcon16x16")); folders.appendChild(folder); } return folders; } private String resolveDriveLabel(String name, String lang) { if (resourceBundleService == null) { resourceBundleService = WCMCoreUtils.getService(ResourceBundleService.class); resourceBundleNames = resourceBundleService.getSharedResourceBundleNames(); } if (StringUtils.isBlank(lang)) { lang = Locale.ENGLISH.getLanguage(); } Locale locale = new Locale(lang); ResourceBundle sharedResourceBundle = resourceBundleService.getResourceBundle(resourceBundleNames, locale); try { sharedResourceBundle = resourceBundleService.getResourceBundle(resourceBundleNames, locale); String key = "ContentSelector.title." + name.replaceAll(" ", ""); if(sharedResourceBundle.containsKey(key)) { return sharedResourceBundle.getString(key); } else { return getDriveTitle(name); } } catch (MissingResourceException e) { if (LOG.isDebugEnabled()) { LOG.debug(e.getMessage()); } } return name; } /** * Personal drivers. * * @param driveList the drive list * * @return the list< drive data> * @throws Exception */ private List<DriveData> personalDrivers(List<DriveData> driveList, String userId) throws Exception { List<DriveData> personalDrivers = new ArrayList<DriveData>(); NodeHierarchyCreator nodeHierarchyCreator = WCMCoreUtils.getService(NodeHierarchyCreator.class); SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); Node userNode = nodeHierarchyCreator.getUserNode(sessionProvider, userId); for(DriveData drive : driveList) { String driveHomePath = Utils.getPersonalDrivePath(drive.getHomePath(), userId); if(driveHomePath.startsWith(userNode.getPath())) { drive.setHomePath(driveHomePath); personalDrivers.add(drive); } } Collections.sort(personalDrivers); return personalDrivers; } /** * Group drivers. * * @param driverList the driver list * @return the list< drive data> * @throws Exception the exception */ private List<DriveData> groupDrivers(List<DriveData> driverList) throws Exception { ManageDriveService driveService = WCMCoreUtils.getService(ManageDriveService.class); String currentUserId = ConversationState.getCurrent().getIdentity().getUserId(); List<String> userRoles = this.getMemberships(currentUserId); return driveService.getGroupDrives(currentUserId, userRoles); } /** * General drivers. * * @param driverList the driver list * * @return the list< drive data> * * @throws Exception the exception */ private List<DriveData> generalDrivers(List<DriveData> driverList) throws Exception { List<DriveData> generalDrivers = new ArrayList<DriveData>(); NodeHierarchyCreator nodeHierarchyCreator = WCMCoreUtils.getService(NodeHierarchyCreator.class); String userPath = nodeHierarchyCreator.getJcrPath(BasePath.CMS_USERS_PATH); String groupPath = nodeHierarchyCreator.getJcrPath(BasePath.CMS_GROUPS_PATH); for(DriveData drive : driverList) { if((!drive.getHomePath().startsWith(userPath) && !drive.getHomePath().startsWith(groupPath)) || drive.getHomePath().equals(userPath)) { generalDrivers.add(drive); } } return generalDrivers; } /** * Gets the memberships. * * @param userId the user id * * @return the memberships * * @throws Exception the exception */ private List<String> getMemberships(String userId) throws Exception { List<String> userMemberships = new ArrayList<String> (); userMemberships.add(userId); // here we must retrieve memberships of the user using the // IdentityRegistry Service instead of Organization Service to // allow JAAS based authorization Collection<MembershipEntry> memberships = getUserMembershipsFromIdentityRegistry(userId); if (memberships != null) { for (MembershipEntry membership : memberships) { String role = membership.getMembershipType() + ":" + membership.getGroup(); userMemberships.add(role); } } return userMemberships; } /** * this method retrieves memberships of the user having the given id using the * IdentityRegistry service instead of the Organization service to allow JAAS * based authorization * * @param authenticatedUser the authenticated user id * @return a collection of MembershipEntry */ private static Collection<MembershipEntry> getUserMembershipsFromIdentityRegistry(String authenticatedUser) { IdentityRegistry identityRegistry = WCMCoreUtils.getService(IdentityRegistry.class); Identity currentUserIdentity = identityRegistry.getIdentity(authenticatedUser); return currentUserIdentity.getMemberships(); } private Response buildXMLResponseForChildren(Node node, String command, String filterBy, Session session, String currentPortal, String currentParentFolder, String nodeDriveName, String type) throws Exception { TemplateService templateService = WCMCoreUtils.getService(TemplateService.class); Element rootElement = FCKUtils.createRootElement(command, node, folderHandler.getFolderType(node)); NodeList nodeList = rootElement.getElementsByTagName("CurrentFolder"); Element currentFolder = (Element) nodeList.item(0); currentFolder.setAttribute("isUpload", "true"); Document document = rootElement.getOwnerDocument(); Element folders = document.createElement("Folders"); folders.setAttribute("isUpload", "true"); Element files = document.createElement("Files"); files.setAttribute("isUpload", "true"); Node sourceNode = null; Node checkNode = null; Node targetNode = null; if (node.isNodeType(NodetypeConstant.EXO_SYMLINK)) { targetNode = linkManager.getTarget(node); } else { targetNode = node; } List<Node> childList = new ArrayList<Node>(); for (NodeIterator iterator = targetNode.getNodes(); iterator.hasNext();) { childList.add(iterator.nextNode()); } Collections.sort(childList,new NodeTitleComparator()); for (Node child:childList) { String fileType = null; if (child.isNodeType(FCKUtils.EXO_HIDDENABLE)) continue; if(TYPE_FOLDER.equals(type) && templateService.isManagedNodeType(child.getPrimaryNodeType().getName())) continue; if(child.isNodeType("exo:symlink") && child.hasProperty("exo:uuid")) { sourceNode = linkManager.getTarget(child); } else { sourceNode = child; } checkNode = sourceNode != null ? sourceNode : child; String folderPath = child.getPath(); folderPath = folderPath.substring(folderPath.lastIndexOf("/") + 1, folderPath.length()); String childRelativePath = StringUtils.isEmpty(currentParentFolder) ? folderPath : currentParentFolder.concat("/") .concat(folderPath); if (isFolder(checkNode, type)) { // Get node name from node path to fix same name problem (ECMS-3586) String nodePath = child.getPath(); Element folder = createFolderElement(document, checkNode, checkNode.getPrimaryNodeType().getName(), nodePath.substring(nodePath.lastIndexOf("/") + 1, nodePath.length()), childRelativePath, nodeDriveName, type); folders.appendChild(folder); } if (FILE_TYPE_ALL.equals(filterBy) && (checkNode.isNodeType(NodetypeConstant.EXO_WEBCONTENT) || !isFolder(checkNode, type))) { fileType = FILE_TYPE_ALL; } if (FILE_TYPE_WEBCONTENT.equals(filterBy)) { if(checkNode.isNodeType(NodetypeConstant.EXO_WEBCONTENT)) { fileType = FILE_TYPE_WEBCONTENT; } } if (FILE_TYPE_MEDIAS.equals(filterBy) && isMediaType(checkNode)){ fileType = FILE_TYPE_MEDIAS; } if (FILE_TYPE_DMSDOC.equals(filterBy) && isDMSDocument(checkNode)) { fileType = FILE_TYPE_DMSDOC; } if (FILE_TYPE_IMAGE.equals(filterBy) && isImageType(checkNode)) { fileType = FILE_TYPE_IMAGE; } if (FILE_TYPE_SIMPLE_IMAGE.equals(filterBy) && isSimpleImageType(checkNode)) { fileType = FILE_TYPE_SIMPLE_IMAGE; } if (fileType != null) { Element file = FCKFileHandler.createFileElement(document, fileType, checkNode, child, currentPortal, childRelativePath, linkManager); files.appendChild(file); } } rootElement.appendChild(folders); rootElement.appendChild(files); return getResponse(document); } /** * Checks if is folder and is not web content. * * @param checkNode the check node * * @return true, if is folder and is not web content * * @throws RepositoryException the repository exception */ private boolean isFolder(Node checkNode, String type) throws RepositoryException { try { if (isDocument(checkNode, type)) return false; } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } return checkNode.isNodeType(NodetypeConstant.NT_UNSTRUCTURED) || checkNode.isNodeType(NodetypeConstant.NT_FOLDER) || checkNode.isNodeType(NodetypeConstant.EXO_TAXONOMY); } /** * Check if specific node has child which is type of nt:folder or nt:unstructured. * * @param checkNode The node to be checked * @return True if the folder has some child. * @throws Exception */ private boolean hasFolderChild(Node checkNode) throws Exception { return (Utils.hasChild(checkNode, NodetypeConstant.NT_UNSTRUCTURED) || Utils.hasChild(checkNode, NodetypeConstant.NT_FOLDER)); } /** * Checks if is dMS document.(not including free layout webcontent and media and article) * * @param node the node * * @return true, if is dMS document * * @throws Exception the exception */ private boolean isDMSDocument(Node node) throws Exception { TemplateService templateService = WCMCoreUtils.getService(TemplateService.class); List<String> dmsDocumentListTmp = templateService.getDocumentTemplates(); List<String> dmsDocumentList = new ArrayList<String>(); dmsDocumentList.addAll(dmsDocumentListTmp); dmsDocumentList.remove(NodetypeConstant.EXO_WEBCONTENT); for (String documentType : dmsDocumentList) { if (node.getPrimaryNodeType().isNodeType(documentType) && !isMediaType(node) && !node.isNodeType(NodetypeConstant.EXO_WEBCONTENT)) { return true; } } return false; } /** * Checks if specific node is document * * @param node specific Node * @return true: is document, false: not document * @throws RepositoryException */ private boolean isDocument(Node node, String type) throws RepositoryException { TemplateService templateService = WCMCoreUtils.getService(TemplateService.class); List<String> documentTypeList = templateService.getDocumentTemplates(); if (TYPE_EDITOR.equals(type) && browsableContent != null) { for (String browsableDocument : browsableContent) { documentTypeList.remove(browsableDocument); } } for (String documentType : documentTypeList) { if (node.getPrimaryNodeType().isNodeType(documentType)) { return true; } } return false; } /** * Checks if is media type. * * @param node the node * * @return true, if is media type */ private boolean isMediaType(Node node){ String mimeType = ""; try { mimeType = node.getNode("jcr:content").getProperty("jcr:mimeType").getString(); } catch (Exception e) { return false; } for(String type: MEDIA_MIMETYPE) { if(mimeType.contains(type)){ return true; } } return false; } /** * Checks if is image of type JPG, JPEG, PNG or GIF. * * @param node the node * * @return true, if is simple image type */ private boolean isSimpleImageType(Node node){ String mimeType = ""; try { mimeType = node.getNode("jcr:content").getProperty("jcr:mimeType").getString(); } catch (Exception e) { return false; } for(String type: SIMPLE_IMAGE_MIMETYPE) { if(mimeType.equalsIgnoreCase(type)){ return true; } } return false; } /** * Checks if is image type. * * @param node the node * * @return true, if is image type */ private boolean isImageType(Node node){ String mimeType = ""; try { mimeType = node.getNode("jcr:content").getProperty("jcr:mimeType").getString(); } catch (Exception e) { return false; } for(String type: IMAGE_MIMETYPE) { if(mimeType.contains(type)){ return true; } } return false; } /* (non-Javadoc) * @see org.exoplatform.wcm.connector.BaseConnector#getContentStorageType() */ @Override protected String getContentStorageType() throws Exception { return null; } /* (non-Javadoc) * @see org.exoplatform.wcm.connector.BaseConnector#getRootContentStorage(javax.jcr.Node) */ @Override protected Node getRootContentStorage(Node node) throws Exception { try { PortalFolderSchemaHandler folderSchemaHandler = webSchemaConfigService .getWebSchemaHandlerByType(PortalFolderSchemaHandler.class); return folderSchemaHandler.getImagesFolder(node); } catch (Exception e) { WebContentSchemaHandler webContentSchemaHandler = webSchemaConfigService .getWebSchemaHandlerByType(WebContentSchemaHandler.class); return webContentSchemaHandler.getImagesFolders(node); } } /** * * @param workspaceName The workspace name. * @param currentFolderNode The current folder. * @param siteName The portal name. * @param userId The user Id. * @param jcrPath The path of the file. * @param action The action. * @param language The language. * @param fileName The file name. * @param uploadId The Id of upload. * @param existenceAction Checks if an action exists. * @return the response * @throws Exception the exception */ protected Response createProcessUploadResponse(String workspaceName, Node currentFolderNode, String siteName, String userId, String jcrPath, String action, String language, String fileName, String uploadId, String existenceAction) throws Exception { if (FileUploadHandler.SAVE_ACTION.equals(action)) { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); return fileUploadHandler.saveAsNTFile(workspaceName, currentFolderNode, uploadId, fileName, language,OLD_APP , siteName, userId, existenceAction); }else if(FileUploadHandler.SAVE_NEW_VERSION_ACTION.equals(action)){ CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); return fileUploadHandler.saveAsNTFile(workspaceName, currentFolderNode, uploadId, fileName, language,OLD_APP , siteName, userId, existenceAction,true); } return fileUploadHandler.control(uploadId, action); } /** * Gets the parent folder node. * * @param workspaceName the workspace name * @param driverName the driver name * @param currentFolder the current folder * * @return the parent folder node * * @throws Exception the exception */ private Node getParentFolderNode(String workspaceName, String driverName, String currentFolder) throws Exception { SessionProvider sessionProvider = WCMCoreUtils.getUserSessionProvider(); ManageableRepository manageableRepository = WCMCoreUtils.getRepository(); Session session = sessionProvider.getSession(workspaceName, manageableRepository); ManageDriveService manageDriveService = WCMCoreUtils.getService(ManageDriveService.class); DriveData driveData = manageDriveService.getDriveByName(driverName); String parentPath = (driveData != null ? driveData.getHomePath() : ""); NodeHierarchyCreator nodeHierarchyCreator = WCMCoreUtils.getService(NodeHierarchyCreator.class); if(driveData != null && driveData.getHomePath().startsWith(nodeHierarchyCreator.getJcrPath(BasePath.CMS_USERS_PATH) + "/${userId}")) { parentPath = Utils.getPersonalDrivePath(driveData.getHomePath(), ConversationState.getCurrent().getIdentity().getUserId()); }; parentPath += ((currentFolder != null && currentFolder.length() != 0) ? "/" : "") + currentFolder; parentPath = parentPath.replace("//", "/"); //return result; return getTargetNode(session, parentPath); } private Node getTargetNode(Session session, String path) throws Exception { Node node = null; if (linkManager_ == null) { linkManager_ = WCMCoreUtils.getService(LinkManager.class); } if (nodeFinder_ == null) { nodeFinder_ = WCMCoreUtils.getService(NodeFinder.class); } node = (Node)nodeFinder_.getItem(session, path, true); return node; } private Element createFolderElement(Document document, Node child, String folderType, String childName, String childCurrentFolder, String nodeDriveName, String type) throws Exception { Element folder = document.createElement("Folder"); folder.setAttribute("name", childName.replaceAll("%", "%25")); folder.setAttribute("title", Utils.getTitle(child).replaceAll("%", "%25")); folder.setAttribute("url", FCKUtils.createWebdavURL(child)); folder.setAttribute("folderType", folderType); folder.setAttribute("currentFolder", childCurrentFolder); if(TYPE_FOLDER.equals(type) || TYPE_CONTENT.equals(type)) { boolean hasFolderChild = (getChildOfType(child, NodetypeConstant.NT_UNSTRUCTURED, type) != null) || (getChildOfType(child, NodetypeConstant.NT_FOLDER, type) != null); folder.setAttribute("hasFolderChild", String.valueOf(hasFolderChild)); }else{ folder.setAttribute("hasFolderChild", String.valueOf(this.hasFolderChild(child))); } folder.setAttribute("path", child.getPath()); folder.setAttribute("isUpload", "true"); folder.setAttribute("nodeTypeCssClass", Utils.getNodeTypeIcon(child, "uiIcon16x16")); if (nodeDriveName!=null && nodeDriveName.length()>0) folder.setAttribute("nodeDriveName", nodeDriveName); return folder; } /** * Check isFolder (skip all templateNodetype) * @param node * @param childType * @return * @throws Exception */ private Node getChildOfType(Node node, String childType, String type) throws Exception { TemplateService templateService = WCMCoreUtils.getService(TemplateService.class); if (node == null) { return null; } NodeIterator iter = node.getNodes(); while (iter.hasNext()) { Node child = iter.nextNode(); if (!isDocument(child, type) && child.isNodeType(childType) && !templateService.isManagedNodeType(child.getPrimaryNodeType().getName()) && !"exo:thumbnails".equals(child.getPrimaryNodeType().getName())) { return child; } } return null; } /** * returns a DOMSource object containing given message * @param message the message * @return DOMSource object * @throws Exception */ private DOMSource createDOMResponse(String message) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element rootElement = doc.createElement(message); doc.appendChild(rootElement); return new DOMSource(doc); } private static class NodeTitleComparator implements Comparator<Node>{ @Override public int compare(Node node1, Node node2) { try{ String titleNode1 = Utils.getTitle(node1); String titleNode2 = Utils.getTitle(node2); return titleNode1.compareToIgnoreCase(titleNode2) ; }catch (Exception e) { return 0; } } } public String getDriveTitle(String name) { if (name.startsWith(".")) { String groupLabel = getGroupLabel(name); if (groupLabel == null) { groupLabel = getGroupLabel(name, !name.startsWith("/spaces")); } return groupLabel; } else { return name; } } public String getGroupLabel(String groupId, boolean isFull) { String ret = groupId.replace(".", " / "); if (!isFull) { if (ret.startsWith(" / spaces")) { return ret.substring(ret.lastIndexOf("/") + 1).trim(); } int count = 0; int slashPosition = -1; for (int i = 0; i < ret.length(); i++) { if ('/' == ret.charAt(i)) { if (++count == 4) { slashPosition = i; break; } } } if (slashPosition > 0) { ret = ret.substring(0, slashPosition) + "..."; } else if (ret.length() > 70) { ret = ret.substring(0, 70) + "..."; } } return ret; } public String getGroupLabel(String name) { try { RepositoryService repoService = WCMCoreUtils.getService(RepositoryService.class); NodeHierarchyCreator nodeHierarchyCreator = WCMCoreUtils.getService(NodeHierarchyCreator.class); String groupPath = nodeHierarchyCreator.getJcrPath(BasePath.CMS_GROUPS_PATH); String absPath = groupPath + name.replace(".", "/"); ManageableRepository currentRepository = repoService.getCurrentRepository(); String workspace = currentRepository.getConfiguration().getDefaultWorkspaceName(); return getNode(workspace, absPath).getProperty(NodetypeConstant.EXO_LABEL).getString(); } catch (Exception e) { return null; } } public Node getNode(String workspace, String absPath) throws Exception { RepositoryService repoService = WCMCoreUtils.getService(RepositoryService.class); ManageableRepository currentRepository = repoService.getCurrentRepository(); Node groupNode = (Node) WCMCoreUtils.getSystemSessionProvider().getSession(workspace, currentRepository).getItem(absPath); return groupNode; } }
46,127
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PortalLinkConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/fckeditor/PortalLinkConnector.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.connector.fckeditor; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.ResourceBundle; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.dom.DOMSource; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.exoplatform.commons.utils.ISO8601; import org.exoplatform.commons.utils.PageList; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.component.RequestLifeCycle; import org.exoplatform.container.xml.InitParams; 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.PortalConfig; import org.exoplatform.portal.mop.page.PageContext; import org.exoplatform.portal.mop.page.PageKey; 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.mop.user.UserPortalContext; import org.exoplatform.portal.webui.util.NavigationUtils; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import jakarta.servlet.ServletContext; /** * Returns a page URI for a given location. * * @LevelAPI Provisional * * @anchor PortalLinkConnector */ @Path("/portalLinks/") public class PortalLinkConnector implements ResourceContainer { /** The RESOURC e_ type. */ final private String RESOURCE_TYPE = "PortalPageURI"; /** The portal data storage. */ private DataStorage portalDataStorage; /** The portal user acl. */ private UserACL portalUserACL; /** The servlet context. */ private ServletContext servletContext; /** The log. */ private static final Log LOG = ExoLogger.getLogger(PortalLinkConnector.class.getName()); /** 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"; /** * Instantiates a new portal link connector. * * @param params The params. * @param dataStorage The data storage. * @param userACL The user ACL. * @param servletContext The servlet context. * * @throws Exception the exception */ public PortalLinkConnector(InitParams params, DataStorage dataStorage, UserACL userACL, ServletContext servletContext) throws Exception { this.portalDataStorage = dataStorage; this.portalUserACL = userACL; this.servletContext = servletContext; } /** * Gets the page URI. * * @param currentFolder The current folder. * @param command The command to get folders/files. * @param type The file type. * @return The page URI. * @throws Exception The exception * * @anchor PortalLinkConnector.getFoldersAndFiles */ @GET @Path("/getFoldersAndFiles/") // @OutputTransformer(XMLOutputTransformer.class) public Response getPageURI(@QueryParam("currentFolder") String currentFolder, @QueryParam("command") String command, @QueryParam("type") String type) throws Exception { try { String userId = getCurrentUser(); return buildReponse(currentFolder, command, userId); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform getPageURI: ", e); } } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } /** * Gets the current user. * * @return The current user */ private String getCurrentUser() { try { ConversationState conversationState = ConversationState.getCurrent(); return conversationState.getIdentity().getUserId(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform getCurrentUser: ", e); } } return null; } /** * Builds the response. * * @param currentFolder The current folder. * @param command The command. * @param userId The user Id * * @return the response * * @throws Exception the exception */ private Response buildReponse(String currentFolder, String command, String userId) throws Exception { Document document = null; if (currentFolder == null || "/".equals(currentFolder)) { document = buildPortalXMLResponse("/", command, userId); } else { document = buildNavigationXMLResponse(currentFolder, command, userId); } CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); cacheControl.setNoStore(true); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok(new DOMSource(document), MediaType.TEXT_XML) .cacheControl(cacheControl) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } /** * Builds the portal xml response. * * @param currentFolder The current folder. * @param command The command. * @param userId The user Id. * * @return The document * * @throws Exception the exception */ private Document buildPortalXMLResponse(String currentFolder, String command, String userId) throws Exception { Element rootElement = initRootElement(command, currentFolder); PortalContainer container = PortalContainer.getInstance(); RequestLifeCycle.begin(container); Query<PortalConfig> query = new Query<PortalConfig>(null, null, null, null, PortalConfig.class); PageList pageList = portalDataStorage.find(query, new Comparator<PortalConfig>() { public int compare(PortalConfig pconfig1, PortalConfig pconfig2) { return pconfig1.getName().compareTo(pconfig2.getName()); } }); // should use PermissionManager to check access permission Element foldersElement = rootElement.getOwnerDocument().createElement("Folders"); rootElement.appendChild(foldersElement); for (Object object : pageList.getAll()) { PortalConfig config = (PortalConfig) object; // if (!portalUserACL.hasPermission(config, userId)) { if (!portalUserACL.hasPermission(config)) { continue; } Element folderElement = rootElement.getOwnerDocument().createElement("Folder"); folderElement.setAttribute("name", config.getName()); folderElement.setAttribute("url", ""); folderElement.setAttribute("folderType", ""); foldersElement.appendChild(folderElement); } RequestLifeCycle.end(); return rootElement.getOwnerDocument(); } /** * Builds the navigation xml response. * * @param currentFolder The current folder. * @param command The command. * @param userId The user Id. * * @return The document. * * @throws Exception the exception */ private Document buildNavigationXMLResponse(String currentFolder, String command, String userId) throws Exception { PortalContainer container = PortalContainer.getInstance(); RequestLifeCycle.begin(container); String portalName = currentFolder.substring(1, currentFolder.indexOf('/', 1)); String pageNodeUri = currentFolder.substring(portalName.length() + 1); // init the return value Element rootElement = initRootElement(command, currentFolder); Element foldersElement = rootElement.getOwnerDocument().createElement("Folders"); Element filesElement = rootElement.getOwnerDocument().createElement("Files"); rootElement.appendChild(foldersElement); rootElement.appendChild(filesElement); // get navigation data UserPortalConfigService pConfig = WCMCoreUtils.getService(UserPortalConfigService.class); UserPortalContext NULL_CONTEXT = new UserPortalContext() { public ResourceBundle getBundle(UserNavigation navigation) { return null; } public Locale getUserLocale() { return Locale.ENGLISH; } }; UserPortalConfig userPortalCfg = pConfig.getUserPortalConfig(portalName, userId, NULL_CONTEXT); UserPortal userPortal = userPortalCfg.getUserPortal(); UserNavigation navigation = NavigationUtils.getUserNavigationOfPortal(userPortal, portalName); UserNode userNode = null; if (pageNodeUri == null) { RequestLifeCycle.end(); return rootElement.getOwnerDocument(); } if ("/".equals(pageNodeUri)) { userNode = userPortal.getNode(navigation, NavigationUtils.ECMS_NAVIGATION_SCOPE, null, null); } else { pageNodeUri = pageNodeUri.substring(1, pageNodeUri.length() - 1); userNode = userPortal.resolvePath(navigation, null, pageNodeUri); if (userNode != null) { userPortal.updateNode(userNode, NavigationUtils.ECMS_NAVIGATION_SCOPE, null); } } if (userNode != null) { // expand root node Iterator<UserNode> childrenIter = userNode.getChildren().iterator(); while (childrenIter.hasNext()) { UserNode child = childrenIter.next(); processPageNode(portalName, child, foldersElement, filesElement, userId, pConfig); } } RequestLifeCycle.end(); return rootElement.getOwnerDocument(); } /** * Initializes the root element. * * @param commandStr The command str. * @param currentPath The current path. * * @return The element. * * @throws ParserConfigurationException the parser configuration exception */ private Element initRootElement(String commandStr, String currentPath) throws ParserConfigurationException { Document doc = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.newDocument(); Element rootElement = doc.createElement("Connector"); doc.appendChild(rootElement); rootElement.setAttribute("command", commandStr); rootElement.setAttribute("resourceType", RESOURCE_TYPE); Element myEl = doc.createElement("CurrentFolder"); myEl.setAttribute("path", currentPath); myEl.setAttribute("url", ""); rootElement.appendChild(myEl); return rootElement; } /** * Processes page nodes. * * @param portalName The portal name. * @param userNode The user node. * @param foldersElement The root element. * @param filesElement * @param userId The user Id. * @param portalConfigService The portal config service. * * @throws Exception the exception */ private void processPageNode(String portalName, UserNode userNode, Element foldersElement, Element filesElement, String userId, UserPortalConfigService portalConfigService) throws Exception { PageKey pageRef = userNode.getPageRef(); PageContext page = portalConfigService.getPage(pageRef); String pageUri = ""; if (page == null) { pageUri = "/"; Element folderElement = foldersElement.getOwnerDocument().createElement("Folder"); folderElement.setAttribute("name", userNode.getName()); folderElement.setAttribute("folderType", ""); folderElement.setAttribute("url", pageUri); foldersElement.appendChild(folderElement); } else { pageUri = "/" + servletContext.getServletContextName() + "/" + portalName + "/" + userNode.getURI(); Element folderElement = foldersElement.getOwnerDocument().createElement("Folder"); folderElement.setAttribute("name", userNode.getName()); folderElement.setAttribute("folderType", ""); folderElement.setAttribute("url", pageUri); foldersElement.appendChild(folderElement); SimpleDateFormat formatter = new SimpleDateFormat(ISO8601.SIMPLE_DATETIME_FORMAT); String datetime = formatter.format(new Date()); Element fileElement = filesElement.getOwnerDocument().createElement("File"); fileElement.setAttribute("name", userNode.getName()); fileElement.setAttribute("dateCreated", datetime); fileElement.setAttribute("fileType", "page node"); fileElement.setAttribute("url", pageUri); fileElement.setAttribute("size", ""); filesElement.appendChild(fileElement); } } }
14,059
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
LinkFileHandler.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/fckeditor/LinkFileHandler.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.connector.fckeditor; import javax.jcr.Node; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.ecm.connector.fckeditor.FCKFileHandler; /* * Created by The eXo Platform SAS * Author : Anh Do Ngoc * anh.do@exoplatform.com * Sep 12, 2008 */ public class LinkFileHandler extends FCKFileHandler { /** * Instantiates a new link file handler. */ public LinkFileHandler() { super(ExoContainerContext.getCurrentContainer()); } /* (non-Javadoc) * @see org.exoplatform.ecm.connector.fckeditor.FCKFileHandler#getFileURL(javax.jcr.Node) */ protected String getFileURL(final Node file) throws Exception { return file.getProperty("exo:linkURL").getString(); } }
1,503
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FCKFileHandler.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/handler/FCKFileHandler.java
package org.exoplatform.wcm.connector.handler; import org.exoplatform.container.PortalContainer; import org.exoplatform.ecm.connector.fckeditor.FCKUtils; import org.exoplatform.services.cms.documents.AutoVersionService; import org.exoplatform.services.cms.impl.Utils; import org.exoplatform.services.cms.link.LinkManager; 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.security.IdentityConstants; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.core.WCMConfigurationService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.jcr.Node; import java.text.SimpleDateFormat; import static org.exoplatform.wcm.connector.fckeditor.DriverConnector.FILE_TYPE_SIMPLE_IMAGE; public class FCKFileHandler { public static Element createFileElement(Document document, String fileType, Node sourceNode, Node displayNode, String currentPortal) throws Exception { return createFileElement(document, fileType, sourceNode, displayNode, currentPortal, null, null); } public static Element createFileElement(Document document, String fileType, Node sourceNode, Node displayNode, String currentPortal, String childRelativePath, LinkManager linkManager) throws Exception { Element file = document.createElement("File"); AutoVersionService autoVersionService=WCMCoreUtils.getService(AutoVersionService.class); file.setAttribute("name", Utils.getTitle(displayNode)); if (sourceNode.hasProperty("ecd:thumbnailUrl") && fileType.equals(FILE_TYPE_SIMPLE_IMAGE)) { file.setAttribute("thumbnailUrl", sourceNode.getProperty("ecd:thumbnailUrl").getString()); } if (childRelativePath != null) { file.setAttribute("currentFolder", childRelativePath); } SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); if(sourceNode.hasProperty("exo:dateCreated")){ file.setAttribute("dateCreated", formatter.format(sourceNode.getProperty("exo:dateCreated").getDate().getTime())); }else if(sourceNode.hasProperty("jcr:created")){ file.setAttribute("dateCreated", formatter.format(sourceNode.getProperty("jcr:created").getDate().getTime())); } if(sourceNode.hasProperty("exo:dateModified")) { file.setAttribute("dateModified", formatter.format(sourceNode.getProperty("exo:dateModified") .getDate() .getTime())); } else { file.setAttribute("dateModified", null); } file.setAttribute("creator", sourceNode.getProperty("exo:owner").getString()); file.setAttribute("path", displayNode.getPath()); if (linkManager==null) { linkManager = WCMCoreUtils.getService(LinkManager.class) ; } if (linkManager.isLink(sourceNode)) { Node targetNode = linkManager.getTarget(sourceNode); if (targetNode!=null) { file.setAttribute("linkTarget", targetNode.getPath()); }else { file.setAttribute("linkTarget", sourceNode.getPath()); } }else { file.setAttribute("linkTarget", sourceNode.getPath()); } if (sourceNode.isNodeType("nt:file")) { Node content = sourceNode.getNode("jcr:content"); file.setAttribute("nodeType", content.getProperty("jcr:mimeType").getString()); } else { file.setAttribute("nodeType", sourceNode.getPrimaryNodeType().getName()); } if (sourceNode.isNodeType(NodetypeConstant.EXO_WEBCONTENT)) { file.setAttribute("url",getDocURL(displayNode, currentPortal)); } else { file.setAttribute("url",getFileURL(displayNode)); } if(sourceNode.isNodeType(FCKUtils.NT_FILE)) { long size = sourceNode.getNode("jcr:content").getProperty("jcr:data").getLength(); file.setAttribute("size", "" + size / 1000); }else { file.setAttribute("size", ""); } if(sourceNode.isNodeType(NodetypeConstant.MIX_VERSIONABLE)){ file.setAttribute("isVersioned", String.valueOf(true)); }else{ file.setAttribute("isVersioned", String.valueOf(false)); } file.setAttribute("title", Utils.getTitle(sourceNode).replaceAll("%", "%25")); file.setAttribute("nodeTypeCssClass", Utils.getNodeTypeIcon(sourceNode, "uiBgd64x64")); file.setAttribute("isVersionSupport", String.valueOf(autoVersionService.isVersionSupport(sourceNode.getPath(), sourceNode.getSession().getWorkspace().getName()))); return file; } /** * Gets the file url. * * @param file the file * @return the file url * @throws Exception the exception */ protected static String getFileURL(final Node file) throws Exception { return FCKUtils.createWebdavURL(file); } private static String getDocURL(final Node node, String currentPortal) throws Exception { String baseURI = "/" + PortalContainer.getCurrentPortalContainerName(); String accessMode = "private"; AccessControlList acl = ((ExtendedNode) node).getACL(); for (AccessControlEntry entry : acl.getPermissionEntries()) { if (entry.getIdentity().equalsIgnoreCase(IdentityConstants.ANY) && entry.getPermission().equalsIgnoreCase(PermissionType.READ)) { accessMode = "public"; break; } } String repository = ((ManageableRepository) node.getSession().getRepository()) .getConfiguration().getName(); String workspace = node.getSession().getWorkspace().getName(); String nodePath = node.getPath(); StringBuilder builder = new StringBuilder(); if(node.isNodeType(NodetypeConstant.NT_FILE)) { if("public".equals(accessMode)) { return builder.append(baseURI).append("/jcr/").append(repository).append("/") .append(workspace).append(nodePath).toString(); } return builder.append(baseURI).append("/private/jcr/").append(repository).append("/") .append(workspace).append(nodePath).toString(); } WCMConfigurationService configurationService = WCMCoreUtils.getService(WCMConfigurationService.class); String parameterizedPageViewerURI = configurationService. getRuntimeContextParam(WCMConfigurationService.PARAMETERIZED_PAGE_URI); return baseURI.replace("/rest", "") + "/" + currentPortal + parameterizedPageViewerURI + "/" + repository + "/" + workspace + nodePath; } }
7,076
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PDFViewerRESTService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/viewer/PDFViewerRESTService.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.connector.viewer; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.jcr.Node; import javax.jcr.Session; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.exoplatform.services.cache.CacheService; import org.exoplatform.services.cache.ExoCache; import org.exoplatform.services.cms.impl.Utils; import org.exoplatform.services.cms.mimetype.DMSMimeTypeResolver; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.pdfviewer.ObjectKey; import org.exoplatform.services.pdfviewer.PDFViewerService; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.icepdf.core.exceptions.PDFException; import org.icepdf.core.exceptions.PDFSecurityException; import org.icepdf.core.pobjects.Document; import org.icepdf.core.pobjects.Page; import org.icepdf.core.pobjects.Stream; import org.icepdf.core.util.GraphicsRenderingHints; /** * Returns a PDF content to be displayed on the web page. * * @LevelAPI Provisional * * @anchor PDFViewerRESTService */ @Path("/pdfviewer/{repoName}/") public class PDFViewerRESTService implements ResourceContainer { private static final int MAX_NAME_LENGTH= 150; private static final String LASTMODIFIED = "Last-Modified"; private static final String PDF_VIEWER_CACHE = "ecms.PDFViewerRestService"; private RepositoryService repositoryService_; private ExoCache<Serializable, Object> pdfCache; private static final Log LOG = ExoLogger.getLogger(PDFViewerRESTService.class.getName()); public PDFViewerRESTService(RepositoryService repositoryService, CacheService caService) throws Exception { repositoryService_ = repositoryService; PDFViewerService pdfViewerService = WCMCoreUtils.getService(PDFViewerService.class); if(pdfViewerService != null){ pdfCache = pdfViewerService.getCache(); }else{ pdfCache = caService.getCacheInstance(PDF_VIEWER_CACHE); } } /** * Returns a thumbnail image for a PDF document. * * @param repoName The repository name. * @param wsName The workspace name. * @param uuid The identifier of the document. * @param pageNumber The page number. * @param rotation The page rotation. The valid values are: 0.0f, 90.0f, 180.0f, 270.0f. * @param scale The Zoom factor which is applied to the rendered page. * @return Response inputstream. * @throws Exception The exception * * @anchor PDFViewerRESTService.getCoverImage */ @GET @Path("/{workspaceName}/{pageNumber}/{rotation}/{scale}/{uuid}/") public Response getCoverImage(@PathParam("repoName") String repoName, @PathParam("workspaceName") String wsName, @PathParam("uuid") String uuid, @PathParam("pageNumber") String pageNumber, @PathParam("rotation") String rotation, @PathParam("scale") String scale) throws Exception { return getImageByPageNumber(repoName, wsName, uuid, pageNumber, rotation, scale); } /** * Returns a pdf file for a PDF document. * * @param repoName The repository name. * @param wsName The workspace name. * @param uuid The identifier of the document. * @return Response inputstream. * @throws Exception The exception * * @anchor PDFViewerRESTService.getPDFFile */ @GET @Path("/{workspaceName}/{uuid}/") public Response getPDFFile(@PathParam("repoName") String repoName, @PathParam("workspaceName") String wsName, @PathParam("uuid") String uuid) throws Exception { Session session = null; InputStream is = null; String fileName = null; try { ManageableRepository repository = repositoryService_.getCurrentRepository(); session = getSystemProvider().getSession(wsName, repository); Node currentNode = session.getNodeByUUID(uuid); fileName = Utils.getTitle(currentNode); File pdfFile = getPDFDocumentFile(currentNode, repoName); is = new FileInputStream(pdfFile); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(e); } } return Response.ok(is).header("Content-Disposition","attachment; filename=\"" + fileName+"\"").build(); } private Response getImageByPageNumber(String repoName, String wsName, String uuid, String pageNumber, String strRotation, String strScale) throws Exception { StringBuilder bd = new StringBuilder(); StringBuilder bd1 = new StringBuilder(); StringBuilder bd2 = new StringBuilder(); bd.append(repoName).append("/").append(wsName).append("/").append(uuid); Session session = null; try { Object objCache = pdfCache.get(new ObjectKey(bd.toString())); InputStream is = null; ManageableRepository repository = repositoryService_.getCurrentRepository(); session = getSystemProvider().getSession(wsName, repository); Node currentNode = session.getNodeByUUID(uuid); String lastModified = (String) pdfCache.get(new ObjectKey(bd1.append(bd.toString()) .append("/jcr:lastModified").toString())); String baseVersion = (String) pdfCache.get(new ObjectKey(bd2.append(bd.toString()) .append("/jcr:baseVersion").toString())); if(objCache!=null) { File content = new File((String) pdfCache.get(new ObjectKey(bd.toString()))); if (!content.exists()) { initDocument(currentNode, repoName); } is = pushToCache(new File((String) pdfCache.get(new ObjectKey(bd.toString()))), repoName, wsName, uuid, pageNumber, strRotation, strScale, lastModified, baseVersion); } else { File file = getPDFDocumentFile(currentNode, repoName); is = pushToCache(file, repoName, wsName, uuid, pageNumber, strRotation, strScale, lastModified, baseVersion); } return Response.ok(is, "image").header(LASTMODIFIED, lastModified).build(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(e); } } return Response.ok().build(); } private SessionProvider getSystemProvider() { SessionProviderService service = WCMCoreUtils.getService(SessionProviderService.class); return service.getSystemSessionProvider(null) ; } private InputStream pushToCache(File content, String repoName, String wsName, String uuid, String pageNumber, String strRotation, String strScale, String lastModified, String baseVersion) throws FileNotFoundException { StringBuilder bd = new StringBuilder(); bd.append(repoName).append("/").append(wsName).append("/").append(uuid).append("/").append( pageNumber).append("/").append(strRotation).append("/").append(strScale); StringBuilder bd1 = new StringBuilder().append(bd).append("/jcr:lastModified"); StringBuilder bd2 = new StringBuilder().append(bd).append("/jcr:baseVersion"); String filePath = (String) pdfCache.get(new ObjectKey(bd.toString())); String fileModifiedTime = (String) pdfCache.get(new ObjectKey(bd1.toString())); String jcrBaseVersion = (String) pdfCache.get(new ObjectKey(bd2.toString())); if (filePath == null || !(new File(filePath).exists()) || !StringUtils.equals(baseVersion, fileModifiedTime) || !StringUtils.equals(jcrBaseVersion, baseVersion)) { File file = buildFileImage(content, uuid, pageNumber, strRotation, strScale); filePath = file.getPath(); pdfCache.put(new ObjectKey(bd.toString()), filePath); pdfCache.put(new ObjectKey(bd1.toString()), lastModified); pdfCache.put(new ObjectKey(bd2.toString()), baseVersion); } return new BufferedInputStream(new FileInputStream(new File(filePath))); } private Document buildDocumentImage(File input, String name) { Document document = new Document(); // Turn off Log of org.icepdf.core.pobjects.Document to avoid printing error stack trace in case viewing // a PDF file which use new Public Key Security Handler. // TODO: Remove this statement after IcePDF fix this Logger.getLogger(Document.class.toString()).setLevel(Level.OFF); // Capture the page image to file try { // cut the file name if name is too long, because OS allows only file with name < 250 characters name = reduceFileNameSize(name); document.setInputStream(new BufferedInputStream(new FileInputStream(input)), name); } catch (PDFException ex) { if (LOG.isDebugEnabled()) { LOG.error("Error parsing PDF document " + ex); } } catch (PDFSecurityException ex) { if (LOG.isDebugEnabled()) { LOG.error("Error encryption not supported " + ex); } } catch (FileNotFoundException ex) { if (LOG.isDebugEnabled()) { LOG.error("Error file not found " + ex); } } catch (IOException ex) { if (LOG.isDebugEnabled()) { LOG.debug("Error handling PDF document: {} {}", name, ex.toString()); } } return document; } private File buildFileImage(File input, String path, String pageNumber, String strRotation, String strScale) { Document document = buildDocumentImage(input, path); // Turn off Log of org.icepdf.core.pobjects.Stream to not print error stack trace in case // viewing a PDF file including CCITT (Fax format) images // TODO: Remove these statement and comments after IcePDF fix ECMS-3765 Logger.getLogger(Stream.class.toString()).setLevel(Level.OFF); // save page capture to file. float scale = 1.0f; try { scale = Float.parseFloat(strScale); // maximum scale support is 300% if (scale > 3.0f) { scale = 3.0f; } } catch (NumberFormatException e) { scale = 1.0f; } float rotation = 0.0f; try { rotation = Float.parseFloat(strRotation); } catch (NumberFormatException e) { rotation = 0.0f; } int maximumOfPage = document.getNumberOfPages(); int pageNum = 1; try { pageNum = Integer.parseInt(pageNumber); } catch(NumberFormatException e) { pageNum = 1; } if(pageNum >= maximumOfPage) pageNum = maximumOfPage; else if(pageNum < 1) pageNum = 1; // Paint each pages content to an image and write the image to file BufferedImage image = (BufferedImage) document.getPageImage(pageNum - 1, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale); RenderedImage rendImage = image; File file = null; try { file= File.createTempFile("imageCapture1_" + pageNum,".png"); /* file.deleteOnExit(); PM Comment : I removed this line because each deleteOnExit creates a reference in the JVM for future removal Each JVM reference takes 1KB of system memory and leads to a memleak */ ImageIO.write(rendImage, "png", file); } catch (IOException e) { if (LOG.isErrorEnabled()) { LOG.error(e); } } finally { image.flush(); // clean up resources document.dispose(); } return file; } /** * Initializes the PDF document from InputStream in the _nt\:file_ node. * @param currentNode The name of the current node. * @param repoName The repository name. * @return * @throws Exception */ public Document initDocument(Node currentNode, String repoName) throws Exception { return buildDocumentImage(getPDFDocumentFile(currentNode, repoName), currentNode.getName()); } /** * Writes PDF data to file. * @param currentNode The name of the current node. * @param repoName The repository name. * @return * @throws Exception */ public File getPDFDocumentFile(Node currentNode, String repoName) throws Exception { String wsName = currentNode.getSession().getWorkspace().getName(); String uuid = currentNode.getUUID(); StringBuilder bd = new StringBuilder(); StringBuilder bd1 = new StringBuilder(); StringBuilder bd2 = new StringBuilder(); bd.append(repoName).append("/").append(wsName).append("/").append(uuid); bd1.append(bd).append("/jcr:lastModified"); bd2.append(bd).append("/jcr:baseVersion"); String path = (String) pdfCache.get(new ObjectKey(bd.toString())); String lastModifiedTime = (String)pdfCache.get(new ObjectKey(bd1.toString())); String baseVersion = (String)pdfCache.get(new ObjectKey(bd2.toString())); File content = null; String name = currentNode.getName().replaceAll(":","_"); Node contentNode = currentNode.getNode("jcr:content"); String lastModified = getJcrLastModified(currentNode); String jcrBaseVersion = getJcrBaseVersion(currentNode); if (path == null || !(content = new File(path)).exists() || !lastModified.equals(lastModifiedTime) || !StringUtils.equals(baseVersion, jcrBaseVersion)) { String mimeType = contentNode.getProperty("jcr:mimeType").getString(); InputStream input = new BufferedInputStream(contentNode.getProperty("jcr:data").getStream()); // Create temp file to store converted data of nt:file node if (name.indexOf(".") > 0) name = name.substring(0, name.lastIndexOf(".")); // cut the file name if name is too long, because OS allows only file with name < 250 characters name = reduceFileNameSize(name); content = File.createTempFile(name + "_tmp", ".pdf"); /* file.deleteOnExit(); PM Comment : I removed this line because each deleteOnExit creates a reference in the JVM for future removal Each JVM reference takes 1KB of system memory and leads to a memleak */ String extension = DMSMimeTypeResolver.getInstance().getExtension(mimeType); if ("pdf".equals(extension)) { read(input, new BufferedOutputStream(new FileOutputStream(content))); } if (content.exists()) { pdfCache.put(new ObjectKey(bd.toString()), content.getPath()); pdfCache.put(new ObjectKey(bd1.toString()), lastModified); pdfCache.put(new ObjectKey(bd2.toString()), jcrBaseVersion); } } return content; } private String getJcrLastModified(Node node) throws Exception { Node checkedNode = node; if (node.isNodeType("nt:frozenNode")) { checkedNode = node.getSession().getNodeByUUID(node.getProperty("jcr:frozenUuid").getString()); } return Utils.getJcrContentLastModified(checkedNode); } private String getJcrBaseVersion(Node node) throws Exception { Node checkedNode = node; if (node.isNodeType("nt:frozenNode")) { checkedNode = node.getSession().getNodeByUUID(node.getProperty("jcr:frozenUuid").getString()); } return checkedNode.hasProperty("jcr:baseVersion") ? checkedNode.getProperty("jcr:baseVersion").getString() : null; } private void read(InputStream is, OutputStream os) throws Exception { int bufferLength = 1024; int readLength = 0; while (readLength > -1) { byte[] chunk = new byte[bufferLength]; readLength = is.read(chunk); if (readLength > 0) { os.write(chunk, 0, readLength); } } os.flush(); os.close(); } /** * reduces the file name size. If the length is > 150, return the first 150 characters, else, return the original value * @param name the name * @return the reduced name */ private String reduceFileNameSize(String name) { return (name != null && name.length() > MAX_NAME_LENGTH) ? name.substring(0, MAX_NAME_LENGTH) : name; } }
17,451
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TagConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/TagConnector.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.connector.collaboration; import java.net.URLDecoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.jcr.Node; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import org.exoplatform.ecm.connector.fckeditor.FCKUtils; import org.exoplatform.services.cms.folksonomy.NewFolksonomyService; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.portal.PortalFolderSchemaHandler; import org.exoplatform.services.wcm.webcontent.WebContentSchemaHandler; import org.exoplatform.wcm.connector.BaseConnector; import org.w3c.dom.Document; import org.w3c.dom.Element; /* * Created by The eXo Platform SAS * Author : Benjamin Paillereau * benjamin.paillereau@exoplatform.com * March 25, 2011 */ /** * Adds and queries the public tags of a document. */ @Path("/contents/tag/") public class TagConnector extends BaseConnector implements ResourceContainer { NewFolksonomyService tagService; /** * Instantiates a new tag connector. */ public TagConnector(NewFolksonomyService tagService) { this.tagService = tagService; } /** * Adds a public tag to a given document. * * @param tag The tag to be added. * * @param jcrPath The path of the document, e.g. /portal/collaboration/test/document1, * in which "portal" is the repository, "collaboration" is the workspace. * * @request POST: http://localhost:8080/rest/private/contents/tag/add/tag1?jcrPath=/portal/collaboration/test/document1 * * @response HTTP Status code. 200 on success. 500 if any error during the process. * * @anchor TagConnector.addTag */ @POST @Path("/add/{tag}") public Response addTag( @PathParam("tag") String tag, @QueryParam("jcrPath") String jcrPath ) throws Exception { if (jcrPath.contains("%20")) jcrPath = URLDecoder.decode(jcrPath, "UTF-8"); String[] path = jcrPath.split("/"); String repositoryName = path[1]; String workspaceName = path[2]; jcrPath = jcrPath.substring(repositoryName.length()+workspaceName.length()+2); if (jcrPath.charAt(1)=='/') jcrPath.substring(1); Node content = getContent(workspaceName, jcrPath, null, false); // tagService.addPublicTag("/Application Data/Tags", new String[]{tag}, content, workspaceName); tagService.addPublicTag("/tags", new String[]{tag}, content, workspaceName); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } /** * Gets the list of public tags of a given document. * * @param jcrPath The path of the document, e.g. /portal/collaboration/test/document1, * in which "portal" is the repository, "collaboration" is the workspace. * * @request GET: http://localhost:8080/rest/private/contents/tag/public?jcrPath=/portal/collaboration/test/document1 * * @format XML * * @response The tag names in XML format. * {@code * <?xml version="1.0" encoding="UTF-8" standalone="no" ?> * <tags> * <tag name="gold" /> * <tag name="silver" /> * </tags> * } * * @anchor TagConnector.getPublicTags */ @GET @Path("/public") public Response getPublicTags( @QueryParam("jcrPath") String jcrPath ) throws Exception { if (jcrPath.contains("%20")) jcrPath = URLDecoder.decode(jcrPath, "UTF-8"); String[] path = jcrPath.split("/"); String repositoryName = path[1]; String workspaceName = path[2]; jcrPath = jcrPath.substring(repositoryName.length()+workspaceName.length()+2); if (jcrPath.charAt(1)=='/') jcrPath.substring(1); try { Node content = getContent(workspaceName, jcrPath, null, false); List<Node> tags = tagService.getLinkedTagsOfDocumentByScope(NewFolksonomyService.PUBLIC, "", content, workspaceName); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element tagsElt = document.createElement("tags"); for (Node tag:tags) { Element element = document.createElement("tag"); element.setAttribute("name", tag.getName()); tagsElt.appendChild(element); } document.appendChild(tagsElt); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok(new DOMSource(document), MediaType.TEXT_XML) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } catch (Exception e){ Response.serverError().build(); } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } /* * (non-Javadoc) * @see * org.exoplatform.wcm.connector.fckeditor.BaseConnector#getRootContentStorage * (javax.jcr.Node) */ @Override protected Node getRootContentStorage(Node parentNode) throws Exception { try { PortalFolderSchemaHandler folderSchemaHandler = webSchemaConfigService.getWebSchemaHandlerByType(PortalFolderSchemaHandler.class); return folderSchemaHandler.getDocumentStorage(parentNode); } catch (Exception e) { WebContentSchemaHandler webContentSchemaHandler = webSchemaConfigService.getWebSchemaHandlerByType(WebContentSchemaHandler.class); return webContentSchemaHandler.getDocumentFolder(parentNode); } } /* * (non-Javadoc) * @see * org.exoplatform.wcm.connector.fckeditor.BaseConnector#getContentStorageType * () */ @Override protected String getContentStorageType() throws Exception { return FCKUtils.DOCUMENT_TYPE; } }
7,202
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
OpenInOfficeConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/OpenInOfficeConnector.java
package org.exoplatform.wcm.connector.collaboration; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.annotation.security.RolesAllowed; import javax.jcr.AccessDeniedException; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Context; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.StringUtils; import org.apache.tika.io.IOUtils; import org.json.JSONObject; import org.picocontainer.Startable; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.services.cms.documents.DocumentTypeService; import org.exoplatform.services.cms.documents.impl.DocumentType; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.resources.ResourceBundleService; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.social.rest.api.RestUtils; import jakarta.servlet.http.HttpServletRequest; /** * Created by The eXo Platform SAS * Author : eXoPlatform * toannh@exoplatform.com * Dec 09, 2014 * Provider all rest methods of Open Document feature. */ @Path("/office/") @RolesAllowed("users") public class OpenInOfficeConnector implements ResourceContainer, Startable { private Log log = ExoLogger.getExoLogger(OpenInOfficeConnector.class); private final String OPEN_DOCUMENT_ON_DESKTOP_ICO = "uiIconOpenOnDesktop"; private final String CONNECTOR_BUNDLE_LOCATION = "locale.wcm.resources.WCMResourceBundleConnector"; private final String OPEN_DOCUMENT_ON_DESKTOP_RESOURCE_KEY = "OpenInOfficeConnector.label.exo.remote-edit.desktop"; private final String OPEN_DOCUMENT_IN_DESKTOP_APP_RESOURCE_KEY = "OpenInOfficeConnector.label.exo.remote-edit.desktop-app"; private final String OPEN_DOCUMENT_DEFAULT_TITLE = "Open on Desktop"; private final int CACHED_TIME = 60*24*30*12; private static final String VERSION_MIXIN ="mix:versionable"; private NodeFinder nodeFinder; private LinkManager linkManager; private ResourceBundleService resourceBundleService; private DocumentTypeService documentTypeService; public OpenInOfficeConnector(NodeFinder nodeFinder, LinkManager linkManager, ResourceBundleService resourceBundleService, DocumentTypeService documentTypeService){ this.nodeFinder = nodeFinder; this.linkManager = linkManager; this.resourceBundleService = resourceBundleService; this.documentTypeService = documentTypeService; } /** * Return a JsonObject's current file to update display titles * @param request * @param objId * @return * @throws Exception */ @GET @RolesAllowed("users") @Path("/updateDocumentTitle") public Response updateDocumentTitle( @Context Request request, @QueryParam("objId") String objId, @QueryParam("lang") String language) throws Exception { //find from cached try { objId = URLDecoder.decode(objId, "UTF-8"); } catch (UnsupportedEncodingException e) { log.debug("Error while decoding file name", e); } int indexColon = objId.indexOf(":/"); if(indexColon < 0) { return Response.status(Response.Status.BAD_REQUEST) .entity("The objId param must start by the workspace name, followed by ':' and the node path").build(); } String workspace = objId.substring(0, indexColon); String filePath = objId.substring(indexColon + 1); String extension = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()); if(extension.contains("[")) extension=extension.substring(0, extension.indexOf("[")); EntityTag etag = new EntityTag(Integer.toString((extension+"_"+language).hashCode())); Response.ResponseBuilder builder = request.evaluatePreconditions(etag); if(builder!=null) return builder.build(); //query form configuration values params CacheControl cc = new CacheControl(); cc.setMaxAge(CACHED_TIME); ResourceBundle resourceBundle = resourceBundleService.getResourceBundle(CONNECTOR_BUNDLE_LOCATION, new Locale(language)); String title = resourceBundle!=null?resourceBundle.getString(OPEN_DOCUMENT_ON_DESKTOP_RESOURCE_KEY):OPEN_DOCUMENT_DEFAULT_TITLE; String ico = OPEN_DOCUMENT_ON_DESKTOP_ICO; DocumentType documentType = documentTypeService.getDocumentType(extension); if(documentType !=null && resourceBundle !=null ){ try { if(!StringUtils.isEmpty(resourceBundle.getString(documentType.getResourceBundleKey()))) title = resourceBundle.getString(documentType.getResourceBundleKey()); }catch(MissingResourceException ex){ String _openonDesktop = resourceBundle.getString(OPEN_DOCUMENT_IN_DESKTOP_APP_RESOURCE_KEY); if(_openonDesktop!=null && _openonDesktop.contains("{0}")) { title = _openonDesktop.replace("{0}", documentType.getResourceBundleKey()); }else{ title = OPEN_DOCUMENT_DEFAULT_TITLE; } } if(!StringUtils.isEmpty(documentType.getIconClass())) ico=documentType.getIconClass(); } Node node; String nodePath = filePath; boolean isFile=false; try{ try { node = (Node)nodeFinder.getItem(workspace, filePath); } catch (PathNotFoundException e) { node = (Node)nodeFinder.getItem(workspace, Text.unescapeIllegalJcrChars(filePath)); } if (linkManager.isLink(node)) node = linkManager.getTarget(node); nodePath = node.getPath(); isFile = node.isNodeType(NodetypeConstant.NT_FILE); } catch (PathNotFoundException | AccessDeniedException e) { if (log.isDebugEnabled()) { String currentUser = RestUtils.getCurrentUser(); log.debug("User {} can't access document {}:{}", currentUser, workspace, filePath, e); } return Response.status(Status.NOT_FOUND).build(); } catch(RepositoryException ex){ if(log.isErrorEnabled()){log.error("Exception when get node with path: "+filePath, ex);} } boolean isMsoffice = false; if (documentType.getResourceBundleKey() != OPEN_DOCUMENT_ON_DESKTOP_RESOURCE_KEY) { isMsoffice = true; } JSONObject rs = new JSONObject(); rs.put("ico", ico); rs.put("title", title); rs.put("repository", WCMCoreUtils.getRepository().getConfiguration().getName()); rs.put("workspace", workspace); rs.put("filePath", nodePath); rs.put("isFile", isFile); rs.put("isMsoffice", isMsoffice); builder = Response.ok(rs.toString(), MediaType.APPLICATION_JSON); builder.tag(etag); builder.cacheControl(cc); return builder.build(); } /** * Get Title, css class of document by document's name * @param fileName * @return */ public String[] getDocumentInfos(String fileName){ String title = OPEN_DOCUMENT_ON_DESKTOP_RESOURCE_KEY; String icon = OPEN_DOCUMENT_ON_DESKTOP_ICO; String _extension = ""; if(fileName.lastIndexOf(".") > 0 ) { _extension = StringUtils.substring(fileName, fileName.lastIndexOf(".") + 1, fileName.length()); } if(StringUtils.isBlank(_extension)) return new String[]{title, icon}; DocumentType documentType = documentTypeService.getDocumentType(_extension); if(documentType !=null){ if(!StringUtils.isEmpty(documentType.getResourceBundleKey())) title=documentType.getResourceBundleKey(); if(!StringUtils.isEmpty(documentType.getIconClass())) icon=documentType.getIconClass(); } return new String[]{title, icon}; } /** * Return a JsonObject's check a version when file has been opened successfully by desktop application * @param request * @param filePath * @return */ @GET @RolesAllowed("users") @Path("/checkout") public Response checkout(@Context Request request, @QueryParam("filePath") String filePath, @QueryParam("workspace") String workspace ) { try { Node node = null; try { node = (Node) nodeFinder.getItem(workspace, filePath); } catch (PathNotFoundException e) { node = (Node) nodeFinder.getItem(workspace, Text.unescapeIllegalJcrChars(filePath)); } if (node.canAddMixin(VERSION_MIXIN)) { node.addMixin(VERSION_MIXIN); node.save(); node.checkin(); node.checkout(); } if (!node.isCheckedOut()) { node.checkout(); } return Response.ok(String.valueOf(node.isCheckedOut()), MediaType.TEXT_PLAIN).build(); } catch (PathNotFoundException | AccessDeniedException e) { if (log.isDebugEnabled()) { String currentUser = RestUtils.getCurrentUser(); log.debug("User {} can't access document {}:{}", currentUser, workspace, filePath, e); } return Response.status(Status.NOT_FOUND).build(); } catch (Exception e) { log.warn("Error checking out document {}:{}", workspace, filePath, e); return Response.serverError().build(); } } /** * Return a a input stream internet shortcut to open file with desktop application * @param httpServletRequest * @param filePath * @return * @throws Exception */ @GET @Path("/{linkFilePath}/") @RolesAllowed("users") @Produces("application/internet-shortcut") public Response createShortcut(@Context HttpServletRequest httpServletRequest, @PathParam("linkFilePath") String linkFilePath, @QueryParam("filePath") String filePath, @QueryParam("workspace") String workspace ) throws Exception { try { Node node = null; try { node = (Node) nodeFinder.getItem(workspace, filePath); } catch (PathNotFoundException e) { node = (Node) nodeFinder.getItem(workspace, Text.unescapeIllegalJcrChars(filePath)); } String repo = WCMCoreUtils.getRepository().getConfiguration().getName(); String obsPath = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + "/" + WCMCoreUtils.getRestContextName() + "/private/jcr/" + repo + "/" + workspace + node.getPath(); String shortCutContent = "[InternetShortcut]\n"; shortCutContent += "URL=" + obsPath + "\n"; return Response.ok(IOUtils.toInputStream(shortCutContent), MediaType.APPLICATION_OCTET_STREAM) .header("Content-Disposition", "attachment; filename=" + node.getName() + ".url") .header("Content-type", "application/internet-shortcut") .build(); } catch (PathNotFoundException | AccessDeniedException e) { if (log.isDebugEnabled()) { String currentUser = RestUtils.getCurrentUser(); log.debug("User {} can't access document {}:{}", currentUser, workspace, filePath, e); } return Response.status(Status.NOT_FOUND).build(); } catch (Exception e) { log.warn("Error getting shortcut of document {}:{}", workspace, filePath, e); return Response.serverError().build(); } } @Override public void start() { } @Override public void stop() { } }
11,948
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CommentConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/CommentConnector.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.connector.collaboration; import java.net.URLDecoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.annotation.security.RolesAllowed; import javax.jcr.Node; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.connector.fckeditor.FCKUtils; import org.exoplatform.services.cms.comments.CommentsService; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.portal.PortalFolderSchemaHandler; import org.exoplatform.services.wcm.webcontent.WebContentSchemaHandler; import org.exoplatform.wcm.connector.BaseConnector; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * The CommentConnector aims to manage and use comments for the content. * * @LevelAPI Experimental * * @anchor CommentConnector */ @Path("/contents/comment/") public class CommentConnector extends BaseConnector implements ResourceContainer { CommentsService commentsService; /** * Instantiates a new tag connector. * * @param commentsService Service instantiation. */ public CommentConnector(CommentsService commentsService) { this.commentsService = commentsService; } /** * * Adds a new comment to the content. * * @param jcrPath The JCR path of the content. * @param comment The comment to add. * @return The last modified date as a property to check the result. * @throws Exception The exception * * @anchor CommentConnector.addComment */ @POST @RolesAllowed("users") @Path("/add") public Response addComment( @FormParam("jcrPath") String jcrPath, @FormParam("comment") String comment ) throws Exception { Node content = getNode(jcrPath); commentsService.addComment(content, content.getSession().getUserID(), null, null, comment,null); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } /** * Gets all comments for a specific content. * * @param jcrPath The JCR path of the content. * @return All comments * @throws Exception The exception * * @anchor CommentConnector.getComments */ @GET @RolesAllowed("users") @Path("/all") public Response getComments( @QueryParam("jcrPath") String jcrPath ) throws Exception { try { Node content = getNode(jcrPath); List<Node> comments = commentsService.getComments(content, null); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element tagsElt = document.createElement("comments"); for (Node comment:comments) { Element tagElt = document.createElement("comment"); //exo:name Element id = document.createElement("id"); id.setTextContent(comment.getName()); //exo:commentor Element commentor = document.createElement("commentor"); commentor.setTextContent(comment.getProperty("exo:commentor").getString()); //exo:commentorEmail Element commentorEmail = document.createElement("email"); if (comment.hasProperty("exo:commentorEmail")) { commentorEmail.setTextContent(comment.getProperty("exo:commentorEmail").getString()); } //exo:commentDate Element date = document.createElement("date"); date.setTextContent(DateFormat.getDateTimeInstance().format(comment.getProperty("exo:commentDate").getDate().getTime())); //exo:commentContent Element commentElt = document.createElement("content"); commentElt.setTextContent(comment.getProperty("exo:commentContent").getString()); tagElt.appendChild(id); tagElt.appendChild(commentor); tagElt.appendChild(commentorEmail); tagElt.appendChild(date); tagElt.appendChild(commentElt); tagsElt.appendChild(tagElt); } document.appendChild(tagsElt); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok(new DOMSource(document), MediaType.TEXT_XML) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } catch (Exception e){ Response.serverError().build(); } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } /** * * Delete a comment of a content. * * @param jcrPath The JCR path of the content. * @param commentId The id of the comment to delete. * @return * @throws Exception The exception * * @anchor CommentConnector.deleteComment */ @DELETE @RolesAllowed("users") @Path("/delete") public Response deleteComment( @QueryParam("jcrPath") String jcrPath, @QueryParam("commentId") String commentId ) throws Exception { if(StringUtils.isEmpty(jcrPath) || StringUtils.isEmpty(commentId)) { return Response.status(400).entity("jcrPath and commentId query parameters are mandatory").build(); } Node content = getNode(jcrPath); if(content.hasNode("comments")) { Node commentsNode = content.getNode("comments"); if(commentsNode.hasNode(commentId)) { commentsService.deleteComment(commentsNode.getNode(commentId)); } else { return Response.noContent().build(); } } else { return Response.noContent().build(); } return Response.ok().build(); } /** * Get the jcr node of the given jcr path * @param jcrPath * @return The node of the given jcr path * @throws Exception */ protected Node getNode(@QueryParam("jcrPath") String jcrPath) throws Exception { if (jcrPath.contains("%20")) { jcrPath = URLDecoder.decode(jcrPath, "UTF-8"); } String[] path = jcrPath.split("/"); String repositoryName = path[1]; String workspaceName = path[2]; jcrPath = jcrPath.substring(repositoryName.length()+workspaceName.length()+2); if (jcrPath.charAt(1)=='/') { jcrPath.substring(1); } return getContent(workspaceName, jcrPath, null, false); } /* * (non-Javadoc) * @see * org.exoplatform.wcm.connector.fckeditor.BaseConnector#getRootContentStorage * (javax.jcr.Node) */ @Override protected Node getRootContentStorage(Node parentNode) throws Exception { try { PortalFolderSchemaHandler folderSchemaHandler = webSchemaConfigService.getWebSchemaHandlerByType(PortalFolderSchemaHandler.class); return folderSchemaHandler.getDocumentStorage(parentNode); } catch (Exception e) { WebContentSchemaHandler webContentSchemaHandler = webSchemaConfigService.getWebSchemaHandlerByType(WebContentSchemaHandler.class); return webContentSchemaHandler.getDocumentFolder(parentNode); } } /* * (non-Javadoc) * @see * org.exoplatform.wcm.connector.fckeditor.BaseConnector#getContentStorageType * () */ @Override protected String getContentStorageType() throws Exception { return FCKUtils.DOCUMENT_TYPE; } }
8,409
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PublicationGetDocumentRESTService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/PublicationGetDocumentRESTService.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.connector.collaboration; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.exoplatform.commons.utils.ISO8601; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; 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.jcr.impl.core.query.QueryImpl; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Returns a list of published documents. * * @LevelAPI Provisional * * @anchor PublicationGetDocumentRESTService */ @Path("/publication/presentation/") public class PublicationGetDocumentRESTService implements ResourceContainer { private RepositoryService repositoryService_; private PublicationService publicationService_; private ManageDriveService manageDriveService_; final static public String DEFAULT_ITEM = "5"; /** 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"; private static final Log LOG = ExoLogger.getLogger(PublicationGetDocumentRESTService.class.getName()); public PublicationGetDocumentRESTService(RepositoryService repositoryService, PublicationService publicationService, ManageDriveService manageDriveService) { repositoryService_ = repositoryService; publicationService_ = publicationService; manageDriveService_ = manageDriveService; } /** * Returns a list of published documents by the default plugin. * For example: {{{/portal/rest/publication/presentation/{repository}/{workspace}/{state}?showItems={numberOfItem}}}} * * @param repository The repository name. * @param workspace The workspace name. * @param state The state is specified to classify the process. * @param showItems Shows the number of items per page. * @return * @throws Exception * * @anchor PublicationGetDocumentRESTService.getPublishDocument */ @Path("/{repository}/{workspace}/{state}/") @GET // @OutputTransformer(Bean2JsonOutputTransformer.class) public Response getPublishDocument(@PathParam("repository") String repository, @PathParam("workspace") String workspace, @PathParam("state") String state, @QueryParam("showItems") String showItems) throws Exception { return getPublishDocuments(workspace, state, null, showItems); } /** * Returns a list of published documents by a specific plugin. * For example: {{{/portal/rest/publication/presentation/{repository}/{workspace}/{publicationPluginName}/{state}?showItems={numberOfItem}}}} * * @param repoName The repository name. * @param workspace The workspace name. * @param publicationPluginName The name of the plugin. * @param state The state is specified to classify the process. * @param showItems Shows the number of items per page. * @return * @throws Exception * * @anchor PublicationGetDocumentRESTService.getPublishedListDocument */ @Path("/{repository}/{workspace}/{publicationPluginName}/{state}/") @GET // @OutputTransformer(Bean2JsonOutputTransformer.class) public Response getPublishedListDocument(@PathParam("repository") String repoName, @PathParam("workspace") String workspace, @PathParam("publicationPluginName") String publicationPluginName, @PathParam("state") String state, @QueryParam("showItems") String showItems) throws Exception { return getPublishDocuments(workspace, state, publicationPluginName, showItems); } @SuppressWarnings("unused") private Response getPublishDocuments(String wsName, String state, String pluginName, String itemPage) throws Exception { List<PublishedNode> publishedNodes = new ArrayList<PublishedNode>(); PublishedListNode publishedListNode = new PublishedListNode(); if(itemPage == null) itemPage = DEFAULT_ITEM; int item = Integer.parseInt(itemPage); String queryStatement = "select * from publication:publication order by exo:dateModified ASC"; SessionProvider provider = WCMCoreUtils.createAnonimProvider(); Session session = provider.getSession(wsName, repositoryService_.getCurrentRepository()); QueryManager queryManager = session.getWorkspace().getQueryManager(); QueryImpl query = (QueryImpl) queryManager.createQuery(queryStatement, Query.SQL); query.setLimit(item); query.setOffset(0); QueryResult queryResult = query.execute(); NodeIterator iter = queryResult.getNodes(); List<Node> listNode = getNodePublish(iter, pluginName); Collections.sort(listNode, new DateComparator()); if(listNode.size() < item) item = listNode.size(); List<DriveData> lstDrive = manageDriveService_.getAllDrives(); for (int i = 0; i < item; i++) { PublishedNode publishedNode = new PublishedNode(); Node node = listNode.get(i); publishedNode.setName(node.getName()); publishedNode.setPath(node.getPath()); publishedNode.setDatePublished(getPublishedDateTime(node)); publishedNode.setDriveName(getDriveName(lstDrive, node)); publishedNodes.add(publishedNode); } publishedListNode.setPublishedListNode(publishedNodes); session.logout(); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok(publishedListNode, new MediaType("application", "json")) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } private List<Node> getNodePublish(NodeIterator iter, String pluginName) throws Exception { List<Node> listNode = new ArrayList<Node>(); while (iter.hasNext()) { Node node = iter.nextNode(); Node nodecheck = publicationService_.getNodePublish(node, pluginName); if (nodecheck != null) { listNode.add(node); } } return listNode; } private String getPublishedDateTime(Node currentNode) throws Exception { Value[] history = currentNode.getProperty("publication:history").getValues(); String time = currentNode.getProperty("exo:dateModified").getString(); for (Value value : history) { String[] arrHistory = value.getString().split(";"); time = arrHistory[3]; } return String.valueOf(ISO8601.parse(time).getTimeInMillis()); } private static class DateComparator implements Comparator<Node> { public int compare(Node node1, Node node2) { try { SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd.HHmmss.SSS"); Date date1 = formatter.parse(getDateTime(node1)); Date date2 = formatter.parse(getDateTime(node2)); return date2.compareTo(date1); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } return 0; } private String getDateTime(Node currentNode) throws Exception { Value[] history = currentNode.getProperty("publication:history").getValues(); for (Value value : history) { String[] arrHistory = value.getString().split(";"); return arrHistory[3]; } return currentNode.getProperty("exo:dateModified").getString(); } } private String getDriveName(List<DriveData> lstDrive, Node node) throws RepositoryException{ String driveName = ""; for (DriveData drive : lstDrive) { if (node.getSession().getWorkspace().getName().equals(drive.getWorkspace()) && node.getPath().contains(drive.getHomePath()) && drive.getHomePath().equals("/")) { driveName = drive.getName(); break; } } return driveName; } public class PublishedNode { private String nodeName_; private String nodePath_; private String driveName_; private String datePublished_; public void setName(String nodeName) { nodeName_ = nodeName; } public String getName() { return nodeName_; } public void setPath(String nodePath) { nodePath_ = nodePath; } public String getPath() { return nodePath_; } public void setDriveName(String driveName) { driveName_ = driveName; } public String getDriveName() { return driveName_; } public void setDatePublished(String datePublished) { datePublished_ = datePublished; } public String getDatePublished() { return datePublished_; } } public class PublishedListNode { private List<PublishedNode> publishedListNode_; public void setPublishedListNode(List<PublishedNode> publishedListNode) { publishedListNode_ = publishedListNode; } public List<PublishedNode> getPublishedListNode() { return publishedListNode_; } } }
10,780
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DocumentEditorsRESTService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/DocumentEditorsRESTService.java
/* * Copyright (C) 2003-2020 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.connector.collaboration; import java.util.List; import java.util.stream.Collectors; import javax.annotation.security.RolesAllowed; import javax.jcr.AccessDeniedException; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.exoplatform.services.cms.documents.DocumentEditorProvider; import org.exoplatform.services.cms.documents.DocumentService; import org.exoplatform.services.cms.documents.exception.DocumentEditorProviderNotFoundException; import org.exoplatform.services.cms.documents.exception.PermissionValidationException; import org.exoplatform.services.cms.documents.impl.EditorProvidersHelper; import org.exoplatform.services.cms.documents.impl.EditorProvidersHelper.ProviderInfo; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ExtendedSession; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.organization.Group; import org.exoplatform.services.organization.OrganizationService; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.security.ConversationState; 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.manager.IdentityManager; 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.wcm.connector.collaboration.editors.DocumentEditorData; import org.exoplatform.wcm.connector.collaboration.editors.EditorPermission; import org.exoplatform.wcm.connector.collaboration.editors.ErrorMessage; import org.exoplatform.wcm.connector.collaboration.editors.HypermediaLink; import org.exoplatform.wcm.connector.collaboration.editors.PreviewInfo; import org.exoplatform.ws.frameworks.json.impl.JsonException; import org.exoplatform.ws.frameworks.json.impl.JsonGeneratorImpl; import jakarta.servlet.http.HttpServletRequest; /** * The Class DocumentEditorsRESTService is REST endpoint for working with editable documents. * */ @Path("/documents/editors") public class DocumentEditorsRESTService implements ResourceContainer { private static final String EXO_SYMLINK = "exo:symlink"; /** The Constant PROVIDER_NOT_REGISTERED. */ private static final String PROVIDER_NOT_REGISTERED = "EditorProviderNotRegistered"; /** The Constant EMPTY_REQUEST. */ private static final String EMPTY_REQUEST = "EmptyRequest"; /** The Constant CANNOT_GET_PROVIDERS. */ private static final String CANNOT_GET_PROVIDERS = "CannotGetProviders"; /** The Constant PERMISSION_NOT_VALID. */ private static final String PERMISSION_NOT_VALID = "PermissionNotValid"; /** The Constant CANNOT_SAVE_PREFERRED_EDITOR. */ private static final String CANNOT_SAVE_PREFERRED_EDITOR = "CannotSavePreferredEditor"; /** The Constant SELF. */ private static final String SELF = "self"; /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(DocumentEditorsRESTService.class); /** The document service. */ protected final DocumentService documentService; /** The document service. */ protected final OrganizationService organization; /** The document service. */ protected final SpaceService spaceService; /** The identity manager. */ protected final IdentityManager identityManager; /** The repository service. */ protected final RepositoryService repositoryService; /** The link manager. */ protected final LinkManager linkManager; /** * Instantiates a new document editors REST service. * * @param documentService the document service * @param spaceService the space service * @param organizationService the organization service * @param identityManager the identity manager * @param repositoryService the repository service * @param linkManager the link manager */ public DocumentEditorsRESTService(DocumentService documentService, SpaceService spaceService, OrganizationService organizationService, IdentityManager identityManager, RepositoryService repositoryService, LinkManager linkManager) { this.documentService = documentService; this.identityManager = identityManager; this.organization = organizationService; this.spaceService = spaceService; this.repositoryService = repositoryService; this.linkManager = linkManager; } /** * Return all available editor providers. * * @param uriInfo the uri info * @return the response */ @GET @RolesAllowed("administrators") @Produces(MediaType.APPLICATION_JSON) public Response getEditors(@Context UriInfo uriInfo) { List<DocumentEditorData> providers = documentService.getDocumentEditorProviders() .stream() .map(this::convertToDTO) .collect(Collectors.toList()); providers.forEach(provider -> initLinks(provider, uriInfo)); try { String json = new JsonGeneratorImpl().createJsonArray(providers).toString(); return Response.status(Status.OK).entity("{\"editors\":" + json + "}").build(); } catch (JsonException e) { LOG.error("Cannot get providers JSON, error: {}", e.getMessage()); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new ErrorMessage(e.getMessage(), CANNOT_GET_PROVIDERS)).build(); } } /** * Gets the preferred editor for specific user/document. * * @param uriInfo the uri info * @param provider the provider * @return the response */ @GET @Path("/{provider}") @RolesAllowed("administrators") @Produces(MediaType.APPLICATION_JSON) public Response getEditor(@Context UriInfo uriInfo, @PathParam("provider") String provider) { try { DocumentEditorProvider editorProvider = documentService.getEditorProvider(provider); DocumentEditorData providerData = convertToDTO(editorProvider); initLinks(providerData, uriInfo); return Response.status(Status.OK).entity(providerData).build(); } catch (DocumentEditorProviderNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(new ErrorMessage(e.getMessage(), PROVIDER_NOT_REGISTERED)).build(); } } /** * Saves the editor provider. * * @param provider the provider * @param documentEditorData the editor provider DTO * @return the response */ @PUT @Path("/{provider}") @RolesAllowed("administrators") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response updateEditor(@PathParam("provider") String provider, DocumentEditorData documentEditorData) { if (documentEditorData == null || documentEditorData.getActive() == null && documentEditorData.getPermissions() == null) { return Response.status(Status.BAD_REQUEST) .entity(new ErrorMessage("The request should contain active or/and permissions fields.", EMPTY_REQUEST)) .build(); } try { DocumentEditorProvider editorProvider = documentService.getEditorProvider(provider); if (documentEditorData.getActive() != null) { editorProvider.updateActive(documentEditorData.getActive()); } if (documentEditorData.getPermissions() != null) { List<String> permissions = documentEditorData.getPermissions() .stream() .map(permission -> permission.getId()) .collect(Collectors.toList()); editorProvider.updatePermissions(permissions); } return Response.status(Status.OK).build(); } catch (DocumentEditorProviderNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(new ErrorMessage(e.getMessage(), PROVIDER_NOT_REGISTERED)).build(); } catch (PermissionValidationException e) { return Response.status(Status.BAD_REQUEST).entity(new ErrorMessage(e.getMessage(), PERMISSION_NOT_VALID)).build(); } } /** * Sets the preferred editor for specific user/document. * * @param fileId the file id * @param userId the user id * @param provider the provider * @param workspace the workspace * @return the response */ @POST @Path("/preferred/{fileId}") @RolesAllowed("users") public Response preferredEditor(@PathParam("fileId") String fileId, @FormParam("userId") String userId, @FormParam("provider") String provider, @FormParam("workspace") String workspace) { try { documentService.savePreferredEditor(userId, provider, fileId, workspace); } catch (AccessDeniedException e) { LOG.error("Access denied to set preferred editor for user {} and node {}: {}", userId, fileId, e.getMessage()); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(new ErrorMessage("Access denied error.", CANNOT_SAVE_PREFERRED_EDITOR)) .build(); } catch (RepositoryException e) { LOG.error("Cannot set preferred editor for user {} and node {}: {}", userId, fileId, e.getMessage()); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(new ErrorMessage(e.getMessage(), CANNOT_SAVE_PREFERRED_EDITOR)) .build(); } return Response.ok().build(); } /** * Inits preview. * * @param uriInfo the uri info * @param request the request * @param fileId the file id * @param workspace the workspace * @return the response */ @POST @Path("/preview") @Produces(MediaType.APPLICATION_JSON) public Response initPreview(@Context UriInfo uriInfo, @Context HttpServletRequest request, @FormParam("fileId") String fileId, @FormParam("workspace") String workspace) { org.exoplatform.services.security.Identity identity = ConversationState.getCurrent().getIdentity(); List<DocumentEditorProvider> providers = documentService.getDocumentEditorProviders(); List<ProviderInfo> providersInfo = EditorProvidersHelper.getInstance() .initPreview(providers, identity, fileId, workspace, uriInfo.getRequestUri(), request.getLocale()); String targetFileId = fileId; try { targetFileId = getTargetFileId(fileId, workspace); } catch (RepositoryException e) { LOG.warn("Cannot get fileId from symlink taget.", e.getMessage()); } PreviewInfo previewInfo = new PreviewInfo(targetFileId, providersInfo); return Response.ok().entity(previewInfo).build(); } /** * Gets the symlink target file id. * * @param fileId the file id * @param workspace the workspace * @return the target file id * @throws RepositoryException the repository exception */ protected String getTargetFileId(String fileId, String workspace) throws RepositoryException { ExtendedSession systemSession = (ExtendedSession) repositoryService.getCurrentRepository().getSystemSession(workspace); Node node = systemSession.getNodeByIdentifier(fileId); if (node.isNodeType(EXO_SYMLINK)) { node = linkManager.getTarget(node, true); if (node != null) { return node.getUUID(); } } return fileId; } /** * Inits the links. * * @param provider the provider * @param uriInfo the uri info */ protected void initLinks(DocumentEditorData provider, UriInfo uriInfo) { String path = uriInfo.getAbsolutePath().toString(); if (!uriInfo.getPathParameters().containsKey("provider")) { StringBuilder pathBuilder = new StringBuilder(path); if (!path.endsWith("/")) { pathBuilder.append("/"); } path = pathBuilder.append(provider.getProvider()).toString(); } provider.addLink(SELF, new HypermediaLink(path.toString())); } /** * Convert to DTO. * * @param provider the provider * @return the document editor provider data */ protected DocumentEditorData convertToDTO(DocumentEditorProvider provider) { List<EditorPermission> permissions = provider.getPermissions().stream().map(permission -> { String[] temp = permission.split(":"); if (temp.length < 2) { // user permission String userId = temp[0]; Identity identity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId); if (identity != null) { Profile profile = identity.getProfile(); String avatarUrl = profile.getAvatarUrl() != null ? profile.getAvatarUrl() : LinkProvider.PROFILE_DEFAULT_AVATAR_URL; return new EditorPermission(userId, profile.getFullName(), avatarUrl); } return new EditorPermission(userId); } else { // space String groupId = temp[1]; Space space = spaceService.getSpaceByGroupId(groupId); if (space != null) { String displayName = space.getDisplayName(); String avatarUrl = space != null && space.getAvatarUrl() != null ? space.getAvatarUrl() : LinkProvider.SPACE_DEFAULT_AVATAR_URL; return new EditorPermission(groupId, displayName, avatarUrl); } else { // group Group group = null; try { group = organization.getGroupHandler().findGroupById(groupId); } catch (Exception e) { LOG.error("Cannot get group by id {}. {}", groupId, e.getMessage()); } if (group != null) { String displayName = group.getLabel(); String avatarUrl = LinkProvider.SPACE_DEFAULT_AVATAR_URL; return new EditorPermission(groupId, displayName, avatarUrl); } } return new EditorPermission(groupId); } }).collect(Collectors.toList()); return new DocumentEditorData(provider.getProviderName(), provider.isActive(), permissions); } }
16,294
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
GetEditedDocumentRESTService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/GetEditedDocumentRESTService.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.connector.collaboration; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; 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.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.utils.comparator.PropertyValueComparator; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.folksonomy.NewFolksonomyService; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.impl.core.query.QueryImpl; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Returns the latest edited documents. * * @LevelAPI Provisional * * @anchor GetEditedDocumentRESTService */ @Path("/presentation/document/edit/") public class GetEditedDocumentRESTService implements ResourceContainer { /** 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"; private RepositoryService repositoryService; private TemplateService templateService; private NewFolksonomyService newFolksonomyService; private ManageDriveService manageDriveService; private static final String DATE_MODIFIED = "exo:dateModified"; private static final String JCR_PRIMARYTYPE = "jcr:primaryType"; private static final String NT_BASE = "nt:base"; private static final String EXO_OWNER = "exo:owner"; private static final int NO_PER_PAGE = 5; private static final String QUERY_STATEMENT = "SELECT * FROM $0 WHERE $1 ORDER BY $2 DESC"; private static final String GADGET = "gadgets"; private boolean show_gadget = false; private static final Log LOG = ExoLogger.getLogger(GetEditedDocumentRESTService.class.getName()); public GetEditedDocumentRESTService(RepositoryService repositoryService, TemplateService templateService, NewFolksonomyService newFolksonomyService, ManageDriveService manageDriveService) { this.repositoryService = repositoryService; this.templateService = templateService; this.newFolksonomyService = newFolksonomyService; this.manageDriveService = manageDriveService; } /** * Returns the latest edited documents. * * @param repository The repository name. * @param showItems Returns the number of items in each page. * @param showGadgetWs Shows the gadget workspace or not. * @return Response inputstream. * @throws Exception * * @anchor GetEditedDocumentRESTService.getLastEditedDoc */ @Path("/{repository}/") @GET public Response getLastEditedDoc(@PathParam("repository") String repository, @QueryParam("showItems") String showItems, @QueryParam("showGadgetWs") String showGadgetWs) throws Exception { List<Node> lstLastEditedNode = getLastEditedNode(showItems, showGadgetWs); List<DocumentNode> lstDocNode = getDocumentData(lstLastEditedNode); ListEditDocumentNode listEditDocumentNode = new ListEditDocumentNode(); listEditDocumentNode.setLstDocNode(lstDocNode); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok(listEditDocumentNode, new MediaType("application", "json")) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } private List<Node> getLastEditedNode(String noOfItem, String showGadgetWs) throws Exception{ if (showGadgetWs != null && showGadgetWs.length() > 0) { show_gadget = Boolean.parseBoolean(showGadgetWs); } ArrayList<Node> lstNode = new ArrayList<Node>(); StringBuffer bf = new StringBuffer(1024); List<String> lstNodeType = templateService.getDocumentTemplates(); if (lstNodeType != null) { for (String nodeType : lstNodeType) { bf.append("(").append(JCR_PRIMARYTYPE).append("=").append("'").append(nodeType).append("'") .append(")").append(" OR "); } } if (bf.length() == 1) return null; bf.delete(bf.lastIndexOf("OR") - 1, bf.length()); if (noOfItem == null || noOfItem.trim().length() == 0) noOfItem = String.valueOf(NO_PER_PAGE); String queryStatement = StringUtils.replace(QUERY_STATEMENT, "$0", NT_BASE); queryStatement = StringUtils.replace(queryStatement, "$1", bf.toString()); queryStatement = StringUtils.replace(queryStatement, "$2", DATE_MODIFIED); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); try { String[] workspaces = manageableRepository.getWorkspaceNames(); List<String> lstWorkspace = new ArrayList<String>(); //Arrays.asList() return fixed size list; lstWorkspace.addAll(Arrays.asList(workspaces)); if (!show_gadget && lstWorkspace.contains(GADGET)) { lstWorkspace.remove(GADGET); } SessionProvider provider = WCMCoreUtils.createAnonimProvider(); QueryImpl query = null; Session session = null; QueryResult queryResult = null; QueryManager queryManager = null; for (String workspace : lstWorkspace) { session = provider.getSession(workspace, manageableRepository); queryManager = session.getWorkspace().getQueryManager(); query = (QueryImpl) queryManager.createQuery(queryStatement, Query.SQL); query.setLimit(Integer.parseInt(noOfItem)); query.setOffset(0); queryResult = query.execute(); puttoList(lstNode, queryResult.getNodes()); session.logout(); } } catch (RepositoryException e) { if (LOG.isErrorEnabled()) { LOG.error("Exception when execute SQL " + queryStatement, e); } } return lstNode; } private void puttoList(List<Node> lstNode, NodeIterator nodeIter) { if (nodeIter != null) { while (nodeIter.hasNext()) { lstNode.add(nodeIter.nextNode()); } } } private List<DocumentNode> getDocumentData(List<Node> lstNode) throws Exception { return getDocumentData(lstNode, String.valueOf(NO_PER_PAGE)); } private String getDateFormat(Calendar date) { return String.valueOf(date.getTimeInMillis()); } private List<DocumentNode> getDocumentData(List<Node> lstNode, String noOfItem) throws Exception { if (lstNode == null || lstNode.size() == 0) return null; List<DocumentNode> lstDocNode = new ArrayList<DocumentNode>(); DocumentNode docNode = null; StringBuilder tags = null; Collections.sort(lstNode, new PropertyValueComparator(DATE_MODIFIED, PropertyValueComparator.DESCENDING_ORDER)); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); List<DriveData> lstDrive = manageDriveService.getAllDrives(); for (Node node : lstNode) { docNode = new DocumentNode(); docNode.setName(node.getName()); docNode.setPath(node.getPath()); docNode.setLastAuthor(node.getProperty(EXO_OWNER).getString()); docNode.setLstAuthor(node.getProperty(EXO_OWNER).getString()); docNode.setDateEdited(getDateFormat(node.getProperty(DATE_MODIFIED).getDate())); tags = new StringBuilder(1024); List<Node> tagList = newFolksonomyService.getLinkedTagsOfDocumentByScope(NewFolksonomyService.PUBLIC, "", node, manageableRepository.getConfiguration() .getDefaultWorkspaceName()); for(Node tag : tagList) { tags.append(tag.getName()).append(", "); } if (tags.lastIndexOf(",") > 0) { tags.delete(tags.lastIndexOf(","), tags.length()); } docNode.setTags(tags.toString()); docNode.setDriveName(getDriveName(lstDrive, node)); if (lstDocNode.size() < Integer.parseInt(noOfItem)) lstDocNode.add(docNode); } return lstDocNode; } private String getDriveName(List<DriveData> lstDrive, Node node) throws RepositoryException{ String driveName = ""; for (DriveData drive : lstDrive) { if (node.getSession().getWorkspace().getName().equals(drive.getWorkspace()) && node.getPath().contains(drive.getHomePath()) && drive.getHomePath().equals("/")) { driveName = drive.getName(); break; } } return driveName; } public class DocumentNode { private String nodeName_; private String nodePath_; private String driveName_; private String dateEdited_; private String tags; private String lastAuthor; private String lstAuthor; public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public String getLastAuthor() { return lastAuthor; } public void setLastAuthor(String lastAuthor) { this.lastAuthor = lastAuthor; } public String getLstAuthor() { return lstAuthor; } public void setLstAuthor(String lstAuthor) { this.lstAuthor = lstAuthor; } public void setName(String nodeName) { nodeName_ = nodeName; } public String getName() { return nodeName_; } public void setPath(String nodePath) { nodePath_ = nodePath; } public String getPath() { return nodePath_; } public void setDriveName(String driveName) { driveName_ = driveName; } public String getDriveName() { return driveName_; } public String getDateEdited() { return dateEdited_; } public void setDateEdited(String dateEdited_) { this.dateEdited_ = dateEdited_; } } public class ListEditDocumentNode { private List<DocumentNode> lstDocNode; public List<DocumentNode> getLstDocNode() { return lstDocNode; } public void setLstDocNode(List<DocumentNode> lstDocNode) { this.lstDocNode = lstDocNode; } } }
12,271
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ResourceBundleConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/ResourceBundleConnector.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.connector.collaboration; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import org.exoplatform.services.resources.ResourceBundleService; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Gets the bundle that is based on the key and the locale. * * @LevelAPI Provisional * * @anchor ResourceBundleConnector */ @Path("/bundle/") public class ResourceBundleConnector implements ResourceContainer { /** * Gets the bundle that is based on the key and the locale. * * @param key The key used to get the bundle. * @param locale The locale used to get the bundle. * * @anchor ResourceBundleConnector.getBundle */ @GET @Path("/getBundle/") public Response getBundle ( @QueryParam("key") String key, @QueryParam("locale") String locale) { try { ResourceBundleService resourceBundleService = WCMCoreUtils.getService(ResourceBundleService.class); String resourceBundleNames[] = resourceBundleService.getSharedResourceBundleNames(); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element bundles = document.createElement("bundles"); bundles.setAttribute("locale", locale); String keys[] = key.split(","); Set<String> remainingKeys = new LinkedHashSet<String>(keys.length + 1, 1f); Collections.addAll(remainingKeys, keys); loop : for (String resourceBundleName : resourceBundleNames) { ResourceBundle resourceBundle = null; if(locale.indexOf("_") > 0) { resourceBundle = resourceBundleService.getResourceBundle(resourceBundleName, new Locale( locale.substring(0, locale.lastIndexOf("_")), locale.substring(locale.lastIndexOf("_") + 1, locale.length()))); } else { resourceBundle = resourceBundleService.getResourceBundle(resourceBundleName, new Locale(locale)); } for (Iterator<String> it = remainingKeys.iterator(); it.hasNext();) { String oneKey = it.next(); try { String value = resourceBundle.getString(oneKey); Element element = document.createElement(oneKey); element.setAttribute("value", value); bundles.appendChild(element); it.remove(); if (remainingKeys.isEmpty()) { break loop; } } catch (MissingResourceException e) { continue; } } } document.appendChild(bundles); CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); cacheControl.setNoStore(true); return Response.ok(new DOMSource(document), MediaType.TEXT_XML).cacheControl(cacheControl).build(); } catch (Exception e) { return Response.serverError().build(); } } }
4,136
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ThumbnailRESTService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/ThumbnailRESTService.java
/* * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.connector.collaboration; import java.awt.image.BufferedImage; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.jcr.*; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; import org.exoplatform.container.component.ComponentPlugin; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.cms.thumbnail.ThumbnailPlugin; import org.exoplatform.services.cms.thumbnail.ThumbnailService; import org.exoplatform.services.cms.thumbnail.impl.ThumbnailUtils; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ExtendedSession; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.impl.core.NodeImpl; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Returns a responding data as a thumbnail image. * {{{{repoName}}}}: The name of repository. * {{{{workspaceName}}}}: The name of workspace. * {{{{nodePath}}}}: The node path. * * {{{{portalname}}}}: The name of the portal. * {{{{restcontextname}}}}: The context name of REST web application which is deployed to the "{{{{portalname}}}}" portal. * * @LevelAPI Provisional * @anchor ThumbnailRESTService */ @Path("/thumbnailImage/") public class ThumbnailRESTService implements ResourceContainer { /** The log **/ private static final Log LOG = ExoLogger.getLogger(ThumbnailRESTService.class.getName()); /** The Constant LAST_MODIFIED_PROPERTY. */ public static final String LAST_MODIFIED_PROPERTY = "Last-Modified"; /** The Constant IF_MODIFIED_SINCE_DATE_FORMAT. */ public static final String IF_MODIFIED_SINCE_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z"; private final RepositoryService repositoryService_; private final ThumbnailService thumbnailService_; private final NodeFinder nodeFinder_; private final LinkManager linkManager_; public ThumbnailRESTService(RepositoryService repositoryService, ThumbnailService thumbnailService, NodeFinder nodeFinder, LinkManager linkManager) { repositoryService_ = repositoryService; thumbnailService_ = thumbnailService; nodeFinder_ = nodeFinder; linkManager_ = linkManager; } /** * Returns an image with a medium size (64x64). * For example: /portal/rest/thumbnailImage/medium/repository/collaboration/test.gif/ * * @param repoName The repository name. * @param workspaceName The workspace name. * @param nodePath The node path. * @return Response inputstream. * @throws Exception * * @anchor ThumbnailRESTService.getThumbnailImage */ @Path("/medium/{repoName}/{workspaceName}/{nodePath:.*}/") @GET public Response getThumbnailImage(@PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("nodePath") String nodePath, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { Node imageNode = getShowingNode(workspaceName, nodePath); return getThumbnailByType(imageNode, ThumbnailService.MEDIUM_SIZE, ifModifiedSince); } /** * Returns an image with a big size. * * @param repoName The repository name. * @param workspaceName The workspace name. * @param nodePath The node path. * @return Response inputstream. * @throws Exception * * @anchor ThumbnailRESTService.getCoverImage */ @Path("/big/{repoName}/{workspaceName}/{nodePath:.*}/") @GET public Response getCoverImage(@PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("nodePath") String nodePath, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { Node imageNode = getShowingNode(workspaceName, nodePath); return getThumbnailByType(imageNode, ThumbnailService.BIG_SIZE, ifModifiedSince); } /** * Returns an image with a large size (300x300). * * @param repoName The repository name. * @param workspaceName The workspace name. * @param nodePath The node path. * @return Response inputstream. * @throws Exception * * @anchor ThumbnailRESTService.getLargeImage */ @Path("/large/{repoName}/{workspaceName}/{nodePath:.*}/") @GET public Response getLargeImage(@PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("nodePath") String nodePath, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { Node imageNode = getShowingNode(workspaceName, nodePath); return getThumbnailByType(imageNode, ThumbnailService.BIG_SIZE, ifModifiedSince); } /** * Returns an image with a small size (32x32). * * @param repoName The repository name. * @param workspaceName The workspace name. * @param nodePath The node path. * @return Response inputstream. * @throws Exception * * @anchor ThumbnailRESTService.getSmallImage */ @Path("/small/{repoName}/{workspaceName}/{nodePath:.*}/") @GET public Response getSmallImage(@PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("nodePath") String nodePath, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { Node imageNode = getShowingNode(workspaceName, nodePath); return getThumbnailByType(imageNode, ThumbnailService.SMALL_SIZE, ifModifiedSince); } /** * Returns an image with a custom size. * * @param size The customized size of the image. * @param repoName The repository name. * @param workspaceName The workspace name. * @param nodePath The node path. * @return Response inputstream. * @throws Exception * * @anchor ThumbnailRESTService.getCustomImage */ @Path("/custom/{size}/{repoName}/{workspaceName}/{nodePath:.*}/") @GET public Response getCustomImage(@PathParam("size") String size, @PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("nodePath") String nodePath, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { Node imageNode = getShowingNode(workspaceName, nodePath); return getThumbnailByType(imageNode, "exo:" + size, ifModifiedSince); } /** * Returns an image with a custom size. * * @param size The customized size of the image. * @param workspaceName The workspace name. * @param identifier The identifier. * @return Response inputstream. * @throws Exception * * @anchor ThumbnailRESTService.getCustomImage */ @Path("/custom/{size}/{workspaceName}/{identifier}") @GET public Response getCustomImage(@PathParam("size") String size, @PathParam("workspaceName") String workspaceName, @PathParam("identifier") String identifier, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { Session session = WCMCoreUtils.getUserSessionProvider().getSession(workspaceName, SessionProviderService.getRepository()); Node imageNode = ((ExtendedSession) session).getNodeByIdentifier(identifier); return getThumbnailByType(imageNode, "exo:" + size, ifModifiedSince); } /** * Returns an image with an original size. * * @param repoName The repository name. * @param workspaceName The workspace name. * @param nodePath The node path. * @return Response data stream. * @throws Exception * * @anchor ThumbnailRESTService.getOriginImage */ @Path("/origin/{repoName}/{workspaceName}/{nodePath:.*}/") @GET public Response getOriginImage(@PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("nodePath") String nodePath, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception { DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); if (!thumbnailService_.isEnableThumbnail()) return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); Node showingNode = getShowingNode(workspaceName, nodePath); Node targetNode = getTargetNode(showingNode); if (targetNode.isNodeType("nt:file") || targetNode.isNodeType("nt:resource")) { Node content = targetNode; if (targetNode.isNodeType("nt:file")) content = targetNode.getNode("jcr:content"); if (ifModifiedSince != null) { // get last-modified-since from header Date ifModifiedSinceDate = dateFormat.parse(ifModifiedSince); // get last modified date of node Date lastModifiedDate = content.getProperty("jcr:lastModified").getDate().getTime(); // Check if cached resource has not been modifed, return 304 code if (ifModifiedSinceDate.getTime() >= lastModifiedDate.getTime()) { return Response.notModified().build(); } } String mimeType = content.getProperty("jcr:mimeType").getString(); for (ComponentPlugin plugin : thumbnailService_.getComponentPlugins()) { if (plugin instanceof ThumbnailPlugin) { ThumbnailPlugin thumbnailPlugin = (ThumbnailPlugin) plugin; if (thumbnailPlugin.getMimeTypes().contains(mimeType)) { InputStream inputStream = content.getProperty("jcr:data").getStream(); return Response.ok(inputStream, "image").header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } } } } return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } private Response getThumbnailByType(Node imageNode, String propertyName, String ifModifiedSince) throws Exception { DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); if (!thumbnailService_.isEnableThumbnail()) return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); Node targetNode = getTargetNode(imageNode); Node parentNode = null; try { parentNode = imageNode.getParent(); } catch (AccessDeniedException e) { Session session = imageNode.getSession(); parentNode = session.getItem(imageNode.getPath()).getParent(); } if(targetNode.isNodeType("nt:file")) { Node content = targetNode.getNode("jcr:content"); String mimeType = content.getProperty("jcr:mimeType").getString(); for(ComponentPlugin plugin : thumbnailService_.getComponentPlugins()) { if(plugin instanceof ThumbnailPlugin) { ThumbnailPlugin thumbnailPlugin = (ThumbnailPlugin) plugin; if(thumbnailPlugin.getMimeTypes().contains(mimeType)) { Node thumbnailFolder = ThumbnailUtils.getThumbnailFolder(parentNode); Node thumbnailNode = ThumbnailUtils.getThumbnailNode(thumbnailFolder, ((NodeImpl)imageNode).getIdentifier()); if(!thumbnailNode.hasProperty(propertyName)) { try { BufferedImage image = thumbnailPlugin.getBufferedImage(content, targetNode.getPath()); thumbnailService_.addThumbnailImage(thumbnailNode, image, propertyName); } catch (UnsatisfiedLinkError e) { LOG.error("Failed to get image: " + e.getMessage(), e); return Response.serverError().entity(e.getMessage()).build(); } } if(ifModifiedSince != null && thumbnailNode.hasProperty(ThumbnailService.THUMBNAIL_LAST_MODIFIED)) { // get last-modified-since from header Date ifModifiedSinceDate = dateFormat.parse(ifModifiedSince); // get last modified date of node Date lastModifiedDate = thumbnailNode.getProperty(ThumbnailService.THUMBNAIL_LAST_MODIFIED) .getDate() .getTime(); // Check if cached resource has not been modifed, return 304 code if (ifModifiedSinceDate.getTime() >= lastModifiedDate.getTime()) { return Response.notModified().build(); } } InputStream inputStream = null; if(thumbnailNode.hasProperty(propertyName)) { inputStream = thumbnailNode.getProperty(propertyName).getStream(); } return Response.ok(inputStream, "image").header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } } } } return getThumbnailRes(parentNode, ((NodeImpl)imageNode).getIdentifier(), propertyName, ifModifiedSince); } private Response getThumbnailRes(Node parentNode, String identifier, String propertyName, String ifModifiedSince) throws Exception { DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); if(parentNode.hasNode(ThumbnailService.EXO_THUMBNAILS_FOLDER)) { Node thumbnailFolder = parentNode.getNode(ThumbnailService.EXO_THUMBNAILS_FOLDER); if(thumbnailFolder.hasNode(identifier)) { Node thumbnailNode = thumbnailFolder.getNode(identifier); if (ifModifiedSince != null && thumbnailNode.hasProperty("exo:dateModified")) { // get last-modified-since from header Date ifModifiedSinceDate = dateFormat.parse(ifModifiedSince); // get last modified date of node Date lastModifiedDate = thumbnailNode.getProperty("exo:dateModified").getDate().getTime(); // Check if cached resource has not been modified, return 304 code if (ifModifiedSinceDate.getTime() >= lastModifiedDate.getTime()) { return Response.notModified().build(); } } if(thumbnailNode.hasProperty(propertyName)) { InputStream inputStream = thumbnailNode.getProperty(propertyName).getStream(); return Response.ok(inputStream, "image").header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } } } return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } private String getNodePath(String nodePath) throws Exception { ArrayList<String> encodeNameArr = new ArrayList<String>(); if(!nodePath.equals("/")) { for(String name : nodePath.split("/")) { if(name.length() > 0) { encodeNameArr.add(Text.escapeIllegalJcrChars(name)); } } StringBuilder encodedPath = new StringBuilder(); for(String encodedName : encodeNameArr) { encodedPath.append("/").append(encodedName); } nodePath = encodedPath.toString(); } return nodePath; } private Node getTargetNode(Node showingNode) throws Exception { Node targetNode = null; if (linkManager_.isLink(showingNode)) { try { targetNode = linkManager_.getTarget(showingNode); } catch (ItemNotFoundException e) { targetNode = showingNode; } } else { targetNode = showingNode; } return targetNode; } private Node getShowingNode(String workspaceName, String nodePath) throws Exception { Session session = WCMCoreUtils.getUserSessionProvider().getSession(workspaceName, SessionProviderService.getRepository()); if(nodePath.equals("/")) { return session.getRootNode(); } else { if (!nodePath.startsWith("/")) { nodePath = "/" + nodePath; } try { return (Node) nodeFinder_.getItem(session, nodePath); } catch (PathNotFoundException e) { try { return (Node) nodeFinder_.getItem(session, getNodePath(nodePath)); } catch (PathNotFoundException e1) { return null; } } } } }
18,134
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FavoriteRESTService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/FavoriteRESTService.java
package org.exoplatform.wcm.connector.collaboration; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import javax.jcr.ItemNotFoundException; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.utils.comparator.PropertyValueComparator; import org.exoplatform.services.cms.documents.FavoriteService; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; /** * Returns a list of favorite documents of a given user. * * @LevelAPI Provisional * * @anchor FavoriteRESTService */ @Path("/favorite/") public class FavoriteRESTService implements ResourceContainer { private final FavoriteService favoriteService; private ManageDriveService manageDriveService; private static final String DATE_MODIFIED = "exo:dateModified"; private static final String TITLE = "exo:title"; private static final int NO_PER_PAGE = 10; /** 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"; private static final Log LOG = ExoLogger.getLogger(FavoriteRESTService.class.getName()); public FavoriteRESTService(FavoriteService favoriteService, ManageDriveService manageDriveService) { this.favoriteService = favoriteService; this.manageDriveService = manageDriveService; } /** * Returns a list of favorite documents of a given user. * * @param repoName The repository name. * @param workspaceName The workspace name. * @param userName The username. * @param showItems Shows the number of items per page. * @return Response inputstream. * @throws Exception * * @anchor FavoriteRESTService.getFavoriteByUser */ @GET @Path("/all/{repoName}/{workspaceName}/{userName}") public Response getFavoriteByUser(@PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("userName") String userName, @QueryParam("showItems") String showItems) throws Exception { List<FavoriteNode> listFavorites = new ArrayList<FavoriteNode>(); List<DriveData> listDrive = manageDriveService.getAllDrives(); if (StringUtils.isEmpty(showItems)) { showItems = String.valueOf(NO_PER_PAGE); } try { List<Node> listNodes = favoriteService.getAllFavoriteNodesByUser(userName,0); Collections.sort(listNodes, new PropertyValueComparator(DATE_MODIFIED, PropertyValueComparator.DESCENDING_ORDER)); FavoriteNode favoriteNode; for (Node favorite : listNodes) { favoriteNode = new FavoriteNode(); favoriteNode.setName(favorite.getName()); favoriteNode.setTitle(getTitle(favorite)); favoriteNode.setDateAddFavorite(getDateFormat(favorite.getProperty(DATE_MODIFIED).getDate())); favoriteNode.setDriveName(getDriveName(listDrive, favorite)); favoriteNode.setPath(favorite.getPath()); if (favoriteNode != null) { if (listFavorites.size() < Integer.valueOf(showItems)) listFavorites.add(favoriteNode); } } } catch (ItemNotFoundException e) { if (LOG.isErrorEnabled()) { LOG.error(e); } return Response.serverError().build(); } catch (RepositoryException e) { if (LOG.isErrorEnabled()) { LOG.error(e); } return Response.serverError().build(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(e); } return Response.serverError().build(); } ListResultNode listResultNode = new ListResultNode(); listResultNode.setListFavorite(listFavorites); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok(listResultNode, new MediaType("application", "json")) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } private String getTitle(Node node) throws Exception { if (node.hasProperty(TITLE)) return node.getProperty(TITLE).getString(); return node.getName(); } private String getDateFormat(Calendar date) { return String.valueOf(date.getTimeInMillis()); } private String getDriveName(List<DriveData> listDrive, Node node) throws RepositoryException{ String driveName = ""; for (DriveData drive : listDrive) { if (node.getSession().getWorkspace().getName().equals(drive.getWorkspace()) && node.getPath().contains(drive.getHomePath()) && drive.getHomePath().equals("/")) { driveName = drive.getName(); break; } } return driveName; } public class ListResultNode { private List<? extends FavoriteNode> listFavorite; public List<? extends FavoriteNode> getListFavorite() { return listFavorite; } public void setListFavorite(List<? extends FavoriteNode> listFavorite) { this.listFavorite = listFavorite; } } public class FavoriteNode { private String name; private String nodePath; private String dateAddFavorite; private String driveName; private String title; public String getName() { return name; } public void setName(String name) { this.name = name; } public void setPath(String path) { this.nodePath = path; } public String getPath() { return nodePath; } public void setDateAddFavorite(String dateAddFavorite) { this.dateAddFavorite = dateAddFavorite; } public String getDateAddFavorite() { return dateAddFavorite; } public void setDriveName(String driveName) { this.driveName = driveName; } public String getDriveName() { return driveName; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } } }
6,520
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DownloadConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/DownloadConnector.java
package org.exoplatform.wcm.connector.collaboration; import org.exoplatform.common.http.HTTPStatus; import org.exoplatform.ecm.utils.text.Text; 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.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import javax.jcr.AccessDeniedException; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.Session; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.InputStream; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; /** * Enables downloading the content of _nt\:file_. * * @LevelAPI Provisional * * @anchor DownloadConnector */ @Path("/contents/") public class DownloadConnector implements ResourceContainer{ private static final Log LOG = ExoLogger.getLogger(DownloadConnector.class.getName()); /** * Returns to browser a stream got from _jcr\:content_/_jcr\:data_ for downloading the content of the node. * * @param workspace The workspace where stores the document node. * @param path The path to the document node. * @param version The version name. * @return the instance of javax.ws.rs.core.Response. * @throws Exception The exception * * @anchor DownloadConnector.download */ @GET @Path("/download/{workspace}/{path:.*}") public Response download(@PathParam("workspace") String workspace, @PathParam("path") String path, @QueryParam("version") String version) throws Exception { InputStream is = null; String mimeType = MediaType.TEXT_XML; Node node = null; String fileName = null; SessionProvider sessionProvider = WCMCoreUtils.getUserSessionProvider(); ManageableRepository manageableRepository = WCMCoreUtils.getRepository(); Session session = sessionProvider.getSession(workspace, manageableRepository); if (!path.startsWith("/")) { path = "/" + path; } try { path = URLDecoder.decode(path, StandardCharsets.UTF_8); } catch (Exception e) { LOG.debug("The filePath is already decoded"); } try { node = (Node) session.getItem(path); fileName = node.getName(); if (node.hasProperty("exo:title")){ fileName = node.getProperty("exo:title").getString(); } // decode the fileName in case the fileName is already encoded, for the old uploaded files. try { fileName = URLDecoder.decode(fileName, "UTF-8"); }catch (Exception e){ LOG.debug("The fileName is already decoded"); } fileName = Text.unescapeIllegalJcrChars(fileName); fileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20"); // In case version is specified, get file from version history if (version != null) { node = node.getVersionHistory().getVersion(version).getNode("jcr:frozenNode"); } Node jrcNode = node.getNode("jcr:content"); is = jrcNode.getProperty("jcr:data").getStream(); }catch (PathNotFoundException pne) { return Response.status(HTTPStatus.NOT_FOUND).build(); } catch (AccessDeniedException ade) { LOG.warn("You have not enough permissions on file: {}", fileName); return Response.status(HTTPStatus.NOT_FOUND).build(); } if (node.isNodeType("nt:file") || (node.isNodeType("nt:frozenNode")) && node.getProperty("jcr:frozenPrimaryType").getValue().getString().equals("nt:file")) { mimeType = node.getNode("jcr:content").getProperty("jcr:mimeType").getString(); } return Response.ok(is, mimeType) .header("Content-Disposition","attachment; filename=\"" + fileName + "\"; filename*=UTF-8''" + fileName) .build(); } }
4,071
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
RESTImagesRendererService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/RESTImagesRendererService.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.connector.collaboration; import java.io.InputStream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.jcr.ItemNotFoundException; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.version.VersionHistory; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import org.exoplatform.common.http.HTTPStatus; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.core.WCMService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Gets the image binary data of a given image node. * * @LevelAPI Provisional * * @anchor RESTImagesRendererService */ @Path("/images/") public class RESTImagesRendererService implements ResourceContainer{ /** The session provider service. */ private SessionProviderService sessionProviderService; /** The repository service. */ private RepositoryService repositoryService; /** The log. */ private static final Log LOG = ExoLogger.getLogger(RESTImagesRendererService.class.getName()); /** 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"; /** Default mime type **/ private static String DEFAULT_MIME_TYPE = "image/jpg"; /** Mime type property **/ private static String PROPERTY_MIME_TYPE = "jcr:mimeType"; /** * Instantiates a new REST images renderer service. * * @param repositoryService The repository service. * @param sessionProviderService The session provider service. */ public RESTImagesRendererService(RepositoryService repositoryService, SessionProviderService sessionProviderService) { this.repositoryService = repositoryService; this.sessionProviderService = sessionProviderService; } /** * Gets the image binary data of a given image node. * @param repositoryName The repository. * @param workspaceName The workspace. * @param nodeIdentifier The node identifier. * @param param Checks if the document is a file or not. The default value is "file". * @param ifModifiedSince Checks the modification date. * @return The response * * @anchor RESTImagesRendererService.serveImage */ @GET @Path("/{repositoryName}/{workspaceName}/{nodeIdentifier}") public Response serveImage(@PathParam("repositoryName") String repositoryName, @PathParam("workspaceName") String workspaceName, @PathParam("nodeIdentifier") String nodeIdentifier, @QueryParam("param") @DefaultValue("file") String param, @HeaderParam("If-Modified-Since") String ifModifiedSince) { try { SessionProvider sessionProvider = sessionProviderService.getSessionProvider(null); WCMService wcmService = WCMCoreUtils.getService(WCMService.class); Node node = wcmService.getReferencedContent(sessionProvider, workspaceName, nodeIdentifier); if (node == null) return Response.status(HTTPStatus.NOT_FOUND).build(); if ("file".equals(param)) { Node dataNode = null; if(WCMCoreUtils.isNodeTypeOrFrozenType(node, NodetypeConstant.NT_FILE)) { dataNode = node; }else if(node.isNodeType("nt:versionedChild")) { VersionHistory versionHistory = (VersionHistory)node.getProperty("jcr:childVersionHistory").getNode(); String versionableUUID = versionHistory.getVersionableUUID(); dataNode = sessionProvider.getSession(workspaceName, repositoryService.getCurrentRepository()) .getNodeByUUID(versionableUUID); }else { return Response.status(HTTPStatus.NOT_FOUND).build(); } if (ifModifiedSince != null && isModified(ifModifiedSince, dataNode) == false) { return Response.notModified().build(); } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); Node jcrContentNode = dataNode.getNode("jcr:content"); String mimeType = DEFAULT_MIME_TYPE; if (jcrContentNode.hasProperty(PROPERTY_MIME_TYPE)) { mimeType = jcrContentNode.getProperty(PROPERTY_MIME_TYPE).getString(); } InputStream jcrData = jcrContentNode.getProperty("jcr:data").getStream(); return Response.ok(jcrData, mimeType).header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } if (ifModifiedSince != null && isModified(ifModifiedSince, node) == false) { return Response.notModified().build(); } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); InputStream jcrData = node.getProperty(param).getStream(); return Response.ok(jcrData, DEFAULT_MIME_TYPE).header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } catch (PathNotFoundException e) { return Response.status(HTTPStatus.NOT_FOUND).build(); }catch (ItemNotFoundException e) { return Response.status(HTTPStatus.NOT_FOUND).build(); }catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when serveImage: ", e); } return Response.serverError().build(); } } /** * Gets the last modified date of a node. + * @param node A specific node. + * @return The last modified date. + * @throws Exception + */ private Date getLastModifiedDate(Node node) throws Exception { Date lastModifiedDate = null; if (node.hasNode("jcr:content") && node.getNode("jcr:content").hasProperty("jcr:lastModified")) { lastModifiedDate = node.getNode("jcr:content").getProperty("jcr:lastModified").getDate().getTime(); } else if (node.hasProperty("exo:dateModified")) { lastModifiedDate = node.getProperty("exo:dateModified").getDate().getTime(); } else if (node.hasProperty("jcr:created")){ lastModifiedDate = node.getProperty("jcr:created").getDate().getTime(); } return lastModifiedDate; } /** * Checks if resources were modified or not. * @param ifModifiedSince The date when the node is modified. * @param node A specific node. * @return * @throws Exception */ private boolean isModified(String ifModifiedSince, Node node) throws Exception { // get last-modified-since from header DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); if(ifModifiedSince == null || ifModifiedSince.length() == 0) return false; try { Date ifModifiedSinceDate = dateFormat.parse(ifModifiedSince); // get last modified date of node Date lastModifiedDate = getLastModifiedDate(node); // Check if cached resource has not been modifed, return 304 code if (lastModifiedDate != null && ifModifiedSinceDate != null && ifModifiedSinceDate.getTime() >= lastModifiedDate.getTime()) { return false; } return true; } catch(ParseException pe) { return false; } } }
8,699
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
RssConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/RssConnector.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.connector.collaboration; import java.io.ByteArrayInputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.jcr.Node; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import com.rometools.rome.feed.synd.SyndContent; import com.rometools.rome.feed.synd.SyndContentImpl; import com.rometools.rome.feed.synd.SyndEntry; import com.rometools.rome.feed.synd.SyndEntryImpl; import com.rometools.rome.feed.synd.SyndFeed; import com.rometools.rome.feed.synd.SyndFeedImpl; import com.rometools.rome.io.SyndFeedOutput; import org.exoplatform.services.jcr.util.Text; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.core.WCMConfigurationService; import org.exoplatform.services.wcm.publication.WCMComposer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.connector.BaseConnector; import org.w3c.dom.Document; /** * Generates an RSS feed. * * @LevelAPI Provisional * @anchor RssConnector */ @Path("/feed/") public class RssConnector extends BaseConnector implements ResourceContainer { /** The WORKSPACE. */ static private String WORKSPACE = "workspace" ; /** The REPOSITORY. */ static private String REPOSITORY = "repository" ; /** The RS s_ version. */ static private String RSS_VERSION = "rss_2.0" ; /** The FEE d_ title. */ static private String FEED_TITLE = "exo:feedTitle" ; /** The DESCRIPTION. */ static private String DESCRIPTION = "exo:description" ; /** The TITLE. */ static private String TITLE = "exo:title"; /** The LINK. */ static private String LINK = "exo:link" ; /** The SUMMARY. */ static private String SUMMARY = "exo:summary"; /** The detail page */ static private String DETAIL_PAGE = "detail-page"; /** The detail get param */ static private String DETAIL_PARAM = "detail-param"; /** The wcm composer service. */ private WCMComposer wcmComposer; /** The wcm configuration service. */ private WCMConfigurationService wcmConfigurationService; /** The log. */ private static final Log LOG = ExoLogger.getLogger(RssConnector.class.getName()); /** * Instantiates a new RSS connector. */ public RssConnector() { this.wcmConfigurationService = WCMCoreUtils.getService(WCMConfigurationService.class); this.wcmComposer = WCMCoreUtils.getService(WCMComposer.class); } /** * Generates an RSS feed. * * @param repository The repository name. * @param workspace The workspace name. * @param server The server. * @param siteName The name of site. * @param title The title of the feed. * @param desc The description of the feed. * @param folderPath The folder path of the feed. * @param orderBy The criteria to order the content. * @param orderType The descending or ascending order. * @param lang The language of the feed. * @param detailPage The page used to open the content. * @param detailParam The parameters are the key in the URL to let CLV know which really is the path in the current URL. * @param recursive This param is deprecated and will be moved soon. * @return The response. * @throws Exception The exception * * @anchor RssConnector.generate */ @GET @Path("/rss/") public Response generate(@QueryParam("repository") String repository, @QueryParam("workspace") String workspace, @QueryParam("server") String server, @QueryParam("siteName") String siteName, @QueryParam("title") String title, @QueryParam("desc") String desc, @QueryParam("folderPath") String folderPath, @QueryParam("orderBy") String orderBy, @QueryParam("orderType") String orderType, @QueryParam("lang") String lang, @QueryParam("detailPage") String detailPage, @QueryParam("detailParam") String detailParam, @QueryParam("recursive") String recursive) throws Exception { Map<String, String> contextRss = new HashMap<String, String>(); contextRss.put(REPOSITORY, repository); contextRss.put(WORKSPACE, workspace); contextRss.put(RSS_VERSION, "rss_2.0"); contextRss.put(FEED_TITLE, title); if (desc == null) desc = "Powered by eXo Platform"; contextRss.put(DESCRIPTION, desc); contextRss.put(LINK, server); if (detailPage == null) detailPage = wcmConfigurationService.getRuntimeContextParam(WCMConfigurationService.PARAMETERIZED_PAGE_URI); contextRss.put(DETAIL_PAGE, detailPage); if (detailParam == null) detailParam = "content-id"; contextRss.put(DETAIL_PARAM, detailParam); HashMap<String, String> filters = new HashMap<String, String>(); filters.put(WCMComposer.FILTER_MODE, WCMComposer.MODE_LIVE); if (orderType == null) orderType = "DESC"; if (orderBy == null) orderBy = "publication:liveDate"; if (lang == null) lang = "en"; filters.put(WCMComposer.FILTER_ORDER_BY, orderBy); filters.put(WCMComposer.FILTER_ORDER_TYPE, orderType); filters.put(WCMComposer.FILTER_LANGUAGE, lang); filters.put(WCMComposer.FILTER_RECURSIVE, recursive); String path=null; if (folderPath!=null) { path = folderPath; } List<Node> nodes = wcmComposer.getContents(workspace, path, filters, WCMCoreUtils.getUserSessionProvider()); String feedXML = generateRSS(nodes, contextRss); Document document = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(new ByteArrayInputStream(feedXML.getBytes())); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); Response response = Response.ok(new DOMSource(document), MediaType.TEXT_XML) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); return response; } /** * Generates RSS. * * @param context The context. * @return the string */ private String generateRSS(List<Node> nodes , Map<String, String> context) { String rssVersion = context.get(RSS_VERSION) ; String feedTitle = context.get(FEED_TITLE) ; String feedDescription = context.get(DESCRIPTION) ; String feedLink = context.get(LINK) ; String detailPage = context.get(DETAIL_PAGE) ; String detailParam = context.get(DETAIL_PARAM) ; String repository = context.get(REPOSITORY) ; String workspace = context.get(WORKSPACE) ; String contentUrl; if (!feedLink.endsWith("/")) { contentUrl = feedLink + "/" + detailPage + "?" + detailParam + "=/" + repository + "/" + workspace; } else { contentUrl = feedLink + detailPage + "?" + detailParam + "=/" + repository + "/" + workspace; } if(feedTitle == null || feedTitle.length() == 0) feedTitle = "" ; try { SyndFeed feed = new SyndFeedImpl(); feed.setFeedType(rssVersion); feed.setTitle(feedTitle.replaceAll("&nbsp;", " ")); feed.setLink(feedLink); feed.setDescription(feedDescription.replaceAll("&nbsp;", " ")); feed.setEncoding("UTF-8"); List<SyndEntry> entries = new ArrayList<SyndEntry>(); Iterator<Node> iter = nodes.iterator(); while (iter.hasNext()) { Node node = iter.next(); StringBuilder url= new StringBuilder(); url.append(contentUrl); if (node.isNodeType("nt:frozenNode")) { String uuid = node.getProperty("jcr:frozenUuid").getString(); Node originalNode = node.getSession().getNodeByUUID(uuid); url.append(originalNode.getPath()); url.append("&version="); url.append(node.getParent().getName()); } else { url.append(node.getPath()); } SyndEntry entry = new SyndEntryImpl(); if (node.hasProperty(TITLE)) { String nTitle = node.getProperty(TITLE).getString(); //encoding nTitle = Text.unescapeIllegalJcrChars(new String(nTitle.getBytes("UTF-8"))); entry.setTitle(Text.encodeIllegalXMLCharacters(nTitle).replaceAll("&quot;", "\"").replaceAll("&apos;", "\'")); } else entry.setTitle("") ; entry.setLink(url.toString()); SyndContent description = new SyndContentImpl(); description.setType("text/plain"); if (node.hasProperty(SUMMARY)){ String summary=Text.encodeIllegalXMLCharacters(node.getProperty(SUMMARY) .getString()) .replaceAll("&nbsp;", " ").replaceAll("&amp;quot;", "\"").replaceAll("&apos;", "\'"); description.setValue(summary); }else description.setValue(""); entry.setDescription(description); entries.add(entry); entry.getEnclosures() ; } feed.setEntries(entries); SyndFeedOutput output = new SyndFeedOutput(); return output.outputString(feed); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform generateRSS: ", e); } } return null; } /* (non-Javadoc) * @see org.exoplatform.wcm.connector.BaseConnector#getContentStorageType() */ protected String getContentStorageType() throws Exception { return null; } /* (non-Javadoc) * @see org.exoplatform.wcm.connector.BaseConnector#getRootContentStorage(javax.jcr.Node) */ protected Node getRootContentStorage(Node node) throws Exception { return null; } }
11,062
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
RenameConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/RenameConnector.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.collaboration; import org.apache.commons.lang3.StringUtils; import org.exoplatform.common.http.HTTPStatus; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.services.cms.CmsService; import org.exoplatform.services.cms.impl.Utils; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.cms.lock.LockService; import org.exoplatform.services.cms.relations.RelationsService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.listener.ListenerService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.publication.WCMPublicationService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import javax.annotation.security.RolesAllowed; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Property; import javax.jcr.PropertyIterator; import javax.jcr.Session; import javax.jcr.lock.LockException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The RenameConnector aims to enhance the use of the _rename_ action on the Sites Explorer. * The system allows setting two values: _name_ and _title_. * The _title_ is a logical name that is used to display in the Sites Explorer. * The _name_ is the technical name of the file at JCR level. It is notably exposed via the WEBDAV layer. * * @LevelAPI Experimental * * @anchor RenameConnector */ @Path("/contents/rename/") public class RenameConnector implements ResourceContainer { private static final Log LOG = ExoLogger.getLogger(RenameConnector.class.getName()); private static final Pattern FILE_EXPLORER_URL_SYNTAX = Pattern.compile("([^:/]+):(/.*)"); private static final String RELATION_PROP = "exo:relation"; private static final String DEFAULT_NAME = "untitled"; /** * Gets _objectid_ of the renamed node. * Basically, _objectid_ is a pattern which is useful to find HTML tags of a specific node. * _objectid_ actually is the node path encoded by _URLEncoder_. * * @param nodePath The node path * @return _objectid_ * @throws Exception The exception * * @anchor RenameConnector.getObjectId */ @GET @Path("/getObjectId/") public Response getObjectId(@QueryParam("nodePath") String nodePath) throws Exception { return Response.ok(Utils.getObjectId(nodePath), MediaType.TEXT_PLAIN).build(); } /** * Calls RenameConnector REST service to execute the "_rename_" process. * * @param oldPath The old path of the renamed node with syntax: [workspace:node path] * @param newTitle The new title of the node. * @return Httpstatus 400 if renaming fails, otherwise the UUID of the renamed node is returned. * @throws Exception The exception * * @anchor RenameConnector.rename */ @GET @Path("/rename/") @RolesAllowed("users") public Response rename(@QueryParam("oldPath") String oldPath, @QueryParam("newTitle") String newTitle) throws Exception { try { // Check and escape newTitle if (StringUtils.isBlank(newTitle)) { return Response.status(HTTPStatus.BAD_REQUEST).build(); } String newExoTitle = newTitle; // Clarify new name & check to add extension String newName = Text.escapeIllegalJcrChars(Utils.cleanString(newTitle)); //clean node name newName = Utils.cleanName(newName); newName = URLDecoder.decode(newName,"UTF-8"); // Set default name if new title contain no valid character newName = (StringUtils.isEmpty(newName)) ? DEFAULT_NAME : newName; // Get renamed node String[] workspaceAndPath = parseWorkSpaceNameAndNodePath(oldPath); Node renamedNode = (Node)WCMCoreUtils.getService(NodeFinder.class) .getItem(this.getSession(workspaceAndPath[0]), workspaceAndPath[1], false); String oldName = renamedNode.getName(); if (oldName.indexOf('.') != -1 && renamedNode.isNodeType(NodetypeConstant.NT_FILE)) { String ext = oldName.substring(oldName.lastIndexOf('.')); newName = newName.concat(ext); newExoTitle = newExoTitle.concat(ext); } // Stop process if new name and exo:title is the same with old one String oldExoTitle = (renamedNode.hasProperty("exo:title")) ? renamedNode.getProperty("exo:title") .getString() : StringUtils.EMPTY; CmsService cmsService = WCMCoreUtils.getService(CmsService.class); cmsService.getPreProperties().clear(); String nodeUUID = ""; if(renamedNode.isNodeType(NodetypeConstant.MIX_REFERENCEABLE)) nodeUUID = renamedNode.getUUID(); cmsService.getPreProperties().put(nodeUUID + "_" + "exo:title", oldExoTitle); if (renamedNode.getName().equals(newName) && oldExoTitle.equals(newExoTitle)) { return Response.status(HTTPStatus.BAD_REQUEST).build(); } // Check if can edit locked node if (!this.canEditLockedNode(renamedNode)) { return Response.status(HTTPStatus.BAD_REQUEST).build(); } // Get uuid if (renamedNode.canAddMixin(NodetypeConstant.MIX_REFERENCEABLE)) { renamedNode.addMixin(NodetypeConstant.MIX_REFERENCEABLE); renamedNode.save(); } String uuid = renamedNode.getUUID(); // Only execute renaming if name is changed Session nodeSession = renamedNode.getSession(); if (!renamedNode.getName().equals(newName)) { // Backup relations pointing to the rename node List<Node> refList = new ArrayList<Node>(); PropertyIterator references = renamedNode.getReferences(); RelationsService relationsService = WCMCoreUtils.getService(RelationsService.class); while (references.hasNext()) { Property pro = references.nextProperty(); Node refNode = pro.getParent(); if (refNode.hasProperty(RELATION_PROP)) { refList.add(refNode); relationsService.removeRelation(refNode, renamedNode.getPath()); } } // Change name Node parent = renamedNode.getParent(); String srcPath = renamedNode.getPath(); String destPath = (parent.getPath().equals("/") ? StringUtils.EMPTY : parent.getPath()) + "/" + newName; this.addLockToken(renamedNode.getParent()); nodeSession.getWorkspace().move(srcPath, destPath); // Update renamed node Node destNode = nodeSession.getNodeByUUID(uuid); // Restore relation to new name node for (Node addRef : refList) { relationsService.addRelation(addRef, destNode.getPath(), nodeSession.getWorkspace().getName()); } // Update lock after moving if (destNode.isLocked()) { WCMCoreUtils.getService(LockService.class).changeLockToken(renamedNode, destNode); } this.changeLockForChild(srcPath, destNode); // Mark rename node as modified if (destNode.canAddMixin("exo:modify")) { destNode.addMixin("exo:modify"); } destNode.setProperty("exo:lastModifier", nodeSession.getUserID()); // Update exo:name if(renamedNode.canAddMixin("exo:sortable")) { renamedNode.addMixin("exo:sortable"); } renamedNode.setProperty("exo:name", renamedNode.getName()); renamedNode = destNode; } // Change title if (!renamedNode.hasProperty("exo:title")) { renamedNode.addMixin(NodetypeConstant.EXO_RSS_ENABLE); } renamedNode.setProperty("exo:title", newExoTitle); nodeSession.save(); // Update state of node WCMPublicationService publicationService = WCMCoreUtils.getService(WCMPublicationService.class); if (publicationService.isEnrolledInWCMLifecycle(renamedNode)) { ListenerService listenerService = WCMCoreUtils.getService(ListenerService.class); listenerService.broadcast(CmsService.POST_EDIT_CONTENT_EVENT, this, renamedNode); } return Response.ok(uuid).build(); } catch (LockException e) { if (LOG.isWarnEnabled()) { LOG.warn("The node or parent node is locked. Rename is not successful!"); } } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Rename is not successful!", e); } else if (LOG.isWarnEnabled()) { LOG.warn("Rename is not successful!"); } } return Response.status(HTTPStatus.BAD_REQUEST).build(); } /** * Updates lock for child nodes after renaming. * * @param srcPath The source path. * @param parentNewNode The destination node which gets the new name. * @throws Exception */ private void changeLockForChild(String srcPath, Node parentNewNode) throws Exception { if(parentNewNode.hasNodes()) { NodeIterator newNodeIter = parentNewNode.getNodes(); String newSRCPath = null; while(newNodeIter.hasNext()) { Node newChildNode = newNodeIter.nextNode(); newSRCPath = newChildNode.getPath().replace(parentNewNode.getPath(), srcPath); if(newChildNode.isLocked()) WCMCoreUtils.getService(LockService.class).changeLockToken(newSRCPath, newChildNode); if(newChildNode.hasNodes()) changeLockForChild(newSRCPath, newChildNode); } } } /** * Checks if a locked node is editable or not. * * @param node A specific node. * @return True if the locked node is editable, false otherwise. * @throws Exception */ private boolean canEditLockedNode(Node node) throws Exception { LockService lockService = WCMCoreUtils.getService(LockService.class); if(!node.isLocked()) return true; String lockToken = lockService.getLockTokenOfUser(node); if(lockToken != null) { node.getSession().addLockToken(lockService.getLockToken(node)); return true; } return false; } /** * Adds the lock token of a specific node to its session. * * @param node A specific node. * @throws Exception */ private void addLockToken(Node node) throws Exception { if (node.isLocked()) { String lockToken = WCMCoreUtils.getService(LockService.class).getLockToken(node); if(lockToken != null) { node.getSession().addLockToken(lockToken); } } } /** * Parse node path with syntax [workspace:node path] to workspace name and path separately * * @param nodePath node path with syntax [workspace:node path] * @return array of String. element with index 0 is workspace name, remaining one is node path */ private String[] parseWorkSpaceNameAndNodePath(String nodePath) { Matcher matcher = RenameConnector.FILE_EXPLORER_URL_SYNTAX.matcher(nodePath); if (!matcher.find()) return null; String[] workSpaceNameAndNodePath = new String[2]; workSpaceNameAndNodePath[0] = matcher.group(1); workSpaceNameAndNodePath[1] = matcher.group(2); return workSpaceNameAndNodePath; } /** * Gets user session from a specific workspace. * * @param workspaceName * @return session * @throws Exception */ private Session getSession(String workspaceName) throws Exception { SessionProvider sessionProvider = WCMCoreUtils.getUserSessionProvider(); return sessionProvider.getSession(workspaceName, WCMCoreUtils.getRepository()); } }
12,610
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
VoteConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/VoteConnector.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.connector.collaboration; import java.net.URLDecoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.jcr.Node; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import org.exoplatform.ecm.connector.fckeditor.FCKUtils; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.portal.PortalFolderSchemaHandler; import org.exoplatform.services.wcm.webcontent.WebContentSchemaHandler; import org.exoplatform.wcm.connector.BaseConnector; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Returns and sets a vote value of a given node in the sent parameter. * * {{{{portalname}}}}: The name of portal. * {{{{restcontextname}}}}: The context name of the REST web application which is deployed to the "{{{{portalname}}}}" portal. * * @LevelAPI Provisional * * @anchor VoteConnector */ @Path("/contents/vote/") public class VoteConnector extends BaseConnector implements ResourceContainer { /** * Instantiates a new vote connector. */ public VoteConnector() {} /** * Sets a vote value for a given content. * * @param jcrPath The path of the content. * @param vote The vote value. * @return http The code. * @throws Exception The exception * * @anchor VoteConnector.postStarVote */ @POST @Path("/star/") // @InputTransformer(PassthroughInputTransformer.class) public Response postStarVote( @FormParam("jcrPath") String jcrPath, @FormParam("vote") String vote ) throws Exception { if (jcrPath.contains("%20")) jcrPath = URLDecoder.decode(jcrPath, "UTF-8"); return postVote(null, null, jcrPath, vote, "en" ); } /** * Returns a vote value for a given content. * * @param repositoryName The repository name. * @param workspaceName The workspace name. * @param jcrPath The path of the content. * @return http The code. * @throws Exception The exception * * @anchor VoteConnector.getStarVote */ @GET @Path("/star/") // @OutputTransformer(XMLOutputTransformer.class) public Response getStarVote( @QueryParam("repositoryName") String repositoryName, @QueryParam("workspaceName") String workspaceName, @QueryParam("jcrPath") String jcrPath) throws Exception { return getVote(repositoryName, workspaceName, jcrPath); } /** * Sets a vote value for a given content. * * @param repositoryName The repository name. * @param workspaceName The workspace name. * @param jcrPath The path of the content. * @param vote The vote value. * @param lang The language of the content. * @return http The code. * @throws Exception The exception * * @anchor VoteConnector.postVote */ @GET @Path("/postVote/") // @InputTransformer(PassthroughInputTransformer.class) public Response postVote( @QueryParam("repositoryName") String repositoryName, @QueryParam("workspaceName") String workspaceName, @QueryParam("jcrPath") String jcrPath, @QueryParam("vote") String vote, @QueryParam("lang") String lang ) throws Exception { try { if (repositoryName==null && workspaceName==null) { String[] path = jcrPath.split("/"); repositoryName = path[1]; workspaceName = path[2]; jcrPath = jcrPath.substring(repositoryName.length()+workspaceName.length()+2); if (jcrPath.charAt(1)=='/') jcrPath.substring(1); } Node content = getContent(workspaceName, jcrPath, null, false); if (content.isNodeType("mix:votable")) { String userName = content.getSession().getUserID(); votingService.vote(content, Double.parseDouble(vote), userName, lang); } } catch (Exception e) { Response.serverError().build(); } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } /** * Returns a vote value for a given content. * * @param repositoryName The repository name. * @param workspaceName The workspace name. * @param jcrPath The path of the content. * @return http The code * @throws Exception The exception * * @anchor VoteConnector.getVote */ @GET @Path("/getVote/") // @OutputTransformer(XMLOutputTransformer.class) public Response getVote( @QueryParam("repositoryName") String repositoryName, @QueryParam("workspaceName") String workspaceName, @QueryParam("jcrPath") String jcrPath) throws Exception { try { if (repositoryName==null && workspaceName==null) { String[] path = jcrPath.split("/"); repositoryName = path[1]; workspaceName = path[2]; jcrPath = jcrPath.substring(repositoryName.length()+workspaceName.length()+2); if (jcrPath.charAt(1)=='/') jcrPath.substring(1); } Node content = getContent(workspaceName, jcrPath); if (content.isNodeType("mix:votable")) { String votingRate = ""; if (content.hasProperty("exo:votingRate")) votingRate = content.getProperty("exo:votingRate").getString(); String votingTotal = ""; if (content.hasProperty("exo:voteTotalOfLang")) votingTotal = content.getProperty("exo:voteTotalOfLang").getString(); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element element = document.createElement("vote"); Element rate = document.createElement("rate"); rate.setTextContent(votingRate); Element total = document.createElement("total"); total.setTextContent(votingTotal); element.appendChild(rate); element.appendChild(total); document.appendChild(element); DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok(new DOMSource(document), MediaType.TEXT_XML) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } } catch (Exception e) { Response.serverError().build(); } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } /* * (non-Javadoc) * @see * org.exoplatform.wcm.connector.fckeditor.BaseConnector#getRootContentStorage * (javax.jcr.Node) */ @Override protected Node getRootContentStorage(Node parentNode) throws Exception { try { PortalFolderSchemaHandler folderSchemaHandler = webSchemaConfigService.getWebSchemaHandlerByType(PortalFolderSchemaHandler.class); return folderSchemaHandler.getDocumentStorage(parentNode); } catch (Exception e) { WebContentSchemaHandler webContentSchemaHandler = webSchemaConfigService.getWebSchemaHandlerByType(WebContentSchemaHandler.class); return webContentSchemaHandler.getDocumentFolder(parentNode); } } /* * (non-Javadoc) * @see * org.exoplatform.wcm.connector.fckeditor.BaseConnector#getContentStorageType * () */ @Override protected String getContentStorageType() throws Exception { return FCKUtils.DOCUMENT_TYPE; } }
8,539
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
NavigationConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/NavigationConnector.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.collaboration; import java.util.Iterator; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.config.UserPortalConfig; import org.exoplatform.portal.config.UserPortalConfigService; import org.exoplatform.portal.mop.SiteKey; import org.exoplatform.portal.mop.Visibility; 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.UserNodeFilterConfig; import org.exoplatform.portal.mop.user.UserPortal; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Created by The eXo Platform SAS * Author : Nguyen The Vinh From ECM Of eXoPlatform * vinh_nguyen@exoplatform.com * 29 May 2012 */ @Path("/content/") public class NavigationConnector implements ResourceContainer{ private static ThreadLocal<Boolean> gotNavigationKeeper = new ThreadLocal<Boolean>(); /** * Return a JsonString include all navigation node * * @param portalName: Destination portal to get the navigation tree * @return * @throws Exception */ @GET @Path("/getFullNavigation/") public Response getFullNavigation ( @QueryParam("portalName") String portalName) throws Exception { String userName = ConversationState.getCurrent().getIdentity().getUserId(); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element element = document.createElement("navigationXML"); element.setTextContent(getNavigationAsJSON(portalName, userName)); document.appendChild(element); return Response.ok(new DOMSource(document), MediaType.TEXT_XML).build(); } private String getNavigationAsJSON(String portalName, String username) throws Exception { UserPortalConfigService userPortalConfigService = WCMCoreUtils.getService(UserPortalConfigService.class); UserPortalConfig userPortalCfg = userPortalConfigService.getUserPortalConfig(portalName, username, PortalRequestContext.USER_PORTAL_CONTEXT); UserPortal userPortal = userPortalCfg.getUserPortal(); //filter nodes UserNodeFilterConfig.Builder filterConfigBuilder = UserNodeFilterConfig.builder(); filterConfigBuilder.withReadWriteCheck().withVisibility(Visibility.DISPLAYED, Visibility.TEMPORAL); filterConfigBuilder.withTemporalCheck(); UserNodeFilterConfig filterConfig = filterConfigBuilder.build(); //get nodes UserNavigation navigation = userPortal.getNavigation(SiteKey.portal(portalName)); UserNode root = userPortal.getNode(navigation, Scope.ALL, filterConfig, null); //set gotNavigation=true gotNavigationKeeper.set(true); return createJsonTree(navigation, root); } /** * Return a JsonString include all navigation node, serve for getNavigationAsJSON method * * @param navigation: Navigation information to create Json tree * @param rootNode : Root node of navigation * @return A String as Json tree * @throws Exception */ private String createJsonTree(UserNavigation navigation, UserNode rootNode) throws Exception { StringBuffer sbJsonTree = new StringBuffer(); sbJsonTree.append("["); sbJsonTree.append("{"); sbJsonTree.append("\"ownerId\":\"").append(navigation.getKey().getName()).append("\","); sbJsonTree.append("\"ownerType\":\"").append(navigation.getKey().getTypeName()).append("\","); sbJsonTree.append("\"priority\":\"").append(navigation.getPriority()).append("\","); sbJsonTree.append("\"nodes\":").append(addJsonNodes(rootNode.getChildren().iterator())); sbJsonTree.append("}"); sbJsonTree.append("]"); return sbJsonTree.toString(); } /** * Build JsonTree for children nodes of navigation * * @param children * @return StringBuffer contain Json tree of children */ private StringBuffer addJsonNodes(Iterator<UserNode> children) { StringBuffer sbJsonTree = new StringBuffer(); String resovleLabel = ""; sbJsonTree.append("["); boolean first = true; while (children.hasNext()) { UserNode child = children.next(); if (!first) { sbJsonTree.append(","); } first = false; sbJsonTree.append("{"); sbJsonTree.append("\"icon\":").append(child.getIcon() != null ? "\"" + child.getIcon() + "\"" : "null").append(","); sbJsonTree.append("\"label\":\"").append(child.getLabel()).append("\","); sbJsonTree.append("\"name\":\"").append(child.getName()).append("\","); try { resovleLabel = child.getResolvedLabel(); } catch (NullPointerException npe) { resovleLabel = ""; } sbJsonTree.append("\"resolvedLabel\":\"").append(resovleLabel).append("\","); sbJsonTree.append("\"uri\":\"").append(child.getURI()).append("\","); sbJsonTree.append("\"getNodeURL\":\"").append(child.getURI().toString()).append("\","); sbJsonTree.append("\"nodes\":").append(addJsonNodes(child.getChildren().iterator())); sbJsonTree.append("}"); } sbJsonTree.append("]"); return sbJsonTree; } }
6,407
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
IdentitySearchRESTService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/IdentitySearchRESTService.java
/* * Copyright (C) 2003-2020 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.connector.collaboration; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.annotation.security.RolesAllowed; import javax.jcr.AccessDeniedException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.organization.Group; import org.exoplatform.services.organization.OrganizationService; import org.exoplatform.services.rest.resource.ResourceContainer; 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.manager.IdentityManager; import org.exoplatform.social.core.profile.ProfileFilter; 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.wcm.connector.collaboration.editors.ErrorMessage; import org.exoplatform.wcm.connector.collaboration.editors.HypermediaLink; import org.exoplatform.wcm.connector.collaboration.editors.HypermediaSupport; import org.exoplatform.wcm.connector.collaboration.editors.IdentityData; /** * The Class IdentitySearchRESTService. */ @Path("/identity/search") public class IdentitySearchRESTService implements ResourceContainer { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(IdentitySearchRESTService.class); /** The Constant CANNOT_LOAD_IDENTITIES. */ protected static final String CANNOT_LOAD_IDENTITIES = "CannotLoadIdentities"; /** The max result size. */ protected static final int MAX_RESULT_SIZE = 30; /** The Constant USER_TYPE. */ protected static final String USER_TYPE = "user"; /** The Constant SPACE_TYPE. */ protected static final String SPACE_TYPE = "space"; /** The Constant GROUP_TYPE. */ protected static final String GROUP_TYPE = "group"; /** The Constant SELF. */ protected static final String SELF = "self"; /** The identity manager. */ protected IdentityManager identityManager; /** The organization service. */ protected OrganizationService organization; /** The space service. */ protected SpaceService spaceService; /** * Instantiates a new IdentitySearchRESTService. * * @param identityManager the identity manager * @param organization the organization * @param spaceService the space service */ public IdentitySearchRESTService(IdentityManager identityManager, OrganizationService organization, SpaceService spaceService) { this.identityManager = identityManager; this.organization = organization; this.spaceService = spaceService; } /** * Search identities. * * @param uriInfo the uri info * @param name the name * @return the response */ @GET @RolesAllowed("administrators") @Path("/{name}") @Produces(MediaType.APPLICATION_JSON) public Response searchIdentities(@Context UriInfo uriInfo, @PathParam("name") String name) { try { IdentitiesDataResponse responseEntity = new IdentitiesDataResponse(findGroupsAndUsers(name)); responseEntity.addLink(SELF, new HypermediaLink(uriInfo.getAbsolutePath().toString())); return Response.status(Status.OK).entity(responseEntity).build(); } catch (AccessDeniedException e) { LOG.error("Access denied to get identities with name: {}, error: {}", name, e.getMessage()); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(new ErrorMessage("Access denied error.", CANNOT_LOAD_IDENTITIES)) .build(); } catch (Exception e) { LOG.error("Cannot get identities with name: {}, error: {}", name, e.getMessage()); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(new ErrorMessage(e.getMessage(), CANNOT_LOAD_IDENTITIES)) .build(); } } /** * Find groups and users. * * @param name the name * @return the list * @throws Exception the exception */ protected List<IdentityData> findGroupsAndUsers(String name) throws Exception { List<IdentityData> identitiesData = findUsers(name, MAX_RESULT_SIZE / 2); int remain = MAX_RESULT_SIZE - identitiesData.size(); identitiesData.addAll(findGroups(name, remain)); Collections.sort(identitiesData, new Comparator<IdentityData>() { public int compare(IdentityData s1, IdentityData s2) { return s1.getDisplayName().compareTo(s2.getDisplayName()); } }); return identitiesData; } /** * Find users. * * @param name the name * @param count the count * @return the list * @throws Exception the exception */ protected List<IdentityData> findUsers(String name, int count) throws Exception { List<IdentityData> results = new ArrayList<>(); ProfileFilter identityFilter = new ProfileFilter(); identityFilter.setName(name); ListAccess<Identity> identitiesList = identityManager.getIdentitiesByProfileFilter(OrganizationIdentityProvider.NAME, identityFilter, false); int size = identitiesList.getSize() >= count ? count : identitiesList.getSize(); if (size > 0) { Identity[] identities = identitiesList.load(0, size); for (Identity id : identities) { Profile profile = id.getProfile(); String fullName = profile.getFullName(); String userName = (String) profile.getProperty(Profile.USERNAME); String avatarUrl = profile.getAvatarUrl() != null ? profile.getAvatarUrl() : LinkProvider.PROFILE_DEFAULT_AVATAR_URL; results.add(new IdentityData(userName, fullName, USER_TYPE, avatarUrl)); } } return results; } /** * Find groups. * * @param name the name * @param count the count * @return the list * @throws Exception the exception */ protected List<IdentityData> findGroups(String name, int count) throws Exception { List<IdentityData> results = new ArrayList<>(); ListAccess<Group> groupsAccess = organization.getGroupHandler().findGroupsByKeyword(name); int size = groupsAccess.getSize() >= count ? count : groupsAccess.getSize(); if (size > 0) { Group[] groups = groupsAccess.load(0, size); for (Group group : groups) { Space space = spaceService.getSpaceByGroupId(group.getId()); if (space != null) { String avatarUrl = space.getAvatarUrl() != null ? space.getAvatarUrl() : LinkProvider.SPACE_DEFAULT_AVATAR_URL; results.add(new IdentityData(space.getGroupId(), space.getDisplayName(), SPACE_TYPE, avatarUrl)); } else { results.add(new IdentityData(group.getId(), group.getLabel(), GROUP_TYPE, LinkProvider.SPACE_DEFAULT_AVATAR_URL)); } } } return results; } /** * The Class IdentitiesDataResponse. */ public static class IdentitiesDataResponse extends HypermediaSupport { /** The identities. */ private final List<IdentityData> identities; /** * Instantiates a new identities data response. * * @param identities the identities */ public IdentitiesDataResponse(List<IdentityData> identities) { this.identities = identities; } /** * Gets the identities. * * @return the identities */ public List<IdentityData> getIdentities() { return identities; } } }
8,811
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
InlineEditingService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/InlineEditingService.java
package org.exoplatform.wcm.connector.collaboration; import java.io.FileNotFoundException; import java.security.AccessControlException; import java.util.Locale; import java.util.ResourceBundle; import javax.jcr.AccessDeniedException; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import javax.jcr.lock.LockException; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import org.exoplatform.container.xml.PortalContainerInfo; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.listener.ListenerService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.resources.ResourceBundleService; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Created by The eXo Platform SEA * Author : Ha Quang Tan * tan.haquang@exoplatform.com * Mar 23, 2011 */ @Path("/contents/editing/") public class InlineEditingService implements ResourceContainer{ private static final Log LOG = ExoLogger.getLogger(InlineEditingService.class.getName()); final static public String EXO_TITLE = "exo:title"; final static public String EXO_SUMMARY = "exo:summary"; final static public String EXO_TEXT = "exo:text"; final static public String EXO_RSS_ENABLE = "exo:rss-enable"; public final static String POST_EDIT_CONTENT_EVENT = "CmsService.event.postEdit"; private final String localeFile = "locale.portlet.i18n.WebUIDms"; /** * SERVICE: Edit title of document. * * @param newTitle the new title of document * @param repositoryName the repository name * @param workspaceName the workspace name * @param nodeUIID the UIID of node * @param siteName the site name * * @return the response */ @POST @Path("/title/") public Response editTitle(@FormParam("newValue") String newTitle, @QueryParam("repositoryName") String repositoryName, @QueryParam("workspaceName") String workspaceName, @QueryParam("nodeUIID") String nodeUIID, @QueryParam("siteName") String siteName, @QueryParam("language") String language){ return modifyProperty(EXO_TITLE, newTitle, repositoryName, workspaceName, nodeUIID, siteName, language); } /** * SERVICE: Edit summary of document. * * @param newSummary the new summary of document * @param repositoryName the repository name * @param workspaceName the workspace name * @param nodeUIID the UIID of node * @param siteName the site name * * @return the response */ @POST @Path("/summary/") public Response editSummary(@FormParam("newValue") String newSummary, @QueryParam("repositoryName") String repositoryName, @QueryParam("workspaceName") String workspaceName, @QueryParam("nodeUIID") String nodeUIID, @QueryParam("siteName") String siteName, @QueryParam("language") String language){ return modifyProperty(EXO_SUMMARY, newSummary, repositoryName, workspaceName, nodeUIID, siteName, language); } /** * SERVICE: Edit summary of document. * * @param newValue the new summary of document * @param repositoryName the repository name * @param workspaceName the workspace name * @param nodeUIID the UIID of node * @param siteName the site name * * @return the response */ @POST @Path("/text/") public Response editText( @FormParam("newValue") String newValue, @QueryParam("repositoryName") String repositoryName, @QueryParam("workspaceName") String workspaceName, @QueryParam("nodeUIID") String nodeUIID, @QueryParam("siteName") String siteName, @QueryParam("language") String language){ return modifyProperty(EXO_TEXT, newValue, repositoryName, workspaceName, nodeUIID, siteName, language); } /** * SERVICE: Edit value of any property * * @param propertyName * @param newValue * @param repositoryName the repository name * @param workspaceName the workspace name * @param nodeUIID the UIID of node * @param siteName the site name * @param language * @return the response */ @POST @Path("/property/") public Response editProperty( @QueryParam("propertyName") String propertyName, @FormParam("newValue") String newValue, @QueryParam("repositoryName") String repositoryName, @QueryParam("workspaceName") String workspaceName, @QueryParam("nodeUIID") String nodeUIID, @QueryParam("siteName") String siteName, @QueryParam("language") String language){ String decodedPropertyName = Text.unescapeIllegalJcrChars(propertyName); return modifyProperty(decodedPropertyName, newValue, repositoryName, workspaceName, nodeUIID, siteName, language); } /** * Edit generic property of document. * @param propertyName property that need to edit * @param newValue the new 'requested property' of document * @param repositoryName the repository name * @param workspaceName the workspace name * @param nodeUIID the UIID of node * @param siteName the site name * * @return the response */ public Response modifyProperty(String propertyName, String newValue, String repositoryName, String workspaceName, String nodeUIID,String siteName, String language){ ResourceBundle resourceBundle = null; String messageKey = ""; String message = ""; Document document = null; Element localeMsg = null; try { Locale locale = new Locale(language); ResourceBundleService resourceBundleService = WCMCoreUtils.getService(ResourceBundleService.class); resourceBundle = resourceBundleService.getResourceBundle(localeFile, locale); } catch(Exception ex) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform create ResourceBundle: ", ex); } } try { document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); } catch(Exception ex) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform create Document object: ", ex); } } CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); cacheControl.setNoStore(true); try { SessionProvider sessionProvider = WCMCoreUtils.getUserSessionProvider(); RepositoryService repositoryService = WCMCoreUtils.getService(RepositoryService.class); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); Session session = sessionProvider.getSession(workspaceName, manageableRepository); try { localeMsg = document.createElement("bundle"); Node node = session.getNodeByUUID(nodeUIID); node = (Node)session.getItem(node.getPath()); if(canSetProperty(node)) { if (!sameValue(newValue, node, propertyName)) { if (newValue.length() > 0) { newValue = Text.unescapeIllegalJcrChars(newValue.trim()); PortalContainerInfo containerInfo = WCMCoreUtils.getService(PortalContainerInfo.class); String containerName = containerInfo.getContainerName(); ListenerService listenerService = WCMCoreUtils.getService(ListenerService.class, containerName); if (propertyName.equals(EXO_TITLE)) { if (!node.hasProperty(EXO_TITLE)) node.addMixin(EXO_RSS_ENABLE); } if (!propertyName.contains("/")) { if (node.hasProperty(propertyName) && node.getProperty(propertyName).getDefinition().isMultiple()) { Value[] currentValue = node.getProperty(propertyName).getValues(); if (currentValue==null) currentValue = new Value[1]; currentValue[0] = session.getValueFactory().createValue(newValue); node.setProperty(propertyName, currentValue); }else { node.setProperty(propertyName, newValue); } } else { int iSlash = propertyName.lastIndexOf("/"); String subnodePath = propertyName.substring(0, iSlash); String subnodeProperty = propertyName.substring(iSlash+1); Node subnode = node.getNode(subnodePath); if (subnode.hasProperty(subnodeProperty) && subnode.getProperty(subnodeProperty).getDefinition().isMultiple()) { Value[] currentValue = subnode.getProperty(subnodeProperty).getValues(); if (currentValue==null) currentValue = new Value[1]; currentValue[0] = session.getValueFactory().createValue(newValue); subnode.setProperty(subnodeProperty, currentValue); } else { subnode.setProperty(subnodeProperty, newValue); } } ConversationState conversationState = ConversationState.getCurrent(); conversationState.setAttribute("siteName", siteName); listenerService.broadcast(POST_EDIT_CONTENT_EVENT, null, node); node.save(); } } } else { messageKey = "AccessDeniedException.msg"; message = resourceBundle.getString(messageKey); localeMsg.setAttribute("message", message); document.appendChild(localeMsg); return Response.ok(new DOMSource(document), MediaType.TEXT_XML).cacheControl(cacheControl).build(); } } catch (AccessDeniedException ace) { if (LOG.isErrorEnabled()) { LOG.error("AccessDeniedException: ", ace); } messageKey = "AccessDeniedException.msg"; message = resourceBundle.getString(messageKey); localeMsg.setAttribute("message", message); document.appendChild(localeMsg); return Response.ok(new DOMSource(document), MediaType.TEXT_XML).cacheControl(cacheControl).build(); } catch (FileNotFoundException fie) { if (LOG.isErrorEnabled()) { LOG.error("FileNotFoundException: ", fie); } messageKey = "ItemNotFoundException.msg"; message = resourceBundle.getString(messageKey); localeMsg.setAttribute("message", message); document.appendChild(localeMsg); return Response.ok(new DOMSource(document), MediaType.TEXT_XML).cacheControl(cacheControl).build(); } catch (LockException lockex) { if (LOG.isErrorEnabled()) { LOG.error("LockException", lockex); } messageKey = "LockException.msg"; message = resourceBundle.getString(messageKey); localeMsg.setAttribute("message", message); document.appendChild(localeMsg); return Response.ok(new DOMSource(document), MediaType.TEXT_XML).cacheControl(cacheControl).build(); } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform edit title: ", e); } messageKey = "UIPresentation.label.Exception"; message = resourceBundle.getString(messageKey); localeMsg.setAttribute("message", message); document.appendChild(localeMsg); return Response.ok(new DOMSource(document), MediaType.TEXT_XML).cacheControl(cacheControl).build(); } localeMsg.setAttribute("message", "OK"); document.appendChild(localeMsg); return Response.ok(new DOMSource(document), MediaType.TEXT_XML).cacheControl(cacheControl).build(); } /** * Compare new value with current value property * * @param newValue the new value of property * @param node the document node * * @return the result of compare * * @throws Exception the exception */ private boolean sameValue(String newValue, Node node, String propertyName) throws Exception { if (!node.hasProperty(propertyName)) return (newValue == null || newValue.length() == 0); if (node.getProperty(propertyName).getDefinition().isMultiple()){ try { return node.getProperty(propertyName).getValues()[0].getString().equals(newValue); }catch (Exception e) { return false; } } return node.getProperty(propertyName).getString().equals(newValue); } /** * Can set property. * * @param node the node * @return true, if successful * @throws RepositoryException the repository exception */ public static boolean canSetProperty(Node node) throws RepositoryException { return checkPermission(node,PermissionType.SET_PROPERTY); } private static boolean checkPermission(Node node,String permissionType) throws RepositoryException { try { ((ExtendedNode)node).checkPermission(permissionType); return true; } catch(AccessControlException e) { return false; } } }
14,025
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CometdDocumentsService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/cometd/CometdDocumentsService.java
package org.exoplatform.wcm.connector.collaboration.cometd; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.inject.Inject; import javax.jcr.RepositoryException; import org.cometd.annotation.Param; import org.cometd.annotation.server.ServerAnnotationProcessor; import org.cometd.annotation.Service; import org.cometd.annotation.Session; import org.cometd.annotation.Subscription; import org.cometd.bayeux.Message; import org.cometd.bayeux.Promise; import org.cometd.bayeux.server.BayeuxServer; import org.cometd.bayeux.server.BayeuxServer.ChannelListener; import org.cometd.bayeux.server.ConfigurableServerChannel; import org.cometd.bayeux.server.LocalSession; import org.cometd.bayeux.server.ServerChannel; import org.cometd.bayeux.server.ServerChannel.SubscriptionListener; import org.cometd.bayeux.server.ServerMessage; import org.cometd.bayeux.server.ServerSession; import org.eclipse.jetty.util.component.LifeCycle; import org.mortbay.cometd.continuation.EXoContinuationBayeux; import org.picocontainer.Startable; import org.exoplatform.commons.utils.PropertyManager; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.component.RequestLifeCycle; import org.exoplatform.services.cms.documents.DocumentEditorProvider; import org.exoplatform.services.cms.documents.DocumentService; import org.exoplatform.services.cms.documents.exception.DocumentEditorProviderNotFoundException; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.security.Authenticator; import org.exoplatform.services.security.Identity; import org.exoplatform.services.security.IdentityRegistry; import org.exoplatform.ws.frameworks.json.impl.JsonException; import org.exoplatform.ws.frameworks.json.impl.JsonGeneratorImpl; /** * The Class CometdDocumentsService. */ public class CometdDocumentsService implements Startable { /** * Command thread factory adapted from {@link Executors#DefaultThreadFactory}. */ static class CommandThreadFactory implements ThreadFactory { /** The group. */ final ThreadGroup group; /** The thread number. */ final AtomicInteger threadNumber = new AtomicInteger(1); /** The name prefix. */ final String namePrefix; /** * Instantiates a new command thread factory. * * @param namePrefix the name prefix */ CommandThreadFactory(String namePrefix) { SecurityManager s = System.getSecurityManager(); this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); this.namePrefix = namePrefix; } /** * New thread. * * @param r the r * @return the thread */ public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0) { /** * {@inheritDoc} */ @Override protected void finalize() throws Throwable { super.finalize(); threadNumber.decrementAndGet(); } }; if (t.isDaemon()) { t.setDaemon(false); } if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } } /** * The Class ContainerCommand. */ abstract class ContainerCommand implements Runnable { /** The container name. */ final String containerName; /** * Instantiates a new container command. * * @param containerName the container name */ ContainerCommand(String containerName) { this.containerName = containerName; } /** * Execute actual work of the commend (in extending class). * * @param exoContainer the exo container */ abstract void execute(ExoContainer exoContainer); /** * Callback to execute on container error. * * @param error the error */ abstract void onContainerError(String error); /** * {@inheritDoc} */ @Override public void run() { // Do the work under eXo container context (for proper work of eXo apps // and JPA storage) ExoContainer exoContainer = ExoContainerContext.getContainerByName(containerName); if (exoContainer != null) { ExoContainer contextContainer = ExoContainerContext.getCurrentContainerIfPresent(); try { // Container context ExoContainerContext.setCurrentContainer(exoContainer); RequestLifeCycle.begin(exoContainer); // do the work here execute(exoContainer); } finally { // Restore context RequestLifeCycle.end(); ExoContainerContext.setCurrentContainer(contextContainer); } } else { onContainerError("Container not found"); } } } /** * The Class EditorsContext holds information about current opened editons (cometd subsriptions). * Keeps closed editor timers (created when the last editor closed) that will be executed after the timeout. */ static class EditorsContext { /** The clients map. The key is session id, the value - client info. */ private ConcurrentHashMap<String, ClientInfo> clients = new ConcurrentHashMap<>(); /** The providers map. The key is fileId, value - Map<Strig provider, Integer count opened editors> */ private ConcurrentHashMap<String, Map<String, Integer>> providers = new ConcurrentHashMap<>(); /** The closed editors. The key is client info, value - timer with task (setCurrentProvider to null) */ private ConcurrentHashMap<ClientInfo, Timer> closedEditorTimers = new ConcurrentHashMap<>(); /** * Adds the client. * * @param sessionId the session id * @param fileId the file id * @param provider the provider * @param workspace the workspace */ public void addClient(String sessionId, String fileId, String provider, String workspace) { clients.put(sessionId, new ClientInfo(fileId, workspace, provider)); providers.compute(fileId, (key, providers) -> { if (providers == null) { Map<String, Integer> providersMap = new HashMap<>(); providersMap.put(provider, 1); return providersMap; } else { providers.compute(provider, (providerName, count) -> (count == null) ? 1 : count + 1); return providers; } }); } /** * Removes the client. * * @param sessionId the session id * @return the client info */ public ClientInfo removeClient(String sessionId) { ClientInfo clientInfo = clients.remove(sessionId); if (clientInfo != null) { Map<String, Integer> editors = providers.get(clientInfo.getFileId()); editors.compute(clientInfo.getProvider(), (provider, count) -> (count == null || count < 1) ? 0 : count - 1); } return clientInfo; } /** * Gets the opened editors count. * * @param fileId the file id * @param provider the provider * @return the opened editors count */ public int getOpenedEditorsCount(String fileId, String provider) { if (providers.containsKey(fileId)) { return providers.get(fileId).get(provider); } return 0; } /** * Cancel closed editor timer. * * @param fileId the file id * @param workspace the workspace * @param provider the provider */ public void cancelClosedEditorTimer(String fileId, String workspace, String provider) { ClientInfo clientInfo = new ClientInfo(fileId, workspace, provider); Timer timer = closedEditorTimers.get(clientInfo); if (timer != null) { timer.cancel(); closedEditorTimers.remove(clientInfo); } } /** * Sets the closed editor timer. * * @param fileId the file id * @param workspace the workspace * @param provider the provider * @param timer the timer */ public void saveClosedEditorTimer(String fileId, String workspace, String provider, Timer timer) { ClientInfo clientInfo = new ClientInfo(fileId, workspace, provider); closedEditorTimers.put(clientInfo, timer); } } /** * The Class ClientInfo. */ static class ClientInfo { /** The workspace. */ private final String workspace; /** The provider. */ private final String provider; /** The file id. */ private final String fileId; /** * Instantiates a new client info. * * @param fileId the fileId * @param workspace the workspace * @param provider the provider */ public ClientInfo(String fileId, String workspace, String provider) { this.fileId = fileId; this.workspace = workspace; this.provider = provider; } /** * Gets the workspace. * * @return the workspace */ public String getWorkspace() { return workspace; } /** * Gets the provider. * * @return the provider */ public String getProvider() { return provider; } /** * Gets the fileId. * * @return the fileId */ public String getFileId() { return fileId; } /** * Hash code. * * @return the int */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((fileId == null) ? 0 : fileId.hashCode()); result = prime * result + ((provider == null) ? 0 : provider.hashCode()); result = prime * result + ((workspace == null) ? 0 : workspace.hashCode()); return result; } /** * Equals. * * @param obj the obj * @return true, if successful */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ClientInfo other = (ClientInfo) obj; if (fileId == null) { if (other.fileId != null) return false; } else if (!fileId.equals(other.fileId)) return false; if (provider == null) { if (other.provider != null) return false; } else if (!provider.equals(other.provider)) return false; if (workspace == null) { if (other.workspace != null) return false; } else if (!workspace.equals(other.workspace)) return false; return true; } } /** * The listener interface for receiving channelSubscription events. * The class that is interested in processing a channelSubscription * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addChannelSubscriptionListener<code> method. When * the channelSubscription event occurs, that object's appropriate * method is invoked. * * @see ChannelSubscriptionEvent */ class ChannelSubscriptionListener implements SubscriptionListener { /** * {@inheritDoc} */ @Override public void subscribed(ServerSession remote, ServerChannel channel, ServerMessage message) { String channelId = channel.getId(); if (channelId.startsWith(CHANNEL_NAME)) { String sessionId = remote.getId(); String exoClientId = asString(message.get("exoClientId")); String exoContainerName = asString(message.get("exoContainerName")); String provider = asString(message.get("provider")); String workspace = asString(message.get("workspace")); if (provider != null) { String fileId = channelId.substring(channelId.lastIndexOf("/") + 1); editorsContext.addClient(sessionId, fileId, provider, workspace); editorsContext.cancelClosedEditorTimer(fileId, workspace, provider); } if (LOG.isDebugEnabled()) { LOG.debug(">> Subscribed: provider: " + provider + ", session:" + sessionId + " (" + exoContainerName + "@" + exoClientId + "), channel:" + channelId); } } } /** * {@inheritDoc} */ @Override public void unsubscribed(ServerSession session, ServerChannel channel, ServerMessage message) { String channelId = channel.getId(); if (channelId.startsWith(CHANNEL_NAME)) { String sessionId = session.getId(); String exoClientId = null; String exoContainerName = null; ClientInfo removedClient = editorsContext.removeClient(sessionId); if (removedClient != null) { String fileId = removedClient.getFileId(); String provider = removedClient.getProvider(); String workspace = removedClient.getWorkspace(); if (editorsContext.getOpenedEditorsCount(fileId, provider) == 0) { try { DocumentEditorProvider editorProvider = documentService.getEditorProvider(provider); // Postpone reseting current editor provider for specified delay Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { try { String currentProvider = documentService.getCurrentDocumentProvider(fileId, workspace); if (currentProvider != null) { service.setCurrentDocumentProvider(fileId, workspace, null); service.sendLastEditorClosedEvent(fileId, provider); if (LOG.isDebugEnabled()) { LOG.debug("Last editor closed. Provider" + provider + ", workspace: " + removedClient.getWorkspace() + ", fileId:" + fileId); } } } catch (RepositoryException e) { LOG.error("Cannot reset current editor provider for fileId: " + fileId + ", workspace: " + workspace, e); } } }, editorProvider.getEditingFinishedDelay()); editorsContext.saveClosedEditorTimer(fileId, workspace, provider, timer); } catch (DocumentEditorProviderNotFoundException e) { LOG.error("Cannot find {} editor provider. {}", provider, e.getMessage()); } } } if (LOG.isDebugEnabled()) { LOG.debug(">> Unsubscribed: session:" + sessionId + " (" + exoContainerName + "@" + exoClientId + "), channel:" + channelId); } } } } /** * The listener interface for receiving client channel events. * * @see ClientChannelEvent */ class ClientChannelListener implements ChannelListener { /** * {@inheritDoc} */ @Override public void configureChannel(ConfigurableServerChannel channel) { } /** * {@inheritDoc} */ @Override public void channelAdded(ServerChannel channel) { // Add sub/unsub listener to WebConferencing channel final String channelId = channel.getId(); if (channelId.startsWith(CHANNEL_NAME)) { if (LOG.isDebugEnabled()) { LOG.debug("> Channel added: " + channelId); } channel.addListener(subscriptionListener); } } /** * {@inheritDoc} */ @Override public void channelRemoved(String channelId) { if (channelId.startsWith(CHANNEL_NAME) && LOG.isDebugEnabled()) { LOG.debug("< Channel removed: " + channelId); } } } /** The Constant LOG. */ private static final Log LOG = ExoLogger.getLogger(CometdDocumentsService.class); /** The channel name. */ public static final String CHANNEL_NAME = "/eXo/Application/documents/editor/"; /** The channel name. */ public static final String CHANNEL_NAME_PARAMS = CHANNEL_NAME + "{fileId}"; /** The document opened event. */ public static final String DOCUMENT_OPENED_EVENT = "DOCUMENT_OPENED"; /** The Constant LAST_EDITOR_CLOSED_EVENT. */ public static final String LAST_EDITOR_CLOSED_EVENT = "LAST_EDITOR_CLOSED"; /** The Constant CURRENT_PROVIDER_INFO. */ public static final String CURRENT_PROVIDER_INFO = "CURRENT_PROVIDER_INFO"; /** * Base minimum number of threads for document updates thread executors. */ public static final int MIN_THREADS = 2; /** * Minimal number of threads maximum possible for document updates thread * executors. */ public static final int MIN_MAX_THREADS = 4; /** Thread idle time for thread executors (in seconds). */ public static final int THREAD_IDLE_TIME = 120; /** * Maximum threads per CPU for thread executors of document changes channel. */ public static final int MAX_FACTOR = 20; /** * Queue size per CPU for thread executors of document updates channel. */ public static final int QUEUE_FACTOR = MAX_FACTOR * 2; /** * Thread name used for the executor. */ public static final String THREAD_PREFIX = "documents-comet-thread-"; /** The exo bayeux. */ protected final EXoContinuationBayeux exoBayeux; /** The service. */ protected final CometdService service; /** The call handlers. */ protected final ExecutorService eventsHandlers; /** The document service. */ protected final DocumentService documentService; /** The identity registry. */ protected final IdentityRegistry identityRegistry; /** The authenticator. */ protected final Authenticator authenticator; /** The subscription listener. */ protected final ChannelSubscriptionListener subscriptionListener = new ChannelSubscriptionListener(); /** The channel listener. */ protected final ClientChannelListener channelListener = new ClientChannelListener(); /** The editors context. */ protected final EditorsContext editorsContext = new EditorsContext(); /** * Instantiates the CometdDocumentsService. * * @param exoBayeux the exoBayeux * @param documentService the document service * @param identityRegistry the identity registry * @param authenticator the authenticator */ public CometdDocumentsService(EXoContinuationBayeux exoBayeux, DocumentService documentService, IdentityRegistry identityRegistry, Authenticator authenticator) { this.exoBayeux = exoBayeux; this.documentService = documentService; this.service = new CometdService(); this.eventsHandlers = createThreadExecutor(THREAD_PREFIX, MAX_FACTOR, QUEUE_FACTOR); this.identityRegistry = identityRegistry; this.authenticator = authenticator; } /** * {@inheritDoc} */ @Override public void start() { // instantiate processor after the eXo container start, to let // start-dependent logic worked before us final AtomicReference<ServerAnnotationProcessor> processor = new AtomicReference<>(); // need initiate process after Bayeux server starts exoBayeux.addEventListener(new LifeCycle.Listener() { @Override public void lifeCycleStarted(LifeCycle event) { ServerAnnotationProcessor p = new ServerAnnotationProcessor(exoBayeux); processor.set(p); p.process(service); } @Override public void lifeCycleStopped(LifeCycle event) { ServerAnnotationProcessor p = processor.get(); if (p != null) { p.deprocess(service); } } @Override public void lifeCycleStarting(LifeCycle event) { // Nothing } @Override public void lifeCycleFailure(LifeCycle event, Throwable cause) { // Nothing } @Override public void lifeCycleStopping(LifeCycle event) { // Nothing } }); if (PropertyManager.isDevelopping()) { // This listener not required for work, just for info during development exoBayeux.addListener(new BayeuxServer.SessionListener() { @Override public void sessionRemoved(ServerSession session, ServerMessage message, boolean timedout) { if (LOG.isDebugEnabled()) { LOG.debug("sessionRemoved: " + session.getId() + " timedout:" + timedout + " channels: " + channelsAsString(session.getSubscriptions())); } } @Override public void sessionAdded(ServerSession session, ServerMessage message) { if (LOG.isDebugEnabled()) { LOG.debug("sessionAdded: " + session.getId() + " channels: " + channelsAsString(session.getSubscriptions())); } } }); } } /** * The CometService is responsible for sending messages to Cometd channels * when a document is saved. */ @Service("documents") public class CometdService { /** The bayeux. */ @Inject private BayeuxServer bayeux; /** The local session. */ @Session private LocalSession localSession; /** The server session. */ @Session private ServerSession serverSession; /** * Post construct. */ @PostConstruct public void postConstruct() { bayeux.addListener(channelListener); } /** * Pre destroy. */ @PreDestroy public void preDestroy() { bayeux.removeListener(channelListener); } /** * Subscribe documents. * * @param message the message * @param fileId the file id * @throws RepositoryException the repository exception */ @Subscription(CHANNEL_NAME_PARAMS) public void subscribeDocuments(Message message, @Param("fileId") String fileId) throws RepositoryException { Object objData = message.getData(); if (!Map.class.isInstance(objData)) { if (LOG.isDebugEnabled()) { LOG.debug("Couldn't get data as a map from event"); } return; } Map<String, Object> data = message.getDataAsMap(); String type = (String) data.get("type"); if (type.equals(DOCUMENT_OPENED_EVENT)) { String userId = (String) data.get("userId"); String workspace = (String) data.get("workspace"); String provider = (String) data.get("provider"); eventsHandlers.submit(new ContainerCommand(PortalContainer.getCurrentPortalContainerName()) { @Override void onContainerError(String error) { LOG.error("An error has occured in container: {}", containerName); } @Override void execute(ExoContainer exoContainer) { try { DocumentEditorProvider editorProvider = documentService.getEditorProvider(provider); Identity identity = userIdentity(userId); boolean allowed = editorProvider.isAvailableForUser(identity); List<String> availableProviders = service.getAllAvailableProviders(identity); String currentProvider = documentService.getCurrentDocumentProvider(fileId, workspace); boolean available = allowed && (currentProvider == null || provider.equals(currentProvider)); service.sendCurrentProviderInfo(fileId, available, availableProviders); if (currentProvider == null) { setCurrentDocumentProvider(fileId, workspace, provider); } } catch (DocumentEditorProviderNotFoundException | RepositoryException e) { LOG.error("Cannot send current provider info for fileId: " + fileId + ", workspace: " + workspace, e); } } }); } } protected List<String> getAllAvailableProviders(Identity identity) { return documentService.getDocumentEditorProviders() .stream() .filter(provider -> provider.isAvailableForUser(identity)) .map(DocumentEditorProvider::getProviderName) .collect(Collectors.toList()); } /** * Sets the current document provider. * * @param fileId the file id * @param workspace the workspace * @param provider the provider */ protected void setCurrentDocumentProvider(String fileId, String workspace, String provider) { eventsHandlers.submit(new ContainerCommand(PortalContainer.getCurrentPortalContainerName()) { @Override void onContainerError(String error) { LOG.error("An error has occured in container: {}", containerName); } @Override void execute(ExoContainer exoContainer) { try { documentService.saveCurrentDocumentProvider(fileId, workspace, provider); } catch (RepositoryException e) { LOG.error("Cannot set current document provider for fileId: " + fileId + ", workspace: " + workspace, e); } } }); } /** * Find or create user identity. * * @param userId the user id * @return the identity can be null if not found and cannot be created via * current authenticator */ protected Identity userIdentity(String userId) { Identity userIdentity = identityRegistry.getIdentity(userId); if (userIdentity == null) { // We create user identity by authenticator, but not register it in the // registry try { if (LOG.isDebugEnabled()) { LOG.debug("User identity not registered, trying to create it for: " + userId); } userIdentity = authenticator.createIdentity(userId); } catch (Exception e) { LOG.warn("Failed to create user identity: " + userId, e); } } return userIdentity; } /** * Send last editor closed event. * * @param fileId the file id * @param provider the provider */ protected void sendLastEditorClosedEvent(String fileId, String provider) { ServerChannel channel = bayeux.getChannel(CHANNEL_NAME + fileId); if (channel != null) { StringBuilder data = new StringBuilder(); data.append('{'); data.append("\"type\": \""); data.append(LAST_EDITOR_CLOSED_EVENT); data.append("\", "); data.append("\"fileId\": \""); data.append(fileId); data.append("\", "); data.append("\"provider\": \""); data.append(provider); data.append("\"}"); channel.publish(localSession, data.toString(), Promise.noop()); } } /** * Send last editor closed event. * * @param fileId the file id * @param available the available */ protected void sendCurrentProviderInfo(String fileId, boolean available, List<String> availableProviders) { ServerChannel channel = bayeux.getChannel(CHANNEL_NAME + fileId); if (channel != null) { String allProviders = null; try { allProviders = new JsonGeneratorImpl().createJsonArray(availableProviders).toString(); } catch (JsonException e) { LOG.warn("Cannot serialize all available providers to JSON", e); } StringBuilder data = new StringBuilder(); data.append('{'); data.append("\"type\": \""); data.append(CURRENT_PROVIDER_INFO); data.append("\", "); data.append("\"fileId\": \""); data.append(fileId); data.append("\", "); data.append("\"available\": \""); data.append(available); data.append("\", "); data.append("\"allProviders\":"); data.append(allProviders); data.append("}"); channel.publish(localSession, data.toString(), Promise.noop()); } } } /** * Channels as string. * * @param channels the channels * @return the string */ protected String channelsAsString(Set<ServerChannel> channels) { return channels.stream().map(c -> c.getId()).collect(Collectors.joining(", ")); } /** * {@inheritDoc} */ @Override public void stop() { // Nothing } /** * Gets the cometd server path. * * @return the cometd server path */ public String getCometdServerPath() { return new StringBuilder("/").append(exoBayeux.getCometdContextName()).append("/cometd").toString(); } /** * Gets the user token. * * @param userId the userId * @return the token */ public String getUserToken(String userId) { return exoBayeux.getUserToken(userId); } /** * Return object if it's String instance or null if it is not. * * @param obj the obj * @return the string or null */ protected String asString(Object obj) { if (obj != null && String.class.isAssignableFrom(obj.getClass())) { return String.class.cast(obj); } return null; } /** * Create a new thread executor service. * * @param threadNamePrefix the thread name prefix * @param maxFactor - max processes per CPU core * @param queueFactor - queue size per CPU core * @return the executor service */ protected ExecutorService createThreadExecutor(String threadNamePrefix, int maxFactor, int queueFactor) { // Executor will queue all commands and run them in maximum set of threads. // Minimum set of threads will be // maintained online even idle, other inactive will be stopped in two // minutes. final int cpus = Runtime.getRuntime().availableProcessors(); int poolThreads = cpus / 4; poolThreads = poolThreads < MIN_THREADS ? MIN_THREADS : poolThreads; int maxThreads = Math.round(cpus * 1f * maxFactor); maxThreads = maxThreads > 0 ? maxThreads : 1; maxThreads = maxThreads < MIN_MAX_THREADS ? MIN_MAX_THREADS : maxThreads; int queueSize = cpus * queueFactor; queueSize = queueSize < queueFactor ? queueFactor : queueSize; if (LOG.isDebugEnabled()) { LOG.debug("Creating thread executor " + threadNamePrefix + "* for " + poolThreads + ".." + maxThreads + " threads, queue size " + queueSize); } return new ThreadPoolExecutor(poolThreads, maxThreads, THREAD_IDLE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(queueSize), new CommandThreadFactory(threadNamePrefix), new ThreadPoolExecutor.CallerRunsPolicy()); } }
31,621
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CometdConfig.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/cometd/CometdConfig.java
/* * Copyright (C) 2003-2019 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.wcm.connector.collaboration.cometd; import org.exoplatform.ws.frameworks.json.impl.JsonException; import org.exoplatform.ws.frameworks.json.impl.JsonGeneratorImpl; /** * The CometdInfo class is used to pass necessary cometd information to a * client. */ public class CometdConfig { /** The path. */ private final String path; /** The token. */ private final String token; /** The container name. */ private final String containerName; private final String provider; private final String workspace; /** * Instantiates CometdConfig. * @param path the path * @param token the token * @param containerName the containerName */ public CometdConfig(String path, String token, String containerName) { super(); this.token = token; this.path = path; this.containerName = containerName; this.provider = null; this.workspace = null; } /** * Instantiates CometdConfig. * @param path the path * @param token the token * @param containerName the containerName * @param provider the provider * @param workspace the workspace */ public CometdConfig(String path, String token, String containerName, String provider, String workspace) { super(); this.token = token; this.path = path; this.containerName = containerName; this.provider = provider; this.workspace = workspace; } /** * Gets the token. * * @return the cometd token */ public String getToken() { return token; } /** * Gets the path. * * @return the cometdPath */ public String getPath() { return path; } /** * Gets the container name. * * @return the container */ public String getContainerName() { return containerName; } /** * Gets the provider. * * @return the provider */ public String getProvider() { return provider; } /** * Gets the workspace. * * @return the provider */ public String getWorkspace() { return workspace; } /** * To JSON. * * @return the string * @throws JsonException the json exception */ public String toJSON() throws JsonException { return new JsonGeneratorImpl().createJsonObject(this).toString(); } }
3,103
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
HypermediaLink.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/editors/HypermediaLink.java
/* * Copyright (C) 2003-2020 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.connector.collaboration.editors; /** * The Class HypermediaLink is used in HATEOAS REST services. */ public class HypermediaLink { /** The href. */ private final String href; /** * Instantiates a new link. * * @param href the href */ public HypermediaLink(String href) { this.href = href; } /** * Gets the href. * * @return the href */ public String getHref() { return href; } }
1,170
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DocumentEditorData.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/editors/DocumentEditorData.java
/* * Copyright (C) 2003-2020 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.connector.collaboration.editors; import java.util.List; /** * The Class DocumentEditorData. */ public class DocumentEditorData extends HypermediaSupport { /** The provider. */ private String provider; /** The active. */ private Boolean active; /** The permissions. */ private List<EditorPermission> permissions; /** * Instantiates a new document editor provider DTO. */ public DocumentEditorData() { } /** * Instantiates a new document editor provider DTO. * * @param provider the provider * @param active the active * @param permissions the permissions */ public DocumentEditorData(String provider, boolean active, List<EditorPermission> permissions) { this.provider = provider; this.active = active; this.permissions = permissions; } /** * Gets the provider. * * @return the provider */ public String getProvider() { return provider; } /** * Gets the active. * * @return the active */ public Boolean getActive() { return active; } /** * Sets the provider. * * @param provider the new provider */ public void setProvider(String provider) { this.provider = provider; } /** * Sets the active. * * @param active the new active */ public void setActive(Boolean active) { this.active = active; } /** * Sets the permissions. * * @param permissions the new permissions */ public void setPermissions(List<EditorPermission> permissions) { this.permissions = permissions; } /** * Gets the permissions. * * @return the permissions */ public List<EditorPermission> getPermissions() { return permissions; } }
2,462
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
IdentityData.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/editors/IdentityData.java
/* * Copyright (C) 2003-2020 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.connector.collaboration.editors; /** * The Class IdentityData. */ public class IdentityData extends EditorPermission { /** The type. */ private String type; /** * Instantiates a new identity search result. * * @param id the id * @param displayName the display name * @param type the type * @param avatarUrl the avatar url */ public IdentityData(String id, String displayName, String type, String avatarUrl) { super(id, displayName, avatarUrl); this.type = type; } /** * Gets the type. * * @return the type */ public String getType() { return type; } /** * Sets the type. * * @param type the new type */ public void setType(String type) { this.type = type; } }
1,488
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
HypermediaSupport.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/editors/HypermediaSupport.java
/* * Copyright (C) 2003-2020 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.connector.collaboration.editors; import java.util.HashMap; import java.util.Map; /** * The Class HypermediaSupport is used in HATEOAS REST services. */ public class HypermediaSupport { /** The links. */ protected Map<String, HypermediaLink> links = new HashMap<>(); /** * Gets the links. * * @return the links */ public Map<String, HypermediaLink> getLinks() { return links; } /** * Sets the links. * * @param links the new links */ public void setLinks(Map<String, HypermediaLink> links) { this.links = links; } /** * Adds the link. * * @param key the key * @param link the link */ public void addLink(String key, HypermediaLink link) { links.put(key, link); } }
1,480
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ErrorMessage.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/editors/ErrorMessage.java
/* * Copyright (C) 2003-2020 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.connector.collaboration.editors; /** * The Class ErrorMessage is used in REST services as response entity in error cases. */ public class ErrorMessage { /** The errorMessage. */ private final String errorMessage; /** The errorCode. */ private final String errorCode; /** * Instantiates a new error message. * * @param message the message * @param error the error */ public ErrorMessage(String message, String error) { this.errorMessage = message; this.errorCode = error; } /** * Gets the error message. * * @return the error message */ public String getErrorMessage() { return errorMessage; } /** * Gets the error code. * * @return the error code */ public String getErrorCode() { return errorCode; } }
1,525
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
EditorPermission.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/editors/EditorPermission.java
package org.exoplatform.wcm.connector.collaboration.editors; /** * The Class EditorPermission. */ public class EditorPermission { /** The name. */ protected String id; /** The display name. */ protected String displayName; /** The avatar url. */ protected String avatarUrl; /** * Instantiates a new EditorPermission. */ public EditorPermission() { } /** * Instantiates a new EditorPermission. * * @param id the id * @param displayName the display name * @param avatarUrl the avatar url */ public EditorPermission(String id, String displayName, String avatarUrl) { this.id = id; this.displayName = displayName; this.avatarUrl = avatarUrl; } /** * Instantiates a new EditorPermission. * * @param id the id */ public EditorPermission(String id) { this.id = id; displayName = null; avatarUrl = null; } /** * Gets the id. * * @return the id */ public String getId() { return id; } /** * Gets the display name. * * @return the display name */ public String getDisplayName() { return displayName; } /** * Gets the avatar url. * * @return the avatar url */ public String getAvatarUrl() { return avatarUrl; } /** * Sets the id. * * @param id the new id */ public void setId(String id) { this.id = id; } /** * Sets the display name. * * @param displayName the new display name */ public void setDisplayName(String displayName) { this.displayName = displayName; } /** * Sets the avatar url. * * @param avatarUrl the new avatar url */ public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; } }
1,739
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PreviewInfo.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/wcm/connector/collaboration/editors/PreviewInfo.java
package org.exoplatform.wcm.connector.collaboration.editors; import java.util.List; import org.exoplatform.services.cms.documents.impl.EditorProvidersHelper.ProviderInfo; /** * The Class PreviewInfo is used to initialize preview of the document. */ public class PreviewInfo { /** The file id. */ private final String fileId; /** The providers info. */ private final List<ProviderInfo> providersInfo; /** * Instantiates a new preview info. * * @param fileId the file id * @param providersInfo the providers info */ public PreviewInfo(String fileId, List<ProviderInfo> providersInfo) { super(); this.fileId = fileId; this.providersInfo = providersInfo; } /** * Gets the file id. * * @return the file id */ public String getFileId() { return fileId; } /** * Gets the providers info. * * @return the providers info */ public List<ProviderInfo> getProvidersInfo() { return providersInfo; } }
987
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
LocalizationConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/LocalizationConnector.java
package org.exoplatform.ecm.connector; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.services.rest.resource.ResourceContainer; import com.ibm.icu.text.Transliterator; @Path("/l11n/") public class LocalizationConnector implements ResourceContainer { /** The Constant LAST_MODIFIED_PROPERTY. */ private static final String LAST_MODIFIED_PROPERTY = "Last-Modified"; private static final String CONTENT_TYPE = "Content-Type"; /** The Constant IF_MODIFIED_SINCE_DATE_FORMAT. */ private static final String IF_MODIFIED_SINCE_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z"; @GET @Path("/cleanName/") public Response getCleanName( @QueryParam("name") String name ) throws Exception { DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); try { return Response.ok(org.exoplatform.services.cms.impl.Utils.cleanString(name)) .header(CONTENT_TYPE, "text/html; charset=utf-8") .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } catch (Exception e) { Response.serverError().build(); } return Response.ok() .header(CONTENT_TYPE, "text/html; charset=utf-8") .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } @GET @Path("/convertName/") public Response convertName( @QueryParam("name") String name ) throws Exception { DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); try { return Response.ok(Text.convertJcrChars(name)) .header(CONTENT_TYPE, "text/html; charset=utf-8") .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } catch (Exception e) { Response.serverError().build(); } return Response.ok() .header(CONTENT_TYPE, "text/html; charset=utf-8") .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } }
2,311
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
MigrationConnector.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/MigrationConnector.java
package org.exoplatform.ecm.connector; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import org.exoplatform.ecm.ProductVersions; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; @Path("/configuration/") public class MigrationConnector implements ResourceContainer { /** 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"; @GET @Path("/export/") public Response export() throws Exception { DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); try { Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element element = document.createElement("ecm"); element.setAttribute("version", ProductVersions.getCurrentVersion()); document.appendChild(element); Element drives = document.createElement("drives"); element.appendChild(drives); ManageDriveService driveService = WCMCoreUtils.getService(ManageDriveService.class); List<DriveData> drivesList = driveService.getAllDrives(); for (DriveData drive:drivesList) { Element driveElt = document.createElement("drive"); driveElt.setAttribute("name", drive.getName()); driveElt.setAttribute("views", drive.getViews()); driveElt.setAttribute("workspace", drive.getWorkspace()); driveElt.setAttribute("allowCreateFolders", drive.getAllowCreateFolders()); driveElt.setAttribute("homePath", drive.getHomePath()); driveElt.setAttribute("permissions", drive.getPermissions()); driveElt.setAttribute("homePath", drive.getHomePath()); driveElt.setAttribute("icon", drive.getIcon()); driveElt.setAttribute("showHiddenNode", String.valueOf(drive.getShowHiddenNode())); driveElt.setAttribute("viewNonDocument", String.valueOf(drive.getViewNonDocument())); driveElt.setAttribute("viewPreferences", String.valueOf(drive.getViewPreferences())); driveElt.setAttribute("viewSideBar", String.valueOf(drive.getViewSideBar())); String[] permissions = drive.getAllPermissions(); Element permsElt = document.createElement("permissions"); driveElt.appendChild(permsElt); for (String permission:permissions) { Element permElt = document.createElement("permission"); permElt.setTextContent(permission); permsElt.appendChild(permElt); } drives.appendChild(driveElt); } return Response.ok(new DOMSource(document), MediaType.TEXT_XML) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } catch (Exception e) { Response.serverError().build(); } return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } }
3,558
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DriveService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/clouddrives/DriveService.java
/* * Copyright (C) 2003-2018 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.ecm.connector.clouddrives; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.concurrent.ExecutionException; import javax.annotation.security.RolesAllowed; import javax.jcr.AccessDeniedException; import javax.jcr.LoginException; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.Session; 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.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDrive.Command; import org.exoplatform.services.cms.clouddrives.CloudDriveException; import org.exoplatform.services.cms.clouddrives.CloudDriveMessage; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.clouddrives.CloudFile; import org.exoplatform.services.cms.clouddrives.CloudProvider; import org.exoplatform.services.cms.clouddrives.DriveRemovedException; import org.exoplatform.services.cms.clouddrives.LocalCloudFile; import org.exoplatform.services.cms.clouddrives.NotCloudFileException; import org.exoplatform.services.cms.clouddrives.NotConnectedException; import org.exoplatform.services.cms.clouddrives.NotYetCloudFileException; import org.exoplatform.services.cms.clouddrives.RefreshAccessException; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import jakarta.servlet.http.HttpServletRequest; /** * REST service providing information about providers. Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: DriveService.java 00000 Oct 22, 2012 pnedonosko $ */ @Path("/clouddrive/drive") @Produces(MediaType.APPLICATION_JSON) public class DriveService implements ResourceContainer { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(DriveService.class); /** The Constant CONTENT_SUFIX. */ protected static final String CONTENT_SUFIX = "/jcr:content"; /** The cloud drives. */ protected final CloudDriveService cloudDrives; /** The jcr service. */ protected final RepositoryService jcrService; /** The session providers. */ protected final SessionProviderService sessionProviders; /** * REST cloudDrives uses {@link CloudDriveService} for actual job. * * @param cloudDrives {@link CloudDriveService} * @param jcrService {@link RepositoryService} * @param sessionProviders {@link SessionProviderService} */ public DriveService(CloudDriveService cloudDrives, RepositoryService jcrService, SessionProviderService sessionProviders) { this.cloudDrives = cloudDrives; this.jcrService = jcrService; this.sessionProviders = sessionProviders; } /** * Return drive information. * * @param uriInfo {@link UriInfo} * @param workspace String * @param path String * @return set of {@link CloudProvider} currently available for connect */ @GET @RolesAllowed("users") public Response getDrive(@Context HttpServletRequest request, @Context UriInfo uriInfo, @QueryParam("workspace") String workspace, @QueryParam("path") String path) { if (workspace != null) { if (path != null) { Locale locale = request.getLocale(); return readDrive(workspace, path, locale, false); } else { return Response.status(Status.BAD_REQUEST).entity(ErrorEntiry.message("Null path")).build(); } } else { return Response.status(Status.BAD_REQUEST).entity(ErrorEntiry.message("Null workspace")).build(); } } /** * Synchronized cloud drive or its file/folder and return result for client refresh. * * @param uriInfo {@link UriInfo} * @param workspace {@link String} Drive Node workspace * @param path {@link String} Drive Node path * @return the response */ @POST @Path("/synchronize/") @RolesAllowed("users") public Response synchronize(@Context HttpServletRequest request, @Context UriInfo uriInfo, @FormParam("workspace") String workspace, @FormParam("path") String path) { if (workspace != null) { if (path != null) { Locale locale = request.getLocale(); return readDrive(workspace, path, locale, true); } else { return Response.status(Status.BAD_REQUEST).entity("Null path.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null workspace.").build(); } } // *********************************** internals ************************************* /** * Read cloud drive and optionally synchronized it before. Drive will contain a file from it will asked, * * @param workspace {@link String} Drive workspace * @param path {@link String} path of a Node in the Drive * @param synchronize {@link Boolean} flag to synch before the read (true to force sync) * @return {@link Response} REST response */ protected Response readDrive(String workspace, String path, Locale locale, boolean synchronize) { try { CloudDrive local = cloudDrives.findDrive(workspace, path); if (local != null) { Collection<CloudFile> files; Collection<String> removed; Collection<CloudDriveMessage> messages; if (synchronize) { try { Command sync = local.synchronize(); sync.await(); // wait for sync process files = sync.getFiles(); initModified(files, locale); removed = sync.getRemoved(); messages = sync.getMessages(); } catch (InterruptedException e) { LOG.warn("Caller of synchronization command interrupted.", e); Thread.currentThread().interrupt(); return Response.status(Status.SERVICE_UNAVAILABLE) .entity(ErrorEntiry.message("Synchrinization interrupted. Try again later.")) .build(); } catch (ExecutionException e) { Throwable err = e.getCause(); if (err instanceof RefreshAccessException) { LOG.warn("Synchronization failed, need refresh access to cloud drive for {}. {}", local.getUser().getId(), err.getMessage() + (err.getCause() != null ? ". " + err.getCause().getMessage() : "")); // client should treat this status in special way and obtain new // credentials using given provider return Response.status(Status.FORBIDDEN).entity(local.getUser().getProvider()).build(); } else if (err instanceof NotConnectedException) { LOG.warn("Cannot synchronize not connected drive. " + err.getMessage(), err); return Response.status(Status.BAD_REQUEST) .entity(ErrorEntiry.notCloudDrive("Drive not connected", workspace, path)) .build(); } else if (err instanceof CloudDriveException) { LOG.error("Error synchrinizing the drive. " + err.getMessage(), err); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(ErrorEntiry.message("Error synchrinizing the drive. Try again later.")) .build(); } else if (err instanceof AccessDeniedException) { if (LOG.isDebugEnabled()) { LOG.debug("Not sufficient permissions. " + err.getMessage()); } return Response.status(Status.FORBIDDEN) .entity(ErrorEntiry.acessDenied("Access denied. Synchronization canceled.")) .build(); } else if (err instanceof RepositoryException) { LOG.error("Storage error. " + err.getMessage(), err); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(ErrorEntiry.message("Storage error. Synchronization canceled.")) .build(); } else if (err instanceof RuntimeException) { LOG.error("Runtime error. " + err.getMessage(), err); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(ErrorEntiry.message("Internal server error. Synchronization canceled. Try again later.")) .build(); } LOG.error("Unexpected error. " + err.getMessage(), err); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(ErrorEntiry.message("Unexpected server error. Synchronization canceled. Try again later.")) .build(); } catch (RefreshAccessException e) { LOG.warn("Synchronization cannot start, need refresh access to cloud drive for {}. {}", local.getUser().getId(), e.getMessage() + (e.getCause() != null ? ". " + e.getCause().getMessage() : "")); // client should treat this status in special way and obtain new // credentials using given provider return Response.status(Status.FORBIDDEN).entity(local.getUser().getProvider()).build(); } catch (CloudDriveException e) { LOG.error("Error synchronizing drive " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(ErrorEntiry.message("Error synchronizing drive. " + e.getMessage())) .build(); } } else { files = new ArrayList<CloudFile>(); removed = Collections.emptyList(); messages = Collections.emptyList(); try { if (!local.getPath().equals(path)) { // if path not the drive itself CloudFile file = local.getFile(path); files.add(file); if (!file.getPath().equals(path)) { // it's symlink, add it also files.add(new LinkedCloudFile(file, path)); } initModified(file, locale); } } catch (NotYetCloudFileException e) { if (LOG.isDebugEnabled()) { LOG.debug("Item " + workspace + ":" + path + " not yet a cloud file : " + e.getMessage()); } files.add(new AcceptedCloudFile(path)); } catch (NotCloudFileException e) { if (LOG.isDebugEnabled()) { LOG.debug("Item " + workspace + ":" + path + " not a cloud file : " + e.getMessage()); } } } return Response.ok().entity(DriveInfo.create(workspace, local, files, removed, messages)).build(); } else { if (LOG.isDebugEnabled()) { LOG.debug("Item " + workspace + ":" + path + " not a cloud file or drive not connected."); } return Response.status(Status.NO_CONTENT).entity(ErrorEntiry.notCloudDrive("Not connected", workspace, path)).build(); } } catch (LoginException e) { LOG.warn("Error login to read drive " + workspace + ":" + path + ". " + e.getMessage()); return Response.status(Status.UNAUTHORIZED).entity(ErrorEntiry.message("Authentication error")).build(); } catch (DriveRemovedException e) { LOG.error("Drive removed " + workspace + ":" + path, e); return Response.status(Status.NOT_FOUND).entity(ErrorEntiry.driveRemoved("Drive removed", workspace, path)).build(); } catch (PathNotFoundException e) { LOG.warn("Error reading file " + workspace + ":" + path + ". " + e.getMessage()); return Response.status(Status.NOT_FOUND) .entity(ErrorEntiry.nodeNotFound("File was removed or renamed", workspace, path)) .build(); } catch (RepositoryException e) { LOG.error("Error reading drive " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(ErrorEntiry.message("Error reading drive: storage error")) .build(); } catch (Throwable e) { LOG.error("Error reading drive " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(ErrorEntiry.message("Error reading drive: runtime error")) .build(); } } /** * Return file information. Returned file may be not yet created in cloud (accepted for creation), then this service response * will be with status ACCEPTED, otherwise it's OK response. * * @param uriInfo the uri info * @param workspace {@link String} Drive Node workspace * @param path {@link String} File Node path * @return {@link Response} REST response */ @GET @Path("/file/") @RolesAllowed("users") public Response getFile(@Context HttpServletRequest request, @Context UriInfo uriInfo, @QueryParam("workspace") String workspace, @QueryParam("path") String path) { if (workspace != null) { if (path != null) { try { Locale locale = request.getLocale(); CloudDrive local = cloudDrives.findDrive(workspace, path); if (local != null) { try { CloudFile file = local.getFile(path); if (!file.getPath().equals(path)) { file = new LinkedCloudFile(file, path); // it's symlink } initModified(file, locale); return Response.ok().entity(file).build(); } catch (NotYetCloudFileException e) { return Response.status(Status.ACCEPTED).entity(new AcceptedCloudFile(path)).build(); } catch (NotCloudFileException e) { return Response.status(Status.NOT_FOUND).entity(ErrorEntiry.notCloudFile(e.getMessage(), workspace, path)).build(); } } if (LOG.isDebugEnabled()) { LOG.debug("Item " + workspace + ":" + path + " not a cloud file or drive not connected."); } return Response.status(Status.NOT_FOUND) .entity(ErrorEntiry.notCloudDrive("Not a cloud file or drive not connected", workspace, path)) .build(); } catch (LoginException e) { LOG.warn("Error login to read drive file " + workspace + ":" + path + ": " + e.getMessage()); return Response.status(Status.UNAUTHORIZED).entity(ErrorEntiry.message("Authentication error")).build(); } catch (CloudDriveException e) { LOG.warn("Error reading file " + workspace + ":" + path, e); return Response.status(Status.BAD_REQUEST).entity(ErrorEntiry.message("Error reading file. " + e.getMessage())).build(); } catch (RepositoryException e) { LOG.error("Error reading file " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(ErrorEntiry.message("Error reading file: storage error.")) .build(); } catch (Throwable e) { LOG.error("Error reading file " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(ErrorEntiry.message("Error reading file: runtime error.")) .build(); } } else { return Response.status(Status.BAD_REQUEST).entity(ErrorEntiry.message("Null path")).build(); } } else { return Response.status(Status.BAD_REQUEST).entity(ErrorEntiry.message("Null workspace")).build(); } } /** * Return list of files in given folder. Returned files may be not yet created in cloud (accepted for creation), then this * service response will be with status ACCEPTED, otherwise it's OK response. This service will not return files for nodes that * do not belong to the cloud drive associated with this path. * * @param uriInfo the uri info * @param workspace {@link String} Drive Node workspace * @param path {@link String} Folder Node path * @return {@link Response} REST response */ @GET @Path("/files/") @RolesAllowed("users") public Response getFiles(@Context HttpServletRequest request, @Context UriInfo uriInfo, @QueryParam("workspace") String workspace, @QueryParam("path") String path) { if (workspace != null) { if (path != null) { try { Locale locale = request.getLocale(); CloudDrive local = cloudDrives.findDrive(workspace, path); if (local != null) { String parentPath; if (local.getPath().equals(path)) { parentPath = path; } else { try { // take node path from parent to unlink if the parent is symlink parentPath = local.getFile(path).getPath(); } catch (NotYetCloudFileException e) { // use path as is parentPath = path; } } SessionProvider sp = sessionProviders.getSessionProvider(null); Session userSession = sp.getSession(workspace, jcrService.getCurrentRepository()); Node parentNode = (Node) userSession.getItem(parentPath); List<CloudFile> files = new ArrayList<CloudFile>(); boolean hasAccepted = false; for (NodeIterator childs = parentNode.getNodes(); childs.hasNext();) { Node fileNode = childs.nextNode(); String filePath = fileNode.getPath(); try { CloudFile file = local.getFile(filePath); if (file != null) { if (!file.getPath().equals(filePath)) { file = new LinkedCloudFile(file, filePath); // it's symlink } initModified(file, locale); files.add(file); } // not a cloud file - skip it } catch (NotYetCloudFileException e) { hasAccepted = true; files.add(new AcceptedCloudFile(filePath)); } } ResponseBuilder resp; if (hasAccepted) { resp = Response.status(Status.ACCEPTED); } else { resp = Response.ok(); } return resp.entity(files).build(); } if (LOG.isDebugEnabled()) { LOG.debug("Item " + workspace + ":" + path + " not a cloud file or drive not connected."); } return Response.status(Status.NOT_FOUND).entity(ErrorEntiry.notCloudDrive("Not connected", workspace, path)).build(); } catch (LoginException e) { LOG.warn("Error login to read drive files in " + workspace + ":" + path + ": " + e.getMessage()); return Response.status(Status.UNAUTHORIZED).entity("Authentication error.").build(); } catch (CloudDriveException e) { LOG.warn("Error reading files in " + workspace + ":" + path, e); return Response.status(Status.BAD_REQUEST).entity("Error reading files. " + e.getMessage()).build(); } catch (RepositoryException e) { LOG.error("Error reading files in " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error reading files: storage error.").build(); } catch (Throwable e) { LOG.error("Error reading files in " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error reading file: runtime error.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity(ErrorEntiry.message("Null path")).build(); } } else { return Response.status(Status.BAD_REQUEST).entity(ErrorEntiry.message("Null workspace")).build(); } } /** * State of a drive pointed by given workspace and path. * * @param uriInfo - request info * @param workspace the workspace * @param path the path * @return {@link Response} */ @GET @Path("/state/") @RolesAllowed("users") public Response getState(@Context UriInfo uriInfo, @QueryParam("workspace") String workspace, @QueryParam("path") String path) { if (workspace != null) { if (path != null) { try { CloudDrive local = cloudDrives.findDrive(workspace, path); if (local != null) { try { return Response.status(Status.OK).entity(local.getState()).build(); } catch (RefreshAccessException e) { Throwable cause = e.getCause(); LOG.warn("Access to cloud drive expired, forbidden or revoked. " + e.getMessage() + (cause != null ? ". " + cause.getMessage() : "")); // client should treat this status in special way and obtain new // credentials using given // provider return Response.status(Status.FORBIDDEN).entity(local.getUser().getProvider()).build(); } catch (CloudDriveException e) { LOG.error("Error getting changes link for drive " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("Error getting changes link. " + e.getMessage()) .build(); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Item " + workspace + ":" + path + " not a cloud file or drive not connected."); } return Response.status(Status.NOT_FOUND).entity(ErrorEntiry.notCloudDrive("Not connected", workspace, path)).build(); } } catch (LoginException e) { LOG.warn("Error login to read drive " + workspace + ":" + path + ". " + e.getMessage()); return Response.status(Status.UNAUTHORIZED).entity("Authentication error.").build(); } catch (RepositoryException e) { LOG.error("Error reading drive " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error reading drive: storage error.").build(); } catch (Throwable e) { LOG.error("Error reading drive " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error reading drive: runtime error.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity(ErrorEntiry.message("Null path")).build(); } } else { return Response.status(Status.BAD_REQUEST).entity(ErrorEntiry.message("Null workspace")).build(); } } private void initModified(Collection<CloudFile> files, Locale locale) { for (CloudFile file : files) { initModified(file, locale); } } private void initModified(CloudFile file, Locale locale) { if (file.isConnected()) { try { LocalCloudFile.class.cast(file).initModified(locale); } catch (ClassCastException e) { // safely ignore it, but let to know it was LOG.warn("Cannot initialize cloud file modified field for {} due to error: {}", file.getPath(), e.getMessage()); } } } }
25,026
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
LinkedCloudFile.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/clouddrives/LinkedCloudFile.java
/* * Copyright (C) 2003-2018 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.ecm.connector.clouddrives; import java.util.Calendar; import javax.jcr.Node; import org.exoplatform.services.cms.clouddrives.CloudFile; import org.exoplatform.services.cms.clouddrives.LocalCloudFile; /** * Wraps fields from another {@link CloudFile} and replace its path with a path of that file {@link Node} symlink node.<br> * NOTE: we cannot wrap instance of another another {@link CloudFile} as it leads to StackOverflowError in WS * JsonGeneratorImpl.<br> * Created by The eXo Platform SAS.<br> * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: LinkedCloudFile.java 00000 Jan 24, 2013 pnedonosko $ */ public class LinkedCloudFile extends LocalCloudFile { /** The id. */ private final String id; /** The title. */ private final String title; /** The link. */ private final String link; /** The edit link. */ private final String editLink; /** The preview link. */ private final String previewLink; /** The thumbnail link. */ private final String thumbnailLink; /** The type mode. */ private final String type, typeMode; /** The last user. */ private final String lastUser; /** The author. */ private final String author; /** The size. */ private final long size; // FYI transient fields will not appear in serialized forms like JSON object // on client side /** The created date. */ private final transient Calendar createdDate; /** The modified date. */ private final transient Calendar modifiedDate; /** The local modified date. */ private final transient Calendar localModifiedDate; /** The folder. */ private final boolean folder; /** The path. */ private final String path; /** The is symlink. */ private final boolean isSymlink; /** * Instantiates a new linked cloud file. * * @param file the file * @param path the path */ public LinkedCloudFile(CloudFile file, String path) { this.id = file.getId(); this.title = file.getTitle(); this.link = file.getLink(); this.editLink = file.getEditLink(); this.previewLink = file.getPreviewLink(); this.thumbnailLink = file.getThumbnailLink(); this.type = file.getType(); this.typeMode = file.getTypeMode(); this.lastUser = file.getLastUser(); this.author = file.getAuthor(); this.folder = file.isFolder(); this.createdDate = file.getCreatedDate(); this.modifiedDate = file.getModifiedDate(); this.path = path; this.size = file.getSize(); this.isSymlink = true; Calendar localModifiedDate; try { localModifiedDate = LocalCloudFile.class.cast(file).getLocalModifiedDate(); } catch (ClassCastException e) { // Not a drive of this file or drive disconnected or removed localModifiedDate = this.modifiedDate; } this.localModifiedDate = localModifiedDate; } /** * Checks if is symlink. * * @return true, if is symlink */ public boolean isSymlink() { return isSymlink; } /** * {@inheritDoc} */ public String getId() { return id; } /** * {@inheritDoc} */ public String getTitle() { return title; } /** * {@inheritDoc} */ public String getLink() { return link; } /** * {@inheritDoc} */ public String getEditLink() { return editLink; } /** * {@inheritDoc} */ public String getPreviewLink() { return previewLink; } /** * {@inheritDoc} */ public String getThumbnailLink() { return thumbnailLink; } /** * {@inheritDoc} */ public String getType() { return type; } /** * {@inheritDoc} */ public String getTypeMode() { return typeMode; } /** * {@inheritDoc} */ public String getLastUser() { return lastUser; } /** * {@inheritDoc} */ public String getAuthor() { return author; } /** * {@inheritDoc} */ public Calendar getCreatedDate() { return createdDate; } /** * {@inheritDoc} */ public Calendar getModifiedDate() { return modifiedDate; } /** * {@inheritDoc} */ public boolean isFolder() { return folder; } /** * {@inheritDoc} */ public String getPath() { return path; } /** * {@inheritDoc} */ @Override public long getSize() { return size; } /** * {@inheritDoc} */ @Override public Calendar getLocalModifiedDate() { return localModifiedDate; } }
5,461
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DriveServiceLocator.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/clouddrives/DriveServiceLocator.java
/* * Copyright (C) 2003-2016 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.ecm.connector.clouddrives; /** * Host management for Cloud Drive connections.<br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: DriveServiceLocator.java 00000 May 22, 2013 pnedonosko $ */ public class DriveServiceLocator { /** * Base host name or <code>null</code> if base should be obtained from a * request. This method can be overridden for context depended locators. * * @return {@link String} */ public String getBaseHost() { return null; } /** * Compile service host name from given request's host, optionally taking in * account context. This method can be overridden for context depended * locators. See also {@link #isRedirect(String)}. * * @param context {@link String} * @param requestURI {@link String} * @return {@link String} */ public String getServiceLink(String context, String requestURI) { // ignore context return requestURI; } /** * Answers whether the request (to given host) should be redirected to its * contextual link. See also {@link #getServiceLink(String, String)}. * * @param requestHost the request host * @return boolean, <code>true</code> if request should be redirected, * <code>false</code> otherwise. */ public final boolean isRedirect(String requestHost) { String baseHost = getBaseHost(); if (baseHost != null) { return baseHost.equals(requestHost); } else { return false; } } /** * Return host name for given request URI. * * @param requestHost {@link String} * @return String with the host's domain name or empty string if it's * <code>localhost</code> */ public final String getServiceHost(String requestHost) { String host = getBaseHost(); if (host == null) { host = requestHost; } if (host.equalsIgnoreCase("localhost")) { // empty host for localhost domain, see // http://curl.haxx.se/rfc/cookie_spec.html host = ""; } return host; } }
2,935
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DisconnectRestService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/clouddrives/DisconnectRestService.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.ecm.connector.clouddrives; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.Parameter; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import javax.ws.rs.*; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.exoplatform.services.cms.clouddrives.*; import org.exoplatform.services.rest.resource.ResourceContainer; @Path("/clouddrive/disconnect") public class DisconnectRestService implements ResourceContainer { private static final Log LOG = ExoLogger.getLogger(DisconnectRestService.class.getName()); private CloudDriveService cloudDriveService; public DisconnectRestService(CloudDriveService cloudDriveService) { this.cloudDriveService = cloudDriveService; } @DELETE @Produces(MediaType.APPLICATION_JSON) @Operation(summary = "Disconnect From Cloud Drive", method = "POST", description = "Disconnect From Cloud Drive") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Request fulfilled"), @ApiResponse(responseCode = "500", description = "Internal server error"), }) public Response disconnect(@Parameter(description = "workspace", required = true) @QueryParam("workspace") String workspace, @Parameter(description = "userEmail", required = true) @QueryParam("userEmail") String userEmail, @Parameter(description = "providerId", required = true) @QueryParam("providerId") String providerId ) { try { cloudDriveService.disconnectCloudDrive(workspace, userEmail, providerId); return Response.ok().build(); } catch (Exception e) { LOG.error("Error disconnecting from cloud drive", e); return Response.serverError().entity(e.getMessage()).build(); } } }
2,934
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ProviderService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/clouddrives/ProviderService.java
/* * Copyright (C) 2003-2016 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.ecm.connector.clouddrives; import java.util.Set; import javax.annotation.security.RolesAllowed; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.exoplatform.services.cms.clouddrives.CloudDriveException; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.clouddrives.CloudProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; /** * REST service providing information about providers. Created by The eXo * Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: ProviderService.java 00000 Oct 13, 2012 pnedonosko $ */ @Path("/clouddrive/provider") @Produces(MediaType.APPLICATION_JSON) public class ProviderService implements ResourceContainer { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(ProviderService.class); /** The cloud drives. */ protected final CloudDriveService cloudDrives; /** * REST cloudDrives uses {@link CloudDriveService} for actual job. * * @param cloudDrives the cloud drives */ public ProviderService(CloudDriveService cloudDrives) { this.cloudDrives = cloudDrives; } /** * Return available providers. * * @return set of {@link CloudProvider} currently available for connect */ @GET @RolesAllowed("users") @Path("/all") public Set<CloudProvider> getAll() { return cloudDrives.getProviders(); } /** * Return provider by its id. * * @param providerId - provider name see more in {@link CloudProvider} * @return response with asked {@link CloudProvider} json */ @GET @RolesAllowed("users") @Path("/{providerid}") public Response getById(@PathParam("providerid") String providerId) { try { return Response.ok().entity(cloudDrives.getProvider(providerId)).build(); } catch (CloudDriveException e) { LOG.warn("Cannot return prvider by id " + providerId + ": " + e.getMessage()); return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build(); } } }
3,192
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DriveInfo.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/clouddrives/DriveInfo.java
/* * Copyright (C) 2003-2018 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.ecm.connector.clouddrives; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import javax.jcr.RepositoryException; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveException; import org.exoplatform.services.cms.clouddrives.CloudDriveMessage; import org.exoplatform.services.cms.clouddrives.CloudFile; import org.exoplatform.services.cms.clouddrives.CloudProvider; /** * Drive representation that will be returned to clients. <br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: DriveInfo.java 00000 10 Nov 2013 peter $ */ public class DriveInfo { /** The provider. */ final CloudProvider provider; /** The files. */ final Map<String, CloudFile> files; /** The removed. */ final Collection<String> removed; /** The messages. */ final Collection<CloudDriveMessage> messages; /** The workspace. */ final String workspace; /** The path. */ final String path; /** The title. */ final String title; /** The state. */ final Object state; /** The connected. */ final boolean connected; /** The connected account. */ final String email; /** * Instantiates a new drive info. * * @param title the title * @param workspace the workspace * @param path the path * @param state the state * @param connected the connected * @param provider the provider * @param files the files * @param removed the removed * @param messages the messages */ DriveInfo(String title, String workspace, String path, Object state, boolean connected, CloudProvider provider, Map<String, CloudFile> files, Collection<String> removed, Collection<CloudDriveMessage> messages, String email) { this.title = title; this.workspace = workspace; this.path = path; this.state = state; this.connected = connected; this.provider = provider; this.files = files; this.messages = messages; this.removed = removed; this.email = email; } /** * Creates the. * * @param workspaces the workspaces * @param drive the drive * @param files the files * @param removed the removed * @param messages the messages * @return the drive info * @throws RepositoryException the repository exception * @throws CloudDriveException the cloud drive exception */ static DriveInfo create(String workspaces, CloudDrive drive, Collection<CloudFile> files, Collection<String> removed, Collection<CloudDriveMessage> messages) throws RepositoryException, CloudDriveException { Map<String, CloudFile> driveFiles = new HashMap<String, CloudFile>(); for (CloudFile cf : files) { driveFiles.put(cf.getPath(), cf); } return new DriveInfo(drive.getTitle(), workspaces, drive.getPath(), drive.getState(), drive.isConnected(), drive.getUser().getProvider(), driveFiles, removed, messages, drive.getUser().getEmail()); } /** * Creates the. * * @param workspaces the workspaces * @param drive the drive * @param files the files * @param messages the messages * @return the drive info * @throws RepositoryException the repository exception * @throws CloudDriveException the cloud drive exception */ static DriveInfo create(String workspaces, CloudDrive drive, Collection<CloudFile> files, Collection<CloudDriveMessage> messages) throws RepositoryException, CloudDriveException { return create(workspaces, drive, files, new HashSet<String>(), messages); } /** * Creates the. * * @param workspaces the workspaces * @param drive the drive * @return the drive info * @throws RepositoryException the repository exception * @throws CloudDriveException the cloud drive exception */ static DriveInfo create(String workspaces, CloudDrive drive) throws RepositoryException, CloudDriveException { return create(workspaces, drive, new ArrayList<CloudFile>(), new HashSet<String>(), new ArrayList<CloudDriveMessage>()); } /** * Gets the provider. * * @return the provider */ public CloudProvider getProvider() { return provider; } /** * Gets the files. * * @return the files */ public Map<String, CloudFile> getFiles() { return files; } /** * Gets the removed. * * @return the removed */ public Collection<String> getRemoved() { return removed; } /** * Gets the messages. * * @return the messages */ public Collection<CloudDriveMessage> getMessages() { return messages; } /** * Gets the path. * * @return the path */ public String getPath() { return path; } /** * Gets the state. * * @return the state */ public Object getState() { return state; } /** * Gets the title. * * @return the title */ public String getTitle() { return title; } /** * Gets the workspace. * * @return the workspace */ public String getWorkspace() { return workspace; } /** * Checks if is connected. * * @return true, if is connected */ public boolean isConnected() { return connected; } /** * Gets the user's email. * * @return the email */ public String getEmail() { return email; } }
6,936
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ErrorEntiry.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/clouddrives/ErrorEntiry.java
/* * Copyright (C) 2003-2016 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.ecm.connector.clouddrives; import java.util.LinkedHashMap; import java.util.Map; /** * Base POJO for web-service errors.<br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: ErrorEntiry.java 00000 Dec 21, 2014 pnedonosko $ */ public class ErrorEntiry { /** The Constant DRIVE_REMOVED. */ public static final String DRIVE_REMOVED = "drive-removed"; /** The Constant NODE_NOT_FOUND. */ public static final String NODE_NOT_FOUND = "node-not-found"; /** The Constant NOT_CLOUD_DRIVE. */ public static final String NOT_CLOUD_DRIVE = "not-cloud-drive"; /** The Constant NOT_CLOUD_FILE. */ public static final String NOT_CLOUD_FILE = "not-cloud-file"; /** The Constant NOT_YET_CLOUD_FILE. */ public static final String NOT_YET_CLOUD_FILE = "not-yet_cloud-file"; /** The Constant ACCESS_DENIED. */ public static final String ACCESS_DENIED = "access-denied"; /** * Acess denied. * * @param message the message * @return the error entiry */ public static ErrorEntiry acessDenied(String message) { ErrorEntiry err = new ErrorEntiry(); err.error = ACCESS_DENIED; err.message = message; return err; } /** * Error. * * @param errorCode the error code * @return the error entiry */ public static ErrorEntiry error(String errorCode) { ErrorEntiry err = new ErrorEntiry(); err.error = errorCode; return err; } /** * Error. * * @param errorCode the error code * @param message the message * @return the error entiry */ public static ErrorEntiry error(String errorCode, String message) { ErrorEntiry err = new ErrorEntiry(); err.error = errorCode; err.message = message; return err; } /** * Error. * * @param errorCode the error code * @param message the message * @param workspace the workspace * @param path the path * @return the error entiry */ public static ErrorEntiry error(String errorCode, String message, String workspace, String path) { ErrorEntiry err = new ErrorEntiry(); err.error = errorCode; err.message = message; err.workspace = workspace; err.path = path; return err; } /** * Message. * * @param message the message * @return the error entiry */ public static ErrorEntiry message(String message) { ErrorEntiry err = new ErrorEntiry(); err.message = message; return err; } /** * Drive removed. * * @param message the message * @param workspace the workspace * @param path the path * @return the error entiry */ public static ErrorEntiry driveRemoved(String message, String workspace, String path) { ErrorEntiry err = new ErrorEntiry(); err.error = DRIVE_REMOVED; err.message = message; return err; } /** * Node not found. * * @param message the message * @param workspace the workspace * @param path the path * @return the error entiry */ public static ErrorEntiry nodeNotFound(String message, String workspace, String path) { ErrorEntiry err = new ErrorEntiry(); err.error = NODE_NOT_FOUND; err.message = message; return err; } /** * Not cloud drive. * * @param message the message * @param workspace the workspace * @param path the path * @return the error entiry */ public static ErrorEntiry notCloudDrive(String message, String workspace, String path) { ErrorEntiry err = new ErrorEntiry(); err.error = NOT_CLOUD_DRIVE; err.message = message; return err; } /** * Not cloud file. * * @param message the message * @param workspace the workspace * @param path the path * @return the error entiry */ public static ErrorEntiry notCloudFile(String message, String workspace, String path) { ErrorEntiry err = new ErrorEntiry(); err.error = NOT_CLOUD_FILE; err.message = message; return err; } /** * Not yet cloud file. * * @param message the message * @param workspace the workspace * @param path the path * @return the error entiry */ public static ErrorEntiry notYetCloudFile(String message, String workspace, String path) { ErrorEntiry err = new ErrorEntiry(); err.error = NOT_YET_CLOUD_FILE; err.message = message; return err; } // ************** instance members ************** /** * Human-readable message. */ protected String message; /** * Context node workspace in JCR. Optional. */ protected String workspace; /** * Context node path in JCR. Optional. */ protected String path; /** * Error key for client software. */ protected String error; /** * Optional properties. */ protected Map<String, Object> props = new LinkedHashMap<String, Object>(); /** * Instantiates a new error entiry. */ public ErrorEntiry() { } /** * Adds the property. * * @param key the key * @param value the value */ public void addProperty(String key, Object value) { props.put(key, value); } /** * Gets the property. * * @param key the key * @return the property */ public Object getProperty(String key) { return props.get(key); } /** * Gets the message. * * @return the message */ public String getMessage() { return message; } /** * Gets the workspace. * * @return the workspace */ public String getWorkspace() { return workspace; } /** * Gets the path. * * @return the path */ public String getPath() { return path; } /** * Gets the error. * * @return the error */ public String getError() { return error; } /** * Gets the props. * * @return the properties */ public Map<String, ?> getProps() { return props; } }
6,799
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CommandState.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/clouddrives/CommandState.java
/* * Copyright (C) 2003-2016 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.ecm.connector.clouddrives; /** * Bean used for creation of connect and state request entity in JSON.<br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: CommandState.java 00000 Jan 17, 2013 pnedonosko $ */ public class CommandState { /** The service url. */ final String serviceUrl; /** The drive. */ final DriveInfo drive; /** The error. */ final String error; /** The progress. */ final int progress; /** * Instantiates a new command state. * * @param drive the drive * @param progress the progress * @param serviceUrl the service url */ CommandState(DriveInfo drive, int progress, String serviceUrl) { this.drive = drive; this.progress = progress; this.serviceUrl = serviceUrl; this.error = ""; } /** * Instantiates a new command state. * * @param drive the drive * @param error the error * @param progress the progress * @param serviceUrl the service url */ CommandState(DriveInfo drive, String error, int progress, String serviceUrl) { this.drive = drive; this.error = error; this.progress = progress; this.serviceUrl = serviceUrl; } /** * Instantiates a new command state. * * @param error the error * @param progress the progress * @param serviceUrl the service url */ CommandState(String error, int progress, String serviceUrl) { this(null, error, progress, serviceUrl); } /** * Gets the drive. * * @return the drive */ public DriveInfo getDrive() { return drive; } /** * Gets the progress. * * @return the progress */ public int getProgress() { return progress; } /** * Gets the service url. * * @return the serviceUrl */ public String getServiceUrl() { return serviceUrl; } /** * Gets the error. * * @return the error */ public String getError() { return error; } }
2,854
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ConnectService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/clouddrives/ConnectService.java
/* * Copyright (C) 2003-2016 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.ecm.connector.clouddrives; import java.net.URI; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.security.RolesAllowed; import javax.jcr.Item; import javax.jcr.LoginException; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.ws.rs.CookieParam; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.exoplatform.services.cms.clouddrives.*; import org.exoplatform.services.cms.clouddrives.CloudDrive.Command; import org.exoplatform.services.cms.clouddrives.jcr.JCRLocalCloudDrive; import org.exoplatform.services.cms.clouddrives.jcr.NodeFinder; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.security.ConversationState; /** * REST service responsible for connection of cloud drives to local JCR nodes. * <br> * Handles following workflow: * <ul> * <li>Initiate user request</li> * <li>Authenticate user</li> * <li>Starts connect command</li> * <li>Check connect status</li> * </ul> * <br> * Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: ConnectService.java 00000 Sep 13, 2012 pnedonosko $ */ @Path("/clouddrive/connect") @Produces(MediaType.APPLICATION_JSON) public class ConnectService implements ResourceContainer { /** The Constant CONNECT_COOKIE. */ public static final String CONNECT_COOKIE = "cloud-drive-connect-id"; /** The Constant ERROR_COOKIE. */ public static final String ERROR_COOKIE = "cloud-drive-error"; /** The Constant INIT_COOKIE. */ public static final String INIT_COOKIE = "cloud-drive-init-id"; /** The Constant INIT_COOKIE_PATH. */ public static final String INIT_COOKIE_PATH = "/portal/rest/clouddrive/connect"; /** * Init cookie expire time in seconds. */ public static final int INIT_COOKIE_EXPIRE = 300; // 5min /** * Connect cookie expire time in seconds. */ public static final int CONNECT_COOKIE_EXPIRE = 90; // 1.5min /** * Error cookie expire time in seconds. */ public static final int ERROR_COOKIE_EXPIRE = 5; // 5sec /** * Connect process expire time in milliseconds. */ public static final int CONNECT_PROCESS_EXPIRE = 60 * 60 * 1000; // 1hr /** The Constant random. */ protected static final Random random = new Random(); /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(ConnectService.class); /** * Response builder for connect and state. */ class ConnectResponse extends ServiceResponse { /** The service url. */ String serviceUrl; /** The progress. */ int progress; /** The drive. */ DriveInfo drive; /** The error. */ String error; /** The location. */ String location; /** * Service url. * * @param serviceUrl the service url * @return the connect response */ ConnectResponse serviceUrl(String serviceUrl) { this.serviceUrl = serviceUrl; return this; } /** * Progress. * * @param progress the progress * @return the connect response */ ConnectResponse progress(int progress) { this.progress = progress; return this; } /** * Drive. * * @param drive the drive * @return the connect response */ ConnectResponse drive(DriveInfo drive) { this.drive = drive; return this; } /** * Error. * * @param error the error * @return the connect response */ ConnectResponse error(String error) { this.error = error; return this; } /** * Location. * * @param location the location * @return the connect response */ ConnectResponse location(String location) { this.location = location; return this; } /** * Connect error. * * @param error the error * @param connectId the connect id * @param host the host * @return the connect response */ ConnectResponse connectError(String error, String connectId, String host) { if (connectId != null) { cookie(CONNECT_COOKIE, connectId, "/", host, "Cloud Drive connect ID", 0, false); } cookie(ERROR_COOKIE, error, "/", host, "Cloud Drive connection error", ERROR_COOKIE_EXPIRE, false); this.error = error; return this; } /** * Auth error. * * @param message the message * @param host the host * @param providerName the provider name * @param initId the init id * @param baseHost the base host * @return the connect response */ ConnectResponse authError(String message, String host, String providerName, String initId, String baseHost) { if (initId != null) { // need reset previous cookie by expire time = 0 cookie(INIT_COOKIE, initId, INIT_COOKIE_PATH, baseHost, "Cloud Drive init ID", 0, false); } cookie(ERROR_COOKIE, message, "/", host, "Cloud Drive connection error", ERROR_COOKIE_EXPIRE, false); super.entity("<!doctype html><html><head><script type='text/javascript'> setTimeout(function() {window.close();}, 4000);</script></head><body><div id='messageString'>" + (providerName != null ? providerName + " return error: " + message : message) + "</div></body></html>"); return this; } /** * Auth error. * * @param message the message * @param host the host * @return the connect response */ ConnectResponse authError(String message, String host) { return authError(message, host, null, null, null); } /** * Builds the. * * @return the response * @inherritDoc */ @Override Response build() { if (drive != null) { super.entity(new CommandState(drive, error, progress, serviceUrl)); } else if (error != null) { super.entity(new CommandState(error, progress, serviceUrl)); } else if (location != null) { super.addHeader("Location", location); super.entity("<!doctype html><html><head></head><body><div id='redirectLink'>" + "<a href='" + location + "'>Use new location to the service.</a>" + "</div></body></html>"); } // else - what was set in entity() return super.build(); } } /** * Connect initialization record used during establishment of connect * workflow. */ class ConnectInit { /** The local user. */ final String localUser; /** The provider. */ final CloudProvider provider; /** The host. */ final String host; /** * Instantiates a new connect init. * * @param localUser the local user * @param provider the provider * @param host the host */ ConnectInit(String localUser, CloudProvider provider, String host) { this.localUser = localUser; this.provider = provider; this.host = host; } } /** * Connect process record used in connect workflow. Also used to answer on * state request. */ class ConnectProcess implements CloudDriveListener { /** The drive. */ final CloudDrive drive; /** The process. */ final Command process; /** The title. */ final String title; /** The workspace name. */ final String workspaceName; /** The lock. */ final Lock lock = new ReentrantLock(); /** The error. */ String error; /** * Instantiates a new connect process. * * @param workspaceName the workspace name * @param drive the drive * @param conversation the conversation * @throws CloudDriveException the cloud drive exception * @throws RepositoryException the repository exception */ ConnectProcess(String workspaceName, CloudDrive drive, ConversationState conversation) throws CloudDriveException, RepositoryException { this.drive = drive; this.title = drive.getTitle(); this.workspaceName = workspaceName; this.drive.addListener(this); // listen to remove from active map this.process = drive.connect(); LOG.info(title + " connect started."); } /** * Rollback. * * @throws RepositoryException the repository exception */ void rollback() throws RepositoryException { SessionProvider provider = sessionProviders.getSessionProvider(null); Session session = provider.getSession(workspaceName, jcrService.getCurrentRepository()); try { session.getItem(drive.getPath()).remove(); session.save(); } catch (PathNotFoundException e) { // not found - ok } catch (DriveRemovedException e) { // removed - ok } finally { session.logout(); } } /** * {@inheritDoc} */ @Override public void onError(CloudDriveEvent event, Throwable error, String operationName) { lock.lock(); // remove from active here (added in 1.8.0, Aug 19, 2019) active.values().remove(this); // unregister listener drive.removeListener(this); this.error = drive.getUser().getProvider().getErrorMessage(error); // XXX Aug 24: special logic for NPE if (this.error == null && error instanceof NullPointerException) { this.error = "null"; } try { rollback(); } catch (Throwable e) { LOG.warn("Error removing the drive Node connected with error (" + error.getMessage() + "). " + e.getMessage(), e); } finally { lock.unlock(); // log error here as the connect was executed asynchronously LOG.error(title + " connect failed.", error); } } /** * {@inheritDoc} */ @Override public void onConnect(CloudDriveEvent event) { // remove from active here active.values().remove(this); // unregister listener drive.removeListener(this); LOG.info(title + " successfully connected."); } } /** * The Class Cleaner. */ protected class Cleaner implements Runnable { /** * {@inheritDoc} */ @Override public void run() { final long now = System.currentTimeMillis(); for (Iterator<Map.Entry<UUID, Long>> titer = timeline.entrySet().iterator(); titer.hasNext() && !Thread.currentThread().isInterrupted();) { Map.Entry<UUID, Long> t = titer.next(); if (now >= t.getValue()) { authenticated.remove(t.getKey()); initiated.remove(t.getKey()); titer.remove(); } } for (Iterator<Map.Entry<String, ConnectProcess>> cpiter = active.entrySet().iterator(); cpiter.hasNext() && !Thread.currentThread().isInterrupted();) { ConnectProcess cp = cpiter.next().getValue(); if (cp != null) { long expireTime = cp.process.getStartTime() + CONNECT_PROCESS_EXPIRE; if (now >= expireTime) { cpiter.remove(); } } } if (Thread.currentThread().isInterrupted()) { LOG.warn("Connections cleaner was interrupted"); } } } /** The cloud drives. */ protected final CloudDriveService cloudDrives; /** The locator. */ protected final DriveServiceLocator locator; /** The session providers. */ protected final SessionProviderService sessionProviders; /** The jcr service. */ protected final RepositoryService jcrService; /** The finder. */ protected final NodeFinder finder; /** The authenticated. */ protected final Map<UUID, CloudUser> authenticated = new ConcurrentHashMap<UUID, CloudUser>(); /** The initiated. */ protected final Map<UUID, ConnectInit> initiated = new ConcurrentHashMap<UUID, ConnectInit>(); /** The timeline. */ protected final Map<UUID, Long> timeline = new ConcurrentHashMap<UUID, Long>(); /** * Connections in progress. */ protected final Map<String, ConnectProcess> active = new ConcurrentHashMap<String, ConnectProcess>(); /** The connects cleaner. */ protected final ScheduledExecutorService connectsCleaner; /** * REST cloudDrives uses {@link CloudDriveService} for actual job. * * @param cloudDrives the cloud drives * @param locator the locator * @param jcrService the jcr service * @param sessionProviders the session providers * @param finder the finder */ public ConnectService(CloudDriveService cloudDrives, DriveServiceLocator locator, RepositoryService jcrService, SessionProviderService sessionProviders, NodeFinder finder) { this.cloudDrives = cloudDrives; this.locator = locator; this.jcrService = jcrService; this.sessionProviders = sessionProviders; this.finder = finder; this.connectsCleaner = Executors.newScheduledThreadPool(1); this.connectsCleaner.schedule(new Cleaner(), CONNECT_COOKIE_EXPIRE, TimeUnit.SECONDS); } /** * Start connection of user's Cloud Drive to local JCR node. * * @param uriInfo - request info * @param workspace - workspace for cloud drive node * @param path - path to user's node to what connect the drive * @param jsessionsId the jsessions id * @param jsessionsIdSSO the jsessions id SSO * @param connectId the connect id * @return {@link Response} */ @POST @RolesAllowed("users") public Response connectStart(@Context UriInfo uriInfo, @FormParam("workspace") String workspace, @FormParam("path") String path, @CookieParam("JSESSIONID") Cookie jsessionsId, @CookieParam("JSESSIONIDSSO") Cookie jsessionsIdSSO, @CookieParam(CONNECT_COOKIE) Cookie connectId) { ConnectResponse resp = new ConnectResponse(); String host = locator.getServiceHost(uriInfo.getRequestUri().getHost()); if (connectId != null) { UUID cid = UUID.fromString(connectId.getValue()); CloudUser user = authenticated.remove(cid); timeline.remove(cid); Node userNode = null; Node driveNode = null; if (user != null) { if (workspace != null) { if (path != null) { Session userSession = null; try { ConversationState convo = ConversationState.getCurrent(); if (convo == null) { LOG.error("Error connect drive for user " + user.getEmail() + ". User identity not set: ConversationState.getCurrent() is null"); return resp.connectError("User identity not set.", cid.toString(), host) .status(Status.INTERNAL_SERVER_ERROR) .build(); } SessionProvider sp = sessionProviders.getSessionProvider(null); userSession = sp.getSession(workspace, jcrService.getCurrentRepository()); Item item = finder.findItem(userSession, path); if (item.isNode()) { userNode = (Node) item; String name; // search drive by found node to take in account symlinks! CloudDrive existing = cloudDrives.findDrive(userNode); if (existing != null) { // drive already exists - it's re-connect to update access // keys driveNode = (Node) userSession.getItem(existing.getPath()); userNode = driveNode.getParent(); name = driveNode.getName(); } else { name = JCRLocalCloudDrive.cleanName(user.createDriveTitle()); } String processId = processId(workspace, userNode.getPath(), name); // rest it by expire = 0 resp.cookie(CONNECT_COOKIE, cid.toString(), "/", host, "Cloud Drive connect ID", 0, false); ConnectProcess connect = active.get(processId); if (connect == null || connect.error != null) { // initiate connect process if it is not already active or a // previous had an exception if (driveNode == null) { try { driveNode = userNode.getNode(name); } catch (PathNotFoundException pnte) { // node not found - add it try { driveNode = userNode.addNode(name, JCRLocalCloudDrive.NT_FOLDER); userNode.save(); } catch (RepositoryException e) { rollback(userNode, null); LOG.error("Error creating node for the drive of user " + user.getEmail() + ". Cannot create node under " + path, e); return resp.connectError("Error creating node for the drive: storage error.", cid.toString(), host) .status(Status.INTERNAL_SERVER_ERROR) .build(); } } } // state check url resp.serviceUrl(uriInfo.getRequestUriBuilder() .queryParam("workspace", workspace) .queryParam("path", driveNode.getPath()) .build(new Object[0]) .toASCIIString()); try { CloudDrive local = cloudDrives.createDrive(user, driveNode); if (local.isConnected()) { // exists and already connected resp.status(Status.CREATED); // OK vs CREATED? DriveInfo drive = DriveInfo.create(workspace, local); resp.drive(drive); LOG.info(drive.getTitle() + " already connected."); } else { // a new or exist but not connected - connect it connect = new ConnectProcess(workspace, local, convo); active.put(processId, connect); resp.status(connect.process.isDone() ? Status.CREATED : Status.ACCEPTED); resp.progress(connect.process.getProgress()); DriveInfo drive = DriveInfo.create(workspace, local, connect.process.getFiles(), connect.process.getMessages()); resp.drive(drive); } } catch (CannotConnectDriveException e) { LOG.warn(e.getMessage(), e); resp.connectError(e.getMessage(), cid.toString(), host).status(Status.CONFLICT); } catch (UserAlreadyConnectedException e) { LOG.warn(e.getMessage(), e); resp.connectError(e.getMessage(), cid.toString(), host).status(Status.CONFLICT); } catch (CloudDriveException e) { rollback(userNode, driveNode); LOG.error("Error connecting drive for user " + user + ", " + workspace + ":" + path, e); resp.connectError("Error connecting drive. " + e.getMessage(), cid.toString(), host) .status(Status.INTERNAL_SERVER_ERROR); } } else { // else, such connect already in progress (probably was // started by another request) // client can warn the user or try use check url to get that // work status String message = "Connect to " + connect.title + " already posted and currently in progress."; LOG.warn(message); try { // do response with that process lock as done in state() connect.lock.lock(); // state check url resp.serviceUrl(uriInfo.getRequestUriBuilder() .queryParam("workspace", workspace) .queryParam("path", connect.drive.getPath()) .build(new Object[0]) .toASCIIString()); resp.progress(connect.process.getProgress()); resp.drive(DriveInfo.create(workspace, connect.drive)); resp.connectError(message, cid.toString(), host).status(Status.CONFLICT); } finally { connect.lock.unlock(); } } } else { LOG.warn("Item " + workspace + ":" + path + " not a node."); resp.connectError("Not a node.", cid.toString(), host).status(Status.PRECONDITION_FAILED); } } catch (LoginException e) { LOG.warn("Error login to connect drive " + workspace + ":" + path + ". " + e.getMessage()); resp.connectError("Authentication error.", cid.toString(), host).status(Status.UNAUTHORIZED); } catch (RepositoryException e) { LOG.error("Error connecting drive for user " + user + ", node " + workspace + ":" + path, e); rollback(userNode, driveNode); resp.connectError("Error connecting drive: storage error.", cid.toString(), host) .status(Status.INTERNAL_SERVER_ERROR); } catch (Throwable e) { LOG.error("Error connecting drive for user " + user + ", node " + workspace + ":" + path, e); rollback(userNode, driveNode); resp.connectError("Error connecting drive: runtime error.", cid.toString(), host) .status(Status.INTERNAL_SERVER_ERROR); } finally { if (userSession != null) { userSession.logout(); } } } else { return Response.status(Status.BAD_REQUEST).entity("Null path.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null workspace.").build(); } } else { LOG.warn("User not authenticated for connectId " + connectId); resp.connectError("User not authenticated.", cid.toString(), host).status(Status.BAD_REQUEST); } } else { LOG.warn("Connect ID not set"); resp.error("Connection not initiated properly.").status(Status.BAD_REQUEST); } return resp.build(); } /** * Return drive connect status. * * @param uriInfo the uri info * @param workspace the workspace * @param path the path * @return {@link Response} */ @GET @RolesAllowed("users") public Response connectState(@Context UriInfo uriInfo, @QueryParam("workspace") String workspace, @QueryParam("path") String path) { ConnectResponse resp = new ConnectResponse(); resp.serviceUrl(uriInfo.getRequestUri().toASCIIString()); String processId = processId(workspace, path); try { ConnectProcess connect = active.get(processId); if (connect != null) { // connect in progress or recently finished int progress = connect.process.getProgress(); resp.progress(progress); // lock to prevent async process to remove the drive (on its fail) while // doing state response connect.lock.lock(); try { if (connect.error != null) { // KO:error during the connect resp.error(connect.error).status(Status.INTERNAL_SERVER_ERROR); } else { // OK:connected or accepted (in progress) // don't send files each time but on done only if (connect.process.isDone()) { DriveInfo drive = DriveInfo.create(workspace, connect.drive, connect.process.getFiles(), connect.process.getMessages()); resp.drive(drive); resp.status(Status.CREATED); } else { DriveInfo drive = DriveInfo.create(workspace, connect.drive); resp.drive(drive); resp.status(Status.ACCEPTED); } } } catch (RepositoryException e) { LOG.warn("Error reading drive " + processId + ". " + e.getMessage(), e); // KO:read error resp.error("Error reading drive: storage error.").status(Status.INTERNAL_SERVER_ERROR); } catch (DriveRemovedException e) { LOG.warn("Drive removed " + processId, e); // KO:removed resp.error("Drive removed '" + connect.title + "'.").status(Status.BAD_REQUEST); } finally { connect.lock.unlock(); } } else { // logic for those who will ask the service to check if drive connected try { CloudDrive drive = cloudDrives.findDrive(workspace, path); if (drive != null) { // return OK: connected resp.progress(Command.COMPLETE).drive(DriveInfo.create(workspace, drive)).ok(); } else { // return OK: drive not found, disconnected or belong to another // user LOG.warn("Item " + workspace + ":" + path + " not a cloud file or drive not connected."); resp.status(Status.NO_CONTENT); } } catch (DriveRemovedException e) { LOG.warn("Drive removed " + processId, e); // KO:removed resp.error("Drive removed.").status(Status.BAD_REQUEST); } catch (PathNotFoundException e) { LOG.warn("Node not found " + processId, e); // KO:not found resp.error("Node not found.").status(Status.NOT_FOUND); } catch (RepositoryException e) { LOG.error("Error reading connected drive '" + processId + "'", e); // KO:storage error resp.error("Error reading connected drive: storage error.").status(Status.INTERNAL_SERVER_ERROR); } } } catch (Throwable e) { LOG.error("Error getting state of drive '" + processId + "'. ", e); resp.error("Error getting state of drive.").status(Status.INTERNAL_SERVER_ERROR); } return resp.build(); } /** * Returns connecting cloud user page. It's an empty page with attributes on * the body for client-side code handling the connect procedure. Some * providers use this service url as callback after authorization (Google * Drive). <br> * This method is GET because of possibility of redirect on it. * * @param uriInfo - request info * @param providerId - provider id, see more in {@link CloudProvider} * @param code - authentication key (OAuth2 code for example) * @param state the state * @param error - error from the provider * @param errorDescription the error description * @param jsessionsId the jsessions id * @param jsessionsIdSSO the jsessions id SSO * @param initId - init cookie * @return response with connecting page or error */ @GET @Path("/{providerid}/") @Produces(MediaType.TEXT_HTML) public Response userAuth(@Context UriInfo uriInfo, @PathParam("providerid") String providerId, @QueryParam("code") String code, @QueryParam("state") String state, @QueryParam("error") String error, @QueryParam("error_description") String errorDescription, @QueryParam("hostName") String hostName, @CookieParam("JSESSIONID") Cookie jsessionsId, @CookieParam("JSESSIONIDSSO") Cookie jsessionsIdSSO, @CookieParam(INIT_COOKIE) Cookie initId) { // LOG.info("JSESSIONID: " + jsessionsId); // LOG.info("JSESSIONIDSSO: " + jsessionsIdSSO); // LOG.info(INIT_COOKIE + ": " + initId); ConnectResponse resp = new ConnectResponse(); URI requestURI = uriInfo.getRequestUri(); StringBuilder serverHostBuilder = new StringBuilder(); serverHostBuilder.append(requestURI.getScheme()); serverHostBuilder.append("://"); if (hostName != null && hostName.length() > 0) { serverHostBuilder.append(hostName); } else { serverHostBuilder.append(requestURI.getHost()); int serverPort = requestURI.getPort(); if (serverPort >= 0 && serverPort != 80 && serverPort != 443) { serverHostBuilder.append(':'); serverHostBuilder.append(serverPort); } } String serverURL = serverHostBuilder.toString(); // TODO implement CSRF handing in state parameter String requestHost = uriInfo.getRequestUri().getHost(); if (state != null) { // state contains repoName set by the provider if (locator.isRedirect(requestHost)) { // need redirect to actual service URL resp.location(locator.getServiceLink(state, uriInfo.getRequestUri().toString())); return resp.status(Status.MOVED_PERMANENTLY).build(); // redirect } } String baseHost = locator.getServiceHost(requestHost); if (initId != null) { try { UUID iid = UUID.fromString(initId.getValue()); ConnectInit connect = initiated.remove(iid); timeline.remove(iid); if (connect != null) { CloudProvider provider = connect.provider; if (provider.getId().equals(providerId)) { // TODO handle auth errors by provider code if (error == null) { // it's the same as initiated request if (code != null) { try { Map<String, String> params = new HashMap<String, String>(); params.put(CloudDriveConnector.OAUTH2_CODE, code); params.put(CloudDriveConnector.OAUTH2_STATE, state); params.put(CloudDriveConnector.OAUTH2_SERVER_URL, serverURL); CloudUser user = cloudDrives.authenticate(provider, params); UUID connectId = generateId(user.getEmail() + code); authenticated.put(connectId, user); timeline.put(connectId, System.currentTimeMillis() + (CONNECT_COOKIE_EXPIRE * 1000) + 5000); // This cookie will be set on host of initial request (i.e. on // host of calling app) resp.cookie(CONNECT_COOKIE, connectId.toString(), "/", connect.host, "Cloud Drive connect ID", CONNECT_COOKIE_EXPIRE, false); // reset it by expire time = 0 resp.cookie(INIT_COOKIE, iid.toString(), INIT_COOKIE_PATH, baseHost, "Cloud Drive init ID", 0, false); resp.entity("<!doctype html><html><head><script type='text/javascript'> window.close();</script></head><body><div id='messageString'>Connecting to " + user.getServiceName() + "</div></body></html>"); return resp.ok().build(); } catch (CloudDriveException e) { LOG.warn("Error authenticating user to access " + provider.getName(), e); return resp.authError("Authentication error on " + provider.getName(), connect.host, provider.getName(), iid.toString(), baseHost) // TODO UNAUTHORIZED ? .status(Status.BAD_REQUEST) .build(); } } else { LOG.warn("Code required for " + provider.getName()); return resp.authError("Code required for " + provider.getName(), connect.host, provider.getName(), iid.toString(), baseHost) .status(Status.BAD_REQUEST) .build(); } } else { // we have an error from provider LOG.warn(provider.getName() + " error: " + error + ". error_description: " + errorDescription); StringBuilder errorMsg = new StringBuilder(); errorMsg.append(provider.getErrorMessage(error, errorDescription)); return resp.authError(errorMsg.toString(), connect.host, provider.getName(), iid.toString(), baseHost) .status(Status.BAD_REQUEST) .build(); } } else { LOG.error("Authentication was not initiated for " + providerId + " but request to " + provider.getId() + " recorded with id " + initId); return resp.authError("Authentication not initiated to " + provider.getName(), connect.host, provider.getName(), iid.toString(), baseHost) .status(Status.INTERNAL_SERVER_ERROR) .build(); } } else { LOG.warn("Authentication not initiated for " + providerId + " and id " + initId); return resp.authError("Authentication request expired. Try again later.", baseHost, null, iid.toString(), baseHost) .status(Status.BAD_REQUEST) .build(); } } catch (Throwable e) { LOG.error("Error initializing drive provider by id " + providerId, e); return resp.authError("Error initializing drive provider", baseHost).status(Status.INTERNAL_SERVER_ERROR).build(); } } else { LOG.warn("Authentication id not set for provider id " + providerId + " and key " + code); return resp.authError("Authentication not initiated or expired. Try again later.", baseHost) .status(Status.BAD_REQUEST) .build(); } } /** * Initiates connection to cloud drive. Used to get a Provider and remember a * user connect request in the service. It will be used later for * authentication. * * @param uriInfo - request with base URI * @param providerId - provider name see more in {@link CloudProvider} * @param jsessionsId the jsessions id * @param jsessionsIdSSO the jsessions id SSO * @return response with */ @GET @Path("/init/{providerid}/") @RolesAllowed("users") public Response userInit(@Context UriInfo uriInfo, @PathParam("providerid") String providerId, @CookieParam("JSESSIONID") Cookie jsessionsId, @CookieParam("JSESSIONIDSSO") Cookie jsessionsIdSSO) { // LOG.info("JSESSIONID: " + jsessionsId); // LOG.info("JSESSIONIDSSO: " + jsessionsIdSSO); ConnectResponse resp = new ConnectResponse(); try { CloudProvider provider = cloudDrives.getProvider(providerId); ConversationState convo = ConversationState.getCurrent(); if (convo != null) { String localUser = convo.getIdentity().getUserId(); String host = locator.getServiceHost(uriInfo.getRequestUri().getHost()); UUID initId = generateId(localUser); initiated.put(initId, new ConnectInit(localUser, provider, host)); timeline.put(initId, System.currentTimeMillis() + (INIT_COOKIE_EXPIRE * 1000) + 5000); resp.cookie(INIT_COOKIE, initId.toString(), INIT_COOKIE_PATH, host, "Cloud Drive init ID", INIT_COOKIE_EXPIRE, false); return resp.entity(provider).ok().build(); } else { LOG.warn("ConversationState not set to initialize connect to " + provider.getName()); return resp.error("User not authenticated to connect " + provider.getName()).status(Status.UNAUTHORIZED).build(); } } catch (ProviderNotAvailableException e) { LOG.warn("Provider not found for id '" + providerId + "'", e); return resp.error("Provider not found.").status(Status.BAD_REQUEST).build(); } catch (Throwable e) { LOG.error("Error initializing user request for drive provider " + providerId, e); return resp.error("Error initializing user request.").status(Status.INTERNAL_SERVER_ERROR).build(); } } /** * Generate id. * * @param name the name * @return the uuid */ protected UUID generateId(String name) { StringBuilder s = new StringBuilder(); s.append(name); s.append(System.currentTimeMillis()); s.append(String.valueOf(random.nextLong())); return UUID.nameUUIDFromBytes(s.toString().getBytes()); } /** * Process id. * * @param workspace the workspace * @param parentPath the parent path * @param driveName the drive name * @return the string */ protected String processId(String workspace, String parentPath, String driveName) { return workspace + ":" + parentPath + "/" + driveName; } /** * Process id. * * @param workspace the workspace * @param nodePath the node path * @return the string */ protected String processId(String workspace, String nodePath) { return workspace + ":" + nodePath; } /** * Rollback connect changes. * * @param userNode {@link Node} * @param driveNode {@link Node} * @return true if rolledback */ protected boolean rollback(Node userNode, Node driveNode) { try { if (userNode != null) { if (driveNode != null) { driveNode.remove(); userNode.save(); } userNode.refresh(false); return true; } } catch (Throwable e) { LOG.warn("Error rolling back the user node: " + e.getMessage(), e); } return false; } }
40,735
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FeaturesService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/clouddrives/FeaturesService.java
/* * Copyright (C) 2003-2016 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.ecm.connector.clouddrives; import javax.annotation.security.RolesAllowed; import javax.jcr.LoginException; import javax.jcr.RepositoryException; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.exoplatform.services.rest.http.PATCH; import org.exoplatform.commons.api.settings.SettingService; import org.exoplatform.commons.api.settings.SettingValue; import org.exoplatform.commons.api.settings.data.Scope; import org.exoplatform.services.cms.clouddrives.CannotCreateDriveException; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.clouddrives.CloudProvider; import org.exoplatform.services.cms.clouddrives.ProviderNotAvailableException; import org.exoplatform.services.cms.clouddrives.features.CloudDriveFeatures; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.security.ConversationState; /** * REST service providing discovery of Cloud Drive features.<br> * Created by The eXo Platform SAS * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: FeaturesService.java 00000 Jan 31, 2014 pnedonosko $ */ @Path("/clouddrive/features") @Produces(MediaType.APPLICATION_JSON) public class FeaturesService implements ResourceContainer { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(FeaturesService.class); /** The features. */ protected final CloudDriveFeatures features; /** The cloud drives. */ protected final CloudDriveService cloudDrives; /** The jcr service. */ protected final RepositoryService jcrService; /** The session providers. */ protected final SessionProviderService sessionProviders; /** The setting service. */ private SettingService settingService; /** The cloud drive setting context. */ private static final org.exoplatform.commons.api.settings.data.Context CLOUD_DRIVE_CONTEXT = org.exoplatform.commons.api.settings.data.Context.GLOBAL.id("CLOUD_DRIVE"); /** The cloud drive setting scope. */ private static final Scope CLOUD_DRIVE_SCOPE = Scope.GLOBAL.id("CLOUD_DRIVE"); /** The cloud drive setting. */ private static final String IS_CLOUD_DRIVE_ENABLED = "isCloudDriveEnabled"; /** * Instantiates a new features service. * * @param cloudDrives the cloud drives * @param features the features * @param jcrService the jcr service * @param sessionProviders the session providers */ public FeaturesService(CloudDriveService cloudDrives, CloudDriveFeatures features, RepositoryService jcrService, SessionProviderService sessionProviders, SettingService settingService) { this.cloudDrives = cloudDrives; this.features = features; this.jcrService = jcrService; this.sessionProviders = sessionProviders; this.settingService = settingService; } /** * Can create drive. * * @param uriInfo the uri info * @param workspace the workspace * @param path the path * @param providerId the provider id * @return the response */ @GET @Path("/can-create-drive/") @RolesAllowed("users") public Response canCreateDrive(@Context UriInfo uriInfo, @QueryParam("workspace") String workspace, @QueryParam("path") String path, @QueryParam("provider") String providerId) { if (workspace != null) { if (path != null) { CloudProvider provider; if (providerId != null && providerId.length() > 0) { try { provider = cloudDrives.getProvider(providerId); } catch (ProviderNotAvailableException e) { LOG.warn("Unknown provider: " + providerId); return Response.status(Status.BAD_REQUEST).entity("Unknown provider.").build(); } } else { provider = null; } ConversationState currentConvo = ConversationState.getCurrent(); try { boolean result = features.canCreateDrive(workspace, path, currentConvo != null ? currentConvo.getIdentity().getUserId() : null, provider); return Response.ok().entity("{\"result\":\"" + result + "\"}").build(); } catch (CannotCreateDriveException e) { return Response.ok().entity("{\"result\":\"false\", \"message\":\"" + e.getMessage() + "\"}").build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null path.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null workspace.").build(); } } /** * Checks if is autosync enabled. * * @param uriInfo the uri info * @param workspace the workspace * @param path the path * @return the response */ @GET @Path("/is-autosync-enabled/") @RolesAllowed("users") public Response isAutosyncEnabled(@Context UriInfo uriInfo, @QueryParam("workspace") String workspace, @QueryParam("path") String path) { if (workspace != null) { if (path != null) { try { CloudDrive local = cloudDrives.findDrive(workspace, path); if (local != null) { boolean result = features.isAutosyncEnabled(local); return Response.ok().entity("{\"result\":\"" + result + "\"}").build(); } else { LOG.warn("Item " + workspace + ":" + path + " not a cloud file or drive not connected."); return Response.status(Status.NO_CONTENT).build(); } } catch (LoginException e) { LOG.warn("Error login to read drive " + workspace + ":" + path + ". " + e.getMessage()); return Response.status(Status.UNAUTHORIZED).entity("Authentication error.").build(); } catch (RepositoryException e) { LOG.error("Error getting autosync status of a drive " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error reading drive: storage error.").build(); } catch (Throwable e) { LOG.error("Error getting autosync status of a drive " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error reading drive: runtime error.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null path.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null workspace.").build(); } } /** * Checks if cloud drive is enabled. * * @param uriInfo the uri info * @return the response */ @GET @Path("/status/enabled") @RolesAllowed("users") public Response isCloudDriveEnabled(@Context UriInfo uriInfo) { SettingValue<?> isCloudDriveEnabled = settingService.get(CLOUD_DRIVE_CONTEXT, CLOUD_DRIVE_SCOPE, IS_CLOUD_DRIVE_ENABLED); boolean enabled = isCloudDriveEnabled != null ? Boolean.valueOf(isCloudDriveEnabled.getValue().toString()) : true; return Response.ok().entity("{\"result\":\"" + enabled + "\"}").build(); } /** * Enable/disable cloud Drive status. * * @param uriInfo the uri info * @return the response */ @PATCH @Path("/status/enabled") @RolesAllowed("administrators") public Response setCloudDriveStatus(@Context UriInfo uriInfo) { SettingValue<?> isCloudDriveEnabled = settingService.get(CLOUD_DRIVE_CONTEXT, CLOUD_DRIVE_SCOPE, IS_CLOUD_DRIVE_ENABLED); settingService.set(CLOUD_DRIVE_CONTEXT, CLOUD_DRIVE_SCOPE, IS_CLOUD_DRIVE_ENABLED, SettingValue.create(isCloudDriveEnabled != null ? !Boolean.valueOf(isCloudDriveEnabled.getValue().toString()) : false)); return Response.ok().entity("{\"result\":\"" + !(Boolean) isCloudDriveEnabled.getValue() + "\"}").build(); } }
9,341
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ContentService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/clouddrives/ContentService.java
/* * Copyright (C) 2003-2016 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.ecm.connector.clouddrives; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.annotation.security.RolesAllowed; import javax.jcr.LoginException; import javax.jcr.RepositoryException; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import org.exoplatform.container.PortalContainer; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveException; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.clouddrives.CloudDriveStorage; import org.exoplatform.services.cms.clouddrives.NotFoundException; import org.exoplatform.services.cms.clouddrives.features.CloudDriveFeatures; import org.exoplatform.services.cms.clouddrives.utils.ExtendedMimeTypeResolver; import org.exoplatform.services.cms.clouddrives.viewer.ContentReader; import org.exoplatform.services.cms.clouddrives.viewer.DocumentNotFoundException; import org.exoplatform.services.cms.clouddrives.viewer.ViewerStorage; import org.exoplatform.services.cms.clouddrives.viewer.ViewerStorage.ContentFile; import org.exoplatform.services.cms.clouddrives.viewer.ViewerStorage.PDFFile; import org.exoplatform.services.cms.clouddrives.viewer.ViewerStorage.PDFFile.ImageFile; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; /** * RESTful service to access file content in Cloud Drive operations.<br> */ @Path("/clouddrive/content") public class ContentService implements ResourceContainer { /** The Constant LOG. */ protected static final Log LOG = ExoLogger.getLogger(ContentService.class); /** * REST service URL path. */ public static String SERVICE_PATH; static { Path restPath = ContentService.class.getAnnotation(Path.class); SERVICE_PATH = restPath.value(); } /** The features. */ protected final CloudDriveFeatures features; /** The cloud drives. */ protected final CloudDriveService cloudDrives; /** The viewer storage. */ protected final ViewerStorage viewerStorage; /** The jcr service. */ protected final RepositoryService jcrService; /** The session providers. */ protected final SessionProviderService sessionProviders; /** * Constructor. * * @param cloudDrives the cloud drives * @param features the features * @param viewerStorage the viewer storage * @param jcrService the jcr service * @param sessionProviders the session providers */ public ContentService(CloudDriveService cloudDrives, CloudDriveFeatures features, ViewerStorage viewerStorage, RepositoryService jcrService, SessionProviderService sessionProviders) { this.cloudDrives = cloudDrives; this.features = features; this.viewerStorage = viewerStorage; this.jcrService = jcrService; this.sessionProviders = sessionProviders; } /** * Create a link to get this file content via eXo REST service as a proxy to * remote drive. It is a path relative to the current server. * * @param workspace {@link String} * @param path {@link String} * @param fileId {@link String} * @return {@link String} * @see #get(String, String, String) */ public static String contentLink(String workspace, String path, String fileId) { StringBuilder linkPath = new StringBuilder(); linkPath.append(PortalContainer.getCurrentPortalContainerName()); linkPath.append('/'); linkPath.append(PortalContainer.getCurrentRestContextName()); linkPath.append(SERVICE_PATH); linkPath.append('/'); linkPath.append(workspace); // path already starts with slash // XXX we want escape + in file names as ECMS does try { String encodedPath = URLEncoder.encode(path, "UTF-8"); encodedPath = encodedPath.replaceAll("%2F", "/"); linkPath.append(encodedPath); } catch (UnsupportedEncodingException e1) { linkPath.append(path); } StringBuilder link = new StringBuilder(); link.append('/'); link.append(linkPath); // add query link.append('?'); link.append("contentId="); link.append(fileId); return link.toString(); } /** * Create a link to get this file representation in PDF form. It is a path * relative to the current server. * * @param contentLink {@link String} * @return {@link String} * @see #get(String, String, String) */ public static String pdfLink(String contentLink) { return contentLink.replace(ContentService.SERVICE_PATH, ContentService.SERVICE_PATH + "/pdf"); } /** * Create a link to get this file representation in PDF pages converted to * images. It is a path relative to the current server. * * @param contentLink {@link String} * @return {@link String} * @see #get(String, String, String) */ public static String pdfPageLink(String contentLink) { return contentLink.replace(ContentService.SERVICE_PATH, ContentService.SERVICE_PATH + "/pdf/page"); } /** * Return file content reading it from cloud side.<br> * * @param workspace the workspace * @param path the path * @param contentId the content id * @return the response */ @GET @Path("/{workspace}/{path:.*}") @RolesAllowed("users") public Response get(@PathParam("workspace") String workspace, @PathParam("path") String path, @QueryParam("contentId") String contentId) { // TODO support for range and if-modified, if-match... in WebDAV fashion, // for browser players etc. if (workspace != null) { if (path != null) { path = normalizePath(path); if (contentId != null) { try { CloudDrive drive = cloudDrives.findDrive(workspace, path); if (drive != null) { ContentReader content = ((CloudDriveStorage) drive).getFileContent(contentId); if (content != null) { ResponseBuilder resp = Response.ok().entity(content.getStream()); long len = content.getLength(); if (len >= 0) { resp.header("Content-Length", len); } resp.type(content.getMimeType()); String typeMode = content.getTypeMode(); if (typeMode != null && typeMode.length() > 0) { resp.header(ExtendedMimeTypeResolver.X_TYPE_MODE, typeMode); } return resp.build(); } } return Response.status(Status.BAD_REQUEST).entity("No cloud file or content not available.").build(); } catch (LoginException e) { LOG.warn("Error login to read cloud file content " + workspace + ":" + path + ": " + e.getMessage()); return Response.status(Status.UNAUTHORIZED).entity("Authentication error.").build(); } catch (NotFoundException e) { LOG.warn("File not found to read its content " + workspace + ":" + path, e); return Response.status(Status.NOT_FOUND).entity("File not found. " + e.getMessage()).build(); } catch (CloudDriveException e) { LOG.warn("Error reading file content " + workspace + ":" + path, e); return Response.status(Status.BAD_REQUEST).entity("Error reading file content. " + e.getMessage()).build(); } catch (RepositoryException e) { LOG.error("Error reading file content " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error reading file content: storage error.").build(); } catch (Throwable e) { LOG.error("Error reading file content " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error reading file content: runtime error.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null fileId.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null path.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null workspace.").build(); } } /** * Return image (PNG) representation of cloud file content (page) reading it * from local PDF storage. File should be previously created in the storage to * be successfully returned by this method, an empty response (204 No Content) * will be returned otherwise.<br> * * @param workspace the workspace * @param path the path * @param contentId the content id * @param strPage the str page * @param strRotation the str rotation * @param strScale the str scale * @return the page image */ @GET @Path("/pdf/page/{workspace}/{path:.*}") @RolesAllowed("users") public Response getPageImage(@PathParam("workspace") String workspace, @PathParam("path") String path, @QueryParam("contentId") String contentId, @DefaultValue("1") @QueryParam("page") String strPage, @DefaultValue("0") @QueryParam("rotation") String strRotation, @DefaultValue("1.0") @QueryParam("scale") String strScale) { if (workspace != null) { if (path != null) { path = normalizePath(path); if (contentId != null) { try { CloudDrive drive = cloudDrives.findDrive(workspace, path); if (drive != null) { String repository = jcrService.getCurrentRepository().getConfiguration().getName(); ContentFile viewFile = viewerStorage.getFile(repository, workspace, drive, contentId); if (viewFile != null && viewFile.isPDF()) { PDFFile pdfFile = viewFile.asPDF(); // save page capture to file. float scale; try { scale = Float.parseFloat(strScale); // maximum scale support is 300% if (scale > 3.0f) { scale = 3.0f; } } catch (NumberFormatException e) { scale = 1.0f; } float rotation; try { rotation = Float.parseFloat(strRotation); } catch (NumberFormatException e) { rotation = 0.0f; } int maximumOfPage = pdfFile.getNumberOfPages(); int page; try { page = Integer.parseInt(strPage); } catch (NumberFormatException e) { page = 1; } if (page >= maximumOfPage) { page = maximumOfPage; } else if (page < 1) { page = 1; } ImageFile image = pdfFile.getPageImage(page, rotation, scale); return Response.ok(image.getStream(), image.getType()) .header("Last-Modified", pdfFile.getLastModified()) .header("Content-Length", image.getLength()) .header("Content-Disposition", "inline; filename=\"" + image.getName() + "\"") .build(); } else { // PDF representation not available LOG.warn("PDF representation not available for " + workspace + ":" + path + " id:" + contentId); return Response.status(Status.NO_CONTENT).build(); } } return Response.status(Status.BAD_REQUEST).entity("No cloud file or content not available.").build(); } catch (DocumentNotFoundException e) { LOG.error("Error reading cloud file representation " + workspace + ":" + path + ": " + e.getMessage()); return Response.status(Status.NOT_FOUND).entity("Cloud file representation not found.").build(); } catch (LoginException e) { LOG.warn("Error login to read cloud file representation " + workspace + ":" + path + ": " + e.getMessage()); return Response.status(Status.UNAUTHORIZED).entity("Authentication error.").build(); } catch (CloudDriveException e) { LOG.warn("Error reading cloud file representation " + workspace + ":" + path, e); return Response.status(Status.BAD_REQUEST) .entity("Error reading cloud file representation. " + e.getMessage()) .build(); } catch (RepositoryException e) { LOG.error("Error reading cloud file representation " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("Error reading cloud file representation: storage error.") .build(); } catch (Throwable e) { LOG.error("Error reading file content " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("Error reading cloud file representation: runtime error.") .build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null fileId.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null path.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null workspace.").build(); } } /** * Return cloud file representation reading it from local PDF storage. File * should be previously created in the storage to be successfully returned by * this method, an empty response (204 No Content) will be returned * otherwise.<br> * * @param workspace the workspace * @param path the path * @param contentId the content id * @return the pdf */ @GET @Path("/pdf/{workspace}/{path:.*}") @RolesAllowed("users") public Response getPDF(@PathParam("workspace") String workspace, @PathParam("path") String path, @QueryParam("contentId") String contentId) { if (workspace != null) { if (path != null) { path = normalizePath(path); if (contentId != null) { try { CloudDrive drive = cloudDrives.findDrive(workspace, path); if (drive != null) { String repository = jcrService.getCurrentRepository().getConfiguration().getName(); ContentFile viewFile = viewerStorage.getFile(repository, workspace, drive, contentId); if (viewFile != null && viewFile.isPDF()) { String filename = viewFile.getName(); if (!filename.endsWith(".pdf")) { filename = new StringBuilder(filename).append(".pdf").toString(); } ResponseBuilder resp = Response.ok(viewFile.getStream(), viewFile.getMimeType()) .header("Last-Modified", viewFile.getLastModified()) .header("Content-Length", viewFile.getLength()); resp.header("Content-Disposition", "attachment; filename=\"" + filename + "\""); return resp.build(); } else { // PDF representation not available LOG.warn("PDF representation not available for " + workspace + ":" + path + " id:" + contentId); return Response.status(Status.NO_CONTENT).build(); } } return Response.status(Status.BAD_REQUEST).entity("No cloud file or content not available.").build(); } catch (DocumentNotFoundException e) { LOG.error("Error reading cloud file PDF representation " + workspace + ":" + path + ": " + e.getMessage()); return Response.status(Status.NOT_FOUND).entity("Cloud file PDF representation not found.").build(); } catch (LoginException e) { LOG.warn("Error login to read cloud file PDF representation " + workspace + ":" + path + ": " + e.getMessage()); return Response.status(Status.UNAUTHORIZED).entity("Authentication error.").build(); } catch (CloudDriveException e) { LOG.warn("Error reading cloud file PDF representation " + workspace + ":" + path, e); return Response.status(Status.BAD_REQUEST) .entity("Error reading cloud file PDF representation. " + e.getMessage()) .build(); } catch (RepositoryException e) { LOG.error("Error reading cloud file representation " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("Error reading cloud file PDF representation: storage error.") .build(); } catch (Throwable e) { LOG.error("Error reading file content " + workspace + ":" + path, e); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("Error reading cloud file PDF representation: runtime error.") .build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null fileId.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null path.").build(); } } else { return Response.status(Status.BAD_REQUEST).entity("Null workspace.").build(); } } /** * Normalize JCR path (as eXo WebDAV does). * * @param path {@link String} * @return normalized path */ protected String normalizePath(String path) { return path.length() > 0 && path.endsWith("/") ? "/" + path.substring(0, path.length() - 1) : "/" + path; } }
19,255
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
AcceptedCloudFile.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/clouddrives/AcceptedCloudFile.java
/* * Copyright (C) 2003-2018 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.ecm.connector.clouddrives; import java.util.Calendar; import org.exoplatform.services.cms.clouddrives.CloudFile; /** * Not yet cloud file. It is a file that accepted to be a cloud file, but currently is creating (uploading) to the cloud and this * operation not completed.<br> * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: LinkedCloudFile.java 00000 May 26, 2014 pnedonosko $ */ public class AcceptedCloudFile implements CloudFile { /** The path. */ private final String path; // FYI transient fields will not appear in serialized forms like JSON object // on client side /** The created date. */ final transient Calendar createdDate = null; /** The modified date. */ final transient Calendar modifiedDate = null; /** * Instantiates a new accepted cloud file. * * @param path the path */ public AcceptedCloudFile(String path) { this.path = path; } /** * Checks if is symlink. * * @return true, if is symlink */ public boolean isSymlink() { return false; } /** * {@inheritDoc} */ public String getId() { return null; } /** * {@inheritDoc} */ public String getTitle() { return null; } /** * {@inheritDoc} */ public String getLink() { return null; } /** * {@inheritDoc} */ public String getEditLink() { return null; } /** * {@inheritDoc} */ public String getPreviewLink() { return null; } /** * {@inheritDoc} */ public String getThumbnailLink() { return null; } /** * {@inheritDoc} */ public String getType() { return null; } /** * {@inheritDoc} */ public String getTypeMode() { return null; } /** * Gets the last user. * * @return the lastUser */ public String getLastUser() { return null; } /** * {@inheritDoc} */ public String getAuthor() { return null; } /** * {@inheritDoc} */ public Calendar getCreatedDate() { return null; } /** * Gets the modified date. * * @return the modifiedDate */ public Calendar getModifiedDate() { return null; } /** * {@inheritDoc} */ public boolean isFolder() { return false; } /** * {@inheritDoc} */ public String getPath() { return path; } /** * {@inheritDoc} */ @Override public long getSize() { return 0; // zero for accepted } /** * {@inheritDoc} */ @Override public final boolean isConnected() { return false; } }
3,418
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ServiceResponse.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/clouddrives/ServiceResponse.java
/* * Copyright (C) 2003-2016 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.ecm.connector.clouddrives; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; /** * Helper builder for REST responses. Created by The eXo Platform SAS. * * @author <a href="mailto:pnedonosko@exoplatform.com">Peter Nedonosko</a> * @version $Id: ResponseBuilder.java 00000 Jan 8, 2013 pnedonosko $ */ public class ServiceResponse { /** The status. */ Status status; /** The entity. */ Object entity; /** The headers. */ Map<String, String> headers = new HashMap<String, String>(); /** The cookies. */ List<NewCookie> cookies = new ArrayList<NewCookie>(); /** * Status. * * @param status the status * @return the service response */ ServiceResponse status(Status status) { this.status = status; return this; } /** * Ok. * * @return the service response */ ServiceResponse ok() { status = Status.OK; return this; } /** * Client error. * * @param entity the entity * @return the service response */ ServiceResponse clientError(Object entity) { this.status = Status.BAD_REQUEST; this.entity = entity; return this; } /** * Error. * * @param entity the entity * @return the service response */ ServiceResponse error(Object entity) { this.status = Status.INTERNAL_SERVER_ERROR; this.entity = entity; return this; } /** * Entity. * * @param entity the entity * @return the service response */ ServiceResponse entity(Object entity) { this.entity = entity; return this; } /** * Adds the header. * * @param name the name * @param value the value * @return the service response */ ServiceResponse addHeader(String name, String value) { this.headers.put(name, value); return this; } /** * Cookie. * * @param cookie the cookie * @return the service response */ ServiceResponse cookie(NewCookie cookie) { cookies.add(cookie); return this; } /** * Cookie. * * @param name the name * @param value the value * @param path the path * @param domain the domain * @param comment the comment * @param maxAge the max age * @param secure the secure * @return the service response */ ServiceResponse cookie(String name, String value, String path, String domain, String comment, int maxAge, boolean secure) { cookies.add(new NewCookie(name, value, path, domain, comment, maxAge, secure)); return this; } /** * Builds the. * * @return the response */ Response build() { ResponseBuilder builder = Response.status(status != null ? status : Status.OK); if (entity != null) { builder.entity(entity); } if (cookies.size() > 0) { builder.cookie(cookies.toArray(new NewCookie[cookies.size()])); } for (Map.Entry<String, String> he : headers.entrySet()) { builder.header(he.getKey(), he.getValue()); } return builder.build(); } }
4,051
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FCKUtils.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/fckeditor/FCKUtils.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.connector.fckeditor; import java.security.AccessControlException; import javax.jcr.Node; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.xml.PortalContainerInfo; 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.wcm.utils.WCMCoreUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Created by The eXo Platform SAS * @author : Hoa.Pham * hoa.pham@exoplatform.com * Jun 23, 2008 */ public class FCKUtils { /** The Constant LAST_MODIFIED_PROPERTY. */ public static final String LAST_MODIFIED_PROPERTY = "Last-Modified"; /** The Constant IF_MODIFIED_SINCE_DATE_FORMAT. */ public static final String IF_MODIFIED_SINCE_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z"; public static String GET_FOLDERS_AND_FILES="getFoldersAndFiles"; public static String CREATE_FOLDER = "createFolder"; public static String UPLOAD_FILE = "upload"; public static final String EXO_HIDDENABLE = "exo:hiddenable"; public static final String NT_FILE = "nt:file"; public static final String NT_FOLDER = "nt:folder"; public static final String NT_UNSTRUCTURED = "nt:unstructured"; public final static String DOCUMENT_TYPE = "file"; /** The Constant IMAGE_TYPE. */ public final static String IMAGE_TYPE = "image"; public final static String FLASH_TYPE = "flash"; public final static String LINK_TYPE = "link"; /** * Creates the root element for connector response. The full connector response looks like: * {@code * <Connector command="GetFolders" resourceType=""> * <CurrentFolder folderType="" name="" path="" url=""/> * </CurrentFolder> * </Connector> * } * * @param command the command * @param node the node * @param folderType the folder type * @return the org.w3c.dom.Element element * @throws Exception the exception */ public static Element createRootElement(String command, Node node, String folderType) throws Exception { Document doc = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.newDocument(); StringBuffer currentPath = new StringBuffer(node.getPath()); if (!currentPath.toString().endsWith("/")) { currentPath.append("/"); } Element rootElement = doc.createElement("Connector"); doc.appendChild(rootElement); rootElement.setAttribute("command", command); rootElement.setAttribute("resourceType", "Node"); Element currentFolderElement = doc.createElement("CurrentFolder"); currentFolderElement.setAttribute("name", node.getName()); currentFolderElement.setAttribute("folderType", folderType); currentFolderElement.setAttribute("path", currentPath.toString()); currentFolderElement.setAttribute("url", createWebdavURL(node)); rootElement.appendChild(currentFolderElement); return rootElement; } public static boolean hasAddNodePermission(Node node) throws Exception { try { ((ExtendedNode)node).checkPermission(PermissionType.ADD_NODE) ; return true ; } catch (AccessControlException e) { return false ; } } public static String getPortalName() { PortalContainerInfo containerInfo = WCMCoreUtils.getService(PortalContainerInfo.class) ; return containerInfo.getContainerName() ; } public static String createWebdavURL(final Node node) throws Exception { String repository = ((ManageableRepository) node.getSession().getRepository()).getConfiguration().getName(); String workspace = node.getSession().getWorkspace().getName(); String currentPath = node.getPath(); String url = "/" + getPortalName() + "/" + PortalContainer.getCurrentRestContextName() + "/jcr/" + repository + "/" + workspace + currentPath; return url; } }
4,929
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FCKFileHandler.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/fckeditor/FCKFileHandler.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.connector.fckeditor; import java.text.SimpleDateFormat; import javax.jcr.Node; import org.exoplatform.commons.utils.ISO8601; import org.exoplatform.container.ExoContainer; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Created by The eXo Platform SAS. * * @author : Hoa.Pham hoa.pham@exoplatform.com Jun 23, 2008 */ public class FCKFileHandler { private TemplateService templateService; private static final String[] IMAGE_MIMETYPE = {"image/gif", "image/jpeg", "image/bmp", "image/png", "image/tiff"}; /** * Instantiates a new fCK file handler. * * @param container the container */ public FCKFileHandler(ExoContainer container) { templateService = WCMCoreUtils.getService(TemplateService.class); } /** * Gets the file type. * * @param node the node * @param resourceType the resource type * @return the file type * @throws Exception the exception */ public String getFileType(final Node node, final String resourceType) throws Exception { if(FCKUtils.DOCUMENT_TYPE.equalsIgnoreCase(resourceType)) { return getDocumentType(node); }else if(FCKUtils.IMAGE_TYPE.equalsIgnoreCase(resourceType)) { return getImageType(node); }else if(FCKUtils.FLASH_TYPE.equalsIgnoreCase(resourceType)) { return getFlashType(node); }else if(FCKUtils.LINK_TYPE.equalsIgnoreCase(resourceType)) { return getLinkType(node); } return null; } /** * Gets the file url. * * @param file the file * @return the file url * @throws Exception the exception */ protected String getFileURL(final Node file) throws Exception { return FCKUtils.createWebdavURL(file); } /** * Creates the file element for connector response looks like that {@code <File * name="" fileType="" dateCreated="" dateModified="" creator="" size="" * url="" />}. * * @param document the document * @param child the child * @param fileType the file type * @return the org.w3c.dom.Element element * @throws Exception the exception */ public Element createFileElement(Document document, Node child, String fileType) throws Exception { Element file = document.createElement("File"); file.setAttribute("name", child.getName()); SimpleDateFormat formatter = new SimpleDateFormat(ISO8601.SIMPLE_DATETIME_FORMAT); file.setAttribute("dateCreated", formatter.format(child.getProperty("exo:dateCreated").getDate().getTime())); file.setAttribute("dateModified", formatter.format(child.getProperty("exo:dateModified").getDate().getTime())); file.setAttribute("creator", child.getProperty("exo:owner").getString()); file.setAttribute("fileType", fileType); file.setAttribute("url",getFileURL(child)); if(child.isNodeType(FCKUtils.NT_FILE)) { long size = child.getNode("jcr:content").getProperty("jcr:data").getLength(); file.setAttribute("size", "" + size / 1000); }else { file.setAttribute("size", ""); } return file; } /** * Gets the document type. * * @param node the node * @return the document type * @throws Exception the exception */ protected String getDocumentType(final Node node) throws Exception { if (node.isNodeType("exo:presentationable")) return node.getProperty("exo:presentationType").getString(); String primaryType = node.getPrimaryNodeType().getName(); if (templateService.getDocumentTemplates().contains(primaryType)) return primaryType; return null; } /** * Gets the image type. * * @param node the node * @return the image type * @throws Exception the exception */ protected String getImageType(final Node node) throws Exception { if(node.isNodeType("nt:file")) { String mimeType = node.getNode("jcr:content").getProperty("jcr:mimeType").getString(); for(String s:IMAGE_MIMETYPE) { if(s.equals(mimeType)) { return node.getPrimaryNodeType().getName(); } } } return null; } /** * Gets the flash type. * * @param node the node * @return the flash type * @throws Exception the exception */ protected String getFlashType(final Node node) throws Exception { return null; } /** * Gets the link type. * * @param node the node * @return the link type * @throws Exception the exception */ protected String getLinkType(final Node node) throws Exception { return "exo:link"; } }
5,489
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FileUploadHandler.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/fckeditor/FileUploadHandler.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.connector.fckeditor; import java.io.ByteArrayInputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import javax.jcr.Node; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.exoplatform.common.http.HTTPStatus; import org.exoplatform.commons.utils.IOUtil; import org.exoplatform.container.ExoContainer; import org.exoplatform.services.cms.mimetype.DMSMimeTypeResolver; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.upload.UploadResource; import org.exoplatform.upload.UploadService; import jakarta.servlet.http.HttpServletRequest; /* * Created by The eXo Platform SAS * @author : Hoa.Pham * hoa.pham@exoplatform.com * Jun 23, 2008 */ /** * The Class FileUploadHandler. */ public class FileUploadHandler { /** The Constant UPLOAD_ACTION. */ public final static String UPLOAD_ACTION = "upload"; /** The Constant PROGRESS_ACTION. */ public final static String PROGRESS_ACTION = "progress"; /** The Constant ABORT_ACTION. */ public final static String ABORT_ACTION = "abort"; /** The Constant DELETE_ACTION. */ public final static String DELETE_ACTION = "delete"; /** The Constant SAVE_ACTION. */ public final static String SAVE_ACTION = "save"; private UploadService uploadService; private FCKMessage fckMessage; /** * Instantiates a new file upload handler. * * @param container the container */ public FileUploadHandler(ExoContainer container) { uploadService = WCMCoreUtils.getService(UploadService.class); fckMessage = new FCKMessage(); } public Response upload(HttpServletRequest servletRequest) throws Exception { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); uploadService.createUploadResource(servletRequest); return Response.ok(null, new MediaType("text", "xml")).cacheControl(cacheControl).build(); } public Response control(String uploadId, String action) throws Exception { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); DateFormat dateFormat = new SimpleDateFormat(FCKUtils.IF_MODIFIED_SINCE_DATE_FORMAT); if (FileUploadHandler.PROGRESS_ACTION.equals(action)) { Document currentProgress = getProgress(uploadId); return Response.ok(currentProgress, new MediaType("text", "xml")) .cacheControl(cacheControl) .header(FCKUtils.LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } else if (FileUploadHandler.ABORT_ACTION.equals(action)) { uploadService.removeUploadResource(uploadId); return Response.ok(null, new MediaType("text", "xml")) .cacheControl(cacheControl) .header(FCKUtils.LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } else if (FileUploadHandler.DELETE_ACTION.equals(action)) { uploadService.removeUploadResource(uploadId); return Response.ok(null, new MediaType("text", "xml")) .cacheControl(cacheControl) .header(FCKUtils.LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } return Response.status(HTTPStatus.BAD_REQUEST) .cacheControl(cacheControl) .header(FCKUtils.LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } public Response saveAsNTFile(Node parent, String uploadId, String fileName, String language) throws Exception { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); UploadResource resource = uploadService.getUploadResource(uploadId); DateFormat dateFormat = new SimpleDateFormat(FCKUtils.IF_MODIFIED_SINCE_DATE_FORMAT); if (parent == null) { Document fileNotUploaded = fckMessage.createMessage(FCKMessage.FILE_NOT_UPLOADED, FCKMessage.ERROR, language, null); return Response.ok(fileNotUploaded, new MediaType("text", "xml")) .cacheControl(cacheControl) .header(FCKUtils.LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } if (!FCKUtils.hasAddNodePermission(parent)) { Object[] args = { parent.getPath() }; Document message = fckMessage.createMessage(FCKMessage.FILE_UPLOAD_RESTRICTION, FCKMessage.ERROR, language, args); return Response.ok(message, new MediaType("text", "xml")) .cacheControl(cacheControl) .header(FCKUtils.LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } if ((fileName == null) || (fileName.length() == 0)) { fileName = resource.getFileName(); } if (parent.hasNode(fileName)) { Object args[] = { fileName, parent.getPath() }; Document fileExisted = fckMessage.createMessage(FCKMessage.FILE_EXISTED, FCKMessage.ERROR, language, args); return Response.ok(fileExisted, new MediaType("text", "xml")) .cacheControl(cacheControl) .header(FCKUtils.LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } String location = resource.getStoreLocation(); byte[] uploadData = IOUtil.getFileContentAsBytes(location); Node file = parent.addNode(fileName,FCKUtils.NT_FILE); Node jcrContent = file.addNode("jcr:content","nt:resource"); String mimetype = DMSMimeTypeResolver.getInstance().getMimeType(resource.getFileName()); jcrContent.setProperty("jcr:data",new ByteArrayInputStream(uploadData)); jcrContent.setProperty("jcr:lastModified",new GregorianCalendar()); jcrContent.setProperty("jcr:mimeType",mimetype); parent.save(); uploadService.removeUploadResource(uploadId); return Response.ok(null, new MediaType("text", "xml")) .cacheControl(cacheControl) .header(FCKUtils.LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } private Document getProgress(String uploadId) throws Exception { UploadResource resource = uploadService.getUploadResource(uploadId); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); if(resource == null) { return doc; } Double percent = 0.0; if (resource.getStatus() == UploadResource.UPLOADING_STATUS) { percent = (resource.getUploadedSize() * 100) / resource.getEstimatedSize(); } else { percent = 100.0; } Element rootElement = doc.createElement("UploadProgress"); rootElement.setAttribute("uploadId", uploadId); rootElement.setAttribute("fileName", resource.getFileName()); rootElement.setAttribute("percent", percent.intValue() + ""); doc.appendChild(rootElement); return doc; } }
8,636
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FCKMessage.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/fckeditor/FCKMessage.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.connector.fckeditor; import java.text.MessageFormat; import java.util.Locale; import java.util.ResourceBundle; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; /* * Created by The eXo Platform SAS @author : Hoa.Pham hoa.pham@exoplatform.com * Jun 23, 2008 */ /** * The Class FCKMessage. */ public class FCKMessage { /** The Constant ERROR. */ public static final String ERROR = "Error"; /** The Constant INFO. */ public static final String INFO = "Info"; /** The Constant FOLDER_CREATED. */ public static final int FOLDER_CREATED = 100; /** The Constant FOLDER_EXISTED. */ public static final int FOLDER_EXISTED = 101; /** The Constant FOLDER_INVALID_NAME. */ public static final int FOLDER_INVALID_NAME = 102; /** The Constant FOLDER_PERMISSION_CREATING. */ public static final int FOLDER_PERMISSION_CREATING = 103; /** The Constant FOLDER_NOT_CREATED. */ public static final int FOLDER_NOT_CREATED = 104; /** The Constant UNKNOWN_ERROR. */ public static final int UNKNOWN_ERROR = 110; /** The Constant FILE_EXISTED. */ public static final int FILE_EXISTED = 201; /** The Constant FILE_NOT_FOUND. */ public static final int FILE_NOT_FOUND = 202; /** The Constant FILE_UPLOAD_RESTRICTION. */ public static final int FILE_UPLOAD_RESTRICTION = 203; /** The Constant FILE_NOT_UPLOADED. */ public static final int FILE_NOT_UPLOADED = 204; /** The Constant FILE_EXCEED_LIMIT. */ public static final int FILE_EXCEED_LIMIT = 205; /** The Constant FCK_RESOURCE_BUNDLE. */ public static final String FCK_RESOURCE_BUNDLE_FILE = "locale.services.fckeditor.FCKConnector" ; /** * Instantiates a new fCK message. */ public FCKMessage() { } public Document createMessage(int messageCode, String messageType, String language, Object[] args) throws Exception { String message = getMessage(messageCode, args, language); return createMessage(messageCode, message, messageType); } public Document createMessage(int messageCode, String message, String messageType) throws Exception { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("Message"); element.setAttribute("number", Integer.toString(messageCode)); element.setAttribute("text", message); element.setAttribute("type", messageType); document.appendChild(element); return document; } /** * Gets the message. * * @param messageNum the message num * @param args the args * @param language the language * @return the message * @throws Exception the exception */ public String getMessage(int messageNum, Object[] args, String language) throws Exception { String messageKey = getMessageKey(messageNum); return getMessage(messageKey, args, language); } /** * Gets the message. * * @param messageKey the message key * @param args the args * @param language the language * @return the message * @throws Exception the exception */ public String getMessage(String messageKey, Object[] args, String language) throws Exception { Locale locale = null; if (language == null) { locale = Locale.ENGLISH; } else { locale = new Locale(language); } ResourceBundle resourceBundle = ResourceBundle.getBundle(FCK_RESOURCE_BUNDLE_FILE, locale); String message = resourceBundle.getString(messageKey); if (args == null) { return message; } return MessageFormat.format(message, args); } protected String getMessageKey(int number) { String messageKey = null; switch (number) { case FOLDER_CREATED: messageKey = "fckeditor.folder-created"; break; case FOLDER_NOT_CREATED: messageKey = "fckeditor.folder-not-created"; break; case FOLDER_INVALID_NAME: messageKey = "fckeditor.folder-invalid-name"; break; case FOLDER_EXISTED: messageKey = "fckeditor.folder-existed"; break; case FOLDER_PERMISSION_CREATING: messageKey = "fckeditor.folder-permission-denied"; break; case FILE_EXISTED: messageKey = "fckeditor.file-existed"; break; case FILE_NOT_FOUND: messageKey = "fckeditor.file-not-found"; break; case FILE_NOT_UPLOADED: messageKey = "fckeditor.file-not-uploaded"; break; case FILE_UPLOAD_RESTRICTION: messageKey = "fckeditor.file-uploaded-restriction"; break; case FILE_EXCEED_LIMIT: messageKey = "fckeditor.file-exceed-limit"; break; default: messageKey = "connector.fckeditor.unknowm-message"; break; } return messageKey; } }
5,975
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FCKFolderHandler.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/fckeditor/FCKFolderHandler.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.connector.fckeditor; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.jcr.Node; import javax.jcr.nodetype.NodeType; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.exoplatform.container.ExoContainer; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Created by The eXo Platform SAS * * @author : Hoa.Pham hoa.pham@exoplatform.com Jun 23, 2008 */ public class FCKFolderHandler { private TemplateService templateService; private FCKMessage fckMessage; public FCKFolderHandler(ExoContainer container) { templateService = WCMCoreUtils.getService(TemplateService.class); fckMessage = new FCKMessage(); } public String getFolderType(final Node node) throws Exception { // need use a service to get extended folder type for the node NodeType nodeType = node.getPrimaryNodeType(); String primaryType = nodeType.getName(); if (templateService.getDocumentTemplates().contains(primaryType)) return null; if (FCKUtils.NT_UNSTRUCTURED.equals(primaryType) || FCKUtils.NT_FOLDER.equals(primaryType)) return primaryType; if (nodeType.isNodeType(FCKUtils.NT_UNSTRUCTURED) || nodeType.isNodeType(FCKUtils.NT_FOLDER)) { // check if the nodetype is exo:videoFolder... return primaryType; } return primaryType; } public String getFolderURL(final Node folder) throws Exception { return FCKUtils.createWebdavURL(folder); } /** * Creates the folder element for connector response look like {@code <folder name="" * url="" folderType="" />} * * @param document the document * @param child the child * @param folderType the folder type * @return the org.w3c.dom.Element element * @throws Exception the exception */ public Element createFolderElement(Document document, Node child, String folderType) throws Exception { Element folder = document.createElement("Folder"); folder.setAttribute("name", child.getName()); folder.setAttribute("url", getFolderURL(child)); folder.setAttribute("folderType", folderType); return folder; } public Response createNewFolder(Node currentNode, String newFolderName, String language) throws Exception { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); Document document = null; DateFormat dateFormat = new SimpleDateFormat(FCKUtils.IF_MODIFIED_SINCE_DATE_FORMAT); if (currentNode != null) { if (!FCKUtils.hasAddNodePermission(currentNode)) { Object[] args = { currentNode.getPath() }; document = fckMessage.createMessage(FCKMessage.FOLDER_PERMISSION_CREATING, FCKMessage.ERROR, language, args); return Response.ok(document, new MediaType("text", "xml")) .cacheControl(cacheControl) .header(FCKUtils.LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } if (currentNode.hasNode(newFolderName)) { Object[] args = { currentNode.getPath(), newFolderName }; document = fckMessage.createMessage(FCKMessage.FOLDER_EXISTED, FCKMessage.ERROR, language, args); return Response.ok(document, new MediaType("text", "xml")) .cacheControl(cacheControl) .header(FCKUtils.LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } currentNode.addNode(newFolderName, FCKUtils.NT_FOLDER); currentNode.save(); Element rootElement = FCKUtils.createRootElement("createFolder", currentNode, getFolderType(currentNode)); document = rootElement.getOwnerDocument(); Element errorElement = document.createElement("Message"); errorElement.setAttribute("number", Integer.toString(FCKMessage.FOLDER_CREATED)); errorElement.setAttribute("text", fckMessage.getMessage(FCKMessage.FOLDER_CREATED, null, language)); errorElement.setAttribute("type", FCKMessage.ERROR); rootElement.appendChild(errorElement); return Response.ok(document, new MediaType("text", "xml")) .cacheControl(cacheControl) .header(FCKUtils.LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } document = fckMessage.createMessage(FCKMessage.FOLDER_NOT_CREATED, FCKMessage.ERROR, language, null); return Response.ok(document, new MediaType("text", "xml")) .cacheControl(cacheControl) .header(FCKUtils.LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } }
5,742
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ManageDocumentService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/connector/src/main/java/org/exoplatform/ecm/connector/platform/ManageDocumentService.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.connector.platform; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import javax.annotation.security.RolesAllowed; import javax.jcr.AccessDeniedException; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.ws.rs.DefaultValue; 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.core.CacheControl; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.dom.DOMSource; import org.apache.commons.lang3.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.exoplatform.container.xml.InitParams; import org.exoplatform.ecm.connector.fckeditor.FCKUtils; import org.exoplatform.ecm.utils.permission.PermissionUtil; import org.exoplatform.ecm.utils.text.Text; import org.exoplatform.services.cms.clouddrives.CloudDrive; import org.exoplatform.services.cms.clouddrives.CloudDriveException; import org.exoplatform.services.cms.clouddrives.CloudDriveService; import org.exoplatform.services.cms.clouddrives.CloudFile; import org.exoplatform.services.cms.clouddrives.NotYetCloudFileException; import org.exoplatform.services.cms.documents.AutoVersionService; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.drives.impl.ManageDriveServiceImpl; import org.exoplatform.services.cms.impl.Utils; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.context.DocumentContext; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.MembershipEntry; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.wcm.connector.FileUploadHandler; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.servlet.http.HttpServletRequest; /** * This service is used to perform some actions on a folder or on a file, such as creating, * or deleting a folder/file, or uploading a file. * * @LevelAPI Provisional * * @anchor ManageDocumentService */ @Path("/managedocument/") public class ManageDocumentService implements ResourceContainer { /** The Constant IF_MODIFIED_SINCE_DATE_FORMAT. */ protected static final String IF_MODIFIED_SINCE_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z"; /** The Constant LAST_MODIFIED_PROPERTY. */ protected static final String LAST_MODIFIED_PROPERTY = "Last-Modified"; /** The cache control. */ private final CacheControl cc; /** The log. */ private static final Log LOG = ExoLogger.getLogger(ManageDocumentService.class.getName()); /** Default folder name if the original is null */ private static final String DEFAULT_NAME = "untitled"; /** The manage drive service. */ private final ManageDriveService manageDriveService; /** The link manager. */ private final LinkManager linkManager; /** The cloud drives. */ private final CloudDriveService cloudDrives; /** The file upload handler. */ protected FileUploadHandler fileUploadHandler; private enum DriveType { GENERAL, GROUP, PERSONAL } private static final String PRIVATE = "Private"; private static final String NEW_APP = "newApp"; /** The limit size of uploaded file. */ private int limit; /** * Instantiates a document service. * * @param manageDriveService Instantiates a drive manager service. * @param linkManager Instantiates a link manager service. * @param cloudDrives the CloudDrives service * @param params the params */ public ManageDocumentService(ManageDriveService manageDriveService, LinkManager linkManager, CloudDriveService cloudDrives, InitParams params) { this.manageDriveService = manageDriveService; this.linkManager = linkManager; this.cloudDrives = cloudDrives; this.fileUploadHandler = new FileUploadHandler(); this.cc = new CacheControl(); this.cc.setNoCache(true); this.cc.setNoStore(true); this.limit = Integer.parseInt(params.getValueParam("upload.limit.size").getValue()); } /** * Gets all drives by type (General, Group or Personal). * * @param driveType The types of drive (General, Group, or Personal). * @param showPrivate Shows the Private drive or not. The default value is false. * @param showPersonal Shows the Personal drive or not. The default value is false. * @return {@link Document} which contains the drives. * @throws Exception The exception * * @anchor ManageDocumentService.getDrives */ @GET @Path("/getDrives/") @RolesAllowed("users") public Response getDrives(@QueryParam("driveType") String driveType, @DefaultValue("false") @QueryParam("showPrivate") String showPrivate, @DefaultValue("false") @QueryParam("showPersonal") String showPersonal) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); List<String> userRoles = getMemberships(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element rootElement = document.createElement("Folders"); document.appendChild(rootElement); String userId = ConversationState.getCurrent().getIdentity().getUserId(); List<DriveData> driveList = new ArrayList<DriveData>(); if (DriveType.GENERAL.toString().equalsIgnoreCase(driveType)) { driveList = manageDriveService.getMainDrives(userId, userRoles); } else if (DriveType.GROUP.toString().equalsIgnoreCase(driveType)) { driveList = manageDriveService.getGroupDrives(userId, userRoles); } else if (DriveType.PERSONAL.toString().equalsIgnoreCase(driveType)) { driveList = manageDriveService.getPersonalDrives(userId); //remove Private drive String privateDrivePath = ""; for (DriveData driveData : driveList) { if (PRIVATE.equals(driveData.getName())) { privateDrivePath = driveData.getHomePath(); if (!Boolean.valueOf(showPrivate)) { driveList.remove(driveData); break; } } } //remove Personal Documents drive if (!Boolean.valueOf(showPersonal)) { for (DriveData driveData : driveList) { if (privateDrivePath.equals(driveData.getHomePath())) { driveList.remove(driveData); break; } } } } rootElement.appendChild(buildXMLDriveNodes(document, driveList, driveType)); return Response.ok(new DOMSource(document), MediaType.TEXT_XML).cacheControl(cc).build(); } /** * Gets all folders and files which can be viewed by the current user. * * @param driveName The drive name. * @param workspaceName The workspace name. * @param currentFolder The path to the folder to achieve its folders and files. * @param showHidden Shows the hidden items or not. The default value is false. * @return {@link Document} which contains the folders and files. * * @anchor ManageDocumentService.getFoldersAndFiles */ @GET @Path("/getFoldersAndFiles/") @RolesAllowed("users") public Response getFoldersAndFiles(@QueryParam("driveName") String driveName, @QueryParam("workspaceName") String workspaceName, @QueryParam("currentFolder") String currentFolder, @DefaultValue("false") @QueryParam("showHidden") String showHidden) { try { Node node = getNode(driveName, workspaceName, currentFolder); return buildXMLResponseForChildren(node, driveName, currentFolder, Boolean.valueOf(showHidden)); } catch (AccessDeniedException e) { if (LOG.isDebugEnabled()) { LOG.debug("Access is denied when perform get Folders and files: ", e); } return Response.status(Status.UNAUTHORIZED).entity(e.getMessage()).cacheControl(cc).build(); } catch (PathNotFoundException e) { if (LOG.isDebugEnabled()) { LOG.debug("Item is not found: ", e); } return Response.status(Status.NOT_FOUND).entity(e.getMessage()).cacheControl(cc).build(); } catch (RepositoryException e) { if (LOG.isErrorEnabled()) { LOG.error("Repository is error: ", e); } return Response.status(Status.SERVICE_UNAVAILABLE).entity(e.getMessage()).cacheControl(cc).build(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform get Folders and files: ", e); } return Response.serverError().entity(e.getMessage()).cacheControl(cc).build(); } } /** * Deletes a folder/file. * * @param driveName The drive name. * @param workspaceName The workspace name. * @param itemPath The path to the folder/file. * @return {@link Response} Returns the status of an item which has been deleted. * * @anchor ManageDocumentService.deleteFolderOrFile */ @GET @Path("/deleteFolderOrFile/") @RolesAllowed("users") public Response deleteFolderOrFile(@QueryParam("driveName") String driveName, @QueryParam("workspaceName") String workspaceName, @QueryParam("itemPath") String itemPath){ try { Node node = getNode(driveName, workspaceName, itemPath); Node parent = node.getParent(); node.remove(); parent.save(); return Response.ok().cacheControl(cc).build(); } catch (AccessDeniedException e) { if (LOG.isDebugEnabled()) { LOG.debug("Access is denied when perform delete folder or file: ", e); } return Response.status(Status.UNAUTHORIZED).entity(e.getMessage()).cacheControl(cc).build(); } catch (PathNotFoundException e) { if (LOG.isDebugEnabled()) { LOG.debug("Item is not found: ", e); } return Response.status(Status.NOT_FOUND).entity(e.getMessage()).cacheControl(cc).build(); } catch (RepositoryException e) { if (LOG.isErrorEnabled()) { LOG.error("Repository is error: ", e); } return Response.status(Status.SERVICE_UNAVAILABLE).entity(e.getMessage()).cacheControl(cc).build(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform delete Folder or file: ", e); } return Response.serverError().entity(e.getMessage()).cacheControl(cc).build(); } } /** * Creates a new folder and returns its information. * * @param driveName The drive name. * @param workspaceName The workspace name. * @param currentFolder The path to the folder where a child folder is added. * @param folderName The folder name. * @return {@link Document} which contains the created folder. * @anchor ManageDocumentService.createFolder */ @GET @Path("/createFolder/") @RolesAllowed("users") public Response createFolder(@QueryParam("driveName") String driveName, @QueryParam("workspaceName") String workspaceName, @QueryParam("currentFolder") String currentFolder, @QueryParam("folderName") String folderName, @QueryParam("folderNodeType") @DefaultValue("nt:folder") String folderNodeType, @QueryParam("isSystem") @DefaultValue("false") boolean isSystem) { try { Node node = getNode(driveName, workspaceName, currentFolder, isSystem); // The name automatically determined from the title according to the current algorithm. String name = Text.escapeIllegalJcrChars(Utils.cleanName(folderName)); // Set default name if new title contain no valid character name = (StringUtils.isEmpty(name)) ? DEFAULT_NAME : name; if (node.hasNode(name)) { if (LOG.isDebugEnabled()) { LOG.debug("Folder already exists"); } return Response.status(Status.BAD_REQUEST).entity("Folder already exists").cacheControl(cc).build(); } Node newNode = node.addNode(name, folderNodeType); if (!newNode.hasProperty(NodetypeConstant.EXO_TITLE) && newNode.canAddMixin(NodetypeConstant.EXO_RSS_ENABLE)) { newNode.addMixin(NodetypeConstant.EXO_RSS_ENABLE); } newNode.setProperty(NodetypeConstant.EXO_TITLE, folderName); node.save(); Document document = createNewDocument(); String childFolder = StringUtils.isEmpty(currentFolder) ? newNode.getName() : currentFolder.concat("/") .concat(newNode.getName()); Element folderNode = createFolderElement(document, newNode, workspaceName, driveName, childFolder); document.appendChild(folderNode); return getResponse(document); } catch (AccessDeniedException e) { if (LOG.isDebugEnabled()) { LOG.debug("Access is denied when perform create folder: ", e); } return Response.status(Status.UNAUTHORIZED).entity(e.getMessage()).cacheControl(cc).build(); } catch (PathNotFoundException e) { if (LOG.isDebugEnabled()) { LOG.debug("Item is not found: ", e); } return Response.status(Status.NOT_FOUND).entity(e.getMessage()).cacheControl(cc).build(); } catch (RepositoryException e) { if (LOG.isErrorEnabled()) { LOG.error("Repository is error: ", e); } return Response.status(Status.SERVICE_UNAVAILABLE) .entity(e.getMessage()) .cacheControl(cc) .build(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform create folder: ", e); } return Response.serverError().entity(e.getMessage()).cacheControl(cc).build(); } } /** * Uploads a file to the server. * * @param uploadId The Id of the uploaded resource. * @param servletRequest The request. * * @return The response. * * @throws Exception The exception * * @anchor ManageDocumentService.uploadFile */ @POST @Path("/uploadFile/upload/") @RolesAllowed("users") // @InputTransformer(PassthroughInputTransformer.class) // @OutputTransformer(XMLOutputTransformer.class) public Response uploadFile(@Context HttpServletRequest servletRequest, @QueryParam("uploadId") String uploadId) throws Exception { return fileUploadHandler.upload(servletRequest, uploadId, limit); } /** * Returns information about the upload status of a file, such as the upload percentage, the file name, and more. * * @param workspaceName The workspace name. * @param driveName The drive name. * @param currentFolder The path to the current folder. * @param currentPortal The name of the current site. * @param action The action to perform (saving, processing, and more). * @param language The language of the user. * @param fileName The name of the file. * @param uploadId The Id of the uploaded resource. * @return The response. * @throws Exception The exception * * @anchor ManageDocumentService.processUpload */ @GET @Path("/uploadFile/control/") @RolesAllowed("users") public Response processUpload( @QueryParam("workspaceName") String workspaceName, @QueryParam("driveName") String driveName, @QueryParam("currentFolder") String currentFolder, @QueryParam("currentPortal") String currentPortal, @QueryParam("action") String action, @QueryParam("language") String language, @QueryParam("fileName") String fileName, @QueryParam("uploadId") String uploadId, @QueryParam("existenceAction") String existenceAction) throws Exception { try { if ((workspaceName != null) && (driveName != null) && (currentFolder != null)) { Node currentFolderNode = getNode(Text.escapeIllegalJcrChars(driveName), Text.escapeIllegalJcrChars(workspaceName), Text.escapeIllegalJcrChars(currentFolder)); String userId = ConversationState.getCurrent().getIdentity().getUserId(); if (!PermissionUtil.canAddNode(currentFolderNode)){ return Response.status(Status.UNAUTHORIZED).build(); } return createProcessUploadResponse(Text.escapeIllegalJcrChars(workspaceName), currentFolderNode, currentPortal, userId, action, language, fileName, uploadId, existenceAction); } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Error when perform processUpload: ", e); } } DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build(); } private Response buildXMLResponseForChildren(Node node, String driveName, String currentFolder, boolean showHidden) throws Exception { Document document = createNewDocument(); Element rootElement = createFolderElement(document, node, node.getSession().getWorkspace().getName(), driveName, currentFolder); Element folders = document.createElement("Folders"); Element files = document.createElement("Files"); Node referParentNode = node; if (node.isNodeType("exo:symlink") && node.hasProperty("exo:uuid") && node.hasProperty("exo:workspace")) { referParentNode = linkManager.getTarget(node); } for (NodeIterator iterator = referParentNode.getNodes(); iterator.hasNext();) { Node sourceNode = null; Node referNode = null; Node child = iterator.nextNode(); if (child.isNodeType(FCKUtils.EXO_HIDDENABLE) && !showHidden) continue; if (child.isNodeType("exo:symlink") && child.hasProperty("exo:uuid") && child.hasProperty("exo:workspace")) { sourceNode = linkManager.getTarget(child); } referNode = sourceNode != null ? sourceNode : child; String workspaceName = referNode.getSession().getWorkspace().getName(); if (isFolder(referNode)) { // Get current folder from folder path to fix same name problem (ECMS-3586) String folderPath = child.getPath(); folderPath = folderPath.substring(folderPath.lastIndexOf("/") + 1, folderPath.length()); String childFolder = StringUtils.isEmpty(currentFolder) ? folderPath : currentFolder.concat("/").concat(folderPath); Element folder = createFolderElement(document, child, workspaceName, driveName, childFolder); folders.appendChild(folder); } else if (isFile(referNode)) { Element file = createFileElement(document, referNode, child, workspaceName); files.appendChild(file); } else { continue; } } rootElement.appendChild(folders); rootElement.appendChild(files); document.appendChild(rootElement); return getResponse(document); } private boolean isFolder(Node checkNode) throws RepositoryException { return checkNode.isNodeType(NodetypeConstant.NT_FOLDER) || checkNode.isNodeType(NodetypeConstant.NT_UNSTRUCTURED); } private boolean isFile(Node checkNode) throws RepositoryException { return checkNode.isNodeType(NodetypeConstant.NT_FILE); } private Element createFolderElement(Document document, Node node, String workspaceName, String driveName, String currentFolder) throws Exception { Element folder = document.createElement("Folder"); boolean hasChild = false; boolean canRemove = true; boolean canAddChild = true; for (NodeIterator iterator = node.getNodes(); iterator.hasNext();) { if (isFolder(iterator.nextNode())) { hasChild = true; break; } } Session session = getSession(workspaceName); try { session.checkPermission(node.getPath(), PermissionType.REMOVE); } catch (Exception e) { canRemove = false; } try { session.checkPermission(node.getPath(), PermissionType.ADD_NODE); } catch (Exception e) { canAddChild = false; } folder.setAttribute("name", node.getName()); folder.setAttribute("title", Utils.getTitle(node)); folder.setAttribute("path", node.getPath()); folder.setAttribute("canRemove", String.valueOf(canRemove)); folder.setAttribute("canAddChild", String.valueOf(canAddChild)); folder.setAttribute("nodeType", getNodeTypeIcon(node)); folder.setAttribute("workspaceName", workspaceName); folder.setAttribute("driveName", driveName); folder.setAttribute("currentFolder", currentFolder); folder.setAttribute("hasChild", String.valueOf(hasChild)); folder.setAttribute("titlePath", createTitlePath(driveName, workspaceName, currentFolder)); // is folder public (available to any user) boolean isPublic = PermissionUtil.canAnyAccess(node); folder.setAttribute("isPublic", String.valueOf(isPublic)); CloudDrive cloudDrive = cloudDrives.findDrive(node); CloudFile cloudFile = null; if (cloudDrive != null && cloudDrive.isConnected()) { // It's connected Cloud Drive or its sub-folder try { if (cloudDrive.isDrive(node)) { folder.setAttribute("isCloudDrive", Boolean.TRUE.toString()); folder.setAttribute("isConnected", Boolean.TRUE.toString()); folder.setAttribute("cloudProvider", cloudDrive.getUser().getProvider().getId()); } else { cloudFile = cloudDrive.getFile(node.getPath()); if (cloudFile.isConnected()) { if (cloudFile.isFolder()) { folder.setAttribute("isCloudFile", Boolean.TRUE.toString()); folder.setAttribute("isConnected", Boolean.TRUE.toString()); } // otherwise we don't want show them } else { folder.setAttribute("isCloudFile", Boolean.TRUE.toString()); folder.setAttribute("isConnected", Boolean.FALSE.toString()); } } } catch (NotYetCloudFileException e) { folder.setAttribute("isCloudFile", Boolean.TRUE.toString()); folder.setAttribute("isConnected", Boolean.FALSE.toString()); } catch (CloudDriveException e) { LOG.warn("Error reading cloud folder {}: {}", node.getPath(), e.getMessage()); } } if (cloudFile == null) { // It's local storage folder } return folder; } private Element createFileElement(Document document, Node sourceNode, Node displayNode, String workspaceName) throws Exception { Element file = document.createElement("File"); AutoVersionService autoVersionService=WCMCoreUtils.getService(AutoVersionService.class); boolean canRemove = true; String sourcePath = sourceNode.getPath(); file.setAttribute("name", Utils.getTitle(displayNode)); file.setAttribute("title", Utils.getTitle(displayNode)); file.setAttribute("workspaceName", workspaceName); file.setAttribute("id", sourceNode.getUUID()); file.setAttribute("path", displayNode.getPath()); file.setAttribute("isVersioned", String.valueOf(sourceNode.isNodeType(NodetypeConstant.MIX_VERSIONABLE))); file.setAttribute("isVersionSupport", String.valueOf(autoVersionService.isVersionSupport(sourcePath, workspaceName))); if (sourceNode.isNodeType("nt:file")) { Node content = sourceNode.getNode("jcr:content"); file.setAttribute("nodeType", content.getProperty("jcr:mimeType").getString()); } else { file.setAttribute("nodeType", sourceNode.getPrimaryNodeType().getName()); } try { getSession(workspaceName).checkPermission(sourcePath, PermissionType.REMOVE); } catch (Exception e) { canRemove = false; } file.setAttribute("canRemove", String.valueOf(canRemove)); SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // is document public (available to any user) boolean isPublic = PermissionUtil.canAnyAccess(sourceNode); file.setAttribute("isPublic", String.valueOf(isPublic)); CloudDrive cloudDrive = cloudDrives.findDrive(sourceNode); CloudFile cloudFile = null; if (cloudDrive != null && cloudDrive.isConnected() && !cloudDrive.isDrive(sourceNode)) { // It's connected Cloud Drive file try { cloudFile = cloudDrive.getFile(sourceNode.getPath()); if (cloudFile.isConnected()) { if (!cloudFile.isFolder()) { file.setAttribute("isCloudFile", Boolean.TRUE.toString()); file.setAttribute("isConnected", Boolean.TRUE.toString()); file.setAttribute("dateCreated", formatter.format(cloudFile.getCreatedDate().getTime())); file.setAttribute("dateModified", formatter.format(cloudFile.getModifiedDate().getTime())); file.setAttribute("lastModifier", cloudFile.getLastUser()); file.setAttribute("creator", cloudFile.getAuthor()); file.setAttribute("size", String.valueOf(cloudFile.getSize())); } // otherwise we don't want show it } else { file.setAttribute("isCloudFile", Boolean.TRUE.toString()); file.setAttribute("isConnected", Boolean.FALSE.toString()); } } catch (NotYetCloudFileException e) { file.setAttribute("isCloudFile", Boolean.TRUE.toString()); file.setAttribute("isConnected", Boolean.FALSE.toString()); } catch (CloudDriveException e) { LOG.warn("Error reading cloud file {}: {}", sourceNode.getPath(), e.getMessage()); } } if (cloudFile == null) { // It's local storage file file.setAttribute("dateCreated", formatter.format(sourceNode.getProperty("exo:dateCreated").getDate().getTime())); if (sourceNode.hasProperty("exo:dateModified")) { file.setAttribute("dateModified", formatter.format(sourceNode.getProperty("exo:dateModified").getDate().getTime())); } else { file.setAttribute("dateModified", null); } if (sourceNode.hasProperty("exo:lastModifier")) { file.setAttribute("lastModifier", sourceNode.getProperty("exo:lastModifier").getString()); } else { file.setAttribute("lastModifier", null); } file.setAttribute("creator", sourceNode.getProperty("exo:owner").getString()); long size = sourceNode.getNode("jcr:content").getProperty("jcr:data").getLength(); file.setAttribute("size", String.valueOf(size)); } return file; } /** * This function gets or creates the folder where the files will be stored * @param driveName the name of the selected JCR drive * @param workspaceName The name of the JCR workspace * @param currentFolder The folder where the files will be stored * for spaces, the currentFolder will be created directly under the Documents folder of the space. * If the currentFolder param is preceded with 'DRIVE_ROOT_NODE' then currentFolder will be created under the root folder of the space * @return Node object representing the parent folder where the files will be uploaded * @throws Exception */ private Node getNode(String driveName, String workspaceName, String currentFolder) throws Exception { return getNode(driveName, workspaceName, currentFolder, false); } /** * This function gets or creates the folder where the files will be stored * @param driveName the name of the selected JCR drive * @param workspaceName The name of the JCR workspace * @param currentFolder The folder where the files will be stored * for spaces, the currentFolder will be created directly under the Documents folder of the space. * If the currentFolder param is preceded with 'DRIVE_ROOT_NODE' then currentFolder will be created under the root folder of the space * @param isSystem use system session if true * @return Node object representing the parent folder where the files will be uploaded * @throws Exception */ private Node getNode(String driveName, String workspaceName, String currentFolder, boolean isSystem) throws Exception { Session session; if (isSystem) { session = getSystemSession(workspaceName); } else { session = getSession(workspaceName); } DriveData driveData = manageDriveService.getDriveByName(Text.escapeIllegalJcrChars(driveName)); String driveHomePath = driveData.getHomePath(); String userId = ConversationState.getCurrent().getIdentity().getUserId(); String drivePath = Utils.getPersonalDrivePath(driveHomePath, userId); Node node = (Node) session.getItem(Text.escapeIllegalJcrChars(drivePath)); if (StringUtils.isEmpty(currentFolder)) { return node; } // Check if we store the file under Documents folder or under the root folder of the space if(driveName.startsWith(".spaces.") && currentFolder.startsWith("DRIVE_ROOT_NODE")) { String driveRootPath = driveHomePath; if(driveHomePath.contains("/Documents")) { driveRootPath = driveHomePath.substring(0, driveHomePath.indexOf("/Documents")); } // Need system session to create the folder if it does not exist SessionProvider sessionProvider = SessionProvider.createSystemProvider(); Session systemSession = sessionProvider.getSession(workspaceName, getCurrentRepository()); node = (Node) systemSession.getItem(Text.escapeIllegalJcrChars(driveRootPath)); currentFolder = currentFolder.substring("DRIVE_ROOT_NODE/".length()); } List<String> foldersNames = Arrays.stream(currentFolder.split("/")).filter(item -> !item.isEmpty()).toList().stream().toList(); for (String folder : foldersNames) { String cleanFolderName = org.exoplatform.services.jcr.util.Text.escapeIllegalJcrChars(org.exoplatform.services.cms.impl.Utils.cleanString(folder)); if (node.hasNode(folder)) { node = node.getNode(folder); } else if (node.hasNode(cleanFolderName)) { node = node.getNode(cleanFolderName); } else { // create new folder String name = Text.escapeIllegalJcrChars(org.exoplatform.services.cms.impl.Utils.cleanString(folder)); name = (StringUtils.isEmpty(name)) ? DEFAULT_NAME : name; Node newNode = node.addNode(name, NodetypeConstant.NT_FOLDER); if (!newNode.hasProperty(NodetypeConstant.EXO_TITLE)) { newNode.addMixin(NodetypeConstant.EXO_RSS_ENABLE); } newNode.setProperty(NodetypeConstant.EXO_TITLE, org.exoplatform.services.cms.impl.Utils.cleanDocumentTitle(folder)); // Update permissions if (newNode.canAddMixin("exo:privilegeable")) { newNode.addMixin("exo:privilegeable"); } String groupId = driveData.getParameters().get(ManageDriveServiceImpl.DRIVE_PARAMATER_GROUP_ID); if(StringUtils.isNotBlank(groupId) && groupId.startsWith("/spaces/")) { ((ExtendedNode) newNode).setPermission("*:" + groupId, new String[]{PermissionType.READ, PermissionType.ADD_NODE, PermissionType.SET_PROPERTY}); } node.save(); node = newNode; } if (node.isNodeType(NodetypeConstant.EXO_SYMLINK)) { node = linkManager.getTarget(node); } } return node; } private Session getSession(String workspaceName) throws Exception { SessionProvider sessionProvider = WCMCoreUtils.getUserSessionProvider(); ManageableRepository manageableRepository = getCurrentRepository(); return sessionProvider.getSession(workspaceName, manageableRepository); } private Session getSystemSession(String workspaceName) throws Exception { SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); ManageableRepository manageableRepository = getCurrentRepository(); return sessionProvider.getSession(workspaceName, manageableRepository); } private Document createNewDocument() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.newDocument(); } private ManageableRepository getCurrentRepository() throws RepositoryException { RepositoryService repositoryService = WCMCoreUtils.getService(RepositoryService.class); return repositoryService.getCurrentRepository(); } private Response getResponse(Document document) { DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT); return Response.ok(new DOMSource(document), MediaType.TEXT_XML) .cacheControl(cc) .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())) .build(); } /** * Build drive node from drive list. * * @param document the document. * @param drivesList the drives list. * @param driveType the drive type. * * @return the element */ private Element buildXMLDriveNodes(Document document, List<DriveData> drivesList, String driveType) throws Exception { Element folders = document.createElement("Folders"); folders.setAttribute("name", driveType); for (DriveData drive : drivesList) { Element folder = document.createElement("Folder"); folder.setAttribute("name", drive.getName()); folder.setAttribute("nodeType", driveType + " " + drive.getName().replaceAll(" ", "_")); folder.setAttribute("workspaceName", drive.getWorkspace()); folder.setAttribute("canAddChild", drive.getAllowCreateFolders()); folders.appendChild(folder); } return folders; } /** * Gets the memberships. * * @return the memberships * * @throws Exception the exception */ private List<String> getMemberships() throws Exception { List<String> userMemberships = new ArrayList<String>(); String userId = ConversationState.getCurrent().getIdentity().getUserId(); userMemberships.add(userId); Collection<?> memberships = ConversationState.getCurrent().getIdentity().getMemberships(); if (memberships == null || memberships.size() < 0) return userMemberships; Object[] objects = memberships.toArray(); for (int i = 0; i < objects.length; i++) { MembershipEntry membership = (MembershipEntry) objects[i]; String role = membership.getMembershipType() + ":" + membership.getGroup(); userMemberships.add(role); } return userMemberships; } public static String getNodeTypeIcon(Node node) throws RepositoryException { StringBuilder str = new StringBuilder(); if (node == null) return ""; String nodeType = node.getPrimaryNodeType().getName(); if (node.isNodeType(NodetypeConstant.EXO_SYMLINK)) { LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class); try { nodeType = node.getProperty(NodetypeConstant.EXO_PRIMARYTYPE).getString(); node = linkManager.getTarget(node); if (node == null) return ""; } catch (Exception e) { return ""; } } if (node.isNodeType(NodetypeConstant.EXO_TRASH_FOLDER)) { nodeType = NodetypeConstant.EXO_TRASH_FOLDER; } if (node.isNodeType(NodetypeConstant.EXO_FAVOURITE_FOLDER)) nodeType = NodetypeConstant.EXO_FAVOURITE_FOLDER; if (nodeType.equals(NodetypeConstant.NT_UNSTRUCTURED) || nodeType.equals(NodetypeConstant.NT_FOLDER)) { for (String specificFolder : NodetypeConstant.SPECIFIC_FOLDERS) { if (node.isNodeType(specificFolder)) { nodeType = specificFolder; break; } } } str.append(nodeType); return str.toString(); } /** * Creates the process upload response. * * @param workspaceName the workspace name. * @param userId The user Id. * @param action The action. * @param language The language. * @param fileName The file name. * @param uploadId The upload Id. * @param siteName The portal name. * @param currentFolderNode The current folder node. * * @return the response * * @throws Exception the exception */ protected Response createProcessUploadResponse(String workspaceName, Node currentFolderNode, String siteName, String userId, String action, String language, String fileName, String uploadId, String existenceAction) throws Exception { if (FileUploadHandler.SAVE_ACTION.equals(action)) { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); DocumentContext.getCurrent().getAttributes().put(DocumentContext.IS_SKIP_RAISE_ACT, true); return fileUploadHandler.saveAsNTFile(workspaceName, currentFolderNode, uploadId, fileName, language,NEW_APP , siteName, userId, existenceAction); } return fileUploadHandler.control(uploadId, action); } private String createTitlePath(String driveName, String workspaceName, String currentFolder) throws Exception { String[] folders = currentFolder.split("/"); StringBuilder sb = new StringBuilder(); StringBuilder tempFolder = new StringBuilder(); Node parentNode = getNode(driveName, workspaceName, ""); if (StringUtils.isEmpty(currentFolder)) { return ""; } for (int i = 0; i < folders.length; i++) { tempFolder = tempFolder.append(folders[i]); Node node = null; try { node = getNode(driveName, workspaceName, tempFolder.toString()); } catch (PathNotFoundException e) { node = parentNode.getNode(folders[i]); } tempFolder = tempFolder.append("/"); sb.append(Utils.getTitle(node)); if (i != folders.length - 1) { sb.append("/"); } parentNode = (node.isNodeType("exo:symlink")? linkManager.getTarget(node) : node); } return sb.toString(); } @GET @Path("/uploadFile/exist/") @Produces(MediaType.TEXT_XML) @RolesAllowed("users") @Operation( summary = "check uploaded file existence", description = "check uploaded file existence", method = "GET") @ApiResponses(value = { @ApiResponse(responseCode = "204", description = "Request fulfilled"), @ApiResponse(responseCode = "400", description = "Invalid query input"), @ApiResponse(responseCode = "500", description = "Internal server error"), }) public Response checkFileExistence(@Parameter(description = "workspace name") @QueryParam("workspaceName") String workspaceName, @Parameter(description = "drive name name") @QueryParam("driveName") String driveName, @Parameter(description = "current folder name") @QueryParam("currentFolder") String currentFolder, @Parameter(description = "uploaded fil name") @QueryParam("fileName") String fileName) throws Exception { if (workspaceName == null) { return Response.status(Response.Status.BAD_REQUEST).entity("workspace name is mandatory").build(); } if (driveName == null) { return Response.status(Response.Status.BAD_REQUEST).entity("drive name is mandatory").build(); } if (currentFolder == null) { return Response.status(Response.Status.BAD_REQUEST).entity("current folder name is mandatory").build(); } if (fileName == null) { return Response.status(Response.Status.BAD_REQUEST).entity("file name is mandatory").build(); } Node node = getNode(driveName,workspaceName, currentFolder); try { return fileUploadHandler.checkExistence(node, Utils.cleanName(fileName.toLowerCase())); } catch (Exception e) { return Response.serverError().entity(e.getMessage()).build(); } } }
42,862
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestSEOService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/seo/TestSEOService.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.services.seo; import java.util.ArrayList; import javax.jcr.Node; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.mop.SiteType; import org.exoplatform.portal.mop.user.UserNode; import org.exoplatform.portal.webui.portal.UIPortal; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.portal.webui.workspace.UIPortalApplication; import org.exoplatform.services.wcm.BaseWCMTestCase; import org.exoplatform.webui.application.WebuiRequestContext; import org.gatein.pc.api.PortletInvoker; import org.mockito.Mockito; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Jun 21, 2011 */ public class TestSEOService extends BaseWCMTestCase{ /** The SEO Service. */ private SEOService seoService; public void setUp() throws Exception { super.setUp(); sessionProvider = sessionProviderService_.getSystemSessionProvider(null); seoService = (SEOService) container.getComponentInstanceOfType(SEOService.class); applySystemSession(); } public void testConstruct() throws Exception{ assertNotNull(seoService); } /** * test store page metadata * @throws Exception */ public void testStorePageMetadata() throws Exception { PageMetadataModel metaModel = new PageMetadataModel(); metaModel.setUri("home"); metaModel.setPageReference("home"); metaModel.setKeywords("test"); metaModel.setRobotsContent("index,follow"); metaModel.setSiteMap(true); metaModel.setDescription("test description"); metaModel.setPriority(0); String portalName = "classic"; WebuiRequestContext context = Mockito.mock(WebuiRequestContext.class); WebuiRequestContext.setCurrentInstance(context); PortalRequestContext ctx = Mockito.mock(PortalRequestContext.class); Mockito.when(Util.getPortalRequestContext()).thenReturn(ctx); UIPortal uiPortal = Mockito.mock(UIPortal.class); UIPortalApplication uiPortalApp = Mockito.mock(UIPortalApplication.class); uiPortalApp.setCurrentSite(uiPortal); Mockito.when(ctx.getUIApplication()).thenReturn(uiPortalApp); Mockito.when(uiPortalApp.getCurrentSite()).thenReturn(uiPortal); UserNode userNode = Mockito.mock(UserNode.class); Mockito.when(uiPortal.getName()).thenReturn(portalName); Mockito.when(uiPortal.getSelectedUserNode()).thenReturn(userNode); Mockito.when(uiPortal.getSiteType()).thenReturn(SiteType.PORTAL); session = sessionProvider.getSession("collaboration", repository); Node rootNode = session.getRootNode(); Node seoNode = rootNode.addNode("SEO"); seoNode.addMixin("mix:referenceable"); session.save(); Mockito.when(userNode.getId()).thenReturn(seoNode.getUUID()); seoService.storeMetadata(metaModel,portalName,false, "en"); PageMetadataModel retrieveModel = seoService.getPageMetadata("home", "en"); assertEquals(retrieveModel.getKeywords(), "test"); } /** * test store content metadata * @throws Exception */ public void testStoreContentMetadata() throws Exception { applyUserSession("john", "gtn", "collaboration"); WebuiRequestContext context = Mockito.mock(WebuiRequestContext.class); WebuiRequestContext.setCurrentInstance(context); PortalRequestContext ctx = Mockito.mock(PortalRequestContext.class); Mockito.when(Util.getPortalRequestContext()).thenReturn(ctx); PageMetadataModel metaModel = new PageMetadataModel(); Node seoNode = session.getRootNode().addNode("parentNode").addNode("childNode"); if(!seoNode.isNodeType("mix:referenceable")) { seoNode.addMixin("mix:referenceable"); } session.save(); metaModel.setUri(seoNode.getUUID()); metaModel.setKeywords("test"); metaModel.setRobotsContent("index,follow"); metaModel.setSiteMap(true); metaModel.setDescription("test description"); metaModel.setPriority(0); seoService.storeMetadata(metaModel,"classic",true, "en"); ArrayList<String> params = new ArrayList<String>(); params.add("/repository/collaboration/parentNode/childNode"); PageMetadataModel retrieveModel = seoService.getContentMetadata(params, "en"); assertEquals(retrieveModel.getKeywords(), "test"); } /** * test remove page metedate */ public void tesRemovePageMetadata() throws Exception{ PageMetadataModel metaModel = new PageMetadataModel(); metaModel.setUri("home"); metaModel.setPageReference("home"); metaModel.setKeywords("test"); metaModel.setRobotsContent("index,follow"); seoService.storeMetadata(metaModel,"classic",false, "en"); assertEquals("test", seoService.getPageMetadata("home", "en").getKeywords()); seoService.removePageMetadata(metaModel, "classic",false, "en"); assertNull(seoService.getPageMetadata("home", "en")); } /** * test remove content metedate */ public void tesRemoveContentMetadata() throws Exception{ PageMetadataModel metaModel = new PageMetadataModel(); metaModel.setUri("home"); metaModel.setKeywords("test"); metaModel.setRobotsContent("index,follow"); seoService.storeMetadata(metaModel,"classic",true, "en"); ArrayList<String> params = new ArrayList<String>(); params.add("home"); assertEquals("test", seoService.getContentMetadata(params, "en").getKeywords()); seoService.removePageMetadata(metaModel, "classic",true, "en"); assertNull(seoService.getPageMetadata("home", "en")); } public void tearDown() throws Exception { super.tearDown(); } }
6,430
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestPDFViewerService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/pdfviewer/TestPDFViewerService.java
package org.exoplatform.services.pdfviewer; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ValueParam; import org.exoplatform.services.cache.CacheService; import org.exoplatform.services.jcr.RepositoryService; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.*; /** * */ @RunWith(MockitoJUnitRunner.class) public class TestPDFViewerService { @Mock private RepositoryService repositoryService; @Mock private CacheService cacheService; @Test public void shouldGetDefaultValuesWhenNoInitParams() throws Exception { InitParams initParams = new InitParams(); PDFViewerService pdfViewerService = new PDFViewerService(repositoryService, cacheService, initParams); assertEquals(PDFViewerService.DEFAULT_MAX_FILE_SIZE, pdfViewerService.getMaxFileSize()); assertEquals(PDFViewerService.DEFAULT_MAX_PAGES, pdfViewerService.getMaxPages()); } @Test public void shouldGetParamValuesWhenValuesAreValidNumbers() throws Exception { InitParams initParams = new InitParams(); ValueParam maxFileSizeValueParam = new ValueParam(); maxFileSizeValueParam.setName(PDFViewerService.MAX_FILE_SIZE_PARAM_NAME); maxFileSizeValueParam.setValue("5"); initParams.addParam(maxFileSizeValueParam); ValueParam maxPagesValueParam = new ValueParam(); maxPagesValueParam.setName(PDFViewerService.MAX_PAGES_PARAM_NAME); maxPagesValueParam.setValue("10"); initParams.addParam(maxPagesValueParam); PDFViewerService pdfViewerService = new PDFViewerService(repositoryService, cacheService, initParams); assertEquals(5 * 1024 * 1024, pdfViewerService.getMaxFileSize()); assertEquals(10, pdfViewerService.getMaxPages()); } @Test public void shouldGetParamValuesWhenValuesAreNotValidNumbers() throws Exception { InitParams initParams = new InitParams(); ValueParam maxFileSizeValueParam = new ValueParam(); maxFileSizeValueParam.setName(PDFViewerService.MAX_FILE_SIZE_PARAM_NAME); maxFileSizeValueParam.setValue("abc"); initParams.addParam(maxFileSizeValueParam); ValueParam maxPagesValueParam = new ValueParam(); maxPagesValueParam.setName(PDFViewerService.MAX_PAGES_PARAM_NAME); maxPagesValueParam.setValue("0.5"); initParams.addParam(maxPagesValueParam); PDFViewerService pdfViewerService = new PDFViewerService(repositoryService, cacheService, initParams); assertEquals(PDFViewerService.DEFAULT_MAX_FILE_SIZE, pdfViewerService.getMaxFileSize()); assertEquals(PDFViewerService.DEFAULT_MAX_PAGES, pdfViewerService.getMaxPages()); } }
2,694
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
BaseWCMTestSuite.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/wcm/BaseWCMTestSuite.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 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; import org.exoplatform.commons.testing.BaseExoContainerTestSuite; import org.exoplatform.commons.testing.ConfigTestCase; import org.exoplatform.services.attachments.service.AttachmentServiceTest; import org.exoplatform.services.cms.clipboard.TestClipboardService; import org.exoplatform.services.cms.documents.TestCustomizeViewService; import org.exoplatform.services.cms.documents.TestDocumentService; import org.exoplatform.services.cms.documents.TestDocumentTypeService; import org.exoplatform.services.cms.documents.impl.DocumentServiceImplTest; import org.exoplatform.services.cms.lock.impl.TestLockService; import org.exoplatform.services.deployment.TestWCMContentInitializerService; import org.exoplatform.services.ecm.dms.cms.TestCmsService; import org.exoplatform.services.ecm.dms.comment.TestCommentService; import org.exoplatform.services.ecm.dms.configuration.TestDMSConfigurationService; import org.exoplatform.services.ecm.dms.documents.TestFavoriteService; import org.exoplatform.services.ecm.dms.documents.TestTrashService; import org.exoplatform.services.ecm.dms.drive.TestDriveService; import org.exoplatform.services.ecm.dms.folksonomy.TestNewFolksonomyService; import org.exoplatform.services.ecm.dms.i18n.TestMultiLanguageService; import org.exoplatform.services.ecm.dms.link.TestLinkManager; import org.exoplatform.services.ecm.dms.metadata.TestMetadataService; import org.exoplatform.services.ecm.dms.queries.TestQueryService; import org.exoplatform.services.ecm.dms.relation.TestRelationsService; import org.exoplatform.services.ecm.dms.scripts.TestScriptService; import org.exoplatform.services.ecm.dms.taxonomy.TestTaxonomyService; import org.exoplatform.services.ecm.dms.template.TestTemplateService; import org.exoplatform.services.ecm.dms.test.LinkUtilsTest; import org.exoplatform.services.ecm.dms.test.TestSymLink; import org.exoplatform.services.ecm.dms.thumbnail.TestThumbnailService; import org.exoplatform.services.ecm.dms.timeline.TestTimelineService; import org.exoplatform.services.ecm.dms.view.TestApplicationTemplateManagerService; import org.exoplatform.services.ecm.dms.view.TestManageViewService; import org.exoplatform.services.ecm.dms.voting.TestVotingService; import org.exoplatform.services.ecm.dms.watchdocument.TestWatchDocumentService; import org.exoplatform.services.pdfviewer.TestPDFViewerService; import org.exoplatform.services.portletcache.TestFragmentCacheService; import org.exoplatform.services.portletcache.TestPortletFutureCache; import org.exoplatform.services.rest.AttachmentsRestServiceTest; import org.exoplatform.services.rest.TestDocumentsAppRedirectService; import org.exoplatform.services.seo.TestSEOService; import org.exoplatform.services.wcm.core.TestWCMConfigurationService; import org.exoplatform.services.wcm.core.TestWCMService; import org.exoplatform.services.wcm.core.TestWebSchemaConfigService; import org.exoplatform.services.wcm.friendly.TestFriendlyService; import org.exoplatform.services.wcm.javascript.TestXJavaScriptService; import org.exoplatform.services.wcm.portal.artifacts.TestCreatePortalArtifactsService; import org.exoplatform.services.wcm.skin.TestXSkinService; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; /** * Created by The eXo Platform SAS * Author : Pham Duy Dong * dongpd@exoplatform.com */ @RunWith(Suite.class) @SuiteClasses({ TestWCMContentInitializerService.class, TestXJavaScriptService.class, TestWCMService.class, TestWebSchemaConfigService.class, /** To be activated later TestLiveLinkManagerService.class, /** END**/ TestWCMConfigurationService.class, TestFriendlyService.class, TestCreatePortalArtifactsService.class, TestXSkinService.class, TestFragmentCacheService.class, TestPortletFutureCache.class, TestDocumentTypeService.class, TestLockService.class, TestTrashService.class, TestFavoriteService.class, TestNewFolksonomyService.class, TestRelationsService.class, TestDriveService.class, TestTimelineService.class, TestMultiLanguageService.class, TestWatchDocumentService.class, TestTemplateService.class, TestScriptService.class, TestVotingService.class, TestCmsService.class, TestManageViewService.class, TestApplicationTemplateManagerService.class, TestCommentService.class, TestMetadataService.class, TestQueryService.class, TestLinkManager.class, TestTaxonomyService.class, LinkUtilsTest.class, TestSymLink.class, TestDMSConfigurationService.class, TestThumbnailService.class, TestSEOService.class, TestClipboardService.class, TestPDFViewerService.class, AttachmentsRestServiceTest.class, TestDocumentsAppRedirectService.class, TestDocumentService.class, TestCustomizeViewService.class, TestXSkinService.class, AttachmentServiceTest.class, DocumentServiceImplTest.class }) @ConfigTestCase(BaseWCMTestCase.class) public class BaseWCMTestSuite extends BaseExoContainerTestSuite { @BeforeClass public static void setUp() throws Exception { initConfiguration(BaseWCMTestSuite.class); beforeSetup(); } @AfterClass public static void tearDown() { afterTearDown(); } }
5,992
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
BaseWCMTestCase.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/wcm/BaseWCMTestCase.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; import java.util.Date; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.exoplatform.component.test.ConfigurationUnit; import org.exoplatform.component.test.ConfiguredBy; import org.exoplatform.component.test.ContainerScope; import org.exoplatform.ecms.test.BaseECMSTestCase; import org.exoplatform.services.jcr.impl.core.NodeImpl; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Jul 14, 2009 */ @ConfiguredBy({ @ConfigurationUnit(scope = ContainerScope.ROOT, path = "conf/configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/portal/configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/standalone/ecms-test-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/exo.social.component.core-configuration.xml"), }) public abstract class BaseWCMTestCase extends BaseECMSTestCase { /** * Check mixins. * * @param mixins the mixins * @param node the node */ protected void checkMixins(String[] mixins, NodeImpl node) { try { String[] nodeMixins = node.getMixinTypeNames(); assertEquals("Mixins count is different", mixins.length, nodeMixins.length); compareMixins(mixins, nodeMixins); } catch (RepositoryException e) { fail("Mixins isn't accessible on the node " + node); } } /** * Compare mixins. * * @param mixins the mixins * @param nodeMixins the node mixins */ protected void compareMixins(String[] mixins, String[] nodeMixins) { nextMixin: for (String mixin : mixins) { for (String nodeMixin : nodeMixins) { if (mixin.equals(nodeMixin)) continue nextMixin; } fail("Mixin '" + mixin + "' isn't accessible"); } } /** * Memory info. * * @return the string */ protected String memoryInfo() { String info = ""; info = "free: " + mb(Runtime.getRuntime().freeMemory()) + "M of " + mb(Runtime.getRuntime().totalMemory()) + "M (max: " + mb(Runtime.getRuntime().maxMemory()) + "M)"; return info; } // bytes to Mbytes /** * Mb. * * @param mem the mem * * @return the string */ protected String mb(long mem) { return String.valueOf(Math.round(mem * 100d / (1024d * 1024d)) / 100d); } /** * Exec time. * * @param from the from * * @return the string */ protected String execTime(long from) { return Math.round(((System.currentTimeMillis() - from) * 100.00d / 60000.00d)) / 100.00d + "min"; } /** * 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 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; } }
7,627
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestXSkinService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/wcm/skin/TestXSkinService.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.skin; import static org.junit.Assert.assertNotEquals; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.Map; import javax.jcr.Node; import javax.jcr.NodeIterator; import org.exoplatform.commons.xml.DocumentSource; import org.exoplatform.component.test.web.ServletContextImpl; import org.exoplatform.component.test.web.WebAppImpl; import org.exoplatform.portal.resource.SkinConfig; import org.exoplatform.portal.resource.SkinService; import org.exoplatform.portal.resource.config.xml.SkinConfigParser; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.wcm.BaseWCMTestCase; import org.exoplatform.services.wcm.core.WCMConfigurationService; import org.exoplatform.services.wcm.portal.LivePortalManagerService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.test.mocks.servlet.MockServletRequest; import org.exoplatform.web.ControllerContext; import org.exoplatform.web.controller.QualifiedName; import org.exoplatform.web.controller.metadata.DescriptorBuilder; import org.exoplatform.web.controller.router.Router; import org.exoplatform.web.controller.router.RouterConfigException; import jakarta.servlet.ServletContext; /** * The Class TestXJavaScriptService. * * Created by The eXo Platform SAS * Author : Ngoc.Tran * ngoc.tran@exoplatform.com * July 21, 2008 */ public class TestXSkinService extends BaseWCMTestCase { private static final String TEST_SKIN_NAME = "TestSkin"; /** The skin service. */ private XSkinService xSkinService; protected ControllerContext controllerCtx; private static ServletContext mockServletContext; protected static MockResourceResolver resResolver; private SkinService skinService; /** The Constant WEB_CONTENT_NODE_NAME. */ private static final String WEB_CONTENT_NODE_NAME = "webContent"; private Node documentNode; private Node sharedCssNode; public void setUp() throws Exception { super.setUp(); applySystemSession(); documentNode = (Node) session.getItem("/sites content/live/classic/documents"); sharedCssNode = (Node) session.getItem("/sites content/live/classic/css"); xSkinService = getService(XSkinService.class); skinService = getService(SkinService.class); skinService.addSkin("", TEST_SKIN_NAME, ""); controllerCtx = getControllerContext(); URL base = TestXSkinService.class.getClassLoader().getResource("mockwebapp"); File f = new File(base.toURI()); mockServletContext = new ServletContextImpl(f, "/mockwebapp", "mockwebapp"); skinService.registerContext(new WebAppImpl(mockServletContext, Thread.currentThread().getContextClassLoader())); resResolver = new MockResourceResolver(); skinService.addResourceResolver(resResolver); URL url = mockServletContext.getResource("/gatein-resources.xml"); SkinConfigParser.processConfigResource(DocumentSource.create(url), skinService, mockServletContext); } /** * Test get active Stylesheet_01. * * When parameter input is null */ public void testGetActiveStylesheet_01() { try { xSkinService.getActiveStylesheet(null); fail(); } catch (Exception e) { assertNotNull(e.getStackTrace()); } } /** * Test get active Stylesheet_02. * * When node input node type is not exo:webcontent. */ public void testGetActiveStylesheet_02() { try { Node nodeInput = documentNode.addNode(WEB_CONTENT_NODE_NAME); session.save(); String cssData = xSkinService.getActiveStylesheet(nodeInput); assertEquals("", cssData); } catch(Exception e) { fail(); } } /** * Test get active Stylesheet_03. * * When node input is exo:webcontent and have some child node but does not content mixin type. */ public void testGetActiveStylesheet_03() { try { Node webContent = documentNode.addNode(WEB_CONTENT_NODE_NAME, "exo:webContent"); webContent.setProperty("exo:title", WEB_CONTENT_NODE_NAME); session.save(); String cssData = xSkinService.getActiveStylesheet(webContent); assertEquals("", cssData); } catch(Exception e) { e.printStackTrace(); fail(); } } /** * Test get active Stylesheet_04. * * Child node have properties normal and value of exo:active is: * - "exo:active": false */ public void testGetActiveStylesheet_04() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node cssNode = webContent.getNode("css").getNode("default.css"); cssNode.setProperty("exo:active", false); session.save(); String cssData = xSkinService.getActiveStylesheet(webContent); assertEquals("", cssData); } catch(Exception e) { fail(); } } /** * Test get active Stylesheet_05. * * Child node have properties normal and value of jcr:mimeType is: * - "jcr:mimeType": text/css */ public void testGetActiveStylesheet_05() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node jsNode = webContent.getNode("css").getNode("default.css"); Node jsContent = jsNode.getNode("jcr:content"); jsContent.setProperty("jcr:mimeType", "text/css"); session.save(); String cssData = xSkinService.getActiveStylesheet(webContent); assertEquals("This is the default.css file.", cssData); } catch(Exception e) { fail(); } } /** * Test get active Stylesheet_06. * * Child node have properties normal and value of jcr:data is "" */ public void testGetActiveStylesheet_06() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, "", null); String cssData = xSkinService.getActiveStylesheet(webContent); assertEquals("", cssData); } catch(Exception e) { fail(); } } /** * Test get active Stylesheet_07. * * In case normal */ public void testGetActiveStylesheet_07() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); String cssData = xSkinService.getActiveStylesheet(webContent); assertEquals("This is the default.css file.", cssData); } catch (Exception e) { fail(); } } /** * Test update portal Skin on modify_01. * When node input is null. */ public void testUpdatePortalSkinOnModify_01() { try { Node portal = findPortalNode(sessionProvider, documentNode); createSharedCssNode(sharedCssNode); xSkinService.updatePortalSkinOnModify(portal, null); } catch(Exception e) { assertNotNull(e.getStackTrace()); } } /** * Test update portal Skin on modify_02. * When Node portal input is null. */ public void testUpdatePortalSkinOnModify_02() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node jsNode = webContent.getNode("css").getNode("default.css"); xSkinService.updatePortalSkinOnModify(null, jsNode); } catch(Exception e) { assertNotNull(e.getStackTrace()); } } /** * Test update portal Skin on modify_03. * When Node input does not cssFile. */ public void testUpdatePortalSkinOnModify_03() { try { Node portal = this.findPortalNode(sessionProvider, documentNode); Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); createSharedCssNode(sharedCssNode); Node jsFolder = webContent.getNode("css"); xSkinService.updatePortalSkinOnModify(portal, jsFolder); } catch(Exception e) { assertNotNull(e.getStackTrace()); } } /** * Test update portal Skin on modify_04. * When node input have jcr:data is "". */ public void testUpdatePortalSkinOnModify_04() { try { Node portal = findPortalNode(sessionProvider, documentNode); Node webcontent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node cssNode = webcontent.getNode("css").getNode("default.css"); createSharedCssNode(sharedCssNode); skinService = getService(SkinService.class); skinService.addSkin(webcontent.getName(), TEST_SKIN_NAME, ""); xSkinService.updatePortalSkinOnModify(portal, cssNode); session.save(); String resource = "/portal/css/jcr/"+XSkinService.createModuleName("classic")+"/" + TEST_SKIN_NAME + "/Stylesheet.css"; String url = newSimpleSkin(resource).createURL(controllerCtx).toString(); resResolver.addResource(resource, "foo"); assertEquals("This is the sharedJsFile.css file.", skinService.getCSS(newControllerContext(getRouter(), url), true)); } catch(Exception e) { fail(); } } /** * Test update portal Skin on modify_05. * When node input have jcr:data is "Test XSkin Service". */ public void testUpdatePortalSkinOnModify_05() { try { Node portal = findPortalNode(sessionProvider, documentNode); Node webcontent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node cssNode = webcontent.getNode("css").getNode("default.css"); createSharedCssNode(sharedCssNode); xSkinService.updatePortalSkinOnModify(portal, cssNode); session.save(); String resource = "/portal/css/jcr/"+XSkinService.createModuleName("classic")+"/" + TEST_SKIN_NAME + "/Stylesheet.css"; String url = newSimpleSkin(resource).createURL(controllerCtx).toString(); resResolver.addResource(resource, "foo"); assertEquals("This is the sharedJsFile.css file.", skinService.getCSS(newControllerContext(getRouter(), url), true)); } catch(Exception e) { fail(); } } /** * Test when updating portal Skin that generates a new URL each update */ public void testUpdatePortalSkinOnModify_06() { try { Node portal = findPortalNode(sessionProvider, documentNode); Node webcontent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node cssNode = webcontent.getNode("css").getNode("default.css"); createSharedCssNode(sharedCssNode); session.save(); SkinConfig skinConfig = skinService.getSkin("repository/" + portal.getName(), TEST_SKIN_NAME); String cssPath = skinConfig.getCSSPath(); // Wait 10 ms to ensure to not have same update time // When machine is very performant (doing two updates in the same // millisecond) Thread.sleep(10); updateSharedCssNode(sharedCssNode); xSkinService.updatePortalSkinOnModify(portal, cssNode); skinConfig = skinService.getSkin("repository/" + portal.getName(), TEST_SKIN_NAME); assertNotEquals(cssPath, skinConfig.getCSSPath()); } catch (Exception e) { fail(); } } /** * Test update portal Skin on remove_01. * When node input is null. */ public void testUpdatePortalSkinOnRemove_01() { try { Node portal = findPortalNode(sessionProvider, documentNode); createSharedCssNode(sharedCssNode); xSkinService.updatePortalSkinOnRemove(portal, null); } catch(Exception e) { assertNotNull(e.getStackTrace()); } } /** * Test update portal Skin on remove_02. * When Node portal input is null. */ public void testUpdatePortalSkinOnRemove_02() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node cssNode = webContent.getNode("css").getNode("default.css"); xSkinService.updatePortalSkinOnRemove(null, cssNode); fail(); } catch(Exception e) { assertNotNull(e.getStackTrace()); } } /** * Test update portal Skin on remove_03. * When Node input does not cssFile. */ public void testUpdatePortalSkinOnRemove_03() { try { Node portal = findPortalNode(sessionProvider, documentNode); Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); createSharedCssNode(sharedCssNode); Node cssFolder = webContent.getNode("css"); xSkinService.updatePortalSkinOnRemove(portal, cssFolder); } catch(Exception e) { assertNotNull(e); } } /** * Test update portal Skin on remove_04. * When node input have jcr:data is "". */ public void testUpdatePortalSkinOnRemove_04() { try { Node portal = findPortalNode(sessionProvider, documentNode); Node webcontent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, "", null); Node cssNode = webcontent.getNode("css").getNode("default.css"); createSharedCssNode(sharedCssNode); skinService = getService(SkinService.class); skinService.removeSkin(XSkinService.createModuleName(portal.getName()), TEST_SKIN_NAME); xSkinService.updatePortalSkinOnRemove(portal, cssNode); session.save(); String resource = "/portal/css/jcr/"+XSkinService.createModuleName("classic")+"/" + TEST_SKIN_NAME + "/Stylesheet.css"; String url = newSimpleSkin(resource).createURL(controllerCtx).toString(); resResolver.addResource(resource, "foo"); assertEquals("This is the sharedJsFile.css file.", skinService.getCSS(newControllerContext(getRouter(), url), true)); } catch(Exception e) { fail(); } } /** * Test update portal Skin on remove_05. * When node input have jcr:data is "Test XSkin Service". */ public void testUpdatePortalSkinOnRemove_05() { try { Node portal = findPortalNode(sessionProvider, documentNode); Node webcontent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, "Test XSkin Service.", null); Node cssNode = webcontent.getNode("css").getNode("default.css"); createSharedCssNode(sharedCssNode); session.save(); skinService = getService(SkinService.class); skinService.invalidateCachedSkin("/portal/css/jcr/"+XSkinService.createModuleName("classic")+"/" + TEST_SKIN_NAME + "/Stylesheet.css"); skinService.addSkin(portal.getName(), TEST_SKIN_NAME, ""); xSkinService.updatePortalSkinOnRemove(portal, cssNode); session.save(); String resource = "/portal/css/jcr/"+XSkinService.createModuleName("classic")+"/" + TEST_SKIN_NAME + "/Stylesheet.css"; String url = newSimpleSkin(resource).createURL(controllerCtx).toString(); resResolver.addResource(resource, "foo"); assertEquals("This is the sharedJsFile.css file.", skinService.getCSS(newControllerContext(getRouter(), url), true)); } catch(Exception e) { fail(); } } /** * Test update portal Skin on remove_07. * When portal node is shared portal. */ public void testUpdatePortalSkinOnRemove_07() { try { WCMConfigurationService configurationService = WCMCoreUtils.getService(WCMConfigurationService.class);; LivePortalManagerService livePortalManagerService = getService(LivePortalManagerService.class); String sharedPortalName = configurationService.getSharedPortalName(); Node portal = livePortalManagerService.getLivePortal(sessionProvider, sharedPortalName); Node sharedNode = (Node) session.getItem("/sites content/live/" + sharedPortalName + "/css"); createSharedCssNode(sharedNode); skinService.invalidateCachedSkin("/portal/css/jcr/" + XSkinService.createModuleName(sharedPortalName) + "/" + TEST_SKIN_NAME + "/Stylesheet.css"); xSkinService.updatePortalSkinOnRemove(portal, null); session.save(); String resource = "/portal/css/jcr/" + XSkinService.createModuleName(sharedPortalName) + "/" + TEST_SKIN_NAME + "/Stylesheet.css"; String url = newSimpleSkin(resource).createURL(controllerCtx).toString(); resResolver.addResource(resource, "foo"); assertEquals("This is the sharedJsFile.css file.", skinService.getCSS(newControllerContext(getRouter(), url), true)); } catch(Exception e) { fail(); } } /** * Test update portal Skin URL on remove. */ public void testUpdatePortalSkinOnRemove_08() { try { WCMConfigurationService configurationService = WCMCoreUtils.getService(WCMConfigurationService.class);; LivePortalManagerService livePortalManagerService = getService(LivePortalManagerService.class); String sharedPortalName = configurationService.getSharedPortalName(); Node portal = livePortalManagerService.getLivePortal(sessionProvider, sharedPortalName); Node sharedNode = (Node) session.getItem("/sites content/live/" + sharedPortalName + "/css"); createSharedCssNode(sharedNode); session.save(); SkinConfig skinConfig = skinService.getPortalSkin("repository/" + sharedPortalName, TEST_SKIN_NAME); String cssPath = skinConfig.getCSSPath(); // Wait 10 ms to ensure to not have same update time // When machine is very performant (doing two updates in the same // millisecond) Thread.sleep(10); xSkinService.updatePortalSkinOnRemove(portal, null); skinConfig = skinService.getPortalSkin("repository/" + sharedPortalName, TEST_SKIN_NAME); assertNotEquals(cssPath, skinConfig.getCSSPath()); } catch(Exception e) { fail(); } } public void testPortalSkins() { try { WCMConfigurationService configurationService = WCMCoreUtils.getService(WCMConfigurationService.class);; LivePortalManagerService livePortalManagerService = getService(LivePortalManagerService.class); String sharedPortalName = configurationService.getSharedPortalName(); Node portal = livePortalManagerService.getLivePortal(sessionProvider, sharedPortalName); SkinService skinService = getService(SkinService.class); Node sharedNode = (Node) session.getItem(portal.getPath() + "/css"); createSharedCssNode(sharedNode); skinService.invalidateCachedSkin("/portal/css/jcr/" + XSkinService.createModuleName(sharedPortalName) + "/" + TEST_SKIN_NAME + "/Stylesheet.css"); session.save(); xSkinService.updatePortalSkinOnModify(portal,sharedNode); Collection<SkinConfig> skins = skinService.getPortalSkins(TEST_SKIN_NAME); assertTrue(skins.size() >= 1); SkinConfig portalSkin = skinService.getPortalSkin("repository/" + sharedPortalName, TEST_SKIN_NAME); String url = portalSkin.createURL(controllerCtx).toString(); resResolver.addResource(url, "foo"); assertEquals("This is the sharedJsFile.css file.", skinService.getCSS(newControllerContext(getRouter(), url), true)); } catch(Exception e) { fail(); } } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ public void tearDown() throws Exception { Node sharedPortalNode = (Node) session.getItem("/sites content/live/shared/css"); NodeIterator nodeIterator = documentNode.getNodes(); NodeIterator cssNodeIterator = sharedCssNode.getNodes(); NodeIterator sharedIterator = sharedPortalNode.getNodes(); while(nodeIterator.hasNext()) { nodeIterator.nextNode().remove(); } while(cssNodeIterator.hasNext()) { cssNodeIterator.nextNode().remove(); } while(sharedIterator.hasNext()) { sharedIterator.nextNode().remove(); } session.save(); } private Node findPortalNode(SessionProvider sessionProvider, Node child) throws Exception{ LivePortalManagerService livePortalManagerService = getService(LivePortalManagerService.class); String portalName = null; for(String portalPath: livePortalManagerService.getLivePortalsPath()) { if(child.getPath().startsWith(portalPath)) { portalName = livePortalManagerService.getPortalNameByPath(portalPath); break; } } if(portalName == null) return null; return livePortalManagerService.getLivePortal(sessionProvider, portalName); } private void createSharedCssNode(Node parentNode) throws Exception { Node cssNode; cssNode = parentNode.addNode("sharedJsFile.css", "nt:file"); if (!cssNode.isNodeType("exo:cssFile")) { cssNode.addMixin("exo:cssFile"); } cssNode.setProperty("exo:active", true); cssNode.setProperty("exo:priority", 2); 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()); String cssData = "This is the sharedJsFile.css file."; cssContent.setProperty("jcr:data", cssData); session.save(); } private void updateSharedCssNode(Node parentNode) throws Exception { Node cssNode = parentNode.getNode("sharedJsFile.css"); Node cssContent = cssNode.getNode("jcr:content"); cssContent.setProperty("jcr:encoding", "UTF-8"); cssContent.setProperty("jcr:mimeType", "text/css"); cssContent.setProperty("jcr:lastModified", new Date().getTime()); String cssData = "This is the sharedJsFile.css file updated."; cssContent.setProperty("jcr:data", cssData); session.save(); } Router getRouter() { Router router; try { router = DescriptorBuilder.router().add( DescriptorBuilder.route("/skins/{gtn:version}/{gtn:resource}{gtn:compress}{gtn:orientation}.css") .with(DescriptorBuilder.routeParam("gtn:handler").withValue("skin")) .with(DescriptorBuilder.pathParam("gtn:version").matchedBy("[^/]*").preservePath()) .with(DescriptorBuilder.pathParam("gtn:orientation").matchedBy("-(lt)|-(rt)|").captureGroup(true)) .with(DescriptorBuilder.pathParam("gtn:compress").matchedBy("-(min)|").captureGroup(true)) .with(DescriptorBuilder.pathParam("gtn:resource").matchedBy(".+?").preservePath())).build(); return router; } catch (RouterConfigException e) { return null; } } public static ControllerContext newControllerContext(Router router, String requestURI) { try { MockServletRequest request = new MockServletRequest(null, new URL("http://localhost" + requestURI), "/portal", null, false); String portalPath = request.getRequestURI().substring(request.getContextPath().length()); // Iterator<Map<QualifiedName, String>> matcher = router.matcher(portalPath, request.getParameterMap()); Map<QualifiedName, String> parameters = null; if (matcher.hasNext()) { parameters = matcher.next(); } return new ControllerContext(null, router, request, null, parameters); } catch (MalformedURLException e) { return null; } } ControllerContext getControllerContext() { try { return newControllerContext(getRouter()); } catch (Exception e) { throw new IllegalArgumentException("The controller context is not initialized properly", e); } } public static ControllerContext newControllerContext(Router router) { return newControllerContext(router, "/portal"); } public SimpleSkin newSimpleSkin(String uri) { return new SimpleSkin(skinService, "module", null, uri); } }
24,328
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
MockResourceResolver.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/wcm/skin/MockResourceResolver.java
/* * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.services.wcm.skin; import java.io.Reader; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import org.exoplatform.portal.resource.ResourceResolver; import org.exoplatform.portal.resource.Resource; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; /** * @author <a href="trongtt@gmail.com">Trong Tran</a> * @version $Revision$ */ class MockResourceResolver implements ResourceResolver { /** . */ private final Log log = ExoLogger.getLogger(MockResourceResolver.class); private Map<String, String> map = new HashMap<String, String>(); public MockResourceResolver() { addResource("/path/to/MockResourceResolver.css", this.getClass().getName()); } public void addResource(String path, String value) { map.put(path, value); } public String removeResource(String path) { return map.remove(path); } @Override public Resource resolve(String path) throws NullPointerException { if (path == null) { throw new NullPointerException("No null path is accepted"); } log.info("path to resolve : " + path); final String css = map.get(path); if (css != null) { return new Resource(path) { @Override public Reader read() { return new StringReader(css); } }; } return null; } public void reset() { map.clear(); } }
2,378
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
SimpleSkin.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/wcm/skin/SimpleSkin.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.skin; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.exoplatform.commons.utils.PropertyManager; import org.exoplatform.portal.resource.SkinConfig; import org.exoplatform.portal.resource.SkinService; import org.exoplatform.portal.resource.SkinURL; import org.exoplatform.services.resources.Orientation; import org.exoplatform.web.ControllerContext; import org.exoplatform.web.WebAppController; import org.exoplatform.web.controller.QualifiedName; import org.exoplatform.web.controller.router.URIWriter; import org.exoplatform.web.url.MimeType; import org.gatein.portal.controller.resource.ResourceRequestHandler; /** * An implementation of the skin config. * * Created by The eXo Platform SAS Jan 19, 2007 */ class SimpleSkin implements SkinConfig { private final SkinService service_; private final String module_; private final String name_; private final String cssPath_; private final String id_; private final int priority; private String type; public SimpleSkin(SkinService service, String module, String name, String cssPath) { this(service, module, name, cssPath, Integer.MAX_VALUE); } public SimpleSkin(SkinService service, String module, String name, String cssPath, int cssPriority) { service_ = service; module_ = module; name_ = name; cssPath_ = cssPath; id_ = module.replace('/', '_'); priority = cssPriority; } public int getCSSPriority() { return priority; } public String getId() { return id_; } public String getModule() { return module_; } public String getCSSPath() { return cssPath_; } public String getName() { return name_; } public String toString() { return "SimpleSkin[id=" + id_ + ",module=" + module_ + ",name=" + name_ + ",cssPath=" + cssPath_ + ", priority=" + priority + "]"; } public SkinURL createURL(final ControllerContext context) { if (context == null) { throw new NullPointerException("No controller context provided"); } return new SkinURL() { Orientation orientation = null; boolean compress = !PropertyManager.isDevelopping(); public void setOrientation(Orientation orientation) { this.orientation = orientation; } @Override public String toString() { try { String resource = cssPath_.substring(1, cssPath_.length() - ".css".length()); // Map<QualifiedName, String> params = new HashMap<QualifiedName, String>(); params.put(ResourceRequestHandler.VERSION_QN, ResourceRequestHandler.VERSION); params.put(ResourceRequestHandler.ORIENTATION_QN, orientation == Orientation.RT ? "rt" : "lt"); params.put(ResourceRequestHandler.COMPRESS_QN, compress ? "min" : ""); params.put(WebAppController.HANDLER_PARAM, "skin"); params.put(ResourceRequestHandler.RESOURCE_QN, resource); StringBuilder url = new StringBuilder(); context.renderURL(params, new URIWriter(url, MimeType.PLAIN)); // return url.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } }; } @Override public String getType() { return type; } @Override public void setType(String type) { this.type = type; } }
4,500
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestFriendlyService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/wcm/friendly/TestFriendlyService.java
package org.exoplatform.services.wcm.friendly; /* * 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/>. */ import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.wcm.friendly.impl.FriendlyServiceImpl; import junit.framework.TestCase; public class TestFriendlyService extends TestCase { private FriendlyServiceImpl fserv; public void setUp() throws Exception { InitParams initParams = new InitParams(); fserv = new FriendlyServiceImpl(initParams); } public void testNotActiveByDefault() { assertFalse(fserv.isEnabled()); } public void testUnfriendlyUriIfNotActive() { fserv.setEnabled(false); String friendlyUri = "news"; String unfriendlyUri = "/public/acme/news?path=/acme"; fserv.addFriendly(friendlyUri, unfriendlyUri); String target = fserv.getUnfriendlyUri(friendlyUri); assertEquals(friendlyUri, target); } public void testFriendlyUriIfNotActive() { fserv.setEnabled(false); String friendlyUri = "news"; String unfriendlyUri = "/public/acme/news?path=/acme"; fserv.addFriendly(friendlyUri, unfriendlyUri); String target = fserv.getFriendlyUri(unfriendlyUri); assertEquals(unfriendlyUri, target); } public void testNoDuplicates() { fserv.setEnabled(true); fserv.addFriendly("acme", "/public/acme/detail?path=/repository/collaboration/sites content/live/acme/web contents"); fserv.addFriendly("news", "/public/acme/news?path=/acme"); fserv.addFriendly("news-detail", "/public/acme/detail?path=/acme"); fserv.addFriendly("events", "/public/acme/events?path=/events"); fserv.addFriendly("files", "/rest-ecmdemo/jcr/repository/collaboration/sites content/live/acme/documents"); assertEquals(5, fserv.getFriendlies().size()); } public void testFriendly() { fserv.setEnabled(true); fserv.setServletName("content"); fserv.addFriendly("acme", "/public/acme/detail?path=/repository/collaboration/sites content/live/acme/web contents"); fserv.addFriendly("news", "/public/acme/news?path=/acme"); fserv.addFriendly("news-detail", "/public/acme/detail?path=/acme"); fserv.addFriendly("events", "/public/acme/events?path=/events"); fserv.addFriendly("files", "/rest-ecmdemo/jcr/repository/collaboration/sites content/live/acme/documents"); // returns friendly assertEquals("http://monsite/ecmdemo/content/acme/News/News1", fserv.getFriendlyUri("http://monsite/ecmdemo/public/acme/detail?path=/repository/collaboration/sites content/live/acme/web contents"+"/News/News1")); assertEquals("http://monsite/ecmdemo/content/news/MyCategory/myContent", fserv.getFriendlyUri("http://monsite/ecmdemo/public/acme/news?path=/acme/MyCategory/myContent")); assertEquals("http://monsite/ecmdemo/content/files/doc1", fserv.getFriendlyUri("http://monsite/ecmdemo/rest-ecmdemo/jcr/repository/collaboration/sites content/live/acme/documents/doc1")); // no friendly assertEquals("http://monsite/ecmdemo/rest-ecmdemo/jcr/repository/collaboration/doc1", fserv.getFriendlyUri("http://monsite/ecmdemo/rest-ecmdemo/jcr/repository/collaboration/doc1")); } public void testUnfriendly() { fserv.setEnabled(true); fserv.setServletName("content"); fserv.addFriendly("acme", "/public/acme/detail?path=/repository/collaboration/sites content/live/acme/web contents"); fserv.addFriendly("news", "/public/acme/news?path=/acme"); fserv.addFriendly("news-detail", "/public/acme/detail?path=/acme"); fserv.addFriendly("events", "/public/acme/events?path=/events"); fserv.addFriendly("files", "/rest-ecmdemo/jcr/repository/collaboration/sites content/live/acme/documents"); // returns unfriendly assertEquals("/ecmdemo/public/acme/detail?path=/repository/collaboration/sites content/live/acme/web contents/News/News1", fserv.getUnfriendlyUri("/ecmdemo/content/acme/News/News1")); // no unfriendly assertEquals("/ecmdemo/content/xxxx/News/News1", fserv.getUnfriendlyUri("/ecmdemo/content/xxxx/News/News1")); } public void testRemoveFriendly() { fserv.setEnabled(true); fserv.setServletName("content"); fserv.addFriendly("acme", "/public/acme/detail?path=/repository/collaboration/sites content/live/acme/web contents"); fserv.addFriendly("news", "/public/acme/news?path=/acme"); fserv.addFriendly("news-detail", "/public/acme/detail?path=/acme"); fserv.addFriendly("events", "/public/acme/events?path=/events"); fserv.addFriendly("files", "/rest-ecmdemo/jcr/repository/collaboration/sites content/live/acme/documents"); // returns friendly assertEquals(5, fserv.getFriendlies().size()); assertEquals("http://monsite/ecmdemo/content/acme/News/News1", fserv.getFriendlyUri("http://monsite/ecmdemo/public/acme/detail?path=/repository/collaboration/sites content/live/acme/web contents"+"/News/News1")); fserv.removeFriendly("acme"); assertEquals(4, fserv.getFriendlies().size()); assertEquals("http://monsite/ecmdemo/public/acme/detail?path=/repository/collaboration/sites content/live/acme/web contents"+"/News/News1", fserv.getFriendlyUri("http://monsite/ecmdemo/public/acme/detail?path=/repository/collaboration/sites content/live/acme/web contents"+"/News/News1")); } public void testPriority() { InitParams initParams = new InitParams(); fserv = new FriendlyServiceImpl(initParams); fserv.setEnabled(true); fserv.setServletName("content"); fserv.addFriendly("acme", "/public/acme/detail?path=/repository/collaboration/sites content/live/acme/web contents"); fserv.addFriendly("collab", "/public/acme/detail?path=/repository/collaboration"); assertEquals("http://monsite/ecmdemo/content/acme/News/News1", fserv.getFriendlyUri("http://monsite/ecmdemo/public/acme/detail?path=/repository/collaboration/sites content/live/acme/web contents/News/News1")); assertEquals("http://monsite/ecmdemo/content/collab/Doc/Doc1", fserv.getFriendlyUri("http://monsite/ecmdemo/public/acme/detail?path=/repository/collaboration/Doc/Doc1")); } }
6,719
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestXJavaScriptService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/wcm/javascript/TestXJavaScriptService.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.javascript; import java.util.Date; import javax.jcr.Node; import javax.jcr.NodeIterator; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.wcm.BaseWCMTestCase; import org.exoplatform.services.wcm.portal.LivePortalManagerService; /** * The Class TestXJavaScriptService. * * Created by The eXo Platform SAS * Author : Ngoc.Tran * ngoc.tran@exoplatform.com * July 15, 2008 */ public class TestXJavaScriptService extends BaseWCMTestCase { /** The javascript service. */ private XJavascriptService javascriptService; /** The Constant WEB_CONTENT_NODE_NAME. */ private static final String WEB_CONTENT_NODE_NAME = "webContent"; private Node documentNode; private Node sharedJsNode; public void setUp() throws Exception { super.setUp(); javascriptService = getService(XJavascriptService.class); applySystemSession(); documentNode = (Node) session.getItem("/sites content/live/classic/documents"); sharedJsNode = (Node) session.getItem("/sites content/live/classic/js"); } /** * Test get active java script_01. * * When parameter input is null */ public void testGetActiveJavaScript_01() { try { javascriptService.getActiveJavaScript(null); } catch (Exception e) { assertNotNull(e.getStackTrace()); } } /** * Test get active java script_02. * * When node input node type is not exo:webcontent. */ public void testGetActiveJavaScript_02() { try { Node nodeInput = documentNode.addNode(WEB_CONTENT_NODE_NAME); session.save(); String jsData = javascriptService.getActiveJavaScript(nodeInput); assertEquals("", jsData); } catch(Exception e) { fail(); } } /** * Test get active java script_03. * * When node input is exo:webcontent and have some child node but does not content mixin type. */ public void testGetActiveJavaScript_03() { try { Node webContent = documentNode.addNode(WEB_CONTENT_NODE_NAME, "exo:webContent"); webContent.setProperty("exo:title", WEB_CONTENT_NODE_NAME); webContent.addNode("jsFolder", "exo:jsFolder"); session.save(); String jsData = javascriptService.getActiveJavaScript(webContent); assertEquals("", jsData); } catch(Exception e) { fail(); } } /** * Test get active java script_04. * * When node input is exo:webcontent and have some child node but have mixin type does not exo:jsFile. */ public void testGetActiveJavaScript_04() { try { Node webContent = documentNode.addNode(WEB_CONTENT_NODE_NAME, "exo:webContent"); webContent.setProperty("exo:title", WEB_CONTENT_NODE_NAME); Node jsFolder = webContent.addNode("jsFolder", "exo:jsFolder"); Node jsNode = jsFolder.addNode("default.js", "nt:file"); jsNode.setProperty("exo:active", false); Node 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()); jsContent.setProperty("jcr:data", "This is the default.js file."); session.save(); String jsData = javascriptService.getActiveJavaScript(webContent); assertEquals("", jsData); } catch(Exception e) { fail(); } } /** * Test get active java script_05. * * Child node have properties normal and value of exo:active is: * - "exo:active": false */ public void testGetActiveJavaScript_05() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node jsNode = webContent.getNode("js").getNode("default.js"); jsNode.setProperty("exo:active", false); session.save(); String jsData = javascriptService.getActiveJavaScript(webContent); assertEquals("", jsData); } catch(Exception e) { fail(); } } /** * Test get active java script_06. * * Child node have properties normal and value of jcr:mimeType is: * - "jcr:mimeType": text/html */ public void testGetActiveJavaScript_06() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node jsNode = webContent.getNode("js").getNode("default.js"); Node jsContent = jsNode.getNode("jcr:content"); jsContent.setProperty("jcr:mimeType", "text/html"); session.save(); String jsData = javascriptService.getActiveJavaScript(webContent); assertEquals("This is the default.js file.", jsData); } catch(Exception e) { fail(); } } /** * Test get active java script_07. * * Child node have properties normal and value of jcr:mimeType is: * - "jcr:mimeType": text/javascript */ public void testGetActiveJavaScript_07() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node jsNode = webContent.getNode("js").getNode("default.js"); Node jsContent = jsNode.getNode("jcr:content"); jsContent.setProperty("jcr:mimeType", "text/javascript"); session.save(); String jsData = javascriptService.getActiveJavaScript(webContent); assertEquals("This is the default.js file.", jsData); } catch(Exception e) { fail(); } } /** * Test get active java script_08. * * Child node have properties normal and value of jcr:mimeType is: * - "jcr:mimeType": application/x-javascript */ public void testGetActiveJavaScript_08() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node jsNode = webContent.getNode("js").getNode("default.js"); Node jsContent = jsNode.getNode("jcr:content"); jsContent.setProperty("jcr:mimeType", "application/x-javascript"); session.save(); String jsData = javascriptService.getActiveJavaScript(webContent); assertEquals("This is the default.js file.", jsData); } catch(Exception e) { fail(); } } /** * Test get active java script_09. * * Child node have properties normal and value of jcr:mimeType is: * - "jcr:mimeType": text/ecmascript */ public void testGetActiveJavaScript_09() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node jsNode = webContent.getNode("js").getNode("default.js"); Node jsContent = jsNode.getNode("jcr:content"); jsContent.setProperty("jcr:mimeType", "text/ecmascript"); session.save(); String jsData = javascriptService.getActiveJavaScript(webContent); assertEquals("This is the default.js file.", jsData); } catch(Exception e) { fail(); } } /** * Test get active java script_10. * * Child node have properties normal and value of jcr:data is "" */ public void testGetActiveJavaScript_10() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node jsNode = webContent.getNode("js").getNode("default.js"); Node jsContent = jsNode.getNode("jcr:content"); jsContent.setProperty("jcr:data", ""); session.save(); String jsData = javascriptService.getActiveJavaScript(webContent); assertEquals("", jsData); } catch(Exception e) { fail(); } } /** * Test get active java script_11. * * Child node have properties normal and value of jcr:data is: * - "jcr:data": This is the default.js file. */ public void testGetActiveJavaScript_11() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); Node jsNode = webContent.getNode("js").getNode("default.js"); Node jsContent = jsNode.getNode("jcr:content"); jsContent.setProperty("jcr:data", "This is the default.js file."); session.save(); String jsData = javascriptService.getActiveJavaScript(webContent); assertEquals("This is the default.js file.", jsData); } catch(Exception e) { fail(); } } /** * Test get active java script_12. * * Child node have properties normal and value of jcr:mimeType is: * - "jcr:data": alert('Test method getActiveJavaScript()');. */ public void testGetActiveJavaScript_12() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, "alert('Test method getActiveJavaScript()');"); session.save(); String jsData = javascriptService.getActiveJavaScript(webContent); assertEquals("alert('Test method getActiveJavaScript()');", jsData); } catch(Exception e) { fail(); } } /** * Test get active java script_13. * * In case normal */ public void testGetActiveJavaScript_13() { try { Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); String jsData = javascriptService.getActiveJavaScript(webContent); assertEquals("This is the default.js file.", jsData); } catch (Exception e) { fail(); } } /** * Test update portal js on modify_01. * When node input is null. */ public void testUpdatePortalJSOnModify_01() { try { Node portalNode = findPortalNode(sessionProvider, documentNode); javascriptService.updatePortalJSOnModify(portalNode, null); session.save(); } catch(Exception e) { fail(); } } /** * Test update portal js on modify_02. * When Node input does not jsFile. */ public void testUpdatePortalJSOnModify_02() { try { Node portalNode = findPortalNode(sessionProvider, documentNode); Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, null); createSharedJsNode(sharedJsNode); Node jsFolder = webContent.getNode("js"); javascriptService.updatePortalJSOnModify(portalNode, jsFolder); } catch(Exception e) { assertNotNull(e.getStackTrace()); } } /** * Test update portal js on modify_03. * When node input have jcr:data is "". */ public void testUpdatePortalJSOnModify_03() { try { Node portalNode = findPortalNode(sessionProvider, documentNode); Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, ""); createSharedJsNode(sharedJsNode); Node jsNode = webContent.getNode("js").getNode("default.js"); javascriptService.updatePortalJSOnModify(portalNode, jsNode); session.save(); } catch(Exception e) { fail(); } } /** * Test update portal js on modify_04. * When node input have jcr:data is "When perform testUpdatePortalJSOnModify...". *//* public void testUpdatePortalJSOnModify_04() { try { JavascriptConfigService configService = null; Node portalNode = findPortalNode(sessionProvider, documentNode); createSharedJsNode(sharedJsNode); Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, "When perform testUpdatePortalJSOnModify..."); Node jsNode = webContent.getNode("js").getNode("default.js"); javascriptService.updatePortalJSOnModify(portalNode, jsNode); session.save(); configService = getService(JavascriptConfigService.class); String jsData = new String(configService.getMergedJavascript()); assertEquals("\nWhen perform testUpdatePortalJSOnModify...", jsData); } catch(Exception e) { fail(); } } *//** * Test update portal js on modify_05. * When node input have jcr:data is "alert('testUpdatePortalJSOnModify...');". *//* public void testUpdatePortalJSOnModify_05() { try { JavascriptConfigService configService = null; Node portalNode = findPortalNode(sessionProvider, documentNode); createSharedJsNode(sharedJsNode); Node js = sharedJsNode.getNode("sharedJsFile.js"); js.setProperty("exo:priority", 2); Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, "alert('testUpdatePortalJSOnModify...');"); Node jsNode = webContent.getNode("js").getNode("default.js"); javascriptService.updatePortalJSOnModify(portalNode, jsNode); session.save(); configService = getService(JavascriptConfigService.class); String jsData = new String(configService.getMergedJavascript()); assertEquals("\nalert('testUpdatePortalJSOnModify...');", jsData); } catch(Exception e) { fail(); } } public void testUpdatePortalJSOnModify_06() { try { JavascriptConfigService configService = null; WCMConfigurationService configurationService = WCMCoreUtils.getService(WCMConfigurationService.class);; LivePortalManagerService livePortalManagerService = getService(LivePortalManagerService.class); String sharedPortalName = configurationService.getSharedPortalName(REPO_NAME); Node portal = livePortalManagerService.getLivePortal(sessionProvider, sharedPortalName); Node sharedNode = (Node) session.getItem("/sites content/live/" + sharedPortalName + "/js"); Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, "alert('testUpdatePortalJSOnModify...');"); Node jsNode = webContent.getNode("js").getNode("default.js"); createSharedJsNode(sharedNode); Node js = sharedNode.getNode("sharedJsFile.js"); js.setProperty("exo:priority", 1); javascriptService.updatePortalJSOnModify(portal, jsNode); session.save(); String jsData = ""; configService = getService(JavascriptConfigService.class); jsData = new String(configService.getMergedJavascript()); assertEquals("\nThis is the default.js file.alert('testUpdatePortalJSOnModify...');", jsData); session.save(); } catch(Exception e) { fail(); } }*/ /** * Test update portal js on remove_01. * When node input is null. */ public void testUpdatePortalJSOnRemove_01() { try { Node portalNode = findPortalNode(sessionProvider, documentNode); createSharedJsNode(sharedJsNode); javascriptService.updatePortalJSOnRemove(portalNode, null); } catch(Exception e) { assertNotNull(e.getStackTrace()); } } /** * Test update portal js on remove_03. * When Node input does not jsFile. */ public void testUpdatePortalJSOnRemove_03() { try { Node portalNode = findPortalNode(sessionProvider, documentNode); createSharedJsNode(sharedJsNode); javascriptService.updatePortalJSOnRemove(portalNode, sharedJsNode); } catch(Exception e) { assertNotNull(e); } } /** * Test update portal js on remove_04. * When node input have jcr:data is "". *//* public void testUpdatePortalJSOnRemove_04() { try { JavascriptConfigService configService = null; Node portalNode = findPortalNode(sessionProvider, documentNode); createSharedJsNode(sharedJsNode); Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, ""); Node jsNode = webContent.getNode("js").getNode("default.js"); configService = getService(JavascriptConfigService.class); String jsData = ""; javascriptService.updatePortalJSOnRemove(portalNode, jsNode); session.save(); jsData = new String(configService.getMergedJavascript()); assertEquals("\nThis is the default.js file.", jsData); } catch(Exception e) { fail(); } } *//** * Test update portal js on remove_05. * When node input have jcr:data is "alert('testUpdatePortalJSOnModify...');". *//* public void testUpdatePortalJSOnRemove_05() { try { JavascriptConfigService configService = null; Node portalNode = findPortalNode(sessionProvider, documentNode); Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, "alert('testUpdatePortalJSOnModify...');"); Node jsNode = webContent.getNode("js").getNode("default.js"); createSharedJsNode(sharedJsNode); Node js = sharedJsNode.getNode("sharedJsFile.js"); js.setProperty("exo:priority", 1); session.save(); String jsData = ""; configService = getService(JavascriptConfigService.class); javascriptService.updatePortalJSOnRemove(portalNode, jsNode); session.save(); jsData = new String(configService.getMergedJavascript()); assertEquals("\nThis is the default.js file.This is the default.js file.", jsData); } catch(Exception e) { fail(); } } *//** * Test update portal js on remove_06. * When portal node is shared portal. *//* public void testUpdatePortalJSOnRemove_06() { try { JavascriptConfigService configService = null; WCMConfigurationService configurationService = WCMCoreUtils.getService(WCMConfigurationService.class);; LivePortalManagerService livePortalManagerService = getService(LivePortalManagerService.class); String sharedPortalName = configurationService.getSharedPortalName(REPO_NAME); Node portal = livePortalManagerService.getLivePortal(sessionProvider, sharedPortalName); Node sharedNode = (Node) session.getItem("/sites content/live/" + sharedPortalName + "/js"); Node webContent = createWebcontentNode(documentNode, WEB_CONTENT_NODE_NAME, null, null, "alert('testUpdatePortalJSOnModify...');"); Node jsNode = webContent.getNode("js").getNode("default.js"); createSharedJsNode(sharedNode); String jsData = ""; configService = getService(JavascriptConfigService.class); javascriptService.updatePortalJSOnRemove(portal, jsNode); session.save(); jsData = new String(configService.getMergedJavascript()); assertEquals("\nThis is the default.js file.alert('testUpdatePortalJSOnModify...');", jsData); session.save(); } catch(Exception e) { fail(); } }*/ private Node findPortalNode(SessionProvider sessionProvider, Node child) throws Exception{ LivePortalManagerService livePortalManagerService = getService(LivePortalManagerService.class); String portalName = null; for(String portalPath: livePortalManagerService.getLivePortalsPath()) { if(child.getPath().startsWith(portalPath)) { portalName = livePortalManagerService.getPortalNameByPath(portalPath); break; } } if(portalName == null) return null; return livePortalManagerService.getLivePortal(sessionProvider, portalName); } private void createSharedJsNode(Node parentNode) throws Exception { Node jsNode; jsNode = parentNode.addNode("sharedJsFile.js", "nt:file"); if (!jsNode.isNodeType("exo:jsFile")) { jsNode.addMixin("exo:jsFile"); } jsNode.setProperty("exo:active", true); jsNode.setProperty("exo:priority", 2); 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()); String jsData = "This is the default.js file."; jsContent.setProperty("jcr:data", jsData); session.save(); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ public void tearDown() throws Exception { Node sharedPortalNode = (Node) session.getItem("/sites content/live/shared/js"); NodeIterator nodeIterator = documentNode.getNodes(); NodeIterator sharedNode = sharedJsNode.getNodes(); NodeIterator sharedIterator = sharedPortalNode.getNodes(); while(nodeIterator.hasNext()) { nodeIterator.nextNode().remove(); } while(sharedNode.hasNext()) { sharedNode.nextNode().remove(); } while(sharedIterator.hasNext()) { sharedIterator.nextNode().remove(); } session.save(); super.tearDown(); } }
20,973
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
LivePortalManagerServiceTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/wcm/portal/LivePortalManagerServiceTest.java
/* * Copyright (C) 2003-2020 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.portal; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import static org.mockito.Mockito.*; import javax.jcr.Node; import org.junit.Test; import org.exoplatform.portal.config.UserPortalConfigService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.listener.ListenerService; import org.exoplatform.services.wcm.core.WCMConfigurationService; import org.exoplatform.services.wcm.core.WebSchemaConfigService; import org.exoplatform.services.wcm.portal.impl.LivePortalManagerServiceImpl; public class LivePortalManagerServiceTest { @Test public void testNotCreatingGlobalSiteFolder() { ListenerService listenerService = mock(ListenerService.class); WebSchemaConfigService webSchemaConfigService = mock(WebSchemaConfigService.class); WCMConfigurationService wcmConfigurationService = mock(WCMConfigurationService.class); RepositoryService repositoryService = mock(RepositoryService.class); UserPortalConfigService portalConfigService = mock(UserPortalConfigService.class); SessionProvider sessionProvider = mock(SessionProvider.class); LivePortalManagerServiceImpl livePortalManagerService = new LivePortalManagerServiceImpl(listenerService, webSchemaConfigService, wcmConfigurationService, portalConfigService, repositoryService); String globalPortalName = "global"; when(portalConfigService.getGlobalPortal()).thenReturn(globalPortalName); try { Node livePortal = livePortalManagerService.getLivePortal(sessionProvider, "repository", globalPortalName); assertNull(livePortal); verifyZeroInteractions(wcmConfigurationService, sessionProvider); } catch (Exception e) { fail(e.getMessage()); } } }
2,930
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestCreatePortalArtifactsService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/wcm/portal/artifacts/TestCreatePortalArtifactsService.java
package org.exoplatform.services.wcm.portal.artifacts; import java.util.ArrayList; import java.util.Collections; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.wcm.BaseWCMTestCase; import org.mockito.Mockito; public class TestCreatePortalArtifactsService extends BaseWCMTestCase { /** The CreatePortalArtifacts Service. */ private CreatePortalArtifactsService createPortalArtifactsService; public void setUp() throws Exception { super.setUp(); createPortalArtifactsService = getService(CreatePortalArtifactsService.class); applySystemSession(); } public void testAddPlugin() throws Exception { CreatePortalPlugin portalPlugin = Mockito.mock(CreatePortalPlugin.class); Mockito.when(portalPlugin.getName()).thenReturn("portalPlugin"); createPortalArtifactsService.addPlugin(portalPlugin); } @SuppressWarnings("deprecation") public void testDeployArtifactsToPortal() throws Exception { SessionProvider sessionProvider = sessionProviderService_.getSystemSessionProvider(null); createPortalArtifactsService.deployArtifactsToPortal(sessionProvider, "test1", "templateportal"); } public void testDeployArtifactsToPortalWithTemplate() throws Exception { SessionProvider sessionProvider = sessionProviderService_.getSystemSessionProvider(null); createPortalArtifactsService.deployArtifactsToPortal(sessionProvider, "portalplugin","templateportal"); } public void testAddIgnorePortalPlugin() throws Exception { IgnorePortalPlugin ignorePortalPlugin = Mockito.mock(IgnorePortalPlugin.class); CreatePortalArtifactsServiceImpl artifactService = (CreatePortalArtifactsServiceImpl)getService(CreatePortalArtifactsService.class); String[] ignorePortals ={"acme","classic","wai"}; ArrayList<String> ignorePortalsList = new ArrayList<String>(); Collections.addAll(ignorePortalsList, ignorePortals); Mockito.when(ignorePortalPlugin.getIgnorePortals()).thenReturn(ignorePortalsList); artifactService.addIgnorePortalPlugin(ignorePortalPlugin); } public void tearDown() throws Exception { super.tearDown(); } }
2,150
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestWCMConfigurationService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/wcm/core/TestWCMConfigurationService.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.core; import java.util.Collection; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.wcm.BaseWCMTestCase; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Jul 20, 2009 */ public class TestWCMConfigurationService extends BaseWCMTestCase { /** The configuration service. */ private WCMConfigurationService configurationService; /* (non-Javadoc) * @see org.exoplatform.services.wcm.BaseWCMTestCase#setUp() */ public void setUp() throws Exception { super.setUp(); configurationService = (WCMConfigurationService) container.getComponentInstanceOfType(WCMConfigurationService.class); applySystemSession(); } /** * Test get site drive config. */ public void testGetSiteDriveConfig() { DriveData driveData = configurationService.getSiteDriveConfig(); assertEquals("{siteName}", driveData.getName()); assertEquals("{workspace}", driveData.getWorkspace()); assertEquals("{accessPermission}", driveData.getPermissions()); assertEquals("{sitePath}/categories/{siteName}", driveData.getHomePath()); assertEquals("", driveData.getIcon()); assertEquals("wcm-category-view", driveData.getViews()); assertFalse(driveData.getViewPreferences()); assertTrue(driveData.getViewNonDocument()); assertTrue(driveData.getViewSideBar()); assertFalse(driveData.getShowHiddenNode()); assertEquals("nt:folder,nt:unstructured", driveData.getAllowCreateFolders()); } /** * Test get live portals location. */ public void testGetLivePortalsLocation() { NodeLocation nodeLocation = configurationService.getLivePortalsLocation(); assertEquals("collaboration", nodeLocation.getWorkspace()); assertEquals("/sites content/live", nodeLocation.getPath()); } /** * Test get runtime context param. */ public void testGetRuntimeContextParam() { assertEquals("/detail", configurationService.getRuntimeContextParam(WCMConfigurationService.PARAMETERIZED_PAGE_URI)); assertEquals("/printviewer", configurationService.getRuntimeContextParam(WCMConfigurationService.PRINT_PAGE_URI)); assertEquals("printviewer", configurationService.getRuntimeContextParam(WCMConfigurationService.PRINT_VIEWER_PAGE)); assertEquals("/presentation/ContentListViewerPortlet", configurationService.getRuntimeContextParam(WCMConfigurationService.CLV_PORTLET)); assertEquals("/presentation/SingleContentViewer", configurationService.getRuntimeContextParam(WCMConfigurationService.SCV_PORTLET)); assertEquals("/exo:ecm/views/templates/content-list-viewer/paginators/DefaultPaginator.gtmpl", configurationService.getRuntimeContextParam(WCMConfigurationService.PAGINATOR_TEMPLAET_PATH)); } /** * Test get runtime context params. */ public void testGetRuntimeContextParams() { Collection<String> runtimeContextParams = configurationService.getRuntimeContextParams(); assertTrue(runtimeContextParams.contains("/detail")); assertTrue(runtimeContextParams.contains("/printviewer")); assertTrue(runtimeContextParams.contains("printviewer")); assertTrue(runtimeContextParams.contains("/presentation/ContentListViewerPortlet")); assertTrue(runtimeContextParams.contains("/presentation/SingleContentViewer")); assertTrue(runtimeContextParams.contains("/exo:ecm/views/templates/content-list-viewer/paginators/DefaultPaginator.gtmpl")); assertEquals(7, runtimeContextParams.size()); } /** * Test get shared portal name. */ public void testGetSharedPortalName() { assertEquals("shared", configurationService.getSharedPortalName()); } /** * Test get all live portals location. */ public void testGetAllLivePortalsLocation() { Collection<NodeLocation> nodeLocations = configurationService.getAllLivePortalsLocation(); assertEquals(1, nodeLocations.size()); } public void tearDown() throws Exception { super.tearDown(); } }
4,746
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestWebSchemaConfigService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/wcm/core/TestWebSchemaConfigService.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.core; import java.util.Date; import javax.jcr.Node; import javax.jcr.NodeIterator; import org.exoplatform.container.component.ComponentPlugin; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.wcm.BaseWCMTestCase; import org.exoplatform.services.wcm.javascript.JSFileHandler; import org.exoplatform.services.wcm.portal.PortalFolderSchemaHandler; import org.exoplatform.services.wcm.skin.CSSFileHandler; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.services.wcm.webcontent.HTMLFileSchemaHandler; import org.exoplatform.services.wcm.webcontent.WebContentSchemaHandler; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Jul 15, 2009 */ public class TestWebSchemaConfigService extends BaseWCMTestCase { /** The web schema config service. */ private WebSchemaConfigService webSchemaConfigService; /** The live node. */ private Node documentNode; public void setUp() throws Exception { super.setUp(); webSchemaConfigService = (WebSchemaConfigService) container.getComponentInstanceOfType(WebSchemaConfigService.class); applySystemSession(); webSchemaConfigService.getAllWebSchemaHandler().clear(); documentNode = (Node) session.getItem("/sites content/live/classic/documents"); } /** * Test add css file schema handler. * * @throws Exception the exception */ public void testAddCSSFileSchemaHandler() throws Exception { ComponentPlugin componentPlugin = new CSSFileHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin); assertEquals(1, webSchemaConfigService.getAllWebSchemaHandler().size()); } /** * Test add double css file schema handler. * * @throws Exception the exception */ public void testAddDoubleCSSFileSchemaHandler() throws Exception { ComponentPlugin componentPlugin = new CSSFileHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin); ComponentPlugin componentPlugin2 = new CSSFileHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin2); assertEquals(1, webSchemaConfigService.getAllWebSchemaHandler().size()); } /** * Test add js file schema handler. * * @throws Exception the exception */ public void testAddJSFileSchemaHandler() throws Exception { ComponentPlugin componentPlugin = new JSFileHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin); assertEquals(1, webSchemaConfigService.getAllWebSchemaHandler().size()); } /** * Test add double js file schema handler. * * @throws Exception the exception */ public void testAddDoubleJSFileSchemaHandler() throws Exception { ComponentPlugin componentPlugin = new JSFileHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin); ComponentPlugin componentPlugin2 = new JSFileHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin2); assertEquals(1, webSchemaConfigService.getAllWebSchemaHandler().size()); } /** * Test add html file schema handler. * * @throws Exception the exception */ public void testAddHTMLFileSchemaHandler() throws Exception { ComponentPlugin componentPlugin = new HTMLFileSchemaHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin); assertEquals(1, webSchemaConfigService.getAllWebSchemaHandler().size()); } /** * Test add double html file schema handler. * * @throws Exception the exception */ public void testAddDoubleHTMLFileSchemaHandler() throws Exception { ComponentPlugin componentPlugin = new HTMLFileSchemaHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin); ComponentPlugin componentPlugin2 = new HTMLFileSchemaHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin2); assertEquals(1, webSchemaConfigService.getAllWebSchemaHandler().size()); } /** * Test add portal folder schema handler. * * @throws Exception the exception */ public void testAddPortalFolderSchemaHandler() throws Exception { ComponentPlugin componentPlugin = new PortalFolderSchemaHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin); assertEquals(1, webSchemaConfigService.getAllWebSchemaHandler().size()); } /** * Test add double portal folder schema handler. * css * * @throws Exception the exception */ public void testAddDoublePortalFolderSchemaHandler() throws Exception { ComponentPlugin componentPlugin = new PortalFolderSchemaHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin); ComponentPlugin componentPlugin2 = new PortalFolderSchemaHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin2); assertEquals(1, webSchemaConfigService.getAllWebSchemaHandler().size()); } /** * Test add web content schema handler. * * @throws Exception the exception */ public void testAddWebcontentSchemaHandler() throws Exception { ComponentPlugin componentPlugin = new WebContentSchemaHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin); assertEquals(1, webSchemaConfigService.getAllWebSchemaHandler().size()); } /** * Test add double web content schema handler. * * @throws Exception the exception */ public void testAddDoubleWebcontentSchemaHandler() throws Exception { ComponentPlugin componentPlugin = new WebContentSchemaHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin); ComponentPlugin componentPlugin2 = new WebContentSchemaHandler(); webSchemaConfigService.addWebSchemaHandler(componentPlugin2); assertEquals(1, webSchemaConfigService.getAllWebSchemaHandler().size()); } /** * Test get all web schema handler. * * @throws Exception the exception */ public void testGetAllWebSchemaHandler() throws Exception { webSchemaConfigService.addWebSchemaHandler(new JSFileHandler()); webSchemaConfigService.addWebSchemaHandler(new CSSFileHandler()); webSchemaConfigService.addWebSchemaHandler(new HTMLFileSchemaHandler()); webSchemaConfigService.addWebSchemaHandler(new PortalFolderSchemaHandler()); webSchemaConfigService.addWebSchemaHandler(new WebContentSchemaHandler()); assertEquals(5, webSchemaConfigService.getAllWebSchemaHandler().size()); } /** * Test get web schema handler by type. * * @throws Exception the exception */ public void testGetWebSchemaHandlerByType() throws Exception { webSchemaConfigService.addWebSchemaHandler(new JSFileHandler()); webSchemaConfigService.addWebSchemaHandler(new CSSFileHandler()); webSchemaConfigService.addWebSchemaHandler(new HTMLFileSchemaHandler()); webSchemaConfigService.addWebSchemaHandler(new PortalFolderSchemaHandler()); webSchemaConfigService.addWebSchemaHandler(new WebContentSchemaHandler()); CSSFileHandler cssFileSchemaHandler = webSchemaConfigService.getWebSchemaHandlerByType(CSSFileHandler.class); assertTrue(cssFileSchemaHandler instanceof CSSFileHandler); JSFileHandler jsFileSchemaHandler = webSchemaConfigService.getWebSchemaHandlerByType(JSFileHandler.class); assertTrue(jsFileSchemaHandler instanceof JSFileHandler); HTMLFileSchemaHandler htmlFileSchemaHandler = webSchemaConfigService.getWebSchemaHandlerByType(HTMLFileSchemaHandler.class); assertTrue(htmlFileSchemaHandler instanceof HTMLFileSchemaHandler); PortalFolderSchemaHandler portalFolderSchemaHandler= webSchemaConfigService.getWebSchemaHandlerByType(PortalFolderSchemaHandler.class); assertTrue(portalFolderSchemaHandler instanceof PortalFolderSchemaHandler); WebContentSchemaHandler webContentSchemaHandler = webSchemaConfigService.getWebSchemaHandlerByType(WebContentSchemaHandler.class); assertTrue(webContentSchemaHandler instanceof WebContentSchemaHandler); } /** * Test create css file schema handler. * * @throws Exception the exception */ public void testCreateCSSFileSchemaHandler() throws Exception { webSchemaConfigService.addWebSchemaHandler(new CSSFileHandler()); webSchemaConfigService.addWebSchemaHandler(new PortalFolderSchemaHandler()); Node cssFolder = documentNode.addNode("css", NodetypeConstant.EXO_CSS_FOLDER); Node cssNode = cssFolder.addNode("default.css", NodetypeConstant.NT_FILE); cssNode.setProperty(NodetypeConstant.EXO_ACTIVE, true); cssNode.setProperty(NodetypeConstant.EXO_PRIORITY, 1); cssNode.setProperty(NodetypeConstant.EXO_SHARED_CSS, true); Node cssContent = cssNode.addNode(NodetypeConstant.JCR_CONTENT, NodetypeConstant.NT_RESOURCE); cssContent.setProperty(NodetypeConstant.JCR_ENCODING, "UTF-8"); cssContent.setProperty(NodetypeConstant.JCR_MIME_TYPE, "text/css"); cssContent.setProperty(NodetypeConstant.JCR_LAST_MODIFIED, new Date().getTime()); cssContent.setProperty(NodetypeConstant.JCR_DATA, "This is the default.css file."); SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); webSchemaConfigService.createSchema(sessionProvider, cssNode); Node result = (Node)session.getItem("/sites content/live/classic/documents/css/default.css"); assertTrue(result.isNodeType(NodetypeConstant.EXO_CSS_FILE)); assertTrue(result.isNodeType(NodetypeConstant.EXO_OWNEABLE)); assertEquals(result.getProperty(NodetypeConstant.EXO_PRESENTATION_TYPE).getString(), NodetypeConstant.EXO_CSS_FILE); cssFolder.remove(); session.save(); } /** * Test create js file schema handler. * * @throws Exception the exception */ public void testCreateJSFileSchemaHandler() throws Exception { webSchemaConfigService.addWebSchemaHandler(new JSFileHandler()); webSchemaConfigService.addWebSchemaHandler(new PortalFolderSchemaHandler()); Node jsFolder = documentNode.addNode("js", NodetypeConstant.EXO_JS_FOLDER); Node jsNode = jsFolder.addNode("default.js", NodetypeConstant.NT_FILE); jsNode.setProperty(NodetypeConstant.EXO_ACTIVE, true); jsNode.setProperty(NodetypeConstant.EXO_PRIORITY, 1); jsNode.setProperty(NodetypeConstant.EXO_SHARED_JS, true); Node jsContent = jsNode.addNode(NodetypeConstant.JCR_CONTENT, NodetypeConstant.NT_RESOURCE); jsContent.setProperty(NodetypeConstant.JCR_ENCODING, "UTF-8"); jsContent.setProperty(NodetypeConstant.JCR_MIME_TYPE, "text/javascript"); jsContent.setProperty(NodetypeConstant.JCR_LAST_MODIFIED, new Date().getTime()); jsContent.setProperty(NodetypeConstant.JCR_DATA, "This is the default.js file."); SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); webSchemaConfigService.createSchema(sessionProvider, jsNode); Node result = (Node)session.getItem("/sites content/live/classic/documents/js/default.js"); assertTrue(result.isNodeType(NodetypeConstant.EXO_JS_FILE)); assertTrue(result.isNodeType(NodetypeConstant.EXO_OWNEABLE)); assertEquals(result.getProperty(NodetypeConstant.EXO_PRESENTATION_TYPE).getString(), NodetypeConstant.EXO_JS_FILE); jsFolder.remove(); session.save(); } /** * Test create html file schema handler with no pre-defined folder. * * @throws Exception the exception */ public void testCreateWebcontentSchemaHandler_01() throws Exception { webSchemaConfigService.addWebSchemaHandler(new WebContentSchemaHandler()); Node webcontentNode = documentNode.addNode("webcontent", NodetypeConstant.EXO_WEBCONTENT); SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); webSchemaConfigService.createSchema(sessionProvider, webcontentNode); Node result = (Node)session.getItem("/sites content/live/classic/documents/webcontent"); assertEquals("css", result.getNode("css").getName()); assertEquals(NodetypeConstant.EXO_CSS_FOLDER, result.getNode("css").getPrimaryNodeType().getName()); assertEquals("js", result.getNode("js").getName()); assertEquals(NodetypeConstant.EXO_JS_FOLDER, result.getNode("js").getPrimaryNodeType().getName()); assertEquals("documents", result.getNode("documents").getName()); assertEquals(NodetypeConstant.NT_UNSTRUCTURED, result.getNode("documents").getPrimaryNodeType().getName()); Node mediasNode = result.getNode("medias"); assertEquals("medias", mediasNode.getName()); assertEquals(NodetypeConstant.EXO_MULTIMEDIA_FOLDER, result.getNode("medias").getPrimaryNodeType().getName()); assertEquals("images", mediasNode.getNode("images").getName()); assertEquals(NodetypeConstant.NT_FOLDER, mediasNode.getNode("images").getPrimaryNodeType().getName()); assertEquals("videos", mediasNode.getNode("videos").getName()); assertEquals(NodetypeConstant.NT_FOLDER, mediasNode.getNode("videos").getPrimaryNodeType().getName()); assertEquals("audio", mediasNode.getNode("audio").getName()); assertEquals(NodetypeConstant.NT_FOLDER, mediasNode.getNode("audio").getPrimaryNodeType().getName()); result.remove(); session.save(); } /** * Test create html file schema handler. */ public void testCreateHTMLFileSchemaHandler() throws Exception { Node htmlFolder = documentNode.addNode("html", NodetypeConstant.EXO_WEB_FOLDER); Node htmlFile = htmlFolder.addNode("htmlFile", NodetypeConstant.NT_FILE); Node htmlContent = htmlFile.addNode(NodetypeConstant.JCR_CONTENT, NodetypeConstant.NT_RESOURCE); htmlContent.setProperty(NodetypeConstant.JCR_ENCODING, "UTF-8"); htmlContent.setProperty(NodetypeConstant.JCR_MIME_TYPE, "text/html"); htmlContent.setProperty(NodetypeConstant.JCR_LAST_MODIFIED, new Date().getTime()); htmlContent.setProperty(NodetypeConstant.JCR_DATA, "This is the default.html file."); session.save(); SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); webSchemaConfigService.addWebSchemaHandler(new HTMLFileSchemaHandler()); webSchemaConfigService.addWebSchemaHandler(new WebContentSchemaHandler()); webSchemaConfigService.createSchema(sessionProvider, htmlFile); session.save(); Node result = (Node)session.getItem("/sites content/live/classic/documents/html/htmlFile/default.html"); assertTrue(result.isNodeType(NodetypeConstant.EXO_HTML_FILE)); assertEquals(result.getProperty(NodetypeConstant.EXO_PRESENTATION_TYPE).getString(), NodetypeConstant.EXO_HTML_FILE); } /** * Test modified css file schema handler. * * @throws Exception the exception */ public void testUpdateCSSFileSchemaHandlerOnModify() throws Exception { } /** * Test modified js file schema handler. * * @throws Exception the exception */ public void testUpdateJSFileSchemaHandlerOnModify() throws Exception {} /** * Test modified html file schema handler. */ public void testUpdateHTMLFileSchemaHandlerOnModify() throws Exception { String htmlData = "<html>" + "<head>" + "<title>My own HTML file</title>" + "</head>" + "<body>" + "<h1>the first h1 tag</h1>" + "<h2>the first h2 tag</h2>" + "<h2>the second h2 tag</h2>" + "<h1>the second h1 tag</h1>" + "<h2>the third second h2 tag</h2>" + "<h3>the first h3 tag</h3>" + "<a href=" + "#" + ">Test</a>" + "</body>" + "</html>"; Node htmlFolder = documentNode.addNode("html", NodetypeConstant.EXO_WEB_FOLDER); Node htmlFile = htmlFolder.addNode("htmlFile", NodetypeConstant.NT_FILE); Node htmlContent = htmlFile.addNode(NodetypeConstant.JCR_CONTENT, NodetypeConstant.NT_RESOURCE); htmlContent.setProperty(NodetypeConstant.JCR_ENCODING, "UTF-8"); htmlContent.setProperty(NodetypeConstant.JCR_MIME_TYPE, "text/html"); htmlContent.setProperty(NodetypeConstant.JCR_LAST_MODIFIED, new Date().getTime()); htmlContent.setProperty(NodetypeConstant.JCR_DATA, htmlData); session.save(); SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider(); webSchemaConfigService.addWebSchemaHandler(new HTMLFileSchemaHandler()); webSchemaConfigService.addWebSchemaHandler(new WebContentSchemaHandler()); webSchemaConfigService.createSchema(sessionProvider, htmlFile); session.save(); Node result = (Node)session.getItem("/sites content/live/classic/documents/html/htmlFile/default.html"); assertTrue(result.isNodeType(NodetypeConstant.EXO_HTML_FILE)); assertEquals(result.getProperty(NodetypeConstant.EXO_PRESENTATION_TYPE).getString(), NodetypeConstant.EXO_HTML_FILE); webSchemaConfigService.updateSchemaOnModify(sessionProvider, htmlFile); Node webContent = (Node)session.getItem("/sites content/live/classic/documents/html/htmlFile"); assertTrue(webContent.hasProperty("exo:links")); } /** * Test remove css file schema handler. */ public void testUpdateCSSFileSchemaHandlerOnRemove() { } /** * Test remove js file schema handler. * * @throws Exception the exception */ public void testUpdateJSFileSchemaHandlerOnRemove() throws Exception {} /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ public void tearDown() throws Exception { NodeIterator nodeIterator = documentNode.getNodes(); while (nodeIterator.hasNext()) { nodeIterator.nextNode().remove(); } session.save(); super.tearDown(); } }
18,149
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestWCMService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/wcm/core/TestWCMService.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.core; import javax.jcr.Node; import org.exoplatform.services.wcm.BaseWCMTestCase; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Jul 14, 2009 */ public class TestWCMService extends BaseWCMTestCase { /** The WCM Core Service. */ private WCMService wcmService; /** The jcr node. */ private Node node; /* (non-Javadoc) * @see org.exoplatform.services.wcm.core.BaseWCMTestCase#setUp() */ public void setUp() throws Exception { super.setUp(); wcmService = (WCMService) container.getComponentInstanceOfType(WCMService.class); applySystemSession(); node = session.getRootNode().addNode("parentNode").addNode("childNode"); node.addMixin("mix:referenceable"); session.save(); } /** * Test get referenced jcr node by path. * * @throws Exception the exception */ public void testGetReferencedContent1() throws Exception { String nodePath = "/parentNode/childNode"; Node resultNode = wcmService.getReferencedContent(WCMCoreUtils.getSystemSessionProvider(), COLLABORATION_WS, nodePath); assertEquals(resultNode.getPath(), nodePath); } /** * Test get referenced jcr node by UUID. * * @throws Exception the exception */ public void testGetReferencedContent2() throws Exception { String nodeUUID = node.getUUID(); Node resultNode = wcmService.getReferencedContent(WCMCoreUtils.getSystemSessionProvider(), COLLABORATION_WS, nodeUUID); assertEquals(resultNode.getUUID(), nodeUUID); } /** * Test get null if input is wrong identifier. * * @throws Exception the exception */ public void testGetReferencedContent3() throws Exception { String nodeIdentifier = "WrongIdentifier"; Node resultNode = wcmService.getReferencedContent(WCMCoreUtils.getSystemSessionProvider(), COLLABORATION_WS, nodeIdentifier); assertNull(resultNode); } /** * Test a portal is shared portal. * * @throws Exception the exception */ public void testIsSharedPortal1() throws Exception { boolean isSharedPortal = wcmService.isSharedPortal(WCMCoreUtils.getSystemSessionProvider(), "shared"); assertTrue(isSharedPortal); } /** * Test a portal is not shared portal. * * @throws Exception the exception */ public void testIsSharedPortal2() throws Exception { boolean isSharedPortal = wcmService.isSharedPortal(WCMCoreUtils.getSystemSessionProvider(), "classic"); assertFalse(isSharedPortal); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ public void tearDown() throws Exception { session.getRootNode().getNode("parentNode").remove(); session.save(); super.tearDown(); } }
3,549
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestLiveLinkManagerService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/wcm/core/link/TestLiveLinkManagerService.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.core.link; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.Value; import org.exoplatform.services.wcm.BaseWCMTestCase; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.link.LinkBean; import org.exoplatform.services.wcm.link.LiveLinkManagerService; /** * Created by The eXo Platform SAS * Author : eXoPlatform * chuong.phan@exoplatform.com, phan.le.thanh.chuong@gmail.com * Jul 22, 2009 */ public class TestLiveLinkManagerService extends BaseWCMTestCase { /** The live link manager service. */ private LiveLinkManagerService liveLinkManagerService; private Node link; public void setUp() throws Exception { super.setUp(); liveLinkManagerService = getService(LiveLinkManagerService.class); applySystemSession(); Node folder = (Node) session.getItem("/sites content/live/classic/web contents"); link = createWebcontentNode(folder, "webcontent", "This is the live link: <a href='http://www.google.com'>Goolge</a> and this is the broken link: <a href='http://www.thiscannotbeanactivelink.com'>Broken</a>", null, null); } public void testGetBrokenLinks() throws Exception { List<LinkBean> links = liveLinkManagerService.getBrokenLinks("classic"); assertEquals(0, links.size()); String[] linkValues = {"status=broken@url=http://www.mozilla.com"}; link.setProperty("exo:links", linkValues); link.save(); links = liveLinkManagerService.getBrokenLinks("classic"); assertEquals(1, links.size()); } public void testUpdateLinks() throws Exception { List<String> linkValues = new ArrayList<String>(); linkValues.add("http://www.thiscannotbeanactivelink.com"); liveLinkManagerService.updateLinkDataForNode(link, linkValues); liveLinkManagerService.updateLinks(); List<LinkBean> links = liveLinkManagerService.getBrokenLinks("classic"); assertEquals(1, links.size()); } /** * Test extract links. * * @throws Exception the exception */ public void testExtractLinks() throws Exception { Node result = (Node) session.getItem("/sites content/live/classic/web contents/webcontent"); Node htmlFile = result.getNode("default.html"); List<String> links = liveLinkManagerService.extractLinks(htmlFile); assertEquals(2, links.size()); assertEquals("http://www.google.com", links.get(0)); assertEquals("http://www.thiscannotbeanactivelink.com", links.get(1)); } /** * Test update link data for node. * * @throws Exception the exception */ public void testUpdateLinkDataForNode() throws Exception { liveLinkManagerService.updateLinks("classic"); Node result = (Node) session.getItem("/sites content/live/classic/web contents/webcontent"); List<String> links = new ArrayList<String>(); links.add("http://www.mozilla.com"); liveLinkManagerService.updateLinkDataForNode(result, links); Value[] values = result.getProperty(NodetypeConstant.EXO_LINKS).getValues(); assertEquals(1, values.length); assertEquals("status=unchecked@url=http://www.mozilla.com", values[0].getString()); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ public void tearDown() throws Exception { link = null; session.getItem("/sites content/live/classic/web contents/webcontent").remove(); session.save(); super.tearDown(); } }
4,176
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestContentInitializerService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/deployment/TestContentInitializerService.java
package org.exoplatform.services.deployment; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.exoplatform.commons.testing.BaseCommonsTestCase; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.services.deployment.plugins.XMLDeploymentPluginTest; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; public class TestContentInitializerService extends BaseCommonsTestCase { private static final Log LOG = ExoLogger.getLogger(XMLDeploymentPluginTest.class); protected final String REPO_NAME = "repository"; protected final String WORKSPACE_NAME = "portal-test"; protected PortalContainer container; protected RepositoryService repositoryService; protected Session session; protected Node root; private static String EXO_SERVICES = "eXoServices"; private static String EXO_CIS_LOG = "ContentInitializerServiceLog"; private static String CONTENT_INIT = "ContentInitializerService"; private ContentInitializerService contentInitializerService; public void setUp() throws Exception { System.setProperty("exo.test.random.name", "" + Math.random()); super.setUp(); begin(); container = PortalContainer.getInstance(); repositoryService = getService(RepositoryService.class); configurationManager = getService(ConfigurationManager.class); session = repositoryService.getCurrentRepository().getSystemSession(WORKSPACE_NAME); root = session.getRootNode(); System.setProperty("gatein.email.domain.url", "http://localhost:8080"); // see file test-conteninitializerservice-configuration.xml contentInitializerService = getService(ContentInitializerService.class); } public void testStart() throws Exception { SessionProvider sessionProvider = null; try { sessionProvider = SessionProvider.createSystemProvider(); ManageableRepository repository = repositoryService .getCurrentRepository(); Session session = sessionProvider.getSession(repository .getConfiguration().getDefaultWorkspaceName(), repository); NodeHierarchyCreator nodeHierarchyCreator = getService(NodeHierarchyCreator.class); Node serviceFolder = (Node) session.getItem(nodeHierarchyCreator .getJcrPath(EXO_SERVICES)); assertNotNull(contentInitializerService); assertTrue(serviceFolder.hasNode(CONTENT_INIT)); Node contentInitializerServiceNode = serviceFolder .getNode(CONTENT_INIT); assertTrue(contentInitializerServiceNode.hasNode(EXO_CIS_LOG)); Node cisfFilelOG = contentInitializerServiceNode .getNode(EXO_CIS_LOG); assertTrue(cisfFilelOG.hasNode("jcr:content")); Node cisContentLog = cisfFilelOG.getNode("jcr:content"); assertTrue(cisContentLog.getProperty("jcr:data").getString() .contains("successful")); } catch (RepositoryException e) { } finally { sessionProvider.close(); } } @Override public void tearDown() throws Exception { super.tearDown(); } public static class DeploymentPluginTest extends DeploymentPlugin { public DeploymentPluginTest() { super(); } private Log LOG = ExoLogger.getLogger(DeploymentPluginTest.class); @Override public void deploy(SessionProvider sessionProvider) throws Exception { LOG.info("deploying DeploymentPluginTest "); } } }
3,716
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ContentInitializerServiceTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/deployment/ContentInitializerServiceTest.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.deployment; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import junit.framework.TestCase; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.organization.OrganizationService; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; /** * Created by The eXo Platform SAS Author : eXoPlatform annb@exoplatform.com May * 18, 2012 */ public class ContentInitializerServiceTest extends TestCase { private static final Log LOGGER = ExoLogger.getLogger(ContentInitializerServiceTest.class); private ContentInitializerService contentInitializerServiceActual; /** * test constructor */ public void setUp() { LOGGER.info("testContentInitializerService"); // Actual RepositoryService repositoryServiceActual = mock(RepositoryService.class); NodeHierarchyCreator nodeHierarchyCreatorActual = mock(NodeHierarchyCreator.class); OrganizationService organizationServiceActual = mock(OrganizationService.class); contentInitializerServiceActual = new ContentInitializerService(repositoryServiceActual, nodeHierarchyCreatorActual, organizationServiceActual); //verify if class ContentInitializerService assertEquals(contentInitializerServiceActual.getClass(), ContentInitializerService.class); //verify if mock class is not null assertNotNull(contentInitializerServiceActual); } /** * test method addplugin */ @SuppressWarnings("rawtypes") public void testAddPlugin() { LOGGER.info("testAddPlugin"); ContentInitializerService contentMock = mock(ContentInitializerService.class); final List<DeploymentPlugin> listDeploymentPluginActual = new ArrayList<DeploymentPlugin>(); // Actual DeploymentPlugin deploymentPluginActual = mock(DeploymentPlugin.class); // return arraylist when mock calls method addplugin doAnswer(new Answer() { public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); LOGGER.info("argument add is " + args[0]); System.out.println("add for mock"); listDeploymentPluginActual.add((DeploymentPlugin) args[0]); return listDeploymentPluginActual; } }).when(contentMock).addPlugin(any(DeploymentPlugin.class)); // call method contentMock.addPlugin(deploymentPluginActual); // Expected List<DeploymentPlugin> listDeploymentPluginExpected = new ArrayList<DeploymentPlugin>(); DeploymentPlugin deploymentPluginExpected = mock(DeploymentPlugin.class); listDeploymentPluginExpected.add(deploymentPluginExpected); contentInitializerServiceActual.addPlugin(deploymentPluginActual); // verify call method verify(contentMock).addPlugin(deploymentPluginActual); assertEquals(listDeploymentPluginActual.size(), 1); } /** * test method start */ public void testStart() { LOGGER.info("testStart"); Node contentInitializerServiceMock = mock(Node.class); Node contentInitializerServiceLogMock = mock(Node.class); Node contentInitializerServiceLogContentMock = mock(Node.class); try { when(contentInitializerServiceMock.addNode("ContentInitializerServiceLog", "nt:file")).thenReturn(contentInitializerServiceLogMock); when(contentInitializerServiceLogMock.addNode("jcr:content", "nt:resource")).thenReturn(contentInitializerServiceLogContentMock); } catch (Exception e) { } // try { assertEquals(contentInitializerServiceLogMock, (contentInitializerServiceMock.addNode("ContentInitializerServiceLog", "nt:file"))); assertEquals(contentInitializerServiceLogContentMock, (contentInitializerServiceLogMock.addNode("jcr:content", "nt:resource"))); } catch (Exception e) { } ContentInitializerService contentMock = mock(ContentInitializerService.class); contentMock.start(); //verify call method verify(contentMock).start(); } /** * test method stop */ public void testStop() { LOGGER.info("testStop"); ContentInitializerService contentMock = mock(ContentInitializerService.class); contentMock.stop(); //verify call method verify(contentMock).stop(); } }
5,628
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestWCMContentInitializerService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/deployment/TestWCMContentInitializerService.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.deployment; import org.exoplatform.services.wcm.BaseWCMTestCase; /** * Created by The eXo Platform SAS * Author : Nguyen The Vinh From ECM Of eXoPlatform * vinh_nguyen@exoplatform.com * 3 Aug 2012 */ public class TestWCMContentInitializerService extends BaseWCMTestCase { WCMContentInitializerService WCIService; public void testRemoveGroupsOrUsersForLock() throws Exception { //For recovering sonar WCIService.addPlugin(null); } public void setUp() throws Exception { super.setUp(); WCIService = (WCMContentInitializerService)container.getComponentInstanceOfType(WCMContentInitializerService.class); WCIService.start(); applySystemSession(); } public void tearDown() throws Exception { super.tearDown(); } }
1,526
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UtilsTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/deployment/UtilsTest.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.deployment; import java.io.*; import java.util.*; import javax.jcr.*; import javax.jcr.query.*; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.testing.BaseCommonsTestCase; import org.exoplatform.component.test.*; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.services.compress.CompressData; import org.exoplatform.services.deployment.plugins.XMLDeploymentPluginTest; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; /** * Created by The eXo Platform SAS Author : eXoPlatform exo@exoplatform.com May * 18, 2012 */ @ConfiguredBy({ @ConfigurationUnit(scope = ContainerScope.ROOT, path = "conf/test-root-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/portal/commons-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/test-portal-configuration.xml") }) public class UtilsTest extends BaseCommonsTestCase { private static final Log LOG = ExoLogger.getLogger(XMLDeploymentPluginTest.class); protected final String REPO_NAME = "repository"; protected final String WORKSPACE_NAME = "portal-test"; protected PortalContainer container; protected RepositoryService repositoryService; protected Session session; protected Node root; private static final String ROOT_SQL_QUERY = "select * from mix:versionable order by exo:dateCreated DESC"; private static final String VERSION_SQL_QUERY = "select * from mix:versionable where jcr:path like '$0/%' " + "order by exo:dateCreated DESC"; private static final String DOC_VIEW = "docview"; private static final String SYS_VIEW = "sysview"; private static final int CREATE_NEW_BEHAVIOR = 0; public void setUp() throws Exception { System.setProperty("exo.test.random.name", "" + Math.random()); super.setUp(); begin(); container = PortalContainer.getInstance(); repositoryService = getService(RepositoryService.class); configurationManager = getService(ConfigurationManager.class); session = repositoryService.getCurrentRepository().getSystemSession(WORKSPACE_NAME); root = session.getRootNode(); System.setProperty("gatein.email.domain.url", "http://localhost:8080"); } /** * Testcase for Utils.makePath() * * @throws Exception */ public void testMakePath() throws Exception { String level2RelPath = "level1/level2"; Node level2 = Utils.makePath(root, level2RelPath, "nt:folder"); assertEquals(level2.getPath(), root.getPath() + level2RelPath); String level3RelPath = "level1/level2/level3"; Node level3 = Utils.makePath(root, level3RelPath, "nt:folder"); assertEquals(level3.getPath(), root.getPath() + level3RelPath); String level5RelPath = "level4/level5"; Node level5 = Utils.makePath(level3, level5RelPath, "nt:folder"); assertEquals(level5.getPath(), level3.getPath() + "/" + level5RelPath); Map<String, String[]> permissionsMap = new HashMap<String, String[]>(); permissionsMap.put("*:/platform/web-contributors", new String[] { "read", "addNode", "setProperty" }); String level7RelPath = "level6/level7"; Node level7 = Utils.makePath(level5, level7RelPath, "nt:folder", permissionsMap); assertEquals(level7.getPath(), level5.getPath() + "/" + level7RelPath); } /** * Testcase for: - Utils.getMapImportHistory() - Utils.processImportHistory() * Description: In this testcase, we will try to export data from node * testFolder, and then import it into sandbox Input JCR data structure: * /[root] |--> testFolder | |-----> subFolder1 | |-----> subFolder2 | |--> * sandbox Expected result: /[root] |--> testFolder | |-----> subFolder1 | * |-----> subFolder2 | |--> sandbox |--> testFolder |-----> subFolder1 * |-----> subFolder2 * * @throws Exception */ public void testImportNode() throws Exception { /******************************************* * Create JCR data structure for test case * *******************************************/ Node testFolder = root.addNode("testFolder", "nt:folder"); Node sandbox = root.addNode("sandbox", "nt:folder"); testFolder.addNode("subFolder1", "nt:folder"); testFolder.addNode("subFolder2", "nt:folder"); session.save(); if (!testFolder.isNodeType("mix:versionable")) { testFolder.addMixin("mix:versionable"); } session.save(); /***************** * Export data * *****************/ File exportData = exportNode(testFolder, SYS_VIEW); // export test folder to // XML File zippedVersionHistory = exportVersionHistory(testFolder, SYS_VIEW); // export // version // history // of // test // folder /****************************** * Import data into sandbox * ******************************/ // import XML data session.importXML(sandbox.getPath(), new BufferedInputStream(new TempFileInputStream(exportData)), CREATE_NEW_BEHAVIOR); session.save(); // import version history data Map<String, String> mapHistoryValue = Utils.getMapImportHistory(new BufferedInputStream(new FileInputStream(zippedVersionHistory))); Utils.processImportHistory(sandbox, new BufferedInputStream(new TempFileInputStream(zippedVersionHistory)), mapHistoryValue); /***************** * Assertion * *****************/ assertTrue(sandbox.hasNode("testFolder")); Node importedNode = sandbox.getNode("testFolder"); assertTrue(importedNode.isNodeType("mix:versionable")); assertTrue(importedNode.hasNode("subFolder1")); assertTrue(importedNode.hasNode("subFolder2")); } /** * Export a node to XML with document view or system view * * @param currentNode * @param format specify the format used to exported the current JCR node, it * could be docview format or sysview format * @return XML file * @throws Exception */ private File exportNode(Node currentNode, String format) throws Exception { // the file which will keep the exported data of the node. File tempExportedFile = getExportedFile(format, ".xml"); // do export OutputStream out = new BufferedOutputStream(new FileOutputStream(tempExportedFile)); if (format.equals(DOC_VIEW)) { session.exportDocumentView(currentNode.getPath(), out, false, false); } else { session.exportSystemView(currentNode.getPath(), out, false, false); } out.flush(); out.close(); return tempExportedFile; } /** * Export version history data of a node * * @param currentNode * @param format specify the format used to exported version history it could * be docview format or sysview format * @return a zipped file containing the version history data of a node * @throws Exception */ private File exportVersionHistory(Node currentNode, String format) throws Exception { QueryResult queryResult = getVersionableChidren(currentNode); NodeIterator queryIter = queryResult.getNodes(); CompressData zipService = new CompressData(); OutputStream out = null; InputStream in = null; List<File> lstExporedFile = new ArrayList<File>(); File exportedFile = null; File zipFile = null; File propertiesFile = getExportedFile("mapping", ".properties"); OutputStream propertiesBOS = new BufferedOutputStream(new FileOutputStream(propertiesFile)); InputStream propertiesBIS = new BufferedInputStream(new TempFileInputStream(propertiesFile)); while (queryIter.hasNext()) { exportedFile = getExportedFile("data", ".xml"); lstExporedFile.add(exportedFile); out = new BufferedOutputStream(new FileOutputStream(exportedFile)); in = new BufferedInputStream(new TempFileInputStream(exportedFile)); Node node = queryIter.nextNode(); String historyValue = getHistoryValue(node); propertiesBOS.write(historyValue.getBytes()); propertiesBOS.write('\n'); if (format.equals(DOC_VIEW)) session.exportDocumentView(node.getVersionHistory().getPath(), out, false, false); else session.exportSystemView(node.getVersionHistory().getPath(), out, false, false); out.flush(); zipService.addInputStream(node.getUUID() + ".xml", in); } if (currentNode.isNodeType("mix:versionable")) { exportedFile = getExportedFile("data", ".xml"); lstExporedFile.add(exportedFile); out = new BufferedOutputStream(new FileOutputStream(exportedFile)); in = new BufferedInputStream(new TempFileInputStream(exportedFile)); String historyValue = getHistoryValue(currentNode); propertiesBOS.write(historyValue.getBytes()); propertiesBOS.write('\n'); if (format.equals(DOC_VIEW)) session.exportDocumentView(currentNode.getVersionHistory().getPath(), out, false, false); else session.exportSystemView(currentNode.getVersionHistory().getPath(), out, false, false); out.flush(); zipService.addInputStream(currentNode.getUUID() + ".xml", in); } propertiesBOS.flush(); zipService.addInputStream("mapping.properties", propertiesBIS); zipFile = getExportedFile("data", ".zip"); in = new BufferedInputStream(new FileInputStream(zipFile)); out = new BufferedOutputStream(new FileOutputStream(zipFile)); out.flush(); zipService.createZip(out); return zipFile; } /** * Get the version history information of a node * * @param node * @return * @throws Exception */ private String getHistoryValue(Node node) throws Exception { String versionHistory = node.getProperty("jcr:versionHistory").getValue().getString(); String baseVersion = node.getProperty("jcr:baseVersion").getValue().getString(); Value[] predecessors = node.getProperty("jcr:predecessors").getValues(); StringBuilder historyValue = new StringBuilder(); StringBuilder predecessorsBuilder = new StringBuilder(); for (Value value : predecessors) { if (predecessorsBuilder.length() > 0) predecessorsBuilder.append(","); predecessorsBuilder.append(value.getString()); } historyValue.append(node.getUUID()) .append("=") .append(versionHistory) .append(";") .append(baseVersion) .append(";") .append(predecessorsBuilder.toString()); return historyValue.toString(); } /** * get the versionable nodes of the current node * * @param currentNode * @return * @throws RepositoryException */ private QueryResult getVersionableChidren(Node currentNode) throws RepositoryException { QueryManager queryManager = currentNode.getSession().getWorkspace().getQueryManager(); String queryStatement = ""; if (currentNode.getPath().equals("/")) { queryStatement = ROOT_SQL_QUERY; } else { queryStatement = StringUtils.replace(VERSION_SQL_QUERY, "$0", currentNode.getPath()); } Query query = queryManager.createQuery(queryStatement, Query.SQL); return query.execute(); } private File getExportedFile(String prefix, String suffix) throws IOException { return File.createTempFile(prefix.concat(UUID.randomUUID().toString()), suffix); } protected void tearDown() throws Exception { super.tearDown(); } /** * This input stream will remove the file which it connects to when the * virtual machine terminates * * @author hailt */ private static class TempFileInputStream extends FileInputStream { private final File file; public TempFileInputStream(File file) throws FileNotFoundException { super(file); this.file = file; try { file.deleteOnExit(); } catch (Exception e) { // ignore me } } } }
13,111
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
XMLDeploymentPluginTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/deployment/plugins/XMLDeploymentPluginTest.java
package org.exoplatform.services.deployment.plugins; import javax.jcr.*; import org.exoplatform.commons.testing.BaseCommonsTestCase; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ObjectParameter; import org.exoplatform.services.deployment.DeploymentDescriptor; import org.exoplatform.services.deployment.DeploymentDescriptor.Target; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; /* * JUnit test suite for org.exoplatform.services.deployment.plugins.XMLDeploymentPluginTest, * based on BaseCommonsTestCase in commons/testing, * that has configuration for PortalContainer and services, JCR services. * The test cases will verify the feature of deployment data defined by XML file format to JCR. */ public class XMLDeploymentPluginTest extends BaseCommonsTestCase { private static final Log LOG = ExoLogger.getLogger(XMLDeploymentPluginTest.class); protected final String REPO_NAME = "repository"; protected final String WORKSPACE_NAME = "portal-test"; protected PortalContainer container; protected RepositoryService repositoryService; private SessionProvider sessionProvider; private XMLDeploymentPlugin plugin; private DeploymentDescriptor depDesc; protected Session session; protected Node root; /* * Set up before each test case. * @see org.exoplatform.commons.testing.BaseCommonsTestCase#setUp() */ public void setUp() throws Exception { // Set random folder name for JCR index, swap & lock System.setProperty("exo.test.random.name", "" + Math.random()); super.setUp(); begin(); container = PortalContainer.getInstance(); repositoryService = getService(RepositoryService.class); configurationManager = getService(ConfigurationManager.class); session = repositoryService.getCurrentRepository().getSystemSession(WORKSPACE_NAME); root = session.getRootNode(); System.setProperty("gatein.email.domain.url", "http://localhost:8080"); // Session Provider SessionProviderService serv = (SessionProviderService) container.getComponentInstanceOfType(SessionProviderService.class); this.sessionProvider = serv.getSystemSessionProvider(null); // Initial parameters for XML Deployment Plugin this.depDesc = new DeploymentDescriptor(); depDesc.setCleanupPublication(true); // Target to JCR local Target target = new Target(); target.setNodePath(root.getPath()); target.setRepository(REPO_NAME); target.setWorkspace(WORKSPACE_NAME); depDesc.setTarget(target); ObjectParameter objParam = new ObjectParameter(); objParam.setName("Test case XML Deployment Plugin"); objParam.setObject(depDesc); InitParams initParams = new InitParams(); initParams.addParam(objParam); // Create XML Deployment plugin instance this.plugin = new XMLDeploymentPlugin(initParams, configurationManager, repositoryService); } /* * Test case of deployment XML data in format of system view (SV), without history data. */ public void testDeploySVFormat() throws Exception { // Test case context String sourcePath = "classpath:/conf/data/ImagesSVFormat.xml"; String rootDataName = "GlobalImages"; int expectedChildNodes = 1; // Set details Deployment-Description: without history data setDepDesc(sourcePath, null); // Deploy this.plugin.deploy(sessionProvider); // Test data Session session = sessionProvider.getSession(WORKSPACE_NAME, repositoryService.getRepository(REPO_NAME)); Node rootJCR = session.getRootNode(); Node rootData = rootJCR.getNode(rootDataName); assertNotNull(rootData); NodeIterator nodes = rootData.getNodes(); assertEquals(nodes.getSize(), expectedChildNodes); } /* * Test case of deployment XML data in format of system view (SV), with history data. */ public void testDeploySVFormatWithHistory() throws Exception { //Test case context String sourcePath = "classpath:/conf/data/dataSV.xml"; String vHistoryPath = "classpath:/conf/data/dataSV_versionHistory"; String rootDataName = "testFolder"; int expectedChildNodes = 2; // Set details Deployment Description: with history data setDepDesc(sourcePath, vHistoryPath); // Deploy data this.plugin.deploy(sessionProvider); // Test data Session session = sessionProvider.getSession(WORKSPACE_NAME, repositoryService.getRepository(REPO_NAME)); Node rootJCR = session.getRootNode(); Node rootData = rootJCR.getNode(rootDataName); assertNotNull(rootData); NodeIterator nodes = rootData.getNodes(); assertEquals(nodes.getSize(), expectedChildNodes); } /* * Tear down after each test case. * @see org.exoplatform.commons.testing.BaseCommonsTestCase#tearDown() */ public void tearDown() throws Exception { // Remove existing data NodeIterator iter = root.getNodes(); while (iter.hasNext()) { Node node = iter.nextNode(); node.remove(); } session.save(); super.tearDown(); } //======== PRIVATE FUNCTIONS =====// /* * Set details for Deployment-Description following each test case context. */ private void setDepDesc(String source, String historyPath) { this.depDesc.setSourcePath(source); this.depDesc.setVersionHistoryPath(historyPath); } }
5,875
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
LinkUtilsTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/test/LinkUtilsTest.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.ecm.dms.test; import org.exoplatform.services.cms.link.LinkUtils; import org.exoplatform.test.BasicTestCase; /** * Created by The eXo Platform SAS * Author : eXoPlatform * nicolas.filotto@exoplatform.com * 6 avr. 2009 */ public class LinkUtilsTest extends BasicTestCase { public void testEvaluatePath() { assertEquals(LinkUtils.evaluatePath("//"), "/"); assertEquals(LinkUtils.evaluatePath("///"), "/"); assertEquals(LinkUtils.evaluatePath("/a/"), "/a"); assertEquals(LinkUtils.evaluatePath("/////a////"), "/a"); assertEquals(LinkUtils.evaluatePath("/.."), "/"); assertEquals(LinkUtils.evaluatePath("/."), "/."); assertEquals(LinkUtils.evaluatePath("/.a"), "/.a"); assertEquals(LinkUtils.evaluatePath("/../.."), "/"); assertEquals(LinkUtils.evaluatePath("/.././.."), "/"); assertEquals(LinkUtils.evaluatePath("/./../.."), "/"); assertEquals(LinkUtils.evaluatePath("/a/.."), "/"); assertEquals(LinkUtils.evaluatePath("/./a/.."), "/"); assertEquals(LinkUtils.evaluatePath("/a/."), "/a/."); assertEquals(LinkUtils.evaluatePath("/a/../a"), "/a"); assertEquals(LinkUtils.evaluatePath("/a/./b"), "/a/b"); assertEquals(LinkUtils.evaluatePath("/a//.//b//"), "/a/b"); assertEquals(LinkUtils.evaluatePath("/a/b/../c/.."), "/a"); assertEquals(LinkUtils.evaluatePath("/a/b/../c/../.."), "/"); assertEquals(LinkUtils.evaluatePath("/a/b/../c/../../.."), "/"); } }
2,241
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
MockNodeFinderImpl.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/test/MockNodeFinderImpl.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.ecm.dms.test; import javax.jcr.Item; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.link.NodeFinder; import org.exoplatform.services.cms.link.impl.NodeFinderImpl; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.app.SessionProviderService; /** * Created by The eXo Platform SARL * Author : Hoang Van Hung * hunghvit@gmail.com * Jun 10, 2010 */ public class MockNodeFinderImpl extends NodeFinderImpl { private final RepositoryService repositoryService_; private final LinkManager linkManager_; public MockNodeFinderImpl(RepositoryService repositoryService, LinkManager linkManager){ super(repositoryService, linkManager); this.repositoryService_ = repositoryService; this.linkManager_ = linkManager; } /** * {@inheritDoc} */ @Deprecated public Item getItem(String repository, String workspace, String absPath, boolean giveTarget) throws PathNotFoundException, RepositoryException { return getItemGiveTargetSys(repository, workspace, absPath, giveTarget, false); } /** * {@inheritDoc} */ @Deprecated public Item getItemGiveTargetSys(String repository, String workspace, String absPath, boolean giveTarget, boolean system) throws PathNotFoundException, RepositoryException { if (!absPath.startsWith("/")) throw new IllegalArgumentException(absPath + " isn't absolute path"); Session session = getSession(repositoryService_.getCurrentRepository(), workspace); return getItemTarget(session, absPath, giveTarget, system); } /** * {@inheritDoc} */ @Deprecated public Item getItem(String repository, String workspace, String absPath) throws PathNotFoundException, RepositoryException { return getItem(repository, workspace, absPath, false); } /** * {@inheritDoc} */ @Deprecated public Item getItemSys(String repository, String workspace, String absPath, boolean system) throws PathNotFoundException, RepositoryException { return getItemGiveTargetSys(repository, workspace, absPath, false, system); } }
3,518
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestSymLink.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/test/TestSymLink.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.ecm.dms.test; import javax.jcr.Item; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.exoplatform.services.wcm.BaseWCMTestCase; import org.junit.Test; /** * Created by The eXo Platform SARL * Author : Hoang Van Hung * hunghvit@gmail.com * Mar 15, 2009 */ public class TestSymLink extends BaseWCMTestCase { MockNodeFinderImpl nodeFinder; /** * Set up for testing * * In Collaboration workspace * * /---TestTreeNode * | * |_____A1 * | |___C1___C1_1___C1_2___C1_3(exo:symlink -->C2) * | |___C2___C2_2___D(exo:symlink -->C3) * | |___C3___C4 * | * |_____A2 * | |___B2(exo:symlink --> C1) * | * |_____A3(exo:symlink --> C2) * * In System workspace * /------TestTreeNode2 * | * |_____M1___M2(exo:symlink --> C1) * | * |_____N1___N2(exo:symlink --> C2) * | * |_____O1(exo:symlink --> no node) * | * |_____P1 * */ public void setUp() throws Exception { super.setUp(); nodeFinder = (MockNodeFinderImpl) container.getComponentInstanceOfType(MockNodeFinderImpl.class); System.out.println("========== Create root node ========"); applyUserSession("john", "gtn", COLLABORATION_WS); createTreeInCollaboration(); createTreeInSystem(); } /** * Create tree in System workspace * * @throws Exception */ public void createTreeInSystem() throws Exception { // Session session = repository.login(credentials, SYSTEM_WS); Session sessionSys = sessionProviderService_.getSystemSessionProvider(null).getSession(SYSTEM_WS, repository); Node rootNode = sessionSys.getRootNode(); Node testNode = rootNode.addNode("TestTreeNode2"); Node nodeM1 = testNode.addNode("M1"); Node nodeN1 = testNode.addNode("N1"); testNode.addNode("p1"); // Session collaboSession = repository.login(credentials, COLLABORATION_WS); Node nodeC1 = (Node) session.getItem("/TestTreeNode/A1/C1"); addSymlink("M2", nodeM1, nodeC1); Node nodeC2 = (Node) session.getItem("/TestTreeNode/A1/C2"); addSymlink("N2", nodeN1, nodeC2); Node nodeO1 = testNode.addNode("O1","exo:symlink"); nodeO1.setProperty("exo:workspace",COLLABORATION_WS); nodeO1.setProperty("exo:uuid", "12"); nodeO1.setProperty("exo:primaryType", "nt:folder"); /* Set node and properties for Node B1 */ session.save(); } public void addSymlink(String name, Node src, Node target) throws Exception { Node node = src.addNode(name,"exo:symlink"); if (target.hasProperty("jcr:uuid")) { System.out.println("\n\n jcr uuid = " + target.getProperty("jcr:uuid").getValue()); } else { target.addMixin("mix:referenceable"); } node.setProperty("exo:workspace",COLLABORATION_WS); node.setProperty("exo:uuid",target.getProperty("jcr:uuid").getString()); node.setProperty("exo:primaryType",target.getPrimaryNodeType().getName()); } public void createTreeInCollaboration() throws Exception { Node rootNode = session.getRootNode(); Node testNode = rootNode.addNode("TestTreeNode"); Node nodeA1 = testNode.addNode("A1"); Node nodeA2 = testNode.addNode("A2"); Node nodeB2 = nodeA2.addNode("B2","exo:symlink"); Node nodeC1 = nodeA1.addNode("C1"); Node nodeC1_1 = nodeC1.addNode("C1_1"); Node nodeC1_2 = nodeC1_1.addNode("C1_2"); Node nodeC1_3 = nodeC1_2.addNode("C1_3","exo:symlink"); Node nodeC2 = nodeA1.addNode("C2"); Node nodeC3 = nodeA1.addNode("C3"); nodeC3.addNode("C4"); Node nodeC2_2 = nodeC2.addNode("C2_2"); Node nodeD = nodeC2_2.addNode("D", "exo:symlink"); if (nodeC1.hasProperty("jcr:uuid")) { System.out.println("\n\n jcr uuid = " +nodeC1.getProperty("jcr:uuid").getValue()); } else { nodeC1.addMixin("mix:referenceable"); nodeC2.addMixin("mix:referenceable"); nodeC3.addMixin("mix:referenceable"); } nodeB2.setProperty("exo:workspace",COLLABORATION_WS); nodeB2.setProperty("exo:uuid",nodeC1.getProperty("jcr:uuid").getString()); nodeB2.setProperty("exo:primaryType",nodeC1.getPrimaryNodeType().getName()); nodeD.setProperty("exo:workspace",COLLABORATION_WS); nodeD.setProperty("exo:uuid",nodeC3.getProperty("jcr:uuid").getString()); nodeD.setProperty("exo:primaryType",nodeC3.getPrimaryNodeType().getName()); Node nodeA3 = testNode.addNode("A3","exo:symlink"); nodeA3.setProperty("exo:workspace", COLLABORATION_WS); nodeA3.setProperty("exo:uuid", nodeC2.getProperty("jcr:uuid").getString()); nodeA3.setProperty("exo:primaryType",nodeC2.getPrimaryNodeType().getName()); nodeC1_3.setProperty("exo:workspace", COLLABORATION_WS); nodeC1_3.setProperty("exo:uuid", nodeC2.getProperty("jcr:uuid").getString()); nodeC1_3.setProperty("exo:primaryType",nodeC2.getPrimaryNodeType().getName()); System.out.println("Get path = " + nodeA3.getPath()); /* Set node and properties for Node B1 */ session.save(); } /** * Browser tree of one node * * @param node */ private void browserTree(Node node, int iLevel) throws RepositoryException { if (iLevel != 0) { for (int j = 0; j < iLevel; j++) { System.out.print("\t"); System.out.print("|"); } System.out.println("-------" + node.getName()); } else System.out.println(node.getName()); for (int j = 0; j < iLevel; j++) { System.out.print("\t"); System.out.print("|"); } System.out.print("\t"); System.out.println("|"); for (int j = 0; j < iLevel; j++) { System.out.print("\t"); System.out.print("|"); } System.out.print("\t"); System.out.println("|"); /* Get all nodes */ NodeIterator iterNode = node.getNodes(); /* Browser node */ Node tempNode; /* * for(int j = 0; j < iLevel + 1; j++){ System.out.print("\t"); } */ while (iterNode.hasNext()) { for (int j = 0; j < iLevel; j++) { System.out.print("\t"); System.out.print("|"); } System.out.print("\t"); System.out.println("|"); for (int j = 0; j < iLevel; j++) { System.out.print("\t"); System.out.print("|"); } System.out.print("\t"); System.out.println("|"); tempNode = iterNode.nextNode(); this.browserTree(tempNode, iLevel + 1); } } public void testGetPath() throws Exception { String path = "/"; String expectedPath = "/"; System.out.println("\n\n Path input : " + path); System.out.println("\n\n expected Path : " + expectedPath); Node node = (Node)nodeFinder.getItem(REPO_NAME, COLLABORATION_WS, path); System.out.println("Path out put: "+ node.getPath()); assertEquals(expectedPath,node.getPath()); } public void testGetPath1() throws Exception { String path = "/TestTreeNode"; String expectedPath = "/TestTreeNode"; System.out.println("\n\n Path input : " + path); System.out.println("\n\n expected Path : " + expectedPath); Node node = (Node)nodeFinder.getItem(REPO_NAME, COLLABORATION_WS, path); System.out.println("Path out put: "+ node.getPath()); assertEquals(expectedPath,node.getPath()); } public void testGetPath2() throws Exception { String path = "/TestTreeNode/A2/B2"; String expectedPath = "/TestTreeNode/A2/B2"; System.out.println("\n\n Path input : " + path); System.out.println("\n\n expected Path : " + expectedPath); Item item = nodeFinder.getItem(REPO_NAME, COLLABORATION_WS, path); System.out.println("Path output: "+ item.getPath()); assertEquals(expectedPath,item.getPath()); } public void testGetPath3() throws Exception { String path = "/TestTreeNode/A3/C2_2/D/C4"; String expectedPath = "/TestTreeNode/A1/C3/C4"; System.out.println("\n\n Path input : " + path); System.out.println("\n\n expected Path : " + expectedPath); Node node = (Node)nodeFinder.getItem(REPO_NAME, COLLABORATION_WS, path); System.out.println("Path output: "+ node.getPath()); assertEquals(expectedPath,node.getPath()); } public void testGetPath4() throws Exception { String path = "/TestTreeNode/A2/B2/C1_1/C1_2/C1_3/C2_2/D"; String expectedPath = "/TestTreeNode/A1/C2/C2_2/D"; System.out.println("\n\n Path input : " + path); System.out.println("\n\n expected Path : " + expectedPath); Node node = (Node)nodeFinder.getItem(REPO_NAME, COLLABORATION_WS, path); System.out.println("Path output: "+ node.getPath()); assertEquals(expectedPath,node.getPath()); } public void testGetPath5() throws Exception { String path = "/TestTreeNode/A1/C1/C1_1/C1_2/C1_3/C2_2/D/C4"; String expectedPath = "/TestTreeNode/A1/C3/C4"; System.out.println("\n\n Path input : " + path); System.out.println("\n\n expected Path : " + expectedPath); Node node = (Node)nodeFinder.getItem(REPO_NAME, COLLABORATION_WS, path); System.out.println("Path output: "+ node.getPath()); assertEquals(expectedPath,node.getPath()); } // public void testGetPathInOtherWorkspace1() throws Exception { // String path = "/TestTreeNode2/M1/M2/jcr:uuid"; // String expectedPath = "/TestTreeNode/A1/C1/jcr:uuid"; // System.out.println("\n\n Path input : " + path); // System.out.println("\n\n expected Path : " + expectedPath); // Item item = nodeFinder.getItemSys(REPO_NAME, SYSTEM_WS, path, true); // System.out.println("Path output: "+ item.getPath()); // assertEquals(expectedPath, item.getPath()); // } // // public void testGetPathInOtherWorkspace2() throws Exception { // String path = "/TestTreeNode2/N1/N2/C2_2/D/C4"; // String expectedPath = "/TestTreeNode/A1/C3/C4"; // System.out.println("\n\n Path input : " + path); // System.out.println("\n\n expected Path : " + expectedPath); // Node node = (Node)nodeFinder.getItemSys(REPO_NAME, SYSTEM_WS, path, true); // System.out.println("Path output: "+ node.getPath()); // assertEquals(expectedPath,node.getPath()); // } // // /** // * Test get path with target node is in other workspace // * // */ // // public void testGetPathInOtherWorkspace3() throws Exception { // String path = "/TestTreeNode2/M1/M2/C1_1/C1_2/C1_3/C2_2/D/C4"; // String expectedPath = "/TestTreeNode/A1/C3/C4"; // System.out.println("\n\n Path input : " + path); // System.out.println("\n\n expected Path : " + expectedPath); // Node node = (Node)nodeFinder.getItemSys(REPO_NAME, SYSTEM_WS, path, true); // System.out.println("Path output: "+ node.getPath()); // assertEquals(expectedPath,node.getPath()); // } @Test public void testGetInvalidPath1() throws Exception { String path = "/TestTreeNode/A2/D"; System.out.println("\n\n Path input : " + path); try { Node node = (Node)nodeFinder.getItem(REPO_NAME, COLLABORATION_WS, path); System.out.println("Path output: "+ node.getPath()); } catch (PathNotFoundException e) {} } public void testGetInvalidPath2() throws Exception { String path = "/TestTreeNode/A2/B2/C2"; System.out.println("\n\n Path input : " + path); try { Node node = (Node)nodeFinder.getItem(REPO_NAME, COLLABORATION_WS, path); System.out.println("Path output: "+ node.getPath()); } catch (PathNotFoundException e) {} } /** * Test with target Node is remove: Throws PathNotFoundException */ public void testGetInvalidPath3() throws Exception { String path = "/TestTreeNode2/O1"; System.out.println("\n\n Path input : " + path); try { Node node = (Node) nodeFinder.getItem(REPO_NAME, SYSTEM_WS, path); System.out.println("Path output: "+ node.getPath()); } catch (PathNotFoundException e) {} } public void testGetInvalidPath4() throws Exception { String path = "/TestTreeNode2/O1/C2_2"; System.out.println("\n\n Path input : " + path); try { Node node = (Node) nodeFinder.getItemSys(REPO_NAME, SYSTEM_WS, path, true); System.out.println("Path output: " + node.getPath()); } catch (PathNotFoundException e) {} } public void testGetInvalidWorkspace() throws Exception { try { Node node = (Node) nodeFinder.getItem(REPO_NAME, SYSTEM_WS + "12", "/"); System.out.println("Path output: " + node.getPath()); } catch (RepositoryException e) {} } public void testGetInvalidRepository() throws Exception { try { Node node = (Node) nodeFinder.getItem(REPO_NAME + "12", SYSTEM_WS, "/"); System.out.println("Path output: " + node.getPath()); } catch (RepositoryException e) {} } public void tearDown() throws Exception { Node root; try { System.out.println("\n\n -----------Teadown-----------------"); root = session.getRootNode(); root.getNode("TestTreeNode").remove(); root.save(); root = session.getRootNode(); root.getNode("TestTreeNode2").remove(); root.save(); } catch (PathNotFoundException e) { } super.tearDown(); } }
14,470
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestRelationsService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/relation/TestRelationsService.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.ecm.dms.relation; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.Value; import org.exoplatform.services.cms.relations.RelationsService; import org.exoplatform.services.wcm.BaseWCMTestCase; /** * Created by The eXo Platform SARL * June 09, 2009 */ public class TestRelationsService extends BaseWCMTestCase { private RelationsService relationsService; private static final String RELATION_MIXIN = "exo:relationable"; private static final String RELATION_PROP = "exo:relation"; public void setUp() throws Exception { super.setUp(); relationsService = (RelationsService) container.getComponentInstanceOfType(RelationsService.class); applySystemSession(); } /** * Test method: RelationsServiceImpl.init() * Input: repository The name of repository * Expect: Initial the root of relation node and its sub node * @throws Exception */ public void testInit() throws Exception { } /** * Test method: RelationsServiceImpl.addRelation() * Input: node Specify the node wants to remove a relation * relationPath The path of relation * repository The name of repository * Expect: Removes the relation to the given node * @throws Exception */ public void testAddRelation() throws Exception { Node root = session.getRootNode(); Node aaa = root.addNode("AAA"); Node bbb = root.addNode("BBB"); session.save(); relationsService.addRelation(aaa, bbb.getPath(), COLLABORATION_WS); assertTrue(aaa.isNodeType(RELATION_MIXIN)); Value[] values = aaa.getProperty(RELATION_PROP).getValues(); Node relatedNode = session.getNodeByUUID(values[0].getString()); assertEquals(bbb.getPath(), relatedNode.getPath()); } /** * Test method: RelationsServiceImpl.hasRelations() * Input: node Specify the node wants to check relation * Expect: Returns true is the given node has relation * @throws Exception */ public void testHasRelations() throws Exception { Node root = session.getRootNode(); Node aaa = root.addNode("AAA"); Node bbb = root.addNode("BBB"); session.save(); relationsService.addRelation(aaa, bbb.getPath(), COLLABORATION_WS); assertTrue(relationsService.hasRelations(aaa)); assertFalse(relationsService.hasRelations(bbb)); } /** * Test method: RelationsServiceImpl.getRelations() * Input: node Specify the node wants to get all node relative to it * repository The name of repository * provider The SessionProvider object is used to managed Sessions * Expect: Return all node that has relation to the given node * @throws Exception */ public void testGetRelations() throws Exception { Node root = session.getRootNode(); Node aaa = root.addNode("AAA"); Node bbb = root.addNode("BBB"); Node ccc = root.addNode("CCC"); Node ddd = root.addNode("DDD"); session.save(); relationsService.addRelation(aaa, bbb.getPath(), COLLABORATION_WS); relationsService.addRelation(aaa, ccc.getPath(), COLLABORATION_WS); List<Node> listRelation = relationsService.getRelations(aaa, sessionProviderService_.getSystemSessionProvider(null)); List<String> relationPathList = new ArrayList<String>(); for (Node relation : listRelation) { relationPathList.add(relation.getPath()); } assertTrue(relationPathList.contains(bbb.getPath())); assertTrue(relationPathList.contains(ccc.getPath())); assertFalse(relationPathList.contains(ddd.getPath())); } /** * Test method: RelationsServiceImpl.removeRelation() * Input: node Specify the node wants to remove a relation * relationPath The path of relation * repository The name of repository * Expect: Removes the relation to the given node * @throws Exception */ public void testRemoveRelation() throws Exception { Node root = session.getRootNode(); Node aaa = root.addNode("AAA"); Node bbb = root.addNode("BBB"); Node ccc = root.addNode("CCC"); Node ddd = root.addNode("DDD"); session.save(); relationsService.addRelation(aaa, bbb.getPath(), COLLABORATION_WS); relationsService.addRelation(aaa, ccc.getPath(), COLLABORATION_WS); relationsService.addRelation(aaa, ddd.getPath(), COLLABORATION_WS); List<Node> listBeforeRemove = relationsService.getRelations(aaa, sessionProviderService_.getSystemSessionProvider(null)); List<String> pathBeforeRemove = new ArrayList<String>(); for (Node relation : listBeforeRemove) { pathBeforeRemove.add(relation.getPath()); } assertTrue(pathBeforeRemove.contains(bbb.getPath())); assertTrue(pathBeforeRemove.contains(ccc.getPath())); assertTrue(pathBeforeRemove.contains(ddd.getPath())); relationsService.removeRelation(aaa, "/DDD"); List<Node> listAfterRemove = relationsService.getRelations(aaa, sessionProviderService_.getSystemSessionProvider(null)); List<String> pathAfterRemove = new ArrayList<String>(); for (Node relation : listAfterRemove) { pathAfterRemove.add(relation.getPath()); } assertTrue(pathAfterRemove.contains(bbb.getPath())); assertTrue(pathAfterRemove.contains(ccc.getPath())); assertFalse(pathAfterRemove.contains(ddd.getPath())); } /** * Clean all node for testing */ public void tearDown() throws Exception { Node root = session.getRootNode(); String[] paths = new String[] {"AAA", "BBB", "CCC", "DDD"}; for (String path : paths) { if (root.hasNode(path)) { root.getNode(path).remove(); } } session.save(); super.tearDown(); } }
6,649
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestThumbnailService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/thumbnail/TestThumbnailService.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.ecm.dms.thumbnail; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.nio.file.Files; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; import javax.imageio.ImageIO; import javax.jcr.Node; import javax.jcr.Value; import javax.jcr.ValueFactory; import org.exoplatform.services.cms.thumbnail.ThumbnailService; import org.exoplatform.services.jcr.impl.core.NodeImpl; import org.exoplatform.services.thumbnail.ImageResizeService; import org.exoplatform.services.thumbnail.ImageResizeServiceImpl; import org.exoplatform.services.wcm.BaseWCMTestCase; import static org.junit.Assert.assertArrayEquals; /** * Created by The eXo Platform SARL * Author : Hoang Van Hung * hunghvit@gmail.com * Jun 20, 2009 */ public class TestThumbnailService extends BaseWCMTestCase { private ThumbnailService thumbnailService; private ImageResizeService imageResizeService; public void setUp() throws Exception { super.setUp(); imageResizeService = new ImageResizeServiceImpl(); thumbnailService = (ThumbnailService)container.getComponentInstanceOfType(ThumbnailService.class); applySystemSession(); } /** * Test method ThumbnailService.addThumbnailNode() * Input: Node test with no thumbnail node folder * Expect: Node with name = identifier of test node in ThumbnailService.EXO_THUMBNAILS_FOLDER node exists * @throws Exception */ public void testAddThumbnailNode1() throws Exception { Node test = session.getRootNode().addNode("test"); session.save(); assertFalse(test.getParent().hasNode(ThumbnailService.EXO_THUMBNAILS_FOLDER)); thumbnailService.addThumbnailNode(test); assertTrue(test.getParent().hasNode(ThumbnailService.EXO_THUMBNAILS_FOLDER)); Node thumbnailFoder = test.getParent().getNode(ThumbnailService.EXO_THUMBNAILS_FOLDER); String identifier = ((NodeImpl)test).getInternalIdentifier(); assertTrue(thumbnailFoder.hasNode(identifier)); } /** * Test method ThumbnailService.addThumbnailNode() * Input: Node test with thumbnail node folder * Expect: Node with name = identifier of test node in ThumbnailService.EXO_THUMBNAILS_FOLDER node exists * @throws Exception */ public void testAddThumbnailNode2() throws Exception { Node test = session.getRootNode().addNode("test"); test.getParent().addNode(ThumbnailService.EXO_THUMBNAILS_FOLDER, ThumbnailService.EXO_THUMBNAILS); session.save(); assertTrue(test.getParent().hasNode(ThumbnailService.EXO_THUMBNAILS_FOLDER)); thumbnailService.addThumbnailNode(test); assertTrue(test.getParent().hasNode(ThumbnailService.EXO_THUMBNAILS_FOLDER)); Node thumbnailFoder = test.getParent().getNode(ThumbnailService.EXO_THUMBNAILS_FOLDER); String identifier = ((NodeImpl)test).getInternalIdentifier(); assertTrue(thumbnailFoder.hasNode(identifier)); } /** * Test method ThumbnailService.getFlowImages() * Input: Add node test * Expect: return empty list images of node test * @throws Exception */ public void testGetFlowImages1() throws Exception { Node test = session.getRootNode().addNode("test"); session.save(); List<Node> lstFlowImages = thumbnailService.getFlowImages(test); assertEquals(0, lstFlowImages.size()); } /** * Test method ThumbnailService.getFlowImages() * Input: Add node test, add node childTest. getFlowImages of test * Expect: return list images of childTest node with one node name = identifier of childTest node * @throws Exception */ public void testGetFlowImages2() throws Exception { Node test = session.getRootNode().addNode("test"); Node childTest = test.addNode("childTest"); session.save(); Node thumbnail = thumbnailService.addThumbnailNode(childTest); thumbnail.hasProperty(ThumbnailService.BIG_SIZE); InputStream is = getClass().getResourceAsStream("/conf/dms/artifacts/images/ThumnailView.jpg"); Value contentValue = session.getValueFactory().createValue(is); thumbnail.setProperty(ThumbnailService.BIG_SIZE, contentValue); thumbnail.save(); session.save(); thumbnail.getPrimaryNodeType().getName(); thumbnail.hasProperty(ThumbnailService.BIG_SIZE); List<Node> lstFlowImages = thumbnailService.getFlowImages(test); String identifier = ((NodeImpl) childTest).getInternalIdentifier(); assertTrue(test.hasNode(ThumbnailService.EXO_THUMBNAILS_FOLDER)); Node thumbnailFolder = test.getNode(ThumbnailService.EXO_THUMBNAILS_FOLDER); assertTrue(thumbnailFolder.hasNode(identifier)); assertTrue(lstFlowImages.contains(childTest)); } /** * Test method ThumbnailService.getAllFileInNode() * Input: Add 2 node (file1 and file2) with node type = nt:file * Expect: List of 2 node file1 and file2 * @throws Exception */ public void testGetAllFileInNode() throws Exception { Node test = session.getRootNode().addNode("test"); session.save(); Node file1 = test.addNode("file1", "nt:file"); file1.addNode("jcr:content", "nt:resource"); Value contentValue = session.getValueFactory().createValue("test"); file1.getNode("jcr:content").setProperty("jcr:data", contentValue); file1.getNode("jcr:content").setProperty("jcr:mimeType", "text/xml"); file1.getNode("jcr:content").setProperty("jcr:lastModified", new GregorianCalendar()); Node file2 = test.addNode("file2", "nt:file"); file2.addNode("jcr:content", "nt:resource"); file2.getNode("jcr:content").setProperty("jcr:data", contentValue); file2.getNode("jcr:content").setProperty("jcr:mimeType", "text/xml"); file2.getNode("jcr:content").setProperty("jcr:lastModified", new GregorianCalendar()); test.save(); session.save(); List<Node> lstNode = thumbnailService.getAllFileInNode(test); assertEquals(2, lstNode.size()); assertTrue(lstNode.contains(file1)); assertTrue(lstNode.contains(file2)); } /** * Test method ThumbnailService.getFileNodesByType() * Input: Add 2 node (file1 and file2) with node type = nt:file * file1 has child node jcr:content with mimeType = text/xml * file1 has child node jcr:content with mimeType = text/html * Expect: with type = text/xml return list of 1 node (file1) * with type = text/xml return list of 1 node (file2) * @throws Exception */ public void testGetFileNodesByType() throws Exception { Node test = session.getRootNode().addNode("test"); session.save(); Node file1 = test.addNode("file1", "nt:file"); file1.addNode("jcr:content", "nt:resource"); Value contentValue = session.getValueFactory().createValue("test"); file1.getNode("jcr:content").setProperty("jcr:data", contentValue); file1.getNode("jcr:content").setProperty("jcr:mimeType", "text/xml"); file1.getNode("jcr:content").setProperty("jcr:lastModified", new GregorianCalendar()); Node file2 = test.addNode("file2", "nt:file"); file2.addNode("jcr:content", "nt:resource"); file2.getNode("jcr:content").setProperty("jcr:data", contentValue); file2.getNode("jcr:content").setProperty("jcr:mimeType", "text/html"); file2.getNode("jcr:content").setProperty("jcr:lastModified", new GregorianCalendar()); test.save(); session.save(); List<Node> lstNode1 = thumbnailService.getFileNodesByType(test, "text/xml"); assertEquals(1, lstNode1.size()); assertTrue(lstNode1.contains(file1)); assertEquals(lstNode1.get(0), file1); List<Node> lstNode2 = thumbnailService.getFileNodesByType(test, "text/html"); assertEquals(1, lstNode2.size()); assertTrue(lstNode2.contains(file2)); assertEquals(lstNode2.get(0), file2); } /** * Test method ThumbnailService.addThumbnailImage() * Input: Node: thumbnail, resource /conf/dms/artifacts/images/ThumnailView.jpg, size = ThumbnailService.SMALL_SIZE * Expect: data in property exo:smallSize of thumbmail node is resource with height*width = 32x32 * @throws Exception */ public void testAddThumbnailImage() throws Exception { Node test = session.getRootNode().addNode("test"); session.save(); Node childTest = thumbnailService.addThumbnailNode(test); File file = new File(getClass().getClassLoader().getResource("conf/dms/artifacts/images/ThumnailView.jpg").getFile()); byte [] imageContent = Files.readAllBytes(file.toPath()); Value value = session.getValueFactory().createValue(new ByteArrayInputStream(imageResizeService.scaleImage(imageContent, 32, 32, false, false))); thumbnailService.addThumbnailImage(childTest, ImageIO.read(getClass().getResource("/conf/dms/artifacts/images/ThumnailView.jpg").openStream()), ThumbnailService.SMALL_SIZE); assertNotNull(value); } /** * Test method ThumbnailService.getThumbnailImage() * Input: add thumbnail image to childTest node with resource = /conf/dms/artifacts/images/ThumnailView.jpg, size = ThumbnailService.SMALL_SIZE * Expect: property exo:smallSize contains data of resource = /conf/dms/artifacts/images/ThumnailView.jpg * @throws Exception */ public void testGetThumbnailImage() throws Exception { Node test = session.getRootNode().addNode("test"); assertNull(thumbnailService.getThumbnailImage(test, "exo:smallSize")); Node childTest = thumbnailService.addThumbnailNode(test); thumbnailService.addThumbnailImage(childTest, ImageIO.read(getClass().getResourceAsStream("/conf/dms/artifacts/images/ThumnailView.jpg")), ThumbnailService.SMALL_SIZE); assertNotNull(childTest.getProperty(ThumbnailService.SMALL_SIZE).getValue()); } /** * Test method ThumbnailService.createSpecifiedThumbnail() * Input: resource = /conf/dms/artifacts/images/ThumnailView.jpg, mimeType = image/jpeg, node = test * Output: thumbnail node has property exo:smallSize contains data of resource * /conf/dms/artifacts/images/ThumnailView.jpg which is scale by size = 32*32 * @throws Exception */ public void testCreateSpecifiedThumbnail() throws Exception { Node test = session.getRootNode().addNode("test"); thumbnailService.createSpecifiedThumbnail(test, ImageIO.read(getClass().getResourceAsStream("/conf/dms/artifacts/images/ThumnailView.jpg")), ThumbnailService.SMALL_SIZE); Node thumbnail = thumbnailService.getThumbnailNode(test); assertNotNull(thumbnail.getProperty(ThumbnailService.SMALL_SIZE).getValue()); } /** * Test method ThumbnailService.createThumbnailImage() * Input: resource = /conf/dms/artifacts/images/ThumnailView.jpg, mimeType = image/jpeg, node = test * Output: thumbnail node has 3 property exo:smallSize, exo:midiumSize, exo:bigSize contain data of resource * /conf/dms/artifacts/images/ThumnailView.jpg which is scale by size = 32*32, 64*64, 300*300 respectively * @throws Exception */ public void testCreateThumbnailImage() throws Exception { Node test = session.getRootNode().addNode("test"); InputStream is = getClass().getResource("/conf/dms/artifacts/images/ThumnailView.jpg").openStream(); thumbnailService.createThumbnailImage(test, ImageIO.read(is), "image/jpeg"); Node thumbnail = thumbnailService.getThumbnailNode(test); assertNotNull(thumbnail.getProperty(ThumbnailService.SMALL_SIZE).getValue().getStream()); assertNotNull(thumbnail.getProperty(ThumbnailService.MEDIUM_SIZE).getValue()); assertNotNull(thumbnail.getProperty(ThumbnailService.BIG_SIZE).getValue()); } /** * Test method ThumbnailService.processThumbnailList() * Input: List child node, 3 in 4 node are nt:file node type, data in nt:file has mimeType = image/jpeg * binary data = /conf/dms/artifacts/images/ThumnailView.jpg, propertyName = SMALL_SIZE * Output: Create thumbnail node for each node in list, each node has property = SMALL_SIZE * with binary data = /conf/dms/artifacts/images/ThumnailView.jpg * @throws Exception */ public void testProcessThumbnailList() throws Exception { Node test = session.getRootNode().addNode("test2"); Node child1 = test.addNode("child1", "nt:file"); child1.addNode("jcr:content", "nt:resource"); ValueFactory valueFactory = session.getValueFactory(); child1.getNode("jcr:content").setProperty("jcr:data", valueFactory.createValue(getClass().getResourceAsStream("/conf/dms/artifacts/images/ThumnailView.jpg"))); child1.getNode("jcr:content").setProperty("jcr:mimeType", "image/jpeg"); child1.getNode("jcr:content").setProperty("jcr:lastModified", new GregorianCalendar()); Node child2 = test.addNode("child2", "nt:file"); child2.addNode("jcr:content", "nt:resource"); valueFactory = session.getValueFactory(); child2.getNode("jcr:content").setProperty("jcr:data", valueFactory.createValue(getClass().getResourceAsStream("/conf/dms/artifacts/images/ThumnailView.jpg"))); child2.getNode("jcr:content").setProperty("jcr:mimeType", "image/jpeg"); child2.getNode("jcr:content").setProperty("jcr:lastModified", new GregorianCalendar()); Node child3 = test.addNode("child3", "nt:file"); child3.addNode("jcr:content", "nt:resource"); child3.getNode("jcr:content").setProperty("jcr:data", valueFactory.createValue(getClass().getResourceAsStream("/conf/dms/artifacts/images/ThumnailView.jpg"))); child3.getNode("jcr:content").setProperty("jcr:mimeType", "image/jpeg"); child3.getNode("jcr:content").setProperty("jcr:lastModified", new GregorianCalendar()); Node child4 = test.addNode("child4"); List<Node> lstNode = new ArrayList<Node>(); lstNode.add(child1); lstNode.add(child2); lstNode.add(child3); lstNode.add(child4); session.save(); thumbnailService.processThumbnailList(lstNode, ThumbnailService.SMALL_SIZE); assertTrue(session.itemExists("/test2/" + ThumbnailService.EXO_THUMBNAILS_FOLDER)); Node thumbnailsFolder = (Node)session.getItem("/test2/" + ThumbnailService.EXO_THUMBNAILS_FOLDER); assertTrue(thumbnailsFolder.hasNode(((NodeImpl)child1).getInternalIdentifier())); assertTrue(thumbnailsFolder.hasNode(((NodeImpl)child2).getInternalIdentifier())); assertTrue(thumbnailsFolder.hasNode(((NodeImpl)child3).getInternalIdentifier())); assertTrue(thumbnailsFolder.hasNode(((NodeImpl)child4).getInternalIdentifier())); Node thumbnailImage1 = thumbnailsFolder.getNode(((NodeImpl)child1).getInternalIdentifier()); Node thumbnailImage2 = thumbnailsFolder.getNode(((NodeImpl)child2).getInternalIdentifier()); Node thumbnailImage3 = thumbnailsFolder.getNode(((NodeImpl)child3).getInternalIdentifier()); assertNotNull(thumbnailImage1.getProperty(ThumbnailService.SMALL_SIZE).getValue()); assertNotNull(thumbnailImage2.getProperty(ThumbnailService.SMALL_SIZE).getValue()); assertNotNull(thumbnailImage3.getProperty(ThumbnailService.SMALL_SIZE).getValue()); } /** * Test method ThumbnailService.getThumbnailNode() * Input: 1.test node * 2. add thumbnail node for test node * Output: 1. thumbnail of test node = null * 2. return thumbnail node of test node * @throws Exception */ public void testGetThumbnailNode() throws Exception { Node test = session.getRootNode().addNode("test"); session.save(); Node thumbnail = thumbnailService.getThumbnailNode(test); assertNull(thumbnail); thumbnailService.addThumbnailNode(test); thumbnail = thumbnailService.getThumbnailNode(test); assertNotNull(thumbnail); assertEquals(((NodeImpl)test).getInternalIdentifier(), thumbnail.getName()); } /** * Test method ThumbnailService.processRemoveThumbnail() * Input: test node whether or not thumbnail node exists * Output: Delete thumbnail node of test node if it exists * @throws Exception */ public void testProcessRemoveThumbnail() throws Exception { Node test = session.getRootNode().addNode("test"); session.save(); String identifier = ((NodeImpl)test).getInternalIdentifier(); thumbnailService.processRemoveThumbnail(test); assertFalse(session.itemExists("/" + ThumbnailService.EXO_THUMBNAILS_FOLDER + "/" + identifier)); thumbnailService.addThumbnailNode(test); assertTrue(session.itemExists("/" + ThumbnailService.EXO_THUMBNAILS_FOLDER + "/" + identifier)); thumbnailService.processRemoveThumbnail(test); assertFalse(session.itemExists("/" + ThumbnailService.EXO_THUMBNAILS_FOLDER + "/" + identifier)); } public void testCreateCustomThumbnail() throws Exception { byte[] imageContent = new byte[] { 0x12, 0x34, 0x56, 0x78 }; int targetWidth = 100; int targetHeight = 100; String mimeType1 = "image/gif"; String mimeType2 = "image/png"; byte[] expectedResult = new byte[] { 0x12, 0x34, 0x56, 0x78 }; byte[] result1 = thumbnailService.createCustomThumbnail(imageContent, targetWidth, targetHeight, mimeType1); byte[] result2 = thumbnailService.createCustomThumbnail(imageContent, targetWidth, targetHeight, mimeType2); assertArrayEquals(expectedResult, result1); assertArrayEquals(expectedResult, result2); } /** * Clean data */ public void tearDown() throws Exception { String[] paths = {"test2", "test", ThumbnailService.EXO_THUMBNAILS_FOLDER}; for (String path : paths) { if (session.getRootNode().hasNode(path)) { session.getRootNode().getNode(path).remove(); session.save(); } } session.logout(); super.tearDown(); } }
18,723
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestWatchDocumentService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/watchdocument/TestWatchDocumentService.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.ecm.dms.watchdocument; import java.util.Arrays; import java.util.List; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.Value; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeManager; import javax.jcr.nodetype.PropertyDefinition; import org.exoplatform.services.cms.watch.WatchDocumentService; import org.exoplatform.services.wcm.BaseWCMTestCase; /** * Created by eXo Platform * Author : Nguyen Manh Cuong * manhcuongpt@gmail.com * Jun 16, 2009 */ /** * Unit test for WatchDocumentService * Methods need to test: * 1. getNotificationType() method * 2. watthDocument() method * 3. unWatchDocument() method */ public class TestWatchDocumentService extends BaseWCMTestCase{ private final static String EXO_WATCHABLE_MIXIN = "exo:watchable"; private final static String EMAIL_WATCHERS_PROP = "exo:emailWatcher"; private final static String RSS_WATCHERS_PROP = "exo:rssWatcher"; private WatchDocumentService watchDocumentService = null; private Node test; public void setUp() throws Exception { super.setUp(); watchDocumentService = (WatchDocumentService) container.getComponentInstanceOfType(WatchDocumentService.class); applySystemSession(); test = session.getRootNode().addNode("Test"); session.save(); } /** * Test Method: getNotification() * Input: test node is not exo:watchable document * Expected: * Value of notification is -1. */ public void testGetNotificationType() throws Exception{ int notification = watchDocumentService.getNotificationType(test, "root"); assertEquals(-1, notification); } /** * Test Method: getNotification() * Input: type of notification for test node is email and rss. * Expected: * Value of notification is 0. */ public void testGetNotificationType1() throws Exception{ test.addMixin(EXO_WATCHABLE_MIXIN); session.save(); createMultipleProperty(test, "root", "root"); int notification = watchDocumentService.getNotificationType(test, "root"); assertEquals(0, notification); } /** * Test Method: getNotification() * Input: type of notification for test node is email * Expected: * Value of notification is 1. */ public void testGetNotificationType2() throws Exception{ test.addMixin(EXO_WATCHABLE_MIXIN); session.save(); createMultipleProperty(test, "root", "marry"); int notification = watchDocumentService.getNotificationType(test, "root"); assertEquals(1, notification); } /** * Test Method: getNotification() * Input: type of notification for test node is rss * Expected: * Value of notification is 2. */ public void testGetNotificationType3() throws Exception{ test.addMixin(EXO_WATCHABLE_MIXIN); session.save(); createMultipleProperty(test, "marry", "root"); int notification = watchDocumentService.getNotificationType(test, "root"); assertEquals(2, notification); } /** * Test Method: watchDocument() * Input: document node is not added exo:watchable mixinType, user: root will watch this document * Expected: * document is added exo:watchable mixinType * exo:emailWatch property of document node has value: root. */ public void testWatchDocument() throws Exception{ watchDocumentService.watchDocument(test, "root", 1); assertTrue(test.isNodeType(EXO_WATCHABLE_MIXIN)); Property pro = test.getProperty(EMAIL_WATCHERS_PROP); Value[] value = pro.getValues(); for(Value val : value){ assertEquals("root", val.getString()); } } /** * Test Method: watchDocument() * Input: document node is not added exo:watchable mixinType, * user: root will watch this document * Notification has value equal 2 * Expected: * document is added exo:watchable mixinType * document doesn't has exo:emailWatch property. */ public void testWatchDocument1() throws Exception{ watchDocumentService.watchDocument(test, "root", 2); assertTrue(test.isNodeType(EXO_WATCHABLE_MIXIN)); assertFalse(test.hasProperty(EMAIL_WATCHERS_PROP)); } /** * Test Method: watchDocument() * Input: document node follows exo:watchable mixinType, * user: root and marry will watch this document * Expected: * document is added exo:watchable mixinType * exo:emailWatch property of document node has value: root and marry. */ @SuppressWarnings("unchecked") public void testWatchDocument2() throws Exception{ watchDocumentService.watchDocument(test, "root", 1); watchDocumentService.watchDocument(test, "marry", 1); List watcher = Arrays.asList(new String[]{"root", "marry"}); Property pro = test.getProperty(EMAIL_WATCHERS_PROP); Value[] value = pro.getValues(); for(Value val : value){ assertTrue(watcher.contains(val.getString())); } } /** * Test Method: unwatchDocument() * Input: Document is watched by two user(root, marry) * Root user will be unwatched * Expected: * exo:emailWatch property of document node only has value: marry. */ @SuppressWarnings("unchecked") public void testUnWatchDocument() throws Exception { watchDocumentService.watchDocument(test, "root", 1); watchDocumentService.watchDocument(test, "marry", 1); watchDocumentService.unwatchDocument(test, "root", 1); Property pro = test.getProperty(EMAIL_WATCHERS_PROP); List watcher = Arrays.asList(new String[] { "marry" }); Value[] value = pro.getValues(); assertEquals(1, value.length); assertTrue(watcher.contains(value[0].getString())); assertFalse(value[0].equals("root")); } /** * Test Method: unwatchDocument() * Input: Document is watch by two user(root, marry) * Root user will be unwatched * Notification has value: 2 * Expected: * exo:emailWatch property of a document node has value: both root and marry. */ @SuppressWarnings("unchecked") public void testUnWatchDocument2() throws Exception{ watchDocumentService.watchDocument(test, "root", 1); watchDocumentService.watchDocument(test, "marry", 1); watchDocumentService.unwatchDocument(test, "root", 2); List watcher = Arrays.asList(new String[] {"root", "marry"}); Property pro = test.getProperty(EMAIL_WATCHERS_PROP); Value[] value = pro.getValues(); for (Value val : value) { assertTrue(watcher.contains(val.getString())); } assertEquals(2, value.length); } /** * Create multiple value property for node. * @param node * @param emailWatcherValue * @param rssWatcherValue * @throws Exception */ private void createMultipleProperty(Node node, String emailWatcherValue, String rssWatcherValue) throws Exception{ NodeTypeManager nodeTypeManager = session.getWorkspace().getNodeTypeManager(); NodeType nodeType = nodeTypeManager.getNodeType(EXO_WATCHABLE_MIXIN); for(PropertyDefinition def : nodeType.getDeclaredPropertyDefinitions()){ String proName = def.getName(); if(def.isMultiple() & proName.equals(EMAIL_WATCHERS_PROP)){ Value val = session.getValueFactory().createValue(emailWatcherValue); node.setProperty(EMAIL_WATCHERS_PROP, new Value[] {val}); } if(def.isMultiple() & proName.equals(RSS_WATCHERS_PROP)){ Value val = session.getValueFactory().createValue(rssWatcherValue); node.setProperty(RSS_WATCHERS_PROP, new Value[] {val}); } } session.save(); } /** * Clean data test */ public void tearDown() throws Exception { if (session.itemExists("/Test")) { test = session.getRootNode().getNode("Test"); test.remove(); session.save(); } super.tearDown(); } }
8,961
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestManageViewService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/view/TestManageViewService.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.ecm.dms.view; import java.util.ArrayList; import java.util.List; import javax.jcr.AccessDeniedException; import javax.jcr.Node; import javax.jcr.Session; 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.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.wcm.BaseWCMTestCase; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Created by The eXo Platform SARL * Author : Hoang Van Hung * hunghvit@gmail.com * Jun 18, 2009 */ public class TestManageViewService extends BaseWCMTestCase { ManageViewService manageViewService; NodeHierarchyCreator nodeHierarchyCreator; Session sessionDMS; private static final String VIEW_NODETYPE = "exo:view"; private static final String TAB_NODETYPE = "exo:tab"; protected final static String TEMPLATE_NODETYPE = "exo:template"; private String viewsPath; private String templatesPathEx; public void setUp() throws Exception { super.setUp(); manageViewService = (ManageViewService)container.getComponentInstanceOfType(ManageViewService.class); nodeHierarchyCreator = (NodeHierarchyCreator)container.getComponentInstanceOfType(NodeHierarchyCreator.class); viewsPath = nodeHierarchyCreator.getJcrPath(BasePath.CMS_VIEWS_PATH); templatesPathEx = nodeHierarchyCreator.getJcrPath(BasePath.ECM_EXPLORER_TEMPLATES); applySystemSession(); sessionDMS = sessionProviderService_.getSystemSessionProvider(null).getSession(DMSSYSTEM_WS, repository); } /** * Check data that is defined from test-taxonomies-configuration.xml file * Expect: All data is registered * @throws Exception */ private void checkInitData() throws Exception { List<?> buttons = manageViewService.getButtons(); assertTrue(buttons.size() > 0); assertTrue(buttons.contains("ManageAuditing")); assertTrue(buttons.contains("ManagePublications")); assertTrue(buttons.contains("ManageVersions")); assertTrue(buttons.contains("ViewNodeType")); assertTrue(buttons.contains("WatchDocument")); assertTrue(sessionDMS.itemExists(viewsPath)); assertTrue(sessionDMS.itemExists(templatesPathEx)); assertTrue(sessionDMS.itemExists(viewsPath + "/admin-view")); assertTrue(sessionDMS.itemExists(viewsPath + "/admin-view/Admin")); assertTrue(sessionDMS.itemExists(viewsPath + "/admin-view/Info")); assertTrue(sessionDMS.itemExists(viewsPath + "/admin-view/Actions")); assertTrue(sessionDMS.itemExists(viewsPath + "/admin-view/Collaboration")); assertTrue(sessionDMS.itemExists(viewsPath + "/anonymous-view")); assertTrue(sessionDMS.itemExists(viewsPath + "/anonymous-view/Actions")); } /** * Test ManageViewServiceImpl.init() * Check all data initiated from repository * @throws Exception */ public void testInit() throws Exception { manageViewService.init(); checkInitData(); } /** * Test ManageViewServiceImpl.addView() * Input: Add one view with tab to system: * name = templateTest, * permission = *:/platform/administrators, * path to template = /exo:ecm/views/templates/ecm-explorer/ListView * 2 tab: detail tab with 2 buttons: ViewNodeType,ViewContent; glide tab with one button: ViewNodeType * Output: Node view is registered with all component and properties defined above * @throws Exception */ public void testAddView() throws Exception { String name = "templateTest"; String permission = "*:/platform/administrators"; String template = "/ecm-explorer/SystemView.gtmpl"; Tab tab1 = new Tab(); Tab tab2 = new Tab(); tab1.setTabName("detail"); tab1.setButtons("ViewNodeType;ViewContent"); tab2.setTabName("glide"); tab2.setButtons("ViewNodeType"); List<Tab> lstTab = new ArrayList<Tab>(); lstTab.add(tab1); lstTab.add(tab2); manageViewService.addView(name, permission, template, lstTab); Node templateTest = (Node)sessionDMS.getItem(viewsPath + "/" + name); assertEquals(VIEW_NODETYPE, templateTest.getPrimaryNodeType().getName()); assertEquals(permission, templateTest.getProperty("exo:accessPermissions").getString()); assertEquals(template, templateTest.getProperty("exo:template").getString()); Node templateTestTab1 = templateTest.getNode("detail"); assertEquals(TAB_NODETYPE, templateTestTab1.getPrimaryNodeType().getName()); assertEquals("ViewNodeType;ViewContent", templateTestTab1.getProperty("exo:buttons").getString()); Node templateTestTab2 = templateTest.getNode("glide"); assertEquals(TAB_NODETYPE, templateTestTab2.getPrimaryNodeType().getName()); } /** * Test ManageViewServiceImpl.getViewByName() * Input: name of view: admin-view * Expect: Return node admin-view with node type = exo:view * @throws Exception */ public void testGetViewByName() throws Exception { Node adminView = manageViewService.getViewByName("admin-view", WCMCoreUtils.getSystemSessionProvider()); assertEquals(VIEW_NODETYPE, adminView.getPrimaryNodeType().getName()); } /** * Test ManageViewServiceImpl.getButtons() * Get all buttons that are registered */ public void testGetButtons() { //refer to testStart() method } /** * Test ManageViewServiceImpl.removeView() * Input: Remove one view anonymous-view * Expect: anonymous-view in viewsPath does not exist * @throws Exception */ public void testRemoveView() throws Exception { manageViewService.removeView("anonymous-view"); assertFalse(sessionDMS.itemExists(viewsPath + "/anonymous-view")); } /** * Test ManageViewServiceImpl.getAllViews() * Input: Get all views (after remove anonymous-view in testRemoveView method * Expect: Return 8 views (view total is 9 views) * @throws Exception */ public void testGetAllViews() throws Exception { List<ViewConfig> viewList = manageViewService.getAllViews(); assertNotNull(viewList.size()); } /** * Test ManageViewServiceImpl.hasView() * Input: admin-view, admin_view * Expect: 1. Return true with view name = admin-view in path = /exo:ecm/views/userviews in dms-system * 2. Return false with view name = admin_view in path = /exo:ecm/views/userviews in dms-system * @throws Exception */ public void testHasView() throws Exception { assertTrue(manageViewService.hasView("admin-view")); assertFalse(manageViewService.hasView("admin_view")); } /** * Test ManageViewServiceImpl.getTemplateHome() * Input: Path alias to template * Expect: Node in dms-system workspace * @throws Exception */ public void testGetTemplateHome() throws Exception { Node homeNode = manageViewService.getTemplateHome(BasePath.CMS_VIEWS_PATH, WCMCoreUtils.getSystemSessionProvider()); assertEquals("/exo:ecm/views/userviews", homeNode.getPath()); } /** * Test ManageViewServiceImpl.getAllTemplates() * Input: Get all template in alias path = ecmExplorerTemplates * Expect: Return 5 view template: SystemView, CoverFlow, IconView, ListView, ThumbnailsView * @throws Exception */ public void testGetAllTemplates() throws Exception { List<Node> lstNode = manageViewService.getAllTemplates(BasePath.ECM_EXPLORER_TEMPLATES, WCMCoreUtils.getSystemSessionProvider()); assertEquals(1, lstNode.size()); assertEquals("SystemView", lstNode.get(0).getName()); } /** * Test ManageViewServiceImpl.addTemplate() * Input: Add new template SimpleView, SystemView with data content is defined in variable * templateFile = "<%import org.exoplatform.ecm.webui.utils.Utils; " + "import org.exoplatform.web.application.Parameter;" + "import org.exoplatform.webui.core.UIRightClickPopupMenu;%>" + "<div id=$componentId></div>" * Expect: 2 new templates (SimpleView, SystemView) are added with property exo:templateFile is value of variable templateFile * @throws Exception */ public void testAddTemplate() throws Exception { String templateFile = "<%import org.exoplatform.ecm.webui.utils.Utils; " + "import org.exoplatform.web.application.Parameter;" + "import org.exoplatform.webui.core.UIRightClickPopupMenu;%>" + "<div id=$componentId></div>"; manageViewService.addTemplate("SimpleView", templateFile, templatesPathEx); Node simpleViewNode = (Node)sessionDMS.getItem(templatesPathEx + "/SimpleView"); assertEquals("nt:file", simpleViewNode.getPrimaryNodeType().getName()); assertEquals(templateFile, simpleViewNode.getNode("jcr:content").getProperty("jcr:data").getString()); manageViewService.removeTemplate(templatesPathEx + "/SimpleView"); } /** * Test add template with system session provider * @throws Exception */ public void testAddTemplate2() throws Exception { String templateFile = "<%import org.exoplatform.ecm.webui.utils.Utils; " + "import org.exoplatform.web.application.Parameter;" + "import org.exoplatform.webui.core.UIRightClickPopupMenu;%>" + "<div id=$componentId></div>"; manageViewService.addTemplate("SimpleView", templateFile, templatesPathEx, WCMCoreUtils.getSystemSessionProvider()); Node simpleViewNode = (Node) sessionDMS.getItem(templatesPathEx + "/SimpleView"); assertEquals("nt:file", simpleViewNode.getPrimaryNodeType().getName()); assertEquals(templateFile, simpleViewNode.getNode("jcr:content") .getProperty("jcr:data") .getString()); manageViewService.removeTemplate(templatesPathEx + "/SimpleView", WCMCoreUtils.getSystemSessionProvider()); } /** * Test add template with user session provider * expected result: AccessDeniedException * @throws Exception */ public void testAddTemplate3() throws Exception { applyUserSession("marry", "gtn",DMSSYSTEM_WS); String templateFile = "<%import org.exo platform.ecm.webui.utils.Utils; " + "import org.exoplatform.web.application.Parameter;" + "import org.exoplatform.webui.core.UIRightClickPopupMenu;%>" + "<div id=$componentId></div>"; try { manageViewService.addTemplate("SimpleView", templateFile, templatesPathEx, sessionProviderService_.getSessionProvider(null)); fail(); } catch (AccessDeniedException ade) { assertTrue(true); } } /** * Test ManageViewServiceImpl.removeTemplate() * Input: Remove template with name = /PathList in path templatesPathCb * Expect: Node with above path does not exist * @throws Exception */ public void testRemoveTemplate() throws Exception { String templateFile = "<%import org.exoplatform.ecm.webui.utils.Utils; " + "import org.exoplatform.web.application.Parameter;" + "import org.exoplatform.webui.core.UIRightClickPopupMenu;%>" + "<div id=$componentId></div>"; manageViewService.addTemplate("SimpleView", templateFile, templatesPathEx); manageViewService.removeTemplate(templatesPathEx + "/SimpleView"); assertFalse(sessionDMS.itemExists(templatesPathEx + "/SimpleView")); } /** * Test ManageViewServiceImpl.removeTemplate() Input: Remove template with * name = /PathList in path templatesPathCb Expect: Node with above path does * not exist * * @throws Exception */ public void testRemoveTemplate2() throws Exception { String templateFile = "<%import org.exoplatform.ecm.webui.utils.Utils; " + "import org.exoplatform.web.application.Parameter;" + "import org.exoplatform.webui.core.UIRightClickPopupMenu;%>" + "<div id=$componentId></div>"; manageViewService.addTemplate("SimpleView", templateFile, templatesPathEx, WCMCoreUtils.getSystemSessionProvider()); manageViewService.removeTemplate(templatesPathEx + "/SimpleView", WCMCoreUtils.getSystemSessionProvider()); assertFalse(sessionDMS.itemExists(templatesPathEx + "/SimpleView")); } public void testRemoveTemplate3() throws Exception { applyUserSession("marry", "gtn",DMSSYSTEM_WS); try { manageViewService.removeTemplate(templatesPathEx + "/SystemView", sessionProviderService_.getSessionProvider(null)); fail(); } catch (AccessDeniedException ade) { assertTrue(true); } } /** * test updateTemplate() method with system session provider * * @throws Exception */ public void testUpdateTemplate() throws Exception { String templateFile = "<%import org.exoplatform.ecm.webui.utils.Utils; " + "import org.exoplatform.web.application.Parameter;" + "import org.exoplatform.webui.core.UIRightClickPopupMenu;%>" + "<div id=$componentId></div>"; String updateTemplateFile = "<%import org.exoplatform.ecm.webui.utils.Utils; " + "import org.exoplatform.web.application.Parameter;" + "import org.exoplatform.webui.core.UIRightClickPopupMenu;%>" + "<div id=$componentId></div>"; manageViewService.addTemplate("SimpleView", templateFile, templatesPathEx, WCMCoreUtils.getSystemSessionProvider()); Node simpleViewNode = (Node)sessionDMS.getItem(templatesPathEx + "/SimpleView"); assertEquals("nt:file", simpleViewNode.getPrimaryNodeType().getName()); assertEquals(templateFile, simpleViewNode.getNode("jcr:content") .getProperty("jcr:data") .getString()); manageViewService.updateTemplate("SimpleView", updateTemplateFile, templatesPathEx, WCMCoreUtils.getSystemSessionProvider()); simpleViewNode = (Node)sessionDMS.getItem(templatesPathEx + "/SimpleView"); assertEquals("nt:file", simpleViewNode.getPrimaryNodeType().getName()); assertEquals(updateTemplateFile, simpleViewNode.getNode("jcr:content") .getProperty("jcr:data") .getString()); manageViewService.removeTemplate(templatesPathEx + "/SimpleView", WCMCoreUtils.getSystemSessionProvider()); assertFalse(sessionDMS.itemExists(templatesPathEx + "/SimpleView")); } /** * test updateTemplate() method with user session provider * * @throws Exception */ public void testUpdateTemplate2() throws Exception { applyUserSession("marry", "gtn", DMSSYSTEM_WS); String updateTemplateFile = "<%import org.exoplatform.ecm.webui.utils.Utils; " + "import org.exoplatform.web.application.Parameter;" + "import org.exoplatform.webui.core.UIRightClickPopupMenu;%>" + "<div id=$componentId></div>"; try { manageViewService.updateTemplate("SystemView", updateTemplateFile, templatesPathEx, sessionProviderService_.getSessionProvider(null)); fail(); } catch (AccessDeniedException ade) { assertTrue(true); } } /** * Test ManageViewServiceImpl.addTab() * Input: Add more tab in icon-view: tab = My View, buttons = Zoom Out; Zoom In * Expect: One tab with these buttons are added, all tabs and buttons of old views does not change * @throws Exception */ public void testAddTab() throws Exception { Node nodeHome = (Node)sessionDMS.getItem(viewsPath + "/admin-view"); String buttons = "Zoom Out; Zoom In"; manageViewService.addTab(nodeHome, "My View", buttons); Node tab = (Node)sessionDMS.getItem(viewsPath + "/admin-view/My View"); assertEquals(TAB_NODETYPE, tab.getPrimaryNodeType().getName()); assertEquals(buttons, tab.getProperty("exo:buttons").getString()); tab = (Node)sessionDMS.getItem(viewsPath + "/admin-view/Actions"); assertEquals(TAB_NODETYPE, tab.getPrimaryNodeType().getName()); assertEquals("addFolder; addDocument; editDocument; upload; addSymLink", tab.getProperty("exo:buttons").getString().trim()); manageViewService.addTab(nodeHome, "Actions", buttons); tab = (Node)sessionDMS.getItem(viewsPath + "/admin-view/Actions"); assertEquals(TAB_NODETYPE, tab.getPrimaryNodeType().getName()); assertEquals(buttons, tab.getProperty("exo:buttons").getString()); } /** * Clean templateTest node */ public void tearDown() throws Exception { if (sessionDMS.itemExists(viewsPath + "/templateTest")) { Node templateTest = (Node)sessionDMS.getItem(viewsPath + "/templateTest"); templateTest.remove(); sessionDMS.save(); sessionDMS.logout(); } super.tearDown(); } }
18,949
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestApplicationTemplateManagerService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/view/TestApplicationTemplateManagerService.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.ecm.dms.view; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Session; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.views.ApplicationTemplateManagerService; import org.exoplatform.services.cms.views.PortletTemplatePlugin.PortletTemplateConfig; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.wcm.BaseWCMTestCase; /** * Created by The eXo Platform SARL * June 09, 2009 */ public class TestApplicationTemplateManagerService extends BaseWCMTestCase { private ApplicationTemplateManagerService appTemplateManagerService; private NodeHierarchyCreator nodeHierarchyCreator; private String basedApplicationTemplatesPath; private Session sessionDMS; public void setUp() throws Exception { super.setUp(); appTemplateManagerService = (ApplicationTemplateManagerService) container.getComponentInstanceOfType(ApplicationTemplateManagerService.class); nodeHierarchyCreator = (NodeHierarchyCreator) container.getComponentInstanceOfType(NodeHierarchyCreator.class); basedApplicationTemplatesPath = nodeHierarchyCreator.getJcrPath(BasePath.CMS_VIEWTEMPLATES_PATH); System.out.println("basedApplicationTemplatesPath :" + basedApplicationTemplatesPath); applySystemSession(); sessionDMS = sessionProviderService_.getSystemSessionProvider(null).getSession(DMSSYSTEM_WS, repository); } /** * Test ApplicationTemplateManagerServiceImpl.getAllManagedPortletName() * Input: repository String * The name of repository * Expect: Return The templates by category * @throws Exception */ public void testGetAllManagedPortletName() throws Exception { List<String> listTemplateManager = appTemplateManagerService.getAllManagedPortletName(REPO_NAME); assertEquals(0, listTemplateManager.size()); } // /** // * Test ApplicationTemplateManagerServiceImpl.getTemplatesByCategory() // * Input: repository String // * The name of repository // * portletName String // * The name of portlet // * category String // * The name of category // * sessionProvider SessionProvider // * Expect: Return The templates by category // * @throws Exception // */ // public void testGetTemplatesByCategory() throws Exception { // assertEquals(1, appTemplateManagerService.getTemplatesByCategory("content-browser", // "detail-document", sessionProviderService_.getSystemSessionProvider(null)).size()); // } // // /** // * Test ApplicationTemplateManagerServiceImpl.getTemplateByName() // * Input: repository String // * The name of repository // * portletName String // * The name of portlet // * category String // * The name of category // * templateName String // * The name of template // * sessionProvider SessionProvider // * Expect: Return the template by name // * @throws Exception // */ // public void testGetTemplateByName() throws Exception { // assertNotNull(appTemplateManagerService.getTemplateByName("content-browser", // "detail-document", "DocumentView", sessionProviderService_.getSystemSessionProvider(null))); // } // // /** // * Test ApplicationTemplateManagerServiceImpl.getTemplateByPath() // * Input: repository String // * The name of repository // * templatePath String // * The path of template // * sessionProvider SessionProvider // * Expect: Return template by path // * @throws Exception // */ // public void testGetTemplateByPath() throws Exception { // assertNotNull( // appTemplateManagerService.getTemplateByPath("/exo:ecm/views/templates/content-browser/detail-document/DocumentView", // sessionProviderService_.getSystemSessionProvider(null))); // } // // /** // * Test ApplicationTemplateManagerServiceImpl.addTemplate() // * Input: portletTemplateHome the portlet template home // * config the config // * Expect: Add the teamplate // * @throws Exception // */ // public void testAddTemplate() throws Exception { // Node portletTemplateHome = (Node) sessionDMS.getItem(basedApplicationTemplatesPath); // // PortletTemplateConfig config = new PortletTemplateConfig(); // ArrayList<String> accessPermissions = new ArrayList<String>(); // accessPermissions.add("*:/platform/administrators"); // config.setCategory("categoryA"); // config.setAccessPermissions(accessPermissions); // config.setEditPermissions(accessPermissions); // config.setTemplateName("HelloName"); // config.setTemplateData("Hello teamplate data"); // appTemplateManagerService.addTemplate(portletTemplateHome, config); // // assertNotNull(appTemplateManagerService.getTemplateByPath("/exo:ecm/views/templates/categoryA/HelloName", // sessionProviderService_.getSystemSessionProvider(null))); // // sessionDMS.getItem("/exo:ecm/views/templates/categoryA").remove(); // sessionDMS.save(); // } // // /** // * Test ApplicationTemplateManagerServiceImpl.removeTemplate() // * Input: repository String // * The name of repository // * portletName String // * The name of portlet // * catgory String // * The category // * templateName String // * The name of template // * sessionProvider SessionProvider // * Expect: Remove the teamplate // * @throws Exception // */ // public void testRemoveTemplate() throws Exception { // appTemplateManagerService.removeTemplate("content-browser", "detail-document", // "DocumentView", sessionProvider); // // assertEquals(0, appTemplateManagerService.getTemplatesByCategory("content-browser", // "detail-document", sessionProvider).size()); // } public void tearDown() throws Exception { Node nodeAppTemplate = (Node) sessionDMS.getItem(basedApplicationTemplatesPath); if (nodeAppTemplate.hasNode("categoryA")) { nodeAppTemplate.getNode("categoryA").remove(); } sessionDMS.save(); System.out.println("/exo:ecm/views/templates/ecm-explorer"); Node n = (Node)sessionDMS.getItem("/exo:ecm/views/templates/ecm-explorer"); for(NodeIterator iter = n.getNodes(); iter.hasNext();) System.out.println(iter.nextNode().getPath()); super.tearDown(); } }
7,554
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestCommentService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/comment/TestCommentService.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.ecm.dms.comment; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import org.exoplatform.services.cms.CmsService; import org.exoplatform.services.cms.JcrInputProperty; import org.exoplatform.services.cms.comments.CommentsService; import org.exoplatform.services.cms.i18n.MultiLanguageService; import org.exoplatform.services.wcm.BaseWCMTestCase; /** * Created by eXo Platform * Author : Nguyen Manh Cuong * manhcuongpt@gmail.com * Jun 9, 2009 */ /** * Unit test for CommentService * Methods need to test: * 1. addComment() method * 2. getComment() method */ public class TestCommentService extends BaseWCMTestCase { private final static String I18NMixin = "mix:i18n"; private final static String ARTICLE = "exo:article"; private final static String TITLE = "exo:title"; private final static String SUMMARY = "exo:summary"; private final static String TEXT = "exo:text"; private final static String COMMENT = "comments"; private final static String COMMENTOR = "exo:commentor"; private final static String COMMENTOR_EMAIL = "exo:commentorEmail"; private final static String COMMENTOR_MESSAGES = "exo:commentContent"; private final static String ANONYMOUS = "anonymous" ; private CommentsService commentsService = null; private MultiLanguageService multiLangService = null; public void setUp() throws Exception { super.setUp(); commentsService = container.getComponentInstanceOfType(CommentsService.class); multiLangService = container.getComponentInstanceOfType(MultiLanguageService.class); applyUserSession("john", "gtn", "collaboration"); initNode(); } /** * Test Method: addComment() * Input: * Test node: doesn't have multiple languages * doesn't have comment node * Expected: * Test node has comment node with 2 comments. */ public void testAddComment1() throws Exception{ Node test = session.getRootNode().addNode("test"); if(test.canAddMixin(I18NMixin)){ test.addMixin(I18NMixin); } session.save(); commentsService.addComment(test, "john", "john@explatform.com", null, "Hello", multiLangService.getDefault(test)); commentsService.addComment(test, "marry", "marry@explatform.com", null, "Thanks", multiLangService.getDefault(test)); NodeIterator iter = test.getNode(COMMENT).getNodes(); int i = 0; while (iter.hasNext()) { check(i++, iter.nextNode()); } } /** * Test Method: addComment() * Input: * Test Node: has multiple languages, NodeType of test node is "nt:file" * doesn't have comment node, NodeType of COMMENTS node is "nt:unstructured" * Expected Result: throws Exception */ public void testAddComment2() throws Exception { Node test = session.getRootNode().addNode("test1", "nt:file"); if(test.getPrimaryNodeType().getName().equals("nt:file")){ test.addNode("jcr:content", "nt:base"); } if(test.canAddMixin(I18NMixin)){ test.addMixin(I18NMixin); } session.save(); commentsService.addComment(test, "john", "john@explatform.com", null, "Hello", "jp"); NodeIterator iter = test.getNode(COMMENT).getNodes(); while (iter.hasNext()) { Node node = iter.nextNode(); assertEquals("john", node.getProperty(COMMENTOR).getString()); assertEquals("john@explatform.com", node.getProperty(COMMENTOR_EMAIL).getString()); assertEquals("Hello", node.getProperty(COMMENTOR_MESSAGES).getString()); } } /** * Test Method: addComment() * Input: * commenter's name is null. * Expected: * commenter's name will be assigned ANONYMOUS. */ public void testAddComment3() throws Exception{ Node test = session.getRootNode().getNode("test"); commentsService.addComment(test, null, "null@explatform.com", null, "Hello", multiLangService.getDefault(test)); commentsService.addComment(test, null, "abc@explatform.com", null, "Hello", multiLangService.getDefault(test)); List<Node> listCommentNode = commentsService.getComments(test, multiLangService.getDefault(test)); Collections.sort(listCommentNode, new NameComparator()); Iterator<Node> iter = listCommentNode.iterator(); while(iter.hasNext()){ assertEquals(ANONYMOUS, iter.next().getProperty(COMMENTOR).getString()); } } /** * Test Method: updateComment() * Input: * comment = Hello; * update comment = Ciao; * Expected: * Comment message is "Ciao" */ public void testUpdateComment() throws Exception{ Node test = session.getRootNode().getNode("test"); commentsService.addComment(test, "john", "john@explatform.com", null, "Hello", multiLangService.getDefault(test)); List<Node> nodes = commentsService.getComments(test, multiLangService.getDefault(test)); commentsService.updateComment(nodes.get(0), "Ciao"); nodes = commentsService.getComments(test, multiLangService.getDefault(test)); assertEquals("Ciao", nodes.get(0).getProperty(COMMENTOR_MESSAGES).getString()); } /** * Test Method: deleteComment() * Input: * comment for node with given email, comment message, commentor. * Expected: * Comment for node is delete */ public void testDeleteComment() throws Exception{ Node test = session.getRootNode().getNode("test"); commentsService.addComment(test, "john", "john@explatform.com", null, "Hello", multiLangService.getDefault(test)); List<Node> nodes = commentsService.getComments(test, multiLangService.getDefault(test)); assertEquals(1, nodes.size()); commentsService.deleteComment(nodes.get(0)); nodes = commentsService.getComments(test, multiLangService.getDefault(test)); assertEquals(0, nodes.size()); } /** * Test Method: getComments() * Input: Test node doesn't have languages node, so adding comment nodes will be set default * language. * Expected Result: * Get all comment nodes with default language. */ public void testGetComments1() throws Exception{ Node test = session.getRootNode().getNode("test"); commentsService.addComment(test, "john", "john@explatform.com", null, "Hello", multiLangService.getDefault(test)); commentsService.addComment(test, "marry", "marry@explatform.com", null, "Thanks", multiLangService.getDefault(test)); List<Node> listCommentNode = commentsService.getComments(test, multiLangService.getDefault(test)); Collections.sort(listCommentNode, new NameComparator()); Iterator<Node> iter = listCommentNode.iterator(); int i = 0; while(iter.hasNext()){ check(i++, iter.next()); } } /** * Test Method: getComments() * Input: Node has some comment nodes in "jp" node. * Expected Result: * Get all comment nodes with jp language. */ public void testGetComments2() throws Exception{ Node test = session.getRootNode().getNode("test"); multiLangService.addLanguage(test, createMapInput(), "jp", false); commentsService.addComment(test, "john", "john@explatform.com", null, "Hello", "jp"); commentsService.addComment(test, "marry", "marry@explatform.com", null, "Thanks", "jp"); List<Node> listCommentNode = commentsService.getComments(test, "jp"); Collections.sort(listCommentNode, new NameComparator()); Iterator<Node> iter = listCommentNode.iterator(); int i = 0; while(iter.hasNext()){ check(i++, iter.next()); } assertEquals(2, listCommentNode.size()); } /** * Create a map to use for MultilLanguageService */ private Map<String, JcrInputProperty> createMapInput() { Map<String, JcrInputProperty> map = new HashMap<String, JcrInputProperty>(); String titlePath = CmsService.NODE + "/" + TITLE; String summaryPath = CmsService.NODE + "/" + SUMMARY; String textPath = CmsService.NODE + "/" + TEXT; JcrInputProperty inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(CmsService.NODE); inputProperty.setValue("test"); map.put(CmsService.NODE, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(titlePath); inputProperty.setValue("this is title"); map.put(titlePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(summaryPath); inputProperty.setValue("this is summary"); map.put(summaryPath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(textPath); inputProperty.setValue("this is article content"); map.put(textPath, inputProperty); return map; } /** * This method will create a node which is added MultiLanguage */ private Node initNode() throws Exception{ Node test = session.getRootNode().addNode("test", ARTICLE); if (test.canAddMixin(I18NMixin)) { test.addMixin(I18NMixin); } test.setProperty(TITLE, "sport"); test.setProperty(SUMMARY, "report of season"); test.setProperty(TEXT, "sport is exciting"); session.save(); multiLangService.addLanguage(test, createMapInput(), "en", false); multiLangService.addLanguage(test, createMapInput(), "vi", false); return test; } /** * This method is used to check case test. * @param i * @param node node is tested * @throws Exception */ private void check(int i, Node node) throws Exception{ switch (i) { case 0: assertEquals("john", node.getProperty(COMMENTOR).getString()); assertEquals("john@explatform.com", node.getProperty(COMMENTOR_EMAIL).getString()); assertEquals("Hello", node.getProperty(COMMENTOR_MESSAGES).getString()); break; case 1: assertEquals("marry", node.getProperty(COMMENTOR).getString()); assertEquals("marry@explatform.com", node.getProperty(COMMENTOR_EMAIL).getString()); assertEquals("Thanks", node.getProperty(COMMENTOR_MESSAGES).getString()); break; default: break; } } public void tearDown() throws Exception { try { session.getRootNode().getNode("test").remove(); session.save(); } catch(Exception e) { return; } super.tearDown(); } class NameComparator implements Comparator<Node>{ public int compare(Node node1, Node node2){ try { return node1.getName().compareTo(node2.getName()); } catch (RepositoryException e) { return 0; } } } }
11,871
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
MockTaxonomyService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/taxonomy/MockTaxonomyService.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.ecm.dms.taxonomy; import java.util.ArrayList; 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 org.apache.commons.lang3.StringUtils; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.taxonomy.impl.TaxonomyServiceImpl; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Mar 16, 2011 * 6:05:28 PM */ public class MockTaxonomyService extends TaxonomyServiceImpl { private RepositoryService repositoryService_; private final String SQL_QUERY = "Select * from exo:taxonomyLink where jcr:path like '$0/%' and exo:uuid = '$1' " + "order by exo:dateCreated DESC"; private SessionProviderService providerService_; public MockTaxonomyService(InitParams initParams, SessionProviderService providerService, NodeHierarchyCreator nodeHierarchyCreator, RepositoryService repoService, LinkManager linkManager, DMSConfiguration dmsConfiguration) throws Exception { super(initParams, providerService, null, nodeHierarchyCreator, repoService, linkManager, dmsConfiguration); repositoryService_ = repoService; providerService_ = providerService; } public boolean hasCategories(Node node, String taxonomyName, boolean system) throws RepositoryException { List<Node> listCate = getCategories(node, taxonomyName, system); if (listCate != null && listCate.size() > 0) return true; return false; } public List<Node> getAllCategories(Node node, boolean system) throws RepositoryException { List<Node> listCategories = new ArrayList<Node>(); List<Node> allTrees = getAllTaxonomyTrees(system); for (Node tree : allTrees) { List<Node> categories = getCategories(node, tree.getName(), system); for (Node category : categories) listCategories.add(category); } return listCategories; } public List<Node> getCategories(Node node, String taxonomyName, boolean system) throws RepositoryException { List<Node> listCate = new ArrayList<Node>(); Session session = null; try { if (node.isNodeType("mix:referenceable")) { Node rootNodeTaxonomy = getTaxonomyTree(taxonomyName, system); if (rootNodeTaxonomy != null) { String sql = null; sql = StringUtils.replace(SQL_QUERY, "$0", rootNodeTaxonomy.getPath()); sql = StringUtils.replace(sql, "$1", node.getUUID()); session = providerService_.getSystemSessionProvider(null) .getSession(rootNodeTaxonomy.getSession() .getWorkspace() .getName(), repositoryService_.getCurrentRepository()); QueryManager queryManager = session.getWorkspace().getQueryManager(); Query query = queryManager.createQuery(sql, Query.SQL); QueryResult result = query.execute(); NodeIterator iterate = result.getNodes(); while (iterate.hasNext()) { Node parentCate = iterate.nextNode().getParent(); listCate.add(parentCate); } } } } catch (Exception e) { throw new RepositoryException(e); } return listCate; } }
4,766
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestTaxonomyService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/taxonomy/TestTaxonomyService.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.ecm.dms.taxonomy; import java.util.List; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.taxonomy.TaxonomyService; import org.exoplatform.services.cms.taxonomy.impl.TaxonomyAlreadyExistsException; import org.exoplatform.services.cms.taxonomy.impl.TaxonomyNodeAlreadyExistsException; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.wcm.BaseWCMTestCase; /** * Created by The eXo Platform SARL * Author : Hoang Van Hung * hunghvit@gmail.com * Jun 14, 2009 */ public class TestTaxonomyService extends BaseWCMTestCase { private TaxonomyService taxonomyService; private String definitionPath; private String storagePath; private LinkManager linkManage; private Session dmsSesssion; private NodeHierarchyCreator nodeHierarchyCreator; private MockTaxonomyService mockTaxonomyService; public void setUp() throws Exception { super.setUp(); taxonomyService = (TaxonomyService) container.getComponentInstanceOfType(TaxonomyService.class); mockTaxonomyService = (MockTaxonomyService) container.getComponentInstanceOfType(MockTaxonomyService.class); nodeHierarchyCreator = (NodeHierarchyCreator) container.getComponentInstanceOfType(NodeHierarchyCreator.class); linkManage = (LinkManager)container.getComponentInstanceOfType(LinkManager.class); definitionPath = nodeHierarchyCreator.getJcrPath(BasePath.TAXONOMIES_TREE_DEFINITION_PATH); storagePath = nodeHierarchyCreator.getJcrPath(BasePath.TAXONOMIES_TREE_STORAGE_PATH); applySystemSession(); applyUserSession("john", "gtn", COLLABORATION_WS); dmsSesssion = sessionProviderService_.getSystemSessionProvider(null).getSession(DMSSYSTEM_WS, repository); } /** * Test method TaxonomyService.addTaxonomyPlugin() * @see {@link # testInit()} */ public void testAddTaxonomyPlugin() throws Exception { } /** * Test method TaxonomyService.init() * Expect: Create system taxonomy tree in dms-system * @see {@link # testInit()} */ public void testInit() throws Exception { Node systemTreeDef = (Node) dmsSesssion.getItem(definitionPath + "/System"); Node systemTreeStorage = (Node) dmsSesssion.getItem(storagePath + "/System"); assertNotNull(systemTreeDef); assertNotNull(systemTreeStorage); assertEquals(systemTreeStorage, linkManage.getTarget(systemTreeDef, true)); } /** * Test method TaxonomyService.getTaxonomyTree(String repository, String taxonomyName, boolean system) * Expect: return System tree * @throws Exception */ public void testGetTaxonomyTree1() throws Exception { Node systemTree = taxonomyService.getTaxonomyTree("System",true); assertNotNull(systemTree); } /** * Test method TaxonomyService.addTaxonomyTree(Node taxonomyTree) * Input: add Doc as root tree node, get taxonomy tree with name = Doc * Expect: return Doc node * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException * @throws TaxonomyAlreadyExistsException */ public void testAddTaxonomyTree1() throws RepositoryException, TaxonomyNodeAlreadyExistsException, TaxonomyAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Doc", "root"); Node docTree = (Node)session.getItem("/MyDocuments/Doc"); taxonomyService.addTaxonomyTree(docTree); assertTrue(dmsSesssion.itemExists(definitionPath + "/Doc")); Node definitionDocTree = (Node)dmsSesssion.getItem(definitionPath + "/Doc"); assertEquals(docTree, linkManage.getTarget(definitionDocTree, true)); } /** * Test method TaxonomyService.addTaxonomyTree(Node taxonomyTree) with one tree has already existed * Input: add 2 tree node with same name * Expect: Fire TaxonomyAlreadyExistsException * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException */ public void testAddTaxonomyTree2() throws RepositoryException, TaxonomyNodeAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Doc", "root"); Node docTree = (Node)session.getItem("/MyDocuments/Doc"); try { taxonomyService.addTaxonomyTree(docTree); taxonomyService.addTaxonomyTree(docTree); } catch(TaxonomyAlreadyExistsException e) { System.out.println("The taxonomy tree with name '" +docTree.getName()+ "' already exist"); } } /** * Test method TaxonomyService.getTaxonomyTree(String repository, String taxonomyName) * Input: Create taxonomy tree Music * Expect: Node Music * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException * @throws TaxonomyAlreadyExistsException */ public void testGetTaxonomyTree2() throws RepositoryException, TaxonomyNodeAlreadyExistsException, TaxonomyAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Music", "root"); Node musicTree = (Node)session.getItem("/MyDocuments/Music"); taxonomyService.addTaxonomyTree(musicTree); assertTrue(dmsSesssion.itemExists(definitionPath + "/Music")); Node musicTreeDefinition = (Node)dmsSesssion.getItem(definitionPath + "/Music"); assertEquals(musicTree, linkManage.getTarget(musicTreeDefinition, true)); } /** * Test method TaxonomyService.getAllTaxonomyTrees(String repository) * Expect: return one tree in repository * @throws Exception */ public void testGetAllTaxonomyTrees2() throws Exception { assertEquals(1, taxonomyService.getAllTaxonomyTrees(true).size()); } /** * Test method TaxonomyService.getTaxonomyTree(String repository, String taxonomyName) * Input: Add 2 tree Miscellaneous and Shoes, remove Miscellaneous tree * Expect: Node Miscellaneous is remove in definition and real path * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException * @throws TaxonomyAlreadyExistsException */ public void testRemoveTaxonomyTree() throws RepositoryException, TaxonomyNodeAlreadyExistsException, TaxonomyAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Miscellaneous", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Miscellaneous", "Shoes", "root"); Node miscellaneous = (Node)session.getItem("/MyDocuments/Miscellaneous"); taxonomyService.addTaxonomyTree(miscellaneous); assertTrue(dmsSesssion.itemExists(definitionPath + "/Miscellaneous")); taxonomyService.removeTaxonomyTree("Miscellaneous"); assertFalse(dmsSesssion.itemExists(definitionPath + "/Miscellaneous")); assertFalse(dmsSesssion.itemExists("/MyDocuments/Miscellaneous")); } /** * Test method TaxonomyService.getAllTaxonomyTrees(String repository, boolean system) * Input: Add 2 taxonomy tree * Output: size of tree increase 2 trees * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException * @throws TaxonomyAlreadyExistsException */ public void testGetAllTaxonomyTrees1() throws RepositoryException, TaxonomyNodeAlreadyExistsException, TaxonomyAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Champion Leage", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Europa", "root"); Node championLeague = (Node)session.getItem("/MyDocuments/Europa"); Node europa = (Node)session.getItem("/MyDocuments/Champion Leage"); int totalTree1 = taxonomyService.getAllTaxonomyTrees().size(); taxonomyService.addTaxonomyTree(championLeague); taxonomyService.addTaxonomyTree(europa); int totalTree2 = taxonomyService.getAllTaxonomyTrees().size(); assertEquals(2, totalTree2 - totalTree1); } /** * Test method TaxonomyService.hasTaxonomyTree(String repository, String taxonomyName) * Input: Add one tree: Primera Liga * Expect: Return 2 taxonomy tree: System and Primera Liga tree * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException * @throws TaxonomyAlreadyExistsException */ public void testHasTaxonomyTree() throws RepositoryException, TaxonomyNodeAlreadyExistsException, TaxonomyAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Primera Liga", "root"); taxonomyService.addTaxonomyTree((Node)session.getItem("/MyDocuments/Primera Liga")); assertTrue(taxonomyService.hasTaxonomyTree("System")); assertTrue(taxonomyService.hasTaxonomyTree("Primera Liga")); } /** * Test method TaxonomyService.addTaxonomyNode() * Input: Add one taxonomy node below MyDocument * Expect: One node with primary node type = exo:taxonomy in path MyDocument/ * @throws TaxonomyNodeAlreadyExistsException * @throws RepositoryException */ public void testAddTaxonomyNode1() throws TaxonomyNodeAlreadyExistsException, RepositoryException { session.getRootNode().addNode("MyDocuments"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Sport", "root"); Node taxonomyNode = (Node)session.getItem("/MyDocuments/Sport"); assertTrue(taxonomyNode.isNodeType("exo:taxonomy")); } /** * Test method TaxonomyService.addTaxonomyNode() throws TaxonomyNodeAlreadyExistsException when Already exist node * Input: Add 2 taxonomy node below MyDocument path * Ouput: TaxonomyNodeAlreadyExistsException * @throws RepositoryException */ public void testAddTaxonomyNode2() throws RepositoryException { try { session.getRootNode().addNode("MyDocuments"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Sport", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Sport", "root"); } catch (TaxonomyNodeAlreadyExistsException e) { System.out.println("The category with name 'MyDocuments' already exist"); } } /** * Test method TaxonomyService.removeTaxonomyNode() * Input: Add and remove Tennis node * Expect: Node Tennis has not existed * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException */ public void testRemoveTaxonomyNode() throws RepositoryException, TaxonomyNodeAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Tennis", "root"); taxonomyService.removeTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Tennis"); assertFalse(session.itemExists("/MyDocuments/Tennis")); } /** * Test method TaxonomyService.moveTaxonomyNode() * Input: Move node to other place * Output: Node is moved * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException */ public void testMoveTaxonomyNode() throws RepositoryException, TaxonomyNodeAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Serie", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Budesliga", "root"); taxonomyService.moveTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Serie", "/Serie", "cut"); taxonomyService.moveTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Budesliga", "/Budesliga", "copy"); assertFalse(session.itemExists("/MyDocuments/Serie")); assertTrue(session.itemExists("/Serie")); assertTrue(session.itemExists("/Budesliga")); assertTrue(session.itemExists("/MyDocuments/Budesliga")); } /** * Test method TaxonomyService.addCategory() * Input: Add category for article node * Expect: one node with primary type exo:taxonomyLink is create in taxonomy tree * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException * @throws TaxonomyAlreadyExistsException */ public void testAddCategory() throws RepositoryException, TaxonomyNodeAlreadyExistsException, TaxonomyAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); Node article = session.getRootNode().addNode("Article"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Serie", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Serie", "A", "root"); Node rootTree = (Node)session.getItem("/MyDocuments/Serie"); session.save(); taxonomyService.addTaxonomyTree(rootTree); taxonomyService.addCategory(article, "Serie", "A", true); Node link = (Node)session.getItem("/MyDocuments/Serie/A/Article"); assertTrue(link.isNodeType("exo:taxonomyLink")); assertEquals(article, linkManage.getTarget(link)); } /** * Test method TaxonomyService.addCategories() * Input: add 2 categories in article node * Output: create 2 exo:taxonomyLink in each category * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException * @throws TaxonomyAlreadyExistsException */ public void testAddCategories() throws RepositoryException, TaxonomyNodeAlreadyExistsException, TaxonomyAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); Node article = session.getRootNode().addNode("Article"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Serie", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Serie", "A", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Serie", "B", "root"); Node rootTree = (Node)session.getItem("/MyDocuments/Serie"); taxonomyService.addTaxonomyTree(rootTree); taxonomyService.addCategories(article, "Serie", new String[] {"A", "B"}, true); Node link1 = (Node)session.getItem("/MyDocuments/Serie/A/Article"); Node link2 = (Node)session.getItem("/MyDocuments/Serie/B/Article"); assertTrue(link1.isNodeType("exo:taxonomyLink")); assertEquals(article, linkManage.getTarget(link1)); assertTrue(link2.isNodeType("exo:taxonomyLink")); assertEquals(article, linkManage.getTarget(link2)); } /** * Test method TaxonomyService.hasCategories() * Input: Add categories for article node * Expect: return true with category is added * return false with category that is not added * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException * @throws TaxonomyAlreadyExistsException */ public void testHasCategories() throws RepositoryException, TaxonomyNodeAlreadyExistsException, TaxonomyAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); Node article = session.getRootNode().addNode("Article"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Budesliga", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Serie", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Serie", "A", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Serie", "B", "root"); Node rootTree1 = (Node)session.getItem("/MyDocuments/Serie"); Node rootTree2 = (Node)session.getItem("/MyDocuments/Budesliga"); taxonomyService.addTaxonomyTree(rootTree1); taxonomyService.addTaxonomyTree(rootTree2); taxonomyService.addCategories(article, "Serie", new String[] {"A", "B"}, true); assertTrue(mockTaxonomyService.hasCategories(article, "Serie", true)); assertFalse(mockTaxonomyService.hasCategories(article, "Budesliga", true)); } /** * Test method TaxonomyService.getCategories() * Input: Add 2 categories to article node * Expect: Return 2 node of categories * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException * @throws TaxonomyAlreadyExistsException */ public void testGetCategories() throws RepositoryException, TaxonomyNodeAlreadyExistsException, TaxonomyAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); Node article = session.getRootNode().addNode("Article"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Stories", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Stories", "Homorous", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Stories", "Fairy", "root"); Node rootTree = (Node)session.getItem("/MyDocuments/Stories"); taxonomyService.addTaxonomyTree(rootTree); taxonomyService.addCategories(article, "Stories", new String[] {"Homorous", "Fairy"}, true); List<Node> lstNode = mockTaxonomyService.getCategories(article, "Stories", true); Node taxoLink1 = (Node)session.getItem("/MyDocuments/Stories/Homorous"); Node taxoLink2 = (Node)session.getItem("/MyDocuments/Stories/Fairy"); assertEquals(2, lstNode.size()); assertTrue(lstNode.contains(taxoLink1)); assertTrue(lstNode.contains(taxoLink2)); } /** * Test method TaxonomyService.getAllCategories() * Input: Add 3 categories to node * Expect: return 3 categories * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException * @throws TaxonomyAlreadyExistsException */ public void testGetAllCategories() throws RepositoryException, TaxonomyNodeAlreadyExistsException, TaxonomyAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); Node article = session.getRootNode().addNode("Article"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Culture", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "News", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments/News", "Politics", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Culture", "Foods", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Culture", "Art", "root"); Node rootTree1 = (Node)session.getItem("/MyDocuments/Culture"); Node rootTree2 = (Node)session.getItem("/MyDocuments/News"); taxonomyService.addTaxonomyTree(rootTree1); taxonomyService.addTaxonomyTree(rootTree2); taxonomyService.addCategories(article, "Culture", new String[] {"Foods", "Art"}, true); taxonomyService.addCategory(article, "News", "Politics", true); List<Node> lstNode = mockTaxonomyService.getAllCategories(article, true); Node taxoLink1 = (Node)session.getItem("/MyDocuments/Culture/Foods"); Node taxoLink2 = (Node)session.getItem("/MyDocuments/Culture/Art"); Node taxoLink3 = (Node)session.getItem("/MyDocuments/News/Politics"); assertEquals(3, lstNode.size()); assertTrue(lstNode.contains(taxoLink1)); assertTrue(lstNode.contains(taxoLink2)); assertTrue(lstNode.contains(taxoLink3)); } /** * Test method TaxonomyService.removeCategory() * Input: Remove categories of Article node * Expect: Return empty list * @throws RepositoryException * @throws TaxonomyNodeAlreadyExistsException * @throws TaxonomyAlreadyExistsException */ public void testRemoveCategory() throws RepositoryException, TaxonomyNodeAlreadyExistsException, TaxonomyAlreadyExistsException { session.getRootNode().addNode("MyDocuments"); Node article = session.getRootNode().addNode("Article"); session.save(); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "Education", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments", "News", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments/Education", "Language", "root"); taxonomyService.addTaxonomyNode(COLLABORATION_WS, "/MyDocuments/News", "Weather", "root"); Node rootTree1 = (Node)session.getItem("/MyDocuments/Education"); taxonomyService.addTaxonomyTree(rootTree1); Node rootTree2 = (Node)session.getItem("/MyDocuments/News"); taxonomyService.addTaxonomyTree(rootTree2); taxonomyService.addCategory(article, "Education", "Language", true); taxonomyService.addCategory(article, "News", "Weather", true); List<Node> lstNode = mockTaxonomyService.getAllCategories(article, true); assertEquals(2, lstNode.size()); taxonomyService.removeCategory(article, "Education", "Language", true); lstNode = mockTaxonomyService.getAllCategories(article, true); assertEquals(1, lstNode.size()); taxonomyService.removeCategory(article, "News", "Weather", true); lstNode = mockTaxonomyService.getAllCategories(article, true); assertEquals(0, lstNode.size()); } public void tearDown() throws Exception { List<Node> lstNode = taxonomyService.getAllTaxonomyTrees(true); for(Node tree : lstNode) { if (!tree.getName().equals("System")) taxonomyService.removeTaxonomyTree(tree.getName()); } for (String s : new String[] {"/Article","/MyDocuments"}) if (session.itemExists(s)) { session.getItem(s).remove(); session.save(); } super.tearDown(); } }
22,980
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestVotingService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/voting/TestVotingService.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.ecm.dms.voting; import java.io.IOException; import java.util.Arrays; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.Value; import org.exoplatform.services.cms.CmsService; import org.exoplatform.services.cms.JcrInputProperty; import org.exoplatform.services.cms.i18n.MultiLanguageService; import org.exoplatform.services.cms.voting.VotingService; import org.exoplatform.services.wcm.BaseWCMTestCase; /** * Created by eXo Platform * Author : Nguyen Manh Cuong * manhcuongpt@gmail.com * Jun 17, 2009 */ /** * Unit test for VotingService * Methods need to test * 1. Vote method * 2. Get Vote Total method */ public class TestVotingService extends BaseWCMTestCase { private final static String I18NMixin = "mix:i18n"; private final static String VOTEABLE = "mix:votable"; private final static String VOTER_PROP = "exo:voter"; private final static String VOTER_VOTEVALUE_PROP = "exo:voterVoteValues"; private final static String VOTE_TOTAL_PROP = "exo:voteTotal"; private final static String VOTING_RATE_PROP = "exo:votingRate"; private final static String VOTE_TOTAL_LANG_PROP = "exo:voteTotalOfLang"; private final static String ARTICLE = "exo:article"; private final static String CONTENT = "jcr:content"; private final static String MIMETYPE = "jcr:mimeType"; private final static String DATA = "jcr:data"; private final static String LASTMODIFIED = "jcr:lastModified"; private final static String FILE = "nt:file"; private final static String RESOURCE = "nt:resource"; private final static String TITLE = "exo:title"; private final static String SUMMARY = "exo:summary"; private final static String TEXT = "exo:text"; private VotingService votingService = null; private MultiLanguageService multiLanguageService = null; public void setUp() throws Exception { super.setUp(); votingService = (VotingService) container.getComponentInstanceOfType(VotingService.class); multiLanguageService = (MultiLanguageService) container.getComponentInstanceOfType(MultiLanguageService.class); applySystemSession(); } /** * Test Method: vote() * Input: Test node is set English default language, but not set MultiLanguage. * Voter: root, rate: 1.0, voter's language is default language. * marry, rate: 4.0, voter's language is default language. * john, rate: 5.0, voter's language is default language. * Expected: * Value of VOTER_PROP property of test node contains "root" * Vote total of test with default language = 3 * votingRate = (1 + 4 + 5)/3 = 3.33 */ @SuppressWarnings("unchecked") public void testVote() throws Exception { Node test = session.getRootNode().addNode("Test"); if (test.canAddMixin(I18NMixin)) { test.addMixin(I18NMixin); } session.save(); votingService.vote(test, 1, "root", multiLanguageService.getDefault(test)); votingService.vote(test, 4, "marry", multiLanguageService.getDefault(test)); votingService.vote(test, 5, "john", multiLanguageService.getDefault(test)); List voters = Arrays.asList(new String[] {"root", "marry", "john"}); Value[] value = test.getProperty(VOTER_VOTEVALUE_PROP).getValues(); for (int i = 0; i < 3; i++) { assertTrue(value[i].getString().startsWith(voters.get(i) + "")); } assertEquals(3, test.getProperty(VOTE_TOTAL_LANG_PROP).getValue().getLong()); assertEquals(3.33, test.getProperty(VOTING_RATE_PROP).getValue().getDouble()); } /** * Test Method: vote() * Input: test node is set English default language. * adding vote for test node by French * first vote : userName = null, rate = 3.0, language = "fr" * second vote: userName = null, rate = 1.0, language = "fr" * third vote : userName = null, rate = 4.0, language = "fr" * Expected: * user is not voter, value of VOTER_PRO doesn't exist. * votingRate = (3 + 1 + 4)/3 = 2.67 * total of vote: 3. */ public void testVote1() throws Exception { Node test = initNode(); votingService.vote(test, 3, null, "fr"); votingService.vote(test, 1, null, "fr"); votingService.vote(test, 4, null, "fr"); Node fr = multiLanguageService.getLanguage(test, "fr"); assertEquals(0, fr.getProperty(VOTER_VOTEVALUE_PROP).getValues().length); assertEquals(2.67, fr.getProperty(VOTING_RATE_PROP).getValue().getDouble()); assertEquals(3, fr.getProperty(VOTE_TOTAL_LANG_PROP).getValue().getLong()); } /** * Test Method: vote() * Input: Test node is set default language not equals voter's language * In this case: voter's language is fr * Example * first vote : root, rate: 2.0, language = fr, * second vote: root, rate: 3.0, language = fr, * third vote : root, rate: 4.0, language = fr * Expected: * Voter that uses fr language is "root", "marry", "john" * Total of vote of French is 3 * votingRate = (2 + 3 + 4)/3 */ @SuppressWarnings("unchecked") public void testVote2() throws Exception { Node test = initNode(); votingService.vote(test, 2, "root", "fr"); votingService.vote(test, 3, "marry", "fr"); votingService.vote(test, 4, "john", "fr"); Node fr = multiLanguageService.getLanguage(test, "fr"); List voters = Arrays.asList(new String[] { "root", "marry", "john"}); Property voterProperty = fr.getProperty(VOTER_VOTEVALUE_PROP); Value[] value = voterProperty.getValues(); for (int i = 0; i < 3; i++) { assertTrue(value[i].getString().startsWith(voters.get(i) + "")); } assertEquals(3.0, fr.getProperty(VOTING_RATE_PROP).getValue().getDouble()); assertEquals(3, fr.getProperty(VOTE_TOTAL_LANG_PROP).getValue().getLong()); } /** * Test Method: vote() * Input: Test node is set default language and is not equals voter's language. * first vote : root, rate: 3.0, language fr * second vote: marry, rate: 2.0, language fr * second vote: john, rate: 5.0, language fr * Expected: * Each language add "jcr:contest" node and their data is equals data of "jcr:content" of test node. * Voters who use fr language is "root", "marry", "john" * Total of vote of fr is 3 * votingRate = 3.33 */ @SuppressWarnings("unchecked") public void testVote3() throws Exception { Node test = session.getRootNode().addNode("Test", FILE); Node testFile = test.addNode(CONTENT, RESOURCE); testFile.setProperty(DATA, "test"); testFile.setProperty(MIMETYPE, "text/xml"); testFile.setProperty(LASTMODIFIED, new GregorianCalendar()); if (test.canAddMixin(I18NMixin)) { test.addMixin(I18NMixin); } if (test.canAddMixin(VOTEABLE)) { test.addMixin(VOTEABLE); } session.save(); multiLanguageService.addLanguage(test, createFileInput(), "fr", false, "jcr:content"); multiLanguageService.addLanguage(test, createFileInput(), "en", false, "jcr:content"); multiLanguageService.addLanguage(test, createFileInput(), "vi", false, "jcr:content"); votingService.vote(test, 3, "root", "fr"); votingService.vote(test, 2, "marry", "fr"); votingService.vote(test, 5, "john", "fr"); Node viLangNode = multiLanguageService.getLanguage(test, "vi"); Node enLangNode = multiLanguageService.getLanguage(test, "en"); Node frLangNode = multiLanguageService.getLanguage(test, "fr"); assertEquals(testFile.getProperty(MIMETYPE).getString(), frLangNode.getNode(CONTENT).getProperty(MIMETYPE).getString()); assertEquals(testFile.getProperty(DATA).getValue(), frLangNode.getNode(CONTENT).getProperty(DATA).getValue()); assertEquals(testFile.getProperty(MIMETYPE).getString(), viLangNode.getNode(CONTENT).getProperty(MIMETYPE).getString()); assertEquals(testFile.getProperty(DATA).getValue(), viLangNode.getNode(CONTENT).getProperty(DATA).getValue()); assertEquals(3.33, frLangNode.getProperty(VOTING_RATE_PROP).getValue().getDouble()); assertEquals(3, frLangNode.getProperty(VOTE_TOTAL_LANG_PROP).getValue().getLong()); } /** * Test Method: getVoteTotal() * Input: Test node is set English default language and doesn't have MultiLanguage * Voter's language equals default language. * Expected: * Total of test's vote = value of VOTE_TOTAL_LANG_PROP property. */ public void testGetVoteTotal() throws Exception{ Node test = session.getRootNode().addNode("Test"); if (test.canAddMixin(I18NMixin)) { test.addMixin(I18NMixin); } session.save(); votingService.vote(test, 3, "root", multiLanguageService.getDefault(test)); long voteTotal = votingService.getVoteTotal(test); assertEquals(voteTotal, test.getProperty(VOTE_TOTAL_LANG_PROP).getValue().getLong()); } /** * Test Method: getVoteTotal() * Input: test node is set English default language and has MultiLanguage * test node is voted 4 times: root votes 1 times using default language. * john votes 1 times using default language. * marry votes 3 times using both fr, vi, and en language. * Expected: * Total of votes of test node = value of VOTE_TOTAL_PROP property of test node. * In this case: * total = total of voters with default language + total of voter with other languages. */ public void testGetVoteTotal1() throws Exception{ Node test = initNode(); String DefaultLang = multiLanguageService.getDefault(test); votingService.vote(test, 5, "root", DefaultLang); votingService.vote(test, 4, "john", DefaultLang); votingService.vote(test, 4, "marry", "en"); votingService.vote(test, 3, "marry", "fr"); votingService.vote(test, 2, "marry", "vi"); long voteTotal = votingService.getVoteTotal(test); assertEquals(voteTotal, test.getProperty(VOTE_TOTAL_PROP).getValue().getLong()); } /** * Test Method: IsVoted() * Input: test node is set English default language and has MultiLanguage * test node is voted 1 time: root votes 1 times using default language. * Expected: root voted test node and mary didn't * @throws Exception */ public void testIsVoted() throws Exception{ Node test = session.getRootNode().addNode("Test"); if (test.canAddMixin(I18NMixin)) { test.addMixin(I18NMixin); } session.save(); votingService.vote(test, 3, "root", multiLanguageService.getDefault(test)); assertTrue(votingService.isVoted(test, "root", multiLanguageService.getDefault(test))); assertFalse(votingService.isVoted(test, "mary", multiLanguageService.getDefault(test))); } /** * Test Method: getVoteTotal() * Input: test node is set English default language and has MultiLanguage * test node is voted 4 times: root votes 1 times using default language. * john votes 1 times using default language. * marry votes 3 times using both fr, vi, and en language. * Expected: * Total of votes of test node = value of VOTE_TOTAL_PROP property of test node. * In this case: * total = total of voters with default language + total of voter with other languages. */ public void testGetVoteValueOfUser() throws Exception{ Node test = initNode(); String DefaultLang = multiLanguageService.getDefault(test); votingService.vote(test, 5, "root", DefaultLang); votingService.vote(test, 4, "john", DefaultLang); votingService.vote(test, 4, "john", "en"); votingService.vote(test, 3, "john", "fr"); votingService.vote(test, 2, "john", "vi"); assertEquals(5.0, votingService.getVoteValueOfUser(test, "root", DefaultLang)); assertEquals(4.0, votingService.getVoteValueOfUser(test, "john", DefaultLang)); assertEquals(4.0, votingService.getVoteValueOfUser(test, "john", "en")); assertEquals(3.0, votingService.getVoteValueOfUser(test, "john", "fr")); assertEquals(2.0, votingService.getVoteValueOfUser(test, "john", "vi")); } /** * Clean data test */ public void tearDown() throws Exception { if (session.itemExists("/Test")) { Node test = session.getRootNode().getNode("Test"); test.remove(); session.save(); } super.tearDown(); } /** * Create a map to use for MultilLanguageService */ private Map<String, JcrInputProperty> createMapInput() { Map<String, JcrInputProperty> map = new HashMap<String, JcrInputProperty>(); String titlePath = CmsService.NODE + "/" + TITLE; String summaryPath = CmsService.NODE + "/" + SUMMARY; String textPath = CmsService.NODE + "/" + TEXT; JcrInputProperty inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(CmsService.NODE); inputProperty.setValue("test"); map.put(CmsService.NODE, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(titlePath); inputProperty.setValue("this is title"); map.put(titlePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(summaryPath); inputProperty.setValue("this is summary"); map.put(summaryPath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(textPath); inputProperty.setValue("this is article content"); map.put(textPath, inputProperty); return map; } /** * Create binary data */ private Map<String, JcrInputProperty> createFileInput() throws IOException { Map<String, JcrInputProperty> map = new HashMap<String, JcrInputProperty>(); String data = CmsService.NODE + "/" + CONTENT + "/" + DATA; String mimeType = CmsService.NODE + "/" + CONTENT + "/" + MIMETYPE; JcrInputProperty inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(data); inputProperty.setValue("test"); map.put(data, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(mimeType); inputProperty.setValue("text/xml"); map.put(mimeType, inputProperty); return map; } /** * This method will create a node which is added MultiLanguage */ private Node initNode() throws Exception{ Node test = session.getRootNode().addNode("Test", ARTICLE); if (test.canAddMixin(I18NMixin)) { test.addMixin(I18NMixin); } if (test.canAddMixin(VOTEABLE)) { test.addMixin(VOTEABLE); } test.setProperty(TITLE, "sport"); test.setProperty(SUMMARY, "report of season"); test.setProperty(TEXT, "sport is exciting"); session.save(); multiLanguageService.addLanguage(test, createMapInput(), "en", false); multiLanguageService.addLanguage(test, createMapInput(), "vi", false); multiLanguageService.addLanguage(test, createMapInput(), "fr", false); return test; } }
16,400
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestDriveService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/drive/TestDriveService.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.services.ecm.dms.drive; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Session; import org.exoplatform.services.cache.CacheService; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.drives.impl.ManageDriveServiceImpl; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.wcm.BaseWCMTestCase; /** * Created by The eXo Platform SARL * Author : Ly Dinh Quang * quang.ly@exoplatform.com * xxx5669@gmail.com * Jun 11, 2009 */ public class TestDriveService extends BaseWCMTestCase { private ManageDriveService driveService; private NodeHierarchyCreator nodeHierarchyCreator; private CacheService caService; private Node rootNode; private String drivePath; private static String WORKSPACE = "exo:workspace" ; private static String PERMISSIONS = "exo:accessPermissions" ; private static String VIEWS = "exo:views" ; private static String ICON = "exo:icon" ; private static String PATH = "exo:path" ; private static String VIEW_REFERENCES = "exo:viewPreferences" ; private static String VIEW_NON_DOCUMENT = "exo:viewNonDocument" ; private static String VIEW_SIDEBAR = "exo:viewSideBar" ; private static String SHOW_HIDDEN_NODE = "exo:showHiddenNode" ; private static String ALLOW_CREATE_FOLDER = "exo:allowCreateFolders" ; private static String ALL_DRIVES_CACHED_BY_ROLES = "_allDrivesByRoles"; private static String ALL_MAIN_CACHED_DRIVE = "_mainDrives"; private static String ALL_PERSONAL_CACHED_DRIVE = "_personalDrives"; private static String ALL_GROUP_CACHED_DRIVES = "_groupDrives"; private static String CACHE_NAME = "ecms.drive"; /** * Set up for testing * * In Collaboration workspace * * /---TestTreeNode * | * |_____A1 * | |___A1_1 * | |___A1_1_1 * | |___A1_2 * | * |_____B1 * |___B1_1 * */ public void setUp() throws Exception { super.setUp(); driveService = (ManageDriveService)container.getComponentInstanceOfType(ManageDriveService.class); caService = (CacheService)container.getComponentInstanceOfType(CacheService.class); nodeHierarchyCreator = (NodeHierarchyCreator)container.getComponentInstanceOfType(NodeHierarchyCreator.class); drivePath = nodeHierarchyCreator.getJcrPath(BasePath.EXO_DRIVES_PATH); applySystemSession(); // clean and setup data removeAllDrives(); createTree(); } public void createTree() throws Exception { rootNode = session.getRootNode(); Node testNode = rootNode.addNode("TestTreeNode"); Node nodeA1 = testNode.addNode("A1"); nodeA1.addNode("A1_1").addNode("A1_1_1"); nodeA1.addNode("A1_2"); testNode.addNode("B1").addNode("B1_1"); session.save(); } /** * Register all drive plugins to repository * Input: * Init three param which is configured in test-drives-configuration.xml * Expect: * Size of list node = 3, contains 'System files' node, 'Collaboration Center' node, * 'Backup Administration' node * @throws Exception */ public void testInit() throws Exception { Session mySession = sessionProviderService_.getSystemSessionProvider(null).getSession(DMSSYSTEM_WS, repository); Node myDrive = (Node)mySession.getItem(drivePath); assertNotNull(myDrive.getNodes().getSize()); } /** * Register a new drive to workspace or update if the drive is existing * Input: * name = "MyDrive", workspace = COLLABORATION_WS, permissions = "*:/platform/administrators", * homePath = "/TestTreeNode/A1", views = "admin-view", icon = "", viewReferences = true, * viewNonDocument = true, viewSideBar = true, showHiddenNode = true, repository = REPO_NAME, * allowCreateFolder = "nt:folder" * Expect: * node: name = MyDrive is not null * property of this node is mapped exactly * @throws Exception */ public void testAddDrive() throws Exception { driveService.addDrive("MyDrive", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); Session mySession = sessionProviderService_.getSystemSessionProvider(null).getSession(DMSSYSTEM_WS, repository); Node myDrive = (Node)mySession.getItem(drivePath + "/MyDrive"); assertNotNull(myDrive); assertEquals(myDrive.getProperty(WORKSPACE).getString(), COLLABORATION_WS) ; assertEquals(myDrive.getProperty(PERMISSIONS).getString(), "*:/platform/administrators"); assertEquals(myDrive.getProperty(PATH).getString(), "/TestTreeNode/A1"); assertEquals(myDrive.getProperty(VIEWS).getString(), "admin-view"); assertEquals(myDrive.getProperty(ICON).getString(), ""); assertEquals(myDrive.getProperty(VIEW_REFERENCES).getBoolean(), true); assertEquals(myDrive.getProperty(VIEW_NON_DOCUMENT).getBoolean(), true); assertEquals(myDrive.getProperty(VIEW_SIDEBAR).getBoolean(), true); assertEquals(myDrive.getProperty(ALLOW_CREATE_FOLDER).getString(), "nt:folder"); assertEquals(myDrive.getProperty(SHOW_HIDDEN_NODE).getBoolean(), true); } /** * Test addDrive: in case drive already existed * @throws Exception */ public void testAddDrive2() throws Exception { driveService.addDrive("MyDrive", COLLABORATION_WS, "*:/platform/user", "/TestTreeNode/A1_1", "admin-view, system-view", "", true, true, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("MyDrive", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); Session mySession = sessionProviderService_.getSystemSessionProvider(null).getSession(DMSSYSTEM_WS, repository); Node myDrive = (Node)mySession.getItem(drivePath + "/MyDrive"); assertNotNull(myDrive); assertEquals(myDrive.getProperty(WORKSPACE).getString(), COLLABORATION_WS) ; assertEquals(myDrive.getProperty(PERMISSIONS).getString(), "*:/platform/administrators"); assertEquals(myDrive.getProperty(PATH).getString(), "/TestTreeNode/A1"); assertEquals(myDrive.getProperty(VIEWS).getString(), "admin-view"); assertEquals(myDrive.getProperty(ICON).getString(), ""); assertEquals(myDrive.getProperty(VIEW_REFERENCES).getBoolean(), true); assertEquals(myDrive.getProperty(VIEW_NON_DOCUMENT).getBoolean(), true); assertEquals(myDrive.getProperty(VIEW_SIDEBAR).getBoolean(), true); assertEquals(myDrive.getProperty(ALLOW_CREATE_FOLDER).getString(), "nt:folder"); assertEquals(myDrive.getProperty(SHOW_HIDDEN_NODE).getBoolean(), true); } /** * Return an DriveData Object * Input: Add a new drive * name = "MyDrive", workspace = COLLABORATION_WS, permissions = "*:/platform/administrators", * homePath = "/TestTreeNode/A1", views = "admin-view", icon = "", viewReferences = true, * viewNonDocument = true, viewSideBar = true, showHiddenNode = true, repository = REPO_NAME, * allowCreateFolder = "nt:folder" * Input: * driveName = "abc", repository = REPO_NAME * Expect: * node: name = "abc" is null * Input: * driveName = "MyDrive", repository = REPO_NAME * Expect: * node: name = MyDrive is not null * @throws Exception */ public void testGetDriveByName() throws Exception { driveService.addDrive("MyDrive", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); DriveData driveData1 = driveService.getDriveByName("abc"); assertNull(driveData1); DriveData driveData2 = driveService.getDriveByName("MyDrive"); assertNotNull(driveData2); assertEquals(driveData2.getWorkspace(), COLLABORATION_WS) ; assertEquals(driveData2.getPermissions(), "*:/platform/administrators"); assertEquals(driveData2.getHomePath(), "/TestTreeNode/A1"); assertEquals(driveData2.getViews(), "admin-view"); assertEquals(driveData2.getIcon(), ""); assertEquals(driveData2.getViewPreferences(), true); assertEquals(driveData2.getViewNonDocument(), true); assertEquals(driveData2.getViewSideBar(), true); assertEquals(driveData2.getAllowCreateFolders(), "nt:folder"); assertEquals(driveData2.getShowHiddenNode(), true); } /** * Test GetDriveByName: groupdrivetemplate is inactive * @throws Exception */ public void testGetDriveByNameWithInActiveGroupDriveTemplate() throws Exception { deActivateGroupDriveTemplate(); driveService.addDrive("MyDrive", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", null); DriveData driveData1 = driveService.getDriveByName("abc"); DriveData driveData2 = driveService.getDriveByName("MyDrive"); DriveData groupDrive = driveService.getDriveByName(".platform.administrators"); assertNull(driveData1); assertNotNull(driveData2); assertEquals(driveData2.getWorkspace(), COLLABORATION_WS) ; assertEquals(driveData2.getPermissions(), "*:/platform/administrators"); assertEquals(driveData2.getHomePath(), "/TestTreeNode/A1"); assertEquals(driveData2.getViews(), "admin-view"); assertEquals(driveData2.getIcon(), ""); assertEquals(driveData2.getViewPreferences(), true); assertEquals(driveData2.getViewNonDocument(), true); assertEquals(driveData2.getViewSideBar(), true); assertEquals(driveData2.getAllowCreateFolders(), "nt:folder"); assertEquals(driveData2.getShowHiddenNode(), true); assertEquals(driveData2.getAllowNodeTypesOnTree(), "*"); assertNull(groupDrive); } /** * This method will look up in all workspaces of repository to find DriveData * Input: * Add two drive * 1. name = "MyDrive1", workspace = COLLABORATION_WS, * permissions = "*:/platform/administrators", homePath = "/TestTreeNode/A1", * views = "admin-view", icon = "", viewReferences = true, viewNonDocument = true, * viewSideBar = true, showHiddenNode = true, repository = REPO_NAME, * allowCreateFolder = "nt:folder" * 2. name = "MyDrive2", workspace = COLLABORATION_WS, permissions = "*:/platform/user", * homePath = "/TestTreeNode/A1_1", views = "admin-view, system-view", icon = "", * viewReferences = true, viewNonDocument = true, viewSideBar = true, * showHiddenNode = false, repository = REPO_NAME, allowCreateFolder = "nt:folder" * Expect: * Size of list node = 2, contains node MyDrive1 and MyDrive2 * @throws Exception */ public void testGetAllDrives() throws Exception { driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("MyDrive2", COLLABORATION_WS, "*:/platform/user", "/TestTreeNode/A1_1", "admin-view, system-view", "", true, true, true, false, "nt:folder,nt:unstructured", "*"); List<DriveData> listDriveData = driveService.getAllDrives(); assertEquals(listDriveData.size(), 2); assertEquals(listDriveData.get(0).getWorkspace(), COLLABORATION_WS) ; assertEquals(listDriveData.get(0).getPermissions(), "*:/platform/administrators"); assertEquals(listDriveData.get(0).getHomePath(), "/TestTreeNode/A1"); assertEquals(listDriveData.get(0).getViews(), "admin-view"); assertEquals(listDriveData.get(0).getIcon(), ""); assertEquals(listDriveData.get(0).getViewPreferences(), true); assertEquals(listDriveData.get(0).getViewNonDocument(), true); assertEquals(listDriveData.get(0).getViewSideBar(), true); assertEquals(listDriveData.get(0).getAllowCreateFolders(), "nt:folder"); assertEquals(listDriveData.get(0).getShowHiddenNode(), true); assertEquals(listDriveData.get(1).getWorkspace(), COLLABORATION_WS) ; assertEquals(listDriveData.get(1).getPermissions(), "*:/platform/user"); assertEquals(listDriveData.get(1).getHomePath(), "/TestTreeNode/A1_1"); assertEquals(listDriveData.get(1).getViews(), "admin-view, system-view"); assertEquals(listDriveData.get(1).getIcon(), ""); assertEquals(listDriveData.get(1).getViewPreferences(), true); assertEquals(listDriveData.get(1).getViewNonDocument(), true); assertEquals(listDriveData.get(1).getViewSideBar(), true); assertEquals(listDriveData.get(1).getAllowCreateFolders(), "nt:folder,nt:unstructured"); assertEquals(listDriveData.get(1).getShowHiddenNode(), false); } /** * Test getAllDrives(boolean withVirtualDrives): withVirtualDrives = true; * * @throws Exception */ public void testGetAllDrivesWithVitualIsTrue() throws Exception { activateGroupDriveTemplate("john"); driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("MyDrive2", COLLABORATION_WS, "*:/platform/user", "/TestTreeNode/A1_1", "admin-view, system-view", "", true, true, true, false, "nt:folder,nt:unstructured", "*"); List<DriveData> drives = driveService.getAllDrives(true); assertTrue(drives.contains(driveService.getDriveByName("MyDrive1"))); assertTrue(drives.contains(driveService.getDriveByName("MyDrive2"))); assertTrue(drives.contains(driveService.getDriveByName("Groups"))); } /** * Test getAllDrives(boolean withVirtualDrives): withVirtualDrives = false; * * @throws Exception */ public void testGetAllDrivesWithVitualIsFalse() throws Exception { activateGroupDriveTemplate("john"); driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("MyDrive2", COLLABORATION_WS, "*:/platform/user", "/TestTreeNode/A1_1", "admin-view, system-view", "", true, true, true, false, "nt:folder,nt:unstructured", "*"); List<DriveData> drives = driveService.getAllDrives(false); assertTrue(drives.contains(driveService.getDriveByName("MyDrive1"))); assertTrue(drives.contains(driveService.getDriveByName("MyDrive2"))); assertFalse(drives.contains(driveService.getDriveByName("Groups"))); } /** * Remove drive with specified drive name and repository * Input: * Add two drive * 1. name = "MyDrive1", workspace = COLLABORATION_WS, * permissions = "*:/platform/administrators", homePath = "/TestTreeNode/A1", * views = "admin-view", icon = "", viewReferences = true, viewNonDocument = true, * viewSideBar = true, showHiddenNode = true, repository = REPO_NAME, * allowCreateFolder = "nt:folder" * 2. name = "MyDrive2", workspace = COLLABORATION_WS, permissions = "*:/platform/user", * homePath = "/TestTreeNode/A1_1", views = "admin-view, system-view", icon = "", * viewReferences = true, viewNonDocument = true, viewSideBar = true, * showHiddenNode = false, repository = REPO_NAME, allowCreateFolder = "nt:folder" * Input: Remove drive * driveName = "MyDrive1", repository = REPO_NAME * Expect: * Size of list node = 1 * Input: Remove drive * driveName = "xXx", repository = REPO_NAME * Expect: * Size of list node = 1 * @throws Exception */ public void testRemoveDrive() throws Exception { driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("MyDrive2", COLLABORATION_WS, "*:/platform/user", "/TestTreeNode/A1_1", "admin-view, system-view", "", true, true, true, false, "nt:folder,nt:unstructured", "*"); assertEquals(driveService.getAllDrives().size(), 2); driveService.removeDrive("MyDrive1"); assertEquals(driveService.getAllDrives().size(), 1); driveService.removeDrive("xXx"); assertEquals(driveService.getAllDrives().size(), 1); } /** * Return the list of DriveData * Input: * Add three drive * 1. name = "MyDrive1", workspace = COLLABORATION_WS, * permissions = "*:/platform/administrators", homePath = "/TestTreeNode/A1", * views = "admin-view", icon = "", viewReferences = true, viewNonDocument = true, * viewSideBar = true, showHiddenNode = true, repository = REPO_NAME, * allowCreateFolder = "nt:folder" * 2. name = "MyDrive2", workspace = COLLABORATION_WS, permissions = "*:/platform/user", * homePath = "/TestTreeNode/A1_1", views = "admin-view, system-view", icon = "", * viewReferences = true, viewNonDocument = true, viewSideBar = true, * showHiddenNode = false, repository = REPO_NAME, allowCreateFolder = "nt:unstructured" * 2. name = "MyDrive3", workspace = COLLABORATION_WS, permissions = "*:/platform/user", * homePath = "/TestTreeNode/A1_2", views = "system-view", icon = "", * viewReferences = true, viewNonDocument = true, viewSideBar = true, * showHiddenNode = true, repository = REPO_NAME, allowCreateFolder = "nt:unstructured" * Input: * permission = "*:/platform/user", repository = REPO_NAME * Expect: * Size of list node = 2, contains node MyDrive2 and MyDrive3 * * Input: * permission = "*:/platform/xXx", repository = REPO_NAME * Expect: * Size of list node = 0 * @throws Exception */ public void testGetAllDriveByPermission() throws Exception { driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("MyDrive2", COLLABORATION_WS, "*:/platform/user", "/TestTreeNode/A1_1", "admin-view, system-view", "", true, true, true, false, "nt:unstructured", "*"); driveService.addDrive("MyDrive3", COLLABORATION_WS, "*:/platform/user", "/TestTreeNode/A1_2", "system-view", "", true, true, true, true, "nt:unstructured", "*"); List<DriveData> listDriveData = driveService.getAllDrives(); assertEquals(listDriveData.size(), 3); List<DriveData> driveDatas = driveService.getAllDriveByPermission("*:/platform/user"); assertEquals(driveDatas.size(), 2); assertEquals(driveDatas.get(0).getWorkspace(), COLLABORATION_WS) ; assertEquals(driveDatas.get(0).getPermissions(), "*:/platform/user"); assertEquals(driveDatas.get(0).getHomePath(), "/TestTreeNode/A1_1"); assertEquals(driveDatas.get(0).getViews(), "admin-view, system-view"); assertEquals(driveDatas.get(0).getIcon(), ""); assertEquals(driveDatas.get(0).getViewPreferences(), true); assertEquals(driveDatas.get(0).getViewNonDocument(), true); assertEquals(driveDatas.get(0).getViewSideBar(), true); assertEquals(driveDatas.get(0).getAllowCreateFolders(), "nt:unstructured"); assertEquals(driveDatas.get(0).getShowHiddenNode(), false); assertEquals(driveDatas.get(1).getWorkspace(), COLLABORATION_WS) ; assertEquals(driveDatas.get(1).getPermissions(), "*:/platform/user"); assertEquals(driveDatas.get(1).getHomePath(), "/TestTreeNode/A1_2"); assertEquals(driveDatas.get(1).getViews(), "system-view"); assertEquals(driveDatas.get(1).getIcon(), ""); assertEquals(driveDatas.get(1).getViewPreferences(), true); assertEquals(driveDatas.get(1).getViewNonDocument(), true); assertEquals(driveDatas.get(1).getViewSideBar(), true); assertEquals(driveDatas.get(1).getAllowCreateFolders(), "nt:unstructured"); assertEquals(driveDatas.get(1).getShowHiddenNode(), true); List<DriveData> driveDatas2 = driveService.getAllDriveByPermission("*:/platform/xXx"); assertEquals(driveDatas2.size(), 0); } /** * This method will check to make sure the view is not in used before remove this view * Input: * Add three drive * 1. name = "MyDrive1", workspace = COLLABORATION_WS, * permissions = "*:/platform/administrators", homePath = "/TestTreeNode/A1", * views = "admin-view", icon = "", viewReferences = true, viewNonDocument = true, * viewSideBar = true, showHiddenNode = true, repository = REPO_NAME, * allowCreateFolder = "nt:folder" * 2. name = "MyDrive2", workspace = COLLABORATION_WS, permissions = "*:/platform/user", * homePath = "/TestTreeNode/A1_1", views = "admin-view, system-view", icon = "", * viewReferences = true, viewNonDocument = true, viewSideBar = true, * showHiddenNode = false, repository = REPO_NAME, allowCreateFolder = "nt:folder,nt:unstructured" * 2. name = "MyDrive3", workspace = COLLABORATION_WS, permissions = "*:/platform/user", * homePath = "/TestTreeNode/A1_2", views = "system-view", icon = "", * viewReferences = true, viewNonDocument = true, viewSideBar = true, * showHiddenNode = true, repository = REPO_NAME, allowCreateFolder = "nt:unstructured" * Input: * viewName = "system-view", repository = REPO_NAME * Expect: * result: true * Input: * viewName = "xXx", repository = REPO_NAME * Expect: * result: false * @throws Exception */ public void testIsUsedView() throws Exception { driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("MyDrive2", COLLABORATION_WS, "*:/platform/user", "/TestTreeNode/A1_1", "admin-view, system-view", "", true, true, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("MyDrive3", COLLABORATION_WS, "*:/platform/user", "/TestTreeNode/A1_2", "system-view", "", true, true, true, true, "nt:unstructured", "*"); assertTrue(driveService.isUsedView("system-view")); assertFalse(driveService.isUsedView("xXx")); } /** * Test getGroupDrives: groupDriveTemplate is activated. * * @throws Exception */ public void testGetGroupDrivesWithActivatedGroupDriveTemplate() throws Exception { activateGroupDriveTemplate("john"); List<String> userRoles = new ArrayList<String>(); userRoles.add("john"); userRoles.add("manager:/organization/management/executive-board"); userRoles.add("*:/platform/web-contributors"); userRoles.add("*:/platform/administrators"); userRoles.add("*:/platform/administrators"); userRoles.add("*:/platform/users"); List<DriveData> drives = driveService.getGroupDrives("john", userRoles); assertEquals(drives.size(), 4); } /** * Test getGroupDrives: groupDriveTemplate is deactivated * * @throws Exception */ public void testGetGroupDrivesWithDeactivatedGroupDriveTemplate() throws Exception { List<String> userRoles = new ArrayList<String>(); userRoles.add("john"); userRoles.add("manager:/organization/management/executive-board"); userRoles.add("*:/platform/web-contributors"); userRoles.add("*:/platform/administrators"); userRoles.add("*:/platform/users"); Field field = ManageDriveServiceImpl.class.getDeclaredField("groupDriveTemplate"); field.setAccessible(true); field.set(driveService, null); driveService.clearAllDrivesCache(); List<DriveData> drives = driveService.getGroupDrives("john", userRoles); assertEquals(drives.size(), 0); } /** * Test getGroupDrives: drivecache * * @throws Exception */ @SuppressWarnings("unchecked") public void testGetGroupDrivesWithDriveCacheAndActivatedGroupDriveTemplate() throws Exception { activateGroupDriveTemplate("john"); List<String> userRoles = new ArrayList<String>(); userRoles.add("john"); userRoles.add("manager:/organization/management/executive-board"); userRoles.add("*:/platform/web-contributors"); userRoles.add("*:/platform/administrators"); userRoles.add("*:/platform/administrators"); userRoles.add("*:/platform/users"); driveService.getGroupDrives("john", userRoles); Object drivesInCache = caService.getCacheInstance(CACHE_NAME).get(REPO_NAME + "_" + "john" + ALL_GROUP_CACHED_DRIVES); assertTrue(drivesInCache != null); assertEquals(((List<DriveData>)drivesInCache).size(), 4); } /** * Test getPersonalDrives. * Input 4 drives: 3 personal drives * Expected: 3 personal drives * * @throws Exception */ public void testGetPersonalDrives() throws Exception { driveService.addDrive("Public", COLLABORATION_WS, "*:/platform/users", "/Users/${userId}/Public", "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("Private", COLLABORATION_WS, "${userId}", "/Users/${userId}/Private", "timeline-view", "", true, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); Node userNode = nodeHierarchyCreator.getUserNode(sessionProvider, "john"); driveService.addDrive("Public2", COLLABORATION_WS, "*:/platform/users", userNode.getPath() + "/Public2", "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); List<DriveData> drives = driveService.getPersonalDrives("john"); assertEquals(drives.size(), 3); assertEquals(drives.get(0).getWorkspace(), COLLABORATION_WS) ; assertEquals(drives.get(0).getPermissions(), "${userId}"); assertEquals(drives.get(0).getHomePath(), "/Users/${userId}/Private"); assertEquals(drives.get(0).getViews(), "timeline-view"); assertEquals(drives.get(0).getIcon(), ""); assertEquals(drives.get(0).getViewPreferences(), true); assertEquals(drives.get(0).getViewNonDocument(), false); assertEquals(drives.get(0).getViewSideBar(), true); assertEquals(drives.get(0).getAllowCreateFolders(), "nt:folder,nt:unstructured"); assertEquals(drives.get(0).getShowHiddenNode(), false); assertEquals(drives.get(1).getWorkspace(), COLLABORATION_WS) ; assertEquals(drives.get(1).getPermissions(), "*:/platform/users"); assertEquals(drives.get(1).getHomePath(), "/Users/${userId}/Public"); assertEquals(drives.get(1).getViews(), "simple-view, admin-view"); assertEquals(drives.get(1).getIcon(), ""); assertEquals(drives.get(1).getViewPreferences(), false); assertEquals(drives.get(1).getViewNonDocument(), false); assertEquals(drives.get(1).getViewSideBar(), true); assertEquals(drives.get(1).getAllowCreateFolders(), "nt:folder,nt:unstructured"); assertEquals(drives.get(1).getShowHiddenNode(), false); assertEquals(drives.get(2).getWorkspace(), COLLABORATION_WS) ; assertEquals(drives.get(2).getPermissions(), "*:/platform/users"); assertEquals(drives.get(2).getHomePath(), userNode.getPath() + "/Public2"); assertEquals(drives.get(2).getViews(), "simple-view, admin-view"); assertEquals(drives.get(2).getIcon(), ""); assertEquals(drives.get(2).getViewPreferences(), false); assertEquals(drives.get(2).getViewNonDocument(), false); assertEquals(drives.get(2).getViewSideBar(), true); assertEquals(drives.get(2).getAllowCreateFolders(), "nt:folder,nt:unstructured"); assertEquals(drives.get(2).getShowHiddenNode(), false); } /** * Test getPersonalDrives: with drivecache * Input 4 drives: 3 personal drives * Expected: 3 personal drives * * @throws Exception */ @SuppressWarnings("unchecked") public void testGetPersonalDrivesWithCache() throws Exception { driveService.clearAllDrivesCache(); driveService.addDrive("Public", COLLABORATION_WS, "*:/platform/users", "/Users/${userId}/Public", "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("Private", COLLABORATION_WS, "${userId}", "/Users/${userId}/Private", "timeline-view", "", true, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); Node userNode = nodeHierarchyCreator.getUserNode(sessionProvider, "john"); driveService.addDrive("Public2", COLLABORATION_WS, "*:/platform/users", userNode.getPath() + "/Public2", "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.getPersonalDrives("john"); driveService.getPersonalDrives("john"); Object drivesInCache = caService.getCacheInstance(CACHE_NAME).get(REPO_NAME + "_" + "john" + ALL_PERSONAL_CACHED_DRIVE); assertTrue(drivesInCache != null); assertEquals(((List<DriveData>)drivesInCache).size(), 3); } /** * Test isVitualDrive: activate GroupDriveTemplate * * @throws Exception */ public void testIsVitualDriveWithActiveGroupDriveTemplate() throws Exception { activateGroupDriveTemplate("john"); driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("Public2", COLLABORATION_WS, "*:/platform/users", "/Users/john/Public2", "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); assertFalse(driveService.isVitualDrive("MyDrive1")); assertTrue(driveService.isVitualDrive("Groups")); } /** * Test isVitualDrive: deactivate GroupDriveTemplate * * @throws Exception */ public void testIsVitualDriveWithDeactivatedGroupDriveTemplate() throws Exception { driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("Public2", COLLABORATION_WS, "*:/platform/users", "/Users/john/Public2", "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); Field field = ManageDriveServiceImpl.class.getDeclaredField("groupDriveTemplate"); field.setAccessible(true); field.set(driveService, null); assertFalse(driveService.isVitualDrive("MyDrive1")); assertFalse(driveService.isVitualDrive("Groups")); } /** * Test testNewRoleUpdated * * @throws Exception */ public void testNewRoleUpdated() throws Exception { driveService.setNewRoleUpdated(true); assertTrue(driveService.newRoleUpdated()); driveService.setNewRoleUpdated(false); assertFalse(driveService.newRoleUpdated()); } /** * Test getMainDrives * Input: drives including personal, group, general drives * Expect: only general drives * * @throws Exception */ public void testGetMainDrives() throws Exception { driveService.addDrive("Public", COLLABORATION_WS, "*:/platform/users", "/Users/${userId}/Public", "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("Private", COLLABORATION_WS, "${userId}", "/Users/${userId}/Private", "timeline-view", "", true, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); Node userNode = nodeHierarchyCreator.getUserNode(sessionProvider, "john"); driveService.addDrive("Public2", COLLABORATION_WS, "*:/platform/users", userNode.getPath() + "/Public2", "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); activateGroupDriveTemplate("john"); List<String> userRoles = new ArrayList<String>(); userRoles.add("john"); userRoles.add("manager:/organization/management/executive-board"); userRoles.add("*:/platform/web-contributors"); userRoles.add("*:/platform/administrators"); userRoles.add("*:/platform/users"); List<DriveData> drives = driveService.getMainDrives("john", userRoles); assertEquals(drives.size(), 1); assertEquals(drives.get(0).getWorkspace(), COLLABORATION_WS) ; assertEquals(drives.get(0).getPermissions(), "*:/platform/administrators"); assertEquals(drives.get(0).getHomePath(), "/TestTreeNode/A1"); assertEquals(drives.get(0).getViews(), "admin-view"); assertEquals(drives.get(0).getIcon(), ""); assertEquals(drives.get(0).getViewPreferences(), true); assertEquals(drives.get(0).getViewNonDocument(), true); assertEquals(drives.get(0).getViewSideBar(), true); assertEquals(drives.get(0).getAllowCreateFolders(), "nt:folder"); assertEquals(drives.get(0).getShowHiddenNode(), true); } /** * Test getMainDrives: using driveCache * * @throws Exception */ @SuppressWarnings("unchecked") public void testGetMainDrivesWithCaches() throws Exception { driveService.clearAllDrivesCache(); driveService.addDrive("Public", COLLABORATION_WS, "*:/platform/users", "/Users/${userId}/Public", "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("Private", COLLABORATION_WS, "${userId}", "/Users/${userId}/Private", "timeline-view", "", true, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("MyDrive2", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); Node userNode = nodeHierarchyCreator.getUserNode(sessionProvider, "john"); driveService.addDrive("Public2", COLLABORATION_WS, "*:/platform/users", userNode.getPath() + "/Public2", "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); activateGroupDriveTemplate("john"); List<String> userRoles = new ArrayList<String>(); userRoles.add("john"); userRoles.add("manager:/organization/management/executive-board"); userRoles.add("*:/platform/web-contributors"); userRoles.add("*:/platform/administrators"); userRoles.add("*:/platform/users"); driveService.getMainDrives("john", userRoles); driveService.getMainDrives("john", userRoles); Object drivesInCache = caService.getCacheInstance("ecms.drive").get(REPO_NAME + "_" + "john" + ALL_MAIN_CACHED_DRIVE); assertEquals(((List<DriveData>)drivesInCache).size(), 2); } /** * Test getDriveByUserRoles: userId not null * * @throws Exception */ public void testGetDriveByUserRolesWithUserIdNotNull() throws Exception { driveService.clearAllDrivesCache(); driveService.addDrive("Public", COLLABORATION_WS, "*:/platform/users", "/Users/${userId}/Public", // Marry have permission "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("Private", COLLABORATION_WS, "${userId}", "/Users/${userId}/Private", // Marry have permission "timeline-view", "", true, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("MyDrive2", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("MyDrive3", COLLABORATION_WS, "*", "/TestTreeNode/A1", // Marry have permission "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("Public2", COLLABORATION_WS, "*:/platform/users", "/Users/john/Public2", // Marry have permission "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); activateGroupDriveTemplate("marry"); List<String> userRoles = new ArrayList<String>(); userRoles.add("marry"); userRoles.add("*:/platform/web-contributors"); // Marry have permission userRoles.add("*:/platform/users"); // Marry have permission List<DriveData> drives = driveService.getDriveByUserRoles("marry", userRoles); assertEquals(drives.size(), 6); assertTrue(drives.contains(driveService.getDriveByName("Public"))); assertTrue(drives.contains(driveService.getDriveByName("Private"))); assertFalse(drives.contains(driveService.getDriveByName("MyDrive1"))); assertFalse(drives.contains(driveService.getDriveByName("MyDrive2"))); assertTrue(drives.contains(driveService.getDriveByName("Public2"))); assertTrue(drives.contains(driveService.getDriveByName("MyDrive3"))); assertTrue(drives.contains(driveService.getDriveByName(".platform.web-contributors"))); assertTrue(drives.contains(driveService.getDriveByName(".platform.users"))); } /** * Test getDriveByUserRoles: userId null * * @throws Exception */ public void testGetDriveByUserRolesWithUserIdNull() throws Exception { driveService.clearAllDrivesCache(); driveService.addDrive("Public", COLLABORATION_WS, "*:/platform/users", "/Users/${userId}/Public", // Marry have permission "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("Private", COLLABORATION_WS, "${userId}", "/Users/${userId}/Private", // Marry have permission "timeline-view", "", true, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("MyDrive2", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("MyDrive3", COLLABORATION_WS, "*", "/TestTreeNode/A1", // Marry have permission "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("Public2", COLLABORATION_WS, "*:/platform/users", "/Users/john/Public2", // Marry have permission "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); activateGroupDriveTemplate("marry"); List<String> userRoles = new ArrayList<String>(); userRoles.add("marry"); userRoles.add("*:/platform/web-contributors"); // Marry have permission userRoles.add("*:/platform/users"); // Marry have permission List<DriveData> drives = driveService.getDriveByUserRoles(null, userRoles); assertEquals(drives.size(), 1); assertFalse(drives.contains(driveService.getDriveByName("Public"))); assertFalse(drives.contains(driveService.getDriveByName("Private"))); assertFalse(drives.contains(driveService.getDriveByName("MyDrive1"))); assertFalse(drives.contains(driveService.getDriveByName("MyDrive2"))); assertFalse(drives.contains(driveService.getDriveByName("Public2"))); assertTrue(drives.contains(driveService.getDriveByName("MyDrive3"))); assertFalse(drives.contains(driveService.getDriveByName(".platform.web-contributors"))); assertFalse(drives.contains(driveService.getDriveByName(".platform.users"))); } /** * Test getDriveByUserRoles: using driveCache * * @throws Exception */ @SuppressWarnings("unchecked") public void testGetDriveByUserRolesWithDriveCache() throws Exception { driveService.clearAllDrivesCache(); driveService.addDrive("Public", COLLABORATION_WS, "*:/platform/users", "/Users/${userId}/Public", // Marry have permission "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("Private", COLLABORATION_WS, "${userId}", "/Users/${userId}/Private", // Marry have permission "timeline-view", "", true, false, true, false, "nt:folder,nt:unstructured", "*"); driveService.addDrive("MyDrive1", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("MyDrive2", COLLABORATION_WS, "*:/platform/administrators", "/TestTreeNode/A1", "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("MyDrive3", COLLABORATION_WS, "*", "/TestTreeNode/A1", // Marry have permission "admin-view", "", true, true, true, true, "nt:folder", "*"); driveService.addDrive("Public2", COLLABORATION_WS, "*:/platform/users", "/Users/john/Public2", // Marry have permission "simple-view, admin-view", "", false, false, true, false, "nt:folder,nt:unstructured", "*"); activateGroupDriveTemplate("marry"); List<String> userRoles = new ArrayList<String>(); userRoles.add("marry"); userRoles.add("*:/platform/web-contributors"); // Marry have permission userRoles.add("*:/platform/users"); // Marry have permission driveService.getDriveByUserRoles("marry", userRoles); driveService.getDriveByUserRoles("marry", userRoles); Object drivesInCache = caService.getCacheInstance(CACHE_NAME).get(REPO_NAME + "_" + "marry" + ALL_DRIVES_CACHED_BY_ROLES); assertEquals(((List<DriveData>)drivesInCache).size(), 6); } /** * Test init() */ public void testInitMethod() { try { driveService.init(); } catch (Exception e) { fail(); } } /** * Add Groups Drive Template * * @throws Exception */ private void activateGroupDriveTemplate(String userId) throws Exception { driveService.clearGroupCache(userId); driveService.addDrive("Groups", COLLABORATION_WS, "*:${groupId}", "/Groups${groupId}", "simple-view", "", false, true, true, false, "nt:folder,nt:unstructured", "*"); driveService.getAllDrives(); } /** * Deactivate group drive template * @throws Exception */ private void deActivateGroupDriveTemplate() throws Exception { Field field = ManageDriveServiceImpl.class.getDeclaredField("groupDriveTemplate"); field.setAccessible(true); field.set(driveService, null); } public void tearDown() throws Exception { removeAllDrives(); session.getRootNode().getNode("TestTreeNode").remove(); session.save(); super.tearDown(); } private void removeAllDrives() throws Exception { Session mySession = sessionProviderService_.getSystemSessionProvider(null).getSession(DMSSYSTEM_WS, repository); Node rootDrive = (Node)mySession.getItem(drivePath); NodeIterator iter = rootDrive.getNodes(); while (iter.hasNext()) { iter.nextNode().remove(); } rootDrive.getSession().save(); session.save(); } }
45,021
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestMetadataService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/metadata/TestMetadataService.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.ecm.dms.metadata; import java.util.List; import javax.jcr.Node; import javax.jcr.Session; import javax.jcr.nodetype.NodeType; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.metadata.MetadataService; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.wcm.BaseWCMTestCase; /** * Created by The eXo Platform SARL * June 09, 2009 */ public class TestMetadataService extends BaseWCMTestCase { private MetadataService metadataService; private String expectedArticleDialogPath = "/exo:ecm/metadata/exo:article/dialogs/dialog1"; private NodeHierarchyCreator nodeHierarchyCreator; private String baseMetadataPath; private Session sessionDMS; static private final String EXO_ARTICLE = "exo:article"; public void setUp() throws Exception { super.setUp(); metadataService = (MetadataService)container.getComponentInstanceOfType(MetadataService.class); nodeHierarchyCreator = (NodeHierarchyCreator)container.getComponentInstanceOfType(NodeHierarchyCreator.class); baseMetadataPath = nodeHierarchyCreator.getJcrPath(BasePath.METADATA_PATH); applySystemSession(); sessionDMS = sessionProviderService_.getSystemSessionProvider(null).getSession(DMSSYSTEM_WS, repository); } /** * Test MetadataServiceImpl.init() * Check all data initiated from repository in test-metadata-configuration.xml file * @throws Exception */ public void testInit() throws Exception { metadataService.init(); } /** * Test method: MetadataServiceImpl.getMetadataList() * Input: repository String * The name of repository * Expect: Return name of all NodeType in repository * @throws Exception */ public void testGetMetadataList() throws Exception { List<String> metadataTypes = metadataService.getMetadataList(); assertTrue(metadataTypes.contains("dc:elementSet")); } /** * Test method: MetadataServiceImpl.getAllMetadatasNodeType() * Input: repository String * The name of repository * Expect: Return all NodeType in repository with NodeType = exo:metadata * @throws Exception */ public void testGetAllMetadatasNodeType() throws Exception { List<NodeType> metadataTypes = metadataService.getAllMetadatasNodeType(); assertNotNull(metadataTypes.size()); } /** * Test method: MetadataServiceImpl.addMetadata() * Input: nodetype Node name for processing * isDialog true for dialog template * role permission * content content of template * isAddNew false if nodetype exist in repository, true if not * repository repository name * Expect: Add new nodetype and set property EXO_ROLES_PROP, EXO_TEMPLATE_FILE_PROP * @throws Exception */ public void testAddMetadata() throws Exception { metadataService.addMetadata(EXO_ARTICLE, true, "*:/platform/administrators;*:/platform/users", "This is content", true); Node myMetadata = (Node)sessionDMS.getItem("/exo:ecm/metadata/exo:article/dialogs/dialog1"); assertEquals("This is content", myMetadata.getNode("jcr:content").getProperty("jcr:data").getString()); String roles = metadataService.getMetadataRoles(EXO_ARTICLE, true); assertEquals("*:/platform/administrators; *:/platform/users", roles); } /** * Test method: MetadataServiceImpl.getMetadataTemplate() * Input: name Node name * isDialog true: Get dialog template content * false: Get view template content * repository repository name * Expect: Return "This is content" is content of dialog template node or view template in repository * @throws Exception */ public void testGetMetadataTemplate() throws Exception { metadataService.addMetadata(EXO_ARTICLE, true, "*:/platform/administrators", "This is content", true); assertEquals("This is content", metadataService.getMetadataTemplate(EXO_ARTICLE, true)); } /** * Test method: MetadataServiceImpl.removeMetadata() * Input: nodetype name of node * repository repository name * Expect: Remove metadata * @throws Exception */ public void testRemoveMetadata() throws Exception { metadataService.addMetadata(EXO_ARTICLE, true, "*:/platform/administrators", "This is content", true); assertEquals("This is content", metadataService.getMetadataTemplate(EXO_ARTICLE, true)); metadataService.removeMetadata(EXO_ARTICLE); assertNull(metadataService.getMetadataTemplate(EXO_ARTICLE, true)); } /** * Test method: MetadataServiceImpl.getExternalMetadataType() * Input: repository String * The name of repository * Expect: Remove metadata * @throws Exception */ public void testGetExternalMetadataType() throws Exception { List<String> extenalMetaTypes = metadataService.getExternalMetadataType(); assertEquals(2, extenalMetaTypes.size()); } /** * Test method: MetadataServiceImpl.getMetadataPath() * Input: name Node name * isDialog true: Get dialog template content * false: Get view template content * repository repository name * Expect: Return "/exo:ecm/metadata/exo:article/dialogs/dialog1" is path of dialog template or view tempate * @throws Exception */ public void testGetMetadataPath() throws Exception { metadataService.addMetadata(EXO_ARTICLE, true, "*:/platform/administrators", "This is my content", true); assertEquals(expectedArticleDialogPath, metadataService.getMetadataPath(EXO_ARTICLE, true)); } /** * Test method: MetadataServiceImpl.getMetadataRoles() * Input: name Node name * isDialog true: Get dialog template content * false: Get view template content * repository repository name * Expect: Return "/exo:ecm/metadata/exo:article/dialogs/dialog1" is path of dialog template or view tempate * @throws Exception */ public void testGetMetadataRoles() throws Exception { metadataService.addMetadata(EXO_ARTICLE, true, "*:/platform/administrators", "This is content", true); assertEquals("*:/platform/administrators", metadataService.getMetadataRoles(EXO_ARTICLE, true)); } /** * Test method: MetadataServiceImpl.hasMetadata() * Input: name Node name * repository repository name * Expect: true : Exist this node name * false: Not exist this node name * @throws Exception */ public void testHasMetadata() throws Exception { metadataService.addMetadata(EXO_ARTICLE, true, "*:/platform/administrators", "This is content", true); assertTrue(metadataService.hasMetadata(EXO_ARTICLE)); metadataService.removeMetadata(EXO_ARTICLE); assertFalse(metadataService.hasMetadata(EXO_ARTICLE)); } /** * Test method: MetadataServiceImpl.getMetadata(String metaName) * Input: metaName Name of Metadata * Expect: Return a Metadata node based on its name * @throws Exception */ public void testGetMetadata() throws Exception { metadataService.addMetadata(EXO_ARTICLE, true, "*:/platform/administrators", "This is content", true); Node node = metadataService.getMetadata(EXO_ARTICLE); assertEquals(node.getName(), EXO_ARTICLE); } /** * Test method: MetadataServiceImpl.getMetadataLabel(String metaName) * Input: metaName Name of Metadata * Expect: Return the label of Metadata node based on its name * @throws Exception */ public void testGetMetadataLabel() throws Exception { metadataService.addMetadata(EXO_ARTICLE, true, "*:/platform/administrators", "This is content", true); Node node = metadataService.getMetadata(EXO_ARTICLE); node.setProperty("label", "Article metadata label"); assertEquals("Article metadata label", metadataService.getMetadataLabel(EXO_ARTICLE)); } /** * Clean all metadata test node */ public void tearDown() throws Exception { Node myMetadata = (Node)sessionDMS.getItem(baseMetadataPath); if (myMetadata.hasNode("exo:article")) myMetadata.getNode("exo:article").remove(); sessionDMS.save(); super.tearDown(); } }
9,318
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestQueryService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/queries/TestQueryService.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.ecm.dms.queries; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.Session; import javax.jcr.query.Query; import javax.jcr.query.QueryResult; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.queries.QueryService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.wcm.BaseWCMTestCase; /** * Created by The eXo Platform SARL Author : Ly Dinh Quang * quang.ly@exoplatform.com xxx5669@gmail.com Jun 12, 2009 */ public class TestQueryService extends BaseWCMTestCase { private QueryService queryService; private NodeHierarchyCreator nodeHierarchyCreator; private String baseUserPath; private String baseQueriesPath; private String relativePath = "Private/Searches"; private static final String[] USERS = {"john", "root", "demo"}; public void setUp() throws Exception { super.setUp(); queryService = (QueryService) container.getComponentInstanceOfType(QueryService.class); nodeHierarchyCreator = (NodeHierarchyCreator) container .getComponentInstanceOfType(NodeHierarchyCreator.class); baseUserPath = nodeHierarchyCreator.getJcrPath(BasePath.CMS_USERS_PATH); baseQueriesPath = nodeHierarchyCreator.getJcrPath(BasePath.QUERIES_PATH); applySystemSession(); } /** * Init all query plugin by giving the following params : repository * Input: * Init three param which is configured in test-queries-configuration.xml * Expect: * Size of list node = 3, contains CreatedDocuments node, CreatedDocumentsDayBefore node, * AllArticles node * @throws Exception */ public void testInit() throws Exception { Session mySession = sessionProviderService_.getSystemSessionProvider(null).getSession(DMSSYSTEM_WS, repository); Node queriesHome = (Node) mySession.getItem(baseQueriesPath); assertEquals(queriesHome.getNodes().getSize(), 3); assertNotNull(queriesHome.getNode("Created Documents")); assertNotNull(queriesHome.getNode("CreatedDocumentDayBefore")); assertNotNull(queriesHome.getNode("All Articles")); } /** * Add new query by giving the following params : queryName, statement, * language, userName, repository * Input: * queryName = "QueryAll"; statement = "Select * from nt:base"; language = "sql"; * userName = "root"; repository = "repository"; * Expect: * node: name = "QueryAll" not null; * @throws Exception */ public void testAddQuery() throws Exception { queryService.addQuery("QueryAll", "Select * from nt:base", "sql", "root"); Node userNode = nodeHierarchyCreator.getUserNode(sessionProvider, "root"); String userPath = userNode.getPath() + "/" + relativePath; Node nodeSearch = (Node) session.getItem(userPath); Node queryAll = nodeSearch.getNode("QueryAll"); assertNotNull(queryAll); } public void testGetQuery() throws Exception { queryService.addQuery("QueryAll", "Select * from nt:base", "sql", "john"); Node userNode = nodeHierarchyCreator.getUserNode(sessionProvider, "john"); String queryPath = userNode.getPath() + "/" + relativePath + "/QueryAll"; assertNotNull(queryService.getQuery(queryPath, COLLABORATION_WS, sessionProvider, "john")); } /** * Get queries by giving the following params : userName, repository, provider * Input: * 1. Add 2 query node to test * 1.1 queryName = "QueryAll1"; statement = "Select * from nt:base"; language = "sql"; * userName = "root"; repository = "repository"; * 1.2 queryName = "QueryAll2"; statement = "//element(*, exo:article)"; language = "xpath"; * userName = "root"; repository = "repository"; * Input: userName = "root", repository = "repository", provider = sessionProvider * Expect: Size of list node = 2 * Input: userName = "marry", repository = "repository", provider = sessionProvider * Expect: Size of list node = 0 * Input: userName = null, repository = "repository", provider = sessionProvider * Expect: Size of list node = 0 * @throws Exception */ public void testGetQueries() throws Exception { SessionProvider sessionProvider = sessionProviderService_.getSystemSessionProvider(null); queryService.addQuery("QueryAll1", "Select * from nt:base", "sql", "root"); queryService.addQuery("QueryAll2", "//element(*, exo:article)", "xpath", "root"); List<Query> listQueryRoot = queryService.getQueries("root", sessionProvider); assertEquals(listQueryRoot.size(), 2); List<Query> listQueryMarry = queryService.getQueries("marry", sessionProvider); assertEquals(listQueryMarry.size(), 0); List<Query> listQueryNull = queryService.getQueries(null, sessionProvider); assertEquals(listQueryNull.size(), 0); List<Query> listQueryAno = queryService.getQueries("ano", sessionProvider); assertEquals(listQueryAno.size(), 0); } /** * Remove query by giving the following params : queryPath, userName, repository * Input: * 1. Add 2 query node to test * 1.1 queryName = "QueryAll1"; statement = "Select * from nt:base"; language = "sql"; * userName = "root"; repository = "repository"; * 1.2 queryName = "QueryAll2"; statement = "//element(*, exo:article)"; language = "xpath"; * userName = "root"; repository = "repository"; * Input: * queryPath = "/Users/root/Private/Searches/QueryAll1", userName = "root", * repository = "repository" * Expect: * node: name = "QueryAll1" is removed * Input: * queryPath = "/Users/marry/Private/Searches/QueryAll2", userName = "marry", * repository = "repository" * Expect: * exception: Query path not found! * @throws Exception */ public void testRemoveQuery() throws Exception { SessionProvider sessionProvider = sessionProviderService_.getSystemSessionProvider(null); queryService.addQuery("QueryAll1", "Select * from nt:base", "sql", "root"); List<Query> listQuery = queryService.getQueries("root", sessionProvider); assertEquals(listQuery.size(), 1); Node userNode = nodeHierarchyCreator.getUserNode(sessionProvider, "root"); String queryPathRoot = userNode.getPath() + "/" + relativePath + "/QueryAll1"; queryService.removeQuery(queryPathRoot, "root"); listQuery = queryService.getQueries("root", sessionProvider); assertEquals(listQuery.size(), 0); } /** * Get query with path by giving the following params : queryPath, userName, repository, provider * Input: * 1. Add 2 query node to test * 1.1 queryName = "QueryAll1"; statement = "Select * from nt:base"; language = "sql"; * userName = "root"; repository = "repository"; * 1.2 queryName = "QueryAll2"; statement = "//element(*, exo:article)"; language = "xpath"; * userName = "root"; repository = "repository"; * Input: * queryPath = "/Users/root/Private/Searches/QueryAll1", userName = "root", * repository = "repository" * Expect: * node: name = "QueryAll1" is not null * Input: * queryPath = "/Users/root/Private/Searches/QueryAll3", userName = "root", * repository = "repository" * Expect: * node: query node is null * @throws Exception */ public void testGetQueryByPath() throws Exception { SessionProvider sessionProvider = sessionProviderService_.getSystemSessionProvider(null); Node userNode = nodeHierarchyCreator.getUserNode(sessionProvider, "root"); queryService.addQuery("QueryAll1", "Select * from nt:base", "sql", "root"); queryService.addQuery("QueryAll2", "//element(*, exo:article)", "xpath", "root"); String queryPath1 = userNode.getPath() + "/" + relativePath + "/QueryAll1"; Query query = queryService.getQueryByPath(queryPath1, "root", sessionProvider); assertNotNull(query); assertEquals(query.getStatement(), "Select * from nt:base"); String queryPath2 = userNode.getPath() + "/" + relativePath + "/QueryAll3"; query = queryService.getQueryByPath(queryPath2, "root", sessionProvider); assertNull(query); } /** * Add new shared query by giving the following params: queryName, statement, language, * permissions, cachedResult, repository * Input: * queryName = "QueryAll1", statement = "Select * from nt:base", language = "sql", * permissions = { "*:/platform/administrators" }, cachedResult = false, repository = "repository" * Expect: * node: name = "QueryAll1" is not null * Value of property * jcr:language = sql, jcr:statement = Select * from nt:base, exo:cachedResult = false, * exo:accessPermissions = *:/platform/administrators * @throws Exception */ public void testAddSharedQuery() throws Exception { Session mySession = sessionProviderService_.getSystemSessionProvider(null).getSession(DMSSYSTEM_WS, repository); queryService.addSharedQuery("QueryAll1", "Select * from nt:base", "sql", new String[] { "*:/platform/administrators" }, false, sessionProviderService_.getSystemSessionProvider(null)); Node queriesHome = (Node) mySession.getItem(baseQueriesPath); Node queryAll1 = queriesHome.getNode("QueryAll1"); assertNotNull(queryAll1); assertEquals(queryAll1.getProperty("jcr:language").getString(), "sql"); assertEquals(queryAll1.getProperty("jcr:statement").getString(), "Select * from nt:base"); assertEquals(queryAll1.getProperty("exo:cachedResult").getBoolean(), false); assertEquals(queryAll1.getProperty("exo:accessPermissions").getValues()[0].getString(), "*:/platform/administrators"); queryService.addSharedQuery("QueryAll1", "//element(*, nt:base)", "xpath", new String[] { "*:/platform/administrators" }, false, sessionProvider); queryAll1 = queriesHome.getNode("QueryAll1"); assertNotNull(queryAll1); assertEquals(queryAll1.getProperty("jcr:language").getString(), "xpath"); assertEquals(queryAll1.getProperty("jcr:statement").getString(), "//element(*, nt:base)"); assertEquals(queryAll1.getProperty("exo:cachedResult").getBoolean(), false); assertEquals(queryAll1.getProperty("exo:accessPermissions").getValues()[0].getString(), "*:/platform/administrators"); queryAll1.remove(); queriesHome.save(); } /** * Get shared queries by giving the following params : userId, repository, provider * Input: * 1. Add a shared query node * queryName = "QueryAll1", statement = "Select * from nt:base", language = "sql", * permissions = { "*:/platform/administrators" }, cachedResult = false, * repository = "repository" * Expect: * node: name = "QueryAll1" is not null * Value of property * jcr:language = sql, jcr:statement = Select * from nt:base, exo:cachedResult = false, * exo:accessPermissions = *:/platform/administrators * @throws Exception */ public void testGetSharedQuery() throws Exception { SessionProvider sessionProvider = sessionProviderService_.getSystemSessionProvider(null); queryService.addSharedQuery("QueryAll1", "Select * from nt:base", "sql", new String[] { "*:/platform/administrators" }, false, sessionProvider); Node nodeQuery = queryService.getSharedQuery("QueryAll1", sessionProvider); assertNotNull(nodeQuery); assertEquals(nodeQuery.getProperty("jcr:language").getString(), "sql"); assertEquals(nodeQuery.getProperty("jcr:statement").getString(), "Select * from nt:base"); assertEquals(nodeQuery.getProperty("exo:cachedResult").getBoolean(), false); assertEquals(nodeQuery.getProperty("exo:accessPermissions").getValues()[0].getString(), "*:/platform/administrators"); Node queriesHome = (Node) sessionProvider.getSession(DMSSYSTEM_WS, repository).getItem(baseQueriesPath); queriesHome.getNode("QueryAll1").remove(); queriesHome.save(); } /** * Remove share query by giving the following params : queryName, repository * Input: * 1. Add a shared query node * queryName = "QueryAll1", statement = "Select * from nt:base", language = "sql", * permissions = { "*:/platform/administrators" }, cachedResult = false, * repository = "repository" * Input: * queryName = "QueryAll2", repository = "repository" * Expect: * exception: Query Path not found! * Input: * queryName = "QueryAll1", repository = "repository" * Expect: * node: name = "QueryAll1" is removed * @throws Exception */ public void testRemoveSharedQuery() throws Exception { queryService.addSharedQuery("QueryAll1", "Select * from nt:base", "sql", new String[] { "*:/platform/administrators" }, false, sessionProvider); queryService.removeSharedQuery("QueryAll1", sessionProvider); Node nodeQuery = queryService.getSharedQuery("QueryAll1", sessionProvider); assertNull(nodeQuery); } /** * Get shared queries * Input: * 1. Add two shared query node * 1.1 queryName = "QueryAll1", statement = "Select * from nt:base", language = "sql", * permissions = { "*:/platform/administrators" }, cachedResult = false, * repository = "repository" * 1.2 queryName = "QueryAll2", statement = "//element(*, exo:article)", language = "xpath", * permissions = { "*:/platform/users" }, cachedResult = true, repository = "repository" * Input: * repository = "repository", provider = sessionProvider * Expect: * Size of listNode = 2, contains QueryAll1 and QueryAll2 node * Input: * userId = "root", repository = "repository", provider = sessionProvider * Expect: * Size of listNode = 2, contains QueryAll1 and QueryAll2 node * Input: * userId = "marry", repository = "repository", provider = sessionProvider * Expect: * Size of listNode = 1, contains QueryAll2 * Input: * queryType = "sql", userId = "root", repository = "repository", provider = sessionProvider * Expect: * Size of listNode = 1, contains QueryAll1 * Input: * queryType = "sql", userId = "marry", repository = "repository", provider = sessionProvider * Expect: * Size of listNode = 0 * Input: * queryType = "xpath", userId = "marry", repository = "repository", provider = sessionProvider * Expect: * Size of listNode = 1, contains QueryAll2 * @throws Exception */ public void testGetSharedQueries() throws Exception { SessionProvider sessionProvider = sessionProviderService_.getSystemSessionProvider(null); queryService.addSharedQuery("QueryAll1", "Select * from nt:base", "sql", new String[] { "*:/platform/administrators" }, false, sessionProvider); queryService.addSharedQuery("QueryAll2", "//element(*, exo:article)", "xpath", new String[] { "*:/platform/users" }, true, sessionProvider); List<Node> listQuery = queryService.getSharedQueries(sessionProvider); assertEquals(listQuery.size(), 5); listQuery = queryService.getSharedQueries("demo", sessionProvider); assertEquals(listQuery.size(), 4); listQuery = queryService.getSharedQueries("xpath", "demo", sessionProvider); assertEquals(listQuery.size(), 4); Node queriesHome = (Node) sessionProvider.getSession(DMSSYSTEM_WS, repository).getItem(baseQueriesPath); queriesHome.getNode("QueryAll1").remove(); queriesHome.getNode("QueryAll2").remove(); queriesHome.save(); } /** * Execute query by giving the following params : queryPath, workspace, repository, * provider, userId * Input: * 1. Add two shared query node * 1.1 queryName = "QueryAll1", statement = * "Select * from nt:base where jcr:path like '/exo:ecm/queries/%'", language = "sql", * permissions = { "*:/platform/administrators" }, cachedResult = false, * repository = "repository" * 1.2 queryName = "QueryAll2", statement = "//element(*, exo:article)", language = "xpath", * permissions = { "*:/platform/users" }, cachedResult = true, repository = "repository" * Input: * queryPath = "/exo:ecm/queries/QueryAll1", workspace = DMSSYSTEM_WS, * repository = "repository", provider = sessionProvider, userId = "root" * Expect: * Size of list node = 2 * Input: * queryPath = "/exo:ecm/queries/QueryAll2", workspace = DMSSYSTEM_WS, * repository = "repository", provider = sessionProvider, userId = "root" * Expect: * exception: Query Path not found! * @throws Exception */ public void testExecute() throws Exception { SessionProvider sessionProvider = sessionProviderService_.getSystemSessionProvider(null); queryService.addSharedQuery("QueryAll1", "Select * from nt:base where jcr:path like '/exo:ecm/queries/%'", "sql", new String[] { "*:/platform/administrators" }, false, sessionProvider); queryService.addSharedQuery("QueryAll2", "Select * from nt:base where jcr:path like '/exo:ecm/queries/%'", "sql", new String[] { "*:/platform/administrators" }, true, sessionProvider); String queryPath = baseQueriesPath + "/QueryAll1"; QueryResult queryResult = queryService.execute(queryPath, DMSSYSTEM_WS, sessionProvider, "root"); assertEquals(queryResult.getNodes().getSize(), 5); queryPath = baseQueriesPath + "/QueryAll2"; queryResult = queryService.execute(queryPath, DMSSYSTEM_WS, sessionProvider, "root"); assertEquals(queryResult.getNodes().getSize(), 5); Node queriesHome = (Node) sessionProvider.getSession(DMSSYSTEM_WS, repository).getItem(baseQueriesPath); queriesHome.getNode("QueryAll1").remove(); queriesHome.getNode("QueryAll2").remove(); queriesHome.save(); } public void tearDown() throws Exception { Session mySession = sessionProviderService_.getSystemSessionProvider(null).getSession(COLLABORATION_WS, repository); for (String user : USERS) { try { Node userNode = nodeHierarchyCreator.getUserNode(sessionProvider, user); String searchPaths = userNode.getPath() + "/" + relativePath; ((Node)mySession.getItem(searchPaths)).remove(); mySession.save(); } catch (PathNotFoundException e) { } } super.tearDown(); } }
19,873
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
MockCmsServiceImpl.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/cms/MockCmsServiceImpl.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.ecm.dms.cms; import java.util.Map; import javax.jcr.Node; import javax.jcr.Session; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.services.cms.impl.CmsServiceImpl; import org.exoplatform.services.idgenerator.IDGeneratorService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.listener.ListenerService; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Mar 16, 2011 * 5:45:40 PM */ public class MockCmsServiceImpl extends CmsServiceImpl { private RepositoryService jcrService; public MockCmsServiceImpl(RepositoryService jcrService, IDGeneratorService idGeneratorService, ListenerService listenerService) { super(jcrService, idGeneratorService, listenerService); this.jcrService = jcrService; } public String storeNode(String workspace, String nodeTypeName, String storePath, Map mappings) throws Exception { ExoContainer container = ExoContainerContext.getCurrentContainer(); SessionProviderService service = (SessionProviderService)container.getComponentInstanceOfType(SessionProviderService.class); Session session = service.getSystemSessionProvider(null).getSession(workspace, jcrService.getCurrentRepository()); Node storeHomeNode = (Node) session.getItem(storePath); String path = storeNode(nodeTypeName, storeHomeNode, mappings, true); storeHomeNode.save(); session.save(); return path; } }
2,519
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestCmsService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/cms/TestCmsService.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.ecm.dms.cms; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.exoplatform.commons.utils.ISO8601; import org.exoplatform.services.cms.CmsService; import org.exoplatform.services.cms.JcrInputProperty; import org.exoplatform.services.wcm.BaseWCMTestCase; import org.apache.commons.lang3.StringUtils; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; /** * Created by The eXo Platform SARL * Author : Hoang Van Hung * hunghvit@gmail.com * Jun 12, 2009 */ @FixMethodOrder(MethodSorters.JVM) public class TestCmsService extends BaseWCMTestCase { private CmsService cmsService; private static final String ARTICLE = "exo:article"; private static final String NTRESOURCE = "nt:resource"; public void setUp() throws Exception { super.setUp(); cmsService = (CmsService) container.getComponentInstanceOfType(CmsService.class); applySystemSession(); } public void tearDown() throws Exception { super.tearDown(); } /** * Create data for String with String property */ private Map<String, JcrInputProperty> createArticleMapInput() { Map<String, JcrInputProperty> map = new HashMap<String, JcrInputProperty>(); String titlePath = CmsService.NODE + "/" + "exo:title"; String summaryPath = CmsService.NODE + "/" + "exo:summary"; String textPath = CmsService.NODE + "/" + "exo:text"; JcrInputProperty inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(CmsService.NODE); inputProperty.setValue("document_1"); map.put(CmsService.NODE, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(titlePath); inputProperty.setValue("this is title"); map.put(titlePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(summaryPath); inputProperty.setValue("this is summary"); map.put(summaryPath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(textPath); inputProperty.setValue("this is article content"); map.put(textPath, inputProperty); return map; } /** * Add mixin for node */ private Map<String, JcrInputProperty> createArticleEditMapInput() { Map<String, JcrInputProperty> map = new HashMap<String, JcrInputProperty>(); String titlePath = CmsService.NODE + "/" + "exo:title"; String categoryPath = CmsService.NODE + "/" + "exo:category"; JcrInputProperty inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(CmsService.NODE); inputProperty.setMixintype("exo:categorized"); inputProperty.setValue("document_1"); map.put(CmsService.NODE, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(titlePath); inputProperty.setValue("this is title edit"); map.put(titlePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(categoryPath); inputProperty.setValue(new String[] {COLLABORATION_WS + ":/referencedNodeArticle"}); map.put(categoryPath, inputProperty); return map; } /** * Create data for Node with String and date time property */ private Map<String, JcrInputProperty> createSampleMapInput() { Map<String, JcrInputProperty> map = new HashMap<String, JcrInputProperty>(); String titlePath = CmsService.NODE + "/" + "exo:title"; String descriptPath = CmsService.NODE + "/" + "exo:description"; String datePath = CmsService.NODE + "/" + "exo:date"; String datetimePath = CmsService.NODE + "/" + "exo:datetime"; String summaryPath = CmsService.NODE + "/" + "exo:summary"; String contentPath = CmsService.NODE + "/" + "exo:content"; String totalScorePath = CmsService.NODE + "/" + "exo:totalScore"; String averageScorePath = CmsService.NODE + "/" + "exo:averageScore"; String moveablePath = CmsService.NODE + "/" + "exo:moveable"; JcrInputProperty inputProperty = new JcrInputProperty(); inputProperty.setValue("document_2"); inputProperty.setJcrPath(CmsService.NODE); //inputProperty.setMixintype("mix:cms"); map.put(CmsService.NODE, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(titlePath); inputProperty.setValue("this is title"); map.put(titlePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(descriptPath); inputProperty.setValue("this is description"); map.put(descriptPath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(datePath); inputProperty.setValue(ISO8601.parse("06/12/2009")); map.put(datePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(datetimePath); inputProperty.setValue(ISO8601.parse("06/12/2009 14:58:49")); map.put(datetimePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(summaryPath); inputProperty.setValue("this is summary"); map.put(summaryPath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(contentPath); inputProperty.setValue("this is sample's content"); map.put(contentPath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(totalScorePath); inputProperty.setValue(new Long(15)); map.put(totalScorePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(averageScorePath); inputProperty.setValue(new Double(1.23)); map.put(averageScorePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(moveablePath); inputProperty.setValue("true"); map.put(moveablePath, inputProperty); return map; } /** * Create data for Node with String and date time property */ private Map<String, JcrInputProperty> createSampleMapInputEdit() { Map<String, JcrInputProperty> map = new HashMap<String, JcrInputProperty>(); String titlePath = CmsService.NODE + "/" + "exo:title"; String descriptPath = CmsService.NODE + "/" + "exo:description"; String datePath = CmsService.NODE + "/" + "exo:date"; String datetimePath = CmsService.NODE + "/" + "exo:datetime"; String summaryPath = CmsService.NODE + "/" + "exo:summary"; String contentPath = CmsService.NODE + "/" + "exo:content"; String totalScorePath = CmsService.NODE + "/" + "exo:totalScore"; String averageScorePath = CmsService.NODE + "/" + "exo:averageScore"; String moveablePath = CmsService.NODE + "/" + "exo:moveable"; String linkPath = CmsService.NODE + "/" + "exo:linkdata"; JcrInputProperty inputProperty = new JcrInputProperty(); inputProperty.setValue("document_2"); inputProperty.setJcrPath(CmsService.NODE); //inputProperty.setMixintype("mix:cms"); map.put(CmsService.NODE, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(titlePath); inputProperty.setValue("this is title edit"); map.put(titlePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(descriptPath); inputProperty.setValue("this is description"); map.put(descriptPath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(datePath); inputProperty.setValue(ISO8601.parse("06/12/2009")); map.put(datePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(datetimePath); inputProperty.setValue(ISO8601.parse("06/12/2009 14:58:49")); map.put(datetimePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(summaryPath); inputProperty.setValue("this is summary"); map.put(summaryPath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(contentPath); inputProperty.setValue("this is sample's content"); map.put(contentPath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(totalScorePath); inputProperty.setValue(new Long(16)); map.put(totalScorePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(averageScorePath); inputProperty.setValue(new Double(2.34)); map.put(averageScorePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(moveablePath); inputProperty.setValue("false"); map.put(moveablePath, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(linkPath); inputProperty.setValue(COLLABORATION_WS + ":/referencedNode"); map.put(linkPath, inputProperty); return map; } /** * Create data for Node with String and date time property */ private Map<String, JcrInputProperty> createReferenceMapInput() { Map<String, JcrInputProperty> map = new HashMap<String, JcrInputProperty>(); String categoryPath = CmsService.NODE + "/" + "exo:category"; JcrInputProperty inputProperty = new JcrInputProperty(); inputProperty.setValue("document_3"); inputProperty.setJcrPath(CmsService.NODE); inputProperty.setMixintype("exo:categorized"); map.put(CmsService.NODE, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(categoryPath); inputProperty.setValue(new String[] {COLLABORATION_WS + ":/referencedNode"}); map.put(categoryPath, inputProperty); return map; } /** * Test property value is string with * CmsService.storeNode(String nodetypeName, Node storeNode, Map inputProperties, boolean isAddNew,String repository) * Input: property for node: exo:title = "this is title";exo:summary="this is summary";exo:text="this is article content" * name = "document_1"; * Expect: node: name = "document_1";property for node: exo:title = "this is title"; * exo:summary="this is summary";exo:text="this is article content" */ public void testStoreNodeArticle() throws RepositoryException, Exception { Node storeNode = session.getRootNode(); Map<String, JcrInputProperty> map = createArticleMapInput(); String path = cmsService.storeNode(ARTICLE, storeNode, map, true); assertTrue(session.itemExists(path)); Node articleNode = (Node)session.getItem(path); assertEquals("document_1", articleNode.getName()); assertEquals("this is title", articleNode.getProperty("exo:title").getString()); assertEquals("this is summary", articleNode.getProperty("exo:summary").getString()); assertEquals("this is article content", articleNode.getProperty("exo:text").getString()); } /** * Test add mixin * CmsService.storeNode(String nodetypeName, Node storeNode, Map inputProperties, boolean isAddNew,String repository)} * Input: property for node: exo:title = "this is title";exo:summary="this is summary";exo:text="this is article content" * exo:category = uuid of one reference node; name = "document_1"; * Expect: node: name = "document_1";property for node: exo:title = "this is title"; * exo:summary="this is summary";exo:text="this is article content"; exo:category = uuid of one reference node above; */ public void testStoreNodeArticleEdit() throws RepositoryException, Exception { Node storeNode = session.getRootNode(); Node referencedNode = storeNode.addNode("referencedNodeArticle"); if (referencedNode.canAddMixin("mix:referenceable")) { referencedNode.addMixin("mix:referenceable"); } session.save(); Map<String, JcrInputProperty> map = createArticleMapInput(); String path1 = cmsService.storeNode(ARTICLE, storeNode, map, true); assertTrue(session.itemExists(path1)); Node articleNode = (Node)session.getItem(path1); assertEquals("document_1", articleNode.getName()); assertEquals("this is title", articleNode.getProperty("exo:title").getValue().getString()); map = createArticleEditMapInput(); String path2 = cmsService.storeNode(ARTICLE, storeNode, map, false); assertTrue(session.itemExists(path2)); session.getItem(path1).remove(); if(!StringUtils.equals(path1, path2)) { session.getItem(path2).remove(); } referencedNode.remove(); session.save(); } /** * Test property value is string with * CmsService.storeNode(String workspace, String nodetypeName, String storePath, Map inputProperties,String repository) * Input: property for node: exo:title = "this is title";exo:summary="this is summary";exo:text="this is article content" * name = "document_1"; * Expect: node: name = "document_1";property for node: exo:title = "this is title"; * exo:summary="this is summary";exo:text="this is article content" */ // public void testStoreNodeArticleByPath1() throws RepositoryException, Exception { // Node storeNode = session.getRootNode().addNode("storeNode"); // session.save(); // Map<String, JcrInputProperty> map = createArticleMapInput(); // String path = cmsService.storeNode(COLLABORATION_WS, ARTICLE, storeNode.getPath(), map, REPO_NAME); // assertTrue(session.itemExists(path)); // Node articleNode = (Node)session.getItem(path); // assertEquals("document_1", articleNode.getName()); // assertEquals("this is title", articleNode.getProperty("exo:title").getString()); // assertEquals("this is summary", articleNode.getProperty("exo:summary").getString()); // assertEquals("this is article content", articleNode.getProperty("exo:text").getString()); // // articleNode.remove(); // storeNode.remove(); // session.save(); // } /** * Create binary data * @throws IOException */ private Map<String, JcrInputProperty> createBinaryMapInput() throws IOException { Map<String, JcrInputProperty> map = new HashMap<String, JcrInputProperty>(); String data = CmsService.NODE + "/" + "jcr:data"; JcrInputProperty inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(CmsService.NODE); inputProperty.setValue("BinaryData"); map.put(CmsService.NODE, inputProperty); inputProperty = new JcrInputProperty(); inputProperty.setJcrPath(data); inputProperty.setValue("test"); map.put(data, inputProperty); return map; } /** * Test property value is binary * input: data of file /conf/standalone/system-configuration.xml * output: value in property jcr:data of one nt:resource node = value in file /conf/standalone/system-configuration.xml * @throws RepositoryException * @throws Exception */ public void testStoreNodeBinaryProperty() throws RepositoryException, Exception { Node rootNode = session.getRootNode(); Map<String, JcrInputProperty> map = createBinaryMapInput(); if ((rootNode != null) && (map != null)) { try { System.out.println("NTRESOURCE: " + NTRESOURCE); System.out.println("rootNode: " + rootNode.getPath()); System.out.println("map: " + map); System.out.println("REPO_NAME: " + REPO_NAME); String path1 = cmsService.storeNode(NTRESOURCE, rootNode, map, true); System.out.println("path1: " + path1); assertTrue(session.itemExists(path1)); Node binaryNode = (Node)session.getItem(path1); assertEquals("BinaryData", binaryNode.getName()); InputStream is = getClass().getResource("/conf/standalone/system-configuration.xml").openStream(); assertEquals("test", binaryNode.getProperty("jcr:data").getString()); binaryNode.remove(); session.save(); } catch (NullPointerException e) { // TODO: handle exception } } } /** * Test with path does not existed, * Input: /temp: path does not exist * Expect: PathNotFoundException * @throws RepositoryException * @throws Exception */ public void testStoreNodeArticleByPath2() throws RepositoryException, Exception { Map<String, JcrInputProperty> map = createArticleMapInput(); try { MockCmsServiceImpl mock = (MockCmsServiceImpl) container.getComponentInstanceOfType(MockCmsServiceImpl.class); String path = mock.storeNode(COLLABORATION_WS, ARTICLE, "/temp", map); session.getItem(path).remove(); session.save(); } catch (PathNotFoundException ex) { } } /** * Test create property with reference type * Input: property for node: exo:category = uuid of one reference node; name = "document_3"; * Expect: node: name = "document_3";property for node: exo:category = uuid of one reference node above; * @throws RepositoryException * @throws Exception */ public void testStoreNodeWithReference() throws RepositoryException, Exception { Node storeNode = session.getRootNode(); Node referencedNode = storeNode.addNode("referencedNode"); session.save(); if (referencedNode.canAddMixin("mix:referenceable")) { referencedNode.addMixin("mix:referenceable"); } session.save(); String uuid = referencedNode.getUUID(); Map<String, JcrInputProperty> map = createReferenceMapInput(); String path1 = cmsService.storeNode(ARTICLE, storeNode, map, true); assertTrue(session.itemExists(path1)); Node sampleNode = (Node)session.getItem(path1); assertEquals("document_3", sampleNode.getName()); assertEquals(uuid, sampleNode.getProperty("exo:category").getValues()[0].getString()); sampleNode.remove(); referencedNode.remove(); session.save(); } /** * Test method CmsService.moveNode() * Move node test1 to test2 node, clean test1 node * Expect: node test1 does not exist, node test2/test1 exits * @throws Exception */ public void testMoveNode() throws Exception { Node test1 = session.getRootNode().addNode("source"); session.save(); Session session2 = sessionProviderService_.getSystemSessionProvider(null).getSession(SYSTEM_WS, repository); Node test2 = session.getRootNode().addNode("target"); session2.save(); String destPath = test2.getPath() + test1.getPath(); cmsService.moveNode(test1.getPath(), COLLABORATION_WS, SYSTEM_WS, destPath); assertTrue(session2.itemExists(destPath)); assertTrue(!session.itemExists("/source")); test2.remove(); session.save(); session2.save(); } /** * Compare two input stream, return true if bytes of is1 equal bytes of is2 * @param is1 * @param is2 * @return * @throws IOException */ private boolean compareInputStream(InputStream is1, InputStream is2) throws IOException { int b1, b2; do { b1 = is1.read(); b2 = is2.read(); if (b1 != b2) return false; } while ((b1 !=-1) && (b2!=-1)); return true; } }
20,273
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestTimelineService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/timeline/TestTimelineService.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.ecm.dms.timeline; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import javax.jcr.Node; import org.exoplatform.services.cms.timeline.TimelineService; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.wcm.BaseWCMTestCase; /** * Created by The eXo Platform SARL * Author : Dang Van Minh * minh.dang@exoplatform.com * Oct 22, 2009 * 10:50:05 AM */ public class TestTimelineService extends BaseWCMTestCase { private TimelineService timelineService; final private static String EXO_MODIFIED_DATE = "exo:dateModified"; public void setUp() throws Exception { super.setUp(); timelineService = (TimelineService)container.getComponentInstanceOfType(TimelineService.class); applyUserSession("root", "gtn",COLLABORATION_WS); } /** * test method getDocumentsOfToday * input: /testNode/today1(dateModified is today) * /testNode/today2(dateModified is today) * /testNode/yesterday1(dateModified is yesterday) * action: getDocumentsOfToday * expectedValue: 2(today1 and today2); * @throws Exception */ public void testGetDocumentsOfToday() throws Exception { Node rootNode = session.getRootNode(); Node testNode = rootNode.addNode("testNode"); Calendar currentTime = new GregorianCalendar(); Node today1 = testNode.addNode("today1", "exo:article"); today1.setProperty("exo:title", "sample"); if(today1.canAddMixin("exo:datetime")) today1.addMixin("exo:datetime"); today1.setProperty(EXO_MODIFIED_DATE, currentTime); Node today2 = testNode.addNode("today2", "exo:article"); today2.setProperty("exo:title", "sample"); if(today2.canAddMixin("exo:datetime")) today2.addMixin("exo:datetime"); today2.setProperty(EXO_MODIFIED_DATE, currentTime); Calendar yesterdayTime = (Calendar)currentTime.clone(); yesterdayTime.add(Calendar.DATE, -1); Node yesterday1 = testNode.addNode("yesterday1", "exo:article"); yesterday1.setProperty("exo:title", "sample"); if(yesterday1.canAddMixin("exo:datetime")) yesterday1.addMixin("exo:datetime"); yesterday1.setProperty(EXO_MODIFIED_DATE, yesterdayTime); session.save(); List<Node> res = timelineService.getDocumentsOfToday(testNode.getPath(), COLLABORATION_WS, createSessionProvider(), "root", true); assertEquals("testGetDocumentsOfToday failed! ", 2, res.size()); } /** * test method getDocumentsOfToday * input: /testNode/today1(dateModified is today) * /testNode/today2(dateModified is today) * /testNode/today3(dateModified is today) * /testNode/today4(dateModified is today) * /testNode/today5(dateModified is today) * /testNode/today6(dateModified is today) * /testNode/yesterday1(dateModified is yesterday) * action: getDocumentsOfToday * expectedValue: 6(today1, today2, today3, today4, today5 and today6); * @throws Exception */ public void testGetDocumentsOfTodayUnLimited() throws Exception { Node rootNode = session.getRootNode(); Node testNode = rootNode.addNode("testNode"); Calendar currentTime = new GregorianCalendar(); Node today1 = testNode.addNode("today1", "exo:article"); today1.setProperty("exo:title", "sample"); if(today1.canAddMixin("exo:datetime")) today1.addMixin("exo:datetime"); today1.setProperty(EXO_MODIFIED_DATE, currentTime); Node today2 = testNode.addNode("today2", "exo:article"); today2.setProperty("exo:title", "sample"); if(today2.canAddMixin("exo:datetime")) today2.addMixin("exo:datetime"); today2.setProperty(EXO_MODIFIED_DATE, currentTime); Node today3 = testNode.addNode("today3", "exo:article"); today3.setProperty("exo:title", "sample"); if(today3.canAddMixin("exo:datetime")) today3.addMixin("exo:datetime"); today3.setProperty(EXO_MODIFIED_DATE, currentTime); Node today4 = testNode.addNode("today4", "exo:article"); today4.setProperty("exo:title", "sample"); if(today4.canAddMixin("exo:datetime")) today4.addMixin("exo:datetime"); today4.setProperty(EXO_MODIFIED_DATE, currentTime); Node today5 = testNode.addNode("today5", "exo:article"); today5.setProperty("exo:title", "sample"); if(today5.canAddMixin("exo:datetime")) today5.addMixin("exo:datetime"); today5.setProperty(EXO_MODIFIED_DATE, currentTime); Node today6 = testNode.addNode("today6", "exo:article"); today6.setProperty("exo:title", "sample"); if(today6.canAddMixin("exo:datetime")) today6.addMixin("exo:datetime"); today6.setProperty(EXO_MODIFIED_DATE, currentTime); Calendar yesterdayTime = (Calendar)currentTime.clone(); yesterdayTime.add(Calendar.DATE, -1); Node yesterday1 = testNode.addNode("yesterday1", "exo:article"); yesterday1.setProperty("exo:title", "sample"); if(yesterday1.canAddMixin("exo:datetime")) yesterday1.addMixin("exo:datetime"); yesterday1.setProperty(EXO_MODIFIED_DATE, yesterdayTime); session.save(); List<Node> res = timelineService.getDocumentsOfToday(testNode.getPath(), COLLABORATION_WS, createSessionProvider(), "root", true, false); assertEquals("testGetDocumentsOfToday failed! ", 6, res.size()); } /** * test method getDocumentsOfYesterday * input: /testNode/today1(dateModified is today) * /testNode/today2(dateModified is today) * /testNode/yesterday1(dateModified is yesterday) * action: getDocumentsOfYesterday * expectedValue: 1(yesterday1) * @throws Exception */ public void testGetDocumentsOfYesterday() throws Exception { Node rootNode = session.getRootNode(); Node testNode = rootNode.addNode("testNode"); Calendar currentTime = new GregorianCalendar(); Node today1 = testNode.addNode("today1", "exo:article"); today1.setProperty("exo:title", "sample"); if(today1.canAddMixin("exo:datetime")) { today1.addMixin("exo:datetime"); } today1.setProperty(EXO_MODIFIED_DATE, currentTime); Node today2 = testNode.addNode("today2", "exo:article"); today2.setProperty("exo:title", "sample"); if(today2.canAddMixin("exo:datetime")) { today2.addMixin("exo:datetime"); } today2.setProperty(EXO_MODIFIED_DATE, currentTime); Calendar yesterdayTime = (Calendar)currentTime.clone(); yesterdayTime.add(Calendar.DATE, -1); Node yesterday1 = testNode.addNode("yesterday1", "exo:article"); yesterday1.setProperty("exo:title", "sample"); if(yesterday1.canAddMixin("exo:datetime")) { yesterday1.addMixin("exo:datetime"); } yesterday1.setProperty(EXO_MODIFIED_DATE, yesterdayTime); session.save(); List<Node> res = timelineService.getDocumentsOfYesterday(rootNode.getPath(), COLLABORATION_WS, createSessionProvider(), "root", true); assertEquals("testGetDocumentsOfYesterday failed! ", 1, res.size()); } /** * test method getDocumentsOfYesterday * input: /testNode/today1(dateModified is today) * /testNode/today2(dateModified is today) * /testNode/yesterday1(dateModified is yesterday) * /testNode/yesterday2(dateModified is yesterday) * /testNode/yesterday3(dateModified is yesterday) * /testNode/yesterday4(dateModified is yesterday) * /testNode/yesterday5(dateModified is yesterday) * /testNode/yesterday6(dateModified is yesterday) * /testNode/yesterday7(dateModified is yesterday) * action: getDocumentsOfYesterday * expectedValue: 7(yesterday1, yesterday2, yesterday3, yesterday4, yesterday5, yesterday6, yesterday6)); * @throws Exception */ public void testGetDocumentsOfYesterdayUnLimited() throws Exception { Node rootNode = session.getRootNode(); Node testNode = rootNode.addNode("testNode"); Calendar currentTime = new GregorianCalendar(); Node today1 = testNode.addNode("today1", "exo:article"); today1.setProperty("exo:title", "sample"); if(today1.canAddMixin("exo:datetime")) { today1.addMixin("exo:datetime"); } today1.setProperty(EXO_MODIFIED_DATE, currentTime); Node today2 = testNode.addNode("today2", "exo:article"); today2.setProperty("exo:title", "sample"); if(today2.canAddMixin("exo:datetime")) { today2.addMixin("exo:datetime"); } today2.setProperty(EXO_MODIFIED_DATE, currentTime); Calendar yesterdayTime = (Calendar)currentTime.clone(); yesterdayTime.add(Calendar.DATE, -1); Node yesterday1 = testNode.addNode("yesterday1", "exo:article"); yesterday1.setProperty("exo:title", "sample"); if(yesterday1.canAddMixin("exo:datetime")) { yesterday1.addMixin("exo:datetime"); } yesterday1.setProperty(EXO_MODIFIED_DATE, yesterdayTime); Node yesterday2 = testNode.addNode("yesterday2", "exo:article"); yesterday2.setProperty("exo:title", "sample"); if(yesterday2.canAddMixin("exo:datetime")) { yesterday2.addMixin("exo:datetime"); } yesterday2.setProperty(EXO_MODIFIED_DATE, yesterdayTime); Node yesterday3 = testNode.addNode("yesterday3", "exo:article"); yesterday3.setProperty("exo:title", "sample"); if(yesterday3.canAddMixin("exo:datetime")) { yesterday3.addMixin("exo:datetime"); } yesterday3.setProperty(EXO_MODIFIED_DATE, yesterdayTime); Node yesterday4 = testNode.addNode("yesterday4", "exo:article"); yesterday4.setProperty("exo:title", "sample"); if(yesterday4.canAddMixin("exo:datetime")) { yesterday4.addMixin("exo:datetime"); } yesterday4.setProperty(EXO_MODIFIED_DATE, yesterdayTime); Node yesterday5 = testNode.addNode("yesterday5", "exo:article"); yesterday5.setProperty("exo:title", "sample"); if(yesterday5.canAddMixin("exo:datetime")) { yesterday5.addMixin("exo:datetime"); } yesterday5.setProperty(EXO_MODIFIED_DATE, yesterdayTime); Node yesterday6 = testNode.addNode("yesterday6", "exo:article"); yesterday6.setProperty("exo:title", "sample"); if(yesterday6.canAddMixin("exo:datetime")) { yesterday6.addMixin("exo:datetime"); } yesterday6.setProperty(EXO_MODIFIED_DATE, yesterdayTime); Node yesterday7 = testNode.addNode("yesterday7", "exo:article"); yesterday7.setProperty("exo:title", "sample"); if(yesterday7.canAddMixin("exo:datetime")) { yesterday7.addMixin("exo:datetime"); } yesterday7.setProperty(EXO_MODIFIED_DATE, yesterdayTime); session.save(); List<Node> resLimit = timelineService.getDocumentsOfYesterday(rootNode.getPath(), COLLABORATION_WS, createSessionProvider(), "root", true); List<Node> resUnLimit = timelineService.getDocumentsOfYesterday(rootNode.getPath(), COLLABORATION_WS, createSessionProvider(), "root", true, false); assertEquals("testGetDocumentsOfYesterday failed! ", 7, resUnLimit.size()); assertEquals("testGetDocumentsOfYesterday failed! ", 5, resLimit.size()); } /** * test method getDocumentsOfEarlierThisWeek * input: /testNode/Sunday * /testNode/Monday * /testNode/Tuesday * ... * /testNode/${today} (depends on current date time) * action: getDocumentsOfEarlierThisWeek * expectedValue: (depends on current date time, must calculate yourself); * @throws Exception */ public void testGetDocumentsOfEarlierThisWeek() throws Exception { Node rootNode = session.getRootNode(); Node testNode = rootNode.addNode("testNode"); int count = 0; Calendar currentTime = new GregorianCalendar(); Calendar time = (Calendar)currentTime.clone(); int index = 0; while (currentTime.get(Calendar.WEEK_OF_YEAR) == time.get(Calendar.WEEK_OF_YEAR)) { count++; Node dayNode = testNode.addNode("dayNode" + index++, "exo:article"); dayNode.setProperty("exo:title", "sample"); if(dayNode.canAddMixin("exo:datetime")) { dayNode.addMixin("exo:datetime"); } dayNode.setProperty(EXO_MODIFIED_DATE, time); session.save(); time.add(Calendar.DATE, -1); } //exclude today and yesterday if (count < 2){ count = 0; }else{ count -= 2; } session.save(); List<Node> res = timelineService.getDocumentsOfEarlierThisWeek(rootNode.getPath(), COLLABORATION_WS, createSessionProvider(), "root", true); assertEquals("testGetDocumentsOfEarlierThisWeek failed! ", Math.min(5, count), res.size()); } /** * test method getDocumentsOfEarlierThisWeek * input: /testNode/Sunday * /testNode/Monday * /testNode/Tuesday * ... * /testNode/${today} (depends on current date time) * action: getDocumentsOfEarlierThisWeek * expectedValue: (depends on current date time, must calculate yourself); * @throws Exception */ public void testGetDocumentsOfEarlierThisWeek2() throws Exception { Node rootNode = session.getRootNode(); Node testNode = rootNode.addNode("testNode"); int count = 0; Calendar currentTime = new GregorianCalendar(); Calendar time = (Calendar)currentTime.clone(); int index = 0; while (currentTime.get(Calendar.WEEK_OF_YEAR) == time.get(Calendar.WEEK_OF_YEAR)) { count++; Node dayNode = testNode.addNode("dayNode" + index++, "exo:article"); dayNode.setProperty("exo:title", "sample"); if(dayNode.canAddMixin("exo:datetime")) { dayNode.addMixin("exo:datetime"); } dayNode.setProperty(EXO_MODIFIED_DATE, time); session.save(); time.add(Calendar.DATE, -1); } //exclude today and yesterday if (count < 2){ count = 0; }else{ count -= 2; } session.save(); List<Node> res = timelineService.getDocumentsOfEarlierThisWeek(rootNode.getPath(), COLLABORATION_WS, createSessionProvider(), "root", true, false); assertEquals("testGetDocumentsOfEarlierThisWeek failed! ", count, res.size()); } /** * test method getDocumentsOfEarlierThisMonth * input: /testNode/1stOfThisMonth * /testNode/2ndOfThisMonth * /testNode/3rdOfThisMonth * ... * /testNode/${today} (depends on current date time) * action: getDocumentsOfEarlierThisMonth * expectedValue: (depends on current date time, must calculate yourself); * @throws Exception */ public void testGetDocumentsOfEarlierThisMonth() throws Exception { Node rootNode = session.getRootNode(); Node testNode = rootNode.addNode("testNode"); Calendar currentTime = new GregorianCalendar(); Calendar time = (Calendar)currentTime.clone(); int count = 0; int index = 0; while (currentTime.get(Calendar.MONTH) == time.get(Calendar.MONTH)) { if (time.get(Calendar.WEEK_OF_YEAR) != currentTime.get(Calendar.WEEK_OF_YEAR)) { count++; } Node dayNode = testNode.addNode("dayNode" + index++, "exo:article"); dayNode.setProperty("exo:title", "sample"); if(dayNode.canAddMixin("exo:datetime")) { dayNode.addMixin("exo:datetime"); } dayNode.setProperty(EXO_MODIFIED_DATE, time); session.save(); time.add(Calendar.DATE, -1); } session.save(); List<Node> res = timelineService.getDocumentsOfEarlierThisMonth(rootNode.getPath(), COLLABORATION_WS, createSessionProvider(), "root", true); assertEquals("testGetDocumentsOfEarlierThisMonth failed! ", Math.min(5, count), res.size()); } /** * test method getDocumentsOfEarlierThisMonth * input: /testNode/1stOfThisMonth * /testNode/2ndOfThisMonth * /testNode/3rdOfThisMonth * ... * /testNode/${today} (depends on current date time) * action: getDocumentsOfEarlierThisMonth * expectedValue: (depends on current date time, must calculate yourself); * @throws Exception */ public void testGetDocumentsOfEarlierThisMonth2() throws Exception { Node rootNode = session.getRootNode(); Node testNode = rootNode.addNode("testNode"); Calendar currentTime = new GregorianCalendar(); Calendar time = (Calendar)currentTime.clone(); int count = 0; int index = 0; while (currentTime.get(Calendar.MONTH) == time.get(Calendar.MONTH)) { if (time.get(Calendar.WEEK_OF_YEAR) != currentTime.get(Calendar.WEEK_OF_YEAR)) { count++; } Node dayNode = testNode.addNode("dayNode" + index++, "exo:article"); dayNode.setProperty("exo:title", "sample"); if(dayNode.canAddMixin("exo:datetime")) { dayNode.addMixin("exo:datetime"); } dayNode.setProperty(EXO_MODIFIED_DATE, time); session.save(); time.add(Calendar.DATE, -1); } session.save(); List<Node> res = timelineService.getDocumentsOfEarlierThisMonth(rootNode.getPath(), COLLABORATION_WS, createSessionProvider(), "root", true, false); assertEquals("testGetDocumentsOfEarlierThisMonth failed! ", count, res.size()); } /** * test method getDocumentsOfEarlierThisYear * input: /testNode/1stOfThisYear * /testNode/2ndOfThisYear * /testNode/3rdOfThisYear * ... * /testNode/${today} (depends on current date time) * action: getDocumentsOfEarlierThisYear * expectedValue: (depends on current date time, must calculate yourself); * @throws Exception */ public void testGetDocumentsOfEarlierThisYear() throws Exception { Node rootNode = session.getRootNode(); Node testNode = rootNode.addNode("testNode"); Calendar currentTime = new GregorianCalendar(); Calendar time = (Calendar)currentTime.clone(); int count = 0; int index = 0; while (currentTime.get(Calendar.YEAR) == time.get(Calendar.YEAR)) { if (currentTime.get(Calendar.YEAR) == time.get(Calendar.YEAR)) { if (time.get(Calendar.MONTH) < currentTime.get(Calendar.MONTH)) count++; } Node dayNode = testNode.addNode("dayNode" + index++, "exo:article"); dayNode.setProperty("exo:title", "sample"); if(dayNode.canAddMixin("exo:datetime")) { dayNode.addMixin("exo:datetime"); } dayNode.setProperty(EXO_MODIFIED_DATE, time); session.save(); time.add(Calendar.DATE, -1); } session.save(); List<Node> res = timelineService.getDocumentsOfEarlierThisYear(rootNode.getPath(), COLLABORATION_WS, createSessionProvider(), "root", true); assertEquals("testGetDocumentsOfEarlierThisYear failed! ", Math.min(5, count), res.size()); } /** * test method getDocumentsOfEarlierThisYear * input: /testNode/1stOfThisYear * /testNode/2ndOfThisYear * /testNode/3rdOfThisYear * ... * /testNode/${today} (depends on current date time) * action: getDocumentsOfEarlierThisYear * expectedValue: (depends on current date time, must calculate yourself); * @throws Exception */ public void testGetDocumentsOfEarlierThisYear2() throws Exception { Node rootNode = session.getRootNode(); Node testNode = rootNode.addNode("testNode"); Calendar currentTime = new GregorianCalendar(); Calendar time = (Calendar)currentTime.clone(); int count = 0; int index = 0; while (currentTime.get(Calendar.YEAR) == time.get(Calendar.YEAR)) { if (currentTime.get(Calendar.YEAR) == time.get(Calendar.YEAR)) { if (time.get(Calendar.MONTH) < currentTime.get(Calendar.MONTH)) count++; } Node dayNode = testNode.addNode("dayNode" + index++, "exo:article"); dayNode.setProperty("exo:title", "sample"); if(dayNode.canAddMixin("exo:datetime")) { dayNode.addMixin("exo:datetime"); } dayNode.setProperty(EXO_MODIFIED_DATE, time); session.save(); time.add(Calendar.DATE, -1); } session.save(); List<Node> res = timelineService.getDocumentsOfEarlierThisYear(rootNode.getPath(), COLLABORATION_WS, createSessionProvider(), "root", true, false); assertEquals("testGetDocumentsOfEarlierThisYear failed! ", count, res.size()); } /** * private method create sessionProvider instance. * @return SessionProvider */ private SessionProvider createSessionProvider() { SessionProviderService sessionProviderService = (SessionProviderService) container .getComponentInstanceOfType(SessionProviderService.class); return sessionProviderService.getSystemSessionProvider(null); } public void tearDown() throws Exception { Node rootNode = session.getRootNode(); Node testNode = rootNode.getNode("testNode"); if (testNode != null) testNode.remove(); session.save(); super.tearDown(); } }
25,174
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestDMSConfigurationService.java
/FileExtraction/Java_unseen/exoplatform_ecms/core/services/src/test/java/org/exoplatform/services/ecm/dms/configuration/TestDMSConfigurationService.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.ecm.dms.configuration; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.services.cms.impl.DMSRepositoryConfiguration; import org.exoplatform.services.wcm.BaseWCMTestCase; /** * Created by eXo Platform * Author : Nguyen Manh Cuong * manhcuongpt@gmail.com * Jun 24, 2009 */ /** * Unit test for DMSConfiguration * Methods need to test * 1. getConfig() method * 2. addPlugin() method * 3. initNewRepo() method */ public class TestDMSConfigurationService extends BaseWCMTestCase { private DMSConfiguration dmsConfiguration = null; private final static String TEST_WS = "workspace-test"; public void setUp() throws Exception { super.setUp(); dmsConfiguration = (DMSConfiguration)container.getComponentInstanceOfType(DMSConfiguration.class); } public void tearDown() throws Exception { super.tearDown(); } /** * Test Method: getConfig() * Expected: * get configuration contains: * Workspace Name: DMSSYSTEM_WS * Repository Name: REPO_NAME */ public void testGetConfig() throws Exception { DMSRepositoryConfiguration oldDmsRepoConf = dmsConfiguration.getConfig(); try { DMSRepositoryConfiguration dmsRepoConf = dmsConfiguration.getConfig(); assertEquals(DMSSYSTEM_WS, dmsRepoConf.getSystemWorkspace()); } finally { dmsConfiguration.addPlugin(oldDmsRepoConf); } } /** * Test Method: initNewRepo() * Input: DMSRepositoryConfiguration with new repository name and new workspace name * Expected: * New repository is initialized */ public void testInitNewRepo() throws Exception { DMSRepositoryConfiguration oldDmsRepoConf = dmsConfiguration.getConfig(); try { DMSRepositoryConfiguration dmsRepoConfig = new DMSRepositoryConfiguration(); dmsRepoConfig.setSystemWorkspace(TEST_WS); dmsConfiguration.initNewRepo(dmsRepoConfig); DMSRepositoryConfiguration dmsRepoConf = dmsConfiguration.getConfig(); assertEquals(TEST_WS, dmsRepoConf.getSystemWorkspace()); } finally { dmsConfiguration.addPlugin(oldDmsRepoConf); } } /** * Test Method: addPlugin() * Input: plugin is an instance of DMSRespositoryConfig * Expected: * plugin is added to repository */ public void testAddPlugin() throws Exception { DMSRepositoryConfiguration oldDmsRepoConf = dmsConfiguration.getConfig(); try { DMSRepositoryConfiguration dmsRepoConfig = new DMSRepositoryConfiguration(); dmsRepoConfig.setSystemWorkspace(TEST_WS); dmsConfiguration.addPlugin(dmsRepoConfig); DMSRepositoryConfiguration dmsRepoConf = dmsConfiguration.getConfig(); assertEquals(TEST_WS, dmsRepoConf.getSystemWorkspace()); } finally { dmsConfiguration.addPlugin(oldDmsRepoConf); } } }
3,843
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z