public void testSave() throws Exception { UserStateModel userModel = new UserStateModel( session.getUserID(), new Date().getTime(), UserStateService.DEFAULT_STATUS); userStateService.save(userModel); SessionProvider sessionProvider = SessionProvider.createSystemProvider(); try { Node userNodeApp = nodeHierarchyCreator.getUserApplicationNode(sessionProvider, session.getUserID()); assertTrue(userNodeApp.hasNode(VIDEOCALLS_BASE_PATH)); Node videoCallNode = userNodeApp.getNode(VIDEOCALLS_BASE_PATH); assertTrue(videoCallNode.isNodeType(USER_STATATUS_NODETYPE)); assertTrue(videoCallNode.hasProperty(USER_ID_PROP)); assertEquals(userModel.getUserId(), videoCallNode.getProperty(USER_ID_PROP).getString()); assertTrue(videoCallNode.hasProperty(LAST_ACTIVITY_PROP)); assertEquals( userModel.getLastActivity(), videoCallNode.getProperty(LAST_ACTIVITY_PROP).getLong()); assertTrue(videoCallNode.hasProperty(STATUS_PROP)); assertEquals(userModel.getStatus(), videoCallNode.getProperty(STATUS_PROP).getString()); } finally { sessionProvider.close(); } }
public void testRemoveMixLockableFromLockedNode() throws RepositoryException, NotExecutableException { try { lockedNode.removeMixin(mixLockable); lockedNode.save(); // the mixin got removed -> the lock should implicitely be released // as well in order not to have inconsistencies String msg = "Lock should have been released."; assertFalse(msg, lock.isLive()); assertFalse(msg, lockedNode.isLocked()); assertFalse(msg, lockMgr.isLocked(lockedNode.getPath())); assertFalse(msg, lockedNode.hasProperty(jcrLockOwner)); assertFalse(msg, lockedNode.hasProperty(jcrlockIsDeep)); } catch (ConstraintViolationException e) { // cannot remove the mixin -> ok // consequently the node must still be locked, the lock still live... String msg = "Lock must still be live."; assertTrue(msg, lock.isLive()); assertTrue(msg, lockedNode.isLocked()); assertTrue(msg, lockMgr.isLocked(lockedNode.getPath())); assertTrue(msg, lockedNode.hasProperty(jcrLockOwner)); assertTrue(msg, lockedNode.hasProperty(jcrlockIsDeep)); } finally { // ev. re-add the mixin in order to be able to unlock the node if (lockedNode.isLocked()) { ensureMixinType(lockedNode, mixLockable); lockedNode.save(); } } }
/** Test expiration of the lock */ public synchronized void testLockExpiration() throws RepositoryException, NotExecutableException { lockedNode.unlock(); long hint = 1; lock = lockMgr.lock(lockedNode.getPath(), isDeep(), isSessionScoped(), hint, null); // only test if timeout hint was respected. long remaining = lock.getSecondsRemaining(); if (remaining <= hint) { try { wait(remaining * 2000); // wait twice as long to be safe } catch (InterruptedException ignore) { } assertTrue( "A released lock must return a negative number of seconds", lock.getSecondsRemaining() < 0); String message = "If the timeout hint is respected the lock" + " must be automatically released."; assertFalse(message, lock.isLive()); assertFalse(message, lockedNode.isLocked()); assertFalse(message, lockMgr.isLocked(lockedNode.getPath())); assertFalse(message, lockedNode.hasProperty(Property.JCR_LOCK_IS_DEEP)); assertFalse(message, lockedNode.hasProperty(Property.JCR_LOCK_OWNER)); } else { throw new NotExecutableException("timeout hint was ignored."); } }
/** * Get content of document node. Content is got by exo:content or exo:text or exo:summary * * @param node * @return * @throws Exception */ private DocumentContent getArticleContent(Node node, List<Node> taxonomyTrees) throws Exception { DocumentContent documentContent = new DocumentContent(node.getName(), getIcon(node), "", getType(node)); // If node is added mix rss-enabled then get exo:content property if (node.hasProperty("exo:content")) { documentContent.setContent(node.getProperty("exo:content").getString()); } // Some node have exo:text so we override value of exo:content if (node.hasProperty("exo:text")) { documentContent.setContent(node.getProperty("exo:text").getString()); } // Some node have exo:summary so we override value of exo:content if (node.hasProperty("exo:summary")) { documentContent.setContent(node.getProperty("exo:summary").getString()); } List<Node> categories = taxonomyService_.getAllCategories(node); CategoryNode categoryNode; for (Node category : categories) { categoryNode = getCategoryNode(category, ""); for (Node taxonomyTree : taxonomyTrees) { if (category.getPath().contains(taxonomyTree.getPath())) { categoryNode.setParentPath( (category.getParent().getPath().replace(taxonomyTree.getParent().getPath(), ""))); break; } } if (categoryNode != null) documentContent.getCategories().add(categoryNode); } return documentContent; }
public void route(Node n, MessageRoutes routing) { List<MessageRoute> toRemove = new ArrayList<MessageRoute>(); List<MessageRoute> toAdd = new ArrayList<MessageRoute>(); // Check if this message is a discussion message. try { if (n.hasProperty(MessageConstants.PROP_SAKAI_TYPE) && n.hasProperty(DiscussionConstants.PROP_MARKER) && DiscussionTypes.hasValue( n.getProperty(MessageConstants.PROP_SAKAI_TYPE).getString())) { // This is a discussion message, find the settings file for it. String marker = n.getProperty(DiscussionConstants.PROP_MARKER).getString(); String type = n.getProperty(MessageConstants.PROP_SAKAI_TYPE).getString(); // TODO: I have a feeling that this is really part of something more generic // and not specific to discussion. If we make it specific to discussion we // will loose unified messaging and control of that messaging. Node settings = discussionManager.findSettings(marker, n.getSession(), type); if (settings != null && settings.hasProperty(DiscussionConstants.PROP_NOTIFICATION)) { boolean sendMail = settings.getProperty(DiscussionConstants.PROP_NOTIFICATION).getBoolean(); if (sendMail && settings.hasProperty(DiscussionConstants.PROP_NOTIFY_ADDRESS)) { String address = settings.getProperty(DiscussionConstants.PROP_NOTIFY_ADDRESS).getString(); toAdd.add(new DiscussionRoute("internal:" + address)); } } } } catch (ValueFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (PathNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (MessageRoute route : routing) { if (DiscussionTypes.hasValue(route.getTransport())) { toAdd.add(new DiscussionRoute("internal:" + route.getRcpt())); toRemove.add(route); } } // Add the new routes for (MessageRoute route : toAdd) { routing.add(route); } // Remove the discussion route (if there is any). for (MessageRoute route : toRemove) { routing.remove(route); } }
public static Map<String, String> populateActivityData( Node node, String activityOwnerId, String activityMsgBundleKey, boolean isSystemComment, String systemComment) throws Exception { /** The date formatter. */ DateFormat dateFormatter = null; dateFormatter = new SimpleDateFormat(ISO8601.SIMPLE_DATETIME_FORMAT); // get activity data String repository = ((ManageableRepository) node.getSession().getRepository()).getConfiguration().getName(); String workspace = node.getSession().getWorkspace().getName(); String illustrationImg = Utils.getIllustrativeImage(node); String strDateCreated = ""; if (node.hasProperty(NodetypeConstant.EXO_DATE_CREATED)) { Calendar dateCreated = node.getProperty(NodetypeConstant.EXO_DATE_CREATED).getDate(); strDateCreated = dateFormatter.format(dateCreated.getTime()); } String strLastModified = ""; if (node.hasNode(NodetypeConstant.JCR_CONTENT)) { Node contentNode = node.getNode(NodetypeConstant.JCR_CONTENT); if (contentNode.hasProperty(NodetypeConstant.JCR_LAST_MODIFIED)) { Calendar lastModified = contentNode.getProperty(NodetypeConstant.JCR_LAST_MODIFIED).getDate(); strLastModified = dateFormatter.format(lastModified.getTime()); } } activityOwnerId = activityOwnerId != null ? activityOwnerId : ""; // populate data to map object Map<String, String> activityParams = new HashMap<String, String>(); activityParams.put(ContentUIActivity.CONTENT_NAME, node.getName()); activityParams.put(ContentUIActivity.AUTHOR, activityOwnerId); activityParams.put(ContentUIActivity.DATE_CREATED, strDateCreated); activityParams.put(ContentUIActivity.LAST_MODIFIED, strLastModified); activityParams.put(ContentUIActivity.CONTENT_LINK, getContentLink(node)); activityParams.put( ContentUIActivity.ID, node.isNodeType(NodetypeConstant.MIX_REFERENCEABLE) ? node.getUUID() : ""); activityParams.put(ContentUIActivity.REPOSITORY, repository); activityParams.put(ContentUIActivity.WORKSPACE, workspace); activityParams.put(ContentUIActivity.MESSAGE, activityMsgBundleKey); activityParams.put(ContentUIActivity.MIME_TYPE, getMimeType(node)); activityParams.put(ContentUIActivity.IMAGE_PATH, illustrationImg); activityParams.put(ContentUIActivity.IMAGE_PATH, illustrationImg); if (isSystemComment) { activityParams.put(ContentUIActivity.IS_SYSTEM_COMMENT, String.valueOf(isSystemComment)); activityParams.put(ContentUIActivity.SYSTEM_COMMENT, systemComment); } return activityParams; }
/** * initializes fields * * @throws Exception */ public void initParams() throws Exception { // get current node // name field if (currentNode.hasProperty("exo:title")) { nameValue_ = currentNode.getProperty("exo:title").getValue().getString(); } if (currentNode.hasNode("jcr:content")) { Node content = currentNode.getNode("jcr:content"); if (content.hasProperty("dc:title")) { try { nameValue_ = content.getProperty("dc:title").getValues()[0].getString(); } catch (Exception e) { nameValue_ = null; } } } if (nameValue_ == null) nameValue_ = currentNode.getName(); boolean hasNavigableMixinType = currentNode.isNodeType("exo:navigable"); if (hasNavigableMixinType) { isVisible = true; if (currentNode.getParent().isNodeType("exo:navigable")) { if (currentNode.hasProperty("exo:index")) { index_ = currentNode.getProperty("exo:index").getLong(); } renderIndexField = true; } if (currentNode.hasProperty("exo:navigationNode")) { navigationNode_ = currentNode.getProperty("exo:navigationNode").getString(); } if (currentNode.hasProperty("exo:clickable")) { if (currentNode.getProperty("exo:clickable").getBoolean()) { isClickable = true; } else isClickable = false; } if (currentNode.hasProperty("exo:page")) { listTargetPage_ = currentNode.getProperty("exo:page").getString(); } if (currentNode.hasProperty("exo:pageParamId")) { listShowClvBy_ = currentNode.getProperty("exo:pageParamId").getString(); } if (currentNode.hasProperty("exo:childrenPage")) { detailTargetPage_ = currentNode.getProperty("exo:childrenPage").getString(); } if (currentNode.hasProperty("exo:childrenPageParamId")) { detailShowClvBy_ = currentNode.getProperty("exo:childrenPageParamId").getString(); } } }
public VNodeDefinition(Node node) throws RepositoryException { name = node.getProperty(JCR_NODETYPENAME).getString(); // do properties properties = new HashMap<String, VPropertyDefinitionI>(); childSuggestions = new HashMap<String, String>(); NodeIterator nodeIterator = node.getNodes(); while (nodeIterator.hasNext()) { Node definitionNode = nodeIterator.nextNode(); String nodeType = definitionNode.getProperty(AbstractProperty.JCR_PRIMARYTYPE).getString(); // do a property if (NT_PROPERTYDEFINITION.equals(nodeType)) { String propertyName = "*"; // default to wildcard name if (definitionNode.hasProperty(JCR_NAME)) { // only add non-autogenerated properties if (!definitionNode.getProperty(JCR_AUTOCREATED).getBoolean()) { propertyName = definitionNode.getProperty(JCR_NAME).getString(); properties.put(propertyName, new VPropertyDefinition(definitionNode)); } } else { // property with no name means this node can accept custom properties canAddProperties = true; } } // do a child suggestion if (NT_CHILDNODEDEFINITION.equals(nodeType)) { String childName = "*"; // only do well-defined childnodedefinitions with the following 2 jcr properties if (definitionNode.hasProperty(JCR_NAME) && definitionNode.hasProperty(JCR_DEFAULTPRIMARYTYPE)) { childSuggestions.put( definitionNode.getProperty(JCR_NAME).getString(), definitionNode.getProperty(JCR_DEFAULTPRIMARYTYPE).getString()); } } } // do supertypes supertypes = new HashSet<String>(); if (node.hasProperty(JCR_SUPERTYPES)) { for (Value value : node.getProperty(JCR_SUPERTYPES).getValues()) { supertypes.add(value.getString()); } } // set mixin status isMixin = node.hasProperty(JCR_ISMIXIN) && node.getProperty(JCR_ISMIXIN).getBoolean(); }
/** * @param node * @return * @throws Exception */ public static String getTitleWithSymlink(Node node) throws Exception { String title = null; Node nProcessNode = node; if (title == null) { nProcessNode = node; if (nProcessNode.hasProperty("exo:title")) { title = nProcessNode.getProperty("exo:title").getValue().getString(); } if (nProcessNode.hasNode("jcr:content")) { Node content = nProcessNode.getNode("jcr:content"); if (content.hasProperty("dc:title")) { try { title = content.getProperty("dc:title").getValues()[0].getString(); } catch (Exception e) { title = null; } } } if (title != null) title = title.trim(); } if (title != null && title.length() > 0) return ContentReader.getXSSCompatibilityContent(title); if (isSymLink(node)) { nProcessNode = getNodeSymLink(nProcessNode); if (nProcessNode == null) { nProcessNode = node; } if (nProcessNode.hasProperty("exo:title")) { title = nProcessNode.getProperty("exo:title").getValue().getString(); } if (nProcessNode.hasNode("jcr:content")) { Node content = nProcessNode.getNode("jcr:content"); if (content.hasProperty("dc:title")) { try { title = content.getProperty("dc:title").getValues()[0].getString(); } catch (Exception e) { title = null; } } } if (title != null) { title = title.trim(); if (title.length() == 0) title = null; } } if (title == null) title = nProcessNode.getName(); return ContentReader.getXSSCompatibilityContent(title); }
@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(); }
@Test public void testAddRemoveExistingChildAndStore() throws Exception { // GIVEN JcrNodeAdapter item = new JcrNodeAdapter(baseNode); // Add property to the Item DefaultProperty<String> property = new DefaultProperty<String>(String.class, "propertyValue"); item.addItemProperty("propertyName", property); // Create one new child Item // Create a child node Node child = baseNode.addNode("childNode"); JcrNodeAdapter childItem = new JcrNodeAdapter(child); item.addChild(childItem); assertEquals(true, baseNode.hasNode("childNode")); // Add property to the child Item DefaultProperty<String> childProperty = new DefaultProperty<String>(String.class, "childPropertyValue"); childItem.addItemProperty("childPropertyName", childProperty); // WHEN item.removeChild(childItem); // THEN // Get node Node res = item.applyChanges(); assertNotNull(res); assertEquals(baseNode, res); assertEquals(true, res.hasProperty("propertyName")); assertEquals("propertyValue", res.getProperty("propertyName").getValue().getString()); assertEquals(false, res.hasNode("childNode")); }
@Test public void testAddNewChildAndStore() throws Exception { // GIVEN JcrNodeAdapter item = new JcrNodeAdapter(baseNode); // Add property to the Item DefaultProperty<String> property = new DefaultProperty<String>(String.class, "propertyValue"); item.addItemProperty("propertyName", property); // Create one new child Item JcrNewNodeAdapter newChild = new JcrNewNodeAdapter(baseNode, "mgnl:content", "childNode"); item.addChild(newChild); // Add property to the child Item DefaultProperty<String> childProperty = new DefaultProperty<String>(String.class, "childPropertyValue"); newChild.addItemProperty("childPropertyName", childProperty); // WHEN Node res = item.applyChanges(); // THEN assertNotNull(res); assertEquals(baseNode, res); assertEquals(true, res.hasProperty("propertyName")); assertEquals("propertyValue", res.getProperty("propertyName").getValue().getString()); assertEquals(true, res.hasNode("childNode")); assertEquals(true, res.getNode("childNode").hasProperty("childPropertyName")); assertEquals( "childPropertyValue", res.getNode("childNode").getProperty("childPropertyName").getValue().getString()); }
/** * Test {@link LockManager#unlock(String)} for a session that is not lock owner. * * @throws RepositoryException * @throws NotExecutableException */ public void testUnlockByOtherSession() throws RepositoryException, NotExecutableException { Session otherSession = getHelper().getReadWriteSession(); try { getLockManager(otherSession).unlock(lockedNode.getPath()); fail("Another session must not be allowed to unlock."); } catch (LockException e) { // success // make sure the node is still locked and the lock properties are // still present. assertTrue(lockMgr.isLocked(lockedNode.getPath())); assertTrue(lockedNode.hasProperty(jcrlockIsDeep)); assertTrue(lockedNode.hasProperty(jcrLockOwner)); } finally { otherSession.logout(); } }
/** {@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(); } }
private void checkCustomProperties(Session session) throws javax.jcr.RepositoryException { NodeTypeManager nodetypeManager = new NodeTypeManager(); // Check and create required custom properties javax.jcr.Node systemNode = JCRUtils.getSystemNode(session); if (systemNode.hasNode(JLibraryConstants.JLIBRARY_CUSTOM_PROPERTIES)) { javax.jcr.Node propertiesNode = systemNode.getNode(JLibraryConstants.JLIBRARY_CUSTOM_PROPERTIES); NodeIterator it = propertiesNode.getNodes(); while (it.hasNext()) { javax.jcr.Node propsNode = (javax.jcr.Node) it.next(); CustomPropertyDefinition propdef = new CustomPropertyDefinition(); propdef.setName( propsNode.getProperty(JLibraryConstants.JLIBRARY_PROPERTY_NAME).getString()); propdef.setType( (int) propsNode.getProperty(JLibraryConstants.JLIBRARY_PROPERTY_TYPE).getLong()); propdef.setMultivalued( propsNode.getProperty(JLibraryConstants.JLIBRARY_PROPERTY_MULTIVALUED).getBoolean()); propdef.setAutocreated( propsNode.getProperty(JLibraryConstants.JLIBRARY_PROPERTY_AUTOCREATED).getBoolean()); if (propsNode.hasProperty(JLibraryConstants.JLIBRARY_PROPERTY_DEFAULT)) { propdef.setDefaultValues( propsNode.getProperty(JLibraryConstants.JLIBRARY_PROPERTY_DEFAULT).getValues()); } logger.info("Registering property : " + propdef); nodetypeManager.registerCustomProperty(session, propdef); } } }
private Node prepareAnActivityNode(String id, Calendar timestamp) throws RepositoryException { Node activityNode = mock(Node.class, RETURNS_DEEP_STUBS); when(activityNode.hasProperty("timestamp")).thenReturn(true); when(activityNode.getProperty("timestamp").getDate()).thenReturn(timestamp); when(activityNode.getProperty("resourceId").getString()).thenReturn(id); return activityNode; }
/** * @param node * @param node * @throws RepositoryException * @throws PathNotFoundException * @throws ValueFormatException */ public ProviderSettingsImpl(Content profileContent, Node settingsNode) throws RepositoryException { this.profileNode = profileContent; this.settingsNode = settingsNode; if (settingsNode.hasProperty(ProviderSettings.PROFILE_PROVIDER)) { provider = settingsNode.getProperty(ProviderSettings.PROFILE_PROVIDER).getString(); } if (settingsNode.hasProperty(ProviderSettings.PROFILE_PROVIDER_SETTINGS)) { String providerSettingsPath = settingsNode.getProperty(ProviderSettings.PROFILE_PROVIDER_SETTINGS).getString(); Session session = settingsNode.getSession(); if (session.nodeExists(providerSettingsPath)) { this.providerNode = session.getNode(providerSettingsPath); } } }
private JcrNodeModel getPhysicalNode(JcrNodeModel model) { Node node = model.getNode(); if (node != null) { try { if (node.isNodeType("nt:version")) { Node frozen = node.getNode("jcr:frozenNode"); String uuid = frozen.getProperty("jcr:frozenUuid").getString(); try { Node docNode = node.getSession().getNodeByUUID(uuid); if (docNode.getDepth() > 0) { Node parent = docNode.getParent(); if (parent.isNodeType(HippoNodeType.NT_HANDLE)) { return new JcrNodeModel(parent); } } return new JcrNodeModel(docNode); } catch (ItemNotFoundException infe) { // node doesn't exist anymore. If it's a document, the handle // should still be available though. if (frozen.hasProperty(HippoNodeType.HIPPO_PATHS)) { Value[] ancestors = frozen.getProperty(HippoNodeType.HIPPO_PATHS).getValues(); if (ancestors.length > 1) { uuid = ancestors[1].getString(); return new JcrNodeModel(node.getSession().getNodeByUUID(uuid)); } } throw infe; } } } catch (RepositoryException ex) { log.error(ex.getMessage()); } } return model; }
public static ExoSocialActivity createActivity( IdentityManager identityManager, String activityOwnerId, Node node, String activityMsgBundleKey, String activityType, boolean isSystemComment, String systemComment) throws Exception { // Populate activity data Map<String, String> activityParams = populateActivityData( node, activityOwnerId, activityMsgBundleKey, isSystemComment, systemComment); String title = node.hasProperty(NodetypeConstant.EXO_TITLE) ? node.getProperty(NodetypeConstant.EXO_TITLE).getString() : org.exoplatform.ecm.webui.utils.Utils.getTitle(node); ExoSocialActivity activity = new ExoSocialActivityImpl(); String userId = ""; if (ConversationState.getCurrent() != null) { userId = ConversationState.getCurrent().getIdentity().getUserId(); } else { userId = activityOwnerId; } Identity identity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false); activity.setUserId(identity.getId()); activity.setType(activityType); activity.setUrl(node.getPath()); activity.setTitle(title); activity.setTemplateParams(activityParams); return activity; }
@Override public void write(Hit hit, JSONWriter jsonWriter, Query query) throws RepositoryException, JSONException { // Get the Node that represents a Query "hit" Node node = hit.getNode(); // Write simple values like the node's path to the JSON result object jsonWriter.key("path").value(node.getPath()); // Write node properties from the hit result node (or relative nodes) to the JSON result object final String property1 = "jcr:content/jcr:title"; if (node.hasProperty(property1)) { final Property property = node.getProperty(property1); // You have full control over the names/values of the JSON key/value pairs returned. // These do not have to match node names jsonWriter .key("key-to-use-in-json") .value(property.getString() + "(pulled from jcr:content node)"); } // Custom logic can be used to transform and/or retrieve data to be added to the resulting JSON // object // Note: Keep this logic as light as possible. Complex logic can introduce performance issues // that are // less visible (Will not appear in Slow Query logs as this logic executes after the actual // Query returns). String complexValue = sampleComplexLogic(node); jsonWriter.key("complex").value(complexValue); }
/** {@inheritDoc} */ public List<RepositoryFile> getDeletedFiles( final Session session, final PentahoJcrConstants pentahoJcrConstants) throws RepositoryException { Node trashNode = getOrCreateTrashInternalFolderNode(session, pentahoJcrConstants); if (trashNode == null) { return Collections.emptyList(); } List<RepositoryFile> deletedFiles = new ArrayList<RepositoryFile>(); NodeIterator nodes = trashNode.getNodes(); while (nodes.hasNext()) { Node trashFileNode = nodes.nextNode(); // since the nodes returned are the trash file ID nodes, // we need to getNodes().nextNode() to get its first (and only) child if (trashFileNode != null && trashFileNode.hasProperty(pentahoJcrConstants.getPHO_DELETEDDATE())) { NodeIterator trashFileNodeIterator = trashFileNode.getNodes(); if (trashFileNodeIterator.hasNext()) { deletedFiles.add( nodeToDeletedFile(session, pentahoJcrConstants, trashFileNodeIterator.nextNode())); } } } Collections.sort(deletedFiles); return deletedFiles; }
/** * Quietly removes a Property on a Node if it exists. * * @param node * @param property * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws PathNotFoundException * @throws RepositoryException */ protected static void removeProperty(final Node node, final String property) throws VersionException, LockException, ConstraintViolationException, PathNotFoundException, RepositoryException { if (node.hasProperty(property)) { node.getProperty(property).remove(); } }
private Node createFileNode() throws ValueFormatException, RepositoryException { Calendar cal = Calendar.getInstance(); Node contentNode = mock(Node.class); Property dateProp = mock(Property.class); when(dateProp.getDate()).thenReturn(cal); Property lengthProp = mock(Property.class); when(lengthProp.getLength()).thenReturn(12345L); Property mimetypeProp = mock(Property.class); when(mimetypeProp.getString()).thenReturn("text/plain"); when(contentNode.getProperty(JcrConstants.JCR_LASTMODIFIED)).thenReturn(dateProp); when(contentNode.getProperty(JcrConstants.JCR_MIMETYPE)).thenReturn(mimetypeProp); when(contentNode.getProperty(JcrConstants.JCR_DATA)).thenReturn(lengthProp); when(contentNode.hasProperty(JcrConstants.JCR_DATA)).thenReturn(true); Node node = mock(Node.class); Property fooProp = new MockProperty("foo"); fooProp.setValue("bar"); List<Property> propertyList = new ArrayList<Property>(); propertyList.add(fooProp); MockPropertyIterator propertyIterator = new MockPropertyIterator(propertyList.iterator()); when(node.getProperties()).thenReturn(propertyIterator); when(node.hasNode("jcr:content")).thenReturn(true); when(node.getNode("jcr:content")).thenReturn(contentNode); when(node.getPath()).thenReturn("/path/to/file.doc"); when(node.getName()).thenReturn("file.doc"); return node; }
/** Makes sure nobody tampers with root node UUID. */ public void testRootUUID() throws Exception { Node nd = m_session.getRootNode(); assertTrue("uuid missing", nd.hasProperty("jcr:uuid")); assertEquals("uuid value", "93b885ad-fe0d-3089-8df6-34904fd59f71", nd.getUUID()); }
@Override public List<ModelResource> search(String queryExpression) { if (queryExpression == null || queryExpression.isEmpty()) { queryExpression = "*"; } try { List<ModelResource> modelResources = new ArrayList<>(); QueryManager queryManager = session.getWorkspace().getQueryManager(); Query query = queryManager.createQuery( queryExpression, org.modeshape.jcr.api.query.Query.FULL_TEXT_SEARCH); logger.debug("Searching repository with expression " + query.getStatement()); QueryResult result = query.execute(); RowIterator rowIterator = result.getRows(); while (rowIterator.hasNext()) { Row row = rowIterator.nextRow(); Node currentNode = row.getNode(); if (currentNode.hasProperty("vorto:type") && !isMappingNode(currentNode)) { modelResources.add(createModelResource(currentNode)); } } return modelResources; } catch (RepositoryException e) { throw new RuntimeException("Could not create query manager", e); } }
/** * Writes all the properties of a sakai/file node. Also checks what the permissions are for a * session and where the links are. * * @param node * @param write * @param objectInProgress Whether object creation is in progress. If false, object is started and * ended in this method call. * @throws JSONException * @throws RepositoryException */ public static void writeFileNode(Node node, Session session, JSONWriter write, int maxDepth) throws JSONException, RepositoryException { write.object(); // dump all the properties. ExtendedJSONWriter.writeNodeTreeToWriter(write, node, true, maxDepth); // The permissions for this session. writePermissions(node, session, write); if (node.hasNode(JcrConstants.JCR_CONTENT)) { Node contentNode = node.getNode(JcrConstants.JCR_CONTENT); write.key(JcrConstants.JCR_LASTMODIFIED); Calendar cal = contentNode.getProperty(JcrConstants.JCR_LASTMODIFIED).getDate(); write.value(DateUtils.iso8601(cal)); write.key(JcrConstants.JCR_MIMETYPE); write.value(contentNode.getProperty(JcrConstants.JCR_MIMETYPE).getString()); if (contentNode.hasProperty(JcrConstants.JCR_DATA)) { write.key(JcrConstants.JCR_DATA); write.value(contentNode.getProperty(JcrConstants.JCR_DATA).getLength()); } } write.endObject(); }
/** * @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 visit(Node node) throws RepositoryException { if (node.hasProperty(OBSOLETE_APP_PROPERTY_NAME)) { node.getProperty(OBSOLETE_APP_PROPERTY_NAME).remove(); node.setProperty( CLASS_PROPERTY_NAME, ConfiguredContentAppDescriptor.class.getCanonicalName()); } }
@Test public void testGetLastModified() throws RepositoryException { when(mockObjNode.hasProperty(JCR_LASTMODIFIED)).thenReturn(true); when(mockObjNode.getProperty(JCR_LASTMODIFIED)).thenReturn(mockProp); when(mockProp.getDate()).thenReturn(Calendar.getInstance()); testFedoraObject.getLastModifiedDate(); verify(mockObjNode).getProperty(JCR_LASTMODIFIED); }
public static String getNodeOwner(Node node) throws Exception { try { if (node.hasProperty(EXO_OWNER)) { return node.getProperty(EXO_OWNER).getString(); } } catch (Exception e) { return null; } return null; }