public boolean accepts(SlingHttpServletRequest request) { log.debug("accepts(" + request.getRequestPathInfo().getResourcePath() + ")"); if (request.getRequestPathInfo().getResourcePath().startsWith("/gather/sample")) { return true; } return false; }
/** * True if our request wants the "tidy" pretty-printed format Copied from * org.apache.sling.servlets.get.impl.helpers.JsonRendererServlet */ protected boolean isTidy(SlingHttpServletRequest req) { for (String selector : req.getRequestPathInfo().getSelectors()) { if (TIDY.equals(selector)) { return true; } } return false; }
/** * Let other servlets take care of requests for JSON. * * @see * org.apache.sling.api.servlets.OptingServlet#accepts(org.apache.sling.api.SlingHttpServletRequest) */ public boolean accepts(SlingHttpServletRequest request) { String extension = request.getRequestPathInfo().getExtension(); if (extension == null || extension.length() == 0) { return true; } else { return false; } }
@Override public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException { final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request; logger.debug( "request for {}, with selector {}", slingRequest.getRequestPathInfo().getResourcePath(), slingRequest.getRequestPathInfo().getSelectorString()); filterChain.doFilter(request, response); }
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { if ("json".equals(request.getRequestPathInfo().getExtension())) { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.setHeader("Cache-Control", "no-cache"); CampaignsJSONWriter w = new CampaignsJSONWriter(request); w.write(response.getWriter()); } }
public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { if (!authenticate(request, response)) { return; } final String msgId = StringUtils.removeStart(request.getRequestPathInfo().getSuffix(), "/"); if (StringUtils.isBlank(msgId)) { throw new ServletException("No suffix found"); } if (!sentMessages.contains(msgId)) { throw new ServletException("No one is waiting for confirmation for " + msgId); } else { receivedConfirmations.add(msgId); synchronized (receivedConfirmations) { receivedConfirmations.notifyAll(); } response.getWriter().append("Message " + msgId + " confirmed"); LOG.debug("Message " + msgId + " confirmed"); } }
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { if ("json".equals(request.getRequestPathInfo().getExtension())) { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.setHeader("Cache-Control", "no-cache"); // String path = request.getRequestPathInfo().getResourcePath(); String path = request.getParameter(PATH_PARAM); log.debug("Providing experiences for {} .", path); String filterParam = request.getParameter("filter"); log.debug("Filter param: '{}'", filterParam); ExperiencesJSONWriter w = new ExperiencesJSONWriter(request, response); w.setMCMFacade(mcmFacade); try { MapFilter filter = new MapFilter(); int filterCount = filter.ingestJson(filterParam); if (filterCount > 0) { w.setMapFilter(filter); } } catch (JSONException e) { log.error("Cannot parse filter params.", e); } ExtJsSortListOfMapsComparator comparator = new ExtJsSortListOfMapsComparator(); comparator.init(request); if (comparator.isInitialized()) { log.info("Sorting with: {}", comparator); w.setExperienceComparator(comparator); } w.write(response.getWriter(), path); } }
/** {@inheritDoc} */ @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { if ("json".equals(request.getRequestPathInfo().getExtension())) { response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); String path = request.getParameter(PATH_PARAM); int numChildrenCheck = 20; if (request.getParameter(NUM_CHILDREN_CHECK) != null) { try { numChildrenCheck = Integer.parseInt(request.getParameter(NUM_CHILDREN_CHECK)); } catch (NumberFormatException e) { // ignore and use default } } SiteAdminTreeJSONWriter w = new SiteAdminTreeJSONWriter(request.getResourceResolver(), numChildrenCheck); w.write(response.getWriter(), path); } }
/** * Writes a proper UGC response to the response. This handles both HTML and REST style responses. * * @param request the current request * @param response the response to write to * @param resource the resource to serialize * @param location a different location to send to the client. * @return if it can write to UGC * @throws IOException IO Error * @throws ServletException Servlet Error */ protected boolean writeUGCResponse( final SlingHttpServletRequest request, final SlingHttpServletResponse response, final Resource resource, final String location) throws ServletException, IOException { final String extension = request.getRequestPathInfo().getExtension(); boolean ugcResponseWritten = false; if (StringUtils.equalsIgnoreCase(extension, "html")) { response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html"); response.setCharacterEncoding("utf-8"); final SlingHttpServletRequest includeRequest = new TemplateHandlingRequest(request); final String templateRequested = request.getParameter(TEMPLATE_FORM_ID); final RequestDispatcherOptions options = new RequestDispatcherOptions(); if (null != templateRequested) { options.setReplaceSelectors(templateRequested); final Resource newResource = request.getResourceResolver().getResource(resource.getPath()); includeRequest.getRequestDispatcher(newResource, options).include(includeRequest, response); response.setStatus(HttpServletResponse.SC_CREATED); final String locationURL = (null != location) ? location : resource.getPath(); if (!isCORS(request)) { response.setHeader(HttpHeaders.LOCATION, locationURL); } else { // response.setHeader(HttpHeaders.LOCATION, // externalizer.externalLink(request.getResourceResolver(), // (wcmMode == WCMMode.DISABLED) ? Externalizer.PUBLISH : Externalizer.AUTHOR, // locationURL)); response.setHeader( HttpHeaders.LOCATION, externalizer.absoluteLink(request, request.getScheme(), locationURL)); } ugcResponseWritten = true; } } return ugcResponseWritten; }
@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") @Test public void test() throws ServletException, IOException, UnsupportedRepositoryOperationException, RepositoryException { SlingHttpServletRequest request = createNiceMock(SlingHttpServletRequest.class); SlingHttpServletResponse response = createNiceMock(SlingHttpServletResponse.class); RequestPathInfo requestPathInfo = createNiceMock(RequestPathInfo.class); Resource resource = createNiceMock(Resource.class); Node node = createNiceMock(Node.class); VersionHistory versionHistory = createNiceMock(VersionHistory.class); Version version = createNiceMock(Version.class); Node frozenNode = createNiceMock(Node.class); Property resourceTypeProperty = createNiceMock(Property.class); Capture<Resource> capturedResource = new Capture<Resource>(); RequestDispatcher requestDispatcher = createNiceMock(RequestDispatcher.class); Capture<ServletRequest> capturedRequest = new Capture<ServletRequest>(); Capture<ServletResponse> capturedResponse = new Capture<ServletResponse>(); VersionManager versionManager = createNiceMock(VersionManager.class); Session session = createNiceMock(Session.class); Workspace workspace = createNiceMock(Workspace.class); EasyMock.expect(request.getRequestPathInfo()).andReturn(requestPathInfo); EasyMock.expect(requestPathInfo.getSelectorString()).andReturn("version.,1.1,.tidy.json"); EasyMock.expect(request.getResource()).andReturn(resource); EasyMock.expect(resource.adaptTo(Node.class)).andReturn(node); EasyMock.expect(node.getPath()).andReturn("/foo"); EasyMock.expect(node.getSession()).andReturn(session); EasyMock.expect(session.getWorkspace()).andReturn(workspace); EasyMock.expect(workspace.getVersionManager()).andReturn(versionManager); EasyMock.expect(versionManager.getVersionHistory("/foo")).andReturn(versionHistory); EasyMock.expect(versionHistory.getVersion("1.1")).andReturn(version); EasyMock.expect(version.getNode(JcrConstants.JCR_FROZENNODE)).andReturn(frozenNode); EasyMock.expect(frozenNode.getPath()).andReturn("/testnode"); EasyMock.expect(frozenNode.hasProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY)) .andReturn(true); EasyMock.expect(frozenNode.getProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY)) .andReturn(resourceTypeProperty); EasyMock.expect(resourceTypeProperty.getString()).andReturn("sakai/testing"); EasyMock.expect(frozenNode.hasProperty(JcrResourceConstants.SLING_RESOURCE_SUPER_TYPE_PROPERTY)) .andReturn(true); EasyMock.expect(frozenNode.getProperty(JcrResourceConstants.SLING_RESOURCE_SUPER_TYPE_PROPERTY)) .andReturn(resourceTypeProperty); EasyMock.expect(resourceTypeProperty.getString()).andReturn("sakai/super-type-testing"); EasyMock.expect(request.getRequestDispatcher(EasyMock.capture(capturedResource))) .andReturn(requestDispatcher); requestDispatcher.forward( EasyMock.capture(capturedRequest), EasyMock.capture(capturedResponse)); EasyMock.expectLastCall(); replay(); getVersionServlet.doGet(request, response); Assert.assertTrue(capturedRequest.hasCaptured()); Assert.assertTrue(capturedResource.hasCaptured()); Assert.assertTrue(capturedResponse.hasCaptured()); Resource cresource = capturedResource.getValue(); Node capturedNode = cresource.adaptTo(Node.class); Assert.assertEquals(capturedNode, frozenNode); Map<String, String> map = cresource.adaptTo(Map.class); Assert.assertNotNull(map); verify(); }
/** * {@inheritDoc} * * @see * org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.api.SlingHttpServletRequest, * org.apache.sling.api.SlingHttpServletResponse) */ @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { Authorizable authorizable = null; Resource resource = request.getResource(); if (resource != null) { authorizable = resource.adaptTo(Authorizable.class); } if (authorizable == null || !authorizable.isGroup()) { response.sendError(HttpServletResponse.SC_NO_CONTENT, "Couldn't find group"); return; } Group group = (Group) authorizable; List<String> selectors = Arrays.asList(request.getRequestPathInfo().getSelectors()); ExtendedJSONWriter writer = new ExtendedJSONWriter(response.getWriter()); writer.setTidy(selectors.contains("tidy")); // Get the sorting order, default is ascending or the natural sorting order (which is // null for a TreeMap.) Comparator<String> comparator = null; String order = "ascending"; if (request.getRequestParameter("sortOrder") != null) { order = request.getRequestParameter("sortOrder").getString(); if (order.equals("descending")) { comparator = Collections.reverseOrder(); } } try { response.setContentType("application/json"); TreeMap<String, Authorizable> map = null; if (selectors.contains("managers")) { map = getManagers(request, group, comparator); } else { // Members is the default. map = getMembers(request, group, comparator); } // Do some paging. long items = (request.getParameter(ITEMS) != null) ? Long.parseLong(request.getParameter(ITEMS)) : 25; long page = (request.getParameter(PAGE) != null) ? Long.parseLong(request.getParameter(PAGE)) : 0; if (page < 0) { page = 0; } if (items < 0) { items = 25; } Iterator<Entry<String, Authorizable>> iterator = getInPlaceIterator(request, map, items, page); // Write the whole lot out. Session session = request.getResourceResolver().adaptTo(Session.class); writer.array(); int i = 0; while (iterator.hasNext() && i < items) { Entry<String, Authorizable> entry = iterator.next(); Authorizable au = entry.getValue(); ValueMap profile; if (selectors.contains("detailed")) { profile = profileService.getProfileMap(au, session); } else { profile = profileService.getCompactProfileMap(au, session); } if (profile != null) { writer.valueMap(profile); i++; } else { // profile wasn't found. safe to ignore and not include the group logger.info("Profile not found for " + au.getID()); } } writer.endArray(); } catch (RepositoryException e) { response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve members/managers."); return; } catch (JSONException e) { response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to build a proper JSON output."); return; } }
/** * Retrieves the list of members. * * <p>{@inheritDoc} * * @see * org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.api.SlingHttpServletRequest, * org.apache.sling.api.SlingHttpServletResponse) */ @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { try { // Get hold of the actual file. Resource resource = request.getResource(); javax.jcr.Session jcrSession = request.getResourceResolver().adaptTo(javax.jcr.Session.class); Session session = resource.adaptTo(Session.class); AuthorizableManager am = session.getAuthorizableManager(); AccessControlManager acm = session.getAccessControlManager(); Content node = resource.adaptTo(Content.class); Authorizable thisUser = am.findAuthorizable(session.getUserId()); if (!acm.can(thisUser, Security.ZONE_CONTENT, resource.getPath(), Permissions.CAN_READ)) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Map<String, Object> properties = node.getProperties(); String[] managers = (String[]) properties.get(POOLED_CONTENT_USER_MANAGER); String[] editors = (String[]) properties.get(POOLED_CONTENT_USER_EDITOR); String[] viewers = (String[]) properties.get(POOLED_CONTENT_USER_VIEWER); boolean detailed = false; boolean tidy = false; for (String selector : request.getRequestPathInfo().getSelectors()) { if ("detailed".equals(selector)) { detailed = true; } else if ("tidy".equals(selector)) { tidy = true; } } // Loop over the sets and output it. ExtendedJSONWriter writer = new ExtendedJSONWriter(response.getWriter()); writer.setTidy(tidy); writer.object(); writer.key("managers"); writer.array(); for (String manager : StorageClientUtils.nonNullStringArray(managers)) { try { writeProfileMap(jcrSession, am, writer, manager, detailed); } catch (AccessDeniedException e) { LOGGER.debug("Skipping private manager [{}]", manager); } } writer.endArray(); writer.key("editors"); writer.array(); for (String editor : StorageClientUtils.nonNullStringArray(editors)) { try { writeProfileMap(jcrSession, am, writer, editor, detailed); } catch (AccessDeniedException e) { LOGGER.debug("Skipping private editor [{}]", editor); } } writer.endArray(); writer.key("viewers"); writer.array(); for (String viewer : StorageClientUtils.nonNullStringArray(viewers)) { try { writeProfileMap(jcrSession, am, writer, viewer, detailed); } catch (AccessDeniedException e) { LOGGER.debug("Skipping private viewer [{}]", viewer); } } writer.endArray(); writer.endObject(); } catch (JSONException e) { response.sendError(SC_INTERNAL_SERVER_ERROR, "Failed to generate proper JSON."); LOGGER.error(e.getMessage(), e); } catch (StorageClientException e) { response.sendError(SC_INTERNAL_SERVER_ERROR, "Failed to generate proper JSON."); LOGGER.error(e.getMessage(), e); } catch (AccessDeniedException e) { response.sendError(SC_INTERNAL_SERVER_ERROR, "Failed to generate proper JSON."); LOGGER.error(e.getMessage(), e); } catch (RepositoryException e) { response.sendError(SC_INTERNAL_SERVER_ERROR, "Failed to generate proper JSON."); LOGGER.error(e.getMessage(), e); } }