@Test public void shouldNotAllowInternalNodesAsReferrers() throws Exception { federationManager.createProjection( "/testRoot", SOURCE_NAME, MockConnector.DOC1_LOCATION, "federated1"); Node doc1Federated = session.getNode("/testRoot/federated1"); Node externalNode = doc1Federated.addNode("federated1_1", null); externalNode.addMixin("mix:referenceable"); session.save(); Value weakRef = session.getValueFactory().createValue(externalNode, true); testRoot.setProperty("weakRef", weakRef); try { session.save(); fail( "It should not be possible to create weak references from internal nodes to external nodes"); } catch (RepositoryException e) { assertTrue(e.getCause() instanceof ConnectorException); } Value strongRef = session.getValueFactory().createValue(externalNode, false); testRoot.setProperty("strongRef", strongRef); try { session.save(); fail( "It should not be possible to create strong references from internal nodes to external nodes"); } catch (RepositoryException e) { assertTrue(e.getCause() instanceof ConnectorException); } }
@Test public void shouldUpdateExternalNodeProperties() throws Exception { federationManager.createProjection( "/testRoot", SOURCE_NAME, MockConnector.DOC1_LOCATION, "federated1"); Node doc1Federated = session.getNode("/testRoot/federated1"); Node externalNode1 = doc1Federated.addNode("federated1_1", null); externalNode1.setProperty("prop1", "a value"); externalNode1.setProperty("prop2", "a value 2"); session.save(); externalNode1.setProperty("prop1", "edited value"); assertEquals("a value 2", externalNode1.getProperty("prop2").getString()); externalNode1.getProperty("prop2").remove(); externalNode1.setProperty("prop3", "a value 3"); session.save(); Node federated1_1 = doc1Federated.getNode("federated1_1"); assertEquals("edited value", federated1_1.getProperty("prop1").getString()); assertEquals("a value 3", federated1_1.getProperty("prop3").getString()); try { federated1_1.getProperty("prop2"); fail("Property was not removed from external node"); } catch (PathNotFoundException e) { // expected } }
public Book addBook(Book book) throws DuplicateBookException { SessionProvider sProvider = SessionProvider.createSystemProvider(); String nodeId = IdGenerator.generate(); book.setId(nodeId); try { Node parentNode = getNodeByPath(DEFAULT_PARENT_PATH, sProvider); Node bookNode = parentNode.addNode(nodeId, BookNodeTypes.EXO_BOOK); bookNode.setProperty(BookNodeTypes.EXP_BOOK_NAME, book.getName()); bookNode.setProperty( BookNodeTypes.EXP_BOOK_CATEGORY, Utils.bookCategoryEnumToString(book.getCategory())); bookNode.setProperty(BookNodeTypes.EXP_BOOK_CONTENT, book.getContent()); parentNode.getSession().save(); return book; } catch (PathNotFoundException e) { return null; } catch (Exception e) { log.error("Failed to add book", e); return null; } finally { sProvider.close(); } }
@Test public void testProperPoolId() throws ItemNotFoundException, RepositoryException, NoSuchAlgorithmException, UnsupportedEncodingException { SlingHttpServletRequest request = mock(SlingHttpServletRequest.class); HtmlResponse response = new HtmlResponse(); ResourceResolver resolver = mock(ResourceResolver.class); String poolId = "foobarbaz"; Resource resource = mock(Resource.class); // The tagnode Node tagNode = new MockNode("/path/to/tag"); tagNode.setProperty(SLING_RESOURCE_TYPE_PROPERTY, FilesConstants.RT_SAKAI_TAG); tagNode.setProperty(FilesConstants.SAKAI_TAG_NAME, "urban"); // The file we want to tag. Node fileNode = mock(Node.class); when(fileNode.getPath()).thenReturn("/path/to/file"); NodeType type = mock(NodeType.class); when(type.getName()).thenReturn("foo"); when(fileNode.getMixinNodeTypes()).thenReturn(new NodeType[] {type}); Property tagsProp = mock(Property.class); MockPropertyDefinition tagsPropDef = new MockPropertyDefinition(false); Value v = new MockValue("uuid-to-other-tag"); when(tagsProp.getDefinition()).thenReturn(tagsPropDef); when(tagsProp.getValue()).thenReturn(v); when(fileNode.getProperty(FilesConstants.SAKAI_TAGS)).thenReturn(tagsProp); when(fileNode.hasProperty(FilesConstants.SAKAI_TAGS)).thenReturn(true); // Stuff to check if this is a correct request when(session.getNode(CreateContentPoolServlet.hash(poolId))).thenReturn(tagNode); RequestParameter poolIdParam = mock(RequestParameter.class); when(resolver.adaptTo(Session.class)).thenReturn(session); when(resource.adaptTo(Node.class)).thenReturn(fileNode); when(poolIdParam.getString()).thenReturn(poolId); when(request.getResource()).thenReturn(resource); when(request.getResourceResolver()).thenReturn(resolver); when(request.getRequestParameter("key")).thenReturn(poolIdParam); when(request.getRemoteUser()).thenReturn("john"); // Actual tagging procedure Session adminSession = mock(Session.class); when(adminSession.getItem(fileNode.getPath())).thenReturn(fileNode); ValueFactory valueFactory = mock(ValueFactory.class); Value newValue = new MockValue("uuid-of-tag"); when(valueFactory.createValue(Mockito.anyString(), Mockito.anyInt())) .thenReturn(newValue) .thenReturn(newValue); when(adminSession.getValueFactory()).thenReturn(valueFactory).thenReturn(valueFactory); when(slingRepo.loginAdministrative(null)).thenReturn(adminSession); when(adminSession.hasPendingChanges()).thenReturn(true); operation.doRun(request, response, null); assertEquals(200, response.getStatusCode()); verify(adminSession).save(); verify(adminSession).logout(); }
private Node createEmptyCache(HtmlLibrary library, String root, Session session) { Node node = null; // this.lock.writeLock().lock(); try { Node swap = JcrUtils.getOrCreateByPath( root, JcrResourceConstants.NT_SLING_FOLDER, JcrResourceConstants.NT_SLING_FOLDER, session, true); node = swap.addNode(getLibraryName(library), JcrConstants.NT_FILE); swap = node.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE); swap.setProperty(JcrConstants.JCR_LASTMODIFIED, 0L); swap.setProperty(JcrConstants.JCR_MIMETYPE, library.getType().contentType); swap.setProperty( JcrConstants.JCR_DATA, session.getValueFactory().createBinary(new ByteArrayInputStream(new byte[0]))); session.save(); // this.lock.writeLock().unlock(); } catch (RepositoryException re) { log.debug(re.getMessage()); } return node; }
/** * Converts file to JCR binary content and stores to new node * * @param userNode note to which children node will be created with binary content * @param * cvIStream CV file input stream * @param fileType type of file stored to node */ public static void convertFileStreamToNode( Node userNode, InputStream cvIStream, AllowedFileType fileType) { if (userNode == null) { throw new IllegalArgumentException("User node is null"); } if (cvIStream == null) { throw new IllegalArgumentException("CV file input stream is null"); } if (fileType == null) { throw new IllegalArgumentException("File type is null"); } try { Node cvNode = userNode.addNode(fileType.getNodeType().toString(), "nt:file"); cvNode.addMixin(MIXIN_HASCONTENT.toString()); Node content = cvNode.addNode("jcr:content", "nt:resource"); content.setProperty( "jcr:data", userNode.getSession().getValueFactory().createBinary(cvIStream)); content.setProperty("jcr:mimeType", fileType.getMimeType()); cvNode.setProperty( PROP_CONTENT.toString(), Utils.extractText(content.getProperty("jcr:data").getBinary().getStream(), fileType)); } catch (RepositoryException e) { logger.error( "Failed to convert " + fileType.toString() + " file to binary node. " + e.getMessage()); } }
protected Node processAttributeDeclaration( XSDAttributeDeclaration decl, Node parentNode, boolean isUse) throws RepositoryException { if (decl == null) { return null; } logger.debug( "Attribute declaration: '{0}' in ns '{1}' ", decl.getName(), decl.getTargetNamespace()); Node attributeDeclarationNode = parentNode.addNode(decl.getName(), XsdLexicon.ATTRIBUTE_DECLARATION); attributeDeclarationNode.setProperty(XsdLexicon.NC_NAME, decl.getName()); attributeDeclarationNode.setProperty(XsdLexicon.NAMESPACE, decl.getTargetNamespace()); if (decl.isGlobal() && !isUse) { registerForSymbolSpace( ATTRIBUTE_DECLARATIONS, decl.getTargetNamespace(), decl.getName(), attributeDeclarationNode.getIdentifier()); } XSDTypeDefinition type = decl.getType(); if (type != null) { attributeDeclarationNode.setProperty(XsdLexicon.TYPE_NAME, type.getName()); attributeDeclarationNode.setProperty(XsdLexicon.TYPE_NAMESPACE, type.getTargetNamespace()); } processAnnotation(decl.getAnnotation(), attributeDeclarationNode); processNonSchemaAttributes(type, attributeDeclarationNode); return attributeDeclarationNode; }
/** {@inheritDoc} */ public void watchDocument(Node documentNode, String userName, int notifyType) throws Exception { Session session = documentNode.getSession(); Value newWatcher = session.getValueFactory().createValue(userName); if (!documentNode.isNodeType(EXO_WATCHABLE_MIXIN)) { documentNode.addMixin(EXO_WATCHABLE_MIXIN); if (notifyType == NOTIFICATION_BY_EMAIL) { documentNode.setProperty(EMAIL_WATCHERS_PROP, new Value[] {newWatcher}); documentNode.save(); session.save(); EmailNotifyListener listener = new EmailNotifyListener(documentNode); observeNode(documentNode, listener); } session.save(); } else { List<Value> watcherList = new ArrayList<Value>(); if (notifyType == NOTIFICATION_BY_EMAIL) { if (documentNode.hasProperty(EMAIL_WATCHERS_PROP)) { for (Value watcher : documentNode.getProperty(EMAIL_WATCHERS_PROP).getValues()) { watcherList.add(watcher); } watcherList.add(newWatcher); } documentNode.setProperty( EMAIL_WATCHERS_PROP, watcherList.toArray(new Value[watcherList.size()])); documentNode.save(); } session.save(); } }
protected Node processWildcard(XSDWildcard wildcard, Node parentNode) throws RepositoryException { if (wildcard == null) { return null; } logger.debug("Any Attribute"); Node anyAttributeNode = parentNode.addNode(XsdLexicon.ANY_ATTRIBUTE, XsdLexicon.ANY_ATTRIBUTE); @SuppressWarnings("unchecked") EList<String> nsConstraints = wildcard.getNamespaceConstraint(); if (nsConstraints != null && !nsConstraints.isEmpty()) { Set<String> values = new HashSet<String>(); for (String nsConstraint : nsConstraints) { if (nsConstraint == null) continue; nsConstraint = nsConstraint.trim(); if (nsConstraint.length() == 0) continue; values.add(nsConstraint); } if (!values.isEmpty()) { anyAttributeNode.setProperty( XsdLexicon.NAMESPACE, values.toArray(new String[values.size()])); } } if (wildcard.getProcessContents() != null) { XSDProcessContents processContents = wildcard.getProcessContents(); anyAttributeNode.setProperty(XsdLexicon.PROCESS_CONTENTS, processContents.getLiteral()); } processAnnotation(wildcard.getAnnotation(), anyAttributeNode); processNonSchemaAttributes(wildcard, anyAttributeNode); return anyAttributeNode; }
protected void processParticle(XSDParticle content, Node node) throws RepositoryException { if (content == null) { return; } XSDParticleContent particle = content.getContent(); Node particleNode = null; if (particle instanceof XSDModelGroupDefinition) { particleNode = processModelGroupDefinition((XSDModelGroupDefinition) particle, node); } else if (particle instanceof XSDElementDeclaration) { particleNode = processElementDeclaration((XSDElementDeclaration) particle, node); } else if (particle instanceof XSDModelGroup) { particleNode = processModelGroup((XSDModelGroup) particle, node); } else if (particle instanceof XSDWildcard) { particleNode = processWildcard((XSDWildcard) particle, node); } if (particleNode != null) { long minOccurs = content.getMinOccurs(); long maxOccurs = content.getMaxOccurs(); particleNode.setProperty(XsdLexicon.MIN_OCCURS, minOccurs); if (maxOccurs >= 0) { particleNode.setProperty(XsdLexicon.MAX_OCCURS, maxOccurs); } else { // unbounded ... } } }
@Test @FixFor("MODE-1401") public void shouldNotAllowAddingUnderCheckedInNodeNewChildNodeWithOpvOfSomethingOtherThanIgnore() throws Exception { registerNodeTypes(session, "cnd/versioning.cnd"); // Set up parent node and check it in ... Node parent = session.getRootNode().addNode("versionableNode", "ver:versionable"); parent.setProperty("versionProp", "v"); parent.setProperty("copyProp", "c"); parent.setProperty("ignoreProp", "i"); session.save(); versionManager.checkin(parent.getPath()); // Try to add versionable child with OPV of not ignore ... try { parent.addNode("versionedChild", "ver:versionableChild"); fail("should have failed"); } catch (VersionException e) { // expected } // Try to add non-versionable child with OPV of not ignore ... try { parent.addNode("nonVersionedChild", "ver:nonVersionableChild"); fail("should have failed"); } catch (VersionException e) { // expected } }
/** * add new book to workspace * * @param book The new book which want to add * @return Book * @throws DuplicateBookException */ public Node addBook(Book book, String nodePath) throws DuplicateBookException { SessionProvider sProvider = SessionProvider.createSystemProvider(); /* Check exist of book */ if (isExistBookName(book.getName(), sProvider)) { throw new DuplicateBookException(String.format("Book %s is existed", book.getName())); } /* get id and set to new book */ book.setBookId(Utils.bookId++); try { /* execute set data to node and save to workspace */ Node parentNode = getNodeByPath(DEFAULT_PARENT_PATH + DEFAULT_PARENT_BOOK_PATH, sProvider); Node bookNode = parentNode.addNode("" + book.getBookId(), BookNodeTypes.EXO_BOOK); bookNode.setProperty(BookNodeTypes.EXO_BOOK_NAME, book.getName()); bookNode.setProperty( BookNodeTypes.EXO_BOOK_CATEGORY, Utils.bookCategoryEnumToString(book.getCategory())); bookNode.setProperty(BookNodeTypes.EXO_BOOK_CONTENT, book.getContent()); bookNode.setProperty(BookNodeTypes.EXO_BOOK_AUTHOR, getNodeByPath(nodePath, sProvider)); parentNode.getSession().save(); return bookNode; } catch (RepositoryException e) { log.error("Failed to add book", e); return null; } finally { sProvider.close(); } }
/** * add new user * * @param user * @param nodes * @return * @throws DuplicateBookException */ public Node addUser(User user, List<String> nodes) throws DuplicateBookException { SessionProvider sProvider = SessionProvider.createSystemProvider(); if (isExistUserName(user.getUsername(), sProvider)) { throw new DuplicateBookException(String.format("User %s is existed", user.getUsername())); } user.setUserId(Utils.userId++); try { Node parentNode = getNodeByPath(DEFAULT_PARENT_PATH + DEFAULT_PARENT_USER_PATH, sProvider); Node userNode = parentNode.addNode("" + user.getUserId(), BookNodeTypes.EXO_USER); userNode.setProperty(BookNodeTypes.EXO_USER_NAME, user.getUsername()); userNode.setProperty(BookNodeTypes.EXO_USER_PASSWORD, user.getPassword()); userNode.setProperty(BookNodeTypes.EXO_USER_FULLNAME, user.getFullname()); userNode.setProperty(BookNodeTypes.EXO_USER_ADDRESS, user.getAddress()); userNode.setProperty(BookNodeTypes.EXO_USER_PHONE, user.getPhone()); List<Value> values = new ArrayList<Value>(); for (String string : nodes) { Value val = parentNode.getSession().getValueFactory().createValue(getNodeByPath(string, sProvider)); values.add(val); } userNode.setProperty(BookNodeTypes.EXO_BOOK, values.toArray(new Value[values.size()])); parentNode.getSession().save(); return userNode; } catch (RepositoryException re) { log.error("Failed to add user", re); return null; } finally { sProvider.close(); } }
@Override public long setContent( Node parentNode, String resourceName, InputStream newContent, String contentType, String characterEncoding) throws RepositoryException, IOException { Node contentNode; if (parentNode.hasNode(CONTENT_NODE_NAME)) { contentNode = parentNode.getNode(CONTENT_NODE_NAME); } else { contentNode = parentNode.addNode(CONTENT_NODE_NAME, newContentPrimaryType); } // contentNode.setProperty(MIME_TYPE_PROP_NAME, contentType != null ? contentType : // "application/octet-stream"); contentNode.setProperty( ENCODING_PROP_NAME, characterEncoding != null ? characterEncoding : "UTF-8"); Binary binary = parentNode.getSession().getValueFactory().createBinary(newContent); contentNode.setProperty(DATA_PROP_NAME, binary); contentNode.setProperty(MODIFIED_PROP_NAME, Calendar.getInstance()); // Copy the content to the property, THEN re-read the content from the Binary value to avoid // discaring the first // bytes of the stream if (contentType == null) { contentType = mimeTypeDetector.mimeTypeOf(resourceName, binary.getStream()); } return contentNode.getProperty(DATA_PROP_NAME).getLength(); }
private void updateEncodingPresets(Resource configResource, S7Config s7Config, String typeHandle) throws RepositoryException { // Get the presets from S7 and store them on the node // List<Scene7PropertySet> propertySets = scene7Service.getPropertySets(typeHandle, s7Config); String path = configResource.getPath() + "/" + Scene7PresetsService.REL_PATH_ENCODING_PRESETS; Node node = prepNode(configResource.getResourceResolver(), path); Node presetNode; int i = 0; for (Scene7PropertySet propertySet : propertySets) { String handle = propertySet.getSetHandle(); String nodeName = getNodeName(handle); if (StringUtils.isNotBlank(nodeName)) { presetNode = node.addNode(nodeName); presetNode.setProperty("handle", handle); Map<String, String> properties = propertySet.getProperties(); for (String key : properties.keySet()) { String value = properties.get(key); key = StringUtils.uncapitalize(key); presetNode.setProperty(key, value); } } } }
public void testExportSystemView1() throws Exception { Node nd = m_session.getRootNode().addNode("foo"); nd.setProperty("stringprop", "Barba<papa>"); nd.setProperty("binaryprop", new ByteArrayInputStream("Barbabinary".getBytes())); nd.setProperty( "multiprop", new Value[] { m_session.getValueFactory().createValue("pimpim&"), m_session.getValueFactory().createValue("poppop\"") }); m_session.save(); ByteArrayOutputStream out = new ByteArrayOutputStream(); m_session.exportSystemView("/", out, false, false); String s = out.toString("UTF-8"); System.out.println(s); assertTrue("Barbapapa wrong", s.indexOf("Barba<papa>") != -1); assertTrue("pim wrong", s.indexOf("pimpim&") != -1); assertTrue("pop wrong", s.indexOf("poppop"") != -1); }
protected void setProperty(Node node, Property property, boolean isMultiValued) throws RepositoryException { Name name = property.getName(); if (name.equals(JcrLexicon.PRIMARY_TYPE)) return; if (name.equals(ModeShapeIntLexicon.NODE_DEFINITON)) return; if (name.equals(ModeShapeIntLexicon.MULTI_VALUED_PROPERTIES)) return; if (name.equals(JcrLexicon.MIXIN_TYPES)) { for (Object mixinVvalue : property.getValuesAsArray()) { String mixinTypeName = stringFor(mixinVvalue); node.addMixin(mixinTypeName); } return; } // Otherwise, just set the normal property. First determine the expected type ... String propertyName = stringFor(name); if (isMultiValued) { Value[] values = new Value[property.size()]; int index = 0; PropertyType propertyType = null; for (Object value : property) { if (value == null) continue; if (propertyType == null) propertyType = PropertyType.discoverType(value); values[index] = convertToJcrValue(propertyType, value); ++index; } node.setProperty(propertyName, values); } else { Object firstValue = property.getFirstValue(); PropertyType propertyType = PropertyType.discoverType(firstValue); Value value = convertToJcrValue(propertyType, firstValue); node.setProperty(propertyName, value); } }
/** * @param path * @param strings * @param strings2 * @param strings3 * @throws JCRNodeFactoryServiceException * @throws RepositoryException * @throws IOException * @throws UnsupportedEncodingException */ private Map<String, Object> saveProperties(String path, MapParams params) throws RepositoryException, JCRNodeFactoryServiceException, UnsupportedEncodingException, IOException { InputStream in = null; try { Node n = jcrNodeFactoryService.getNode(path); Map<String, Object> map = null; if (n != null) { in = jcrNodeFactoryService.getInputStream(path); String content = IOUtils.readFully(in, "UTF-8"); try { in.close(); } catch (IOException ex) { } map = beanConverter.convertToObject(content, Map.class); } else { map = new HashMap<String, Object>(); } for (int i = 0; i < params.names.length; i++) { if (REMOVE_ACTION.equals(params.actions[i])) { map.remove(params.names[i]); } else { map.put(params.names[i], params.values[i]); } } String result = beanConverter.convertToString(map); in = new ByteArrayInputStream(result.getBytes("UTF-8")); n = jcrNodeFactoryService.setInputStream(path, in, RestProvider.CONTENT_TYPE); // deal with indexed properties. for (int i = 0; i < params.names.length; i++) { boolean index = false; if (params.indexes != null && "1".equals(params.indexes[i])) { index = true; } if (n.hasProperty("sakai:" + params.names[i])) { // if remove, remove it, else update if (REMOVE_ACTION.equals(params.actions[i])) { n.getProperty("sakai:" + params.names[i]).remove(); } else { n.setProperty("sakai:" + params.names[i], params.values[i]); } } else if (index) { // add it n.setProperty("sakai:" + params.names[i], params.values[i]); } } n.getSession().save(); // verify changes Map<String, Object> outputMap = new HashMap<String, Object>(); outputMap.put("response", "OK"); return outputMap; } finally { try { in.close(); } catch (Exception ex) { } } }
@Override public void updateFile( long companyId, long repositoryId, String fileName, String versionLabel, InputStream is) throws PortalException, SystemException { Session session = null; try { session = JCRFactoryUtil.createSession(); Workspace workspace = session.getWorkspace(); VersionManager versionManager = workspace.getVersionManager(); Node rootNode = getRootNode(session, companyId); Node repositoryNode = getFolderNode(rootNode, repositoryId); if (fileName.contains(StringPool.SLASH)) { String path = fileName.substring(0, fileName.lastIndexOf(StringPool.SLASH)); fileName = fileName.substring(path.length() + 1); repositoryNode = getFolderNode(repositoryNode, path); } Node fileNode = repositoryNode.getNode(fileName); Node contentNode = fileNode.getNode(JCRConstants.JCR_CONTENT); versionManager.checkout(contentNode.getPath()); contentNode.setProperty(JCRConstants.JCR_MIME_TYPE, "text/plain"); ValueFactory valueFactory = session.getValueFactory(); Binary binary = valueFactory.createBinary(is); contentNode.setProperty(JCRConstants.JCR_DATA, binary); contentNode.setProperty(JCRConstants.JCR_LAST_MODIFIED, Calendar.getInstance()); session.save(); Version version = versionManager.checkin(contentNode.getPath()); VersionHistory versionHistory = versionManager.getVersionHistory(contentNode.getPath()); versionHistory.addVersionLabel( version.getName(), versionLabel, PropsValues.DL_STORE_JCR_MOVE_VERSION_LABELS); } catch (PathNotFoundException pnfe) { throw new NoSuchFileException( "{fileName=" + fileName + ", versionLabel=" + versionLabel + "}"); } catch (RepositoryException re) { throw new SystemException(re); } finally { JCRFactoryUtil.closeSession(session); } }
/** * Create a link to a file. There is no need to call a session.save, the change is persistent. * * @param fileNode The node that represents the file. This node has to be retrieved via the normal * user his {@link Session session}. If the userID equals {@link UserConstants.ANON_USERID} an * AccessDeniedException will be thrown. * @param linkPath The absolute path in JCR where the link should be placed. * @param slingRepository The {@link SlingRepository} to use to login as an administrative. * @return The newly created node. * @throws AccessDeniedException When the user is anonymous. * @throws RepositoryException Something else went wrong. */ public static boolean createLink(Node fileNode, String linkPath, SlingRepository slingRepository) throws AccessDeniedException, RepositoryException { Session session = fileNode.getSession(); String userId = session.getUserID(); if (UserConstants.ANON_USERID.equals(userId)) { throw new AccessDeniedException(); } boolean hasMixin = JcrUtils.hasMixin(fileNode, REQUIRED_MIXIN) && fileNode.canAddMixin(REQUIRED_MIXIN); // If the fileNode doesn't have the required referenceable mixin, we need to set it. if (!hasMixin) { // The required mixin is not on the node. // Set it. Session adminSession = null; try { adminSession = slingRepository.loginAdministrative(null); // Grab the node via the adminSession String path = fileNode.getPath(); Node adminFileNode = (Node) adminSession.getItem(path); if (!hasMixin) { adminFileNode.addMixin(REQUIRED_MIXIN); } if (adminSession.hasPendingChanges()) { adminSession.save(); } } finally { if (adminSession != null) { adminSession.logout(); } } } // Now that the file is referenceable, it has a uuid. // Use it for the link. // Grab the (updated) node via the user's session id. fileNode = (Node) session.getItem(fileNode.getPath()); // Create the link Node linkNode = JcrUtils.deepGetOrCreateNode(session, linkPath); if (!"sling:Folder".equals(linkNode.getPrimaryNodeType().getName())) { // sling folder allows single and multiple properties, no need for the mixin. if (linkNode.canAddMixin(REQUIRED_MIXIN)) { linkNode.addMixin(REQUIRED_MIXIN); } } linkNode.setProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, RT_SAKAI_LINK); linkNode.setProperty(SAKAI_LINK, fileNode.getIdentifier()); // Save link. if (session.hasPendingChanges()) { session.save(); } return true; }
@Override public void addFile(long companyId, long repositoryId, String fileName, InputStream is) throws PortalException, SystemException { Session session = null; try { session = JCRFactoryUtil.createSession(); Workspace workspace = session.getWorkspace(); VersionManager versionManager = workspace.getVersionManager(); Node rootNode = getRootNode(session, companyId); Node repositoryNode = getFolderNode(rootNode, repositoryId); if (fileName.contains(StringPool.SLASH)) { String path = fileName.substring(0, fileName.lastIndexOf(StringPool.SLASH)); fileName = fileName.substring(path.length() + 1); repositoryNode = getFolderNode(repositoryNode, path); } if (repositoryNode.hasNode(fileName)) { throw new DuplicateFileException(fileName); } else { Node fileNode = repositoryNode.addNode(fileName, JCRConstants.NT_FILE); Node contentNode = fileNode.addNode(JCRConstants.JCR_CONTENT, JCRConstants.NT_RESOURCE); contentNode.addMixin(JCRConstants.MIX_VERSIONABLE); contentNode.setProperty(JCRConstants.JCR_MIME_TYPE, "text/plain"); ValueFactory valueFactory = session.getValueFactory(); Binary binary = valueFactory.createBinary(is); contentNode.setProperty(JCRConstants.JCR_DATA, binary); contentNode.setProperty(JCRConstants.JCR_LAST_MODIFIED, Calendar.getInstance()); session.save(); Version version = versionManager.checkin(contentNode.getPath()); VersionHistory versionHistory = versionManager.getVersionHistory(contentNode.getPath()); versionHistory.addVersionLabel(version.getName(), VERSION_DEFAULT, false); } } catch (RepositoryException re) { throw new SystemException(re); } finally { JCRFactoryUtil.closeSession(session); } }
private void writePartAsFile(Session session, BodyPart part, String nodeName, Node parentNode) throws RepositoryException, MessagingException, IOException { Node fileNode = parentNode.addNode(nodeName, "nt:file"); Node resourceNode = fileNode.addNode("jcr:content", "nt:resource"); resourceNode.setProperty("jcr:mimeType", part.getContentType()); resourceNode.setProperty( "jcr:data", session.getValueFactory().createValue(part.getInputStream())); resourceNode.setProperty("jcr:lastModified", Calendar.getInstance()); }
protected void processImport(XSDImport xsdImport, Node parentNode) throws RepositoryException { logger.debug( "Import: '{0}' with location '{1}' ", xsdImport.getNamespace(), xsdImport.getSchemaLocation()); Node importNode = parentNode.addNode(IMPORT, IMPORT); importNode.setProperty(XsdLexicon.NAMESPACE, xsdImport.getNamespace()); importNode.setProperty(XsdLexicon.SCHEMA_LOCATION, xsdImport.getSchemaLocation()); processNonSchemaAttributes(xsdImport, importNode); }
@Override public void createFile(Node parentNode, String fileName) throws RepositoryException { Node resourceNode = parentNode.addNode(fileName, newResourcePrimaryType); Node contentNode = resourceNode.addNode(CONTENT_NODE_NAME, newContentPrimaryType); contentNode.setProperty(DATA_PROP_NAME, ""); contentNode.setProperty(MODIFIED_PROP_NAME, Calendar.getInstance()); contentNode.setProperty(ENCODING_PROP_NAME, "UTF-8"); contentNode.setProperty(MIME_TYPE_PROP_NAME, "text/plain"); }
@FixFor("MODE-1624") @Test public void shouldAllowRemovingVersionFromVersionHistoryByRemovingVersionNode() throws Exception { print = false; Node outerNode = session.getRootNode().addNode("outerFolder"); Node innerNode = outerNode.addNode("innerFolder"); Node fileNode = innerNode.addNode("testFile.dat"); fileNode.setProperty("jcr:mimeType", "text/plain"); fileNode.setProperty("jcr:data", "Original content"); session.save(); fileNode.addMixin("mix:versionable"); session.save(); // Make several changes ... String path = fileNode.getPath(); for (int i = 2; i != 7; ++i) { versionManager.checkout(path); fileNode.setProperty("jcr:data", "Original content " + i); session.save(); versionManager.checkin(path); } // Get the version history ... VersionHistory history = versionManager.getVersionHistory(path); if (print) System.out.println("Before: \n" + history); assertThat(history, is(notNullValue())); assertThat(history.getAllLinearVersions().getSize(), is(6L)); // Get the versions ... VersionIterator iter = history.getAllLinearVersions(); Version v1 = iter.nextVersion(); Version v2 = iter.nextVersion(); Version v3 = iter.nextVersion(); Version v4 = iter.nextVersion(); Version v5 = iter.nextVersion(); Version v6 = iter.nextVersion(); assertThat(iter.hasNext(), is(false)); assertThat(v1, is(notNullValue())); assertThat(v2, is(notNullValue())); assertThat(v3, is(notNullValue())); assertThat(v4, is(notNullValue())); assertThat(v5, is(notNullValue())); assertThat(v6, is(notNullValue())); // Remove the 3rd version (that is, i=3) ... // history.removeVersion(versionName); try { v3.remove(); fail("Should not allow removing a protected node"); } catch (ConstraintViolationException e) { // expected } }
private Node addDocument(Node folder, String name) throws RepositoryException { Node handle = folder.addNode(name, HippoNodeType.NT_HANDLE); handle.addMixin(HippoNodeType.NT_HARDHANDLE); Node document = handle.addNode(name, "hippo:testdocument"); document.addMixin(JcrConstants.MIX_VERSIONABLE); document.addMixin("hippostd:publishable"); document.setProperty("hippostd:state", "published"); Node html = document.addNode("html", "hippostd:html"); html.setProperty("hippostd:content", "<html><body>Lorem</body></html>"); return handle; }
@Test public void testIsTag() throws RepositoryException { Node node = new MockNode("/path/to/tag"); node.setProperty(SLING_RESOURCE_TYPE_PROPERTY, FilesConstants.RT_SAKAI_TAG); boolean result = FileUtils.isTag(node); assertEquals(true, result); node.setProperty(SLING_RESOURCE_TYPE_PROPERTY, "foobar"); result = FileUtils.isTag(node); assertEquals(false, result); }
// start setting of list in right rail public void rightRailList( Node listNode, Element rightListEle, Map<String, String> urlMap, String locale) { try { Element title; Element description; Elements headElements = rightListEle.getElementsByTag("h2"); if (headElements.size() > 1) { title = rightListEle.getElementsByTag("h2").last(); description = rightListEle.getElementsByTag("p").last(); sb.append("<li>Mismatch in count of list panel component in right rail.</li>"); } else { title = rightListEle.getElementsByTag("h2").first(); description = rightListEle.getElementsByTag("p").first(); } listNode.setProperty("title", title.text()); javax.jcr.Node introNode = listNode.getNode("intro"); introNode.setProperty("paragraph_rte", description.text()); javax.jcr.Node eleListNode = listNode.getNode("element_list_0"); Elements ulList = rightListEle.getElementsByTag("ul"); for (Element element : ulList) { java.util.List<String> list = new ArrayList<String>(); Elements menuLiList = element.getElementsByTag("li"); for (Element li : menuLiList) { JSONObject jsonObjrr = new JSONObject(); Element listItemAnchor = li.getElementsByTag("a").first(); String anchorText = listItemAnchor != null ? listItemAnchor.text() : ""; String anchorHref = listItemAnchor.absUrl("href"); if (StringUtil.isBlank(anchorHref)) { anchorHref = listItemAnchor.attr("href"); } // Start extracting valid href log.debug("Before right list LinkUrl" + anchorHref + "\n"); anchorHref = FrameworkUtils.getLocaleReference(anchorHref, urlMap, locale, sb); log.debug("after right list LinkUrl" + anchorHref + "\n"); // End extracting valid href jsonObjrr.put("linktext", anchorText); jsonObjrr.put("linkurl", anchorHref); jsonObjrr.put("icon", "none"); jsonObjrr.put("size", ""); jsonObjrr.put("description", ""); jsonObjrr.put("openInNewWindow", "false"); list.add(jsonObjrr.toString()); } eleListNode.setProperty("listitems", list.toArray(new String[list.size()])); } log.debug("Updated title, descriptoin and linktext at " + listNode.getPath()); } catch (Exception e) { e.printStackTrace(); } }
protected void setUp() throws Exception { super.setUp(); String value = "a"; n1 = testRootNode.addNode(nodeName1, testNodeType); n1.setProperty(propertyName1, value); n1.setProperty(propertyName2, "b"); n2 = n1.addNode(nodeName2, testNodeType); n2.setProperty(propertyName1, value); n2.setProperty(propertyName2, value); superuser.save(); }
protected void setUp() throws Exception { super.setUp(); String value = createRandomString(10); n1 = testRootNode.addNode(nodeName1, testNodeType); n1.setProperty(propertyName1, value); n2 = n1.addNode(nodeName2, testNodeType); n2.setProperty(propertyName1, value); n2.setProperty(propertyName2, value); ensureMixinType(n2, mixReferenceable); superuser.save(); }