/** * Test if in mode <i>cleanup</i>, only the missing file is removed from a folder /var/dam is * removed if the payload points to a folder. * * @throws Exception in case of any error */ public void testCleanFolder() throws Exception { Node tiffFolder = getTiff().getParent(); Node gif = setUpBinary("test.xmp.gif", tiffFolder.getPath()); String toExist = createAsset(gif).getPath(); String toDelete = getAsset(false).getPath(); String tiffPath = getTiff().getPath(); Session session = getAdminSession(); session.removeItem(tiffPath); session.save(); executeWorkflowProcess(tiffPath, "mode:cleanup"); assertFalse("Binary for Asset has been removed", session.itemExists(toDelete)); assertTrue("Binary for Asset still present", session.itemExists(toExist)); }
/** * 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 if the removeExisting-flag removes an existing node in case of uuid conflict. */ public void testWorkspaceRestoreWithRemoveExistingJcr2() throws NotExecutableException, RepositoryException { // create version for parentNode of childNode superuser .getWorkspace() .clone( workspaceName, wVersionableChildNode.getPath(), wVersionableChildNode.getPath(), false); Version parentV = versionableNode .getSession() .getWorkspace() .getVersionManager() .checkin(versionableNode.getPath()); // move child node in order to produce the uuid conflict String newChildPath = wVersionableNode2.getPath() + "/" + wVersionableChildNode.getName(); wSuperuser.move(wVersionableChildNode.getPath(), newChildPath); wSuperuser.save(); // restore the parent with removeExisting == true >> moved child node // must be removed. wSuperuser.getWorkspace().getVersionManager().restore(new Version[] {parentV}, true); if (wSuperuser.itemExists(newChildPath)) { fail( "Workspace.restore(Version[], boolean) with the boolean flag set to true, must remove the existing node in case of Uuid conflict."); } }
/** {@inheritDoc} */ public void undeleteFile( final Session session, final PentahoJcrConstants pentahoJcrConstants, final Serializable fileId) throws RepositoryException { Node fileToUndeleteNode = session.getNodeByIdentifier(fileId.toString()); String trashFileIdNodePath = fileToUndeleteNode.getParent().getPath(); String origParentFolderPath = getOriginalParentFolderPath(session, pentahoJcrConstants, fileToUndeleteNode, false); String absDestPath = origParentFolderPath + RepositoryFile.SEPARATOR + fileToUndeleteNode.getName(); if (session.itemExists(absDestPath)) { RepositoryFile file = JcrRepositoryFileUtils.nodeToFile( session, pentahoJcrConstants, pathConversionHelper, lockHelper, (Node) session.getItem(absDestPath)); throw new RepositoryFileDaoFileExistsException(file); } session.move(fileToUndeleteNode.getPath(), absDestPath); session.getItem(trashFileIdNodePath).remove(); }
/** * Returns an internal folder to store all files deleted from a given folder. Provides fast access * when searching for files deleted from a given folder. */ private Node legacyGetTrashFolderIdNode( final Session session, final PentahoJcrConstants pentahoJcrConstants, final String origParentFolderPath) throws RepositoryException { // get folder id String folderId = null; if (session.itemExists(origParentFolderPath)) { folderId = ((Node) session.getItem(origParentFolderPath)).getIdentifier(); } else { throw new RuntimeException( Messages.getInstance() .getString("DefaultDeleteHelper.ERROR_0001_PATH_NOT_FOUND")); // $NON-NLS-1$ } final String prefix = session.getNamespacePrefix(PentahoJcrConstants.PHO_NS) + ":"; Node trashInternalFolderNode = getOrCreateTrashInternalFolderNode(session, pentahoJcrConstants); if (NodeHelper.hasNode(trashInternalFolderNode, prefix, folderId)) { return NodeHelper.getNode(trashInternalFolderNode, prefix, folderId); } else { // if Trash Structure 1 (legacy) doesn't exist, no need to create it now return null; } }
@Test public void testCreateLinkNode() throws AccessDeniedException, RepositoryException { Node fileNode = createFileNode(); Session session = mock(Session.class); Session adminSession = mock(Session.class); SlingRepository slingRepository = mock(SlingRepository.class); String linkPath = "/path/to/link"; String sitePath = "/path/to/site"; when(session.getUserID()).thenReturn("alice"); when(fileNode.getSession()).thenReturn(session); NodeType[] nodeTypes = new NodeType[0]; when(fileNode.getMixinNodeTypes()).thenReturn(nodeTypes); when(session.getItem(fileNode.getPath())).thenReturn(fileNode); when(adminSession.getItem(fileNode.getPath())).thenReturn(fileNode); when(slingRepository.loginAdministrative(null)).thenReturn(adminSession); when(adminSession.hasPendingChanges()).thenReturn(true); when(session.hasPendingChanges()).thenReturn(true); // link Node linkNode = mock(Node.class); when(session.itemExists(linkPath)).thenReturn(true); when(session.getItem(linkPath)).thenReturn(linkNode); FileUtils.createLink(fileNode, linkPath, null, slingRepository); verify(fileNode).addMixin(FilesConstants.REQUIRED_MIXIN); verify(session).save(); verify(adminSession).save(); verify(adminSession).logout(); }
/** * Test if in mode <i>cleanup</i>, a file removed from /var/dam is removed from /content/dam if * the payload points to a folder. * * @throws Exception in case of any error */ public void testCleanNotifyFile() throws Exception { String toRemove = getAsset(false).getPath(); String tiffPath = getTiff().getPath(); Session session = getAdminSession(); session.removeItem(tiffPath); session.save(); executeWorkflowProcess(tiffPath, "mode:cleanup"); assertFalse("Asset still exists", session.itemExists(toRemove)); }
/** * 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)); }
/** * The procedure which return the path existed in tree. * * @param node is a Node type which represents current node. * @param path a current path * @return the path existed in tree * @throws RepositoryException when some exceptions occurrence. */ public static String getExistPath(Node node, String path) throws RepositoryException { // The following process is added by lampt. int deep = getDepth(path); // In case of path is root path. if (deep == 0) { path = LinkUtils.getAncestorPath(path, 0); } else { Session session = node.getSession(); for (int i = deep; i > 0; i--) { if (session.itemExists(path)) break; path = getParentPath(path); } } return path; }
/** * Remove a User or Group from the list of viewers or the list of managers. Currently, the node * which points to the user/group remains in place, and only the specified membership property is * deleted. Note that a single user/group can be on both lists, and so their access rights might * not actually change as a result of being removed from a single list. * * @param session * @param filePath * @param authorizable * @param memberType * @throws RepositoryException */ protected void removeMember( Session session, String filePath, Authorizable authorizable, String memberType) throws RepositoryException { String memberPath = getMemberNodePath(filePath, authorizable); // Is there actually such a member? if (session.itemExists(memberPath)) { Node memberNode = session.getNode(memberPath); if (memberNode.hasProperty(memberType)) { // Remove the property. memberNode.setProperty(memberType, (Value[]) null); // Update ACEs that refer to this member. Principal principal = authorizable.getPrincipal(); refreshMemberAccess(session, filePath, principal, memberNode); } } }
@org.junit.Test public void testPathCreation() throws RepositoryException { assertTrue(session.itemExists(REPO_PATH)); }
public void execute(JobExecutionContext context) throws JobExecutionException { Session session = null; try { if (LOG.isInfoEnabled()) { LOG.info("Start Execute ImportXMLJob"); } if (stagingStorage == null) { JobDataMap jdatamap = context.getJobDetail().getJobDataMap(); stagingStorage = jdatamap.getString("stagingStorage"); temporaryStorge = jdatamap.getString("temporaryStorge"); if (LOG.isDebugEnabled()) { LOG.debug("Init parameters first time :"); } } SessionProvider sessionProvider = SessionProvider.createSystemProvider(); String containerName = WCMCoreUtils.getContainerNameFromJobContext(context); RepositoryService repositoryService_ = WCMCoreUtils.getService(RepositoryService.class, containerName); ManageableRepository manageableRepository = repositoryService_.getCurrentRepository(); PublicationService publicationService = WCMCoreUtils.getService(PublicationService.class, containerName); PublicationPlugin publicationPlugin = publicationService .getPublicationPlugins() .get(AuthoringPublicationConstant.LIFECYCLE_NAME); XMLInputFactory factory = XMLInputFactory.newInstance(); File stagingFolder = new File(stagingStorage); File tempfolder = new File(temporaryStorge); File[] files = null; File xmlFile = null; XMLStreamReader reader = null; InputStream xmlInputStream = null; int eventType; List<LinkObject> listLink = new ArrayList<LinkObject>(); LinkObject linkObj = new LinkObject(); boolean hasNewContent = false; if (stagingFolder.exists()) { files = stagingFolder.listFiles(); if (files != null) { hasNewContent = true; for (int i = 0; i < files.length; i++) { xmlFile = files[i]; if (xmlFile.isFile()) { MimeTypeResolver resolver = new MimeTypeResolver(); String fileName = xmlFile.getName(); String hashCode = fileName.split("-")[0]; String mimeType = resolver.getMimeType(xmlFile.getName()); if ("text/xml".equals(mimeType)) { xmlInputStream = new FileInputStream(xmlFile); reader = factory.createXMLStreamReader(xmlInputStream); while (reader.hasNext()) { eventType = reader.next(); if (eventType == XMLEvent.START_ELEMENT && "data".equals(reader.getLocalName())) { String data = reader.getElementText(); if (!tempfolder.exists()) tempfolder.mkdirs(); long time = System.currentTimeMillis(); File file = new File( temporaryStorge + File.separator + "-" + hashCode + "-" + time + ".xml.tmp"); InputStream inputStream = new ByteArrayInputStream(data.getBytes()); OutputStream out = new FileOutputStream(file); byte[] buf = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); } try { if (eventType == XMLEvent.START_ELEMENT && "published-content".equals(reader.getLocalName())) { linkObj.setSourcePath(reader.getAttributeValue(0)); // --Attribute // number // 0 = // targetPath } if (eventType == XMLEvent.START_ELEMENT && "type".equals(reader.getLocalName())) { linkObj.setLinkType(reader.getElementText()); } if (eventType == XMLEvent.START_ELEMENT && "title".equals(reader.getLocalName())) { linkObj.setLinkTitle(reader.getElementText()); } if (eventType == XMLEvent.START_ELEMENT && "targetPath".equals(reader.getLocalName())) { linkObj.setLinkTargetPath(reader.getElementText()); listLink.add(linkObj); } if (eventType == XMLEvent.START_ELEMENT && "unpublished-content".equals(reader.getLocalName())) { String contentTargetPath = reader.getAttributeValue(0); String[] strContentPath = contentTargetPath.split(":"); StringBuffer sbContPath = new StringBuffer(); boolean flag = true; for (int index = 2; index < strContentPath.length; index++) { if (flag) { sbContPath.append(strContentPath[index]); flag = false; } else { sbContPath.append(":").append(strContentPath[index]); } } sessionProvider = SessionProvider.createSystemProvider(); manageableRepository = repositoryService_.getCurrentRepository(); String workspace = strContentPath[1]; session = sessionProvider.getSession(workspace, manageableRepository); String contentPath = sbContPath.toString(); if (session.itemExists(contentPath)) { Node currentContent = (Node) session.getItem(contentPath); HashMap<String, String> variables = new HashMap<String, String>(); variables.put("nodePath", contentTargetPath); variables.put("workspaceName", workspace); if (currentContent.hasProperty( StageAndVersionPublicationConstant.PUBLICATION_LIFECYCLE_NAME) && AuthoringPublicationConstant.LIFECYCLE_NAME.equals( currentContent .getProperty( StageAndVersionPublicationConstant .PUBLICATION_LIFECYCLE_NAME) .getString()) && PublicationDefaultStates.PUBLISHED.equals( currentContent .getProperty(StageAndVersionPublicationConstant.CURRENT_STATE) .getString())) { publicationPlugin.changeState( currentContent, PublicationDefaultStates.UNPUBLISHED, variables); if (LOG.isInfoEnabled()) { LOG.info( "Change the status of the node " + currentContent.getPath() + " from " + PublicationDefaultStates.PUBLISHED + " to " + PublicationDefaultStates.UNPUBLISHED); } } } else { if (LOG.isWarnEnabled()) { LOG.warn("The node " + contentPath + " does not exist"); } } } } catch (Exception ie) { if (LOG.isWarnEnabled()) { LOG.warn("Error in ImportContentsJob: " + ie.getMessage()); } } } reader.close(); xmlInputStream.close(); xmlFile.delete(); } } } } } files = tempfolder.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { xmlFile = files[i]; InputStream inputStream = new FileInputStream(xmlFile); reader = factory.createXMLStreamReader(inputStream); String workspace = null; String nodePath = new String(); while (reader.hasNext()) { eventType = reader.next(); if (eventType == XMLEvent.START_ELEMENT) { if (reader.getLocalName().equals("property")) { String value = reader.getAttributeValue(0); if (MIX_TARGET_PATH.equals(value)) { eventType = reader.next(); if (eventType == XMLEvent.START_ELEMENT) { reader.next(); nodePath = reader.getText(); } } else if (MIX_TARGET_WORKSPACE.equals(value)) { eventType = reader.next(); if (eventType == XMLEvent.START_ELEMENT) { reader.next(); workspace = reader.getText(); } } } } } reader.close(); inputStream.close(); session = sessionProvider.getSession(workspace, manageableRepository); if (session.itemExists(nodePath)) session.getItem(nodePath).remove(); session.save(); String path = nodePath.substring(0, nodePath.lastIndexOf(JCR_File_SEPARATOR)); if (!session.itemExists(path)) { String[] pathTab = path.split(JCR_File_SEPARATOR); Node node_ = session.getRootNode(); StringBuffer path_ = new StringBuffer(JCR_File_SEPARATOR); for (int j = 1; j < pathTab.length; j++) { path_ = path_.append(pathTab[j] + JCR_File_SEPARATOR); if (!session.itemExists(path_.toString())) { node_.addNode(pathTab[j], "nt:unstructured"); } node_ = (Node) session.getItem(path_.toString()); } } session.importXML(path, new FileInputStream(xmlFile), 0); session.save(); xmlFile.delete(); if (hasNewContent) { for (LinkObject obj : listLink) { String[] linkTarget = obj.getLinkTargetPath().split(":"); StringBuffer itemPath = new StringBuffer(); boolean flag = true; for (int index = 2; index < linkTarget.length; index++) { if (flag) { itemPath.append(linkTarget[index]); flag = false; } else { itemPath.append(":"); itemPath.append(linkTarget[index]); } } String[] linkSource = obj.getSourcePath().split(":"); session = sessionProvider.getSession(linkTarget[1], manageableRepository); Node parentNode = (Node) session.getItem(itemPath.toString()); StringBuffer sourcePath = new StringBuffer(); boolean flagSource = true; for (int index = 2; index < linkSource.length; index++) { if (flagSource) { sourcePath.append(linkSource[index]); flagSource = false; } else { sourcePath.append(":"); sourcePath.append(linkSource[index]); } } if (parentNode.hasNode(obj.getLinkTitle())) { Node existedNode = (Node) session.getItem(itemPath + "/" + obj.getLinkTitle()); existedNode.remove(); } session = sessionProvider.getSession(linkSource[1], manageableRepository); Node targetNode = (Node) session.getItem(sourcePath.toString()); LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class, containerName); linkManager.createLink(parentNode, obj.getLinkType(), targetNode, obj.getLinkTitle()); } } } } if (LOG.isInfoEnabled()) { LOG.info("End Execute ImportXMLJob"); } } catch (RepositoryException ex) { if (LOG.isDebugEnabled()) { LOG.debug("Repository 'repository ' not found."); } } catch (Exception ex) { if (LOG.isErrorEnabled()) { LOG.error("Error when importing Contents : " + ex.getMessage(), ex); } } finally { if (session != null) session.logout(); } }
/** @see WorkflowProcess#execute(WorkItem, WorkflowSession, MetaDataMap) */ public void execute(WorkItem workItem, WorkflowSession workflowSession, MetaDataMap args) throws WorkflowException { final Session session = workflowSession.getSession(); final WorkflowData data = workItem.getWorkflowData(); String path = null; String type = data.getPayloadType(); try { if (type.equals(TYPE_JCR_PATH) && data.getPayload() != null) { String payloadData = (String) data.getPayload(); if (session.itemExists(payloadData)) { path = payloadData; } } if (path != null) { final Node userGeneratedNode = (Node) session.getItem(path); if (userGeneratedNode.hasProperty(SLING_RESOURCE_TYPE) && userGeneratedNode .getProperty(SLING_RESOURCE_TYPE) .getString() .equals(COMMENT_RESOURCE_TYPE)) { logger.debug("Spam check for comment node at " + userGeneratedNode.getPath()); String ipAddress = null; if (userGeneratedNode.hasProperty("ip")) { ipAddress = userGeneratedNode.getProperty("ip").getString(); logger.debug("Spam check for comment node with ip " + ipAddress); } else { setIsSpam(userGeneratedNode, false, session); logger.info("Comment has no IP address, setting isSpam to false"); return; } // if the ip is localhost we set isspam to false as well if (ipAddress.equalsIgnoreCase("127.0.0.1") || ipAddress.equalsIgnoreCase("localhost") || ipAddress.equalsIgnoreCase("0:0:0:0:0:0:0:1")) { setIsSpam(userGeneratedNode, false, session); logger.info("Comment IP address is localhost, setting isSpam to false"); return; } String userAgent = null; if (userGeneratedNode.hasProperty("userAgent")) { userAgent = userGeneratedNode.getProperty("userAgent").getString(); logger.debug("Spam check for comment node with userAgent " + userAgent); } else { setIsSpam(userGeneratedNode, false, session); logger.info("Comment has no user agent, setting isSpam to false"); return; } String referrer = null; if (userGeneratedNode.hasProperty("referer")) { referrer = userGeneratedNode.getProperty("referer").getString(); logger.debug("Spam check for comment node with referrer " + referrer); } String permalink = null; try { ResourceResolver resourceResolver = jcrResourceResolverFactory.getResourceResolver(session); Resource resource = resourceResolver.getResource(path); BlogManager blogManager = resource.getResourceResolver().adaptTo(BlogManager.class); Blog entry = blogManager.getBlog(path); permalink = entry.getFullUrl(); logger.debug("Spam check for comment node with permalink " + permalink); } catch (Exception e) { logger.error("Exception " + e.toString() + " getting permalink"); } String author = null; if (userGeneratedNode.hasProperty("userIdentifier")) { author = userGeneratedNode.getProperty("userIdentifier").getString(); logger.debug("Spam check for comment node with permalink " + author); } String authorEmail = null; if (userGeneratedNode.hasProperty("email")) { authorEmail = userGeneratedNode.getProperty("email").getString(); logger.debug("Spam check for comment node with author " + authorEmail); } String authorURL = null; if (userGeneratedNode.hasProperty("url")) { authorURL = userGeneratedNode.getProperty("url").getString(); logger.debug("Spam check for comment node with authorURL " + authorURL); } String commentText = null; if (userGeneratedNode.hasProperty("jcr:description")) { commentText = userGeneratedNode.getProperty("jcr:description").getString(); logger.debug("Spam check for comment node with commentText " + commentText); } boolean isSpam = akismetService.commentCheck( ipAddress, userAgent, referrer, permalink, "comment", author, authorEmail, authorURL, commentText, null); setIsSpam(userGeneratedNode, isSpam, session); logger.info("Spam check result " + isSpam + " for comment: " + workItem.toString()); } else if (userGeneratedNode.hasProperty(SLING_RESOURCE_TYPE) && userGeneratedNode .getProperty(SLING_RESOURCE_TYPE) .getString() .equals(TRACKBACK_RESOURCE_TYPE)) { // for // trackbacks String ipAddress = null; if (userGeneratedNode.hasProperty("ip")) { ipAddress = userGeneratedNode.getProperty("ip").getString(); logger.debug("Spam check for trackback node with ip " + ipAddress); } String authorURL = null; if (userGeneratedNode.hasProperty("url")) { authorURL = userGeneratedNode.getProperty("url").getString(); logger.debug("Spam check for trackback node with authorURL " + authorURL); } String permalink = null; try { ResourceResolver resourceResolver = jcrResourceResolverFactory.getResourceResolver(session); Resource resource = resourceResolver.getResource(path); BlogManager blogManager = resource.getResourceResolver().adaptTo(BlogManager.class); Blog entry = blogManager.getBlog(path); permalink = entry.getFullUrl(); logger.debug("Spam check for trackback node with permalink " + permalink); } catch (Exception e) { logger.error("Exception " + e.toString() + " getting permalink"); } /* * it is not really clear from the akismet api how to map * the trackback's title and blog-name to the api call. will * try with the code below. */ String author = null; if (userGeneratedNode.hasProperty("blogName")) { author = userGeneratedNode.getProperty("blogName").getString(); logger.debug("Spam check for trackback node with blogName " + author); } // prepending the title to the excerpt String excerpt = ""; if (userGeneratedNode.hasProperty("excerpt")) { excerpt = userGeneratedNode.getProperty("excerpt").getString(); logger.debug("Spam check for trackback node with excerpt " + excerpt); } if (userGeneratedNode.hasProperty("jcr:title")) { excerpt = userGeneratedNode.getProperty("jcr:title").getString() + " " + excerpt; logger.debug( "Spam check for trackback node with title " + userGeneratedNode.hasProperty("jcr:title")); } boolean isSpam = akismetService.commentCheck( ipAddress, null, null, permalink, "trackback", author, null, authorURL, excerpt, null); setIsSpam(userGeneratedNode, isSpam, session); logger.info("Spam check result " + isSpam + " for trackback: " + workItem.toString()); } else { logger.warn( "Cannot check for spam because item is not a comment or a trackback. Workitem: " + workItem.toString()); } } else { logger.warn( "Cannot check for spam because path is null for this workitem: " + workItem.toString()); } } catch (RepositoryException e) { throw new WorkflowException(e); } }