@Override protected void writeLayer( SlingHttpServletRequest req, SlingHttpServletResponse resp, ImageContext c, Layer layer) throws IOException, RepositoryException { Image image = new Image(c.resource); if (!image.hasContent()) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // get style and set constraints image.loadStyleData(c.style); // get pure layer layer = image.getLayer(false, false, false); boolean modified = false; if (layer != null) { // crop modified = image.crop(layer) != null; // rotate modified |= image.rotate(layer) != null; // resize modified |= image.resize(layer) != null; // apply diff if needed (because we create the layer inline) modified |= applyDiff(layer, c); } // don't cache images on authoring instances // Cache-Control: no-cache allows caching (e.g. in the browser cache) but // will force revalidation using If-Modified-Since or If-None-Match every time, // avoiding aggressive browser caching if (!WCMMode.DISABLED.equals(WCMMode.fromRequest(req))) { resp.setHeader("Cache-Control", "no-cache"); } if (modified) { String mimeType = image.getMimeType(); if (ImageHelper.getExtensionFromType(mimeType) == null) { // get default mime type mimeType = "image/png"; } resp.setContentType(mimeType); layer.write(mimeType, mimeType.equals("image/gif") ? 255 : 1.0, resp.getOutputStream()); } else { // do not re-encode layer, just spool Property data = image.getData(); InputStream in = data.getStream(); resp.setContentLength((int) data.getLength()); resp.setContentType(image.getMimeType()); IOUtils.copy(in, resp.getOutputStream()); in.close(); } resp.flushBuffer(); }
@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()); } }
/** {@inheritDoc} */ public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { try { Resource resource = request.getResource(); Node node = resource.adaptTo(Node.class); if (node == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Version version = versionService.saveNode(node, request.getRemoteUser()); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); ExtendedJSONWriter write = new ExtendedJSONWriter(response.getWriter()); write.object(); write.key("versionName"); write.value(version.getName()); ExtendedJSONWriter.writeNodeContentsToWriter(write, version); write.endObject(); } catch (RepositoryException e) { LOGGER.info("Failed to save version ", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } catch (JSONException e) { LOGGER.info("Failed to save version ", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } }
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { Resource resource = request.getResource(); Node node = resource.adaptTo(Node.class); Content content = resource.adaptTo(Content.class); if (node != null) { try { Session jcrSession = request.getResourceResolver().adaptTo(Session.class); JSONWriter write = new JSONWriter(response.getWriter()); FileUtils.writeLinkNode(node, jcrSession, write); } catch (JSONException e) { response.sendError(500, "Unable to parse JSON."); } catch (RepositoryException e) { LOGGER.warn("Unable to get file info for link."); response.sendError(500, "Unable get file info."); } } else { try { org.sakaiproject.nakamura.api.lite.Session session = resource.adaptTo(org.sakaiproject.nakamura.api.lite.Session.class); JSONWriter write = new JSONWriter(response.getWriter()); FileUtils.writeLinkNode(content, session, write); } catch (StorageClientException e) { LOGGER.warn("Unable to get file info for link."); response.sendError(500, "Unable get file info."); } catch (JSONException e) { response.sendError(500, "Unable to parse JSON."); } } }
private boolean authenticate(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { final String userId = request.getResourceResolver().getUserID(); if (!isPublish()) { response.sendError(404); return false; } else if (!"admin".equals(userId)) { response.sendError(403); return false; } else { return true; } }
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { // get current user String user = request.getRemoteUser(); if (user == null) { response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "User must be logged in to check their status"); } LOGGER.info("GET to PresenceContactsServlet (" + user + ")"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); try { Writer writer = response.getWriter(); ExtendedJSONWriter output = new ExtendedJSONWriter(writer); // start JSON object output.object(); PresenceUtils.makePresenceJSON(output, user, presenceService, true); // add in the list of contacts info Session session = request.getResourceResolver().adaptTo(Session.class); List<String> userIds = connectionManager.getConnectedUsers(user, ConnectionState.ACCEPTED); output.key("contacts"); output.array(); for (String userId : userIds) { output.object(); // put in the basics PresenceUtils.makePresenceJSON(output, userId, presenceService, true); // add in the profile output.key("profile"); Authorizable au = PersonalUtils.getAuthorizable(session, userId); Node profileNode = (Node) session.getItem(PersonalUtils.getProfilePath(au)); ExtendedJSONWriter.writeNodeToWriter(output, profileNode); output.endObject(); } output.endArray(); // finish it output.endObject(); } catch (JSONException e) { LOGGER.error(e.getMessage(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (RepositoryException e) { LOGGER.error(e.getMessage(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } return; }
/** * Takes the original request and starts the batching. * * @param request * @param response * @throws IOException */ protected void batchRequest( SlingHttpServletRequest request, SlingHttpServletResponse response, boolean allowModify) throws IOException { // Grab the JSON block out of it and convert it to RequestData objects we can use. String json = request.getParameter(REQUESTS_PARAMETER); List<RequestInfo> batchedRequests = new ArrayList<RequestInfo>(); try { JSONArray arr = new JSONArray(json); for (int i = 0; i < arr.length(); i++) { JSONObject obj = arr.getJSONObject(i); RequestInfo r = new RequestInfo(obj); if (allowModify || r.isSafe()) { batchedRequests.add(r); } } } catch (JSONException e) { response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Failed to parse the " + REQUESTS_PARAMETER + " parameter"); LOGGER.warn("Failed to parse the " + REQUESTS_PARAMETER + " parameter"); return; } // Loop over the requests and handle each one. try { StringWriter sw = new StringWriter(); JSONWriter write = new JSONWriter(sw); write.object(); write.key("results"); write.array(); for (RequestInfo r : batchedRequests) { doRequest(request, response, r, write); } write.endArray(); write.endObject(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(sw.getBuffer().toString()); } catch (JSONException e) { LOGGER.warn("Failed to create a JSON response"); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to write JSON response"); } }
@Test public void testAnon() throws IOException, ServletException { SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class); SlingHttpServletResponse response = createMock(SlingHttpServletResponse.class); expect(request.getRemoteUser()).andReturn("anonymous"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Anonymous user cannot crop images."); replay(); servlet.doPost(request, response); }
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { DefaultServletDelegate delegate = (DefaultServletDelegate) request.getAttribute(DefaultServletSwitch.class.getName()); if (delegate != null) { delegate.doDelegateGet(request, response); } else { response.sendError(404); } }
private void setupRedirect(String target) throws JspException { Page currentPage = getContextAttribute("currentPage"); SlingHttpServletResponse response = getContextAttribute("slingResponse"); // The target must be checked here - if an empty target then you send the error, not just if // the target equals the current page (which you check to ensure you don't get any infinite // loops. if (StringUtils.isNotEmpty(target) && !target.equals(currentPage.getPath())) { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); // response.setHeader( "Location", UtilityFunctions.createValidLink( target, "" ) // ); response.setHeader("Connection", "close"); } else if (sendError) { try { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (IOException e) { throw new JspException(e); } } }
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { Resource resource = request.getResource(); Node node = resource.adaptTo(Node.class); Content content = resource.adaptTo(Content.class); System.err.println("Node is " + node + " content is " + content); String link = null; try { if (node != null && node.hasProperty(FilesConstants.SAKAI_LINK)) { link = node.getProperty(FilesConstants.SAKAI_LINK).getString(); } else if (content != null && content.hasProperty(FilesConstants.SAKAI_LINK)) { link = (String) content.getProperty(FilesConstants.SAKAI_LINK); } System.err.println("Link is " + link); if (link != null) { String[] linkProps = StringUtils.split(link, ':'); LinkHandler handler = null; String path = null; if (linkProps.length == 2) { handler = fileHandlerTracker.getProcessorByName(linkProps[0]); path = linkProps[1]; } else { if (node != null) { handler = new JcrInternalFileHandler(); } else { handler = new SparseContentInternalFileHandler(); } path = link; } if (handler != null) { handler.handleFile(request, response, path); } } } catch (RepositoryException e) { LOGGER.warn(e.getMessage(), e); response.sendError(500, "Unable to handle linked file."); } }
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { String resourceType = request.getResource().getResourceType(); Resource resource = null; if (UserConstants.GROUP_HOME_RESOURCE_TYPE.equals(resourceType)) { resource = request.getResourceResolver().getResource(groupHome); } else if (UserConstants.USER_HOME_RESOURCE_TYPE.equals(resourceType)) { resource = request.getResourceResolver().getResource(userHome); } if (resource == null) { response.sendError( 500, "Somehow didn't get a user or group home resource [" + resourceType + "]"); } else { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.setStatus(HttpServletResponse.SC_OK); IOUtils.stream(resource.adaptTo(InputStream.class), response.getOutputStream()); } }
@Test public void testMissingParameters() throws IOException, ServletException { SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class); SlingHttpServletResponse response = createMock(SlingHttpServletResponse.class); expect(request.getRequestParameter("img")).andReturn(null); expect(request.getRemoteUser()).andReturn("johndoe"); addStringRequestParameter(request, "save", null); addStringRequestParameter(request, "x", null); addStringRequestParameter(request, "y", null); addStringRequestParameter(request, "width", null); addStringRequestParameter(request, "height", null); addStringRequestParameter(request, "dimensions", ""); response.sendError( HttpServletResponse.SC_BAD_REQUEST, "The following parameters are required: img, save, x, y, width, height, dimensions"); replay(); servlet.doPost(request, response); }
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { Resource resource = request.getResource(); Node node = (Node) resource.adaptTo(Node.class); String filename = null; try { if (node.hasNode(JcrConstants.JCR_CONTENT)) { Node content = node.getNode(JcrConstants.JCR_CONTENT); response.setHeader( "Content-Type", content.getProperty(JcrConstants.JCR_MIMETYPE).getString()); response.setHeader( "Content-Length", "" + content.getProperty(JcrConstants.JCR_DATA).getLength()); } if (node.hasProperty(FilesConstants.SAKAI_FILENAME)) { filename = node.getProperty(FilesConstants.SAKAI_FILENAME).getString(); } // If we provided a filename and we haven't changed the name in a previous request. if (filename != null && !response.containsHeader("Content-Disposition")) { response.setHeader("Content-Disposition", "filename=\"" + filename + "\""); } response.setStatus(HttpServletResponse.SC_OK); InputStream in = (InputStream) request.getResource().adaptTo(InputStream.class); OutputStream out = response.getOutputStream(); IOUtils.stream(in, out); } catch (RepositoryException e) { logger.warn("Unable to download file due to repositoryexception!"); e.printStackTrace(); response.sendError(500); } }
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { String path = request.getResource().getPath(); // check path is a valid DAM root folder path for asset service if (!damPathHandler.isAllowedDataVersionPath(path)) { log.debug("Path not allowed to get data version {}", path); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // return data version as JSON try { JSONObject jsonResponse = new JSONObject(); jsonResponse.put("dataVersion", damPathHandler.getDataVersion()); response.setContentType(ContentType.JSON); response.setCharacterEncoding(CharEncoding.UTF_8); response.getWriter().write(jsonResponse.toString()); } catch (JSONException ex) { throw new ServletException("Unable to generate JSON.", ex); } }
/** * {@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 { List<Content> contentList = null; RequestParameter rp = request.getRequestParameter("path"); ResourceResolver resourceResolver = request.getResourceResolver(); if (rp != null) { String contentPath = rp.getString("UTF-8"); if (contentPath.startsWith("/_groupa:")) { contentPath = contentPath.replaceFirst("/_groupa:", "/~"); } if (contentPath.endsWith("/")) { contentPath = contentPath.substring(0, contentPath.length() - 1); } Resource pagesResource = resourceResolver.getResource(contentPath); if (pagesResource != null) { contentList = getPageTree(pagesResource.adaptTo(Content.class)); ; } } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter w = response.getWriter(); ExtendedJSONWriter writer = new ExtendedJSONWriter(w); writer.object(); // pages info int messageCount = 0; writer.key("items"); writer.value(255); writer.key("results"); writer.array(); if (contentList != null) { for (int i = 0; i < contentList.size(); i++) { Content page = contentList.get(i); writer.object(); writer.key("jcr:path"); writer.value( page.getPath() .replaceFirst( LitePersonalUtils.PATH_AUTHORIZABLE, LitePersonalUtils.PATH_RESOURCE_AUTHORIZABLE)); for (String messagePropKey : page.getProperties().keySet()) { writer.key(messagePropKey); writer.value(massageValue(messagePropKey, page.getProperty(messagePropKey))); } writer.endObject(); messageCount++; } } writer.endArray(); writer.key("total"); writer.value(messageCount); writer.endObject(); } catch (JSONException e) { LOG.error("Failed to create proper JSON response in /var/search/page", e); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create proper JSON response."); } }
/** * Manipulate the member list for this file. * * <p>{@inheritDoc} * * @see * org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest, * org.apache.sling.api.SlingHttpServletResponse) */ @SuppressWarnings("unchecked") @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { // fail if anonymous String remoteUser = request.getRemoteUser(); if (User.ANON_USER.equals(remoteUser)) { response.sendError(SC_FORBIDDEN, "Anonymous users cannot update content members."); return; } Session session = null; boolean releaseSession = false; try { Resource resource = request.getResource(); session = resource.adaptTo(Session.class); Content pooledContent = resource.adaptTo(Content.class); AccessControlManager accessControlManager = session.getAccessControlManager(); AuthorizableManager authorizableManager = session.getAuthorizableManager(); User thisUser = authorizableManager.getUser(); if (!accessControlManager.can( thisUser, Security.ZONE_CONTENT, pooledContent.getPath(), Permissions.CAN_READ)) { response.sendError(SC_FORBIDDEN, "Insufficient permission to read this content."); } Map<String, Object> properties = pooledContent.getProperties(); String[] managers = StorageClientUtils.nonNullStringArray( (String[]) properties.get(POOLED_CONTENT_USER_MANAGER)); String[] editors = StorageClientUtils.nonNullStringArray( (String[]) properties.get(POOLED_CONTENT_USER_EDITOR)); String[] viewers = StorageClientUtils.nonNullStringArray( (String[]) properties.get(POOLED_CONTENT_USER_VIEWER)); Set<String> managerSet = Sets.newHashSet(managers); Set<String> editorSet = Sets.newHashSet(editors); Set<String> viewerSet = Sets.newHashSet(viewers); List<String> removeViewers = Arrays.asList( StorageClientUtils.nonNullStringArray(request.getParameterValues(":viewer@Delete"))); List<String> removeManagers = Arrays.asList( StorageClientUtils.nonNullStringArray(request.getParameterValues(":manager@Delete"))); List<String> removeEditors = Arrays.asList( StorageClientUtils.nonNullStringArray(request.getParameterValues(":editor@Delete"))); List<String> addViewers = Arrays.asList( StorageClientUtils.nonNullStringArray(request.getParameterValues(":viewer"))); List<String> addManagers = Arrays.asList( StorageClientUtils.nonNullStringArray(request.getParameterValues(":manager"))); List<String> addEditors = Arrays.asList( StorageClientUtils.nonNullStringArray(request.getParameterValues(":editor"))); if (!accessControlManager.can( thisUser, Security.ZONE_CONTENT, pooledContent.getPath(), Permissions.CAN_WRITE)) { if (!addManagers.isEmpty()) { response.sendError(SC_FORBIDDEN, "Non-managers may not add managers to content."); return; } for (String name : removeManagers) { // asking to remove managers who don't exist is harmless if (managerSet.contains(name)) { response.sendError(SC_FORBIDDEN, "Non-managers may not remove managers from content."); return; } } if (addViewers.contains(User.ANON_USER) || addViewers.contains(Group.EVERYONE)) { response.sendError( SC_FORBIDDEN, "Non-managers may not add 'anonymous' or 'everyone' as viewers."); return; } if (addEditors.contains(User.ANON_USER) || addEditors.contains(Group.EVERYONE)) { response.sendError( SC_FORBIDDEN, "Non-managers may not add 'anonymous' or 'everyone' as editors."); return; } for (String name : removeViewers) { if (!thisUser.getId().equals(name)) { Authorizable viewer = authorizableManager.findAuthorizable(name); if (viewer != null && !accessControlManager.can( thisUser, Security.ZONE_AUTHORIZABLES, name, Permissions.CAN_WRITE)) { response.sendError( SC_FORBIDDEN, "Non-managers may not remove any viewer other than themselves or a group which they manage."); } } } // the request has passed all the rules that govern non-manager users // so we'll grant an administrative session session = session.getRepository().loginAdministrative(); releaseSession = true; } List<AclModification> aclModifications = Lists.newArrayList(); for (String addManager : addManagers) { if ((addManager.length() > 0) && !managerSet.contains(addManager)) { managerSet.add(addManager); AclModification.addAcl(true, Permissions.CAN_MANAGE, addManager, aclModifications); } } for (String removeManager : removeManagers) { if ((removeManager.length() > 0) && managerSet.contains(removeManager)) { managerSet.remove(removeManager); AclModification.removeAcl(true, Permissions.CAN_MANAGE, removeManager, aclModifications); } } for (String addEditor : addEditors) { if ((addEditor.length() > 0) && !editorSet.contains(addEditor)) { editorSet.add(addEditor); AclModification.addAcl(true, PERMISSION_EDITOR, addEditor, aclModifications); } } for (String removeEditor : removeEditors) { if ((removeEditor.length() > 0) && editorSet.contains(removeEditor)) { editorSet.remove(removeEditor); AclModification.removeAcl(true, PERMISSION_EDITOR, removeEditor, aclModifications); } } for (String addViewer : addViewers) { if ((addViewer.length() > 0) && !viewerSet.contains(addViewer)) { viewerSet.add(addViewer); AclModification.addAcl(true, Permissions.CAN_READ, addViewer, aclModifications); } } for (String removeViewer : removeViewers) { removeViewer = removeViewer.trim(); if ((removeViewer.length() > 0) && viewerSet.contains(removeViewer)) { viewerSet.remove(removeViewer); if (!managerSet.contains(removeViewer)) { AclModification.removeAcl(true, Permissions.CAN_READ, removeViewer, aclModifications); } } } updateContentMembers(session, pooledContent, viewerSet, managerSet, editorSet); updateContentAccess(session, pooledContent, aclModifications); this.authorizableCountChanger.notify( UserConstants.CONTENT_ITEMS_PROP, addViewers, addEditors, addManagers, removeViewers, removeEditors, removeManagers); response.setStatus(SC_OK); } catch (StorageClientException e) { LOGGER.error(e.getMessage()); response.sendError( SC_INTERNAL_SERVER_ERROR, "StorageClientException: " + e.getLocalizedMessage()); } catch (AccessDeniedException e) { response.sendError( SC_FORBIDDEN, "Insufficient permission to update content members at " + request.getRequestURI()); } finally { if (session != null && releaseSession) { try { session.logout(); } catch (ClientPoolException e) { LOGGER.error(e.getMessage()); } } } }
protected void dispatch( SlingHttpServletRequest request, SlingHttpServletResponse response, boolean userInputStream) throws ServletException, IOException { try { Resource resource = request.getResource(); if (!resource.getPath().startsWith(PROXY_PATH_PREFIX)) { response.sendError( HttpServletResponse.SC_FORBIDDEN, "Proxying templates may only be stored in " + PROXY_PATH_PREFIX); return; } Node node = resource.adaptTo(Node.class); if (!userInputStream) { Value[] v = JcrUtils.getValues(node, SAKAI_REQUEST_STREAM_BODY); if (v != null && v.length > 0) { userInputStream = Boolean.parseBoolean(v[0].getString()); } } Map<String, String> headers = new ConcurrentHashMap<String, String>(); for (Enumeration<?> enames = request.getHeaderNames(); enames.hasMoreElements(); ) { String name = (String) enames.nextElement(); if (!headerBacklist.contains(name)) { headers.put(name, request.getHeader(name)); } } // search for special headers. if (headers.containsKey(BASIC_USER)) { String user = headers.get(BASIC_USER); String password = headers.get(BASIC_PASSWORD); Base64 base64 = new Base64(); String passwordDigest = new String(base64.encode((user + ":" + password).getBytes("UTF-8"))); String digest = BASIC + passwordDigest.trim(); headers.put(AUTHORIZATION, digest); } for (Entry<String, String> e : headers.entrySet()) { if (e.getKey().startsWith(":")) { headers.remove(e.getKey()); } } // collect the parameters and store into a mutable map. RequestParameterMap parameterMap = request.getRequestParameterMap(); Map<String, Object> templateParams = new ConcurrentHashMap<String, Object>(parameterMap); // search for special parameters. if (parameterMap.containsKey(BASIC_USER)) { String user = parameterMap.getValue(BASIC_USER).getString(); String password = parameterMap.getValue(BASIC_PASSWORD).getString(); Base64 base64 = new Base64(); String passwordDigest = new String(base64.encode((user + ":" + password).getBytes("UTF-8"))); String digest = BASIC + passwordDigest.trim(); headers.put(AUTHORIZATION, digest); } // we might want to pre-process the headers if (node.hasProperty(ProxyPreProcessor.SAKAI_PREPROCESSOR)) { String preprocessorName = node.getProperty(ProxyPreProcessor.SAKAI_PREPROCESSOR).getString(); ProxyPreProcessor preprocessor = preProcessors.get(preprocessorName); if (preprocessor != null) { preprocessor.preProcessRequest(request, headers, templateParams); } else { LOGGER.warn( "Unable to find pre processor of name {} for node {} ", preprocessorName, node.getPath()); } } ProxyPostProcessor postProcessor = defaultPostProcessor; // we might want to post-process the headers if (node.hasProperty(ProxyPostProcessor.SAKAI_POSTPROCESSOR)) { String postProcessorName = node.getProperty(ProxyPostProcessor.SAKAI_POSTPROCESSOR).getString(); if (postProcessors.containsKey(postProcessorName)) { postProcessor = postProcessors.get(postProcessorName); } if (postProcessor == null) { LOGGER.warn( "Unable to find post processor of name {} for node {} ", postProcessorName, node.getPath()); postProcessor = defaultPostProcessor; } } ProxyResponse proxyResponse = proxyClientService.executeCall(node, headers, templateParams, null, -1, null); try { postProcessor.process(templateParams, response, proxyResponse); } finally { proxyResponse.close(); } } catch (IOException e) { throw e; } catch (ProxyClientException e) { response.sendError(500, e.getMessage()); } catch (RepositoryException e) { response.sendError(500, e.getMessage()); } }
/** * {@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; } }
/** * {@inheritDoc} * * @see * org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest, * org.apache.sling.api.SlingHttpServletResponse) */ @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { // Check if the current user is logged in. if (request.getRemoteUser().equals("anonymous")) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Anonymous user cannot crop images."); return; } RequestParameter imgParam = request.getRequestParameter("img"); RequestParameter saveParam = request.getRequestParameter("save"); RequestParameter xParam = request.getRequestParameter("x"); RequestParameter yParam = request.getRequestParameter("y"); RequestParameter widthParam = request.getRequestParameter("width"); RequestParameter heightParam = request.getRequestParameter("height"); RequestParameter dimensionsParam = request.getRequestParameter("dimensions"); if (imgParam == null || saveParam == null || xParam == null || yParam == null || widthParam == null || heightParam == null || dimensionsParam == null) { response.sendError( HttpServletResponse.SC_BAD_REQUEST, "The following parameters are required: img, save, x, y, width, height, dimensions"); return; } try { // Grab the session ResourceResolver resourceResolver = request.getResourceResolver(); Session session = resourceResolver.adaptTo(Session.class); String img = imgParam.getString(); String save = saveParam.getString(); int x = Integer.parseInt(xParam.getString()); int y = Integer.parseInt(yParam.getString()); int width = Integer.parseInt(widthParam.getString()); int height = Integer.parseInt(heightParam.getString()); String[] dimensionsList = StringUtils.split(dimensionsParam.getString(), ';'); List<Dimension> dimensions = new ArrayList<Dimension>(); for (String s : dimensionsList) { Dimension d = new Dimension(); String[] size = StringUtils.split(s, 'x'); int diWidth = Integer.parseInt(size[0]); int diHeight = Integer.parseInt(size[1]); diWidth = checkIntBiggerThanZero(diWidth, 0); diHeight = checkIntBiggerThanZero(diHeight, 0); d.setSize(diWidth, diHeight); dimensions.add(d); } x = checkIntBiggerThanZero(x, 0); y = checkIntBiggerThanZero(y, 0); width = checkIntBiggerThanZero(width, 0); height = checkIntBiggerThanZero(height, 0); // Make sure the save path is correct. save = PathUtils.normalizePath(save) + "/"; String[] crop = CropItProcessor.crop(session, x, y, width, height, dimensions, img, save); JSONWriter output = new JSONWriter(response.getWriter()); output.object(); output.key("files"); output.array(); for (String url : crop) { output.value(url); } output.endArray(); output.endObject(); } catch (ArrayIndexOutOfBoundsException e) { response.sendError( HttpServletResponse.SC_BAD_REQUEST, "The dimensions have to be specified in a widthxheight;widthxheight fashion."); return; } catch (NumberFormatException e) { response.sendError( HttpServletResponse.SC_BAD_REQUEST, "The following parameters have to be integers: x, y, width, height. (Dimensions has to be of the form widthxheight;widthxheight"); return; } catch (ImageException e) { // Something went wrong.. logger.warn("ImageException e: " + e.getMessage()); response.sendError(e.getCode(), e.getMessage()); } catch (JSONException e) { response.sendError(500, "Unable to output JSON."); } }
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { try { Resource resource = request.getResource(); if (!resource.getPath().startsWith(SEARCH_PATH_PREFIX)) { response.sendError( HttpServletResponse.SC_FORBIDDEN, "Search templates can only be executed if they are located under " + SEARCH_PATH_PREFIX); return; } Node node = resource.adaptTo(Node.class); if (node != null && node.hasProperty(SAKAI_QUERY_TEMPLATE)) { // TODO: we might want to use this ? @SuppressWarnings("unused") boolean limitResults = true; if (node.hasProperty(SAKAI_LIMIT_RESULTS)) { limitResults = node.getProperty(SAKAI_LIMIT_RESULTS).getBoolean(); } // KERN-1147 Respond better when all parameters haven't been provided for a query Query query = null; try { query = processQuery(request, node); } catch (MissingParameterException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return; } long nitems = SolrSearchUtil.longRequestParameter( request, PARAMS_ITEMS_PER_PAGE, DEFAULT_PAGED_ITEMS); long page = SolrSearchUtil.longRequestParameter(request, PARAMS_PAGE, 0); // allow number of items to be specified in sakai:query-template-options if (query.getOptions().containsKey(PARAMS_ITEMS_PER_PAGE)) { nitems = Long.valueOf(query.getOptions().get(PARAMS_ITEMS_PER_PAGE)); } else { // add this to the options so that all queries are constrained to a limited // number of returns per page. query.getOptions().put(PARAMS_ITEMS_PER_PAGE, Long.toString(nitems)); } if (query.getOptions().containsKey(PARAMS_PAGE)) { page = Long.valueOf(query.getOptions().get(PARAMS_PAGE)); } else { // add this to the options so that all queries are constrained to a limited // number of returns per page. query.getOptions().put(PARAMS_PAGE, Long.toString(page)); } boolean useBatch = false; // Get the SolrSearchBatchResultProcessor searchBatchProcessor = defaultSearchBatchProcessor; if (node.hasProperty(SAKAI_BATCHRESULTPROCESSOR)) { searchBatchProcessor = batchProcessors.get(node.getProperty(SAKAI_BATCHRESULTPROCESSOR).getString()); useBatch = true; if (searchBatchProcessor == null) { searchBatchProcessor = defaultSearchBatchProcessor; } } SolrSearchResultProcessor searchProcessor = defaultSearchProcessor; if (node.hasProperty(SAKAI_RESULTPROCESSOR)) { searchProcessor = processors.get(node.getProperty(SAKAI_RESULTPROCESSOR).getString()); if (searchProcessor == null) { searchProcessor = defaultSearchProcessor; } } SolrSearchResultSet rs = null; try { // Prepare the result set. // This allows a processor to do other queries and manipulate the results. if (useBatch) { rs = searchBatchProcessor.getSearchResultSet(request, query); } else { rs = searchProcessor.getSearchResultSet(request, query); } } catch (SolrSearchException e) { response.sendError(e.getCode(), e.getMessage()); return; } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); ExtendedJSONWriter write = new ExtendedJSONWriter(response.getWriter()); write.setTidy(isTidy(request)); write.object(); write.key(PARAMS_ITEMS_PER_PAGE); write.value(nitems); write.key(JSON_RESULTS); write.array(); Iterator<Result> iterator = rs.getResultSetIterator(); if (useBatch) { LOGGER.info("Using batch processor for results"); searchBatchProcessor.writeResults(request, write, iterator); } else { LOGGER.info("Using regular processor for results"); // We don't skip any rows ourselves here. // We expect a rowIterator coming from a resultset to be at the right place. for (long i = 0; i < nitems && iterator.hasNext(); i++) { // Get the next row. Result result = iterator.next(); // Write the result for this row. searchProcessor.writeResult(request, write, result); } } write.endArray(); // write the total out after processing the list to give the underlying iterator // a chance to walk the results then report how many there were. write.key(TOTAL); write.value(rs.getSize()); write.endObject(); } } catch (RepositoryException e) { LOGGER.error(e.getMessage(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (JSONException e) { LOGGER.error(e.getMessage(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
/** * {@inheritDoc} * * @see * org.apache.sling.api.servlets.SlingAllMethodsServlet#doPut(org.apache.sling.api.SlingHttpServletRequest, * org.apache.sling.api.SlingHttpServletResponse) */ @Override protected void doPut(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); }
public void process(SlingHttpServletResponse response, ProxyResponse proxyResponse) throws IOException { Map<String, String[]> headers = proxyResponse.getResponseHeaders(); // Check if the content-length is smaller than the maximum (if any). String[] contentLengthHeader = headers.get("Content-Length"); if (contentLengthHeader != null) { int length = Integer.parseInt(contentLengthHeader[0]); if (length > MAX_RSS_LENGTH) { response.sendError( HttpServletResponse.SC_FORBIDDEN, "This RSS feed is too big. The maximum for a feed is: " + MAX_RSS_LENGTH); return; } } // Check if the Content-Type we get is valid (if any). String[] contentTypeHeader = headers.get("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader[0]; if (contentType.contains(";")) { contentType = contentType.substring(0, contentType.indexOf(';')); } if (!contentTypes.contains(contentType)) { response.sendError( HttpServletResponse.SC_FORBIDDEN, "This URL doesn't send a proper Content-Type back"); return; } } boolean isValid = false; InputStream in = proxyResponse.getResponseBodyAsInputStream(); InputStreamReader reader = new InputStreamReader(in); // XMLStreamWriter writer = null; XMLEventWriter writer = null; ByteArrayOutputStream out = null; int i = 0; try { XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(reader); // Create a temporary outputstream where we can write to. out = new ByteArrayOutputStream(); Map<String, Boolean> checkedElements = new HashMap<String, Boolean>(); checkedElements.put("rss", false); checkedElements.put("channel", false); checkedElements.put("title", false); checkedElements.put("link", false); checkedElements.put("item", false); checkedElements.put("title", false); checkedElements.put("link", false); XMLOutputFactory outputFactory = new WstxOutputFactory(); writer = outputFactory.createXMLEventWriter(out); while (eventReader.hasNext()) { XMLEvent e = eventReader.nextEvent(); // Stream it to an output stream. writer.add(e); if (!isValid) { if (e.getEventType() == XMLEvent.START_ELEMENT) { StartElement el = e.asStartElement(); String name = el.getName().toString().toLowerCase(); if (checkedElements.containsKey(name)) { checkedElements.put(name, true); } boolean all = true; for (Entry<String, Boolean> es : checkedElements.entrySet()) { if (!checkedElements.get(es.getKey())) { all = false; break; } } if (all) isValid = true; } if (i > 100) { response.sendError( HttpServletResponse.SC_FORBIDDEN, "This file does not match an RSS formatted XML file.."); break; } i++; } } if (!isValid) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid RSS file."); return; } // Check if we are not streaming a gigantic file.. if (out.size() > MAX_RSS_LENGTH) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "This file is to big."); return; } for (Entry<String, String[]> h : proxyResponse.getResponseHeaders().entrySet()) { for (String v : h.getValue()) { response.setHeader(h.getKey(), v); } } // We always return 200 when we get to this point. response.setStatus(200); response.setHeader("Content-Length", "" + out.size()); // Write the cached stream to the output. out.writeTo(response.getOutputStream()); } catch (XMLStreamException e) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "This is not a valid XML file."); } catch (Exception e) { logger.warn("Exception reading RSS feed."); response.sendError(HttpServletResponse.SC_FORBIDDEN, "General exception caught."); } finally { out.close(); reader.close(); try { writer.close(); } catch (XMLStreamException e) { // Not much we can do? e.printStackTrace(); } } }
/** * 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); } }
/** * {@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 { // Grab the search node. Node node = request.getResource().adaptTo(Node.class); // Grab the node that holds the repository information. Node proxyNode = DocProxyUtils.getProxyNode(node); // Grab the correct processor String type = proxyNode.getProperty(REPOSITORY_PROCESSOR).getString(); ExternalRepositoryProcessor processor = tracker.getProcessorByType(type); if (processor == null) { LOGGER.warn("No processor found for type - {}", type); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not handle this repository type."); return; } // Handle properties. Map<String, Object> searchProperties = new HashMap<String, Object>(); handleProperties(searchProperties, node, request); // Process search Iterator<ExternalDocumentResult> results = processor.search(proxyNode, searchProperties); // Do the default search paging. long toSkip = SearchUtil.getPaging(request, -1); while (toSkip > 0) { if (results.hasNext()) { results.next(); toSkip--; } else { throw new NoSuchElementException(); } } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); ExtendedJSONWriter write = new ExtendedJSONWriter(response.getWriter()); write.array(); long nitems = SearchUtil.longRequestParameter( request, SearchConstants.PARAMS_ITEMS_PER_PAGE, SearchConstants.DEFAULT_PAGED_ITEMS); for (long i = 0; i < nitems && results.hasNext(); i++) { ExternalDocumentResult result = results.next(); DocProxyUtils.writeMetaData(write, result); } write.endArray(); } catch (RepositoryException e) { LOGGER.error("Got a repository exception when trying to grab search node information.", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to perform search."); } catch (JSONException e) { LOGGER.error("Got a JSON exception when trying to grab search node information.", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to perform search."); } catch (DocProxyException e) { LOGGER.error("Got a DocProxy exception when trying to grab search node information.", e); response.sendError(e.getCode(), e.getMessage()); } }