public static boolean createLink( Content content, String link, org.sakaiproject.nakamura.api.lite.Session session) throws org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException, StorageClientException { String userId = session.getUserId(); if (User.ANON_USER.equals(userId)) { throw new org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException( Security.ZONE_CONTENT, link, "Cant create a link", userId); } ContentManager contentManager = session.getContentManager(); Content linkNode = contentManager.get(link); if (linkNode == null) { linkNode = new Content( link, ImmutableMap.of( JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, (Object) RT_SAKAI_LINK, SAKAI_LINK, content.getPath())); } else { linkNode.setProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, RT_SAKAI_LINK); linkNode.setProperty(SAKAI_LINK, content.getPath()); } contentManager.update(linkNode); return true; }
public void writeResult(SlingHttpServletRequest request, JSONWriter write, Result result) throws JSONException { String contentPath = result.getPath(); Session session = StorageClientUtils.adaptToSession( request.getResourceResolver().adaptTo(javax.jcr.Session.class)); try { Content contentResult = session.getContentManager().get(contentPath); if (contentResult != null) { write.object(); writeCanManageProperty(request, write, session, contentResult); writeCommentCountProperty(write, session, contentResult); int depth = SolrSearchUtil.getTraversalDepth(request); ExtendedJSONWriter.writeContentTreeToWriter(write, contentResult, true, depth); write.endObject(); } } catch (AccessDeniedException ade) { // if access is denied we simply won't // write anything for this result // this implies content was private LOGGER.info("Denied {} access to {}", request.getRemoteUser(), contentPath); return; } catch (Exception e) { throw new JSONException(e); } }
/** * {@inheritDoc} * * @see * org.sakaiproject.nakamura.api.solr.IndexingHandler#getDocuments(org.sakaiproject.nakamura.api.solr.RepositorySession, * org.osgi.service.event.Event) */ @Override public Collection<SolrInputDocument> getDocuments(RepositorySession repoSession, Event event) { LOGGER.debug("getDocuments for {}", event); String path = (String) event.getProperty(IndexingHandler.FIELD_PATH); List<SolrInputDocument> documents = Lists.newArrayList(); if (!StringUtils.isBlank(path)) { Session session = repoSession.adaptTo(Session.class); try { ContentManager cm = session.getContentManager(); Content content = cm.get(path); SolrInputDocument doc = new SolrInputDocument(); for (Entry<String, String> prop : PROPERTIES.entrySet()) { String key = prop.getKey(); Object value = content.getProperty(key); if (value != null) { doc.addField(PROPERTIES.get(key), value); } } doc.setField(_DOC_SOURCE_OBJECT, content); documents.add(doc); } catch (StorageClientException e) { LOGGER.error(e.getMessage(), e); } catch (AccessDeniedException e) { LOGGER.error(e.getMessage(), e); } } return documents; }
/** * Apply the 'search by role' filter to the lucene query string. * * @param parametersMap * @param filters */ protected void buildSearchByRoleQuery(Map<String, String> parametersMap, List<String> filters) { SearchableRole role = SearchableRole.valueOf(getSearchParam(parametersMap, REQUEST_PARAMETERS.role.toString())); String userid = getSearchParam(parametersMap, REQUEST_PARAMETERS.userid.toString()); AuthorizableManager authorizableManager = null; Session adminSession = null; try { adminSession = repository.loginAdministrative(); authorizableManager = adminSession.getAuthorizableManager(); Authorizable au = authorizableManager.findAuthorizable(userid); List<Authorizable> groups = AuthorizableUtil.getUserFacingGroups(au, authorizableManager); groups.add(au); List<String> groupStrs = new ArrayList<String>(groups.size()); for (Authorizable memberAuthz : groups) { groupStrs.add(ClientUtils.escapeQueryChars(memberAuthz.getId())); } filters.add(String.format(ROLE_TEMPLATE, role.toString(), JOINER_OR.join(groupStrs))); adminSession.logout(); } catch (ClientPoolException e) { throw new RuntimeException(e); } catch (StorageClientException e) { throw new RuntimeException(e); } catch (AccessDeniedException e) { throw new RuntimeException(e); } finally { SparseUtils.logoutQuietly(adminSession); } }
private String[] getReadingPrincipals( RepositorySession repositorySession, String zone, String path) throws StorageClientException { Session session = repositorySession.adaptTo(Session.class); AccessControlManager accessControlManager = session.getAccessControlManager(); return accessControlManager.findPrincipals( zone, path, Permissions.CAN_READ.getPermission(), true); }
/** * {@inheritDoc} * * @see * org.sakaiproject.nakamura.api.personal.PersonalTrackingStore#recordActivity(java.lang.String, * java.lang.String, java.lang.String, java.lang.String, java.util.Date) */ public void recordActivity( String resourceId, String resourceType, String activityType, String userId, Calendar timestamp) { Session session = null; try { session = repository.loginAdministrative(); final ContentManager cm = session.getContentManager(); final String trackingNodePath = "/activity/" + resourceType + "/" + resourceId; Content trackingNode = null; if (cm.exists(trackingNodePath)) { trackingNode = cm.get(trackingNodePath); } else { trackingNode = new Content(trackingNodePath, new HashMap<String, Object>()); } if (!trackingNode.hasProperty("count")) { trackingNode.setProperty("count", BigDecimal.ZERO); } if (!trackingNode.hasProperty("sling:resourceType")) { trackingNode.setProperty("sling:resourceType", "sakai/resource-activity"); } final String generatedNodeName = Base64.encodeBase64URLSafeString(asShorterByteArray(UUID.randomUUID())); final String activityNodePath = trackingNodePath + "/" + generatedNodeName; Content activityNode = null; if (cm.exists(activityNodePath)) { activityNode = cm.get(activityNodePath); } else { activityNode = new Content(activityNodePath, new HashMap<String, Object>()); } BigDecimal activityCount = (BigDecimal) trackingNode.getProperty("count"); activityNode.setProperty("sling:resourceType", "sakai/resource-update"); trackingNode.setProperty("count", activityCount.add(BigDecimal.ONE)); activityNode.setProperty("resourceId", resourceId); activityNode.setProperty("resourcetype", resourceType); activityNode.setProperty("activitytype", activityType); activityNode.setProperty("timestamp", timestamp); activityNode.setProperty("userid", userId); cm.update(activityNode); cm.update(trackingNode); } catch (AccessDeniedException e) { LOG.error(e.getLocalizedMessage(), e); } catch (StorageClientException e) { LOG.error(e.getLocalizedMessage(), e); } finally { if (session != null) { try { session.logout(); } catch (ClientPoolException e) { LOG.error(e.getLocalizedMessage(), e); throw new IllegalStateException(e); } } } }
private AuthorizableManager getAuthorizableManager( HttpServletRequest request, HttpServletResponse response) throws StorageClientException { Session session = sessionTracker.get(request); if (session == null) { session = sessionTracker.register(authenticationService.authenticate(request, response), request); } return session.getAuthorizableManager(); }
/** * {@inheritDoc} * * @see * org.sakaiproject.nakamura.api.solr.IndexingHandler#getDocuments(org.sakaiproject.nakamura.api.solr.RepositorySession, * org.osgi.service.event.Event) */ public Collection<SolrInputDocument> getDocuments( RepositorySession repositorySession, Event event) { String path = (String) event.getProperty(FIELD_PATH); logger.info("Indexing connections at path {}", path); List<SolrInputDocument> documents = Lists.newArrayList(); if (!StringUtils.isBlank(path)) { try { Session session = repositorySession.adaptTo(Session.class); ContentManager cm = session.getContentManager(); Content content = cm.get(path); int lastSlash = path.lastIndexOf('/'); String contactName = path.substring(lastSlash + 1); AuthorizableManager am = session.getAuthorizableManager(); Authorizable contactAuth = am.findAuthorizable(contactName); if (content != null && contactAuth != null) { SolrInputDocument doc = new SolrInputDocument(); for (Entry<String, String> prop : WHITELISTED_PROPS.entrySet()) { String key = prop.getKey(); Object value = content.getProperty(key); if (value != null) { doc.addField(WHITELISTED_PROPS.get(key), value); } } // flatten out the contact so we can search it Map<String, Object> contactProps = contactAuth.getSafeProperties(); if (contactAuth != null) { for (String prop : FLATTENED_PROPS) { Object value = contactProps.get(prop); if (value != null) { doc.addField(prop, value); } } } doc.addField(_DOC_SOURCE_OBJECT, content); documents.add(doc); } else { logger.warn( "Did not index {}: Content == {}; Contact Auth == {}", new Object[] {path, content, contactAuth}); } } catch (StorageClientException e) { logger.error(e.getMessage(), e); } catch (AccessDeniedException e) { logger.error(e.getMessage(), e); } } logger.debug("Got documents {} ", documents); return documents; }
/** * {@inheritDoc} * * @see * org.sakaiproject.nakamura.api.solr.IndexingHandler#getDocuments(org.sakaiproject.nakamura.api.solr.RepositorySession, * org.osgi.service.event.Event) */ public Collection<SolrInputDocument> getDocuments( RepositorySession repositorySession, Event event) { LOGGER.debug("GetDocuments for {} ", event); String path = (String) event.getProperty("path"); if (ignorePath(path)) { return Collections.emptyList(); } List<SolrInputDocument> documents = Lists.newArrayList(); if (path != null) { try { Session session = repositorySession.adaptTo(Session.class); ContentManager contentManager = session.getContentManager(); Content content = contentManager.get(path); if (content != null) { SolrInputDocument doc = new SolrInputDocument(); Map<String, Object> properties = content.getProperties(); for (Entry<String, Object> p : properties.entrySet()) { String indexName = index(p); if (indexName != null) { for (Object o : convertToIndex(p)) { doc.addField(indexName, o); } } } InputStream contentStream = contentManager.getInputStream(path); if (contentStream != null) { try { String extracted = tika.parseToString(contentStream); doc.addField("content", extracted); } catch (TikaException e) { LOGGER.warn(e.getMessage(), e); } } doc.addField(_DOC_SOURCE_OBJECT, content); documents.add(doc); } } catch (ClientPoolException e) { LOGGER.warn(e.getMessage(), e); } catch (StorageClientException e) { LOGGER.warn(e.getMessage(), e); } catch (AccessDeniedException e) { LOGGER.warn(e.getMessage(), e); } catch (IOException e) { LOGGER.warn(e.getMessage(), e); } } LOGGER.debug("Got documents {} ", documents); return documents; }
public CreateContentPoolServletTest() throws ClientPoolException, StorageClientException, AccessDeniedException, ClassNotFoundException { MockitoAnnotations.initMocks(this); BaseMemoryRepository baseMemoryRepository = new BaseMemoryRepository(); repository = baseMemoryRepository.getRepository(); Session session = repository.loginAdministrative(); AuthorizableManager authorizableManager = session.getAuthorizableManager(); authorizableManager.createUser("ieb", "Ian Boston", "test", ImmutableMap.of("x", (Object) "y")); org.sakaiproject.nakamura.api.lite.authorizable.Authorizable authorizable = authorizableManager.findAuthorizable("ieb"); System.err.println("Got ieb as " + authorizable); session.logout(); }
@SuppressWarnings("unchecked") private <T> T getHandler( RepositorySession repositorySession, String path, Map<String, T> indexers, Map<String, String> ignoreCache) { org.sakaiproject.nakamura.api.lite.Session sparseSession = repositorySession.adaptTo(org.sakaiproject.nakamura.api.lite.Session.class); while (path != null) { if (!ignoreCache.containsKey(path)) { try { if (sparseSession != null) { ContentManager contentManager = sparseSession.getContentManager(); Content c = contentManager.get(path); LOGGER.debug("Checking Content at {} got {} ", path, c); if (c != null) { if (c.hasProperty("sling:resourceType")) { String resourceType = (String) c.getProperty("sling:resourceType"); T handler = indexers.get(resourceType); if (handler != null) { LOGGER.debug( "Handler of type {} found {} for {} from {} ", new Object[] {resourceType, handler, path, indexers}); return handler; } else { LOGGER.debug("Ignoring {}; no handler", path); synchronized (this) { ignoreCache.put(path, path); } } } else { LOGGER.debug("Ignored {} no resource type ", path); } } } } catch (StorageClientException e) { LOGGER.debug(e.getMessage(), e); } catch (AccessDeniedException e) { LOGGER.debug(e.getMessage(), e); } } if (StorageClientUtils.isRoot(path)) { break; } path = Utils.getParentPath(path); } return (T) defaultHandler; }
public static void writeLinkNode( Content content, org.sakaiproject.nakamura.api.lite.Session session, JSONWriter writer, boolean objectInProgress) throws StorageClientException, JSONException { if (!objectInProgress) { writer.object(); } ContentManager contentManager = session.getContentManager(); // Write all the properties. ExtendedJSONWriter.writeNodeContentsToWriter(writer, content); // permissions writePermissions(content, session, writer); // Write the actual file. if (content.hasProperty(SAKAI_LINK)) { String linkPath = (String) content.getProperty(SAKAI_LINK); writer.key("file"); try { Content fileNode = contentManager.get(linkPath); writeFileNode(fileNode, session, writer); } catch (org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException e) { writer.value(false); } } if (!objectInProgress) { writer.endObject(); } }
/** * Gets the principals that can read content at a given path. * * @param session * @param path The path to check. * @return {@link String[]} of principal names that can read {@link path}. An empty array is * returned if no principals can read the path. * @throws StorageClientException */ @SuppressWarnings("unused") private String[] getReadingPrincipals(Session session, String path) throws StorageClientException { AccessControlManager accessControlManager = session.getAccessControlManager(); return accessControlManager.findPrincipals( Security.ZONE_CONTENT, path, Permissions.CAN_READ.getPermission(), true); }
private static void writePermissions( Content content, org.sakaiproject.nakamura.api.lite.Session session, JSONWriter writer) throws StorageClientException, JSONException { if (content == null) { log.warn("Can't output permissions of null content."); return; } AccessControlManager acm = session.getAccessControlManager(); String path = content.getPath(); writer.key("permissions"); writer.object(); writer.key("set_property"); // TODO does CAN_WRITE == set_property -CFH : yes, ieb // TODO: make this a bit more efficient, checking permissions one by one is going to rely on // caching to make it efficient. It would be better to get the permissions bitmap and then // check it to see what has been set. That might require a niew methods in the // AccessControl // manager API. writer.value(hasPermission(acm, path, Permissions.CAN_WRITE)); writer.key("read"); writer.value(hasPermission(acm, path, Permissions.CAN_READ)); writer.key("remove"); writer.value(hasPermission(acm, path, Permissions.CAN_DELETE)); writer.endObject(); }
public void writeResult(SlingHttpServletRequest request, JSONWriter write, Result result) throws JSONException { String contentPath = (String) result.getFirstValue("path"); Session session = StorageClientUtils.adaptToSession( request.getResourceResolver().adaptTo(javax.jcr.Session.class)); try { Content contentResult = session.getContentManager().get(contentPath); if (contentResult != null) { ExtendedJSONWriter.writeContentTreeToWriter(write, contentResult, -1); } else { write.object().endObject(); } } catch (Exception e) { throw new JSONException(e); } }
/** * Same as writeResults logic, but counts number of results iterated over. * * @param request * @param write * @param iterator * @return Set containing all unique paths processed. * @throws JSONException */ public Set<String> writeResultsInternal( SlingHttpServletRequest request, JSONWriter write, Iterator<Result> iterator) throws JSONException { final Set<String> uniquePaths = new HashSet<String>(); final Integer iDepth = (Integer) request.getAttribute("depth"); int depth = 0; if (iDepth != null) { depth = iDepth.intValue(); } try { javax.jcr.Session jcrSession = request.getResourceResolver().adaptTo(javax.jcr.Session.class); final Session session = StorageClientUtils.adaptToSession(jcrSession); while (iterator.hasNext()) { final Result result = iterator.next(); uniquePaths.add(result.getPath()); try { if ("authorizable".equals(result.getFirstValue("resourceType"))) { AuthorizableManager authManager = session.getAuthorizableManager(); Authorizable auth = authManager.findAuthorizable((String) result.getFirstValue("id")); if (auth != null) { write.object(); ValueMap map = profileService.getProfileMap(auth, jcrSession); ExtendedJSONWriter.writeValueMapInternals(write, map); write.endObject(); } } else { String contentPath = result.getPath(); final Content content = session.getContentManager().get(contentPath); if (content != null) { handleContent(content, session, write, depth); } else { LOGGER.debug("Found null content item while writing results [{}]", contentPath); } } } catch (AccessDeniedException e) { // do nothing } catch (RepositoryException e) { throw new JSONException(e); } } } catch (StorageClientException e) { throw new JSONException(e); } return uniquePaths; }
private IndexingHandler getHandler(RepositorySession repositorySession, String path) { org.sakaiproject.nakamura.api.lite.Session sparseSession = repositorySession.adaptTo(org.sakaiproject.nakamura.api.lite.Session.class); while (path != null) { if (!ignoreCache.containsKey(path)) { try { if (sparseSession != null) { ContentManager contentManager = sparseSession.getContentManager(); Content c = contentManager.get(path); LOGGER.debug("Checking Content at {} got {} ", path, c); if (c != null) { if (c.hasProperty(SLING_RESOURCE_TYPE)) { String resourceType = (String) c.getProperty(SLING_RESOURCE_TYPE); IndexingHandler handler = indexers.get(resourceType); if (handler != null) { LOGGER.debug( "Handler of type {} found {} for {} from {} ", new Object[] {resourceType, handler, path, indexers}); return handler; } else { TelemetryCounter.incrementValue( "solr", "SparseIndexingServiceImpl-ignoredPath", path); LOGGER.debug("Ignored {} no handler for {} ", path, resourceType); ignoreCache.put(path, path); } } else { LOGGER.debug("Ignored {} no resource type ", path); } } } } catch (StorageClientException e) { LOGGER.debug(e.getMessage(), e); } catch (AccessDeniedException e) { LOGGER.debug(e.getMessage(), e); } } if (StorageClientUtils.isRoot(path)) { break; } path = Utils.getParentPath(path); } TelemetryCounter.incrementValue("solr", "SparseIndexingServiceImpl", "useDefaultHandler"); return defaultHandler; }
/** Return the administrative session and close it. */ private void ungetSession(final Session session) { if (session != null) { try { session.logout(); } catch (Throwable t) { LOGGER.error("Unable to log out of session: " + t.getMessage(), t); } } }
public void process(FilterChain chain, Request request, Response response) { try { chain.process(request, response); for (Session s : tracker.get()) { LOGGER.debug("Committing {} ", s); s.commit(); } } finally { Set<Session> sessions = tracker.get(); for (Session s : sessions) { try { LOGGER.debug("Logout {} ", s); s.logout(); } catch (ClientPoolException e) { LOGGER.error(e.getMessage(), e); } } sessions.clear(); } }
/** * Writes commentCount of content * * @param node * @param session * @param write * @throws RepositoryException * @throws JSONException */ public static void writeCommentCountProperty( Content content, org.sakaiproject.nakamura.api.lite.Session session, JSONWriter writer, Repository repository) throws StorageClientException, JSONException { int commentCount = 0; String COMMENTCOUNT = "commentCount"; if (content.hasProperty(COMMENTCOUNT)) { commentCount = (Integer) content.getProperty(COMMENTCOUNT); } else { // no commentCount property on Content, then evaluate count and add property Content comments = null; org.sakaiproject.nakamura.api.lite.Session adminSession = null; try { comments = session.getContentManager().get(content.getPath() + "/comments"); if (comments != null) { commentCount = Iterables.size(comments.listChildPaths()); } content.setProperty(COMMENTCOUNT, commentCount); // save property adminSession = repository.loginAdministrative(); ContentManager adminContentManager = adminSession.getContentManager(); adminContentManager.update(content); } catch (org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException e) { log.error(e.getMessage(), e); } finally { if (adminSession != null) { try { adminSession.logout(); } catch (Exception e) { log.error("Could not logout administrative session."); } } } } writer.key(COMMENTCOUNT); writer.value(commentCount); }
private String convertToEmail(String address, org.sakaiproject.nakamura.api.lite.Session session) throws StorageClientException, AccessDeniedException { if (address.indexOf('@') < 0) { String emailAddress = null; Authorizable user = session.getAuthorizableManager().findAuthorizable(address); if (user != null) { Content profile = session.getContentManager().get(LitePersonalUtils.getProfilePath(user.getId())); if (profile != null) { emailAddress = LitePersonalUtils.getProfilePath(user.getId()); } } if (emailAddress != null && emailAddress.trim().length() > 0) { address = emailAddress; } else { address = address + "@" + smtpServer; } } return address; }
private void updateContentAccess( Session session, Content content, List<AclModification> aclModifications) throws StorageClientException, AccessDeniedException { LOGGER.debug( "ACL Modifications {}", Arrays.toString(aclModifications.toArray(new AclModification[aclModifications.size()]))); session .getAccessControlManager() .setAcl( Security.ZONE_CONTENT, content.getPath(), aclModifications.toArray(new AclModification[aclModifications.size()])); }
private void writeCommentCountProperty(JSONWriter write, Session session, Content contentResult) throws StorageClientException, JSONException, AccessDeniedException { ContentManager contentManager = session.getContentManager(); Content comments = contentManager.get(contentResult.getPath() + "/" + "comments"); long commentCount = 0; if (comments != null) { for (@SuppressWarnings("unused") Content comment : comments.listChildren()) { commentCount++; } } write.key("commentCount"); write.value(commentCount); }
/** * Process properties to query sparse content directly. * * @param request * @param query * @param asAnon * @return * @throws StorageClientException * @throws AccessDeniedException */ private SolrSearchResultSet processSparseQuery( SlingHttpServletRequest request, Query query, boolean asAnon) throws StorageClientException, AccessDeniedException, ParseException { // use solr parsing to get the terms from the query string QueryParser parser = new QueryParser(Version.LUCENE_40, "id", new TextField().getQueryAnalyzer()); org.apache.lucene.search.Query luceneQuery = parser.parse(query.getQueryString()); Set<Term> terms = Sets.newHashSet(); luceneQuery.extractTerms(terms); Map<String, Object> props = Maps.newHashMap(); for (Term term : terms) { props.put(term.field(), term.text()); } Session session = StorageClientUtils.adaptToSession( request.getResourceResolver().adaptTo(javax.jcr.Session.class)); ContentManager cm = session.getContentManager(); Iterable<Content> items = cm.find(props); SolrSearchResultSet rs = new SparseSearchResultSet(items); return rs; }
/** * Process a query string to search using Solr. * * @param request * @param query * @param asAnon * @param rs * @return * @throws SolrSearchException */ private SolrSearchResultSet processSolrQuery( SlingHttpServletRequest request, Query query, boolean asAnon) throws StorageClientException, AccessDeniedException, SolrServerException { String queryString = query.getQueryString(); // apply readers restrictions. if (asAnon) { queryString = "(" + queryString + ") AND readers:" + User.ANON_USER; } else { Session session = StorageClientUtils.adaptToSession( request.getResourceResolver().adaptTo(javax.jcr.Session.class)); if (!User.ADMIN_USER.equals(session.getUserId())) { AuthorizableManager am = session.getAuthorizableManager(); Authorizable user = am.findAuthorizable(session.getUserId()); Set<String> readers = Sets.newHashSet(); for (Iterator<Group> gi = user.memberOf(am); gi.hasNext(); ) { readers.add(gi.next().getId()); } readers.add(session.getUserId()); queryString = "(" + queryString + ") AND readers:(" + StringUtils.join(readers, " OR ") + ")"; } } SolrQuery solrQuery = buildQuery(request, queryString, query.getOptions()); SolrServer solrServer = solrSearchService.getServer(); try { LOGGER.info("Performing Query {} ", URLDecoder.decode(solrQuery.toString(), "UTF-8")); } catch (UnsupportedEncodingException e) { } QueryResponse response = solrServer.query(solrQuery); SolrDocumentList resultList = response.getResults(); LOGGER.info("Got {} hits in {} ms", resultList.size(), response.getElapsedTime()); return new SolrSearchResultSetImpl(response); }
@Before public void setUp() throws Exception { provider = new MyRelatedGroupsPropertyProvider(searchServiceFactory); when(request.getRemoteUser()).thenReturn("user1"); when(repo.loginAdministrative()).thenReturn(session); when(session.getAuthorizableManager()).thenReturn(authMgr); when(authMgr.findAuthorizable("user1")).thenReturn(auth1); Group group1 = mock(Group.class); when(group1.getId()).thenReturn("group1"); when(group1.getProperty(GROUP_TITLE_PROPERTY)).thenReturn("Group 1 Test"); when(group1.getProperty("sakai:tag-uuid")).thenReturn(new String[] {"123-456"}); when(auth1.memberOf(authMgr)).thenReturn(Sets.newHashSet(group1).iterator()); when(searchServiceFactory.getSearchResultSet(eq(request), any(Query.class))).thenReturn(rs); }
/** * Writes comments of content * * @param node * @param session * @param write * @throws RepositoryException * @throws JSONException */ public static void writeComments( Content content, org.sakaiproject.nakamura.api.lite.Session session, JSONWriter writer) throws StorageClientException, JSONException { if (content == null) { log.warn("Can't output comments of null content."); return; } writer.key("comments"); writer.object(); Content commentContent = null; try { commentContent = session.getContentManager().get(content.getPath() + "/comments"); ExtendedJSONWriter.writeContentTreeToWriter(writer, commentContent, true, 2); } catch (org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException e) { writer.value(false); } finally { writer.endObject(); } }
private void writeCanManageProperty( SlingHttpServletRequest request, JSONWriter write, Session session, Content contentResult) throws StorageClientException, JSONException, AccessDeniedException { write.key("sakai:canmanage"); Authorizable thisUser = session.getAuthorizableManager().findAuthorizable(request.getRemoteUser()); Collection<String> principals = new ArrayList<String>(); principals.addAll(Arrays.asList(thisUser.getPrincipals())); principals.add(request.getRemoteUser()); boolean canManage = false; for (String principal : principals) { if (Arrays.asList( StorageClientUtils.nonNullStringArray( (String[]) contentResult.getProperty("sakai:pooled-content-manager"))) .contains(principal)) { canManage = true; } } write.value(canManage); }
private void updateContentMembers( Session session, Content content, Set<String> viewerSet, Set<String> managerSet, Set<String> editorSet) throws StorageClientException, AccessDeniedException { content.setProperty( POOLED_CONTENT_USER_VIEWER, viewerSet.toArray(new String[viewerSet.size()])); content.setProperty( POOLED_CONTENT_USER_MANAGER, managerSet.toArray(new String[managerSet.size()])); content.setProperty( POOLED_CONTENT_USER_EDITOR, editorSet.toArray(new String[editorSet.size()])); LOGGER.debug( "Set Managers to {}", Arrays.toString(managerSet.toArray(new String[managerSet.size()]))); LOGGER.debug( "Set Editors to {}", Arrays.toString(editorSet.toArray(new String[editorSet.size()]))); LOGGER.debug( "Set Viewers to {}", Arrays.toString(viewerSet.toArray(new String[managerSet.size()]))); session.getContentManager().update(content); }
@Test public void testProperPost() throws ServletException, IOException, RepositoryException, JSONException, AccessDeniedException, StorageClientException { SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class); SlingHttpServletResponse response = createMock(SlingHttpServletResponse.class); javax.jcr.Session jcrSession = Mockito.mock( javax.jcr.Session.class, Mockito.withSettings().extraInterfaces(SessionAdaptable.class)); Session mockSession = mock(Session.class); ContentManager contentManager = mock(ContentManager.class); when(mockSession.getContentManager()).thenReturn(contentManager); Mockito.when(((SessionAdaptable) jcrSession).getSession()).thenReturn(mockSession); ResourceResolver resourceResolver = mock(ResourceResolver.class); Mockito.when(resourceResolver.adaptTo(javax.jcr.Session.class)).thenReturn(jcrSession); expect(request.getResourceResolver()).andReturn(resourceResolver); // Provide parameters String[] dimensions = new String[] {"16x16", "32x32"}; addStringRequestParameter(request, "img", "/~johndoe/people.png"); addStringRequestParameter(request, "save", "/~johndoe/breadcrumbs"); addStringRequestParameter(request, "x", "10"); addStringRequestParameter(request, "y", "10"); addStringRequestParameter(request, "width", "70"); addStringRequestParameter(request, "height", "70"); addStringRequestParameter(request, "dimensions", StringUtils.join(dimensions, 0, ';')); expect(request.getRemoteUser()).andReturn("johndoe"); String imagePath = "a:johndoe/people.png"; when(contentManager.getInputStream(imagePath)) .thenReturn(getClass().getClassLoader().getResourceAsStream("people.png")); when(contentManager.get(anyString())).thenReturn(new Content("foo", null)); SparseContentResource someResource = mock(SparseContentResource.class); when(someResource.adaptTo(Content.class)) .thenReturn( new Content( imagePath, ImmutableMap.of( "mimeType", (Object) "image/png", "_bodyLocation", "2011/lt/zz/x8"))); JackrabbitSession jrSession = mock(JackrabbitSession.class); SparseMapUserManager userManager = mock(SparseMapUserManager.class); when(userManager.getSession()).thenReturn(mockSession); when(jrSession.getUserManager()).thenReturn(userManager); when(resourceResolver.adaptTo(javax.jcr.Session.class)).thenReturn(jrSession); when(resourceResolver.getResource(anyString())).thenReturn(someResource); // Capture output. ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter write = new PrintWriter(baos); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); expect(response.getWriter()).andReturn(write); replay(); servlet.doPost(request, response); write.flush(); String s = baos.toString("UTF-8"); JSONObject o = new JSONObject(s); JSONArray files = o.getJSONArray("files"); assertEquals(2, files.length()); for (int i = 0; i < files.length(); i++) { String url = files.getString(i); assertEquals("/~johndoe/breadcrumbs/" + dimensions[i] + "_people.png", url); } }