@Test public void testCreateLinkNode() throws AccessDeniedException, RepositoryException { Node fileNode = createFileNode(); Session session = mock(Session.class); Session adminSession = mock(Session.class); SlingRepository slingRepository = mock(SlingRepository.class); String linkPath = "/path/to/link"; String sitePath = "/path/to/site"; when(session.getUserID()).thenReturn("alice"); when(fileNode.getSession()).thenReturn(session); NodeType[] nodeTypes = new NodeType[0]; when(fileNode.getMixinNodeTypes()).thenReturn(nodeTypes); when(session.getItem(fileNode.getPath())).thenReturn(fileNode); when(adminSession.getItem(fileNode.getPath())).thenReturn(fileNode); when(slingRepository.loginAdministrative(null)).thenReturn(adminSession); when(adminSession.hasPendingChanges()).thenReturn(true); when(session.hasPendingChanges()).thenReturn(true); // link Node linkNode = mock(Node.class); when(session.itemExists(linkPath)).thenReturn(true); when(session.getItem(linkPath)).thenReturn(linkNode); FileUtils.createLink(fileNode, linkPath, null, slingRepository); verify(fileNode).addMixin(FilesConstants.REQUIRED_MIXIN); verify(session).save(); verify(adminSession).save(); verify(adminSession).logout(); }
protected void activate(final ComponentContext ctx) { if (TMP_DIR != null) { File tmpDir = new File(TMP_DIR); fontsDir = new File(tmpDir, "fonts." + UUID.randomUUID()); fontsDir.mkdir(); fontsDir.deleteOnExit(); Session session = null; try { session = repo.loginAdministrative(repo.getDefaultWorkspace()); if (session.nodeExists(FONT_CONFIG)) { configFile = createFile(session.getNode(FONT_CONFIG)); } if (session.nodeExists(FONT_CONFIG_FONTS)) { Node fonts = session.getNode(FONT_CONFIG_FONTS); NodeIterator children = fonts.getNodes(); while (children.hasNext()) { createFile((Node) children.next()); } } } catch (RepositoryException e) { logger.error("Failed exporting FOP font data.", e); } finally { if (session != null) { session.logout(); } } } }
@org.junit.BeforeClass public static void setupRepository() throws Exception { RepositoryUtil.startRepository(); final SlingRepository repository = RepositoryUtil.getRepository(); session = repository.loginAdministrative(repository.getDefaultWorkspace()); assertTrue( RepositoryUtil.registerNodeType( session, DistributingEventHandler.class.getResourceAsStream("/SLING-INF/nodetypes/event.cnd"))); assertTrue( RepositoryUtil.registerNodeType( session, DistributingEventHandler.class.getResourceAsStream("/SLING-INF/nodetypes/folder.cnd"))); }
@Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { String paramUser = request.getParameter(SiteService.SiteEvent.USER); logger.info("Request to add user " + paramUser); String paramGroup = ""; try { Node requestedNode = request.getResource().adaptTo(Node.class); Value[] authorizables = requestedNode.getProperty("sakai:authorizables").getValues(); paramGroup = authorizables[1].getString(); request.setAttribute(JoinRequestConstants.PARAM_SITENODE, requestedNode); Session session = slingRepository.loginAdministrative(null); UserManager userManager = AccessControlUtil.getUserManager(session); Authorizable userAuth = userManager.getAuthorizable(paramUser); Group groupAuth = (Group) userManager.getAuthorizable(paramGroup); if (siteJoinIsAuthorized(request)) { groupAuth.addMember(userAuth); logger.info(paramUser + " added as member of group " + paramGroup); } else { response.sendError(403, "Not authorized to add member to site."); } if (session.hasPendingChanges()) { session.save(); } } catch (Exception e) { response.sendError(500, e.getMessage()); } }
public void initDefaultUsers() { Session session = null; try { session = repository.loginAdministrative(null); UserManager userManager = AccessControlUtil.getUserManager(session); // Apply default user properties from JSON files. Pattern fileNamePattern = Pattern.compile("/users/|\\.json"); @SuppressWarnings("rawtypes") Enumeration entriesEnum = bundle.findEntries("users", "*.json", true); while (entriesEnum.hasMoreElements()) { Object entry = entriesEnum.nextElement(); URL jsonUrl = new URL(entry.toString()); String jsonFileName = jsonUrl.getFile(); String authorizableId = fileNamePattern.matcher(jsonFileName).replaceAll(""); Authorizable authorizable = userManager.getAuthorizable(authorizableId); if (authorizable != null) { applyJsonToAuthorizable(jsonUrl, authorizable, session); LOGGER.info("Initialized default authorizable {}", authorizableId); } else { LOGGER.warn("Configured default authorizable {} not found", authorizableId); } } } catch (RepositoryException e) { LOGGER.error("Could not configure default authorizables", e); } catch (IOException e) { LOGGER.error("Could not configure default authorizables", e); } finally { if (session != null) { session.logout(); } } }
@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 Session createAdminSession() { try { return repository.loginAdministrative(null); } catch (final RepositoryException e) { } return null; }
/** * 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; }
/** * {@inheritDoc} * * @see org.subethamail.smtp.helper.SimpleMessageListener#accept(java.lang.String, * java.lang.String) */ public boolean accept(String from, String recipient) { Session session = null; try { session = slingRepository.loginAdministrative(null); List<String> paths = getLocalPath(session, recipient); return paths.size() > 0; } catch (Exception e) { LOGGER.error("Develier message with this handler ", e); } finally { if (session != null) { session.logout(); } } return false; }
public void deliver(String from, String recipient, InputStream data) throws TooMuchDataException, IOException { LOGGER.info("Got message FROM: " + from + " TO: " + recipient); Session session = null; try { session = slingRepository.loginAdministrative(null); List<String> paths = getLocalPath(session, recipient); if (paths.size() > 0) { Map<String, Object> mapProperties = new HashMap<String, Object>(); mapProperties.put( JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, MessageConstants.SAKAI_MESSAGE_RT); mapProperties.put(MessageConstants.PROP_SAKAI_READ, false); mapProperties.put(MessageConstants.PROP_SAKAI_FROM, from); mapProperties.put(MessageConstants.PROP_SAKAI_MESSAGEBOX, MessageConstants.BOX_INBOX); Node createdMessage = writeMessage(session, mapProperties, data, paths.get(0)); String messagePath = createdMessage.getPath(); String messageId = createdMessage.getProperty("message-id").getString(); LOGGER.info("Created message {} at: {} ", messageId, messagePath); // we might want alias expansion for (int i = 1; i < paths.size(); i++) { String targetPath = paths.get(i); messagingService.copyMessageNode(createdMessage, targetPath); } if (session.hasPendingChanges()) { session.save(); } } } catch (RepositoryException e) { LOGGER.error("Unable to write message", e); throw new IOException("Message can not be written to repository"); } finally { if (session != null) { session.logout(); } } }
@Override public void execute(WorkItem workItem, WorkflowSession workflowSession, String[] strings) throws Exception { log.info("executing workflow"); WorkflowData workflowData = workItem.getWorkflowData(); String payload = workflowData.getPayload().toString(); log.info("payload " + payload); // find agent id if (strings.length == 0) { throw new Exception("Agent name is not set in arguments for workflow process step"); } final String agentId = StringUtils.trim(strings[0]); log.info("agent id " + agentId); // filter agent ReplicationOptions opts = new ReplicationOptions(); opts.setFilter( new AgentFilter() { public boolean isIncluded(final Agent agent) { return agentId.equals(agent.getId()); } }); // activate page Session session = null; try { session = repository.loginAdministrative(null); replicator.replicate(session, ReplicationActionType.ACTIVATE, payload, opts); } finally { if (session != null) { session.logout(); } } }
@Test public void testCreate() throws Exception { // activate when(slingRepository.loginAdministrative(null)).thenReturn(adminSession); when(request.getResourceResolver()).thenReturn(resourceResolver); when(resourceResolver.adaptTo(javax.jcr.Session.class)).thenReturn(jcrSesson); Session session = repository.loginAdministrative("ieb"); when(jcrSesson.getUserManager()).thenReturn(sparseMapUserManager); when(sparseMapUserManager.getSession()).thenReturn(session); when(clusterTrackingService.getClusterUniqueId()) .thenReturn(String.valueOf(System.currentTimeMillis())); when(request.getRequestPathInfo()).thenReturn(requestPathInfo); when(requestPathInfo.getExtension()).thenReturn(null); when(adminSession.getUserManager()).thenReturn(userManager); when(adminSession.getPrincipalManager()).thenReturn(principalManager); when(adminSession.getAccessControlManager()).thenReturn(accessControlManager); when(request.getRemoteUser()).thenReturn("ieb"); when(request.getRequestParameterMap()).thenReturn(requestParameterMap); Map<String, RequestParameter[]> map = new HashMap<String, RequestParameter[]>(); RequestParameter[] requestParameters = new RequestParameter[] { requestParameter1, requestParameterNot, requestParameter2, }; map.put("files", requestParameters); when(requestParameterMap.entrySet()).thenReturn(map.entrySet()); when(requestParameter1.isFormField()).thenReturn(false); when(requestParameter1.getContentType()).thenReturn("application/pdf"); when(requestParameter1.getFileName()).thenReturn("testfilename.pdf"); InputStream input1 = new ByteArrayInputStream(new byte[10]); when(requestParameter1.getInputStream()).thenReturn(input1); when(requestParameter2.isFormField()).thenReturn(false); when(requestParameter2.getContentType()).thenReturn("text/html"); when(requestParameter2.getFileName()).thenReturn("index.html"); InputStream input2 = new ByteArrayInputStream(new byte[10]); when(requestParameter2.getInputStream()).thenReturn(input2); when(requestParameterNot.isFormField()).thenReturn(true); // deep create // when(adminSession.nodeExists(CreateContentPoolServlet.POOLED_CONTENT_ROOT)).thenReturn(true); when(adminSession.itemExists(Mockito.anyString())).thenReturn(true); // Because the pooled content paths are generated by a private method, // mocking the repository is more problematic than usual. The test // therefore relies on inside knowledge that there should be three // calls to deepGetOrCreateNode for each file: one for the pooled content // node, one for its members node, and one for the manager node. when(adminSession.getItem(Mockito.anyString())) .thenAnswer( new Answer<Item>() { public Item answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); String path = (String) args[0]; if (path.endsWith(POOLED_CONTENT_MEMBERS_NODE)) { return membersNode; } else if (path.endsWith("ieb")) { return memberNode; } else { return parentNode; } } }); when(parentNode.addNode(JCR_CONTENT, NT_RESOURCE)).thenReturn(resourceNode); when(adminSession.getValueFactory()).thenReturn(valueFactory); when(valueFactory.createBinary(Mockito.any(InputStream.class))).thenReturn(binary); // access control utils accessControlList = new AccessControlList() { // Add an "addEntry" method so AccessControlUtil can execute something. // This method doesn't do anything useful. @SuppressWarnings("unused") public boolean addEntry(Principal principal, Privilege[] privileges, boolean isAllow) throws AccessControlException { return true; } public void removeAccessControlEntry(AccessControlEntry ace) throws AccessControlException, RepositoryException {} public AccessControlEntry[] getAccessControlEntries() throws RepositoryException { return new AccessControlEntry[0]; } public boolean addAccessControlEntry(Principal principal, Privilege[] privileges) throws AccessControlException, RepositoryException { return false; } }; when(accessControlManager.privilegeFromName(Mockito.anyString())).thenReturn(allPrivilege); AccessControlPolicy[] acp = new AccessControlPolicy[] {accessControlList}; when(accessControlManager.getPolicies(Mockito.anyString())).thenReturn(acp); StringWriter stringWriter = new StringWriter(); when(response.getWriter()).thenReturn(new PrintWriter(stringWriter)); CreateContentPoolServlet cp = new CreateContentPoolServlet(); cp.eventAdmin = eventAdmin; cp.clusterTrackingService = clusterTrackingService; cp.sparseRepository = repository; cp.doPost(request, response); // Verify that we created all the nodes. JSONObject jsonObject = new JSONObject(stringWriter.toString()); Assert.assertNotNull(jsonObject.getString("testfilename.pdf")); Assert.assertNotNull(jsonObject.getString("index.html")); Assert.assertEquals(2, jsonObject.length()); }
@SuppressWarnings("unchecked") public void onMessage(Message message) { try { LOGGER.debug("Started handling email jms message."); String nodePath = message.getStringProperty(NODE_PATH_PROPERTY); String contentPath = message.getStringProperty(CONTENT_PATH_PROPERTY); Object objRcpt = message.getObjectProperty(RECIPIENTS); List<String> recipients = null; if (objRcpt instanceof List<?>) { recipients = (List<String>) objRcpt; } else if (objRcpt instanceof String) { recipients = new LinkedList<String>(); String[] rcpts = StringUtils.split((String) objRcpt, ','); for (String rcpt : rcpts) { recipients.add(rcpt); } } if (contentPath != null && contentPath.length() > 0) { javax.jcr.Session adminSession = repository.loginAdministrative(null); org.sakaiproject.nakamura.api.lite.Session sparseSession = StorageClientUtils.adaptToSession(adminSession); try { ContentManager contentManager = sparseSession.getContentManager(); Content messageContent = contentManager.get(contentPath); if (objRcpt != null) { // validate the message if (messageContent != null) { if (messageContent.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX) && (MessageConstants.BOX_OUTBOX.equals( messageContent.getProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX)) || MessageConstants.BOX_PENDING.equals( messageContent.getProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX)))) { if (messageContent.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) { // We're retrying this message, so clear the errors messageContent.setProperty( MessageConstants.PROP_SAKAI_MESSAGEERROR, (String) null); } if (messageContent.hasProperty(MessageConstants.PROP_SAKAI_TO) && messageContent.hasProperty(MessageConstants.PROP_SAKAI_FROM)) { // make a commons-email message from the message MultiPartEmail email = null; try { email = constructMessage(messageContent, recipients, adminSession, sparseSession); email.setSmtpPort(smtpPort); email.setHostName(smtpServer); email.send(); } catch (EmailException e) { String exMessage = e.getMessage(); Throwable cause = e.getCause(); setError(messageContent, exMessage); LOGGER.warn("Unable to send email: " + exMessage); // Get the SMTP error code // There has to be a better way to do this boolean rescheduled = false; if (cause != null && cause.getMessage() != null) { String smtpError = cause.getMessage().trim(); try { int errorCode = Integer.parseInt(smtpError.substring(0, 3)); // All retry-able SMTP errors should have codes starting // with 4 scheduleRetry(errorCode, messageContent); rescheduled = true; } catch (NumberFormatException nfe) { // smtpError didn't start with an error code, let's dig for // it String searchFor = "response:"; int rindex = smtpError.indexOf(searchFor); if (rindex > -1 && (rindex + searchFor.length()) < smtpError.length()) { int errorCode = Integer.parseInt( smtpError.substring(searchFor.length(), searchFor.length() + 3)); scheduleRetry(errorCode, messageContent); rescheduled = true; } } } if (rescheduled) { LOGGER.info("Email {} rescheduled for redelivery. ", nodePath); } else { LOGGER.error("Unable to reschedule email for delivery: " + e.getMessage(), e); } } } else { setError(messageContent, "Message must have a to and from set"); } } else { setError(messageContent, "Not an outbox"); } if (!messageContent.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) { messageContent.setProperty( MessageConstants.PROP_SAKAI_MESSAGEBOX, MessageConstants.BOX_SENT); } } } else { String retval = "null"; setError( messageContent, "Expected recipients to be String or List<String>. Found " + retval); } } finally { if (adminSession != null) { adminSession.logout(); } } } } catch (PathNotFoundException e) { LOGGER.error(e.getMessage(), e); } catch (RepositoryException e) { LOGGER.error(e.getMessage(), e); } catch (JMSException e) { LOGGER.error(e.getMessage(), e); } catch (EmailDeliveryException e) { LOGGER.error(e.getMessage()); } catch (ClientPoolException e) { LOGGER.error(e.getMessage(), e); } catch (StorageClientException e) { LOGGER.error(e.getMessage(), e); } catch (AccessDeniedException e) { LOGGER.error(e.getMessage(), e); } }
public String getRepositoryName() { return repository.getDescriptor(Repository.REP_NAME_DESC); }
private Resource resolveMappedResource(ResourceResolver resourceResolver, String path) throws RepositoryException { String poolId = null; if (path.startsWith("/p/")) { poolId = path.substring("/p/".length()); } else if (path.length() == 2) { try { poolId = generatePoolId(); // we also need to create the node. Session adminSession = null; Session userSession = resourceResolver.adaptTo(Session.class); try { adminSession = slingRepository.loginAdministrative(null); String userId = userSession.getUserID(); PrincipalManager principalManager = AccessControlUtil.getPrincipalManager(userSession); Principal userPrincipal = principalManager.getPrincipal(userId); Node node = JcrUtils.deepGetOrCreateNode(adminSession, hash(poolId)); // make the node inherit the repository defaults for content, but admin for the user. String nodePath = node.getPath(); AccessControlUtil.replaceAccessControlEntry( adminSession, nodePath, userPrincipal, new String[] {JCR_ALL}, null, null, null); // set some properties to make it possible to locate this pool file without having to use // the path. node.setProperty("sakai:pool-file", "1"); node.setProperty("sakai:pool-file-owner", userId); // save so the resolver further down will find this file. if (adminSession.hasPendingChanges()) { adminSession.save(); } } finally { adminSession.logout(); } } catch (Exception e) { throw new RepositoryException("Unable to generate new pool ID " + e.getMessage(), e); } } if (poolId != null && poolId.length() > 0) { int i = poolId.indexOf('/'); if (i > 0) { poolId = poolId.substring(0, i); } i = poolId.indexOf('.'); String selectors = ""; if (i > 0) { selectors = poolId.substring(i); poolId = poolId.substring(0, i); } if (LOGGER.isInfoEnabled()) { LOGGER.info("Pool ID is [{}]", poolId); } String poolPath = null; try { poolPath = hash(poolId) + selectors; } catch (Exception e) { throw new RepositoryException("Unable to hash pool ID " + e.getMessage(), e); } Resource r = resourceResolver.resolve(poolPath); if (r instanceof NonExistingResource) { LOGGER.info("Pool ID does not exist, reject and dont allow creation on POST {} ", poolPath); throw new SlingException( "Resources may not be created at /p by the user", new AccessDeniedException("Cant create user specified pool resoruce")); } LOGGER.info("Resolving [{}] to [{}] ", poolPath, r); if (r != null) { // are the last elements the same ? if (getLastElement(r.getPath()).equals("/" + poolId)) { r.getResourceMetadata().put(CONTENT_RESOURCE_PROVIDER, this); return r; } else { if (LOGGER.isInfoEnabled()) { LOGGER.info("Rejected [{}] != [{}] ", getLastElement(r.getPath()), "/" + poolId); } } } } return null; }